Coder Social home page Coder Social logo

Comments (69)

bigstation17 avatar bigstation17 commented on May 28, 2024 1

馃憤 and i will order an wemos d1 pro :))) to test it.

from paradoxrs232tomqtt.

maragelis avatar maragelis commented on May 28, 2024 1

https://github.com/maragelis/ParadoxRs232toMqtt/releases/tag/20190125

from paradoxrs232tomqtt.

maragelis avatar maragelis commented on May 28, 2024 1

Pgm is easy just have to pass a new action 0x32 pgm on and 0x33 pgm off

from paradoxrs232tomqtt.

maragelis avatar maragelis commented on May 28, 2024 1

Ok done updated to support PGM thanks for the cleanup code, also added OTA to mqtt to enable disable it .

from paradoxrs232tomqtt.

maragelis avatar maragelis commented on May 28, 2024 1

I think this issue is closed

from paradoxrs232tomqtt.

maragelis avatar maragelis commented on May 28, 2024

are you getting any messages back on the status mqtt sub

from paradoxrs232tomqtt.

maragelis avatar maragelis commented on May 28, 2024

I also hope you are not missing a quote, in your image its missing after the semicolon.
{
"password":"1234",
"Command":"arm",
"Subcommand":"0"
}

from paradoxrs232tomqtt.

bigstation17 avatar bigstation17 commented on May 28, 2024

Noup. Is not missing. It was hide in image.
When i send an mqtt command i dont get any response back, i get only sensors event, events when i arm manually from keypad...

from paradoxrs232tomqtt.

maragelis avatar maragelis commented on May 28, 2024

double check you rx cable is connected ok

from paradoxrs232tomqtt.

bigstation17 avatar bigstation17 commented on May 28, 2024

I checked, even i replaced the d1 mini.
It is posible that sp4000 board was programed to not send data trough tx?
How can i debug? I have ttl usb serial adapter.

from paradoxrs232tomqtt.

maragelis avatar maragelis commented on May 28, 2024

you are getting tx readings it is not receiving RX (paradox side)
I suggest you set trace to 1 and connect serial ttl to debug pin 13 and see what comes up

from paradoxrs232tomqtt.

maragelis avatar maragelis commented on May 28, 2024

No i have a sp4000 working great i used that (sp4000) in the lab

from paradoxrs232tomqtt.

bigstation17 avatar bigstation17 commented on May 28, 2024

I connect TX from d1mini > RX ftdi adapter i have this
screenshot 46

from paradoxrs232tomqtt.

maragelis avatar maragelis commented on May 28, 2024

that looks like binary, try connecting to gpio 13 (D7)

from paradoxrs232tomqtt.

bigstation17 avatar bigstation17 commented on May 28, 2024

I don't have any response on D7 pin

from paradoxrs232tomqtt.

maragelis avatar maragelis commented on May 28, 2024

you have to set trace to 1 in the code to get output debug messages on D*8. Is your user code 4 digits or more?

from paradoxrs232tomqtt.

maragelis avatar maragelis commented on May 28, 2024

I will ask again not to be rude, are you not getting any messages on paradox/status ,

If you are not getting messages on status/ means the in payload is not recognized

from paradoxrs232tomqtt.

maragelis avatar maragelis commented on May 28, 2024

sorry about that but Debug messages can be read through D8 TXD2 Pin on the wemos or if you prefer IO15.

from paradoxrs232tomqtt.

bigstation17 avatar bigstation17 commented on May 28, 2024

My panel code is 4 digits.
I have set trace 1
screenshot 47

No. on paradox/status i ony get: Paradox Connected and ParadoxController V2.11
an on paradox/out id get sensors events like ({ "armstatus":224, "event":0, "sub_event":3, "dummy":"Zone 03 "})

from paradoxrs232tomqtt.

maragelis avatar maragelis commented on May 28, 2024

Output is working ok. Try connecting d8 for debug send a arm payload and paste messages so I can see

from paradoxrs232tomqtt.

bigstation17 avatar bigstation17 commented on May 28, 2024

On D8 Pin i have:
"飧府飧府飧府}?锟絵oo锟絵飧甝飧府飧府飧府飧府飧府锟給[飧府飧府飧府飧府{斯飧府飧府飧府飧府飧嬧府}飧畕}锟斤拷飧府飧府飧府zuvuz锟解府飧府飧府飧府飧府虢封府飧府o锟解府k飧府飧府飧府{飧府飧府飧府飧府飧府飧府飧府飧府飧府飧府飧府飧府飧府飧府飧府飧畕飧府飧府飧府飧畗飧府飧府飧府锟解府飧府飧府"

from paradoxrs232tomqtt.

maragelis avatar maragelis commented on May 28, 2024

Bring it down to 9600

from paradoxrs232tomqtt.

bigstation17 avatar bigstation17 commented on May 28, 2024

It is at 9600 :(
I connected another mini direct with usb cable on laptop to debug, and when i send messages i have:
image

from paradoxrs232tomqtt.

maragelis avatar maragelis commented on May 28, 2024

U are using esp core 2.4.2 I haven't tested it on that and there are many problems with that. Bring it down to 2.3.0

from paradoxrs232tomqtt.

bigstation17 avatar bigstation17 commented on May 28, 2024

screenshot 48

from paradoxrs232tomqtt.

maragelis avatar maragelis commented on May 28, 2024

I don't how else to help you.

from paradoxrs232tomqtt.

bigstation17 avatar bigstation17 commented on May 28, 2024

Ok. Thank you very much.

from paradoxrs232tomqtt.

maragelis avatar maragelis commented on May 28, 2024

Try release files bin
dont forget to flash blank.bin before
https://github.com/maragelis/ParadoxRs232toMqtt/releases

from paradoxrs232tomqtt.

bigstation17 avatar bigstation17 commented on May 28, 2024

Thank you for your work.
I tried new version and unfortunately i have the same problem. I think that i am a special case :)
I receive all sensors correct, but no with the commands.

Now i have discover a strange behavior. When i send any message to topic paradoxdCTL/in ESP is rebooting. Even if i send a blank message.

image 13-01-2019 at 12 36

from paradoxrs232tomqtt.

maragelis avatar maragelis commented on May 28, 2024

If you flashed by arduino ide change the max message length in the pubsubclient.h to 512. Or better try flashing realese bin file.

from paradoxrs232tomqtt.

bigstation17 avatar bigstation17 commented on May 28, 2024

Yes. I tried with ParadoxAlarmSystemOTA.HASSIO.bin, ParadoxAlarmSystemOTA.ino.TRACE.bin and with arduino IDE, erase all data.

Esp is rebooting when i send message to paradoxdCTL/in even is not connected to panel.

serial monitor is up
Running MountFs
mounted file system
reading config file
opened config file
{"mqtt_server":"192.168.1.200","mqtt_port":"1883"}
parsed json
values ar no null
*WM: Adding parameter
*WM: server
*WM: Adding parameter
*WM: port
*WM:
*WM: AutoConnect
*WM: Connecting as wifi client...
*WM: Already connected. Bailing out.
*WM: IP Address:
*WM: 192.168.1.233
connected...yeey :)
Setting Mqtt Server values
mqtt_server :
192.168.1.200
mqtt_server_port :
1883
Setting Mqtt Server connection
Attempting MQTT connection...
connected
sending
{"status":"Paradox connected"}
to
paradoxdCTL/status
subscription OK to
paradoxdCTL/in

WiFi connected
IP address:
3909200064
*WM: freeing allocated params!
Starting HTTP...
Starting SSDP...
mDNS responder started
Ready!

Finnished wifi setup
Hey I got a callback
JSON Returned! ====
returned command = 4
Start login
Address-0=5F
Address-1=20
Address-2=0
Address-3=0
Address-4=0

from paradoxrs232tomqtt.

maragelis avatar maragelis commented on May 28, 2024

i will try see what鈥檚 causing this, what panel are you using.

from paradoxrs232tomqtt.

maragelis avatar maragelis commented on May 28, 2024

Sp4000 that鈥檚 what I am using without any problems. The only thing I can think of is old firmware on your panel.

from paradoxrs232tomqtt.

maragelis avatar maragelis commented on May 28, 2024

I have a new realese with better debug and better panel support. Will try finish it by tomorrow night.

from paradoxrs232tomqtt.

maragelis avatar maragelis commented on May 28, 2024

Did you try the 20190111 realese?

from paradoxrs232tomqtt.

bigstation17 avatar bigstation17 commented on May 28, 2024

Thank you very much, you are very patient with me :D
Yes. I tried every version :))) 20190111 - 20190103, bin files (ESPEasy), compile with arduino..etc.
I think is an esp problem because every time (even without connected to sp4000) i send message to topic paradoxdCTL/in esp is rebooting. I tried with 2 wemos, same behavior.

from paradoxrs232tomqtt.

maragelis avatar maragelis commented on May 28, 2024

Did you try sending the payload in the wiki.
{
"password":"1234",
"Command":"arm",
"Subcommand":"0"
}

from paradoxrs232tomqtt.

FigJam23 avatar FigJam23 commented on May 28, 2024

I'm also having Sim issue with latest v2
Unfortunately I haven't had time to play around but same as big station output .
I did also have rebooting issue on commands but think I fixed that by either reflash or I had comms reversed.

from paradoxrs232tomqtt.

bigstation17 avatar bigstation17 commented on May 28, 2024

Did you try sending the payload in the wiki.
{
"password":"1234",
"Command":"arm",
"Subcommand":"0"
}

Yes. i have rebooting problem with any payload that i send.

from paradoxrs232tomqtt.

maragelis avatar maragelis commented on May 28, 2024

https://github.com/maragelis/ParadoxRs232toMqtt/releases/tag/20190114a

from paradoxrs232tomqtt.

bigstation17 avatar bigstation17 commented on May 28, 2024

https://github.com/maragelis/ParadoxRs232toMqtt/releases/tag/20190114a

Noup. Same issue.
image 15-01-2019 at 12 50

As soon i send any json message to esp is rebooting. {"xxx":"xxx"} > Reboot.
Set Trace i s working.

I'm using Wemos D1 mini (https://wiki.wemos.cc/products:d1:d1_mini) regular version with 4mb not PRO version. Can this be the problem ?

from paradoxrs232tomqtt.

maragelis avatar maragelis commented on May 28, 2024

Please do me a favor as soon as it boots set TRACE=1 send mqtt message
then send this payload as is (please dont change anything)
{"Command":"stay","Subcommand":"0","password":"0000"}
Post serial output

from paradoxrs232tomqtt.

maragelis avatar maragelis commented on May 28, 2024

I will try a wemos d1 mini tonight and get back to you..

from paradoxrs232tomqtt.

bigstation17 avatar bigstation17 commented on May 28, 2024

Please do me a favor as soon as it boots set TRACE=1 send mqtt message
then send this payload as is (please dont change anything)
{"Command":"stay","Subcommand":"0","password":"0000"}
Post serial output

pres212

from paradoxrs232tomqtt.

maragelis avatar maragelis commented on May 28, 2024

you are crashing on the panel logon session. Looks like the SoftwareSerial lib is crashing.could you paste the full stack trace
Thanks for your help

from paradoxrs232tomqtt.

bigstation17 avatar bigstation17 commented on May 28, 2024

Trace is ON
Hey I got a callback
JSON Returned! ====
parsing Recievied Json Data
returned command = 1
Json Data is ok
Start login

Soft WDT reset

ctx: cont
sp: 3ffffc40 end: 3fffffd0 offset: 01b0

stack>>>
3ffffdf0: 00000009 00000001 0000000f 4010683d
3ffffe00: 3ffe99e4 00000000 3ffefce4 4020b040
3ffffe10: 00000001 000002f3 000002f3 4010020c
3ffffe20: 00000000 00000000 3ffffeac 3ffffeaa
3ffffe30: 3ffefce4 00000024 3ffffea9 40218dd0
3ffffe40: 00000000 00000001 00000000 00000000
3ffffe50: 3ffefcdf 00000001 3ffefce4 4020aa1a
3ffffe60: 00000000 00000000 00000000 00000000
3ffffe70: 00000000 00000000 00000000 00000000
3ffffe80: 00000000 00205f00 00000000 00000000
3ffffe90: 00000000 00000000 00000000 00000000
3ffffea0: 00000000 00050000 3fff8400 40215c8d
3ffffeb0: 3fff03dc 000002f3 000002f3 4010020c
3ffffec0: 00000000 00000001 3fffff00 401006dc
3ffffed0: 00000000 00000001 3fffff00 402168cc
3ffffee0: 3ffe9460 00000001 00000000 00000000
3ffffef0: 3ffefcdf 00000001 00000000 4020ad68
3fffff00: 00000000 00000000 00000000 00000002
3fffff10: 00000042 3ffefd24 3fff2c8c 0000003f
3fffff20: 00000035 00010000 00000064 402175b2
3fffff30: 3fffff60 00000001 0000000e 00000001
3fffff40: 0000000e 00005c86 3ffefd24 402184e0
3fffff50: 3fffdad0 00005c86 3ffefd24 40213530
3fffff60: 3ffef501 00000000 3ffefbcc 40210acd
3fffff70: 00000004 3ffefd27 00000047 3fffefb0
3fffff80: 00000000 00000000 00000000 3fff04dc
3fffff90: 3fffdad0 00000000 00000024 4020a000
3fffffa0: 00000000 00000000 3fff04d5 4020a22c
3fffffb0: feefeffe 00000000 3fff04d5 40217584
3fffffc0: feefeffe feefeffe 3ffe8640 40100739
<<<stack<<<
锟絜飧府锟解府飧府飧畘{"mqtt_server":"192.168.1.200","mqtt_port":"1883"}*WM: Adding parameter
*WM: server
*WM: Adding parameter
*WM: port
*WM:
*WM: AutoConnect
*WM: Connecting as wifi client...
*WM: Using last saved values, should be faster
*WM: Connection result:
*WM: 3
*WM: IP Address:
*WM: 192.168.1.233
*WM: freeing allocated params!
Starting HTTP...
Starting SSDP...

from paradoxrs232tomqtt.

maragelis avatar maragelis commented on May 28, 2024

I need to try replicate you error on my rig.

from paradoxrs232tomqtt.

maragelis avatar maragelis commented on May 28, 2024

OK software serial is doing the job its running out of memory. I will try a wemos d1 mini and see what the problem is.

0x4010683d: micros64 at /Users/panagiotis/Library/Arduino15/packages/esp8266/hardware/esp8266/2.4.2/cores/esp8266/core_esp8266_wiring.c line 201
0x4020b040: SoftwareSerial::write(unsigned char) at /Users/panagiotis/Library/Arduino15/packages/esp8266/hardware/esp8266/2.4.2/libraries/SoftwareSerial/SoftwareSerial.cpp line 188
0x4010020c: _umm_free at /Users/panagiotis/Library/Arduino15/packages/esp8266/hardware/esp8266/2.4.2/cores/esp8266/umm_malloc/umm_malloc.c line 1295
0x40218dd0: fs::FS::begin() at /Users/panagiotis/Library/Arduino15/packages/esp8266/hardware/esp8266/2.4.2/cores/esp8266/FS.cpp line 168
0x4020aa1a: doLogin(unsigned char, unsigned char) at /Users/panagiotis/Documents/Github/ParadoxRs232toMqtt/ParadoxAlarmSystem/ParadoxAlarmSystemOTA/ParadoxAlarmSystemOTA.ino line 814
0x40215c8d: MD5Builder::getChars(char*) at /Users/panagiotis/Library/Arduino15/packages/esp8266/hardware/esp8266/2.4.2/cores/esp8266/MD5Builder.cpp line 84
0x4010020c: _umm_free at /Users/panagiotis/Library/Arduino15/packages/esp8266/hardware/esp8266/2.4.2/cores/esp8266/umm_malloc/umm_malloc.c line 1295
0x401006dc: free at /Users/panagiotis/Library/Arduino15/packages/esp8266/hardware/esp8266/2.4.2/cores/esp8266/umm_malloc/umm_malloc.c line 1755
0x402168cc: String::reserve(unsigned int) at /Users/panagiotis/Library/Arduino15/packages/esp8266/hardware/esp8266/2.4.2/cores/esp8266/WString.cpp line 148
0x4020ad68: callback(char*, unsigned char*, unsigned int) at /Users/panagiotis/Documents/Github/ParadoxRs232toMqtt/ParadoxAlarmSystem/ParadoxAlarmSystemOTA/ParadoxAlarmSystemOTA.ino line 376
0x402175b2: user_init() at /Users/panagiotis/Library/Arduino15/packages/esp8266/hardware/esp8266/2.4.2/cores/esp8266/core_esp8266_main.cpp line 230
0x402184e0: run_scheduled_functions() at /Users/panagiotis/Library/Arduino15/packages/esp8266/hardware/esp8266/2.4.2/cores/esp8266/Schedule.cpp line 45
0x40213530: PubSubClient::loop() at /Users/panagiotis/Documents/Arduino/libraries/PubSubClient/src/PubSubClient.cpp line 331
0x40210acd: ESP8266WebServer::~ESP8266WebServer() at /Users/panagiotis/Library/Arduino15/packages/esp8266/tools/xtensa-lx106-elf-gcc/1.20.0-26-gb404fb9-2/xtensa-lx106-elf/include/c++/4.8.2/bits/unique_ptr.h line 185
0x4020a000: readSerialData() at /Users/panagiotis/Documents/Github/ParadoxRs232toMqtt/ParadoxAlarmSystem/ParadoxAlarmSystemOTA/ParadoxAlarmSystemOTA.ino line 327
0x4020a22c: setup() at /Users/panagiotis/Library/Arduino15/packages/esp8266/hardware/esp8266/2.4.2/cores/esp8266/HardwareSerial.h line 75
0x40217584: user_init() at /Users/panagiotis/Library/Arduino15/packages/esp8266/hardware/esp8266/2.4.2/cores/esp8266/core_esp8266_main.cpp line 218

from paradoxrs232tomqtt.

maragelis avatar maragelis commented on May 28, 2024

Just flashed a new wemos d1 mini works fine.

from paradoxrs232tomqtt.

maragelis avatar maragelis commented on May 28, 2024

used
arduino IDE 1.8.8
pubsubclient 2.7.0
wifimanager 0.14.0
arduinojson 5.13.4

from paradoxrs232tomqtt.

maragelis avatar maragelis commented on May 28, 2024

image

from paradoxrs232tomqtt.

bigstation17 avatar bigstation17 commented on May 28, 2024

Well....i used latest bin file 20190114a with EspEasy.
It is normal that esp is rebooting on any json payload ?

test-bins

from paradoxrs232tomqtt.

maragelis avatar maragelis commented on May 28, 2024

{"Command":"stay","Subcommand":"0","password":"0000"}

from paradoxrs232tomqtt.

bigstation17 avatar bigstation17 commented on May 28, 2024

I get reboot with any command
{"Command":"stay","Subcommand":"0","password":"0000"}
{"Command":"stay","Subcommand":"0","password":"master pass"}
{"Command":"stay","Subcommand":"0","password":"user pass"}

from paradoxrs232tomqtt.

maragelis avatar maragelis commented on May 28, 2024

Try download ino file and compile yourself chech libs are the same. Update arduino core and libs. Next thing left is for me to send you a working wemos. Also check cables

from paradoxrs232tomqtt.

bigstation17 avatar bigstation17 commented on May 28, 2024

:)))))) You are very patient.
Thanks anyway..i'm using as it is..reporting works very well.
I ordered wemos pro and i will check with that.
Have a nice evening.

from paradoxrs232tomqtt.

maragelis avatar maragelis commented on May 28, 2024

The thing is I have two panels an sp6000 and a sp4000 both on my bench for test. They both work ok with the last update.

from paradoxrs232tomqtt.

bigstation17 avatar bigstation17 commented on May 28, 2024

It's possible to have a different firmware in panel and cannot login through serial port...
But still..i think i have an esp problem due to wdt reset on payloads.

from paradoxrs232tomqtt.

maragelis avatar maragelis commented on May 28, 2024

It鈥檚 not the payload it鈥檚 when trying to logon and it鈥檚 using the serial write procedure that鈥檚 when it crashes.

from paradoxrs232tomqtt.

maragelis avatar maragelis commented on May 28, 2024

It鈥檚 a soft wdt and when debugging the crash data it shows memory problem on softwareserial

from paradoxrs232tomqtt.

FigJam23 avatar FigJam23 commented on May 28, 2024

What's the recommendation tested firmware versions for panel please

from paradoxrs232tomqtt.

maragelis avatar maragelis commented on May 28, 2024

https://github.com/maragelis/ParadoxRs232toMqtt/wiki/Tested-Paradox-Alarm-Systems

from paradoxrs232tomqtt.

tasosstr avatar tasosstr commented on May 28, 2024

Well....i used latest bin file 20190114a with EspEasy.
It is normal that esp is rebooting on any json payload ?

test-bins

螒纬伪蟺畏蟿苇 螤维谓慰, Well Done, you have done a Perfect job ! ! !

I had the same issue, after 2 days i was searching, i got message from panel but when i was try to arm ... or any other command i had a message Problem login ...

The solution, i move back the pin to Serial Hardware (Rx - Tx) and change the lines of code from SoftwareSerial to Serial and i use Serial1 for the debug (i din't check if working this) and everything are back to normal.

I have see somewhere in the past how to use and the 3 Hardware serial at the same time, something change in a file and then you have access to 3 at the same time, i will try to find and i will update here so to use it, because it is better from software, not loosing data :-)

螠蔚 桅喂位喂魏慰蠉蟼 围伪喂蟻蔚蟿喂蟽渭慰蠉蟼,
韦维蟽慰蟼

from paradoxrs232tomqtt.

tasosstr avatar tasosstr commented on May 28, 2024

I found it :-)

Here you are https://www.youtube.com/watch?v=GwShqW39jlE

I will give a try tomorrow ...

from paradoxrs232tomqtt.

maragelis avatar maragelis commented on May 28, 2024

螝伪位畏渭蔚蟻伪 韦伪蟽慰.
螘蠀蠂伪蟻喂蟽蟿蠅 纬喂伪 蟿伪 魏伪位伪 蟽慰蠀 位慰纬喂伪.
I had no time lately to work on the project. The last time i checked it was a software error int the softwareserial lib, the truth is I changed it to software so I could get debug messages from the usb connection. I have this project running 1,5 years now on my Paradox with no problems, but using the hardware serial on the chip.

I will swap back the hardware serial (If you have done the work I would appreciate a pull request), and will use the second TX on the chip for debug. (or send debug through the mqtt channel).

The link you sent is good but its for ESP32 which by default has three harware serial, the esp8266 only has one.

Will get back as soon as possible...
螤伪谓慰蟼

from paradoxrs232tomqtt.

tasosstr avatar tasosstr commented on May 28, 2024

螝伪位畏渭苇蟻伪 蠁委位蔚 螤维谓慰,

I use a NodeMCU V3 ( https://www.teachmemicro.com/nodemcu-pinout/ ) and now i check the the Serial1 as debug on D4 pin and i am happy because it sends data after Trace=1

I try to do Pull Request but somewhere stuck so i will paste here the changes on code i did it

#include <FS.h>
#include <SoftwareSerial.h>
#include <ESP8266WiFi.h>
#include <ESP8266mDNS.h>
#include <ESP8266SSDP.h>
#include <ESP8266WebServer.h>
#include <WiFiUdp.h>
#include <ArduinoOTA.h>
#include <DNSServer.h>
#include <PubSubClient.h>
#include <WiFiManager.h>
#include <ArduinoJson.h>

#define mqtt_server "192.168.1.230"
#define mqtt_port "1883"
#define Hostname "paradoxdCTL" //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 Hassio 1
bool TRACE = 0;

const char *root_topicOut = "paradoxdCTL/out";
const char *root_topicStatus = "paradoxdCTL/status";
const char *root_topicIn = "paradoxdCTL/in";
const char *root_topicArmStatus = "paradoxdCTL/status/Arm";
const char *root_topicZoneStatus = "paradoxdCTL/status/Zone";

WiFiClient espClient;
PubSubClient client(espClient);
//SoftwareSerial paradoxSerial(paradoxRX, paradoxTX, false ,255);

bool shouldSaveConfig = false;
bool ResetConfig = false;
bool PannelConnected =false;
bool PanelError = false;
bool RunningCommand=false;
bool JsonParseError=false;

unsigned long lastReconnectAttempt = 0UL;
unsigned long ul_Interval = 5000UL;

char inData[38]; // Allocate some space for the string
byte pindex = 0; // Index into array; where to store the character

ESP8266WebServer HTTP(80);

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, OUTPUT);
blink(100);
delay(1000);
WiFi.mode(WIFI_STA);

Serial.begin(9600);
Serial.flush();

Serial1.begin(9600);
Serial1.flush(); // Clean up the serial buffer in case previous junk is there
trc("serial monitor is up");
serial_flush_buffer();

trc("Running MountFs");
mountfs();

setup_wifi();
StartSSDP();

ArduinoOTA.setHostname(Hostname);
ArduinoOTA.begin();
trc("Finnished wifi setup");
delay(1500);
lastReconnectAttempt = 0;
digitalWrite(LED, HIGH);
}

void loop() {

readSerial();

if ( (inData[0] & 0xF0)!=0xE0){ // re-align serial buffer
serial_flush_buffer();
}
}

void StartSSDP()
{
if (WiFi.waitForConnectResult() == WL_CONNECTED) {

Serial1.printf("Starting HTTP...\n");
HTTP.on("/index.html", HTTP_GET, []() {
  HTTP.send(200, "text/plain", Hostname);
});
HTTP.on("/", HTTP_GET, []() {
  HTTP.send(200, "text/plain", Hostname);
});

HTTP.on("/description.xml", HTTP_GET, []() {
  SSDP.schema(HTTP.client());
});
HTTP.begin();

Serial1.printf("Starting SSDP...\n");
SSDP.setSchemaURL("description.xml");
SSDP.setDeviceType("upnp:rootdevice");
SSDP.setHTTPPort(80);
SSDP.setName(Hostname);
SSDP.setSerialNumber(WiFi.macAddress());
SSDP.setURL(String("http://") + WiFi.localIP().toString().c_str() +"/index.html");
SSDP.setModelName("ESP8266Wemos");
SSDP.setModelNumber("WEMOSD1");
SSDP.setModelURL("https://github.com/maragelis/ParadoxRs232toMqtt");
SSDP.setManufacturer("PM ELECTRONICS");
SSDP.setManufacturerURL("https://github.com/maragelis/");
SSDP.begin();

if (!MDNS.begin(Hostname)) {
trc("Error setting up MDNS responder!");
while (1) {
  delay(1000);
}

}
trc("mDNS responder started");

// Add service to MDNS-SD
MDNS.addService("http", "tcp", 80);

trc("Ready!\n");

}
}

bool sleepflag;
void SendJsonString(byte armstatus, byte event,byte sub_event ,String dummy)
{
if (Hassio)
{
char ZoneTopic[80];
char stateTopic[80];

String zone = String(root_topicOut) + "/zone";
zone.toCharArray(ZoneTopic, 80);

String state_topic = String(root_topicOut) + "/state";
state_topic.toCharArray(stateTopic, 80);

if (event == 1 || event == 0)
{

  zone = String(ZoneTopic) + String(sub_event);
  zone.toCharArray(ZoneTopic, 80);

  String zonestatus="OFF";

  if (event==1 )
  {
    zonestatus = "ON";
  }

  sendMQTT(ZoneTopic, zonestatus);
}
else if (event ==2  )
{
  
  if (sub_event==4 )
    sendMQTT(stateTopic, "triggered");
  if (sub_event == 11){
    sendMQTT(stateTopic, "disarmed");
    sleepflag = false;
  }
  if (sub_event == 12 && sleepflag==false)
    sendMQTT(stateTopic, "armed_away");
}
else if (event == 6)
{
  
  if (sub_event == 3 || sub_event == 4){
    sendMQTT(stateTopic, "armed_home");
    sleepflag=true;
  }
}

}
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()) {
unsigned long now = millis();
if (now - lastReconnectAttempt > ul_Interval) {
lastReconnectAttempt = now;
trc("client mqtt not connected, trying to connect");
// Attempt to reconnect
if (reconnect()) {
lastReconnectAttempt = 0UL;
}
}
}
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 readSerialQuick(){
while (Serial.available()<37 )
{
//client.loop();
yield();
}

 { 
   readSerialData();
 }

}

void readSerial(){
while (Serial.available()<37 )
{
ArduinoOTA.handle();
client.loop();
HTTP.handleClient();
yield();
}

 //{
   readSerialData();       
 //}

}

void readSerialData() {
pindex=0;

    while(pindex < 37) // Paradox packet is 37 bytes 
    {
        inData[pindex++]=Serial.read();      
        yield();      
    }
   
        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]);
            if (inData[14]!= 1){
            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, "{\"status\":\"Panel logout\"}");
            }
            else if (inData[7] == 48 && inData[8] == 2 )
            {
              PannelConnected = true;
              trc("panel Login");
              sendMQTT(root_topicStatus, "{\"status\":\"Panel Login Success\"}");
            }
            
          }

}

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.
if (RunningCommand){
trc("Command already Running exiting");
return;
}
trc("Hey I got a callback ");
// Conversion to a printable string
payload[length] = '\0';
inPayload data;

trc("JSON Returned! ====");
String callbackstring = String((char *)payload);
if (callbackstring == "Trace=1")
{
TRACE=1;
Serial1.println("Trace is ON");
return ;
}
else if (callbackstring == "Trace=0")
{
TRACE=0;
Serial1.println("Trace is OFF");
return ;
}
else if (callbackstring=="")
{
trc("No payload data");
return;
}
else
{
trc("parsing Recievied Json Data");
data = Decodejson((char *)payload);
if (JsonParseError)
{
trc("Error parsing Json Command") ;
JsonParseError=false;
return;
}
trc("Json Data is ok ");
PanelError = false;
trc("Start login");
if (!PannelConnected)
doLogin(data.PcPasswordFirst2Digits, data.PcPasswordSecond2Digits);
trc("end login");

}

