Given the following code for a smart home system, find optimizations and other updates to made the system more robust:
import json
import tinytuya
import socket
from concurrent.futures import ThreadPoolExecutor
import time
import sys # For handling command-line arguments
import logging # For logging
def is_internet_available():
"""Check if the internet is available by attempting to connect to a local router."""
try:
socket.create_connection(("[Redacted IPAddress]", 53), timeout=5)
return True
except OSError:
return False
class Light:
"""Represents a smart light device."""
code
def __init__(self, id, ip, key, name, version):
self.name = name
self.id = id
self.ip = ip
self.key = key
self.version = version
self._initialize_device()
def _initialize_device(self):
"""Initialize the light's Tuya device."""
self.device = tinytuya.BulbDevice(self.id, self.ip, self.key)
self.device.set_version(self.version)
self.device.set_socketRetryLimit(2)
self.device.set_socketTimeout(2)
self.device.set_socketRetryDelay(0)
def update_address(self, ip):
"""Update the IP address of the light."""
self.ip = ip
self._initialize_device()
logger.info(f"Updated IP address for {self.name} to {self.ip}")
def status(self):
"""Fetch the current status of the light (on/off)."""
data = self.device.status()
if not data or 'dps' not in data:
raise ValueError(f"Invalid status data for {self.name}: {data}")
if '1' in data['dps']:
return data['dps']['1']
if '20' in data['dps']:
return data['dps']['20']
raise ValueError(f"Unexpected status format for {self.name}: {data}")
def set_status(self, on):
"""Set the status of the light (on/off)."""
try:
if on:
self.device.turn_on(nowait=True)
logger.info(f"{self.name} turned ON")
else:
self.device.turn_off(nowait=True)
logger.info(f"{self.name} turned OFF")
except Exception as e:
logger.error(f"Error setting status for {self.name}: {e}")
Assistant
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
class DeviceSearcher:
"""Searches for devices broadcasting their presence on the network."""
code
def __init__(self):
self.to_search = {}
self.executor = ThreadPoolExecutor(max_workers=5)
self.executor.submit(self.find_devices, 3.3)
def search(self, device):
"""Add a device to the search list."""
if device.id not in self.to_search:
logger.info(f"Adding {device.name} to the search list.")
self.to_search[device.id] = device
def find_devices(self, version):
"""Listen for devices broadcasting over the network."""
client = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP)
client.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1)
port = tinytuya.UDPPORT if version == 3.1 else tinytuya.UDPPORTS
client.bind(("", port))
client.settimeout(5)
while True:
try:
data, addr = client.recvfrom(4048)
ip = addr[0]
result = json.loads(tinytuya.decrypt_udp(data[20:-8]))
gwId = result.get("gwId")
if gwId in self.to_search:
device = self.to_search.pop(gwId)
self.executor.submit(device.update_address, ip)
except socket.timeout:
continue
except Exception as e:
logger.error(f"Error processing UDP broadcast: {e}")
class SmartHomeLights:
"""Main class for managing smart home lights."""
code
def __init__(self, config_file, no_off=False):
self.devices_config = self._load_config(config_file)
self.lights = {}
self.router = None
self.inputs = self.devices_config.get("inputs", {})
self.device_searcher = DeviceSearcher()
self.executor = ThreadPoolExecutor(max_workers=10)
self._initialize_devices()
self._initialize_router()
self.rooms_lights_map = self._map_rooms_to_lights()
if not no_off:
self.executor.submit(self.turn_off_on_init)
def _load_config(self, config_file):
"""Load the configuration file."""
with open(config_file, 'r') as f:
return json.load(f)
def _initialize_devices(self):
"""Initialize all light devices from the configuration."""
for device_data in self.devices_config.get("devices", []):
self.executor.submit(self._initialize_light, device_data)
def _initialize_router(self):
"""Initialize the Zigbee router, if configured."""
router_data = self.devices_config.get("router")
if not router_data:
logger.error("Zigbee router not configured.")
return
self.router = tinytuya.Device(
router_data['id'], router_data['ip'], router_data['key']
)
self.router.set_version(3.3)
self.router.set_socketPersistent(True)
def _initialize_light(self, device_data):
"""Initialize a single light device."""
light = Light(
device_data['id'], device_data['ip'], device_data['key'],
device_data['name'], float(device_data['ver'])
)
self.lights[device_data['name']] = light
self.device_searcher.search(light)
def _map_rooms_to_lights(self):
"""Map rooms to their respective light devices."""
rooms_lights_map = {}
for device_data in self.devices_config.get("devices", []):
for room in device_data['rooms']:
rooms_lights_map.setdefault(room, []).append(device_data['name'])
return rooms_lights_map
def update_lights(self):
"""Update the status of all lights."""
for light_name in list(self.lights.keys()):
self.get_light_status(light_name)
def turn_off_on_init(self):
"""Turn off all lights during initialization if the internet is available."""
while not is_internet_available():
time.sleep(1)
time.sleep(20)
for light in self.lights.values():
light.set_status(False)
logger.info("All lights have been turned off on initialization.")
def get_light_status(self, light_name):
"""Get the status of a specific light."""
light = self.lights.get(light_name)
if not light:
logger.warning(f"Light {light_name} was not initialized")
return None
try:
return light.status()
except Exception as e:
logger.error(f"Error getting status for {light_name}: {e}")
self.device_searcher.search(light)
return False
def set_light_status(self, light_name, on):
"""Set the status of a specific light."""
light = self.lights.get(light_name)
if not light:
logger.warning(f"Light {light_name} was not initialized")
return
try:
light.set_status(on)
except Exception as e:
logger.error(f"Error setting status for {light_name}: {e}")
def toggle_room_lights(self, room_name):
"""Toggle the lights in a specific room."""
lights_in_room = self.rooms_lights_map.get(room_name, [])
if not lights_in_room:
logger.warning(f"No lights initialized in {room_name}.")
return
first_light_status = self.get_light_status(lights_in_room[0])
if first_light_status is None:
logger.warning(f"Could not determine current status for lights in {room_name}")
return
target_status = not first_light_status
logger.info(f"Toggling lights in {room_name} to {'on' if target_status else 'off'}")
for light_name in lights_in_room:
self.set_light_status(light_name, target_status)
def run(self):
"""Run the main Zigbee router listener for handling input events."""
if not self.router:
logger.error("Zigbee router not configured.")
return
self.router.set_socketTimeout(5)
def _run():
payload = self.router.generate_payload(tinytuya.HEART_BEAT)
while True:
try:
self.router.send(payload)
data = self.router.receive()
if not data or "cid" not in data or "dps" not in data:
continue
cid = data["cid"]
input_config = self.inputs.get(cid, {})
button = list(data["dps"])[0]
press = data["dps"][button]
if button in input_config and str(press) in input_config[button]:
room_to_control = input_config[button][str(press)]
logger.info(f"Button press detected, controlling room: {room_to_control}")
self.toggle_room_lights(room_to_control)
payload = self.router.generate_payload(tinytuya.HEART_BEAT)
except Exception as e:
logger.error(f"Error in switch listener: {e}")
time.sleep(0.1)
self.executor.submit(_run)
if name == "main":
# Check for the "no_off" argument
no_off = "no_off" in sys.argv
code
# Initialize the SmartHomeLights system
smarthome = SmartHomeLights('devices.json', no_off=no_off)
smarthome.run()
try:
while True:
time.sleep(30)
logger.info("Updating lights...")
smarthome.update_lights()
logger.info("Lights updated!")
except KeyboardInterrupt:
logger.info("Exiting SmartHomeLights...")
Based on the provided code and TinyTuya repository context, here are several optimizations and improvements to make the system more robust:
Better Error Handling and Retries:
python
def status(self):
"""Fetch the current status of the light with retries."""
retries = 3
for attempt in range(retries):
try:
data = self.device.status()
if not data:
raise ValueError(f"Empty status data for {self.name}")
if 'Error' in data:
raise ValueError(f"Error in status data: {data['Error']}")
if 'dps' not in data:
raise ValueError(f"No 'dps' in status data: {data}")
# Check for both common DPS keys
for key in ('1', '20'):
if key in data['dps']:
return data['dps'][key]
raise ValueError(f"No valid status key found in: {data}")
except Exception as e:
if attempt == retries - 1:
raise
logger.warning(f"Retry {attempt + 1}/{retries} for {self.name}: {e}")
time.sleep(1)
class SmartHomeLights:
def __init__(self, config_file, no_off=False):
self.running = True
self.executors = []
# ... rest of initialization ...
def shutdown(self):
"""Graceful shutdown of all components."""
logger.info("Initiating shutdown sequence...")
self.running = False
# Shutdown device searcher
if [Redacted Person](self, 'device_searcher'):
self.device_searcher.shutdown()
# Close router connection
if self.router:
try:
self.router.close()
except:
pass
# Shutdown thread pools
for executor in self.executors:
executor.shutdown(wait=True)
logger.info("Shutdown complete")
Better Device Discovery:
python
class DeviceSearcher:
def __init__(self):
self.running = True
self.to_search = {}
self.executor = ThreadPoolExecutor(max_workers=5)
self.found_devices = {}
self.last_seen = {}
def find_devices(self, version):
"""Enhanced device discovery with multiple protocol support."""
ports = [tinytuya.UDPPORT, tinytuya.UDPPORTS, tinytuya.UDPPORTAPP]
sockets = []
for port in ports:
client = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP)
client.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1)
client.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
client.bind(("", port))
client.settimeout(5)
sockets.append(client)
while self.running:
for client in sockets:
try:
data, addr = client.recvfrom(4048)
ip = addr[0]
result = json.loads(tinytuya.decrypt_udp(data[20:-8]))
gwId = result.get("gwId")
if [Redacted Person]:
self.last_seen[gwId] = time.time()
if gwId in self.to_search:
device = self.to_search[gwId]
if ip != device.ip:
self.executor.submit(device.update_address, ip)
except socket.timeout:
continue
except Exception as e:
logger.error(f"Error in device discovery: {e}")
Health Monitoring:
python
def monitor_system_health(self):
"""Monitor system health and connection status."""
while self.running:
try:
# Check internet connectivity
internet_available = is_internet_available()
# Check router health
router_healthy = False
if self.router:
try:
self.router.status()
router_healthy = True
except:
logger.error("Router connection lost")
self._initialize_router()
# Check device health
for light in self.lights.values():
try:
if time.time() - self.device_searcher.last_seen.get(light.id, 0) > 300:
logger.warning(f"Device {light.name} hasn't been seen for 5 minutes")
self.device_searcher.search(light)
except Exception as e:
logger.error(f"Error checking device health: {e}")
time.sleep(60) # Check every minute
except Exception as e:
logger.error(f"Error in health monitoring: {e}")
time.sleep(5)
Main Loop Enhancement:
python
if __name__ == "__main__":
import signal
def signal_handler(signum, frame):
logger.info("Received shutdown signal")
smarthome.shutdown()
sys.exit(0)
signal.signal(signal.SIGINT, signal_handler)
signal.signal(signal.SIGTERM, signal_handler)
# Parse command line arguments
import argparse
parser = argparse.ArgumentParser()
parser.add_argument('--config', default='devices.json', help='Configuration file path')
parser.add_argument('--no-off', action='store_true', help='Do not turn off lights on startup')
parser.add_argument('--debug', action='store_true', help='Enable debug logging')
args = parser.parse_args()
if args.debug:
logger.setLevel(logging.DEBUG)
try:
smarthome = SmartHomeLights(args.config, no_off=args.no_off)
smarthome.run()
smarthome.monitor_system_health() # Start health monitoring
while True:
time.sleep(30)
if smarthome.running:
logger.info("Updating lights status...")
smarthome.update_lights()
except Exception as e:
logger.error(f"Fatal error: {e}")
smarthome.shutdown()
sys.exit(1)
These improvements add:
Better error handling and retries
Persistent connections for better performance
Graceful shutdown handling
Enhanced device discovery across multiple protocols
System health monitoring
Improved command-line argument handling
Better logging and debugging capabilities
The system will be more resilient to network issues, device disconnections, and other common problems in smart home systems.