-
Notifications
You must be signed in to change notification settings - Fork 19
/
mqttFunctions.ino
89 lines (83 loc) · 2.43 KB
/
mqttFunctions.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
boolean connectMQTT(){
if (mqttClient.connected()){
return true;
}
Serial.print("Connecting to MQTT server ");
Serial.print(mqttServer);
Serial.print(" as ");
Serial.println(host);
if (mqttClient.connect(host)) {
Serial.println("Connected to MQTT broker");
if(mqttClient.subscribe((char*)subTopic.c_str())){
Serial.println("Subsribed to topic.");
} else {
Serial.println("NOT subsribed to topic!");
}
return true;
}
else {
Serial.println("MQTT connect failed! ");
return false;
}
}
void disconnectMQTT(){
mqttClient.disconnect();
}
void mqtt_handler(){
if (toPub==1){
Debugln("DEBUG: Publishing state via MWTT");
if(pubState()){
toPub=0;
}
}
mqttClient.loop();
delay(100); //let things happen in background
}
void mqtt_arrived(char* subTopic, byte* payload, unsigned int length) { // handle messages arrived
int i = 0;
Serial.print("MQTT message arrived: topic: " + String(subTopic));
// create character buffer with ending null terminator (string)
for(i=0; i<length; i++) {
buf[i] = payload[i];
}
buf[i] = '\0';
String msgString = String(buf);
Serial.println(" message: " + msgString);
if (msgString == "1"){
Serial.print("Light is ");
Serial.println(digitalRead(OUTPIN));
Serial.print("Switching light to ");
Serial.println("high");
digitalWrite(OUTPIN, 1);
} else if (msgString == "0"){
Serial.print("Light is ");
Serial.println(digitalRead(OUTPIN));
Serial.print("Switching light to ");
Serial.println("low");
digitalWrite(OUTPIN, 0);
}
}
boolean pubState(){ //Publish the current state of the light
if (!connectMQTT()){
delay(100);
if (!connectMQTT){
Serial.println("Could not connect MQTT.");
Serial.println("Publish state NOK");
return false;
}
}
if (mqttClient.connected()){
//String state = (digitalRead(OUTPIN))?"1":"0";
Serial.println("To publish state " + state );
if (mqttClient.publish((char*)pubTopic.c_str(), (char*) state.c_str())) {
Serial.println("Publish state OK");
return true;
} else {
Serial.println("Publish state NOK");
return false;
}
} else {
Serial.println("Publish state NOK");
Serial.println("No MQTT connection.");
}
}