RunningCommand=true;
if (!PannelConnected)
{
trc("Problem connecting to panel");
sendMQTT(root_topicStatus, "{"status":"Problem connecting to panel"}");
}else if (data.Command == 0x90 )
{

trc("Running panel status command");
if (data.Subcommand==0)
{
 PanelStatus0(false,0);
}
if (data.Subcommand==1)
{
 PanelStatus1(false);
}

}
else if (data.Command == 0x91 ) {
trc("Running Setdate");
ArmState();
}
else if (data.Command == 0x92 ) {
trc("Running ZoneState");
ZoneState(data.Subcommand);
}
else if (data.Command != 0x00 ) {
trc("Running Command");
ControlPanel(data);
}
else {
trc("Bad Command ");
sendMQTT(root_topicStatus, "{"status":"Bad Command" }");
}

RunningCommand=false;

}

byte getPanelCommand(String data){
byte retval=0x00;
data.toLowerCase();
if (data == "stay" || data=="0")
{

retval = Stay_Arm;

}
else if (data == "arm" || data=="1")
{
retval= Full_Arm;
}
else if (data == "sleep" || data=="2")
{

retval= Sleep_Arm;

}
else if (data == "disarm" || data == "3")
{

retval=Disarm;

}

else if (data == "bypass" || data == "10")
{

retval=Bypass;

}

else if (data == "panelstatus" )
{
retval=0x90;
trc("PAnelStatus command ");

}

else if (data == "setdate")
{
retval=0x89;

}
else if (data == "armstate")
{
retval=0x91;

}
else if (data == "zonestate")
{
retval=0x92;

}
else if (data == "disconnect" || data == "99")
{
retval=0x00;
//PanelDisconnect();
}
if(TRACE)
{
Serial1.print("returned command = ");
Serial1.println(retval , HEX);
}
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] = 0x05;
data[7] = 0x05;
data[8] = 0x13;
data[9] = 0x22;
data[33] = 0x05;

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] = 0x05;
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();
yield();
}

trc("sending Data");
Serial.write(armdata, MessageLength);
readSerialQuick();

if ( inData[0] >= 40 && inData[0] <= 45)
{
sendMQTT(root_topicStatus, "{"status":"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] = 0x05;

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 PanelStatus0(bool showonlyZone ,int zone)
{
byte data[MessageLength] = {};
byte checksum;
for (int x = 0; x < MessageLength; x++)
{
data[x] = 0x00;
}

serial_flush_buffer();
data[0] = 0x50;
data[1] = 0x00;
data[2] = 0x80;
data[3] = 0x00;
data[33] = 0x05;
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);

readSerialQuick();

bool Timer_Loss = bitRead(inData[4],7);
bool PowerTrouble  = bitRead(inData[4],1);
bool ACFailureTroubleIndicator = bitRead(inData[6],1);
bool NoLowBatteryTroubleIndicator = bitRead(inData[6],0);
bool TelephoneLineTroubleIndicator = bitRead(inData[8],0);
int ACInputDCVoltageLevel = inData[15];
int PowerSupplyDCVoltageLevel =inData[16];
int BatteryDCVoltageLevel=inData[17];

//sendMQTT(root_topicStatus,"Timer_Loss=" +String(inData[4]) );
String retval = "{ "Timer_Loss":"" + String(Timer_Loss) + """ +
","PowerTrouble":"" + String(PowerTrouble) + """ +
","ACFailureTrouble":"" + String(ACFailureTroubleIndicator) + """ +
","TelephoneLineTrouble":"" + String(TelephoneLineTroubleIndicator) + """ +
","PSUDCVoltage":"" + String(PowerSupplyDCVoltageLevel) + """ +
","BatteryDCVoltage":"" + String(BatteryDCVoltageLevel) + """ +
","BatteryTrouble":"" + String(NoLowBatteryTroubleIndicator) + ""}";

trc(retval);
if (!showonlyZone)
{
sendMQTT(root_topicStatus,retval);
}
String Zonename ="";
int zcnt = 0;
for (int i = 19 ; i <= 22;i++)
{
 for (int j = 0 ; j < 8;j++) 
   {
     Zonename = "Z" + String(++zcnt);

    retval = "{ \""+ Zonename +"\" :\""+ bitRead(inData[i],j) +"\"}" ;
    trc (retval);
    if ((zone==0 && bitRead(inData[i],j) == 1) || zone== zcnt)
    {
       sendMQTT(root_topicZoneStatus ,retval);
    }
   }
}

}

void ZoneState(int zone)
{
PanelStatus0(true,zone);
}

void ArmState()
{
PanelStatus1(true);
}

void PanelStatus1(bool ShowOnlyState)
{
byte data[MessageLength] = {};
byte checksum;
for (int x = 0; x < MessageLength; x++)
{
data[x] = 0x00;
}

serial_flush_buffer();
data[0] = 0x50;
data[1] = 0x00;
data[2] = 0x80;
data[3] = 0x01;
data[33] = 0x05;

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);

readSerialQuick();

bool Fire=bitRead(inData[17],7);
bool Audible=bitRead(inData[17],6);
bool Silent=bitRead(inData[17],5);
bool AlarmFlg=bitRead(inData[17],4);
bool StayFlg=bitRead(inData[17],2);
bool SleepFlg=bitRead(inData[17],1);
bool ArmFlg=bitRead(inData[17],0);

//sendMQTT(root_topicStatus,"Timer_Loss=" +String(inData[4]) );
String retval = "{ "Fire":"" + String(Fire) + """ +
","Audible":"" + String(Audible) + """ +
","Silent":"" + String(Silent) + """ +
","AlarmFlg":"" + String(AlarmFlg) + """ +
","StayFlg":"" + String(StayFlg) + """ +
","SleepFlg":"" + String(SleepFlg) + """ +
","ArmFlg":"" + String(ArmFlg) + ""}";

trc(retval);
if (!ShowOnlyState)
{
sendMQTT(root_topicStatus,retval);
}

 if (AlarmFlg)
{
   retval = "{ \"PanelArmStatus\":4,\"description\":\"ALARM_TRIGGERED\"}" ;
   
}
else if (StayFlg)
{
   retval = "{ \"PanelArmStatus\":0,\"description\":\"STAY_ARM\"}" ;
}else if (SleepFlg)
{
   retval = "{ \"PanelArmStatus\":2,\"description\":\"NIGHT_ARM\"}" ;
}
else if (ArmFlg)
{
   retval = "{ \"PanelArmStatus\":1,\"description\":\"AWAY_ARM\"}" ;
}
else if (!SleepFlg && !StayFlg && !ArmFlg)
{
   retval = "{ \"PanelArmStatus\":3,\"description\":\"DISARMED\"}" ;
}

else
{
   retval = "{ \"PanelArmStatus\":99,\"description\":\"unknown\"}" ;
}
sendMQTT(root_topicArmStatus,retval);

bool zoneisbypassed =bitRead(inData[18],3);
bool ParamedicAlarm=bitRead(inData[19],7);

retval = "{ "zoneisbypassed":"" + String(zoneisbypassed) + """ +
","ParamedicAlarm":"" + String(ParamedicAlarm) + ""}";

trc(retval);
if (!ShowOnlyState)
{
sendMQTT(root_topicStatus,retval);
}

}
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] = 0x05;
data[34] = 0x00;
data[35] = 0x00;

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++)
{
//Serial.print("Address-");
//Serial.print(x);
//Serial.print("=");
//Serial.println(data[x], HEX);
}
}

Serial.write(data, MessageLength);

readSerialQuick();
if (TRACE)
{
   for (int x = 0; x < MessageLength; x++)
   {
     Serial1.print("replAddress-");
     Serial1.print(x);
     Serial1.print("=");
     Serial1.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[10] = 0x00;
  data1[11] = 0x00;
  data1[13] = 0x55;
  data1[14] = pass1; //panel pc password digit 1 & 2
  data1[15] = pass2; //panel pc password digit 3 & 4
  data1[33] = 0x05;

  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++)
     {
      // Serial1.print("SendinGINITAddress-");
      // Serial1.print(x);
      // Serial1.print("=");
      // Serial1.println(data1[x], HEX);
     }
  }

  Serial.write(data1, MessageLength);
  readSerial();
  if (inData[0]==0x10  && inData[1]==0x25)
  {
    PannelConnected = true;
    trc("panel Login");
    sendMQTT(root_topicStatus, "{\"status\":\"Panel NEware direct successfull connecting\"}");
  }else
  {
    trc("Login response number0");
    trc(String(inData[0],HEX));
    trc("Login response number1");
    trc(String(inData[1],HEX));
  }
  if (TRACE)
  {
     for (int x = 0; x < MessageLength; x++)
     {
       Serial1.print("lastAddress-");
       Serial1.print(x);
       Serial1.print("=");
       Serial1.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!");
JsonParseError=true;
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)
// {
//   Serial1.print("0x");
//   Serial1.println(PanelPassword1, HEX);
//   Serial1.print("0x");
//   Serial1.println(PanelPassword2, HEX);
// }
  inPayload data1 = {PanelPassword1, PanelPassword2, CommandB, SubCommand};

  return data1;

}

return indata;
}

void serial_flush_buffer(){
while (Serial.read() >= 0)
yield();
;
}

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(Hostname, "")) {
  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("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,"{\"status\":\"Paradox Disconnected\"}")) {
// Once connected, publish an announcement...
  //client.publish(root_topicOut,"connected");
  trc("connected");
  sendMQTT(root_topicStatus, "{\"status\":\"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) {
Serial1.println(msg);
// sendMQTT(root_topicStatus,msg);
}
}

Will get back as soon as possible...

螠蔚 桅喂位喂魏慰蠉蟼 围伪喂蟻蔚蟿喂蟽渭慰蠉蟼,
韦维蟽慰蟼

from paradoxrs232tomqtt.

tasosstr avatar tasosstr commented on May 28, 2024

螢蔚蠂伪蟽伪 畏 未慰魏喂渭萎 蔚委谓伪喂 蟽蔚 SP7000 慰蟺蠈蟿蔚 尾维位蟿慰 蟽蟿畏谓 位委蟽蟿伪 蟿慰蠀 螣螝

from paradoxrs232tomqtt.

tasosstr avatar tasosstr commented on May 28, 2024

Hello Dear,

I do some cleanup :-)

#include <FS.h>
#include <SoftwareSerial.h>
#include <ESP8266WiFi.h>
#include <ESP8266mDNS.h>
#include <ESP8266SSDP.h>
#include <ESP8266WebServer.h>
#include <WiFiUdp.h>
#include <ArduinoOTA.h>
#include <DNSServer.h>
#include <PubSubClient.h>
#include <WiFiManager.h>
#include <ArduinoJson.h>

#define mqtt_server "192.168.1.230"
#define mqtt_port "1883"
#define Hostname "paradoxdCTL" //not more than 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 Hassio 1
bool TRACE = 0;

const char *root_topicOut = "paradoxdCTL/out";
const char *root_topicStatus = "paradoxdCTL/status";
const char *root_topicIn = "paradoxdCTL/in";
const char *root_topicArmStatus = "paradoxdCTL/status/Arm";
const char *root_topicZoneStatus = "paradoxdCTL/status/Zone";

WiFiClient espClient;
PubSubClient client(espClient);

bool shouldSaveConfig = false;
bool ResetConfig = false;
bool PannelConnected = false;
bool PanelError = false;
bool RunningCommand = false;
bool JsonParseError = false;

unsigned long lastReconnectAttempt = 0UL;
unsigned long ul_Interval = 5000UL;

char inData[38]; // Allocate some space for the string
byte pindex = 0; // Index into array; where to store the character

ESP8266WebServer HTTP(80);

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, OUTPUT);
blink(100);
delay(1000);
WiFi.mode(WIFI_STA);

Serial.begin(9600);
Serial.flush();

Serial1.begin(9600);
Serial1.flush(); // Clean up the serial buffer in case previous junk is there
trc("serial monitor is up");
serial_flush_buffer();

trc("Running MountFs");
mountfs();

setup_wifi();
StartSSDP();

ArduinoOTA.setHostname(Hostname);
ArduinoOTA.setPassword((const char *)"12345");
ArduinoOTA.begin();
trc("Finnished wifi setup");
delay(1500);
lastReconnectAttempt = 0;
digitalWrite(LED, HIGH);

}

void loop() {
readSerial();

if ((inData[0] & 0xF0) != 0xE0) { // re-align serial buffer
	serial_flush_buffer();
}

}

void StartSSDP()
{
if (WiFi.waitForConnectResult() == WL_CONNECTED) {

	Serial1.printf("Starting HTTP...\n");
	HTTP.on("/index.html", HTTP_GET, []() {
		HTTP.send(200, "text/plain", Hostname);
	});
	HTTP.on("/", HTTP_GET, []() {
		HTTP.send(200, "text/plain", Hostname);
	});

	HTTP.on("/description.xml", HTTP_GET, []() {
		SSDP.schema(HTTP.client());
	});
	HTTP.begin();

	Serial1.printf("Starting SSDP...\n");
	SSDP.setSchemaURL("description.xml");
	SSDP.setDeviceType("upnp:rootdevice");
	SSDP.setHTTPPort(80);
	SSDP.setName(Hostname);
	SSDP.setSerialNumber(WiFi.macAddress());
	SSDP.setURL(String("http://") + WiFi.localIP().toString().c_str() + "/index.html");
	SSDP.setModelName("ESP8266Wemos");
	SSDP.setModelNumber("WEMOSD1");
	SSDP.setModelURL("https://github.com/maragelis/ParadoxRs232toMqtt");
	SSDP.setManufacturer("PM ELECTRONICS");
	SSDP.setManufacturerURL("https://github.com/maragelis/");
	SSDP.begin();

	if (!MDNS.begin(Hostname)) {
		trc("Error setting up MDNS responder!");
		while (1) {
			delay(1000);
		}
	}
	trc("mDNS responder started");

	// Add service to MDNS-SD
	MDNS.addService("http", "tcp", 80);

	trc("Ready!\n");
}

}

