WS_MQTT.cpp 6.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216
  1. #include "WS_MQTT.h"
  2. // The name and password of the WiFi access point
  3. const char* ssid = STASSID;
  4. const char* password = STAPSK;
  5. // Details about devices on the Waveshare cloud
  6. const char* mqtt_server = MQTT_Server;
  7. int PORT = MQTT_Port;
  8. const char* ID = MQTT_ID; // Defining device ID
  9. char pub[] = MQTT_Pub; // MQTT release topic
  10. char sub[] = MQTT_Sub; // MQTT subscribe to topics
  11. WiFiClient espClient; //MQTT initializes the contents
  12. PubSubClient client(espClient);
  13. StaticJsonDocument<400> sendJson;
  14. StaticJsonDocument<400> readJson;
  15. unsigned long lastUpdateTime = 0;
  16. char msg[MSG_BUFFER_SIZE];
  17. bool WIFI_Connection = 0;
  18. char ipStr[16];
  19. const unsigned long updateInterval = 5000;
  20. // MQTT subscribes to callback functions for processing received messages
  21. void callback(char* topic, byte* payload, unsigned int length) {
  22. uint8_t CH_Flag = 0;
  23. String inputString;
  24. for (int i = 0; i < length; i++) {
  25. inputString += (char)payload[i];
  26. }
  27. printf("%s\r\n",inputString.c_str()); // Format of data sent back by the server {"data":{"CH1":1}}
  28. int dataBegin = inputString.indexOf("\"data\""); // Finds if "data" is present in the string (quotes also)
  29. if (dataBegin == -1) {
  30. printf("Missing 'data' field in JSON. - MQTT\r\n");
  31. return;
  32. }
  33. int CH_Begin = -1;
  34. if (inputString.indexOf("\"CH1\"", dataBegin) != -1){
  35. CH_Flag = 1;
  36. CH_Begin = inputString.indexOf("\"CH1\"", dataBegin);
  37. }
  38. else if (inputString.indexOf("\"CH2\"", dataBegin) != -1){
  39. CH_Flag = 2;
  40. CH_Begin = inputString.indexOf("\"CH2\"", dataBegin);
  41. }
  42. else if (inputString.indexOf("\"CH3\"", dataBegin) != -1){
  43. CH_Flag = 3;
  44. CH_Begin = inputString.indexOf("\"CH3\"", dataBegin);
  45. }
  46. else if (inputString.indexOf("\"CH4\"", dataBegin) != -1){
  47. CH_Flag = 4;
  48. CH_Begin = inputString.indexOf("\"CH4\"", dataBegin);
  49. }
  50. else if (inputString.indexOf("\"CH5\"", dataBegin) != -1){
  51. CH_Flag = 5;
  52. CH_Begin = inputString.indexOf("\"CH5\"", dataBegin);
  53. }
  54. else if (inputString.indexOf("\"CH6\"", dataBegin) != -1){
  55. CH_Flag = 6;
  56. CH_Begin = inputString.indexOf("\"CH6\"", dataBegin);
  57. }
  58. else if (inputString.indexOf("\"ALL\"", dataBegin) != -1){
  59. CH_Flag = 7;
  60. CH_Begin = inputString.indexOf("\"ALL\"", dataBegin);
  61. }
  62. else{
  63. printf("Note : Non-instruction data was received - MQTT!\r\n");
  64. CH_Flag = 0;
  65. return;
  66. }
  67. int valueBegin = inputString.indexOf(':', CH_Begin);
  68. int valueEnd = inputString.indexOf('}', valueBegin);
  69. if (valueBegin != -1 && valueEnd != -1) {
  70. if(CH_Flag != 0)
  71. {
  72. String ValueStr = inputString.substring(valueBegin + 1, valueEnd);
  73. int Value = ValueStr.toInt();
  74. if(CH_Flag < 7){
  75. if(Value == 1 && Relay_Flag[CH_Flag - 1] == 0){
  76. uint8_t Data[1]={CH_Flag+48};
  77. Relay_Analysis(Data,MQTT_Mode);
  78. }
  79. else if(Value == 0 && Relay_Flag[CH_Flag - 1] == 1){
  80. uint8_t Data[1]={CH_Flag+48};
  81. Relay_Analysis(Data,MQTT_Mode);
  82. }
  83. }
  84. else if(CH_Flag == 7){
  85. if(Value == 1 && ((Relay_Flag[0] & Relay_Flag[1] & Relay_Flag[2] & Relay_Flag[3] & Relay_Flag[4] & Relay_Flag[5]) == 0)){
  86. uint8_t Data[1]={7+48};
  87. Relay_Analysis(Data,MQTT_Mode);
  88. }
  89. else if(Value == 0 && ((Relay_Flag[0] | Relay_Flag[1] | Relay_Flag[2] | Relay_Flag[3] | Relay_Flag[4] | Relay_Flag[5] )== 1)){
  90. uint8_t Data[1]={8+48};
  91. Relay_Analysis(Data,MQTT_Mode);
  92. }
  93. }
  94. }
  95. }
  96. }
  97. void setup_wifi() {
  98. uint8_t Count = 0;
  99. printf("Connecting to ");
  100. printf("%s\r\n",ssid);
  101. WiFi.mode(WIFI_STA);
  102. WiFi.begin(ssid, password);
  103. while (WiFi.status() != WL_CONNECTED) {
  104. Count++;
  105. delay(500);
  106. printf(".\r\n");
  107. if(Count % 2 == 0 && Count != 0){
  108. RGB_Light(60, 0, 0);
  109. delay(1000);
  110. RGB_Light(0, 0, 0);
  111. }
  112. if(Count % 10 == 0){ // 10 attempts failed to connect, cancel the connection, try again
  113. WiFi.disconnect();
  114. delay(100);
  115. WiFi.mode(WIFI_OFF);
  116. delay(100);
  117. WiFi.mode(WIFI_STA);
  118. delay(100);
  119. WiFi.begin(ssid, password);
  120. }
  121. if(Count > 22){ // connection fail
  122. break;
  123. }
  124. }
  125. delay(100);
  126. if(Count < 23){
  127. WIFI_Connection = 1;
  128. RGB_Light(0, 60, 0);
  129. delay(1000);
  130. RGB_Light(0, 0, 0);
  131. // IPAddress myIP = WiFi.localIP();
  132. // printf("AP IP address: ");
  133. // sprintf(ipStr, "%d.%d.%d.%d", myIP[0], myIP[1], myIP[2], myIP[3]);
  134. // printf("%s\r\n", ipStr);
  135. printf("WIFI connection is successful, relay control can be performed via Waveshare cloud.\r\n");
  136. }
  137. else{
  138. WIFI_Connection = 0;
  139. printf("WIFI connection fails, you can use the Bluetooth debugging Assistant to control the device.\r\n");
  140. RGB_Light(60, 0, 0);
  141. }
  142. }
  143. // Reconnect to the MQTT server
  144. void reconnect() {
  145. uint8_t Count = 0;
  146. while (!client.connected()) {
  147. Count++;
  148. if (client.connect(ID)) {
  149. client.subscribe(sub);
  150. printf("Waveshare Cloud connection is successful and now you can use all features.\r\n");
  151. }
  152. else{
  153. delay(500);
  154. if(Count % 2 == 0 && Count != 0){
  155. printf("%d\r\n", client.state());
  156. RGB_Light(60, 0, 60);
  157. delay(1000);
  158. RGB_Light(0, 0, 0);
  159. }
  160. if(Count % 10 == 0){ // 10 attempts failed to connect, cancel the connection, try again
  161. client.disconnect();
  162. delay(100);
  163. client.setServer(mqtt_server, PORT);
  164. delay(100);
  165. client.setCallback(callback);
  166. delay(100);
  167. }
  168. if(Count > 32){ // connection fail
  169. Count = 0;
  170. printf("warning: Waveshare cloud connection fails. Currently, only Bluetooth control is available !!!\r\n");
  171. }
  172. }
  173. }
  174. }
  175. // Send data in JSON format to MQTT server
  176. void sendJsonData() {
  177. sendJson["ID"] = ID;
  178. String pubres;
  179. serializeJson(sendJson, pubres);
  180. int str_len = pubres.length() + 1;
  181. char char_array[str_len];
  182. pubres.toCharArray(char_array, str_len);
  183. client.publish(pub, char_array);
  184. }
  185. void MQTT_Init()
  186. {
  187. setup_wifi();
  188. if(WIFI_Connection == 1){
  189. client.setServer(mqtt_server, PORT);
  190. client.setCallback(callback);
  191. }
  192. }
  193. void MQTT_Loop()
  194. {
  195. if(WIFI_Connection == 1){
  196. if (!client.connected()) {
  197. reconnect();
  198. }
  199. client.loop();
  200. // if (millis() - lastUpdateTime > updateInterval) { // Periodic data reporting
  201. // sendJsonData();
  202. // lastUpdateTime = millis();
  203. // }
  204. }
  205. }