Control Relay by MQTT Publish Subcribe - c++

sorry for my bad english, but i'll try my best
i have a code like this
void mqttCallback(char *topic, byte *payload, unsigned int length)
{
Serial.print("Message arrived [");
Serial.print(topic);
Serial.print("] ");
for (int i = 0; i < length; i++)
{
Serial.print((char)payload[i]);
}
Serial.println();
if (strcmp(topic, DeviceConfig.MqttSub) == 0)
{
Serial.print("Recvd relay command parse code: ");
StaticJsonDocument<100> doc;
DeserializationError error = deserializeJson(doc, (char *)payload);
Serial.println(error.code());
if (error == DeserializationError::Ok)
{
if (doc.containsKey("state") && doc["state"].is<int>())
{
DeviceConfig.RelayOn = (doc["state"].as<int>() == 1);
Serial.print("Changing state: ");
Serial.print(DeviceConfig.RelayOn );
Serial.println();
}
}
}
}
it means if the broker send data like {state : 1}, it automactically changing state turn on, or {state : 0} to turn off, it works if i see on serial monitor, the state status is changed, but the relay is not affected at all
this is the loop function
void loop()
{
mqttReconnect();
if (client.connected() && millis() - lastSendMs >= (DeviceConfig.MqttPubSec * 1000))
{
Serial.print("Publishing:");
String json = composeSensorJson();
Serial.println(json);
Serial.println(client.publish(DeviceConfig.MqttPub, json.c_str()) ? "OK" : "FAIL");
lastSendMs = millis();
}
if (DeviceConfig.Device == Relay) {
digitalWrite(AIO_SENSOR_PIN_3, DeviceConfig.RelayOn ? LOW : HIGH);
}
client.loop();
}
why the relay is not working
this is the serial monitor if the state is 1
and this is the monitor if state is 0

Related

Is it possible to make a sip call over gprs with a SIM800 module?

I have an Asterisk server on cloud and I want ESP32 devices to register as SIP clients and make a VoIP call over GPRS via SIM800 module. AT commands of SIM800 module allows me to make a GPRS connection and I can send http request and send MQTT messages. However, I couldn't find a way to connect to VoIP server, if possible.
My current code establises MQTT connection over GPRS and make calls over GSM but cannot connect to Asterisk:
// ESP32 Configuration
#define TINY_GSM_MODEM_SIM800
#define SerialMon Serial
#define SerialAT Serial2
#define TINY_GSM_DEBUG SerialMon
#define GSM_AUTOBAUD_MIN 9600 /
#define GSM_AUTOBAUD_MAX 38400
#define TINY_GSM_USE_GPRS true
#define PhoneNumber "xxxxxxxxxxxxxxx"
#define rcSwitchInterruptPin 35
#define ENABLE_SIM800C 22
#define BUTTON_PIN 33
#define SOS_BUTTON_ID0 4236140
#define SOS_BUTTON_ID1 4236132
#define SOS_BUTTON_PIN 27
// GPRS internet settings, specific to your SIM card
const char apn[] = "internet";
const char gprsUser[] = "";
const char gprsPass[] = "";
// MQTT settings
const char *broker = "broker.emqx.io";
const int mqttPort = 1883;
const char * clientID = "esp32-client";
const char * mqttUser = "acido";
const char * mqttPassword = "12345678";
#include <TinyGsmClient.h>
#include <PubSubClient.h>
#include <SPI.h>
#include <Wire.h>
#include <PubSubClient.h>
#include <elapsedMillis.h>
#include <RCSwitch.h>
RCSwitch mySwitch = RCSwitch();
TinyGsm modem(SerialAT);
TinyGsmClient client(modem);
PubSubClient mqtt(client);
uint32_t lastReconnectAttempt = 0;
void mqttCallback(char *, byte *, unsigned int);
boolean mqttConnect();
void DRE_switch();
elapsedSeconds serialLogSeconds;
unsigned int serialLog_Interval = 3;
elapsedSeconds sinyalBekletme;
unsigned int sinyalBekletme_Interval = 3;
elapsedSeconds sosDelay;
unsigned int sosDelay_Interval = 3;
elapsedSeconds kapiacikDelay;
unsigned int kapiacikDelay_Interval = 3;
elapsedSeconds kapiKapaliDelay;
unsigned int kapiKapaliDelay_Interval = 3;
elapsedSeconds gazDelay;
unsigned int gazDelay_Interval = 3;
elapsedSeconds pirDelay;
unsigned int pirDelay_Interval = 3;
elapsedSeconds dumanDelay;
unsigned int dumanDelay_Interval = 3;
void setup()
{
mqtt.setKeepAlive(60);
// Set console baud rate
SerialMon.begin(9600);
while (!SerialMon)
delay(10);
// !!!!!!!!!!!
mySwitch.enableReceive(35);
pinMode(BUTTON_PIN, INPUT_PULLDOWN);
pinMode(ENABLE_SIM800C, OUTPUT);
digitalWrite(ENABLE_SIM800C, HIGH);
delay(3000);
digitalWrite(ENABLE_SIM800C, LOW);
// !!!!!!!!!!!
TinyGsmAutoBaud(SerialAT, GSM_AUTOBAUD_MIN, GSM_AUTOBAUD_MAX);
delay(6000);
// Restart takes quite some time
// To skip it, call init() instead of restart()
// if (!modem.restart()) {
if (!modem.init()) {
DBG("Failed to restart modem, delaying 10s and retrying");
// restart autobaud in case GSM just rebooted
TinyGsmAutoBaud(SerialAT, GSM_AUTOBAUD_MIN, GSM_AUTOBAUD_MAX);
return;
}
String modemInfo = modem.getModemInfo();
SerialMon.print("setup: Modem Info: ");
SerialMon.println(modemInfo);
SerialMon.print("setup: Waiting for network...");
if (!modem.waitForNetwork())
{
SerialMon.println("setup: fail, wait 5 seconds");
delay(5000);
return;
}
SerialMon.println("setup: success");
if (modem.isNetworkConnected())
SerialMon.println("setup: Network connected");
#if TINY_GSM_USE_GPRS
// GPRS connection parameters are usually set after network registration
SerialMon.print(F("setup: Connecting to apn: "));
SerialMon.print(apn);
if (!modem.gprsConnect(apn, gprsUser, gprsPass))
{
SerialMon.println("setup: GPRS Connecting fail, wait 5 seconds");
delay(5000);
return;
}
SerialMon.println("setup: GPRS success");
if (modem.isGprsConnected())
{
SerialMon.println("setup: GPRS connected");
}
#endif
// MQTT Broker setup
mqtt.setServer(broker, mqttPort);
mqtt.setCallback(mqttCallback);
}
void loop()
{
bool result;
// check if we're connected to network
if (!modem.isNetworkConnected())
{
SerialMon.println("loop: modem disconnected");
if (!modem.waitForNetwork(180000L, true))
{
SerialMon.println("loop: modem fail, wait 10 sec");
delay(10000);
return;
}
if (modem.isNetworkConnected())
{
SerialMon.println("loop: Modem re-connected");
}
// And make sure GPRS/EPS is still connected
if (!modem.isGprsConnected())
{
SerialMon.println("loop: GPRS disconnected!");
SerialMon.print(F("loop: Connecting to apn:"));
SerialMon.print(apn);
if (!modem.gprsConnect(apn, gprsUser, gprsPass))
{
SerialMon.println("loop: GPRS fail, wait 10 sec");
delay(10000);
return;
}
if (modem.isGprsConnected())
{
SerialMon.println("loop: GPRS reconnected");
}
}
}
// check if we're connected to MQTT
if (!mqtt.connected())
{
SerialMon.println("loop: === mqtt not connected ===");
// Reconnect every 10 seconds
uint32_t t = millis();
if (t - lastReconnectAttempt > 10000L)
{
lastReconnectAttempt = t;
if (mqttConnect())
{
lastReconnectAttempt = 0;
}
}
return;
}
if (digitalRead(BUTTON_PIN) == HIGH)
{
Serial.println("BUTONA BASILDI");
result = modem.callNumber(PhoneNumber);
DBG("Call:", result ? "OK" : "fail");
}
// Check RF signals and publish to MQTT
if (mySwitch.available())
{
int num = mySwitch.getReceivedValue();
Serial.print("Num: ");
Serial.print(num);
Serial.print(" Protocol: ");
Serial.println(mySwitch.getReceivedProtocol());
if (sosDelay >= sosDelay_Interval)
{
if (num == 4236132) // SOS
{
Serial.println("SOS Butonuna Basıldı.");
DRE_switch();
mqtt.publish("CMR/ESP32s/SENSOR/SOS", "SOS"); // Publish message.
result = modem.callNumber(PhoneNumber);
DBG("Call:", result ? "OK" : "fail");
}
else
{
mqtt.publish("CMR/ESP32s/SENSOR/SOS", "0"); // Publish message.
}
sosDelay = 0;
}
if (pirDelay >= pirDelay_Interval)
{
if (num == 8330345)
{
DRE_switch();
Serial.println("HAREKET ALGILANDI.");
mqtt.publish("CMR/ESP32s/SENSOR/PIR", "HAREKET ALGILANDI"); // Publish message.
}
else
{
mqtt.publish("CMR/ESP32s/SENSOR/PIR", "0"); // Publish message
}
pirDelay = 0;
}
if (kapiacikDelay >= kapiacikDelay_Interval)
{
if (num == 5729285) // Kapi acilinca gelen sinyal
{
DRE_switch();
Serial.println("KAPI AÇILDI.");
mqtt.publish("CMR/ESP32s/SENSOR/KAPIACIK", "1"); // Publish message.
}
else
{
mqtt.publish("CMR/ESP32s/SENSOR/KAPIACIK", "0"); // Publish message
}
kapiacikDelay = 0;
}
if (kapiKapaliDelay >= kapiKapaliDelay_Interval)
{
if (num == 5729294) // Kapi kapaninca gelen sinyal
{
DRE_switch();
Serial.println("KAPI KAPANDI.");
mqtt.publish("CMR/ESP32s/SENSOR/KAPIKAPALI", "1"); // Publish message.
}
else
{
mqtt.publish("CMR/ESP32s/SENSOR/KAPIKAPALI", "0"); // Publish message
}
kapiKapaliDelay = 0;
}
if (gazDelay >= gazDelay_Interval)
{
if (num == 12607491)
{
DRE_switch();
Serial.println("Gas Algılandı.");
mqtt.publish("CMR/ESP32s/SENSOR/GAS", "GAS ALGILANDI"); // Publish message.
}
else
{
mqtt.publish("CMR/ESP32s/SENSOR/GAS", "0"); // Publish message
}
gazDelay = 0;
}
if (dumanDelay >= dumanDelay_Interval)
{
if (num == 79974)
{
DRE_switch();
Serial.println("Duman Algılandı .");
mqtt.publish("CMR/ESP32s/SENSOR/DUMAN", "DUMAN ALGILANDI"); // Publish message.
}
else
{
mqtt.publish("CMR/ESP32s/SENSOR/DUMAN", "0"); // Publish message
}
dumanDelay = 0;
}
} // end if mySwitch.available
modem.maintain();
mqtt.loop(); // Handling MQTT on the background.
} // end of loop
boolean mqttConnect()
{
// Connect to MQTT Broker
SerialMon.print("mqttConnect: MQTT trying to connect: ");
SerialMon.print(broker);
// Connect to MQTT Broker with password protected
boolean status = mqtt.connect(clientID, mqttUser, mqttPassword);
// boolean status = mqtt.connect(clientID); // without password
if (status == false)
{
SerialMon.println("mqttConnect: MQTT Connection Fail");
return false;
}
SerialMon.println("mqttConnect: *** MQTT CONNECTED *** ");
mqtt.publish("topic/akes", "Client connection started");
mqtt.subscribe("topic/akes"); // subscribe to topic
return mqtt.connected();
}
void mqttCallback(char *topic, byte *payload, unsigned int len)
{
// Handle message arrived
SerialMon.print("mqttCallback: Message arrived [");
SerialMon.print(topic);
SerialMon.print("]: ");
SerialMon.write(payload, len);
SerialMon.println();
}
void DRE_switch()
{
// Disable Reset Enable function for RF module
mySwitch.disableReceive();
mySwitch.resetAvailable();
mySwitch.enableReceive(rcSwitchInterruptPin);
}

3x Arduino + ESP32 with ESP-NOW

The configuration on "machine" looks like this:
Computer with custom app WPF C#, have connected ESP32-sender.
On other side of room there is ESP32 as recaiver that have connected to it 3 arduino due, that controls a lot of stepper motors.
My problem is, that if I send a single command all works great. Directly on other side it executes.
The problem starts when there is a lot of commands to send. ESP32 starts to makes Delivery fail status and after that moment all further commands are lost.
That's the code of Master-ESP connected to PC.
Which arduino to send is decide by one of the symbols on begin of message "!,#,#"
#include <esp_now.h>
#include <WiFi.h>
#include <Wire.h>
uint8_t broadcastAddress[] = {0x94, 0xB9, 0x7E, 0xD0, 0x93, 0x64};
String inMess;
typedef struct Message {
char a[100];
} Message;
// Variable to store if sending data was successful
String success;
Message message;
Message send_message;
esp_now_peer_info_t peerInfo;
char incoming;
String full = "";
bool text_done = false;
bool sended = false;
// Callback when data is sent
void OnDataSent(const uint8_t *mac_addr, esp_now_send_status_t status) {
//Serial.println(status == ESP_NOW_SEND_SUCCESS ? "Delivery Success*" : "Delivery Fail*");
if (status ==0){
success = "Delivery Success :)";
text_done = false;
full = "";
sended = false;
}
else{
success = "Delivery Fail :(";
delay(10);
sended = false;
Serial.println(success);
}
}
// Callback when data is received
void OnDataRecv(const uint8_t * mac, const uint8_t *incomingData, int len) {
memcpy(&message, incomingData, sizeof(message));
Serial.println(message.a);
}
void setup() {
// Init Serial Monitor
Serial.begin(115200);
// Set device as a Wi-Fi Station
WiFi.mode(WIFI_STA);
Serial.println(WiFi.macAddress());
// Init ESP-NOW
if (esp_now_init() != ESP_OK) {
Serial.println("Error initializing ESP-NOW");
return;
}
esp_now_register_send_cb(OnDataSent);
// Register peer
memcpy(peerInfo.peer_addr, broadcastAddress, 6);
peerInfo.channel = 0;
peerInfo.encrypt = false;
// Add peer
if (esp_now_add_peer(&peerInfo) != ESP_OK){
Serial.println("Failed to add peer");
return;
}
esp_now_register_recv_cb(OnDataRecv);
}
void loop() {
if(Serial.available() > 0 && !text_done){
incoming = Serial.read();
if(incoming == '\n'){
text_done = true;
full.trim();
full.toUpperCase();
}
if(text_done == false){
full += incoming;
}
}
if(text_done){
if(full[0] != '!' && full[0] != '#' && full[0] != '#'){ //check if text is worth sending to other esp
text_done = false;
full = "";
}
}
if(text_done){
if(!sended){
full.toCharArray(send_message.a,sizeof(send_message));
esp_err_t result = esp_now_send(broadcastAddress, (uint8_t *) &send_message, sizeof(send_message));
if (result == ESP_OK) {
//Serial.println("Sent success*");
sended = true;
}
else {
Serial.println("Error sending*");
delay(10);
}
}
}
}
That's the code of recaiver ESP
#include <esp_now.h>
#include <WiFi.h>
#include <SoftwareSerial.h>
#include <Wire.h>
SoftwareSerial worker;
SoftwareSerial tool;
//Serial2 is Table, software serials are others
uint8_t broadcastAddress[] = {0x7C, 0x9E, 0xBD, 0x4B, 0x47, 0xA4};
String outMess;
String outMessTable;
String outMessTool;
String inMess;
typedef struct Message {
char a[100];
} Message;
String success;
Message message;
Message send_message;
bool sended = true;
String again_message = "";
esp_now_peer_info_t peerInfo;
void OnDataSent(const uint8_t *mac_addr, esp_now_send_status_t status) {
//Serial.println(status == ESP_NOW_SEND_SUCCESS ? "Delivery Success" : "Delivery Fail");
if (status == 0) {
success = "Delivery Success :)";
sended = true;
again_message = "";
}
else {
success = "Delivery Fail :(";
sended = false;
delay(5);
}
}
void OnDataRecv(const uint8_t * mac, const uint8_t *incomingData, int len) {
memcpy(&message, incomingData, sizeof(message));
Serial.println(message.a);
sendTo((String)message.a);
}
void setup() {
// Init Serial Monitor
Serial.begin(115200);
Serial2.begin(115200, SERIAL_8N1, 16, 17);
//rx tx
worker.begin(57600, SWSERIAL_8N1, 25, 26, false);
if (!worker) {
Serial.println("Invalid SoftwareSerial pin configuration, check config");
while (1) {
delay (1000);
}
}
//rx tx
tool.begin(57600, SWSERIAL_8N1, 32, 33, false);
if (!tool) {
Serial.println("Invalid SoftwareSerial pin configuration, check config");
while (1) {
delay (1000);
}
}
// Set device as a Wi-Fi Station
WiFi.mode(WIFI_STA);
Serial.println(WiFi.macAddress());
// Init ESP-NOW
if (esp_now_init() != ESP_OK) {
Serial.println("Error initializing ESP-NOW");
return;
}
// Once ESPNow is successfully Init, we will register for Send CB to
// get the status of Trasnmitted packet
esp_now_register_send_cb(OnDataSent);
// Register peer
memcpy(peerInfo.peer_addr, broadcastAddress, 6);
peerInfo.channel = 0;
peerInfo.encrypt = false;
// Add peer
if (esp_now_add_peer(&peerInfo) != ESP_OK) {
Serial.println("Failed to add peer");
return;
}
// Register for a callback function that will be called when data is received
esp_now_register_recv_cb(OnDataRecv);
}
void loop() {
// Set values to send
if(sended){
if (worker.available() > 0) {//!
char t = worker.read();
if(t == '\n'){
outMess.trim();
sendToEsp(outMess,"!");
outMess = "";
}
else{
outMess += t;
}
}
}else{
if(again_message.length()>0){
delay(10);
sendToEsp(again_message.substring(1),again_message.substring(0,1));
}else{
sended = true;
}
}
if(sended){
if (tool.available() > 0) {//#
char t = tool.read();
if(t == '\n'){
outMessTool.trim();
sendToEsp(outMessTool,"#");
outMessTool = "";
}
else{
outMessTool += t;
}
}
}else{
if(again_message.length()>0){
delay(10);
sendToEsp(again_message.substring(1),again_message.substring(0,1));
}else{
sended = true;
}
}
if(sended){
if (Serial2.available() > 0) { //#
char t = Serial2.read();
if(t == '\n'){
outMessTable.trim();
sendToEsp(outMessTable,"#");
outMessTable = "";
}else{
outMessTable += t;
}
}
}else{
if(again_message.length()>0){
delay(10);
sendToEsp(again_message.substring(1),again_message.substring(0,1));
}else{
sended = true;
}
}
if(Serial.available() > 0){
outMess = Serial.readStringUntil('\n'); //read command from pc
outMess.trim(); // remove uneccesery spaces
sendTo(outMess);
}
}
void sendToEsp(String text, String which){
String mess = which + text;
again_message = mess;
mess.toCharArray(send_message.a,sizeof(send_message));
esp_err_t result = esp_now_send(broadcastAddress, (uint8_t *) &send_message, sizeof(send_message));
if (result == ESP_OK) {
// Serial.println("Sent with success");
}
else {
Serial.println("Error sending the data");
sended = true;
again_message = "";
}
}
void sendTo(String outMess){
Serial.print("=");
Serial.print(outMess);
if(outMess[0] == '!'){ //worker
worker.enableTx(true);
worker.println(outMess.substring(1));
worker.enableTx(false);
Serial.println("send to worker");
}
if(outMess[0] == '#') {//table
Serial2.println(outMess.substring(1));
Serial.println("send to table");
}
if(outMess[0] == '#'){ //tool
tool.enableTx(true);
tool.println(outMess.substring(1));
tool.enableTx(false);
Serial.println("send to tool");
}
}
If I send one message with a delay of writing next one by hand it works great.
If the message is sended via c# very fast, esp32 is handling first few of them then losing on sending or recaiving, sometimes both of esp32 sometimes only one.
How could I prevent that to make stable connection ?

