I'm new to python and wrote this script for an IoT app. I want to use thread in while loop. Actually I want to use threading before waiting time (9.98). I want lines 34-38 (from PID = random.randint
) to be executed by thread. Is this possible?
import paho.mqtt.client as mqtt
import time
import random
import thread
brokerAddress = "foobar.s2.eu.hivemq.cloud"
userName = "username"
passWord = "password"
topic = "Sensor"
#The callback for when the client recives a connack response from broker
def on_connect(client, userdata, flags, rc):
if rc == 0:
print("Connection Established")
else:
print("Coneect returened result code: " + str(rc))
def on_message(client, userdata, msg):
print("Received message: " +msg.topic + " -> " + msg.payload.decode("utf-8"))
client = mqtt.Client()
client.on_connect = on_connect
client.on_message = on_message
client.tls_set(tls_version=mqtt.ssl.PROTOCOL_TLS)
client.username_pw_set(userName, passWord)
print("Connecting to broker::",brokerAddress)
client.connect(brokerAddress, 8883)
client.loop_start()
time.sleep(2)
while True:
try:
input("press enter to put the box on line:")
except SyntaxError:
pass
PID = random.randint(0 , 2000000)
print(PID)
print("wait for the box to arrive to sensor:9.980")
time.sleep(9.980)
client.publish(topic, PID)
print("..............................................................")
client.loop_stop()
Output from the above is:
output first (enter):
Connecting to broker:: d615ed48421a497f892c98c1b04cfb82.s2.eu.hivemq.cloud
Connection Established
press enter to put the box on line:
168488
Subscriber is:
import paho.mqtt.client as mqtt
import datetime
import time
brokerAddress = "foobar.s2.eu.hivemq.cloud"
userName = "user"
passWord = "password"
topic = "Sensor"
#the callback for when the client recieves a connack response from broker
def on_connect(client, userdata, flags, rc ):
if rc == 0:
print("Connection Established")
else:
print("Connect retured result code: " +str(rc))
#the calback from when a Publish message is received from the broker
def on_message(client, userdata, msg):
print("Received message: " +msg.topic + " -> " + msg.payload.decode("utf-8"))
#wait for actuactor
time.sleep(.02)
Prduction_time = datetime.datetime.now()
print("production Time",Prduction_time)
#create the client
client = mqtt.Client()
client.on_connect = on_connect
client.on_message = on_message
client.tls_set(tls_version=mqtt.ssl.PROTOCOL_TLS)
client.username_pw_set(userName, passWord)
print("Connecting to broker::",brokerAddress)
client.connect(brokerAddress, 8883)
client.subscribe(topic)
client.loop_forever()