This program is meant to read a moisture sensor attached to an Arduino UNO board via USB to a Raspberry Pi3 which broadcasts it over MQTT.
I am looking for any constructive criticism.
import serial
import time
import RPi.GPIO as GPIO
import paho.mqtt.client as mqtt
def main():
try:
while 1:
sendMQTT(read_sensor("clean"),"Planty/moisture_readings")
alerts()
except KeyboardInterrupt:
print "\n\nExiting via Keyboard Interrupt"
def debugger():
# This is just to test each reading
moisture_clean = read_sensor("clean")
output = "Soil Moisture is " + str(moisture_clean) + "%"
moisture_raw_adjusted = read_sensor("raw_adjusted")
output += "\nRaw_adjusted is " + str(moisture_raw_adjusted)
moisture_raw = read_sensor("raw")
output += "\nRaw is " + str(moisture_raw)
sendMQTT(output, "Planty/debug")
def alerts():
# Generates alerts that are humanly readable for certain moisture thresholds
moisture = read_sensor("clean")
alert_low = 10
alert_high = 90
alert_threshold = 30
if moisture <= alert_low:
output = "**Moisture is below 10%**"
if moisture <= alert_threshold and moisture > alert_low:
output = "***Moisture is between 10%` and 30%, watering***"
relay(14)
time.sleep(60*1)
if moisture >= alert_high:
output = "***Moisture is above 90%***"
sendMQTT(output, "Planty/alerts")
def read_sensor(choice):
# Read analog moisture data from moisture probe via Arduino UNO plugged into
# the RPi via USB
min = 330
max = 970
ser = serial.Serial('/dev/ttyACM0', 9600)
#Line below handles the problem of the Arduino returning more than 1 reading
raw_data = int(str.split(ser.readline())[0])
if choice == "raw":
moisture = raw_data
#Stop readings going over or under 0 or 100%
if raw_data < min:
raw_data = min
if raw_data > max:
raw_data = max
if choice == "raw_adjusted":
moisture = raw_data
if choice == "clean":
#Get moisture as % reading
moisture = int(round(100-(100/float(max-min))*(raw_data-min), 0))
return moisture
def relay(pin):
# Turn on relay via PIN.HIGH
try:
GPIO.setmode(GPIO.BCM)
GPIO.setwarnings(False)
GPIO.setup(pin,GPIO.OUT,initial=1)
sendMQTT("Turning Relay1 ON", "Planty/relay")
GPIO.output(pin,0)
time.sleep(5)
sendMQTT("Turning Relay1 OFF", "Planty/relay")
GPIO.output(pin,1)
finally:
GPIO.cleanup()
def sendMQTT(output, topic):
# Publish to MQTT for given topic
host = "MQTTBroker.local"
user = "user"
password = "password"
mqttc = mqtt.Client()
mqttc.username_pw_set(user, password)
mqttc.connect(host, 1883)
mqttc.publish(topic, output)
if __name__ == '__main__':
main()