I have written a python script to fetch the data from MQTT, It's working fine, the problem is after a month or so, It automatically stops getting the data from MQTT, and when i restart the script then it again start working. What will be the best approach to run the script so that it will work continuously?
PS: I have tried running through bash but still I have faced the same problem. Even though I have run through Monit but even that didn't solved the issue and in monit it shows the script is running.
My Script is :
import paho.mqtt.client as mqtt
import json
import base64
import sqlite3
import datetime
import requests
APPID = ""
PSW = ''
def on_connect(mqttc, mosq, obj,rc):
print("Connected with result code:"+str(rc))
mqttc.subscribe('+/devices/+/up')
def on_message(mqttc,obj,msg):
file1 = open('weather.txt','a')
try:
feed = json.loads(msg.payload.decode('utf-8'))
print(msg.payload + '\n')
except Exception as e:
print(e)
pass
def on_publish(mosq, obj, mid):
print("mid: " + str(mid) + '\n')
def on_subscribe(mosq, obj, mid, granted_qos):
print("Subscribed: " + str(mid) + " " + str(granted_qos))
def on_log(mqttc,obj,level,buf):
print(datetime.datetime.now())
print("message:" + str(buf))
print("userdata:" + str(obj))
mqttc= mqtt.Client()
mqttc.on_connect=on_connect
mqttc.on_message=on_message
mqttc.on_subscribe=on_subscribe
mqttc.on_log=on_log
mqttc.username_pw_set(APPID, PSW)
mqttc.connect("eu.thethings.network",XXXX,XX)
# and listen to server
run = True
while run:
mqttc.loop()
Any suggestion will be highly appreciated. Thanks in advance!!
For client connect run forever use forever
mqttc.loop_forever()
May this hope will help.
import paho.mqtt.client as mqtt
import json
import base64
import sqlite3
import datetime
import requests
APPID = ""
PSW = ''
def on_connect(mqttc, mosq, obj,rc):
print("Connected with result code:"+str(rc))
mqttc.subscribe('+/devices/+/up')
def on_message(mqttc,obj,msg):
file1 = open('weather.txt','a')
try:
feed = json.loads(msg.payload.decode('utf-8'))
print(msg.payload + '\n')
except Exception as e:
print(e)
pass
def on_publish(mosq, obj, mid):
print("mid: " + str(mid) + '\n')
def on_subscribe(mosq, obj, mid, granted_qos):
print("Subscribed: " + str(mid) + " " + str(granted_qos))
def on_log(mqttc,obj,level,buf):
print(datetime.datetime.now())
print("message:" + str(buf))
print("userdata:" + str(obj))
mqttc= mqtt.Client()
mqttc.on_connect=on_connect
mqttc.on_message=on_message
mqttc.on_subscribe=on_subscribe
mqttc.on_log=on_log
mqttc.username_pw_set(APPID, PSW)
mqttc.connect("eu.thethings.network",XXXX,XX)
mqttc.loop_forever()
Happy Coding folk.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.