-
Notifications
You must be signed in to change notification settings - Fork 0
/
ESP32_MQTT.ino
81 lines (73 loc) · 1.82 KB
/
ESP32_MQTT.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
#include <WiFi.h>
#include <PubSubClient.h>
// Update these with values suitable for your network.
const char* ssid = "MJU_Wireless";
const char* password = "00000000";
const char* mqtt_server = "broker.mqtt-dashboard.com";
WiFiClient espClient;
PubSubClient client(espClient);
unsigned long lastMsg = 0;
#define MSG_BUFFER_SIZE (50)
char distribute_msg[MSG_BUFFER_SIZE];
char amount_left_msg[MSG_BUFFER_SIZE];
int val[10];
int i;
void setup_wifi() {
delay(10);
WiFi.mode(WIFI_STA);
WiFi.begin(ssid);
while (WiFi.status() != WL_CONNECTED) {}
randomSeed(micros());
}
void callback(char* topic, byte* payload, unsigned int length) {
char MQTT_msg[MSG_BUFFER_SIZE];
for (int i = 0; i < length; i++) {
Serial.write((char)payload[i]);
}
}
void reconnect() {
while (!client.connected()) {
String clientId = "ESP32Client-";
clientId += String(random(0xffff), HEX);
if (client.connect(clientId.c_str())) {
client.publish("13_output", "Pet_Service ON");
client.subscribe("13_input");
}
}
}
void setup() {
Serial.begin(115200);
setup_wifi();
client.setServer(mqtt_server, 1883);
client.setCallback(callback);
i = 0;
val[0]=0;
val[1]=0;
val[2]=0;
}
void loop() {
if (!client.connected()) {
reconnect();
}
client.loop();
if (Serial.available()){
val[i] = Serial.read();
i++;
}
if(val[2] == 99){
snprintf (distribute_msg, MSG_BUFFER_SIZE, "distribute : %d g", val[0]);
client.publish("13_output", distribute_msg);
snprintf (amount_left_msg, MSG_BUFFER_SIZE, "left : %d g", val[1]);
client.publish("13_output", amount_left_msg);
i = 0;
val[0]=0;
val[1]=0;
val[2]=0;
}
else if(i == 2 && val[2] != 99){
i = 0;
val[0]=0;
val[1]=0;
val[2]=0;
}
}