From 6ca643f35011fbcae0d906c40c19fe603e1af85d Mon Sep 17 00:00:00 2001 From: Rafal Szabat Date: Sun, 17 Nov 2024 18:50:44 +0100 Subject: [PATCH 01/14] Update LawnMower.py Deleted connect to device --- Devices/LawnMower.py | 8 -------- 1 file changed, 8 deletions(-) diff --git a/Devices/LawnMower.py b/Devices/LawnMower.py index 5bc53a9..24e16fe 100644 --- a/Devices/LawnMower.py +++ b/Devices/LawnMower.py @@ -5,14 +5,6 @@ class LawnMower(Device): def __init__(self, device_id: str, device_type: str): super().__init__(device_id, device_type) - def connect_to_device(self) -> None: - """ - Connect to the lawn mower device. - """ - if self.device_type != "LawnMower": - raise NotCompatibleDevice("Device type is not compatible.") - else: - print(f"Connected to Lawn Mower {self.device_id}") def load_device_info(self) -> dict: """ From 734f141d398202c8c1f4870a2f2e7da0dbef1e5d Mon Sep 17 00:00:00 2001 From: Rafal Szabat Date: Sun, 17 Nov 2024 18:51:50 +0100 Subject: [PATCH 02/14] Update WeatherStation.py Deleted connect to device --- Devices/WeatherStation.py | 9 +-------- 1 file changed, 1 insertion(+), 8 deletions(-) diff --git a/Devices/WeatherStation.py b/Devices/WeatherStation.py index 8867e4f..6008851 100644 --- a/Devices/WeatherStation.py +++ b/Devices/WeatherStation.py @@ -5,14 +5,7 @@ class WeatherStation(Device): def __init__(self, device_id: str, device_type: str): super().__init__(device_id, device_type) - def connect_to_device(self) -> None: - """ - Connect to the weather station device. - """ - if self.device_type != "WeatherStation": - raise NotCompatibleDevice("Device type is not compatible.") - else: - print(f"Connected to Weather Station {self.device_id}") + def load_device_info(self) -> dict: """ From 130da12539579e40f4239c5ca8dd0b0948ad80be Mon Sep 17 00:00:00 2001 From: Rafal Szabat Date: Sun, 17 Nov 2024 18:52:24 +0100 Subject: [PATCH 03/14] Update bulb.py Deleted connect to device --- Devices/bulb.py | 9 +-------- 1 file changed, 1 insertion(+), 8 deletions(-) diff --git a/Devices/bulb.py b/Devices/bulb.py index cfaa932..6fc32ba 100644 --- a/Devices/bulb.py +++ b/Devices/bulb.py @@ -5,14 +5,7 @@ class Bulb(Device): def __init__(self, device_id: str, device_type: str): super().__init__(device_id, device_type) - def connect_to_device(self) -> None: - """ - Connect to the bulb device. - """ - if self.device_type != "Bulb": - raise NotCompatibleDevice("Device type is not compatible.") - else: - print(f"Connected to Bulb {self.device_id}") + def load_device_info(self) -> dict: """ From 75de2d5b7b07d0295a00734b86b5bf67ae14177b Mon Sep 17 00:00:00 2001 From: Rafal Szabat Date: Sun, 17 Nov 2024 18:52:54 +0100 Subject: [PATCH 04/14] Update curtain.py Deleted connect to device --- Devices/curtain.py | 11 ++--------- 1 file changed, 2 insertions(+), 9 deletions(-) diff --git a/Devices/curtain.py b/Devices/curtain.py index eb6eb2a..4e3a5ca 100644 --- a/Devices/curtain.py +++ b/Devices/curtain.py @@ -4,14 +4,7 @@ class Curtain(Device): def __init__(self, device_id: str, device_type: str): super().__init__(device_id, device_type) - def connect_to_device(self) -> None: - """ - Connect to the curtain device. - """ - if self.device_type != "curtain": - raise NotCompatibleDevice - else: - print(f"Connected to curtain device {self.device_id}") + def get_current_position(self) -> float: """ @@ -48,4 +41,4 @@ def get_open_percentage(self) -> float: curtain = Curtain("curtain12345", "curtain") curtain.connect_to_device() print("Current Position:", curtain.get_current_position()) - print("Open Percentage:", curtain.get_open_percentage()) \ No newline at end of file + print("Open Percentage:", curtain.get_open_percentage()) From e4314b3abe13cb5b4c3aa5536ee36641eb750256 Mon Sep 17 00:00:00 2001 From: Rafal Szabat Date: Sun, 17 Nov 2024 18:53:48 +0100 Subject: [PATCH 05/14] Update thermostat.py Deleted conect to device --- Devices/thermostat.py | 8 -------- 1 file changed, 8 deletions(-) diff --git a/Devices/thermostat.py b/Devices/thermostat.py index 03bab32..078c8c7 100644 --- a/Devices/thermostat.py +++ b/Devices/thermostat.py @@ -4,14 +4,6 @@ class Thermostat(Device): def __init__(self, device_id: str, device_type: str): super().__init__(device_id, device_type) - def connect_to_device(self) -> None: - """ - Connect to the thermostat device. - """ - if self.device_type != "thermostat": - raise NotCompatibleDevice - else: - print(f"Connected to thermostat device {self.device_id}") def get_current_temperature(self) -> float: """ From 2ea8946fbb19fb2501d02d9e053e734a64a49ea0 Mon Sep 17 00:00:00 2001 From: Rafal Szabat Date: Sun, 17 Nov 2024 19:51:03 +0100 Subject: [PATCH 06/14] Delete Devices/LawnMower.py --- Devices/LawnMower.py | 121 ------------------------------------------- 1 file changed, 121 deletions(-) delete mode 100644 Devices/LawnMower.py diff --git a/Devices/LawnMower.py b/Devices/LawnMower.py deleted file mode 100644 index 24e16fe..0000000 --- a/Devices/LawnMower.py +++ /dev/null @@ -1,121 +0,0 @@ -from device import NotCompatibleDevice, Device, load_json, save_json - - -class LawnMower(Device): - def __init__(self, device_id: str, device_type: str): - super().__init__(device_id, device_type) - - - def load_device_info(self) -> dict: - """ - Load the JSON data and retrieve the information for this specific lawn mower. - - Returns the device's information as a dictionary, or an empty dictionary if not found. - """ - json_data = load_json() - for device in json_data.get('devices', []): - if device['device_id'] == self.device_id: - return device - return {} - - def get_name(self) -> str: - """ - Get the name of the lawn mower. - """ - return self.load_device_info().get('name', None) - - def get_brand(self) -> str: - """ - Get the brand of the lawn mower. - """ - return self.load_device_info().get('brand', None) - - def get_model(self) -> str: - """ - Get the model of the lawn mower. - """ - return self.load_device_info().get('model', None) - - def get_power(self) -> str: - """ - Get the current power status of the lawn mower (on or off). - """ - return self.load_device_info().get('status', {}).get('power', None) - - def get_battery_percent(self) -> int: - """ - Get the battery percentage of the lawn mower. - """ - return self.load_device_info().get('status', {}).get('battery_percent', None) - - def get_cutting_mode(self) -> str: - """ - Get the cutting mode of the lawn mower (e.g., auto or manual). - """ - return self.load_device_info().get('status', {}).get('cutting_mode', None) - - def get_cutting_height(self) -> int: - """ - Get the cutting height of the lawn mower in millimeters. - """ - return self.load_device_info().get('status', {}).get('cutting_height_mm', None) - - def get_current_area(self) -> float: - """ - Get the current area being mowed in square meters. - """ - return self.load_device_info().get('status', {}).get('current_area_m2', None) - - def get_total_cutting_time(self) -> int: - """ - Get the total cutting time in minutes. - """ - return self.load_device_info().get('status', {}).get('total_cutting_time_minutes', None) - - def get_location(self) -> str: - """ - Get the location of the lawn mower. - """ - return self.load_device_info().get('location', None) - - def get_last_updated(self) -> str: - """ - Get the last updated time of the lawn mower. - """ - return self.load_device_info().get('last_updated', None) - - def turn_on_off(self, state: str) -> None: - """ - Turn the lawn mower on or off and update its power state in the JSON data. - """ - if state.upper() not in ["ON", "OFF"]: - raise ValueError("State must be 'ON' or 'OFF'") - - json_data = load_json() - for device in json_data['devices']: - if device['device_id'] == self.device_id: - device['status']['power'] = state.upper() # Update power state - break - - save_json(json_data) - print(f"Lawn Mower {self.device_id} turned {state}") - - -if __name__ == "__main__": - lawn_mower_device = LawnMower("mower98765", "LawnMower") - lawn_mower_device.connect_to_device() - - - print("Name:", lawn_mower_device.get_name()) - print("Brand:", lawn_mower_device.get_brand()) - print("Model:", lawn_mower_device.get_model()) - print("Power:", lawn_mower_device.get_power()) - print("Battery Percentage:", lawn_mower_device.get_battery_percent()) - print("Cutting Mode:", lawn_mower_device.get_cutting_mode()) - print("Cutting Height (mm):", lawn_mower_device.get_cutting_height()) - print("Current Area (m²):", lawn_mower_device.get_current_area()) - print("Total Cutting Time (minutes):", lawn_mower_device.get_total_cutting_time()) - print("Location:", lawn_mower_device.get_location()) - print("Last Updated:", lawn_mower_device.get_last_updated()) - - lawn_mower_device.turn_on_off("off") From 1305d23552013d499afffb0f90570947318567e3 Mon Sep 17 00:00:00 2001 From: Rafal Szabat Date: Sun, 17 Nov 2024 19:54:04 +0100 Subject: [PATCH 07/14] Delete Devices/WeatherStation.py --- Devices/WeatherStation.py | 115 -------------------------------------- 1 file changed, 115 deletions(-) delete mode 100644 Devices/WeatherStation.py diff --git a/Devices/WeatherStation.py b/Devices/WeatherStation.py deleted file mode 100644 index 6008851..0000000 --- a/Devices/WeatherStation.py +++ /dev/null @@ -1,115 +0,0 @@ -from device import NotCompatibleDevice, Device, load_json, save_json - - -class WeatherStation(Device): - def __init__(self, device_id: str, device_type: str): - super().__init__(device_id, device_type) - - - - def load_device_info(self) -> dict: - """ - Load the JSON data and retrieve the information for this specific weather station. - - Returns the device's information as a dictionary, or an empty dictionary if not found. - """ - json_data = load_json() - for device in json_data.get('devices', []): - if device['device_id'] == self.device_id: - return device - return {} - - def get_name(self) -> str: - """ - Get the name of the weather station. - """ - return self.load_device_info().get('name', None) - - def get_brand(self) -> str: - """ - Get the brand of the weather station. - """ - return self.load_device_info().get('brand', None) - - def get_model(self) -> str: - """ - Get the model of the weather station. - """ - return self.load_device_info().get('model', None) - - def get_temperature(self) -> float: - """ - Get the current temperature in Celsius. - """ - return self.load_device_info().get('status', {}).get('temperature_c', None) - - def get_humidity(self) -> float: - """ - Get the current humidity percentage. - """ - return self.load_device_info().get('status', {}).get('humidity_percent', None) - - def get_pressure(self) -> float: - """ - Get the atmospheric pressure in hPa. - """ - return self.load_device_info().get('status', {}).get('pressure_hpa', None) - - def get_wind_speed(self) -> float: - """ - Get the current wind speed in km/h. - """ - return self.load_device_info().get('status', {}).get('wind_speed_kmh', None) - - def get_rainfall(self) -> float: - """ - Get the rainfall measurement in millimeters. - """ - return self.load_device_info().get('status', {}).get('rainfall_mm', None) - - def get_location(self) -> str: - """ - Get the location of the weather station. - """ - return self.load_device_info().get('location', None) - - def get_last_updated(self) -> str: - """ - Get the last updated timestamp of the weather station. - """ - return self.load_device_info().get('last_updated', None) - - def turn_on_off(self, state: str) -> None: - """ - Turn the weather station on or off and update its power state in the JSON data. - """ - if state.upper() not in ["ON", "OFF"]: - raise ValueError("State must be 'ON' or 'OFF'") - - json_data = load_json() - for device in json_data['devices']: - if device['device_id'] == self.device_id: - device['status']['power'] = state.upper() # Update power state - break - - save_json(json_data) - print(f"Weather Station {self.device_id} turned {state}") - - -if __name__ == "__main__": - weather_station_device = WeatherStation("weatherstation56789", "WeatherStation") - weather_station_device.connect_to_device() - - - print("Name:", weather_station_device.get_name()) - print("Brand:", weather_station_device.get_brand()) - print("Model:", weather_station_device.get_model()) - print("Temperature (C):", weather_station_device.get_temperature()) - print("Humidity (%):", weather_station_device.get_humidity()) - print("Pressure (hPa):", weather_station_device.get_pressure()) - print("Wind Speed (km/h):", weather_station_device.get_wind_speed()) - print("Rainfall (mm):", weather_station_device.get_rainfall()) - print("Location:", weather_station_device.get_location()) - print("Last Updated:", weather_station_device.get_last_updated()) - - weather_station_device.turn_on_off("off") From 068513ab9b955d49ede7630a48019c7eee039a71 Mon Sep 17 00:00:00 2001 From: Rafal Szabat Date: Sun, 17 Nov 2024 19:54:11 +0100 Subject: [PATCH 08/14] Delete Devices/bulb.py --- Devices/bulb.py | 106 ------------------------------------------------ 1 file changed, 106 deletions(-) delete mode 100644 Devices/bulb.py diff --git a/Devices/bulb.py b/Devices/bulb.py deleted file mode 100644 index 6fc32ba..0000000 --- a/Devices/bulb.py +++ /dev/null @@ -1,106 +0,0 @@ -from device import NotCompatibleDevice, Device, load_json, save_json - - -class Bulb(Device): - def __init__(self, device_id: str, device_type: str): - super().__init__(device_id, device_type) - - - - def load_device_info(self) -> dict: - """ - Load the JSON data and retrieve the information for this specific bulb. - - A dictionary containing the device's information, or an empty dictionary if not found. - """ - json_data = load_json() - for device in json_data.get('devices', []): - if device['device_id'] == self.device_id: - return device - return {} - - def get_name(self) -> str: - """ - Get the name of the bulb. - - The name of the bulb as a string, or None if not found. - """ - return self.load_device_info().get('name', None) - - def get_brand(self) -> str: - """ - Get the brand of the bulb. - - The brand of the bulb as a string, or None if not found. - """ - return self.load_device_info().get('brand', None) - - def get_model(self) -> str: - """ - Get the model of the bulb. - - The model of the bulb as a string, or None if not found. - """ - return self.load_device_info().get('model', None) - - def get_power(self) -> str: - """ - Get the current power status of the bulb (on or off). - - The power status as a string, or None if not found. - """ - return self.load_device_info().get('status', {}).get('power', None) - - def get_brightness(self) -> int: - """ - Get the current brightness level of the bulb. - - The brightness level as an integer, or None if not found. - """ - return self.load_device_info().get('status', {}).get('brightness', None) - - def get_color_temp(self) -> int: - """ - Get the color temperature of the bulb. - - The color temperature as an integer, or None if not found. - """ - return self.load_device_info().get('status', {}).get('color_temp', None) - - def get_rgb(self) -> dict: - """ - Get the RGB color settings of the bulb. - - A dictionary with 'red', 'green', 'blue' values, or None if not found. - """ - return self.load_device_info().get('status', {}).get('rgb', None) - - def turn_on_off(self, state: str) -> None: - """ - Turn the bulb on or off and update the power state in the JSON data. - - state: Desired state, "ON" or "OFF". - """ - if state.strip().upper() not in ["ON", "OFF"]: - raise ValueError("State must be 'ON' or 'OFF'") - - json_data = load_json() - for device in json_data['devices']: - if device['device_id'] == self.device_id: - device['status']['power'] = state.lower() # Update power state - break - save_json(json_data) - print(f"Bulb {self.device_id} turned {state}") - - -if __name__ == '__main__': - bulb_device = Bulb("1234567890abcdef", "Bulb") - bulb_device.connect_to_device() - print("Name:", bulb_device.get_name()) - print("Brand:", bulb_device.get_brand()) - print("Model:", bulb_device.get_model()) - print("Power:", bulb_device.get_power()) - print("Brightness:", bulb_device.get_brightness()) - print("Color Temperature:", bulb_device.get_color_temp()) - print("RGB:", bulb_device.get_rgb()) - bulb_device.turn_on_off("OFF") From 79bbd03c4da1a4f531466126b7122bb39e9fa88a Mon Sep 17 00:00:00 2001 From: Rafal Szabat Date: Sun, 17 Nov 2024 19:54:18 +0100 Subject: [PATCH 09/14] Delete Devices/curtain.py --- Devices/curtain.py | 44 -------------------------------------------- 1 file changed, 44 deletions(-) delete mode 100644 Devices/curtain.py diff --git a/Devices/curtain.py b/Devices/curtain.py deleted file mode 100644 index 4e3a5ca..0000000 --- a/Devices/curtain.py +++ /dev/null @@ -1,44 +0,0 @@ -from device import NotCompatibleDevice, Device, load_json - -class Curtain(Device): - def __init__(self, device_id: str, device_type: str): - super().__init__(device_id, device_type) - - - - def get_current_position(self) -> float: - """ - Get the current position of the curtain. - - Loads the JSON data, searches for the device with the matching device_id, - and returns the current position of the curtain. - - :return: The current position of the curtain as a float, or None if not found. - """ - json_data = load_json() - for device in json_data['devices']: - if device['device_id'] == self.device_id: - return float(device['status'].get('position', None)) - return None - - def get_open_percentage(self) -> float: - """ - Get the open percentage of the curtain. - - Loads the JSON data, searches for the device with the matching device_id, - and returns the open percentage of the curtain. - - :return: The open percentage of the curtain as a float, or None if not found. - """ - json_data = load_json() - for device in json_data['devices']: - if device['device_id'] == self.device_id: - return float(device['status'].get('open_percent')) - return None - - -if __name__ == "__main__": - curtain = Curtain("curtain12345", "curtain") - curtain.connect_to_device() - print("Current Position:", curtain.get_current_position()) - print("Open Percentage:", curtain.get_open_percentage()) From 964460adae1fe7c21b15d9093118bae5303b0685 Mon Sep 17 00:00:00 2001 From: Rafal Szabat Date: Sun, 17 Nov 2024 19:54:25 +0100 Subject: [PATCH 10/14] Delete Devices/device.py --- Devices/device.py | 166 ---------------------------------------------- 1 file changed, 166 deletions(-) delete mode 100644 Devices/device.py diff --git a/Devices/device.py b/Devices/device.py deleted file mode 100644 index c13fd1b..0000000 --- a/Devices/device.py +++ /dev/null @@ -1,166 +0,0 @@ -from abc import ABC -import json -from datetime import datetime -from colorama import Fore, init - -FILE_PATH = "../devices.json" -# Initialize Colorama (necessary for Windows compatibility) -init(autoreset=True) - -def load_json(file_path = FILE_PATH): - with open(file_path, 'r') as file: - data = json.load(file) - return data - -def save_json(data, file_path = FILE_PATH): - with open(file_path, 'w') as file: - json.dump(data, file, indent=4) - -class NotCompatibleDevice(Exception): - """ - Exception raised when device is not compatible - """ - -class Device(ABC): - """ - Abstract class for all devices - """ - - def __init__(self, device_id: str, device_type: str): - self.device_id = device_id - self.device_type = device_type - self.connected = False - - def connect_to_device(self) -> None: - """ - Connects to the device if compatible with the current class. - """ - print(f"{Fore.YELLOW}Connecting to device {self.device_id}...") - - if self.device_type != self.__class__.__name__.lower(): - print(f"{Fore.RED}Connection error: Device {self.device_id} is not compatible.") - raise NotCompatibleDevice - - self.connected = True - print(f"{Fore.GREEN}Successfully connected to device {self.device_id}.") - - def disconnect_from_device(self) -> None: - """ - Disconnects from the device if currently connected. - """ - print(f"{Fore.YELLOW}Disconnecting from device {self.device_id}...") - - if self.connected: - self.connected = False - print(f"{Fore.GREEN}Successfully disconnected from device {self.device_id}.") - else: - print(f"{Fore.YELLOW}Device {self.device_id} was not connected.") - - def turn_on_off(self, new_state: str) -> None: - """ - Updates the device's power status to the specified state. - - Loads the JSON data, finds the device by `device_id`, updates its 'power' status, - modifies the 'last_updated' timestamp, and saves the updated JSON data. - - Args: - new_state (str): The new power state to set for the device ('on' or 'off'). - """ - json_data = load_json() - - for device in json_data['devices']: - if device['device_id'] == self.device_id: - device['status']['power'] = new_state - self.modify_last_updated(json_data) - print(f"{Fore.GREEN}Device {self.device_id} power set to {new_state}.") - break - - def reboot(self) -> bool: - """ - Reboots the device by turning it off and then on, updating the 'last_updated' timestamp. - - Returns: - bool: True if reboot was successful, False otherwise. - """ - if not self.connected: - print(f"{Fore.RED}Cannot perform reboot. Device {self.device_id} is not connected.") - return False - - print(f"{Fore.YELLOW}Rebooting device {self.device_id}...") - - self.turn_on_off("off") - self.turn_on_off("on") - - print(f"{Fore.GREEN}Device {self.device_id} is back online.") - return True - - def get_status(self) -> str | None: - """ - Retrieves the status of the device if connected. - - Returns: - str | None: The status of the device in JSON format if connected, None otherwise. - """ - if not self.connected: - print(f"{Fore.RED}Cannot get status. Device {self.device_id} is not connected.") - return None - - print(f"{Fore.GREEN}Getting status for device {self.device_id}") - - json_data = load_json() - device_status = next( - (device['status'] for device in json_data['devices'] if device['device_id'] == self.device_id), - None - ) - - if device_status is not None: - return f"{Fore.BLUE}{json.dumps(device_status, indent=4)}" - else: - print(f"{Fore.RED}Status not found for device {self.device_id}.") - return None - - def change_device_name(self, name: str) -> bool: - """ - Changes the name of the device if connected. - - This method checks if the user is connected to the device, then loads the JSON data, finds the device by ID, - and updates the 'name' attribute. It also updates the 'last_updated' timestamp and saves the modified JSON data. - - Args: - name (str): The new name for the device. - - Returns: - bool: True if the name was successfully changed, False otherwise. - """ - if not self.connected: - print(f"{Fore.RED}Cannot change device name. Device {self.device_id} is not connected.") - return False - - json_data = load_json() - - for device in json_data['devices']: - if device['device_id'] == self.device_id: - device['name'] = name - self.modify_last_updated(json_data) - print(f"{Fore.GREEN}Device name changed successfully. New name: {name}") - return True - - print(f"{Fore.RED}Failed to change device name. Device {self.device_id} not found.") - return False - - def modify_last_updated(self, json_data) -> None: - """ - Updates the 'last_updated' timestamp for the device in the JSON data. - - Finds the device with the matching `device_id` and updates its 'last_updated' - field with the current date and time, then saves the updated JSON data. - - Args: - json_data (dict): The JSON data containing device information. - """ - for device in json_data['devices']: - if device['device_id'] == self.device_id: - device['last_updated'] = datetime.now().strftime("%Y-%m-%d %H:%M:%S") - save_json(json_data, FILE_PATH) - break - From 9fd45488e30f5e6542107961c5539e44e28b0706 Mon Sep 17 00:00:00 2001 From: Rafal Szabat Date: Sun, 17 Nov 2024 19:54:32 +0100 Subject: [PATCH 11/14] Delete Devices/plug.py --- Devices/plug.py | 47 ----------------------------------------------- 1 file changed, 47 deletions(-) delete mode 100644 Devices/plug.py diff --git a/Devices/plug.py b/Devices/plug.py deleted file mode 100644 index 226c845..0000000 --- a/Devices/plug.py +++ /dev/null @@ -1,47 +0,0 @@ -from device import NotCompatibleDevice, Device, load_json - -class Plug(Device): - def __init__(self, device_id: str, device_type: str): - super().__init__(device_id, device_type) - - def get_current_power_usage(self) -> str: - """ - Get the total power usage of the device. - - This method loads the JSON data from the file, iterates through the devices, - and returns the total energy consumption in kWh for the device with the matching device_id. - - :return: The total energy consumption in kWh as a string. If the device is not found, - it returns "Power usage not available". - """ - json_data = load_json() - for device in json_data['devices']: - if device['device_id'] == self.device_id: - return device['status']['energy_consumption']['current_power_w'] - return "Power usage not available" - - def get_total_power_usage(self) -> str: - """ - Get the total power usage of the device. - - This method loads the JSON data from the file, iterates through the devices, - and returns the total energy consumption in kWh for the device with the matching device_id. - - :return: The total energy consumption in kWh as a string. If the device is not found, - it returns "Power usage not available". - """ - json_data = load_json() - for device in json_data['devices']: - if device['device_id'] == self.device_id: - return device['status']['energy_consumption']['total_energy_kwh'] - return "Power usage not available" - - -if __name__ == "__main__": - plug = Plug("abcdef1234567999", "plug") - plug.connect_to_device() - print(f"Current power usage: {plug.get_current_power_usage()}") - print(f"Total power usage: {plug.get_total_power_usage()}") - plug.reboot() - plug.get_status() - plug.change_device_name("new_plug_name") From 974dce37b5b301979caff9b5f72c095288218f1b Mon Sep 17 00:00:00 2001 From: Rafal Szabat Date: Sun, 17 Nov 2024 19:54:38 +0100 Subject: [PATCH 12/14] Delete Devices/thermostat.py --- Devices/thermostat.py | 60 ------------------------------------------- 1 file changed, 60 deletions(-) delete mode 100644 Devices/thermostat.py diff --git a/Devices/thermostat.py b/Devices/thermostat.py deleted file mode 100644 index 078c8c7..0000000 --- a/Devices/thermostat.py +++ /dev/null @@ -1,60 +0,0 @@ -from device import NotCompatibleDevice, Device, load_json - -class Thermostat(Device): - def __init__(self, device_id: str, device_type: str): - super().__init__(device_id, device_type) - - - def get_current_temperature(self) -> float: - """ - Get the current temperature of the thermostat. - - Loads the JSON data, searches for the device with the matching device_id, - and returns the current temperature in Celsius. - - :return: The current temperature in Celsius as a float, or None if not found. - """ - json_data = load_json() - for device in json_data['devices']: - if device['device_id'] == self.device_id: - return float(device['status'].get('current_temperature_c', None)) - return None - - def get_target_temperature(self) -> float: - """ - Get the target temperature of the thermostat. - - Loads the JSON data, searches for the device with the matching device_id, - and returns the target temperature in Celsius. - - :return: The target temperature in Celsius as a float, or None if not found. - """ - json_data = load_json() - for device in json_data['devices']: - if device['device_id'] == self.device_id: - return float(device['status'].get('target_temperature_c', None)) - return None - - def get_humidity(self) -> float: - """ - Get the current humidity level of the thermostat. - - Loads the JSON data, searches for the device with the matching device_id, - and returns the current humidity percentage. - - :return: The current humidity percentage as a float, or None if not found. - """ - json_data = load_json() - for device in json_data['devices']: - if device['device_id'] == self.device_id: - return float(device['status'].get('humidity', None)) - return None - - -if __name__ == "__main__": - thermostat = Thermostat("abcdef1234563298", "thermostat") - thermostat.connect_to_device() - print("Current Temperature:", thermostat.get_current_temperature()) - print("Target Temperature:", thermostat.get_target_temperature()) - print("Humidity:", thermostat.get_humidity()) - thermostat.turn_on_off("off") From 673eca4faf76c7f756e4a9399c5b158acb84c63f Mon Sep 17 00:00:00 2001 From: IwonaAnna2024 Date: Sun, 8 Dec 2024 05:30:47 +0100 Subject: [PATCH 13/14] Operating time schedules for devices --- schedule_timers.py | 113 +++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 113 insertions(+) create mode 100644 schedule_timers.py diff --git a/schedule_timers.py b/schedule_timers.py new file mode 100644 index 0000000..5f006f5 --- /dev/null +++ b/schedule_timers.py @@ -0,0 +1,113 @@ +import json +import os +from typing import Dict, Any + +from datetime import timedelta, datetime + +class ScheduleUpdate: + def __init__(self, turn_on_time, turn_off_time, working_duration, current_time = str(datetime.now()), task_list = []): + self.turn_on_time = turn_on_time ("%Y-%m-%d-%H-%M") + self.turn_off_time = turn_off_time ("%Y-%m-%d-%H-%M") + self.working_duration = working_duration("%M") + self.current_time = current_time + self.task_list = task_list + + # Adding turn-on and turn-off time + def add_turn_on_off_time(self, devices_data: Dict[str, Any], task_list): + print_devices(devices_data) + device_number = int(input("Enter the device number to set working time schedule: ")) + if device_number not in devices_data: + return "Device is not available." + else: + # Setting turn-on time + self.turn_on_time = input("Enter time for turning on the device: ") + + # Setting turn-off time + self.turn_off_time = input("Enter time for turning off the device: ") + + # Verification of dates and adding them to the task list + if self.turn_on_time <= self.current_time < self.turn_off_time: + self.task_list.append(self.turn_on_time) + + else: + return "Incorrect device turn-on time entered." + + if self.current_time >= self.turn_off_time: + self.task_list.append(self.turn_off_time) + + else: + return "Incorrect device turn-off time entered." + + return f"Device's working schedule time has been set: {self.turn_on_time} - {self.turn_off_time}." + + # Setting a time period when (starting from now) the device is going to work + def add_working_time(self, index: int, devices_data: Dict[str, Any]): + self.device = devices_data["devices"][index] + print_devices(devices_data) + device_number = int(input("Enter the device number to set working time schedule: ")) + + if device_number not in devices_data: + return "Device is not available." + + # Setting the device's operating time + else: + self.working_duration = input(int("Enter for how long the device is to be turned on in minutes: ")) + if self.working_duration > 0: + self.turn_off_time = self.current_time + timedelta(minutes=self.working_duration) + self.task_list.append(self.current_time, self.turn_off_time) + + else: + return "Wrong operating time for the device." + + # Verification if there's any schedule for any device and turning it on/off if conditions are met + def check_schedule_time(self, scheduled_devices: Dict[str, Any]) -> None: + self.device = scheduled_devices["task_list"][index] + print_devices(scheduled_devices) + for self.device in self.task_list: + if self.turn_on_time <= self.current_time < self.turn_off_time: + if self.device["status"]["power"] == "off": + self.device["status"]["power"] = "on" + else: + self.device["status"]["power"] = "on" + + elif self.current_time >= self.turn_off_time: + if self.device["status"]["power"] == "on": + self.device["status"]["power"] = "off" + else: + self.device["status"]["power"] = "off" + + else: + pass + + +""" +Adding to the menu: + +def menu() -> None: + devices_data = load_devices() + + while True: + print("\nChoose an option:") + print("1. Show devices") + print("2. Toggle device") + print("3. Add device") + print("4. Remove device") + print("5. Set working schedule time for a device") + print("6. Save and exit") + + # Checking if there are any time schedules set and activating them if conditions are met + ScheduleUpdate.check_schedule_time(devices_data["devices"]) + + + + elif option == "5": + print("\nChoose an option:") + print("a. Set time for turning on and turning off the device") + print("b. Set working duration time for the device") + + option_time = input("Choose an option: ") + if option_time == "a": + ScheduleUpdate.add_turn_on_off_time(devices_data) + if option_time == "b": + ScheduleUpdate.duration_time(devices_data, devices_data) +""" \ No newline at end of file From a74df3cdc10f39f3e300864d501439063c901293 Mon Sep 17 00:00:00 2001 From: IwonaAnna2024 Date: Sun, 8 Dec 2024 06:04:10 +0100 Subject: [PATCH 14/14] Added load_devices and print devices methods --- schedule_timers.py | 40 +++++++++++++++++++++++++++++----------- 1 file changed, 29 insertions(+), 11 deletions(-) diff --git a/schedule_timers.py b/schedule_timers.py index 5f006f5..bacf17c 100644 --- a/schedule_timers.py +++ b/schedule_timers.py @@ -12,9 +12,29 @@ def __init__(self, turn_on_time, turn_off_time, working_duration, current_time = self.current_time = current_time self.task_list = task_list + def load_devices(self) -> Dict[str, Any]: + try: + with open(os.path.join(os.path.dirname(__file__), "devices.json"), "r") as file: + return json.load(file) + except FileNotFoundError: + print("File not found.") + return {"devices": []} + except json.JSONDecodeError: + print("Error reading the file.") + return {"devices": []} + + def print_devices(self, devices_data: Dict[str, Any]) -> None: + if not devices_data["devices"]: + print("No devices in the system.") + return + + for index, device in enumerate(devices_data["devices"]): + power_status = device['status'].get('power', 'unknown') + print(f"{index + 1}. {device['name']} ({device['location']}) - Power: {power_status}") + # Adding turn-on and turn-off time - def add_turn_on_off_time(self, devices_data: Dict[str, Any], task_list): - print_devices(devices_data) + def add_turn_on_off_time(self, devices_data: Dict[str, Any]): + self.print_devices(devices_data) device_number = int(input("Enter the device number to set working time schedule: ")) if device_number not in devices_data: return "Device is not available." @@ -43,7 +63,7 @@ def add_turn_on_off_time(self, devices_data: Dict[str, Any], task_list): # Setting a time period when (starting from now) the device is going to work def add_working_time(self, index: int, devices_data: Dict[str, Any]): self.device = devices_data["devices"][index] - print_devices(devices_data) + self.print_devices(devices_data) device_number = int(input("Enter the device number to set working time schedule: ")) if device_number not in devices_data: @@ -60,9 +80,9 @@ def add_working_time(self, index: int, devices_data: Dict[str, Any]): return "Wrong operating time for the device." # Verification if there's any schedule for any device and turning it on/off if conditions are met - def check_schedule_time(self, scheduled_devices: Dict[str, Any]) -> None: - self.device = scheduled_devices["task_list"][index] - print_devices(scheduled_devices) + def check_schedule_time(self, scheduled_devices: [str, Any]) -> None: + self.device = scheduled_devices["task_list"] + for self.device in self.task_list: if self.turn_on_time <= self.current_time < self.turn_off_time: if self.device["status"]["power"] == "off": @@ -96,10 +116,8 @@ def menu() -> None: print("6. Save and exit") # Checking if there are any time schedules set and activating them if conditions are met - ScheduleUpdate.check_schedule_time(devices_data["devices"]) - - - + ScheduleUpdate.check_schedule_time(devices_data["devices"]) + elif option == "5": print("\nChoose an option:") print("a. Set time for turning on and turning off the device") @@ -110,4 +128,4 @@ def menu() -> None: ScheduleUpdate.add_turn_on_off_time(devices_data) if option_time == "b": ScheduleUpdate.duration_time(devices_data, devices_data) -""" \ No newline at end of file +"""