Advertisement
Guest User

Untitled

a guest
Jan 8th, 2016
70
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.26 KB | None | 0 0
  1. import RPi.GPIO as GPIO
  2. import time
  3. import paho.mqtt.client as mqtt
  4. import json
  5.  
  6. username = "43807467-bbbf-4cd0-9d90-b13d454209d2"
  7. password ="Orh4r16u+dntVFyNRpjpuAyYGE+hZCug906oRVV1VM0="
  8. controllTopic = "xi/blue/v1/93336b3c-49f4-44a5-885f-5cb31504dea7/d/43807467-bbbf-4cd0-9d90-b13d454209d2/device-log"
  9.  
  10. publishTopic = "xi/blue/v1/93336b3c-49f4-44a5-885f-5cb31504dea7/d/7d7afa69-bda6-4219-a9ae-633262a81cfb/device-log"
  11. publishPayload = "{\"default\": \"message message\"}"
  12.  
  13.  
  14. # The callback for when the client receives a CONNACK response from the server.
  15. def on_connect(client, userdata, rc):
  16. print("Connected with result code "+str(rc))
  17. # Subscribing in on_connect() means that if we lose the connection and
  18. # reconnect then subscriptions will be renewed.
  19. #client.subscribe("$SYS/#")
  20. client.subscribe(controllTopic)
  21. client.subscribe(publishTopic)
  22.  
  23. # The callback for when a PUBLISH message is received from the server.
  24. def on_message(client, userdata, msg):
  25. global publishTopic
  26. global publishPayload
  27.  
  28. print(msg.payload)
  29. parsedMessage = json.loads(msg.payload)
  30.  
  31. if 'channel' in parsedMessage:
  32. publishTopic = json.dumps(parsedMessage['channel']).replace("\"", "")
  33. if 'message-by-device' in parsedMessage:
  34. publishPayload = json.dumps(parsedMessage['message-by-device'])
  35. if 'led_blink_count' in parsedMessage and msg.topic == publishTopic:
  36. print('here you go')
  37. for i in range(0, parsedMessage['led_blink_count']):
  38. GPIO.output(20, GPIO.HIGH)
  39. time.sleep(1)
  40. GPIO.output(20, GPIO.LOW)
  41. time.sleep(1)
  42.  
  43. def on_publish(client, userdata, mid):
  44. print("message sent")
  45.  
  46. client = mqtt.Client()
  47.  
  48. client.on_connect = on_connect
  49. client.on_message = on_message
  50. client.on_publish = on_publish
  51.  
  52. client.username_pw_set(username, password)
  53. client.tls_set("gs_root.cer")
  54. client.connect("broker.demo.xively.com", 8883, 60)
  55.  
  56. client.loop_start()
  57.  
  58. # Handling button press on Raspbery PI
  59. GPIO.setmode(GPIO.BCM)
  60. GPIO.setup(21, GPIO.IN, pull_up_down=GPIO.PUD_UP)
  61.  
  62. GPIO.setmode(GPIO.BCM)
  63. GPIO.setup(20, GPIO.OUT)
  64. GPIO.output(20, GPIO.LOW)
  65.  
  66. while True:
  67. input_state = GPIO.input(21)
  68.  
  69. if input_state == False:
  70. print('Button Pressed')
  71. client.publish(publishTopic, publishPayload, qos=0)
  72. time.sleep(1)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement