I'm using a Raspberry Pi 3B+ with SIM7600X 4G HAT for communication with Python. I want to connect to MQTT server to receive messages via writing MQTT commands directly to the serial port of the SIM7600 (based on the manual examples).
It works fine for a while, but after a few hours it loses MQTT connection, and I can't reconnect the same way as I connected the first time.
This is my main loop:
def loop():
global isMQTTServerReady
while True:
if isMQTTServerReady:
if ser.inWaiting():
EVENT = ser.read(ser.inWaiting()).decode()
if "+CMQTTCONNLOST" in EVENT:
connectToMQTT()
if "+CMQTTRXPAYLOAD" in EVENT:
# do something with the MQTT message
else:
connectToMQTT()
time.sleep(5)
And this is my connect function:
def connectToMQTT():
openSerialPortIfNotOpen()
ser.write("AT+CRESET")
time.sleep(5)
log(ser.read(ser.inWaiting()))
time.sleep(1)
ser.write('AT+CMQTTSTART\r\n'.encode())
time.sleep(3)
log(ser.read(ser.inWaiting()))
ser.write('AT+CMQTTDISC=0,60\r\n'.encode())
time.sleep(2)
log(ser.read(ser.inWaiting()))
ser.write('AT+CMQTTREL=0\r\n'.encode())
time.sleep(2)
log(ser.read(ser.inWaiting()))
ser.write('AT+CMQTTSTOP\r\n'.encode())
time.sleep(2)
log(ser.read(ser.inWaiting()))
startAndSubscribe()
def startAndSubscribe():
global isMQTTServerReady
isMQTTServerReady=False
ser.write('AT+CMQTTSTART\r\n'.encode())
time.sleep(3)
log(ser.read(ser.inWaiting()))
ser.write('AT+CMQTTACCQ=0,'+MQTT_CLIENT_NAME+'\r\n'.encode())
time.sleep(5)
log(ser.read(ser.inWaiting()))
ser.write(MQTT_BROKER_URL+',60,1\r\n'.encode())
while not isMQTTServerReady:
connStatus = ser.read(ser.inWaiting())
log (connStatus.decode())
if "+CMQTTCONNECT: 0,0" in connStatus.decode():
time.sleep(.1)
log(ser.read(ser.inWaiting()))
ser.write('AT+CMQTTSUB=0,12,1,0\r\n'.encode())
time.sleep(2)
log(ser.read(ser.inWaiting()))
ser.write(MQTT_TOPIC_NAME.encode())
time.sleep(3)
isMQTTServerReady=True
if "+CMQTTCONNLOST:" in connStatus.decode():
connectToMQTT()
It works for a while, but after 1-2 hours I got into this loop (this is the log file):
AT+CRESET
AT+CMQTTSTART
ERROR
AT+CMQTTDISC=0,60
+CMQTTDISC: 0,11 #--> 11 means: No connection
ERROR
AT+CMQTTREL=0
+CMQTTREL: 0,19 #--> 19 means: Client is used
ERROR
AT+CMQTTSTOP
+CMQTTSTOP: 21 #--> 21 means: Client not released
ERROR
AT+CMQTTSTART
+CMQTTSTART: 23 #--> 23 means: Network is opened
ERROR
AT+CMQTTACCQ=0,"client_1"
+CMQTTACCQ: 0,19 #--> 19 means: Client is used
ERROR
AT+CMQTTCONNECT=0,"tcp://test.mosquitto.org:1883",60,1
+CMQTTCONNECT: 0,13 #--> 13 means: Not supported operations
ERROR
And I stuck in an infinite loop of trying to reconnect, but it can never reconnect again. But if I reboot the device, it works fine again.
What is wrong with this? I thought that if I lose connection, I should:
- disconnect client, -release client, -stop mqtt, -start mqtt, -acquire client, -connect to mqtt and then subscibe to topic, as it is in the Sim 7600X Manual