Advertisement
glaucogoncalves

commander.py

May 6th, 2016
170
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.87 KB | None | 0 0
  1. #!/usr/bin/python3
  2.  
  3. import ssl
  4. import paho.mqtt.client as mqtt
  5. import cmd
  6. import time
  7. import json
  8. import configparser
  9.  
  10. devStatus = None
  11.  
  12. def on_connect(mqttc, obj, flags, rc):
  13.     if rc==0:
  14.         global thingname
  15.         print ("Connection successful")
  16.         mqttc.subscribe("$aws/things/"+thingname+"/shadow/lamp", qos=0)
  17.     elif rc==1:
  18.         print ("Connection refused")
  19.  
  20. def on_subscribe(mqttc, obj, mid, granted_qos):
  21.     print("Subscribed")
  22.  
  23. def on_message(mqttc, obj, msg):
  24.     global devStatus
  25.     jData = json.loads(msg.payload.decode("utf-8"))
  26.     devStatus = jData["color"]
  27.  
  28. class ControlInterface(cmd.Cmd):
  29.    
  30.     def do_status(self, line):
  31.         global devStatus
  32.         print(devStatus)
  33.    
  34.     def do_send(self, color):
  35.         global thingname
  36.         mqttc.publish(topic="$aws/things/"+thingname+"/shadow/control",payload=color,qos=0)
  37.    
  38.     def do_EOF(self, line):
  39.         return True
  40.  
  41. if __name__ == '__main__':
  42.     config = configparser.RawConfigParser()
  43.     config.read('conf/config.prop')
  44.     thingname = config.get("General","thingname")
  45.     rootcert = config.get("General","rootcert")
  46.     certificate = config.get("General","certificate")
  47.     key = config.get("General","key")
  48.     endpoint = config.get("General","endpoint")
  49.     awsport = config.getint("General","port")
  50.  
  51.     mqttc = mqtt.Client(client_id="commander")
  52.  
  53.     mqttc.on_connect = on_connect
  54.     mqttc.on_subscribe = on_subscribe
  55.     mqttc.on_message = on_message
  56.  
  57.     mqttc.tls_set(rootcert,
  58.                 certfile=certificate,
  59.                 keyfile=key,
  60.                 tls_version=ssl.PROTOCOL_TLSv1_2,
  61.                 ciphers=None)
  62.    
  63.     mqttc.connect(endpoint, port=awsport)
  64.  
  65.     mqttc.loop_start()
  66.     time.sleep(2)
  67.     mqttc.publish(topic="$aws/things/"+thingname+"/shadow/control",payload="",qos=0)
  68.     ControlInterface().cmdloop()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement