-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathSim5320MQTT.cpp
329 lines (259 loc) · 9.41 KB
/
Sim5320MQTT.cpp
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
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
/*
Sim5320MQTT.cpp - Library for MQTT protocol on SIM5320.
Created by Boris Deletic, October 30, 2018.
Released into the public domain.
*/
#include <Arduino.h>
#include <Sim5320MQTT.h>
#define MQTT_MSG_CONNECT 0x10
#define MQTT_MSG_CONNACK 0x20
#define MQTT_MSG_PUBLISH 0x30
#define MQTT_SUBSCRIBE 0x82
#define MQTT_SUBACK 0x90
#define MQTT_PINGREQ 0xc0
#define MQTT_PINGRESP 0xd0
#define CR '\r' // 0x0D
#define LF '\n' // 0x0A
//////////////////////////////////////////////////////////////////////////
SimMQTT::SimMQTT(const int simSerialRX, const int simSerialTX, const int powerPin, String network, String IP) :
_gDebug(false),
logSer(nullptr),
Sim5320(simSerialRX, simSerialTX),
interface(&Sim5320, powerPin, network, IP)
{
// Note on Sim900 baud rates. The unit defaults to 115200 but I have
// found it to be unreliable. To change baud rate, issue 'AT+IPREX=115200'
// or similar (change the baud rate number). After this command the sketch
// cannot communicate with the Sim5320 any more. Change the next line to
// match the new baud rate and restart.
//
// If echoing commands from the Serial to Sim5320 and vv (see loop()), it
// is best if the two baud rates are identical.
// Sim5320(simSerialRX, simSerialTX);
Sim5320.begin(19200);
//Software Serial RX, TX pins must be connected to SIM5320 appropriately and support software serial functionality
//See more @https://www.arduino.cc/en/Reference/SoftwareSerial
//Power pin is used to turn on SIM5320 chip in order to restart and check successful serial connection.
// interface(&Sim5320, powerPin);
}
void SimMQTT::setLogging(Stream* pntSer, bool verbosity) {
interface.setLogging(pntSer, verbosity);
logSer = pntSer;
if (verbosity) {
logSer->println("Enabled logging");
_gDebug = true;
} else {
_gDebug = false;
}
}
//////////////////////////////////////////////////////////////////////////
// Generate random client ID, pass in char array to be modified
void SimMQTT::genRandomID(char *s, const int len) {
static const char alphanum[] =
"012346789"
"ABCDEFGHIJKLMNOPQRSTUVWYZ"
"abcdefghijklmnopqrstuvwxyz";
for (int i = 0; i < len; ++i) {
s[i] = alphanum[rand() % (sizeof(alphanum) - 1)];
}
s[len] = 0;
}
///////////////////////////////////////////////////////////////////////////
bool SimMQTT::MqttOpen (const char* const brokerUrl, const char* const brokerPort) {
interface.InitSim5320();
interface.InitWeb();
String cmd = String("AT+CIPOPEN=0,\"TCP\",\"") + brokerUrl + "\"," + brokerPort;
for (int n=0; n=5; n++) {
delay(500);
if (interface.sendATcommand(cmd, "OK", 10000)) {
delay(1000);
interface.ReadSim5320(_gDebug);
return true;
}
else {
if (interface.sendATcommand(cmd, "OK", 10000)) {
delay(1000);
interface.ReadSim5320(_gDebug);
return true;
} else {
interface.sendATcommand("AT+CIPCLOSE=0", "OK", 10000);
}
}
}
return false;
}
///////////////////////////////////////////////////////////////////////////
bool SimMQTT::MqttConnect (const char* clientId, const char* username, const char* password) {
//
// See http://docs.oasis-open.org/mqtt/mqtt/v3.1.1/os/mqtt-v3.1.1-os.html for details
//
uint8_t clientIdLength = strlen(clientId);
uint8_t usernameLength = strlen(username);
uint8_t passwordLength = strlen(password);
uint8_t mqttMessage[128];
uint8_t mqttMessageLength = 19 + clientIdLength + usernameLength + passwordLength;
// Header
mqttMessage[0] = MQTT_MSG_CONNECT;
mqttMessage[1] = 17 + clientIdLength + usernameLength + passwordLength; // Remaining length of the message (bytes 2-13 + clientId)
// Protocol name
mqttMessage[2] = 0; // Protocol Name Length MSB
mqttMessage[3] = 4; // Protocol Name Length LSB
mqttMessage[4] = 'M';
mqttMessage[5] = 'Q';
mqttMessage[6] = 'T';
mqttMessage[7] = 'T';
// Protocol level
mqttMessage[8] = 4; // MQTT Protocol version = 4 (mqtt 3.1.1)
// Connection flags 2 for clean session
// mqttMessage[9] = 2;
mqttMessage[9] = 194; //enable username, password, clean session
// Keep-alive (maximum duration)
mqttMessage[10] = 100; // Keep-alive Time Length MSB
mqttMessage[11] = 100; // Keep-alive Time Length LSB
// Client ID
mqttMessage[12] = 0; // Client ID length MSB
mqttMessage[13] = clientIdLength; // Client ID length LSB
memcpy(&mqttMessage[14], clientId, clientIdLength);
// Username
mqttMessage[14 + clientIdLength] = 0; // Client ID length MSB
mqttMessage[15 + clientIdLength] = usernameLength; // Client ID length LSB
memcpy(&mqttMessage[16 + clientIdLength], username, usernameLength);
// Password
mqttMessage[16 + clientIdLength + usernameLength] = 0; // Client ID length MSB
mqttMessage[17 + clientIdLength + usernameLength] = passwordLength; // Client ID length LSB
memcpy(&mqttMessage[18 + clientIdLength + usernameLength], password, passwordLength);
delay(1000);
// Prepare command
if (_gDebug) {
logSer->println("Tx: MQTT_CONNECT");
}
String cmd = "AT+CIPSEND=0,";
cmd += mqttMessageLength;
cmd += CR;
// Send command
interface.ReadSim5320(_gDebug); // clear rx buffer
Sim5320.print(cmd);
delay(100);
// Send message
for (int i=0; i<mqttMessageLength; i++) {
Sim5320.write(mqttMessage[i]); // Message contents
if (_gDebug) {
logSer->print(interface.byteToHexStr(mqttMessage[i]));
logSer->println();
}
}
// Check if send was successful
delay(100);
bool retVal = interface.verifyResponse(MQTT_MSG_CONNACK);
return retVal;
}
//////////////////////////////////////////////////////////////////////////
bool SimMQTT::MqttSubscribe (const char* const topic) {
bool retVal = false;
uint8_t lenTopic = strlen(topic);
uint8_t mqttMessage[128];
uint8_t written = 0;
// Write fixed header
mqttMessage[written++] = MQTT_SUBSCRIBE;
mqttMessage[written++] = 5 + lenTopic;
//Variable Header
mqttMessage[written++] = 0; // MSB
mqttMessage[written++] = rand() % 256; // LSB message ID
// TODO: make message id dynamic
// Write topic
mqttMessage[written++] = 0; // lenTopic MSB
mqttMessage[written++] = lenTopic; // lenTopic LSB
memcpy(&mqttMessage[written], topic, lenTopic);
written += lenTopic;
// Write QoS
mqttMessage[written++] = 1;
if (_gDebug) {
logSer->println("Tx: MQTT_SUBSCRIBE");
}
String cmd = "AT+CIPSEND=0,";
cmd += written;
cmd += CR;
// Send command
interface.ReadSim5320(_gDebug); // clear rx buffer
Sim5320.print(cmd);
//uint8_t fie = ReadSim5320(true);
delay(100);
// Send message
for (int i=0; i<written; i++) {
Sim5320.write(mqttMessage[i]); // Message contents
// refSer.print(byteToHexStr(mqttMessage[i]));
}
delay(100);
retVal = interface.verifyResponse(MQTT_SUBACK);
return retVal;
}
///////////////////////////////////////////////////////////////////////////
bool SimMQTT::MqttPublish (const char* const topic, const char* const msg) {
bool retVal = true;
uint8_t lenTopic = strlen(topic);
uint8_t lenMsg = strlen(msg);
uint8_t mqttMessage[128];
uint8_t written = 0;
// Write fixed header
mqttMessage[written++] = MQTT_MSG_PUBLISH;
mqttMessage[written++] = 2 + lenTopic + lenMsg;
// Write topic
mqttMessage[written++] = 0; // lenTopic MSB
mqttMessage[written++] = lenTopic; // lenTopic LSB
memcpy(&mqttMessage[written], topic, lenTopic);
written += lenTopic;
// Write msg
memcpy(&mqttMessage[written], msg, lenMsg);
written += lenMsg;
// Prepare command
if (_gDebug) {
logSer->println("Tx: MQTT_PUBLISH");
}
String cmd = "AT+CIPSEND=0,";
cmd += written;
cmd += CR;
// Send command
interface.ReadSim5320(_gDebug); // clear rx buffer
Sim5320.print(cmd);
delay(20);
// Send message
for (int i=0; i<written; i++) {
Sim5320.write(mqttMessage[i]); // Message contents
}
// Check if send was successful
delay(100);
retVal = interface.CheckOk();
if ((retVal == false) && (_gDebug == true)) {
logSer->println(String("[ERROR] Publish failed"));
}
return retVal;
}
///////////////////////////////////////////////////////////////////////////
bool SimMQTT::MqttPingreq() {
delay(1000);
bool retVal = false;
uint8_t mqttMessage[40];
uint8_t written = 0;
// Write fixed header
mqttMessage[written++] = MQTT_PINGREQ;
mqttMessage[written++] = 0;
if (_gDebug) {
logSer->println("Tx: MQTT_PINGREQ");
}
String cmd = "AT+CIPSEND=0,";
cmd += written;
cmd += CR;
// Send command
interface.ReadSim5320(_gDebug); // clear rx buffer
Sim5320.print(cmd);
//uint8_t fie = ReadSim5320(true);
delay(100);
// Send message
for (int i=0; i<written; i++) {
Sim5320.write(mqttMessage[i]); // Message contents
// Serial.print(byteToHexStr(mqttMessage[i]));
}
delay(100);
retVal = interface.verifyResponse(MQTT_PINGRESP);
return retVal;
}