Advertisement
Guest User

Untitled

a guest
Mar 12th, 2019
99
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.49 KB | None | 0 0
  1. # Before running this script, you must have paso-mqtt installed. Use pip install paho-mqtt
  2. # This script was tested with python version 3.7
  3.  
  4. import paho.mqtt.client as paho
  5. import json
  6. import time
  7. import datetime
  8. import sys
  9. import random
  10.  
  11. # MQTT device event topic string format
  12. # iot-2/type/device_type/id/device_id/evt/event_id/fmt/format_string
  13.  
  14. # MQTT device event topic string we will be publishing to
  15. topic = "iot-2/type/temperaturesensor/id/sensor1/evt/temperature/fmt/json"
  16.  
  17. # device credentials
  18. # replace these with credentials to your own instance of IOT platform
  19. appname =
  20. iotorg =
  21. username =
  22. password =
  23.  
  24. # Note that all client ids must be unique
  25. client_id = 'a:'+iotorg+':'+appname
  26.  
  27.  
  28. # ------------- #
  29. # MQTT settings #
  30. # ------------- #
  31.  
  32. # create the MQTT client
  33. client = paho.Client(client_id=client_id, protocol=paho.MQTTv311)
  34.  
  35. # client connection
  36. # MQTT server credentials
  37. client.username_pw_set(username, password)
  38.  
  39. # Connect at the MQTT server address
  40. try:
  41. client.connect(iotorg + ".messaging.internetofthings.ibmcloud.com")
  42. except:
  43. print('could not connect')
  44.  
  45. #send out this message forever, at intervals of 10 seconds
  46. while True:
  47. time.sleep(10)
  48. print("sending event to Watson IOT platform")
  49. # We wish to publish the following JSON message
  50. temp = random.randint(0,90)
  51. event_json = json.dumps({"d":{"deviceid":"sensor1","temperature":temp}})
  52. print(event_json)
  53. client.publish(topic,event_json)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement