0

This code will be working fine until it tries to run LightsOn() or LightsOff() which it does successfully, but then after the lights turn on or off, nothing else happens and everything stops running. There is no error, there are just no prints in the terminal and it doesn't work anymore.

Here is the code:

from pyHS100 import Discover
import requests
import time
import traceback
import asyncio
from kasa import SmartStrip

dev = SmartStrip("192.168.7.105")
url = 'https://awesomebits.online/SmartHome/controlLights/light_status.txt'
stat = ''
previous_content = None

# Discover devices
discovered_devices = Discover.discover().values()
bedroom_lights = next((dev for dev in discovered_devices if dev.alias == "Bens Bedroom lights"), None)

if bedroom_lights is None:
    print("Bens Bedroom lights not found.")

async def LightsOn():
    await dev.turn_on()

async def LightsOff():
    await dev.turn_off()

def my_function():
    global previous_content, stat  # Declare previous_content and stat as global variables
    bedroom_lights_status = bedroom_lights.is_on if bedroom_lights else None

    if bedroom_lights_status is not None:
        print()
    else:
        print("Bens Bedroom lights not found.")

    if bedroom_lights_status is False:
        print("lights off")
        stat = 0

    if bedroom_lights_status is True:
        print("lights on")
        stat = 1

    current_content = requests.get(url).text.strip().lower()
    print(current_content)

    if current_content != previous_content:
        # Content has changed, log the new status
        if current_content == 'on' and stat == 0:
            print('The lights are on')
            asyncio.run(LightsOn())
            print("coolio")
        elif current_content == 'off' and stat == 1:
            print('The lights are off')
            try:
                asyncio.run(LightsOff())
            except Exception as e:
                print('An error occurred in turnOff.py:', e)
                traceback.print_exc()
        else:
            print('Invalid data')

        previous_content = current_content

while True:
    my_function()
    time.sleep(0.5)
mkrieger1
  • 19,194
  • 5
  • 54
  • 65
john deere
  • 34
  • 4

0 Answers0