IoT - Modular - MQTT.cpp

From The TinkerNet Wiki
Revision as of 14:04, 29 April 2021 by Tinker (talk | contribs)
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Jump to navigation Jump to search

#includes, Defines, etc...

1 #include "libraries.h"
2 #include "functions.h"
3 #include "externs.h"
4 
5 #include "MQTT.h"
6 
7 WiFiClient espClient;
8 PubSubClient MQTT_client(espClient);

MQTT_handler()

1 void MQTT_handler()
2 {
3     if (!MQTT_client.connected())
4     {
5         MQTT_reconnect();
6     }
7     MQTT_client.loop();
8     // MQTT_beacon();
9 }

MQTT_init()

 1 void MQTT_init()
 2 {
 3     MQTT_client.setServer(MQTT_broker, 1883);
 4     MQTT_client.setCallback(MQTT_callback);
 5 
 6     //  Build the topic names
 7     strcpy(MQTT_inTopic, "cmnd/"); //  in - Commands
 8     strcat(MQTT_inTopic, MQTT_ClientName);
 9     strcat(MQTT_inTopic, "/#");
10     strcpy(MQTT_teleTopic, "tele/"); // out - Telemetry
11     strcat(MQTT_teleTopic, MQTT_ClientName);
12     strcpy(MQTT_statTopic, "stat/"); // out - Status
13     strcat(MQTT_statTopic, MQTT_ClientName);
14     strcpy(MQTT_outTopic, "noti/"); // out - Notifications
15     strcat(MQTT_outTopic, MQTT_ClientName);
16 
17     MQTT_reconnect();
18 }

MQTT_callback()

  1 void MQTT_callback(char *topic, byte payload[100], int length)
  2 {
  3     char debugTEXT[46];
  4 
  5     char MQTT_msg_in[MQTT_BUFFER_SIZE];
  6     char *MQTT_command = strrchr(topic, '/');
  7     char CNasT[MQTT_BUFFER_SIZE];
  8     strcpy(CNasT, "/");
  9     strcat(CNasT, MQTT_ClientName); // "ClientName as Topic"
 10 
 11 #ifdef DEBUG4
 12     debug_SectionTitle("Message arrived");
 13     sprintf(debugTEXT, "Topic: %30s", MQTT_command);
 14     debug_LineOut(debugTEXT);
 15 #endif
 16 
 17     // if (length < MQTT_BUFFER_SIZE)
 18     // if (length < 63)
 19     // Messages 63 characters long or bigger make BOOM
 20     // with a "Soft WDT reset"
 21     // MQTT_BUFFER_SIZE is 100
 22     // I R cornfoozed...
 23     if (length < 59) // & now 59 is bad...  :|
 24     {
 25 
 26         MQTT_msg_in[0] = '\0'; // start with an empty string!
 27         for (int i = 0; i < length; i++)
 28         {
 29             MQTT_msg_in[i] = (char)payload[i];
 30             MQTT_msg_in[i + 1] = '\0';
 31         }
 32 
 33 #ifdef DEBUG4
 34         sprintf(debugTEXT, "Message: %28s", MQTT_msg_in);
 35         debug_LineOut(debugTEXT);
 36         sprintf(debugTEXT, "Message Size: %d", length);
 37         debug_LineOut(debugTEXT);
 38 #endif
 39 
 40         /////////////////////////////////////////////////////
 41         // Message handling goes here...
 42         /////////////////////////////////////////////////////
 43 
 44         if (strcmp(MQTT_command, CNasT) == 0) // MQTT_ClientName as Topic
 45         {
 46             // Missing topic
 47 #ifdef DEBUG4
 48             debug_Trouble("Missing topic...");
 49 #endif
 50         }
 51         else if (strcmp(MQTT_command, "/Level") == 0) // Tank Level
 52         {
 53             if (strcmp(MQTT_msg_in, "") == 0)
 54             {
 55 #ifdef DEBUG4
 56                 debug_Trouble("No actual message...");
 57 #endif
 58                 // Might be a good way to request status...
 59             }
 60             else
 61             {
 62                 int level = atoi(MQTT_msg_in);
 63                 sprintf(debugTEXT, "Tank Level is: %d", level);
 64                 debug_Action(debugTEXT);
 65 
 66 #ifdef d_Pixels
 67 
 68                 if (level == 0)
 69                 {
 70                     SetAPixel(0, BLK);
 71                     SetAPixel(1, BLK);
 72                     SetAPixel(2, BLK);
 73                     SetAPixel(3, BLK);
 74                     STFU();
 75                 }
 76                 if (level >= 25)
 77                 {
 78                     SetAPixel(0, GRN);
 79                     SetAPixel(1, BLK);
 80                     SetAPixel(2, BLK);
 81                     SetAPixel(3, BLK);
 82                     STFU();
 83                 }
 84                 if (level >= 50)
 85                 {
 86 
 87                     SetAPixel(1, GRN);
 88                     SetAPixel(2, BLK);
 89                     SetAPixel(3, BLK);
 90                     STFU();
 91                 }
 92                 if (level >= 75)
 93                 {
 94                     SetAPixel(2, GRN);
 95                     SetAPixel(3, BLK);
 96                     STFU();
 97                 }
 98                 if (level >= 100)
 99                 {
100                     SetAPixel(0, RED);
101                     SetAPixel(1, RED);
102                     SetAPixel(2, RED);
103                     SetAPixel(3, RED);
104                     ScreamBloodyMurder();
105                 }
106 #endif // d_Pixels
107             }
108         }
109         else if (strcmp(MQTT_command, "/Dump") == 0) // Dumper has dumped
110         {
111 #ifdef d_Audio
112             Boop();
113 #endif // d_Audio
114         }
115         else if (strcmp(MQTT_command, "/Screen") == 0) // Screen control
116         {
117             if (strcmp(MQTT_msg_in, "") == 0)
118             {
119 #ifdef DEBUG4
120                 debug_Trouble("No actual message...");
121 #endif
122                 // Might be a good way to request status...
123             }
124             // else if ((strcmp(MQTT_msg_in, "1") == 0) || (strcmp(MQTT_msg_in, "ON") == 0))
125             // SSD1306_on();
126             // else if ((strcmp(MQTT_msg_in, "0") == 0) || (strcmp(MQTT_msg_in, "OFF") == 0))
127             // SSD1306_off();
128             // else if ((strcmp(MQTT_msg_in, "+") == 0) || (strcmp(MQTT_msg_in, "UP") == 0))
129             // SSD1306_Bright();
130             // else if ((strcmp(MQTT_msg_in, "-") == 0) || (strcmp(MQTT_msg_in, "DOWN") == 0))
131             // SSD1306_Dim();
132             else
133                 debug_Trouble("Say What?");
134         }
135 #ifdef s_CLIMATE
136         else if (strcmp(MQTT_command, "/Pressure_Correction") == 0) // Correction Value sent
137         {
138             Pressure_Correction = atof(MQTT_msg_in);
139             /*
140              *  Need to create afunction in BME280 (& one in BMP180) to accept 
141              *  current pressure & calculate the correction number.
142              */
143             char FooBar[42];
144             sprintf(FooBar, "Correction B: %f", Pressure_Correction);
145             debug_Success(FooBar);
146         }
147         else if (strcmp(MQTT_command, "/Pressure_Actual") == 0) // Correction Value sent
148         {
149             float Pressure_Actual = atof(MQTT_msg_in);
150 
151             Pressure_Correction = Climate_Pressure_Correction(Pressure_Actual);
152 
153             char FooBar[42];
154             sprintf(FooBar, "Correction A: %f", Pressure_Correction);
155             debug_Success(FooBar);
156         }
157 #endif // s_CLIMATE
158         else
159         {
160 #ifdef DEBUG4
161             debug_Trouble("Dunno Whatcha want...");
162 #endif
163         }
164     }
165     else
166     {
167 #ifdef DEBUG4
168         debug_Trouble("But, it's TOO Bloody Big!");
169 #endif
170     }
171 }

MQTT_reconnect()

 1 void MQTT_reconnect()
 2 {
 3     char debugTEXT[46];
 4 
 5     // Loop until we're reconnected
 6     while (!MQTT_client.connected())
 7     {
 8 ////////////////////////////////////////////////////////////////////////////////
 9 #ifdef DEBUG4
10         sprintf(debugTEXT, "WiFi:%d dBm", WiFi_strength());
11         debug_Action(debugTEXT);
12 #endif  // DEBUG4
13         ////////////////////////////////////////////////////////////////////////////////
14         debug_SectionTitle("Attempting MQTT connection...");
15 
16         // Create a random client ID
17         String clientId = MQTT_ClientName;
18         clientId += String(random(0xffff), HEX);
19 
20         // Attempt to connect
21         if (MQTT_client.connect(clientId.c_str()))
22         {
23 ////////////////////////////////////////////////////////////////////////////////
24 #ifdef DEBUG4
25             sprintf(debugTEXT, "WiFi:%d dBm", WiFi_strength());
26             debug_Action(debugTEXT);
27 #endif      // DEBUG4
28             ////////////////////////////////////////////////////////////////////////////////
29             // SSD1306_Static(" MQTT good ", 3);
30             // delay(500);
31             // SSD1306_Static("           ", 3);
32             sprintf(debugTEXT, "connected to %-24s", MQTT_broker);
33             debug_LineOut(debugTEXT);
34             sprintf(debugTEXT, "My Name:  %-27s", MQTT_ClientName);
35             debug_LineOut(debugTEXT);
36             // Once connected, publish an announcement...
37             char MQTT_statTopic_Device[100];
38             strcpy(MQTT_statTopic_Device, MQTT_statTopic);
39             strcat(MQTT_statTopic_Device, "/HELLO");
40             // MQTT_client.publish(MQTT_statTopic_Device, "world");
41             MQTT_client.publish(MQTT_statTopic_Device, WiFi_ssid);
42             // ... and resubscribe
43             MQTT_client.subscribe(MQTT_inTopic);
44         }
45         else
46         {
47             /////////////////////////////////////////////////////////////////////////////////////////////////
48             sprintf(debugTEXT, "WiFi:%d dBm", WiFi_strength());
49             debug_Action(debugTEXT);
50             /////////////////////////////////////////////////////////////////////////////////////////////////
51 
52             if (WiFi.status() != WL_CONNECTED)
53             {
54                 WiFi_Test2();
55                 debug_Trouble("UH OH!!!  No WiFi!!!");
56             }
57             else
58             {
59                 // SSD1306_Static("  no MQTT  ", 3);
60                 WiFi_Test3();
61                 debug_Trouble("UH OH!!!  No MQTT!!!");
62             }
63 
64             sprintf(debugTEXT, "failed, rc=%d", MQTT_client.state());
65             debug_Trouble(debugTEXT);
66             debug_Trouble("trying again in 2 seconds");
67             // Wait 5 seconds before retrying
68             delay(2000);
69         }
70     }
71 }

MQTT_beacon()

 1 void MQTT_beacon()
 2 {
 3     /* Beacon signal published at set interval to indicate the device
 4    * is still powered up and actively connected to MQTT...
 5    * A keepalive of sorts
 6    * also updates state within MQTT so it can be captured for
 7    * indicator light elsewhere
 8    * &, as a bonus, it's sending the WiFi strength.
 9    */
10     char MQTT_statTopic_Device[100];
11     char WiFiSignal[10];
12     strcpy(MQTT_statTopic_Device, MQTT_statTopic);
13     strcat(MQTT_statTopic_Device, "/WiFi_strength");
14     sprintf(WiFiSignal, "%d dBm", WiFi_strength());
15 #ifdef DEBUG0
16     debug_SectionTitle("WiFi:");
17     debug_LineOut(WiFiSignal);
18 #endif
19 
20     MQTT_client.publish(MQTT_statTopic_Device, WiFiSignal);
21     blinkLED(5);
22 
23 #ifdef DEBUG4
24     debug_Action("Beacon sent");
25 #endif
26 }

MQTT_Status()

 1 void MQTT_Status(char const *Device, char const *Status) // Send status messages
 2 {
 3     char MQTT_statTopic_Device[100];
 4     strcpy(MQTT_statTopic_Device, MQTT_statTopic);
 5     strcat(MQTT_statTopic_Device, "/");
 6     strcat(MQTT_statTopic_Device, Device);
 7 
 8 #ifdef DEBUG4
 9     char debugTEXT[46];
10 
11     sprintf(debugTEXT, "}- %16s = %-16s -{", Device, Status);
12     debug_Trouble(debugTEXT);
13 #endif
14     MQTT_client.publish(MQTT_statTopic_Device, Status);
15 }

MQTT_SendTELE()

1 void MQTT_SendTELE(const char *Topic, const char *Message)
2 {
3     char MQTT_teleTopic_Device[100];
4     strcpy(MQTT_teleTopic_Device, MQTT_teleTopic);
5     strcat(MQTT_teleTopic_Device, "/");
6     strcat(MQTT_teleTopic_Device, Topic);
7     MQTT_client.publish(MQTT_teleTopic_Device, Message);
8 }

MQTT_SendSTAT()

1 void MQTT_SendSTAT(const char *Topic, const char *Message)
2 {
3     char MQTT_statTopic_Device[100];
4     strcpy(MQTT_statTopic_Device, MQTT_statTopic);
5     strcat(MQTT_statTopic_Device, "/");
6     strcat(MQTT_statTopic_Device, Topic);
7     MQTT_client.publish(MQTT_statTopic_Device, Message);
8 }

MQTT_SendCMND()

1 void MQTT_SendCMND(const char *Topic, const char *Message)
2 {
3     char MQTT_statTopic_Device[100];
4     strcpy(MQTT_statTopic_Device, Topic);
5     // strcat(MQTT_statTopic_Device, "/");
6     // strcat(MQTT_statTopic_Device, Topic);
7     MQTT_client.publish(MQTT_statTopic_Device, Message);
8 }

MQTT_HandleMessages()

1 void MQTT_HandleMessages()
2 {
3 }