GSM MQTT+CMT(SMS Reading)

I'm working a code to pubsub over GSM SIM800L and ARDUINO MEGA.
I'm able to workout MQTT fine, using ElementzOnline / SIM800_MQTT code.
I'm now having trouble to use MQTT alongside SMSReading (+CMT) and Call Receiving. I've made a RecSMS() to receive incoming messages, and it works fine as long as TCP Connection is not true, The problem is: Once TCP/MQTT is connected, my RecSMS Function displays no more sms to Serial and calls can not be received
This is Call Receiving, which is handled via RingPing....
void GSM_MQTT::receivecall(){
HangUp=1;
if(MQTT.TCP_Flag==true){disconnect();}
delay(1000);
SIMSerial.write("AT+CGATT=0\n");
delay(1000);
//SIMSerial.write("AT+CIPSHUT\n");
modemStatus=0;
SIMSerial.write("ATA\n");SIMSerial.write(26);Monitor("Incomig Call");
}
void GSM_MQTT::endcall(){if(HangUp==1){HangUp=0;SIMSerial.write("ATH\n");SIMSerial.write(26);Monitor("Call Ended");}}
This is RecSMS():
char inchar4;char inchar3;char inchar2;char inchar1;int times=0;
void RecSMS(char data){
if(times==3){inchar4=data;times++;}
if(times==2){inchar3=data;times++;}
if(times==1){inchar2=data;times++;}
if(times==0){inchar1=data;times++;}
if(times>=4){
inchar1=inchar2;inchar2=inchar3;inchar3=inchar4;inchar4=data;
if((inchar1== '+') && (inchar2== 'C')&&(inchar3== 'M')&&(inchar4== 'T')){RcvdConf = 1;}
if(RcvdConf == 1){
if(data == '\n'){RcvdEnd++;}
if(RcvdEnd == 3){RcvdEnd = 0;}
RcvdMsg[count] = data;
count++;
if(RcvdEnd == 2){RcvdConf = 0;MsgLength = count-2;count= 0;}
if(RcvdConf == 0){
Serial.print("Mobile Number is: ");
for(int x = 4;x < 18;x++){MsgMob[x-4] = RcvdMsg[x];Serial.print(MsgMob[x-4]);}
Serial.println();
Serial.print("Message Text: ");
for(int x = 47; x < MsgLength; x++){MsgTxt[x-47] = RcvdMsg[x];Serial.print(MsgTxt[x-47]);}
Serial.println();
char RcvdMsg[200] = "";int RcvdConf = 0;int count = 0;int RcvdEnd = 0;char MsgMob[15];char MsgTxt[50];int MsgLength = 0;
}
}
}
}
SerialEvent() is called every second...
void serialEvent(){
while(Serial3.available()){
char inChar=(char)Serial3.read();
RecSMS(inChar);//<////////////////////////sms reading
if(MQTT.TCP_Flag==false){
if(MQTT.index<200){MQTT.inputString[MQTT.index++]=inChar;}
if(inChar=='\n'){
MQTT.inputString[MQTT.index]=0;stringComplete=true;Serial.print(MQTT.inputString);
if(strstr(MQTT.inputString,MQTT.reply)!=NULL){
MQTT.GSM_ReplyFlag=1;
if(strstr(MQTT.inputString," INITIAL")!=0){MQTT.GSM_ReplyFlag=2;}
else if(strstr(MQTT.inputString," START")!=0){MQTT.GSM_ReplyFlag=3;}
else if(strstr(MQTT.inputString," IP CONFIG")!=0){_delay_us(10);MQTT.GSM_ReplyFlag=4;}
else if(strstr(MQTT.inputString," GPRSACT")!=0){MQTT.GSM_ReplyFlag=4;}
else if((strstr(MQTT.inputString," STATUS")!=0)||(strstr(MQTT.inputString,"TCP CLOSED")!=0)){MQTT.GSM_ReplyFlag=5;}
else if(strstr(MQTT.inputString," TCP CONNECTING")!=0){MQTT.GSM_ReplyFlag=6;}
else if((strstr(MQTT.inputString," CONNECT OK")!=0)||(strstr(MQTT.inputString,"CONNECT FAIL")!=NULL)||(strstr(MQTT.inputString,"PDP DEACT")!=0)){MQTT.GSM_ReplyFlag=7;}}
else if(strstr(MQTT.inputString,"OK")!=NULL){GSM_Response=1;}
else if(strstr(MQTT.inputString,"ERROR")!=NULL){GSM_Response=2;}
else if(strstr(MQTT.inputString,".")!= NULL){GSM_Response=3;}
else if(strstr(MQTT.inputString,"CONNECT FAIL")!=NULL){GSM_Response=5;}
else if(strstr(MQTT.inputString,"CONNECT")!=NULL){GSM_Response=4;MQTT.TCP_Flag=true;MQTT.AutoConnect();MQTT.pingFlag=true;MQTT.tcpATerrorcount=0;Serial.println("MQTT.TCP_Flag=True");}
else if(strstr(MQTT.inputString,"CLOSED")!=NULL){GSM_Response=4;MQTT.TCP_Flag=false;MQTT.MQTT_Flag=false;Serial.println("TCP_Flag=False");}
MQTT.index=0;MQTT.inputString[0]=0;
}
}else{
uint8_t ReceivedMessageType=(inChar/16) & 0x0F;uint8_t DUP=(inChar & DUP_Mask)/DUP_Mask;
uint8_t QoS=(inChar & QoS_Mask)/QoS_Scale;uint8_t RETAIN=(inChar & RETAIN_Mask);
if((ReceivedMessageType>=CONNECT)&&(ReceivedMessageType<=DISCONNECT)){
bool NextLengthByte=true;MQTT.length=0;MQTT.lengthLocal=0;uint32_t multiplier=1;delay(2);char Cchar=inChar;
while((NextLengthByte==true)&&(MQTT.TCP_Flag==true)){
if(Serial3.available()){
inChar=(char)Serial3.read();/*Serial.println(inChar, DEC);*/
if(((((Cchar & 0xFF)=='C')&&((inChar & 0xFF)=='L'))||(((Cchar & 0xFF)=='+')&&((inChar & 0xFF)=='P')))&&(MQTT.length==0)){
MQTT.index=0;MQTT.inputString[MQTT.index++]=Cchar;MQTT.inputString[MQTT.index++]=inChar;
MQTT.TCP_Flag=false;MQTT.MQTT_Flag=false;MQTT.pingFlag=false;Serial.println("Disconnecting");
Serial.println("MQTT.TCP_Flag=False (ln223)");
}else{
if((inChar&128)==128){MQTT.length+=(inChar&127)*multiplier;multiplier*=128;Serial.println("More");}
else{NextLengthByte=false;MQTT.length+=(inChar&127)*multiplier;multiplier*=128;}
}
}
}
MQTT.lengthLocal=MQTT.length;/*Serial.println(MQTT.length);*/
if(MQTT.TCP_Flag==true){
MQTT.printMessageType(ReceivedMessageType);MQTT.index=0L;uint32_t a=0;
while((MQTT.length-- > 0)&&(Serial3.available())){MQTT.inputString[uint32_t(MQTT.index++)]=(char)Serial3.read();delay(1);}
/*Serial.println(" ");*/
if (ReceivedMessageType==CONNACK){
MQTT.ConnectionAcknowledgement=MQTT.inputString[0]*256+MQTT.inputString[1];
if(MQTT.ConnectionAcknowledgement==0){MQTT.MQTT_Flag=true;MQTT.OnConnect();}
MQTT.printConnectAck(MQTT.ConnectionAcknowledgement); /*MQTT.OnConnect();*/
}else if(ReceivedMessageType==PUBLISH){
uint32_t TopicLength=(MQTT.inputString[0])*256+(MQTT.inputString[1]);Serial.print("Topic: '");MQTT.PublishIndex = 0;
for(uint32_t iter=2;iter<TopicLength+2;iter++){Serial.print(MQTT.inputString[iter]);MQTT.Topic[MQTT.PublishIndex++]=MQTT.inputString[iter];}
MQTT.Topic[MQTT.PublishIndex]=0;Serial.print("' Message: '");
MQTT.TopicLength=MQTT.PublishIndex;MQTT.PublishIndex=0;uint32_t MessageSTART=TopicLength+2UL;int MessageID=0;
if(QoS!=0){MessageSTART+=2;MessageID=MQTT.inputString[TopicLength+2UL]*256+MQTT.inputString[TopicLength+3UL];}
for(uint32_t iter=(MessageSTART);iter<(MQTT.lengthLocal);iter++){Serial.print(MQTT.inputString[iter]);MQTT.Message[MQTT.PublishIndex++]=MQTT.inputString[iter];}
MQTT.Message[MQTT.PublishIndex]=0;Serial.println("'");MQTT.MessageLength=MQTT.PublishIndex;
if(QoS==1){MQTT.publishACK(MessageID);}else if(QoS==2){MQTT.publishREC(MessageID);}
MQTT.OnMessage(MQTT.Topic,MQTT.TopicLength,MQTT.Message,MQTT.MessageLength);MQTT.MessageFlag=true;
}else if(ReceivedMessageType==PUBREC){MQTT.publishREL(0,MQTT.inputString[0]*256+MQTT.inputString[1]);
int MessageID=MQTT.inputString[0]*256+MQTT.inputString[1];
}else if(ReceivedMessageType==PUBREL){MQTT.publishCOMP(MQTT.inputString[0]*256+MQTT.inputString[1]);
int MessageID=MQTT.inputString[0]*256+MQTT.inputString[1];
}else if((ReceivedMessageType==PUBACK)||(ReceivedMessageType==PUBCOMP)||(ReceivedMessageType==SUBACK)||(ReceivedMessageType==UNSUBACK)){
int MessageID=MQTT.inputString[0]*256+MQTT.inputString[1];
}else if(ReceivedMessageType==PINGREQ){
MQTT.TCP_Flag=false;MQTT.pingFlag=false;MQTT.sendATreply("AT+CIPSHUT\r\n",".",4000);MQTT.modemStatus=0;
Serial.println("Disconnecting");Serial.println("MQTT.TCP_Flag=False (ln261)");
}
}
}else if((inChar==13)||(inChar==10)){Serial.print("inChar=13||10");}else{Serial.print("Received: Unknown Message Type: ");Serial.println(inChar);}
}
}
}
My Code is published at pedromancuso/GSM_MQTT.
Suggestions?

