Guest User

lamp.py

a guest
May 6th, 2016
223
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. #!/usr/bin/python3
  2.  
  3. import ssl
  4. import paho.mqtt.client as mqtt
  5. import configparser
  6. import json
  7.  
  8. devStatus = {}
  9. devStatus["color"] = "Red"
  10.  
  11. def on_connect(mqttc, obj, flags, rc):
  12.     global devStatus
  13.     if rc==0:
  14.         global thingname
  15.         print ("Connection successful")
  16.         mqttc.subscribe("$aws/things/"+thingname+"/shadow/control", qos=0)
  17.         print("My color is",devStatus["color"])
  18.     elif rc==1:
  19.         print ("Connection refused")
  20.  
  21. def on_message(mqttc, obj, msg):
  22.     global devStatus
  23.     global thingname
  24.     newStatus = msg.payload.decode("utf-8")
  25.     if (newStatus in ['Red','Green','Blue']):
  26.         devStatus["color"] = newStatus
  27.     mqttc.publish(topic="$aws/things/"+thingname+"/shadow/lamp",payload=json.dumps(devStatus),qos=0)
  28.     print("My color is",devStatus["color"])
  29.  
  30. if __name__ == '__main__':
  31.     config = configparser.RawConfigParser()
  32.     config.read('conf/config.prop')
  33.     thingname = config.get("General","thingname")
  34.     rootcert = config.get("General","rootcert")
  35.     certificate = config.get("General","certificate")
  36.     key = config.get("General","key")
  37.     endpoint = config.get("General","endpoint")
  38.     awsport = config.getint("General","port")
  39.     #creating a client with client-id=mqtt-test
  40.     mqttc = mqtt.Client(client_id="lamp")
  41.  
  42.     mqttc.on_connect = on_connect
  43.     mqttc.on_message = on_message
  44.  
  45.     mqttc.tls_set(rootcert,
  46.                 certfile=certificate,
  47.                 keyfile=key,
  48.                 tls_version=ssl.PROTOCOL_TLSv1_2,
  49.                 ciphers=None)
  50.    
  51.     mqttc.connect(endpoint, port=awsport)
  52.  
  53.     mqttc.loop_forever()
RAW Paste Data