Konubinix' opinionated web of thoughts

IOT Heart Again, With Micropython

Fleeting

IOT heart again, with micropython

See how to play with the wemos d1.

cat<<EOF > /tmp/main.py
#!/usr/bin/env python3
# -*- coding:utf-8 -*-
import time

import machine
import neopixel
import network
import ntptime
import requests

led = machine.Pin(2, machine.Pin.OUT)
led.off()  # on
time.sleep(2)
led.on()  # off

wlan = network.WLAN()

left = neopixel.NeoPixel(machine.Pin(4), 5)
right = neopixel.NeoPixel(machine.Pin(5), 5)

def run_command(led, command, name):
    r, g, b, l = command
    command = (int(r*l/255),int(g*l/255),int(b*l/255),)
    print(f"{name}: Running command: {command}")
    led.fill(command)
    led.write()

def step():
    if wlan.isconnected():
        commands = requests.get("http://192.168.1.46:9696/get2").json()
    else:
        commands = {
            "left": [100, 100, 100, 100],
            "right": [100, 100, 100, 100],
        }
    run_command(left, commands["left"], "left")
    run_command(right, commands["right"], "right")


ntptime.settime()

initialsleeptime = 1

sleeptime = initialsleeptime

while True:
    try:
        step()
        sleeptime = initialsleeptime
    except Exception as e:
        sleeptime *= 2
        if sleeptime > 3600:
            sleeptime = 3600
        try:
            now = time.localtime()
            h = now[3]
            m = now[4]
            requests.post(
                "http://192.168.1.46:9705/n",
                headers={"title": f"{h:02d}:{m:02d} iot heart error"},
                data=f"""{e}
will wait for {sleeptime}s""")
        except Exception as e2:
            print(f"Could not notify: {e2}")
    time.sleep(sleeptime)
EOF

webrepl_cli.py -p 0000 /tmp/main.py 192.168.1.230:main.py
op:put, host:192.168.1.230, port:8266, passwd:0000.
/tmp/main.py -> main.py
Remote WebREPL version: (1, 23, 0)
Sent 0 of 1532 bytes
Sent 1024 of 1532 bytes
Sent 1532 of 1532 bytes