Connecting an Arduino ESP32 microcontroller to javafx via PacketSender

We have built a drone controller using C++ and an Arduino ESP32 module. We have achieved connection to a Tello Drone and can control it successfully. However, now we want to connect our controller to a javafx program that receives input and then draws on a canvas in scene builder.
Meanwhile the problem is that we can't seem to connect our controller through PacketSender. We have attached our code, including the previous built that enabled connection with a drone.
The big question is how to send the messages between two programs and initiate our virtual depiction of our drone on a canvas - instead of the actual physical one.
The issue seems to be in case 1, line 190, where we connected controller to actual drone, but now have to write up a new connection somehow.
#include <Arduino.h>
#include "WiFi.h"
#include "AsyncUDP.h"
const char * ssid = "OnePlus 7 Pro";
const char * password = "hej12345";
//Connect button variables (Command)
int inPinLand = 18;
int valLand = 0;
//Ultra sonic sensor variables
#define trigPin 2
#define echoPin 21
//Land button variables (Land)
int inPin = 25;
int val = 0;
//Instantiate specific drone
const char * networkName = "TELLO-59F484";
const char * networkPswd = "";
//IP address to send UDP data to:
// either use the ip address of the server or
// a network broadcast address
const char * udpAddress = "10.60.0.227";
const int udpPort = 7000;
boolean connected = false;
char fromTello[256];
unsigned long timer;
//static const byte glyph[] = { B00010000, B00110100, B00110000, B00110100, B00010000 };
//static PCD8544 lcd;
uint8_t state = 0;
//Controller movement variables
int pitch = 0;
int roll = 0;
int yaw = 0;
int throttle = 0;
char cmd[256];
AsyncUDP udp;
void setup() {
Serial.begin(9600);
WiFi.mode(WIFI_STA);
WiFi.begin(ssid, password);
if (WiFi.waitForConnectResult() != WL_CONNECTED) {
Serial.println("WiFi Failed");
while (1) {
delay(1000);
}
}
pinMode(5, OUTPUT);
digitalWrite(5, HIGH);
pinMode(trigPin, OUTPUT);
pinMode(echoPin, INPUT);
pinMode(inPin, INPUT);
pinMode(inPinLand, INPUT);
//LCD screen initialization
//lcd.begin(84, 48);
Serial.begin(9600);
//pinMode(trigPin, OUTPUT);
//pinMode(echoPin, INPUT);
//pinMode(BL, OUTPUT);
//digitalWrite(BL, HIGH);
if (udp.listen(7000)) {
Serial.print("UDP Listening on IP: ");
Serial.println(WiFi.localIP());
udp.onPacket([](AsyncUDPPacket packet) {
Serial.print("UDP Packet Type: ");
Serial.print(packet.isBroadcast()
? "Broadcast"
: packet.isMulticast() ? "Multicast" : "Unicast");
Serial.print(", From: ");
Serial.print(packet.remoteIP());
Serial.print(":");
Serial.print(packet.remotePort());
Serial.print(", To: ");
Serial.print(packet.localIP());
Serial.print(":");
Serial.print(packet.localPort());
Serial.print(", Length: ");
Serial.print(packet.length());
Serial.print(", Data: ");
Serial.write(packet.data(), packet.length());
Serial.println();
// reply to the client/sender
packet.printf("Got %u bytes of data", packet.length());
});
}
// Send unicast
// udp.print("Hello Server!");
// udp.
}
//WiFi connection function
void connectToWiFi(const char * ssid, const char * pwd) {
Serial.println("Connecting to WiFi network: " + String(ssid));
// delete old config
WiFi.disconnect(true);
//Initiate connection
WiFi.begin(ssid, pwd);
Serial.println("Waiting for WIFI connection...");
}
//Drone connection function
void TelloCommand(char *cmd) {
//only send data when connected
if (connected) {
//Send a packet
//udp.beginPacket(udpAddress, udpPort); OUTDATED has new name with ASync
udp.printf(cmd);
//udp.endPacket(); OUTDATED has new name with ASync
Serial.printf("Send [%s] to Tello.\n", cmd);
}
}
void sendMessage(String msg){
udp.writeTo((const uint8_t *)msg.c_str(), msg.length(),
IPAddress(169, 254, 107, 16), 4000);
}
void loop() {
delay(5000);
// Send broadcast on port 4000
udp.broadcastTo("Anyone here?", 4000);
// Serial.println("waiting for udp message...");
int x = 100;
int y = 100;
sendMessage("init " + String(x) + " " + String(y));
}
void loop() {
long duration, distance;
val = digitalRead(inPin); // read input value
//Ultra sonic sensor
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
duration = pulseIn(echoPin, HIGH);
distance = (duration / 2) / 29.1;
//LCD screen line 2
// lcd.setCursor(0, 1);
// lcd.print(distance, DEC);
//State machine that connects the drone to WiFi and the controller
switch (state)
{
case 0: //Idle not connected
//LCD screen line 1
//lcd.setCursor(0, 0);
//lcd.print("Controller");
if (val == HIGH)
{
state = 1;
connectToWiFi(networkName, networkPswd);
timer = millis() + 5000;
}
break;
case 1: //Trying to connect
if (WiFi.status() == WL_CONNECTED)
{
Serial.print("Connected to: ");
Serial.println(networkName);
udp.begin(WiFi.localIP(), udpPort);
connected = true;
TelloCommand("command");
timer = millis() + 2000;
state = 2;
}
if (millis() > timer)
{
state = 0;
}
break;
case 2: //Connected on ground
//lcd.setCursor(0, 0);
//lcd.print("Connected ");
if (WiFi.status() != WL_CONNECTED)
{
WiFi.disconnect(true);
Serial.println("Disconnected");
state = 0;
}
if (distance < 10)
{
TelloCommand("takeoff");
timer = millis() + 1000;
state = 3;
Serial.println("takeoff");
}
break;
case 3: //In air
//lcd.setCursor(0, 0);
//lcd.print("In air ");
if (millis() > timer)
{
timer = millis() + 20;
pitch = map(analogRead(34) - 1890, -2000, 2000, -100, 100);
roll = map(analogRead(35) - 1910, -2000, 2000, -100, 100);
throttle = map(analogRead(33) - 1910, -2000, 2000, -100, 100);
yaw = map(analogRead(32) - 1910, -2000, 2000, -100, 100);
sprintf(cmd, "rc %d %d %d %d", roll, pitch, throttle, yaw);
TelloCommand(cmd);
}
if (val == HIGH) {
TelloCommand("land");
timer = millis() + 1000;
state = 0;
Serial.println("land");
}
break;
}
delay(200);
}

