Konubinix' opinionated web of thoughts

IOT Heart Again, With Micropython

Fleeting

IOT heart again, with micropython on my wemos/lolin d1 (some ESP8266)

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 esp
import gc
import ntptime
import requests

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


# * SLEEP_LIGHT - light sleep, shuts down the WiFi Modem circuit and suspends the processor periodically.
# The system enters the set sleep mode automatically when possible.
esp.sleep_type(esp.SLEEP_LIGHT)

leds = {
    "left": neopixel.NeoPixel(machine.Pin(4), 5),
    "right": neopixel.NeoPixel(machine.Pin(5), 5),
}

def run_command(name, command):
    r, g, b, l = command
    now = time.localtime()
    h = now[3]
    m = now[4]
    print(f"{h:02d}:{m:02d} - {gc.mem_free()}: {name}: Running command: {command}")
    command = (int(r*l/255),int(g*l/255),int(b*l/255),)
    led = leds[name]
    led.fill(command)
    led.write()

class Connection:
    def __init__(self):
        self.connect()

    def reconnect(self):
        self.disconnect()
        self.connect()

    def disconnect(self):
        self.wlan.disconnect()

    def connect(self):
        run_command("left", [0, 0, 0, 0])
        run_command("right", [0, 0, 0, 0])
        self.wlan = network.WLAN(network.STA_IF)
        self.wlan.active(True)
        self.wlan.connect()
        run_command("left", [0, 50, 0, 50])
        run_command("right", [0, 0, 0, 0])
        while not self.wlan.isconnected():
            time.sleep(1)
        run_command("left", [0, 0, 0, 0])
        run_command("right", [0, 50, 0, 50])

        try:
            ntptime.settime()
        except OSError as e:
            requests.post(
                "http://home/ntfy/iotheart",
                headers={"title": "iot heart error"},
                data=f"""{e}
while trying to set the time""")

    @property
    def isconnected(self):
        return self.wlan.status() == network.STAT_GOT_IP

connection = Connection()
connection.connect()


def try_get():
    try:
        return requests.get("http://home/iotheart/get2").json()
    except Exception as e:
        print(f"{e}")
        return None

def step():
    print("Do step")
    if not connection.isconnected:
        connection.reconnect()
    commands = try_get()
    if commands is None:
        commands = {
            "left": [50, 0, 0, 50],
            "right": [50, 0, 0, 50],
        }
        connection.reconnect()

    run_command("left", commands["left"])
    run_command("right", commands["right"])

initialsleeptime = 1

sleeptime = initialsleeptime

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

    print(f"Waiting for {sleeptime}s")
    machine.lightsleep(sleeptime * 1000)
EOF

webrepl_cli.py -p 0000 /tmp/main.py ${ip}:main.py
op:put, host:iotheart, port:8266, passwd:0000.
/tmp/main.py -> main.py
Remote WebREPL version: (1, 25, 0)
Sent 0 of 3207 bytes
Sent 1024 of 3207 bytes
Sent 2048 of 3207 bytes
Sent 3072 of 3207 bytes
Sent 3207 of 3207 bytes
spawn webrepl_cli.py -p 0000 iotheart
op:repl, host:iotheart, port:8266, passwd:0000.
Remote WebREPL version: (1, 25, 0)
Use Ctrl-] to exit this shell

>>>

cat<<EOF > /tmp/app.py

EOF

webrepl_cli.py -p 0000 /tmp/app.py ${ip}:app.py