bool sleepflag;
void SendJsonString(byte armstatus, byte event, byte sub_event, String dummy)
{
if (Hassio) {
char ZoneTopic[80];
char stateTopic[80];

	String zone = String(root_topicOut) + "/zone";
	zone.toCharArray(ZoneTopic, 80);

	String state_topic = String(root_topicOut) + "/state";
	state_topic.toCharArray(stateTopic, 80);

	if (event == 1 || event == 0)		{
		zone = String(ZoneTopic) + String(sub_event);
		zone.toCharArray(ZoneTopic, 80);

		String zonestatus = "OFF";

		if (event == 1)			{
			zonestatus = "ON";
		}

		sendMQTT(ZoneTopic, zonestatus);
	}
	else if (event == 2) {

		if (sub_event == 4)
			sendMQTT(stateTopic, "triggered");

		if (sub_event == 11) {
			sendMQTT(stateTopic, "disarmed");
			sleepflag = false;
		}

		if (sub_event == 12 && sleepflag == false)
			sendMQTT(stateTopic, "armed_away");
	}
	else if (event == 6) {

		if (sub_event == 3 || sub_event == 4) {
			sendMQTT(stateTopic, "armed_home");
			sleepflag = true;
		}
	}
}

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()) {
unsigned long now = millis();
if (now - lastReconnectAttempt > ul_Interval) {
lastReconnectAttempt = now;
trc("client mqtt not connected, trying to connect");
if (reconnect()) {
lastReconnectAttempt = 0UL;
}
}
}
else {
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 readSerialQuick() {
while (Serial.available()<37) {
yield();
}

readSerialData();

}

void readSerial() {
while (Serial.available()<37) {
ArduinoOTA.handle();
client.loop();
HTTP.handleClient();
yield();
}

readSerialData();

}

void readSerialData() {
pindex = 0;

while (pindex < 37) { // Paradox packet is 37 bytes 
	inData[pindex++] = Serial.read();
	yield();
}

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]);
	
	if (inData[14] != 1) 
		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, "{\"status\":\"Panel logout\"}");
	}
	else if (inData[7] == 48 && inData[8] == 2)
	{
		PannelConnected = true;
		trc("panel Login");
		sendMQTT(root_topicStatus, "{\"status\":\"Panel Login Success\"}");
	}

}

}

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) {
if (RunningCommand) {
trc("Command already Running exiting");
return;
}

trc("Hey I got a callback ");
// Conversion to a printable string
payload[length] = '\0';
inPayload data;

trc("JSON Returned! ====");
String callbackstring = String((char *)payload);
if (callbackstring == "Trace=1")
{
	TRACE = 1;
	Serial1.println("Trace is ON");
	return;
}
else if (callbackstring == "Trace=0")
{
	TRACE = 0;
	Serial1.println("Trace is OFF");
	return;
}
else if (callbackstring == "")
{
	trc("No payload data");
	return;
}
else
{
	trc("parsing Recievied Json Data");
	data = Decodejson((char *)payload);

	if (JsonParseError){
		trc("Error parsing Json Command");
		JsonParseError = false;
		return;
	}

	trc("Json Data is ok ");
	PanelError = false;
	trc("Start login");

	if (!PannelConnected)
		doLogin(data.PcPasswordFirst2Digits, data.PcPasswordSecond2Digits);
	trc("end login");

}

RunningCommand = true;
if (!PannelConnected){
	trc("Problem connecting to panel");
	sendMQTT(root_topicStatus, "{\"status\":\"Problem connecting to panel\"}");
}
else if (data.Command == 0x90)
{

	trc("Running panel status command");
	if (data.Subcommand == 0){
		PanelStatus0(false, 0);
	}

	if (data.Subcommand == 1){
		PanelStatus1(false);
	}
}
else if (data.Command == 0x91) {
	trc("Running Setdate");
	ArmState();
}
else if (data.Command == 0x92) {
	trc("Running ZoneState");
	ZoneState(data.Subcommand);
}
else if (data.Command != 0x00) {
	trc("Running Command");
	ControlPanel(data);
}
else {
	trc("Bad Command ");
	sendMQTT(root_topicStatus, "{\"status\":\"Bad Command\" }");
}

RunningCommand = false;

}

byte getPanelCommand(String data) {
byte retval = 0x00;
data.toLowerCase();
if (data == "stay" || data == "0"){
retval = Stay_Arm;
}
else if (data == "arm" || data == "1"){
retval = Full_Arm;
}
else if (data == "sleep" || data == "2"){
retval = Sleep_Arm;
}
else if (data == "disarm" || data == "3"){
retval = Disarm;
}
else if (data == "bypass" || data == "10"){
retval = Bypass;
}
else if (data == "panelstatus"){
retval = 0x90;
trc("PAnelStatus command ");
}
else if (data == "setdate"){
retval = 0x89;
}
else if (data == "armstate"){
retval = 0x91;
}
else if (data == "zonestate"){
retval = 0x92;
}
else if (data == "disconnect" || data == "99"){
retval = 0x00;
//PanelDisconnect();
}
if (TRACE){
Serial1.print("returned command = ");
Serial1.println(retval, HEX);
}
return retval;
}

byte checksumCalculate(byte checksum) {
while (checksum > 255) {
checksum = checksum - (checksum / 256) * 256;
}

return checksum & 0xFF;

}

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] = 0x05;
data[7] = 0x05;
data[8] = 0x13;
data[9] = 0x22;
data[33] = 0x05;

checksum = 0;
for (int x = 0; x < MessageLength - 1; x++){
	checksum += data[x];
}

/*while (checksum > 255){
	checksum = checksum - (checksum / 256) * 256;
}
*/

data[36] = checksumCalculate(checksum);// 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] = 0x05;
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] = checksumCalculate(checksum);// checksum & 0xFF;

while (Serial.available()>37){
	trc("serial cleanup");
	readSerial();
	yield();
}

trc("sending Data");
Serial.write(armdata, MessageLength);
readSerialQuick();