SIM800L + Arduino TCP disconnect issue

Okay so I am currently using an arduino-uno to send AT commands to a SIM800l module. I am running a basic TCP socket server on my computer and the SIM800L is initially able to connect to it fine and send a message. After a seemingly random period of time on my serial monitor "NUL" is then displayed at which I am unable to send messages.
(So it is working initially however it seems to suddenly just stop mid process)
bool connectionProcedure()
{
bool result = false;
if(sendATcommand("AT+CIPSHUT", "SHUT OK", 200) == 1)
{
Serial.println("Proceed: AT+CIPMUX=0");
if(sendATcommand("AT+CIPMUX=0", "OK", 1000) == 1 )
{
Serial.println("Proceed: AT+CGATT=1");
if(sendATcommand("AT+CGATT=1", "OK", 1000) == 1 )
{
Serial.println("Proceed: AT+CSTT=\"gifgaff.com\",\"gifgaff\"");
if(sendATcommand("AT+CSTT=\"gifgaff.com\",\"gifgaff\"", "OK", 1000) == 1 )
{
Serial.println("Proceed: AT+CIICR");
if(sendATcommand("AT+CIICR", "OK", 60000) == 1 )
{
Serial.println("Proceed: AT+CIFSR");
if(sendATcommand("AT+CIFSR", ".", 5000) == 1 )
{
Serial.println("Process Success!");
result = true;
}
else
{
Serial.println("Error: AT+CIFSR");
}
}
else
{
Serial.println("Error: AT+CIICR");
}
}
else
{
Serial.println("Error: AT+CSTT=\"gifgaff.com\",\"gifgaff\"");
}
}
else
{
Serial.println("Error: AT+CGATT=1");
}
}
else
{
Serial.println("Error: AT+CIPMUX=0");
}
}
else
{
Serial.println("Error: CIPSHUT");
}
return result;
}
void awaitGSMConnection()
{
while( sendATcommand2("AT+CREG?", "+CREG: 0,1", "+CREG: 0,5", 1000) == 0 );
}
void initTCPConnection()
{
unsigned long previous;
unsigned int timeout = 10000;
Serial.println("Starting TCP Connection!");
if(sendATcommand("AT+CIPSTART=\"TCP\"," + tcpIp + "," + tcpPort, "OK", 10000) == 1)
{
Serial.println("Connection Success: Checking for stable connection before handshake!");
String expected = "CLOSED";
uint8_t x=0, answer=0;
char response[100];
memset(response, '\0', 100);
while( mySerial.available() > 0) mySerial.read();
x = 0;
previous = millis();
// Loop waits for the response from SIM800L
do {
if(mySerial.available() != 0) {
response[x] = mySerial.read();
x++;
// check if the desired answer 1 is in the response of the module
if (strstr(response, expected.c_str()) != NULL)
{
answer = 1;
}
}
}
while((answer == 0) && ((millis() - previous) < timeout));
if(answer == 0)
{
Serial.println("No Apparent ISSUE sending handshake!");
if(sendATcommand("AT+CIPSEND", ">", 4000) == 1)
{
Serial.println("SEND-HANDSHAKE");
sendMessage("Handshake");
//sendATcommand("AT+CIPCLOSE","OK",2000);
}
else
{
Serial.println("Error: AT+CIPSEND");
}
}
else
{
Serial.println("Connection test failed: Attempting to RECONNECT!");
}
}
else
{
Serial.println("Connection Error!");
}
}
Serial Monitor - Output
Here is the "NUL" I am talking about, this seems to appear completely randomly sometime during the connection. Random messages being sent from me from the server and being received.
No Apparent ISSUE sending handshake!
AT+CIPSEND
>
SEND-HANDSHAKE
Handshake␚
SEND OK
HELLO
AWESOME
COOL
INSANE
STILL WORKING!!!!
␀
Thanks in advance!