Advertisement
Guest User

Untitled

a guest
Apr 24th, 2017
78
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.40 KB | None | 0 0
  1. #!/usr/bin/env python3
  2. import paho.mqtt.client as mqtt
  3. import datetime
  4. import time
  5. from Adafruit_IO import MQTTClient
  6. from adafruit_credentials import ADAFRUIT_IO_USERNAME, ADAFRUIT_IO_KEY
  7. from mylogger import logger
  8.  
  9. #
  10. # Subscribes to messages via a local MQTT broker
  11. # and forwards them to a cloud service (Adafruit IO)
  12. #
  13.  
  14. def on_connected(client, userdata, rc):
  15. print("Connected to local MQTT broker with result code "+str(rc))
  16. client.subscribe("Home/Outdoor/Temperature")
  17. client.subscribe("Home/Outdoor/Humidity")
  18. client.subscribe("Home/Laundry/Temperature")
  19. client.subscribe("Home/Laundry/Humidity")
  20. client.subscribe("Home/GroundFloor/Temperature")
  21. client.subscribe("Home/GroundFloor/Humidity")
  22. client.subscribe("Home/TopFloor/Temperature")
  23. client.subscribe("Home/TopFloor/Pressure")
  24. client.subscribe("Home/RPI3/Temp")
  25. client.subscribe("Home/FrontDoor/Status")
  26.  
  27. def on_disconnected(client,userdata,rc):
  28. print("Disconnected from local MQTT broker")
  29. try_connect_to_local_broker(client)
  30.  
  31. def adafruit_connected(client):
  32. print("Connected to Adafruit IO")
  33.  
  34. def on_message(client, userdata, msg):
  35. print(str(datetime.datetime.now()) + ": " + msg.topic + " " + str(msg.payload))
  36. #
  37. # Forward the data to Adafruit IO. Replace topic with a valid feed name
  38. #
  39. feedname=msg.topic.replace("/","_")
  40. print("Publish to Adafruit feedname: " + feedname)
  41.  
  42. # Initialize the client that should connect to io.adafruit.com
  43. adafruitClient = MQTTClient(ADAFRUIT_IO_USERNAME, ADAFRUIT_IO_KEY,service_port=1883)
  44. adafruitClient.on_connect = adafruit_connected
  45. adafruitClient.connect()
  46. adafruitClient.loop()
  47. adafruitClient.publish(feedname,msg.payload)
  48.  
  49. def try_connect_to_local_broker(client):
  50. print("trying to connect to local broker")
  51. connOK=False
  52. while(connOK == False):
  53. try:
  54. client.connect("192.168.1.16", 1883, 60)
  55. connOK = True
  56. except:
  57. connOK = False
  58. time.sleep(2)
  59.  
  60. #
  61. # Initialize the client that should connect to the local MQTT broker
  62. #
  63. client = mqtt.Client()
  64. client.on_connect = on_connected
  65. client.on_disconnect = on_disconnected
  66. client.on_message = on_message
  67.  
  68. while True:
  69. # Blocking loop to the local Mosquitto broker
  70. try:
  71. try_connect_to_local_broker(client)
  72. client.loop_forever()
  73. except:
  74. print("Exception from client.loop_forever")
  75. time.sleep(20)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement