import time from umqttsimple import MQTTClient import ubinascii import machine import micropython import network import esp from machine import Pin from utime import sleep_ms from neopixel import NeoPixel esp.osdebug(None) import gc gc.collect() ssid = 'your_ssid' password = 'your_password' mqtt_server = 'mqtt_server_ip' #EXAMPLE IP ADDRESS #mqtt_server = '192.168.1.144' client_id = ubinascii.hexlify(machine.unique_id()) topic_sub = b'notification' topic_pub = b'power/power_03/cmnd/Power' last_message = 0 message_interval = 5 counter = 0 button = Pin(14, Pin.IN, Pin.PULL_UP) # D5 PIXELS = 10 np = NeoPixel(Pin(12, Pin.OUT), PIXELS) # Pixel on pin 22 (D6), lenght=10 station = network.WLAN(network.STA_IF) station.active(True) station.connect(ssid, password) while station.isconnected() == False: pass print('Connection successful') print(station.ifconfig()) def check_pin(): if not button.value(): print("Woha! Someone pressed the button!") return(1) else: return(0) def translate(value, leftMin, leftMax, rightMin, rightMax): ''' Translates a value from one range to another. Borrowed from: https://stackoverflow.com/questions/1969240/mapping-a-range-of-values-to-another ''' # Figure out how 'wide' each range is leftSpan = leftMax - leftMin rightSpan = rightMax - rightMin # Convert the left range into a 0-1 range (float) valueScaled = float(value - leftMin) / float(leftSpan) # Convert the 0-1 range into a value in the right range. return int(rightMin + (valueScaled * rightSpan)) def sub_cb(topic, msg): print((topic, msg)) def connect_and_subscribe(): global client_id, mqtt_server, topic_sub client = MQTTClient(client_id, mqtt_server) client.set_callback(sub_cb) client.connect() client.subscribe(topic_sub) print('Connected to %s MQTT broker, subscribed to %s topic' % (mqtt_server, topic_sub)) return client def restart_and_reconnect(): print('Failed to connect to MQTT broker. Reconnecting...') time.sleep(10) machine.reset() try: client = connect_and_subscribe() except OSError as e: restart_and_reconnect() POWERSTATE = False WATER_TIME = 120 START_TIME = time.time() client.publish(topic_pub, b'OFF') while True: try: new_message = client.check_msg() if new_message != 'None': # Check for button push if check_pin(): START_TIME = time.time() client.publish(topic_pub, b'ON') POWERSTATE = True sleep_ms(500) # Check if timer has run out if (time.time() - START_TIME) > WATER_TIME: if POWERSTATE: client.publish(topic_pub, b'OFF') print("Time is up.!") POWERSTATE = False #If water is running, show time left on LEDs if POWERSTATE: for i in range(PIXELS): np[i] = (0, 0, 0) #time_left = WATER_TIME - (time.time() - START_TIME) i = translate((time.time() - START_TIME), 0, WATER_TIME, 0, PIXELS-1) np[i] = (20,20,20) else: for i in range(PIXELS): np[i] = (0, 0, 0) np.write() except OSError as e: restart_and_reconnect()