Wednesday, October 11, 2023

redesigning python code to fade out smart lamps

 The smart lamp controls with a python flask app as in a previous post had some issues. 

  1. There was no feedback to the user in case the mobile browser lost connection or the python app lost connection to the smart lamps.

  2. The raspberry pi was showing slightly excessive cpu usage, with the lightning bolt icon on the top right corner appearing sometimes.

  3. There was no way to stop the python loop in case it was taking too long to complete.

  4. The way I'd written it, if the /fadein url was the last used one before mobile browser disconnect, the next time I opened the mobile browser, the lights would come on! due to the mobile browser retrying that page.

So, thought of redesigning the code. 

Found that RaspController has a section for running user-defined custom commands. Since both KR and I use RaspController on our phones, the simplest solution seemed to be to just use a python script to do the fadeout of the lights, and show the output of the script on the terminal using RaspController. 

And that seems to be working fine. 

Since the code on github has the device ids and local keys, instead of taking the time to modify the code to put the private info in separate files etc, I'll just copy-paste the current state of the code here.

import tinytuya, sys
from time import sleep

def moveup(lines):
        for _ in range(lines):
            sys.stdout.write("\x1b[A")

nowait = bool(1);

# Connect to Device
d = tinytuya.BulbDevice(
    dev_id='changeme',
    address='our.ip.2',      # Or set to 'Auto' to auto-discover IP address
    local_key="changeme12",
    version=3.5)
print("Connected to d")
b = tinytuya.BulbDevice(
    dev_id='deviceidchange',
    address='our.ip.1',      # Or set to 'Auto' to auto-discover IP address, but that takes 10 sec
    local_key="changeme34",
    version=3.4)
print("Connected to b")

def fadeout():
    d.set_brightness_percentage(100, nowait)
    sleep(1)
    b.set_brightness_percentage(100, nowait)
    sleep(1)
    d.turn_on()
    print("d turn on")
    sleep(1)
    b.turn_on()
    print("b turn on")
    sleep(1)
    i = 100
    while i > 10:
      d.set_brightness_percentage(i, nowait)
      print("d brightness {0:3d}".format(i))
      b.set_brightness_percentage(i, nowait)
      print("b brightness {0:3d}".format(i), end='\r')
      moveup(1)
      sleep(1)
      i -= 10
    i = 10
    while i > 11:
      d.set_brightness_percentage(i, nowait)
      print("d brightness {0:3d}".format(i))
      b.set_brightness_percentage(i, nowait)
      print("b brightness {0:3d}".format(i), end='\r')
      moveup(1)
      i -= 1
    d.turn_off()
    print("d turned off.          ")
    b.turn_off()
    print("b turned off.          ")

fadeout() 

No comments:

Post a Comment