-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathesp8266_pubsub_mqtt.cpp
More file actions
117 lines (82 loc) · 1.91 KB
/
esp8266_pubsub_mqtt.cpp
File metadata and controls
117 lines (82 loc) · 1.91 KB
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
117
//MQTT
#include <PubSubClient.h>
//i-
//MQTT
const char* MQTTSERVER = "192.168.100.101";
const int MQTTPORT = 1883;
WiFiClient espClient;
PubSubClient mqtt(espClient);
//v-
//MQTT
//ClientID will be auto generated on start
//MCU
#define FLOW "sensors/esp8266"
#define BUTTON1 FLOW "/button1"
#define SENSOR1 FLOW "/sensor1"
#define SENSOR2 FLOW "/sensor2"
#define SENSOR3 FLOW "/sensor3"
//enable serial debug
#define mqttdebug true
long mqtttimer = 0;
//will receive button value from subscription
int button1val=0;
//s-
//sb-
//MQTT
mqtt.setServer(MQTTSERVER, MQTTPORT);
mqtt.setCallback(mqttcallback);
if(mqttdebug) Serial.println("Started");
randomSeed(micros());
//l-
//lb-
if (!mqtt.connected()) {
mqttconnect();
}
mqtt.loop();
if(((millis()-mqtttimer)/1000)>3){
int val=0;
//Read Analog Input
val=analogRead(0);
//Send Value to Mqtt
char msg[10];
snprintf(msg, 10, "%2d", val);
mqtt.publish(SENSOR1, msg);
mqtttimer=millis();
}
//buttonval1 is button state
//f-
//MQTT
void mqttcallback(char* topic, byte* payload, unsigned int length) {
if(mqttdebug){
Serial.println(topic);
if(strcmp(topic,BUTTON1)==0){
button1val=atoi((char*)payload);
Serial.print("Button1: ");
Serial.println(button1val);
}
}
}
void mqttconnect() {
int tries=0;
while (!mqtt.connected()) {
String mqttId = "ESP8266mqtt-";
mqttId += String(random(0xffff), HEX);
if (mqtt.connect(mqttId.c_str())) {
// My own Retain Script (NODE-RED) Send last value on Reconnect
//More info : https://pastebin.com/WFW7ArSQ
mqtt.publish(BUTTON1 "/init","1");
mqtt.subscribe(BUTTON1);
}else{tries++; if(tries>10)return;}
delay(2000);
}
}
char* convchar(int value){
char msg[10];
snprintf(msg, 10, "%ld", value);
return(msg);
}
char* convchar(float value){
char msg[10];
snprintf(msg, 10, "%ld", value);
return(msg);
}