Guest User

Untitled

a guest
Nov 30th, 2018
196
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 7.52 KB | None | 0 0
  1. Traceback (most recent call last):
  2. File "lily_telemetry.py", line 220, in <module>
  3. main()
  4. File "lily_telemetry.py", line 217, in main
  5. main()
  6. File "lily_telemetry.py", line 185, in main
  7. client.connect(args.mqtt_bridge_hostname, args.mqtt_bridge_port)
  8. File "/home/pi/.local/lib/python3.5/site-packages/paho/mqtt/client.py", line 839, in connect
  9. return self.reconnect()
  10. File "/home/pi/.local/lib/python3.5/site-packages/paho/mqtt/client.py", line 962, in reconnect
  11. sock = socket.create_connection((self._host, self._port), source_address=(self._bind_address, 0))
  12. File "/usr/lib/python3.5/socket.py", line 694, in create_connection
  13. for res in getaddrinfo(host, port, 0, SOCK_STREAM):
  14. File "/usr/lib/python3.5/socket.py", line 733, in getaddrinfo
  15. for res in _socket.getaddrinfo(host, port, family, type, proto, flags):
  16. socket.gaierror: [Errno -3] Temporary failure in name resolution
  17.  
  18. #!/usr/bin/python
  19.  
  20. import argparse
  21. import json
  22. import datetime
  23. import time
  24. import ssl
  25. import subprocess
  26.  
  27. import board
  28. import busio
  29. import adafruit_mcp9808
  30. import adafruit_tsl2591
  31. import digitalio
  32.  
  33. import jwt
  34. import paho.mqtt.client as mqtt
  35.  
  36. # Update and publish temperature readings at a rate of SENSOR_POLL per second.
  37. SENSOR_POLL=60
  38.  
  39. # Initialise I2C Master Bus
  40. i2c_bus = busio.I2C(board.SCL, board.SDA)
  41.  
  42. # Set temperature sensor inputs MCP9808 board
  43. mcp1 = adafruit_mcp9808.MCP9808(i2c_bus)
  44. mcp2 = adafruit_mcp9808.MCP9808(i2c_bus,0x1C)
  45.  
  46. # Set light sensor inputs TSL2591 board
  47. tsl = adafruit_tsl2591.TSL2591(i2c_bus)
  48.  
  49. def create_jwt(project_id, private_key_file, algorithm):
  50. """Create a JWT (https://jwt.io) to establish an MQTT connection."""
  51. token = {
  52. 'iat': datetime.datetime.utcnow(),
  53. 'exp': datetime.datetime.utcnow() + datetime.timedelta(minutes=60),
  54. 'aud': project_id
  55. }
  56. with open(private_key_file, 'r') as f:
  57. private_key = f.read()
  58. print('Creating JWT using {} from private key file {}' .format(algorithm, private_key_file))
  59. return jwt.encode(token, private_key, algorithm=algorithm)
  60.  
  61. def error_str(rc):
  62. """Convert a Paho error to a human readable string."""
  63. return '{}: {}'.format(rc, mqtt.error_string(rc))
  64.  
  65. class Device(object):
  66. """Represents the state of a single device."""
  67. def __init__(self):
  68. self.temperature = 0
  69. self.connected = False
  70.  
  71. def update_sensor_data(self):
  72. # CPU Temp
  73. rawdata = subprocess.check_output(["sudo", "/opt/vc/bin/vcgencmd", "measure_temp"]).decode().split('=', 1)[-1].rstrip()
  74. sendtemp = '"temp":"{}"' .format(rawdata.replace("'", "-").split("-", 1)[0])
  75. self.temperature = sendtemp
  76.  
  77. # Temperature Sensor 1 Data
  78. self.sensortemperature_1 = '"sensor_temp_1":"{}"' .format(mcp1.temperature)
  79.  
  80. # Temperature Sensor 2 Data
  81. self.sensortemperature_2 = '"sensor_temp_2":"{}"' .format(mcp2.temperature)
  82.  
  83. # Light Sensor Data
  84. lux = tsl.lux
  85. infrared = tsl.infrared
  86. visible = tsl.visible
  87. full_spectrum = tsl.full_spectrum
  88. self.lightsensor_lux = '"light_sensor_lux":"{}"' .format(round(lux,4))
  89. self.lightsensor_infrared = '"light_sensor_infrared":"{}"' .format(infrared)
  90. self.lightsensor_visible = '"light_sensor_visible":"{}"' .format(visible)
  91. self.lightsensor_full_spectrum = '"light_sensor_full_spectrum":"{}"' .format(full_spectrum)
  92.  
  93. def wait_for_connection(self, timeout):
  94. """Wait for the device to become connected."""
  95. total_time = 0
  96. while not self.connected and total_time < timeout:
  97. time.sleep(1)
  98. total_time += 1
  99.  
  100. if not self.connected:
  101. raise RuntimeError('Could not connect to MQTT bridge.')
  102.  
  103. def on_connect(self, unused_client, unused_userdata, unused_flags, rc):
  104. """Callback for when a device connects."""
  105. print('Connection Result:', error_str(rc))
  106. self.connected = True
  107.  
  108. def on_disconnect(self, unused_client, unused_userdata, rc):
  109. """Callback for when a device disconnects."""
  110. print('Disconnected:', error_str(rc))
  111. print('...')
  112. main()
  113. self.connected = False
  114.  
  115. def on_publish(self, unused_client, unused_userdata, unused_mid):
  116. """Callback when the device receives a PUBACK from the MQTT bridge."""
  117. print('Published message.')
  118. print("Waiting {} seconds." .format(SENSOR_POLL))
  119.  
  120. def on_subscribe(self, unused_client, unused_userdata, unused_mid,
  121. granted_qos):
  122. """Callback when the device receives a SUBACK from the MQTT bridge."""
  123. print('Subscribed: ', granted_qos)
  124. if granted_qos[0] == 128:
  125. print('Subscription failed.')
  126.  
  127. def parse_command_line_args():
  128. """Parse command line arguments."""
  129. parser = argparse.ArgumentParser(
  130. description='Lily Grow Logging using MQTT')
  131. parser.add_argument(
  132. '--project_id', required=True, help='GCP cloud project name')
  133. parser.add_argument(
  134. '--registry_id', required=True, help='Cloud IoT registry id')
  135. parser.add_argument('--device_id', required=True, help='Cloud IoT device id')
  136. parser.add_argument(
  137. '--private_key_file', required=True, help='Path to private key file.')
  138. parser.add_argument(
  139. '--algorithm',
  140. choices=('RS256', 'ES256'),
  141. required=True,
  142. help='Which encryption algorithm to use to generate the JWT.')
  143. parser.add_argument(
  144. '--cloud_region', default='us-central1', help='GCP cloud region')
  145. parser.add_argument(
  146. '--ca_certs',
  147. default='roots.pem',
  148. help='CA root certificate. Get from https://pki.google.com/roots.pem')
  149. parser.add_argument(
  150. '--num_messages',
  151. type=int,
  152. default=60,
  153. help='Number of messages to publish.')
  154. parser.add_argument(
  155. '--mqtt_bridge_hostname',
  156. default='mqtt.googleapis.com',
  157. help='MQTT bridge hostname.')
  158. parser.add_argument(
  159. '--mqtt_bridge_port', default=8883, help='MQTT bridge port.')
  160.  
  161. return parser.parse_args()
  162.  
  163. def main():
  164. args = parse_command_line_args()
  165.  
  166. # Create our MQTT client and connect to Cloud IoT.
  167. client = mqtt.Client(
  168. client_id='projects/{}/locations/{}/registries/{}/devices/{}'.format(
  169. args.project_id, args.cloud_region, args.registry_id, args.device_id))
  170. client.username_pw_set(
  171. username='unused',
  172. password=create_jwt(args.project_id, args.private_key_file,
  173. args.algorithm))
  174. client.tls_set(ca_certs=args.ca_certs, tls_version=ssl.PROTOCOL_TLSv1_2)
  175.  
  176. device = Device()
  177.  
  178. client.on_connect = device.on_connect
  179. client.on_publish = device.on_publish
  180. client.on_disconnect = device.on_disconnect
  181. client.on_subscribe = device.on_subscribe
  182.  
  183. client.connect(args.mqtt_bridge_hostname, args.mqtt_bridge_port)
  184.  
  185. client.loop_start()
  186.  
  187. # This is the topic that the device will publish telemetry events (temperature
  188. # data) to.
  189. mqtt_telemetry_topic = '/devices/{}/events'.format(args.device_id)
  190.  
  191. # Wait up to 5 seconds for the device to connect.
  192. device.wait_for_connection(5)
  193.  
  194. # Update and publish temperature readings at a rate of SENSOR_POLL per second.
  195. for _ in range(args.num_messages):
  196. device.update_sensor_data()
  197.  
  198. # Time
  199. sendtime = '"datetime":"{}"'.format(datetime.datetime.now().strftime("%Y-%m-%d"" ""%H:%M:%S.%f"))
  200. # Payload
  201. payload = '{{''{},{},{},{},{},{},{},{}''}}'.format(device.temperature, device.sensortemperature_1,device.sensortemperature_2,device.lightsensor_lux,device.lightsensor_infrared,device.lightsensor_visible,device.lightsensor_full_spectrum,sendtime)
  202. # Message
  203. print('Payload: {}'.format(payload))
  204. # Publish, Sleep
  205. client.publish(mqtt_telemetry_topic, payload, qos=1)
  206. time.sleep(SENSOR_POLL)
  207.  
  208. client.disconnect()
  209. client.loop_stop()
  210. print('Finished loop successfully. Goodbye!')
  211. main()
  212.  
  213. if __name__ == '__main__':
  214. main()
Add Comment
Please, Sign In to add comment