-
Notifications
You must be signed in to change notification settings - Fork 1
/
ESP_SerialToMQTT.ino
116 lines (99 loc) · 2.54 KB
/
ESP_SerialToMQTT.ino
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
#include <WiFi.h>
#include <PubSubClient.h>
#define LED 21
const char* ssid = "SSID";
const char* password = "PASSWORD";
const char* mqtt_Broker = "BROKER_IP";
const char* mqttClient = "CLIENT_NAME";
const char* mqttUser = "USR_NAME";
const char* mqttPassword = "PASS";
const char * topicPublish = "TOPIC_PUBLISH";
WiFiClient espClient;
PubSubClient client(espClient);
void setup() {
pinMode(LED, OUTPUT); // Initialize the BUILTIN_LED pin as an output
Serial.begin(19200);
delay(1000);
setup_wifi();
client.setServer(mqtt_Broker, 1883);
client.setCallback(callback);
//client.subscribe(topicSubscribe1);
}
void setup_wifi()
{
delay(10);
// We start by connecting to a WiFi network
Serial.println();
Serial.print("Connecting to ");
Serial.println(ssid);
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println("");
Serial.println("WiFi connected");
Serial.println("IP address: ");
Serial.println(WiFi.localIP());
}
void reconnect() {
// Loop until we're reconnected
while (!client.connected()) {
Serial.print("Attempting MQTT connection...");
// Attempt to connect
if (client.connect(mqttClient, mqttUser, mqttPassword ))
{
Serial.println("connected");
// Once connected, publish an announcement...
//client.publish("outTopic/sample1", "Conexion establecida");
// ... and resubscribe
//client.subscribe(topicSubscribe1);
} else {
Serial.print("failed, rc=");
Serial.print(client.state());
Serial.println(" try again in 5 seconds");
// Wait 5 seconds before retrying
delay(5000);
}
}
}
uint8_t incomingByte = 0;
long start = 0;
long endd = 0;
long periodd = 0;
bool f_serialrx = false;
unsigned int i = 0;
uint8_t msg_to_publish[100];
void loop() {
if (!client.connected()) {
reconnect();
}
client.loop();
if (Serial.available() > 0) {
if(!f_serialrx)
{
start = millis();
f_serialrx = true;
i = 0;
}
// read the incoming byte:
incomingByte = Serial.read();
if(incomingByte != 10)
{
// say what you got:
msg_to_publish[i] = incomingByte;
i ++;
}
else
{
msg_to_publish[i] = 10;
client.publish(topicPublish, msg_to_publish, i);
endd = millis();
periodd = endd - start;
Serial.println("Msg sent!");
Serial.println("Delay in transmition (ms):");
Serial.println(periodd);
f_serialrx = false;
}
}
}