Advertisement
Guest User

Untitled

a guest
Nov 13th, 2016
115
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 5.88 KB | None | 0 0
  1. import serial
  2. import time
  3. import RPi.GPIO as GPIO
  4. import paho.mqtt.client as mqtt
  5. import logging
  6. import sys
  7.  
  8. logging.basicConfig(filename='planty.log', level=logging.ERROR)
  9.  
  10. MIN = 330
  11. MAX = 970
  12. ALERT_LOW = 10
  13. ALERT_HIGH = 90
  14. ALERT_THRESHOLD = 30
  15. MQTT_HOST = 'hostname
  16. MQTT_PORT = 1883
  17. MQTT_USER = 'root'
  18. MQTT_PASS = 'root'
  19. PIN_POT = {7:0}
  20.  
  21.  
  22. def read_sensor():
  23. """
  24. Read analog moisture reading from moisture probe via Arduino via USB.
  25. try exists as Arduino sometimes passes bogus readings which causes
  26. IndexErrors
  27. """
  28. try:
  29. ser = serial.Serial('/dev/ttyACM0', 9600)
  30. raw_reading = ser.readline().strip()
  31. print raw_reading
  32. if 8 > len(raw_reading) >= 5:
  33. # If reading is valid length do:
  34. reading = {'pot': int(raw_reading.split(':')[1]),
  35. 'moisture_raw': int(raw_reading.split(':')[0])}
  36. else:
  37. reading = {'invalid':1}
  38. except: # catch *all* exceptions
  39. e = 'Error:%s Reading: %s' % (str(sys.exc_info()[0]), raw_reading)
  40. logging.error(e)
  41. reading = {'invalid':1}
  42. finally:
  43. ser.close()
  44. return reading
  45.  
  46.  
  47. def validate(data):
  48. check = 0
  49. try:
  50. if 'invalid' not in data:
  51. # if there is no invalid key
  52. # print 'Invlaid key not detected'
  53. if 1024 > data['moisture_raw'] > 0:
  54. # Valid moisture reading
  55. # print 'Valid moisture reading'
  56. if data['pot'] in PIN_POT:
  57. # Valid serial reading of pin
  58. # print 'PIN_POT key exists'
  59. check = 1
  60. else:
  61. print 'PIN_POT key does not exist'
  62. else:
  63. print 'Invalid moisture reading'
  64. else:
  65. print 'Invalid key detected'
  66. except:
  67. e = 'Error:%s Reading: %s' % (str(sys.exc_info()[0]), raw_reading)
  68. logging.error(e)
  69. finally:
  70. return check
  71.  
  72.  
  73. def process_raw_data():
  74. """
  75. Calls read_sensor(), checks if the reading is valid (sometimes over 1023 or null)
  76. Assigns the correct Pot for the Pin used via PIN_POT dictionary
  77. Normalizes the reading if it falls outside the ranges
  78. """
  79. valid = 0
  80. while valid == 0:
  81. data = read_sensor()
  82. valid = validate(data)
  83. data['pot'] = PIN_POT[data['pot']]
  84. # Set moisture_adj
  85. if data['moisture_raw'] < MIN:
  86. data['moisture_adj'] = MIN
  87. elif data['moisture_raw'] > MAX:
  88. data['moisture_adj'] = MAX
  89. else:
  90. data['moisture_adj'] = 0
  91. data['moisture'] = moisture(data['moisture_raw'])
  92. print data
  93. return data
  94. data['moisture'] = moisture(data['moisture_adj'])
  95. print data
  96. return data
  97.  
  98.  
  99. def moisture(data):
  100. return int(round(100-(100/float(MAX-MIN))*(data-MIN), 0))
  101.  
  102.  
  103. def pub_mqtt(output, topic):
  104. """Publish to MQTT for given topic"""
  105. mqtt_client = mqtt.Client()
  106. mqtt_client.username_pw_set(MQTT_USER, MQTT_PASS)
  107. mqtt_client.connect(MQTT_HOST, MQTT_PORT)
  108. mqtt_client.publish(topic, output)
  109.  
  110.  
  111. def alerts(data):
  112. """Generates alerts that are humanly readable for certain moisture thresholds"""
  113. if data['moisture'] <= ALERT_LOW:
  114. output = 'LOW ALERT'
  115. relay(data['pot'])
  116. time.sleep(60*5)
  117. elif ALERT_LOW > data['moisture'] <= ALERT_THRESHOLD:
  118. output = 'THRESHOLD ALERT'
  119. relay(data['pot'])
  120. time.sleep(60*5)
  121. elif data['moisture'] >= ALERT_HIGH:
  122. output = 'HIGH ALERT'
  123. else:
  124. return
  125. pub_mqtt(output, 'Planty/alerts')
  126.  
  127.  
  128. def relay(pin):
  129. try:
  130. GPIO.setmode(GPIO.BCM)
  131. GPIO.setwarnings(False)
  132. GPIO.setup(pin, GPIO.OUT, initial=1)
  133. # Message pin on
  134. pub_mqtt(str(pin) + ':1', 'Planty/relay')
  135. GPIO.output(pin, 0)
  136. time.sleep(5)
  137. # Message pin off
  138. pub_mqtt(str(pin) + ':0', 'Planty/relay')
  139. GPIO.output(pin, 1)
  140. finally:
  141. GPIO.cleanup()
  142.  
  143.  
  144. def debugger(data):
  145. """This is just to test each reading if there are issues"""
  146. output ='n=====DEBUG LOG=====n'
  147. 'raw is: {}n'
  148. 'raw_adjusted is: {}n'
  149. 'soil moisture is: {}%n'
  150. .format(data['moisture_raw'],
  151. data['moisture_adj'],
  152. data['moisture'])
  153. pub_mqtt(output, 'Planty/debug')
  154.  
  155.  
  156. def main():
  157. while 1:
  158. data = process_raw_data()
  159. output = '%d:%d:%d:%d'
  160. % (data['pot'],
  161. data['moisture_raw'],
  162. data['moisture_adj'],
  163. data['moisture'])
  164. pub_mqtt(output, 'Planty/moisture_readings')
  165. # alerts(data)
  166. # debugger(data)
  167.  
  168.  
  169. if __name__ == '__main__':
  170. main()
  171.  
  172. import paho.mqtt.client as mqtt
  173. from influxdb import InfluxDBClient
  174.  
  175. INFLUX_HOST = 'hostname'
  176. INFLUX_PORT = 8086
  177. INFLUX_DB = 'Planty'
  178. INFLUX_USER = 'root'
  179. INFLUX_PASS = 'root'
  180. MQTT_HOST = 'hostname'
  181. MQTT_PORT = 1883
  182. MQTT_USER = 'root'
  183. MQTT_PASS = 'root'
  184. MQTT_TOPIC = 'Planty/moisture_readings'
  185.  
  186.  
  187. def on_message(client, userdata, msg):
  188. raw_message = msg.payload.split(':')
  189. data = {}
  190. print raw_message
  191. data['pot'] = raw_message[0]
  192. data['moisture_raw'] = raw_message[1]
  193. data['moisture_adj'] = raw_message[2]
  194. data['moisture'] = raw_message[3]
  195. json_body = [
  196. {
  197. "measurement": "moisture_readings",
  198. "tags": {
  199. "pot": data['pot']
  200. },
  201. "fields": {
  202. "moisture_raw": data['moisture_raw'],
  203. "moisture_adj": data['moisture_adj'],
  204. "moisture": data['moisture']
  205. }
  206. }
  207. ]
  208. client = InfluxDBClient(INFLUX_HOST,INFLUX_PORT, INFLUX_USER, INFLUX_PASS, INFLUX_DB)
  209. client.write_points(json_body)
  210.  
  211.  
  212. def main():
  213. mqttc = mqtt.Client()
  214. mqttc.username_pw_set(MQTT_USER, MQTT_PASS)
  215. mqttc.connect(MQTT_HOST, MQTT_PORT)
  216. mqttc.subscribe(MQTT_TOPIC)
  217. mqttc.on_message = on_message
  218. mqttc.loop_forever()
  219.  
  220. if __name__ == '__main__':
  221. main()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement