MnMWizard

Untitled

Oct 15th, 2021
1,124
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. # leftSensor and broker file
  2.  
  3. #Preliminary code for an outer pi, definitely not finished just an idea
  4.  
  5. import time
  6. import board
  7. import os
  8. import threading
  9. from gpiozero import MotionSensor
  10. from gpiozero import Servo
  11. from paho.mqtt import client as mqtt
  12. from paho.mqtt import publish
  13. from paho.mqtt import subscribe
  14.  
  15. IRSensor = MotionSensor(4)
  16.  
  17. servo = Servo(16)
  18.  
  19. ThermalCamOff = 1  #temp variable at the moment
  20. stopLSensorReading = False
  21.  
  22. broker = '192.168.1.15'
  23. port = 1883
  24. topic = "peripheralSensor/leftSensor"
  25. clientID = "leftPumpkin"
  26. subscription = ("servoPosition", 2)
  27.  
  28. def subscribe(client, subscription):
  29.     r = client.subscribe(subscription)
  30.     if r[0] == 0:
  31.         print(f"Successfully subscribed to {subscription}")
  32.     else:
  33.         print(f"Failed to subscribe to {subscription}")
  34.  
  35. def connect_mqtt():
  36.     def on_connect(client, userdata, flags, rc):
  37.         if rc==0:
  38.             print("connected to MQTT Broker!")
  39.         else:
  40.             print("failed to connect")
  41.     client = mqtt.Client(clientID)
  42.     client.on_connect = on_connect
  43.     client.on_message = on_message
  44.     client.connect(broker, port)
  45.     subscribe(client, subscription)
  46.     return client
  47.  
  48.  
  49. def publish(client, msg):
  50.     print("in publish")
  51.     result = client.publish(topic, msg)
  52.     status = result[0]
  53.     if status == 0:
  54.         print(f"sent `{msg}` to topic `{topic}`")
  55.     else:
  56.         print(f"failed to send message to topic {topic}")
  57.     time.sleep(5)
  58.  
  59. def on_message(client, userdata, message):
  60.     print("in response to subscription")
  61.     global stopLSensorReading
  62.     if (message.payload == "0enmasse"):
  63.         stopLSensorReading = True
  64.         servo.value = 0
  65.         print("0enmasse")
  66.         time.sleep(60)
  67.         stopLSensorReading = False
  68.         LSensor()
  69.     else:
  70.         servo.value = message.payload
  71.         print(f'{message.payload}')
  72.        
  73. def LSensor(client):
  74.     print("in LSensor")
  75.     global stopLSensorReading
  76.     while(True):
  77.         print("loop")
  78.         if stopLSensorReading:
  79.             break
  80.         IRSensor.wait_for_motion()
  81.         print('seen')
  82.         publish(client, 1)
  83.  
  84. def run():
  85.     leftSensorThread = threading.Thread(target = LSensor)
  86.     client = connect_mqtt()
  87.     client.loop_start()
  88.     LSensor(client)
  89.    
  90.    
  91. if __name__ == '__main__':
  92.     run()
RAW Paste Data