0

I'm working on a project that contain a webserver that handle "time" and "traffic light" parameter and save it to a pickle file and another script load the pickle and use it for mqtt client

import pickle
import paho.mqtt.client as mqtt
from datetime import datetime, date, time
from threading import Timer
date=datetime.now()
print date
try:
    while True:
        fp = open("shared.pkl", 'rb')
        shared = pickle.load(fp)
        if date < shared["now"] :
            time= shared["time"]
            light = shared["light"]
            date = shared["now"]
            fp.close()
            time= int(time)
            def pub (s):
                client.publish("traffic/light1", payload = s ,qos=0, retain=False)
            t= Timer(time , pub,[light])
            t.start()
            print time
            print light
            print date




        client = mqtt.Client()


        client.connect("localhost", 1883, 60)

# Blocking call that processes network traffic, dispatches callbacks and
# handles reconnecting.
# Other loop*() functions are available that give a threaded interface and a
# manual interface.

        client.loop(timeout=1.0, max_packets=1)

except (EOFError, UnpicklingError):
    pass

it works good but sometimes it doesn't publish or doesn't read the pkl file!! any suggestions?

hardillb
  • 54,545
  • 11
  • 67
  • 105

1 Answers1

1

Without looking at it too closely, something like the below should do the job.

Calling client.loop() just processes a bit of network traffic, there is no guarantee that after it has been called all traffic will have been sent. Use loop_start() or loop_forever() depending on whether you want asynchronous/blocking behaviour.

client = mqtt.Client()
client.connect("localhost", 1883, 60)

client.loop_start()

print date

while True:
    try:
        fp = open("shared.pkl", 'rb')
        shared = pickle.load(fp)
        fp.close()
    except (EOFError, UnpicklingError):
        continue

    if date < shared["now"] :
        time= shared["time"]
        light = shared["light"]
        date = shared["now"]

        time= int(time)
        def pub (s):
            client.publish("traffic/light1", payload = s ,qos=0, retain=False)
        t= Timer(time , pub,[light])
        t.start()
        print time
        print light
        print date
ralight
  • 11,033
  • 3
  • 49
  • 59