handle-cam2.py 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  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. global p
  18. print(msg.topic+" "+str(msg.payload))
  19. if msg.topic == "video/cam2/preview":
  20. try:
  21. run = int(msg.payload)
  22. except Exception as e:
  23. print(e)
  24. return
  25. if run == 1 and p is None:
  26. print("Starting")
  27. p = subprocess.Popen(["/home/curso/code/snowmix/camera1/play-cam2.sh"])
  28. if (p is not None and run == 0):
  29. print("Stopping")
  30. p.terminate()
  31. sleep(0.1)
  32. if p is not None:
  33. p.kill()
  34. sleep(0.1)
  35. p = None
  36. client = mqtt.Client()
  37. client.on_connect = on_connect
  38. client.on_message = on_message
  39. client.connect("192.168.2.123", 1883, 60)
  40. t = threading.Thread(target=client.loop_forever)
  41. t.start()
  42. t.join()