SIM800L + Arduino TCP disconnect issue - c++

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!

Related

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 ?

Control Relay by MQTT Publish Subcribe

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

How to block http flood connections in windows

I have an application made in c ++ that acts as a server. Gameserver.exe
The problem is that they manage to attack gameserver.exe with http flood connections, for example http://ip:port
The attacks are sent from an application called "railgun"
How can I block or prevent these http connections?
Currently I use an anti flood in the gameserver.exe application which is basically this.
int gObjGetIPIndex(char* IpAddress)
{
int Ret = -1;
for (int x = 0; x < LastIPList; x++)
{
if (IPList[x][0] == IpAddress[0])
{
if (strcmp(IPList[x], IpAddress) == 0)
{
return x;
break;
}
}
}
Ret = LastIPList;
sprintf(IPList[LastIPList], "%s", IpAddress);
LastIPList++;
if (LastIPList >= 2000)LastIPList = 0;
return Ret;
}
short gObjAdd(SOCKET socket, char* IpAddress, int aIndex) // OK stdafx.h ?
{
if (OBJECT_RANGE(aIndex) == 0)
{
return -1;
}
if (gObj[aIndex].Connected != OBJECT_OFFLINE)
{
return -1;
}
//========================================
// Anti Flood Fix 13/08/2020
//========================================
if (gServerInfo.m_EnableAntiflood == 1)
{
int IPIndex = gObjGetIPIndex(IpAddress);
DWORD CurTick = GetTickCount();
if ((CurTick - LastConnect[IPIndex]) < 1000)
{
LastConnect[IPIndex] = CurTick;
LogAdd(LOG_RED, "[AntiFlood][%d] BlockAttack (%s)", aIndex, IpAddress);
return -1;
}
LastConnect[IPIndex] = CurTick;
}
Thanks for your time.

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?

Why when I change the value (file in linux belong to gpio pin) from 1 to 0, nothing changed?

I have a matrix relay with a nanopi fire (like rasperry pi). I connected this relay to my device and want to change gpio value.(my device has multi gpio pin. first I should create gpio(echo 95 > /sys/class/gpio/export) and then change direction folder "out" (echo "out" > /sys/class/gpio/gpio95/direction) and with changing value the relay should turn on and off.)
this is my code:
bool GPIOClass::ChangeValue(QString IO, QString port)
{
QString gpio;
QString comand;
// comand=" echo ";
// comand.append(QIO);
// comand.append(" > ");
// gpio=config->GpioFromPort(port);
// if(gpio.length()==0)
// return false;
// //IO should be 1 or 0
QString src=IdenGPIOSrc(gpio);//src is /sys/class/gpio/gpio95
src.append("/value");
// comand.append(src);
// qDebug()<<port<<gpio<<"with src:"
// <<src <<"with command:"<<comand;
// system(comand.toStdString().c_str());
///===========================================================
QFile file(src);
if ( file.open(QIODevice::WriteOnly) )
{
//clear the content
// file.resize(0);
file.seek(0);
file.write(QByteArray::number(IO.toInt()),1);
}
if(GetValue(port)==IO.toInt())
{
return true;
}
else
return false;
}
the relay is not changed, but when I run the executable sample the relay is turn on and off:
int main(int argc, char ** argv)
{
int pin = GPIO_PIN(7);
int i, value, board;
int ret = -1;
if ((board = boardInit()) < 0) {
printf("Fail to init board\n");
return -1;
}
if (board == BOARD_NANOPI_T2)
pin = GPIO_PIN(15);
if (argc == 2)
pin = GPIO_PIN(atoi(argv[1]));
if ((ret = exportGPIOPin(pin)) == -1) {
printf("exportGPIOPin(%d) failed\n", pin);
}
if ((ret = setGPIODirection(pin, GPIO_OUT)) == -1) {
printf("setGPIODirection(%d) failed\n", pin);
}
for (i = 0; i < STATUS_CHANGE_TIMES; i++) {
if (i % 2) {
value = GPIO_HIGH;
} else {
value = GPIO_LOW;
}
if ((ret = setGPIOValue(pin, value)) > 0) {
printf("%d: GPIO_PIN(%d) value is %d\n", i+1, pin, value);
} else {
printf("setGPIOValue(%d) failed\n", pin);
}
sleep(1);
}
unexportGPIOPin(pin);
return 0;
}
in that code also the value in that address changed like my code (change value file to 1 and 0 ) and the relay is working. where is the diffrence between my code and that code? both of them change the value content.
where is my code problem?