if (inData[0] >= 40 && inData[0] <= 45){
	sendMQTT(root_topicStatus, "{\"status\":\"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] = 0x05;

checksum = 0;
for (int x = 0; x < MessageLength - 1; x++){
	checksum += data[x];
}
/*
while (checksum > 255){
	checksum = checksum - (checksum / 256) * 256;
}
*/
data[36] = checksumCalculate(checksum);// checksum & 0xFF;

Serial.write(data, MessageLength);

}

void PanelStatus0(bool showonlyZone, int zone){
byte data[MessageLength] = {};
byte checksum;

for (int x = 0; x < MessageLength; x++){
	data[x] = 0x00;
}

serial_flush_buffer();
data[0] = 0x50;
data[1] = 0x00;
data[2] = 0x80;
data[3] = 0x00;
data[33] = 0x05;
checksum = 0;

for (int x = 0; x < MessageLength - 1; x++){
	checksum += data[x];
}
/*
while (checksum > 255){
	checksum = checksum - (checksum / 256) * 256;
}
*/
data[36] = checksumCalculate(checksum);// checksum & 0xFF;

Serial.write(data, MessageLength);

readSerialQuick();

bool Timer_Loss = bitRead(inData[4], 7);
bool PowerTrouble = bitRead(inData[4], 1);
bool ACFailureTroubleIndicator = bitRead(inData[6], 1);
bool NoLowBatteryTroubleIndicator = bitRead(inData[6], 0);
bool TelephoneLineTroubleIndicator = bitRead(inData[8], 0);

int ACInputDCVoltageLevel = inData[15];
int PowerSupplyDCVoltageLevel = inData[16];
int BatteryDCVoltageLevel = inData[17];

//sendMQTT(root_topicStatus,"Timer_Loss=" +String(inData[4]) );
String retval = "{ \"Timer_Loss\":\"" + String(Timer_Loss) + "\"" +
	",\"PowerTrouble\":\"" + String(PowerTrouble) + "\"" +
	",\"ACFailureTrouble\":\"" + String(ACFailureTroubleIndicator) + "\"" +
	",\"TelephoneLineTrouble\":\"" + String(TelephoneLineTroubleIndicator) + "\"" +
	",\"PSUDCVoltage\":\"" + String(PowerSupplyDCVoltageLevel) + "\"" +
	",\"BatteryDCVoltage\":\"" + String(BatteryDCVoltageLevel) + "\"" +
	",\"BatteryTrouble\":\"" + String(NoLowBatteryTroubleIndicator) + "\"}";

trc(retval);
if (!showonlyZone)
	sendMQTT(root_topicStatus, retval);

String Zonename = "";
int zcnt = 0;

for (int i = 19; i <= 22; i++){
	for (int j = 0; j < 8; j++){
		Zonename = "Z" + String(++zcnt);

		retval = "{ \"" + Zonename + "\" :\"" + bitRead(inData[i], j) + "\"}";
		trc(retval);
		if ((zone == 0 && bitRead(inData[i], j) == 1) || zone == zcnt)
			sendMQTT(root_topicZoneStatus, retval);
	}
}

}

void ZoneState(int zone){
PanelStatus0(true, zone);
}

void ArmState(){
PanelStatus1(true);
}

void PanelStatus1(bool ShowOnlyState){
byte data[MessageLength] = {};
byte checksum;

for (int x = 0; x < MessageLength; x++){
	data[x] = 0x00;
}

serial_flush_buffer();
data[0] = 0x50;
data[1] = 0x00;
data[2] = 0x80;
data[3] = 0x01;
data[33] = 0x05;

checksum = 0;
for (int x = 0; x < MessageLength - 1; x++){
	checksum += data[x];
}
/*
while (checksum > 255){
	checksum = checksum - (checksum / 256) * 256;
}
*/
data[36] = checksumCalculate(checksum);// checksum & 0xFF;

Serial.write(data, MessageLength);

readSerialQuick();

bool Fire = bitRead(inData[17], 7);
bool Audible = bitRead(inData[17], 6);
bool Silent = bitRead(inData[17], 5);
bool AlarmFlg = bitRead(inData[17], 4);
bool StayFlg = bitRead(inData[17], 2);
bool SleepFlg = bitRead(inData[17], 1);
bool ArmFlg = bitRead(inData[17], 0);


//sendMQTT(root_topicStatus,"Timer_Loss=" +String(inData[4]) );
String retval = "{ \"Fire\":\"" + String(Fire) + "\"" +
	",\"Audible\":\"" + String(Audible) + "\"" +
	",\"Silent\":\"" + String(Silent) + "\"" +
	",\"AlarmFlg\":\"" + String(AlarmFlg) + "\"" +
	",\"StayFlg\":\"" + String(StayFlg) + "\"" +
	",\"SleepFlg\":\"" + String(SleepFlg) + "\"" +
	",\"ArmFlg\":\"" + String(ArmFlg) + "\"}";

trc(retval);
if (!ShowOnlyState){
	sendMQTT(root_topicStatus, retval);
}

if (AlarmFlg){
	retval = "{ \"PanelArmStatus\":4,\"description\":\"ALARM_TRIGGERED\"}";
}
else if (StayFlg){
	retval = "{ \"PanelArmStatus\":0,\"description\":\"STAY_ARM\"}";
}
else if (SleepFlg){
	retval = "{ \"PanelArmStatus\":2,\"description\":\"NIGHT_ARM\"}";
}
else if (ArmFlg){
	retval = "{ \"PanelArmStatus\":1,\"description\":\"AWAY_ARM\"}";
}
else if (!SleepFlg && !StayFlg && !ArmFlg){
	retval = "{ \"PanelArmStatus\":3,\"description\":\"DISARMED\"}";
}

else{
	retval = "{ \"PanelArmStatus\":99,\"description\":\"unknown\"}";
}
sendMQTT(root_topicArmStatus, retval);

bool zoneisbypassed = bitRead(inData[18], 3);
bool ParamedicAlarm = bitRead(inData[19], 7);

retval = "{ \"zoneisbypassed\":\"" + String(zoneisbypassed) + "\"" +
	",\"ParamedicAlarm\":\"" + String(ParamedicAlarm) + "\"}";

trc(retval);
if (!ShowOnlyState){
	sendMQTT(root_topicStatus, retval);
}

}
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] = 0x05;
data[34] = 0x00;
data[35] = 0x00;

checksum = 0;
for (int x = 0; x < MessageLength - 1; x++){
	checksum += data[x];
}
/*
while (checksum > 255){
	checksum = checksum - (checksum / 256) * 256;
}
*/
data[36] = checksumCalculate(checksum);// checksum & 0xFF;

if (TRACE){
	for (int x = 0; x < MessageLength; x++){
		//Serial.print("Address-");
		//Serial.print(x);
		//Serial.print("=");
		//Serial.println(data[x], HEX);
	}
}

Serial.write(data, MessageLength);

readSerialQuick();

if (TRACE){
	for (int x = 0; x < MessageLength; x++){
		Serial1.print("replAddress-");
		Serial1.print(x);
		Serial1.print("=");
		Serial1.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[10] = 0x00;
data1[11] = 0x00;
data1[13] = 0x55;
data1[14] = pass1; //panel pc password digit 1 & 2
data1[15] = pass2; //panel pc password digit 3 & 4
data1[33] = 0x05;

checksum = 0;

for (int x = 0; x < MessageLength - 1; x++){
	checksum += data1[x];
}
/*
while (checksum > 255){
	checksum = checksum - (checksum / 256) * 256;
}
*/
data1[36] = checksumCalculate(checksum);// checksum & 0xFF;

if (TRACE){
	for (int x = 0; x < MessageLength; x++){
		// Serial1.print("SendinGINITAddress-");
		// Serial1.print(x);
		// Serial1.print("=");
		// Serial1.println(data1[x], HEX);
	}
}

Serial.write(data1, MessageLength);
readSerial();

if (inData[0] == 0x10 && inData[1] == 0x25){
	PannelConnected = true;
	trc("panel Login");
	sendMQTT(root_topicStatus, "{\"status\":\"Panel NEware direct successfull connecting\"}");
}
else{
	trc("Login response number0");
	trc(String(inData[0], HEX));
	trc("Login response number1");
	trc(String(inData[1], HEX));
}

if (TRACE){
	for (int x = 0; x < MessageLength; x++){
		Serial1.print("lastAddress-");
		Serial1.print(x);
		Serial1.print("=");
		Serial1.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!");
	JsonParseError = true;
	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)
	// {
	//   Serial1.print("0x");
	//   Serial1.println(PanelPassword1, HEX);
	//   Serial1.print("0x");
	//   Serial1.println(PanelPassword2, HEX);
	// }
	inPayload data1 = { PanelPassword1, PanelPassword2, CommandB, SubCommand };

	return data1;
}

return indata;

}

void serial_flush_buffer() {
while (Serial.read() >= 0)
yield();
;
}

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(Hostname, "")) {
	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("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() {
while (!client.connected()) {
trc("Attempting MQTT connection...");
String mqname = WiFi.macAddress();
char charBuf[50];
mqname.toCharArray(charBuf, 50);

	//if (client.connect("433toMQTTto433", mqtt_user, mqtt_password)) {
	if (client.connect(charBuf, root_topicStatus, 0, false, "{\"status\":\"Paradox Disconnected\"}")) {
		trc("connected");
		sendMQTT(root_topicStatus, "{\"status\":\"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");
		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");
		trc("Formatted Spiffs");
	}
}
else {
	trc("failed to mount FS");
}

}

void trc(String msg) {
if (TRACE) {
Serial1.println(msg);
// sendMQTT(root_topicStatus,msg);
}
}

Because you use the checksum in many sub routines i have done a function.

Tested and all ok 馃憤

Thank you dear Panos 馃憤

It is possible to check - control the PGM functions ?

PS. I thing the ArduinoOTA.handle(); should be disable and activated or by a MQTT command like the Trace=1 or at startup (or when press a button ...), i said this because i was looking for OTA and everyone they have with flag checking so this working only at upload.

What do you thing ?

Best Regard's ,
Tasos

from paradoxrs232tomqtt.

tasosstr avatar tasosstr commented on May 28, 2024

Hello Dear Panos,

You are PERFECT ! ! !

Thank you ! ! !

Best Regards,
Tasos

from paradoxrs232tomqtt.

Related Issues (20)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    馃枛 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 馃搳馃搱馃帀

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google 鉂わ笍 Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.