handle-cam2.py 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  1. #!/usr/bin/env python3
  2. import paho.mqtt.client as mqtt
  3. import threading
  4. import json
  5. import subprocess
  6. from time import sleep
  7. from os import path
  8. p = None
  9. # The callback for when the client receives a CONNACK response from the server.
  10. def on_connect(client, userdata, flags, rc):
  11. print("Connected with result code "+str(rc))
  12. # Subscribing in on_connect() means that if we lose the connection and
  13. # reconnect then subscriptions will be renewed.
  14. client.subscribe("video/cam2/preview")
  15. # The callback for when a PUBLISH message is received from the server.
  16. def on_message(client, userdata, msg):
  17. print(msg.topic+" "+str(msg.payload))
  18. if msg.topic == "video/cam2/preview":
  19. try:
  20. run = int(msg.payload)
  21. except Exception as e:
  22. print(e)
  23. return
  24. if run and p is None:
  25. print("Starting")
  26. p = subprocess.Popen(["/home/curso/code/snowmix/camera1/play-cam2.sh"]
  27. if p is not None and not run:
  28. print("Stopping")
  29. p.terminate()
  30. client = mqtt.Client()
  31. client.on_connect = on_connect
  32. client.on_message = on_message
  33. client.connect("192.168.2.123", 1883, 60)
  34. t = threading.Thread(target=client.loop_forever)
  35. t.start()
  36. t.join()