forked from maragelis/ParadoxRs232toMqtt
-
Notifications
You must be signed in to change notification settings - Fork 0
/
ParadoxAlarmSystemOTA.ino
783 lines (602 loc) · 17.4 KB
/
ParadoxAlarmSystemOTA.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
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
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
#include <FS.h>
#include <SoftwareSerial.h>
#include <ESP8266WiFi.h>
#include <ESP8266mDNS.h>
#include <WiFiUdp.h>
#include <ArduinoOTA.h>
#include <DNSServer.h>
#include <PubSubClient.h>
#include <WiFiManager.h>
#include <ArduinoJson.h>
#define mqtt_server "192.168.2.230"
#define mqtt_port "1883"
#define Hostname "paradoxtest" //not more than 15
#define paradoxRX 13
#define paradoxTX 15
#define Stay_Arm 0x01
#define Stay_Arm2 0x02
#define Sleep_Arm 0x03
#define Full_Arm 0x04
#define Disarm 0x05
#define Bypass 0x10
#define MessageLength 37
#define LED LED_BUILTIN
#define TRACE 1
const char *root_topicOut = "/paradox/out";
const char *root_topicStatus = "/paradox/status";
const char *root_topicIn = "/paradox/in";
WiFiClient espClient;
// client parameters
PubSubClient client(espClient);
SoftwareSerial paradoxSerial(paradoxRX, paradoxTX);
bool shouldSaveConfig = false;
bool ResetConfig = false;
bool PannelConnected =false;
bool PanelError = false;
long lastReconnectAttempt = 0;
char inData[38]; // Allocate some space for the string
byte pindex = 0; // Index into array; where to store the character
struct inPayload
{
byte PcPasswordFirst2Digits;
byte PcPasswordSecond2Digits;
byte Command;
byte Subcommand;
} ;
typedef struct {
byte armstatus;
byte event;
byte sub_event;
String dummy;
} Payload;
Payload paradox;
void setup() {
pinMode(LED_BUILTIN, OUTPUT);
blink(100);
delay(1000);
paradoxSerial.begin(9600);
trc("serial monitor is up");
Serial.begin(9600);
Serial.flush(); // Clean up the serial buffer in case previous junk is there
trc("Paradox serial monitor is up");
blink(1000);
serial_flush_buffer();
trc("Running MountFs");
mountfs();
setup_wifi();
ArduinoOTA.setHostname("ParadoxControllerV2");
ArduinoOTA.begin();
trc("Finnished wifi setup");
delay(1500);
lastReconnectAttempt = 0;
wifi_station_set_hostname(Hostname);
sendMQTT(root_topicStatus,"ParadoxController V2.11");
}
void loop() {
readSerial();
if ( (inData[0] & 0xF0)!=0xE0){ // re-align serial buffer
blink(200);
serial_flush_buffer();
}
}
void SendJsonString(byte armstatus, byte event,byte sub_event ,String dummy)
{
String retval = "{ \"armstatus\":" + String(armstatus) + ", \"event\":" + String(event) + ", \"sub_event\":" + String(sub_event) + ", \"dummy\":\"" + String(dummy) + "\"}";
sendMQTT(root_topicOut,retval);
}
void sendMQTT(String topicNameSend, String dataStr){
if (!client.connected()) {
long now = millis();
if (now - lastReconnectAttempt > 5000) {
lastReconnectAttempt = now;
trc("client mqtt not connected, trying to connect");
// Attempt to reconnect
if (reconnect()) {
lastReconnectAttempt = 0;
}
}
}
else {
// MQTT loop
client.loop();
}
char topicStrSend[26];
topicNameSend.toCharArray(topicStrSend,26);
char dataStrSend[200];
dataStr.toCharArray(dataStrSend,200);
boolean pubresult = client.publish(topicStrSend,dataStrSend);
trc("sending ");
trc(dataStr);
trc("to ");
trc(topicNameSend);
}
void readSerial() {
while (Serial.available()<37 )
{
ArduinoOTA.handle();
client.loop();
}
{
pindex=0;
while(pindex < 37) // Paradox packet is 37 bytes
{
inData[pindex++]=Serial.read();
}
inData[++pindex]=0x00; // Make it print-friendly
if ((inData[0] & 0xF0) == 0xE0)
{ // Does it look like a valid packet?
paradox.armstatus = inData[0];
paradox.event = inData[7];
paradox.sub_event = inData[8];
String zlabel = String(inData[15]) + String(inData[16]) + String(inData[17]) + String(inData[18]) + String(inData[19]) + String(inData[20]) + String(inData[21]) + String(inData[22]) + String(inData[23]) + String(inData[24]) + String(inData[25]) + String(inData[26]) + String(inData[27]) + String(inData[28]) + String(inData[29]) + String(inData[30]);
paradox.dummy = zlabel;
SendJsonString(paradox.armstatus, paradox.event, paradox.sub_event, paradox.dummy);
if (inData[7] == 48 && inData[8] == 3)
{
PannelConnected = false;
// trc("panel logout");
sendMQTT(root_topicStatus, "panel logout");
}
if (inData[7] == 48 && inData[8] == 2 && !PannelConnected)
{
PannelConnected = true;
//trc("panel Login");
sendMQTT(root_topicStatus, "panel Login");
}
}
}
}
void blink(int duration) {
digitalWrite(LED_BUILTIN,LOW);
delay(duration);
digitalWrite(LED_BUILTIN,HIGH);
}
void saveConfigCallback () {
trc("Should save config");
shouldSaveConfig = true;
}
void callback(char* topic, byte* payload, unsigned int length) {
// In order to republish this payload, a copy must be made
// as the orignal payload buffer will be overwritten whilst
// constructing the PUBLISH packet.
trc("Hey I got a callback ");
// Conversion to a printable string
payload[length] = '\0';
trc("JSON Returned! ====");
String callbackstring = String((char *)payload);
inPayload data = Decodejson((char *)payload);
PanelError= false;
doLogin(data.PcPasswordFirst2Digits, data.PcPasswordSecond2Digits);
int cnt = 0;
while (!PannelConnected && cnt < 10)
{
readSerial();
cnt++;
}
if (!PannelConnected)
{
trc("Problem connecting to panel");
sendMQTT(root_topicStatus, "Problem connecting to panel");
} else if (data.Command != 0x00 && PannelConnected ) {
ControlPanel(data);
}else {
trc("Bad Command ");
sendMQTT(root_topicStatus, "Bad Command ");
}
}
byte getPanelCommand(String data){
byte retval=0x00;
if (data == "stay" || data == "Stay" || data == "STAY" || data=="0")
{
retval = Stay_Arm;
}
else if (data == "arm" || data == "Arm" || data == "ARM" || data=="1")
{
retval= Full_Arm;
}
else if (data == "sleep" || data == "Sleep" || data == "SLEEP" || data=="2")
{
retval= Sleep_Arm;
}
else if (data == "disarm" || data == "Disarm" || data == "DISARM" || data == "3")
{
retval=Disarm;
}
else if (data == "bypass" || data == "Bypass" || data == "BYPASS" || data == "10")
{
retval=Bypass;
}
else if (data == "setdate")
{
retval=0x00;
panelSetDate();
}
else if (data == "disconnect" || data == "Disconnect" || data == "DISCONNECT" || data == "99")
{
retval=0x00;
PanelDisconnect();
}
return retval;
}
void panelSetDate(){
byte data[MessageLength] = {};
byte checksum;
for (int x = 0; x < MessageLength; x++)
{
data[x] = 0x00;
}
data[0] = 0x30;
data[4] = 0x21;
data[5] = 0x18;
data[6] = 0x02;
data[7] = 0x06;
data[8] = 0x01;
data[9] = 0x22;
data[33] = 0x01;
checksum = 0;
for (int x = 0; x < MessageLength - 1; x++)
{
checksum += data[x];
}
while (checksum > 255)
{
checksum = checksum - (checksum / 256) * 256;
}
data[36] = checksum & 0xFF;
Serial.write(data, MessageLength);
}
void ControlPanel(inPayload data){
byte armdata[MessageLength] = {};
byte checksum;
for (int x = 0; x < MessageLength; x++)
{
armdata[x] = 0x00;
}
armdata[0] = 0x40;
armdata[2] = data.Command;
armdata[3] = data.Subcommand;;
armdata[33] = 0x01;
armdata[34] = 0x00;
armdata[35] = 0x00;
checksum = 0;
for (int x = 0; x < MessageLength - 1; x++)
{
checksum += armdata[x];
}
while (checksum > 255)
{
checksum = checksum - (checksum / 256) * 256;
}
armdata[36] = checksum & 0xFF;
while (Serial.available()>37)
{
trc("serial cleanup");
readSerial();
}
trc("sending Data");
Serial.write(armdata, MessageLength);
readSerial();
if ( inData[0] >= 40 && inData[0] <= 45)
{
sendMQTT(root_topicStatus, "Command success ");
trc(" Command success ");
}
}
void PanelDisconnect(){
byte data[MessageLength] = {};
byte checksum;
for (int x = 0; x < MessageLength; x++)
{
data[x] = 0x00;
}
data[0] = 0x70;
data[2] = 0x05;
data[33] = 0x01;
checksum = 0;
for (int x = 0; x < MessageLength - 1; x++)
{
checksum += data[x];
}
while (checksum > 255)
{
checksum = checksum - (checksum / 256) * 256;
}
data[36] = checksum & 0xFF;
Serial.write(data, MessageLength);
readSerial();
}
void doLogin(byte pass1, byte pass2){
byte data[MessageLength] = {};
byte data1[MessageLength] = {};
byte checksum;
for (int x = 0; x < MessageLength; x++)
{
data[x]=0x00;
data1[x]=0x00;
}
serial_flush_buffer();
data[0] = 0x5f;
data[1] = 0x20;
data[33] = 0x01;
data[34] = 0x00;
data[35] = 0x00;
data[33] = 0x01;
checksum = 0;
for (int x = 0; x < MessageLength - 1; x++)
{
checksum += data[x];
}
while (checksum > 255)
{
checksum = checksum - (checksum / 256) * 256;
}
data[36] = checksum & 0xFF;
if (TRACE)
{
// for (int x = 0; x < MessageLength; x++)
// {
// paradoxSerial.print("Address-");
// paradoxSerial.print(x);
// paradoxSerial.print("=");
// paradoxSerial.println(data[x], HEX);
// }
}
Serial.write(data, MessageLength);
readSerial();
if (TRACE)
{
// for (int x = 0; x < MessageLength; x++)
// {
// paradoxSerial.print("replAddress-");
// paradoxSerial.print(x);
// paradoxSerial.print("=");
// paradoxSerial.println(inData[x], HEX);
// }
}
data1[0] = 0x00;
data1[4] = inData[4];
data1[5] = inData[5];
data1[6] = inData[6];
data1[7] = inData[7];
data1[7] = inData[8];
data1[9] = inData[9];
data1[10] = pass1; //panel pc password digit 1 & 2
data1[11] = pass2; //panel pc password digit 3 & 4
data1[33] = 0x01;
checksum = 0;
for (int x = 0; x < MessageLength - 1; x++)
{
checksum += data1[x];
}
while (checksum > 255)
{
checksum = checksum - (checksum / 256) * 256;
}
data1[36] = checksum & 0xFF;
if (TRACE)
{
// for (int x = 0; x < MessageLength; x++)
// {
// paradoxSerial.print("SendinGINITAddress-");
// paradoxSerial.print(x);
// paradoxSerial.print("=");
// paradoxSerial.println(data1[x], HEX);
// }
}
Serial.write(data1, MessageLength);
readSerial();
if (TRACE)
{
// for (int x = 0; x < MessageLength; x++)
// {
// paradoxSerial.print("lastAddress-");
// paradoxSerial.print(x);
// paradoxSerial.print("=");
// paradoxSerial.println(inData[x], HEX);
// }
}
}
struct inPayload Decodejson(char *Payload){
inPayload indata;
DynamicJsonBuffer jsonBuffer;
JsonObject &root = jsonBuffer.parseObject(Payload);
if (!root.success())
{
indata = {0x00,0x00,0x00,0x00};
trc("JSON parsing failed!");
return indata;
}
else
{
char charpass1[4];
char charpass2[4];
char charsubcommand[4];
String password = root["password"];
String command = root["Command"];
String subcommand = root["Subcommand"];
String pass1 = password.substring(0, 2);
String pass2 = password.substring(2, 4);
trc(pass1);
trc(pass2);
pass1.toCharArray(charpass1, 4);
pass2.toCharArray(charpass2, 4);
subcommand.toCharArray(charsubcommand,4);
trc(password);
trc(command);
trc(charpass1);
trc(charpass2);
unsigned long number1 = strtoul(charpass1, nullptr, 16);
unsigned long number2 = strtoul(charpass2, nullptr, 16);
unsigned long number3 = strtoul(charsubcommand, nullptr, 16);
byte PanelPassword1 = number1 & 0xFF;
byte PanelPassword2 = number2 & 0xFF;
byte SubCommand = number3 & 0xFF;
byte CommandB = getPanelCommand(command) ;
if (TRACE)
{
paradoxSerial.print("0x");
paradoxSerial.println(PanelPassword1, HEX);
paradoxSerial.print("0x");
paradoxSerial.println(PanelPassword2, HEX);
}
inPayload data1 = {PanelPassword1, PanelPassword2, CommandB, SubCommand};
return data1;
}
return indata;
}
void serial_flush_buffer(){
while (Serial.read() >= 0)
;
}
void setup_wifi(){
WiFiManagerParameter custom_mqtt_server("server", "mqtt server", mqtt_server, 40);
WiFiManagerParameter custom_mqtt_port("port", "mqtt port", mqtt_port, 6);
WiFiManager wifiManager;
if (ResetConfig)
{
trc("Resetting wifiManager");
WiFi.disconnect();
wifiManager.resetSettings();
}
if (mqtt_server=="" || mqtt_port=="")
{
trc("Resetting wifiManager");
WiFi.disconnect();
wifiManager.resetSettings();
ESP.reset();
delay(1000);
}
else
{
trc("values ar no null ");
}
wifiManager.setSaveConfigCallback(saveConfigCallback);
wifiManager.setConfigPortalTimeout(180);
wifiManager.addParameter(&custom_mqtt_server);
wifiManager.addParameter(&custom_mqtt_port);
if (!wifiManager.autoConnect("PARADOXController_AP", "")) {
trc("failed to connect and hit timeout");
delay(3000);
//reset and try again, or maybe put it to deep sleep
ESP.reset();
delay(5000);
}
//if you get here you have connected to the WiFi
trc("connected...yeey :)");
//read updated parameters
strcpy(mqtt_server, custom_mqtt_server.getValue());
strcpy(mqtt_port, custom_mqtt_port.getValue());
//save the custom parameters to FS
if (shouldSaveConfig) {
trc("saving config");
DynamicJsonBuffer jsonBuffer;
JsonObject& json = jsonBuffer.createObject();
json["mqtt_server"] = mqtt_server;
json["mqtt_port"] = mqtt_port;
File configFile = SPIFFS.open("/config.json", "w");
if (!configFile) {
trc("failed to open config file for writing");
}
json.printTo(Serial);
json.printTo(configFile);
configFile.close();
//end save
}
trc("local ip : ");
paradoxSerial.println(WiFi.localIP());
trc("Setting Mqtt Server values");
trc("mqtt_server : ");
trc(mqtt_server);
trc("mqtt_server_port : ");
trc(mqtt_port);
trc("Setting Mqtt Server connection");
unsigned int mqtt_port_x = atoi (mqtt_port);
client.setServer(mqtt_server, mqtt_port_x);
client.setCallback(callback);
reconnect();
trc("");
trc("WiFi connected");
trc("IP address: ");
trc((String)WiFi.localIP());
}
boolean reconnect() {
// Loop until we're reconnected
while (!client.connected()) {
trc("Attempting MQTT connection...");
// Attempt to connect
// If you want to use a username and password, uncomment next line and comment the line if (client.connect("433toMQTTto433")) {
//if (client.connect("433toMQTTto433", mqtt_user, mqtt_password)) {
// and set username and password at the program beginning
String mqname = WiFi.macAddress();
char charBuf[50];
mqname.toCharArray(charBuf, 50) ;
if (client.connect(charBuf,root_topicStatus,0,false,"Paradox Disconnected")) {
// Once connected, publish an announcement...
//client.publish(root_topicOut,"connected");
trc("connected");
sendMQTT(root_topicStatus,"Paradox Connected");
//Topic subscribed so as to get data
String topicNameRec = root_topicIn;
//Subscribing to topic(s)
subscribing(topicNameRec);
} else {
trc("failed, rc=");
trc(String(client.state()));
trc(" try again in 5 seconds");
// Wait 5 seconds before retrying
delay(5000);
}
}
return client.connected();
}
void subscribing(String topicNameRec){ // MQTT subscribing to topic
char topicStrRec[26];
topicNameRec.toCharArray(topicStrRec,26);
// subscription to topic for receiving data
boolean pubresult = client.subscribe(topicStrRec);
if (pubresult) {
trc("subscription OK to");
trc(topicNameRec);
}
}
void mountfs(){
if (SPIFFS.begin()) {
trc("mounted file system");
if (SPIFFS.exists("/config.json")) {
//file exists, reading and loading
trc("reading config file");
File configFile = SPIFFS.open("/config.json", "r");
if (configFile) {
trc("opened config file");
size_t size = configFile.size();
// Allocate a buffer to store contents of the file.
std::unique_ptr<char[]> buf(new char[size]);
configFile.readBytes(buf.get(), size);
DynamicJsonBuffer jsonBuffer;
JsonObject& json = jsonBuffer.parseObject(buf.get());
json.printTo(Serial);
if (json.success()) {
trc("\nparsed json");
strcpy(mqtt_server, json["mqtt_server"]);
strcpy(mqtt_port, json["mqtt_port"]);
} else {
trc("failed to load json config");
}
}
}
else
{
trc("File /config.json doesnt exist");
//SPIFFS.format();
trc("Formatted Spiffs");
}
} else {
trc("failed to mount FS");
}
}
void trc(String msg){
if (TRACE) {
paradoxSerial.println(msg);
// sendMQTT(root_topicStatus,msg);
}
}