import re import requests import sys import os from bs4 import BeautifulSoup from requests.exceptions import HTTPError, Timeout, RequestException # Set the working directory to parent os.chdir(os.path.abspath(os.path.join(os.path.dirname(__file__), '..'))) # Update sys.path to include the parent directory of the current script sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), '..'))) # Import the get_token function from utilities.get_token import get_token # FHEM URL base (replace with your actual FHEM server URL) FHEM_URL_BASE = "https://fhem.auwiesen2.de/fhem" # Retrieve the CSRF token dynamically csrf_token = get_token(FHEM_URL_BASE) # Headers including CSRF token HEADERS = { "X-FHEM-csrfToken": csrf_token, "Content-Type": "application/x-www-form-urlencoded", "Accept": "application/json" } # Path to the log file created by the first script log_file_path = 'fhem_script.log' # Define the pattern to match devices in the log file device_pattern = r'^attr (MA_[a-zA-Z0-9]+) alias (.+)$' # Session to handle requests session = requests.Session() def get_device_attributes(device_name): """Fetch the room and alias attributes for a given device from FHEM.""" try: # Construct the URL to get the device details detail_url = f"{FHEM_URL_BASE}?detail={device_name}" # Send the request response = session.get(detail_url, headers=HEADERS, timeout=10) response.raise_for_status() # Parse the HTML response using BeautifulSoup soup = BeautifulSoup(response.text, 'html.parser') # Find the table with the class 'block wide attributes' attributes_table = soup.find('table', class_='block wide attributes') # Extract the alias and room values alias = None room = None if attributes_table: rows = attributes_table.find_all('tr') for row in rows: name_div = row.find('div', class_='dname') value_div = row.find('div', class_='dval') if name_div and value_div: attr_name = name_div.text.strip() attr_value = value_div.text.strip() if attr_name == "alias": alias = attr_value elif attr_name == "room": room = attr_value return alias, room except (HTTPError, Timeout) as err: print(f"Error fetching attributes for device {device_name}: {err}") return None, None except RequestException as req_err: print(f"An error occurred: {req_err}") return None, None def list_ma_devices_with_aliases_and_rooms(log_file_path, device_pattern): matched_devices = [] try: # Open the log file and read line by line with open(log_file_path, 'r') as log_file: for line in log_file: # Check if the line matches the pattern for devices starting with "MA_" match = re.search(device_pattern, line) if match: device_name = match.group(1) # Get the alias and room for the matched device alias, room = get_device_attributes(device_name) # Add the device name, alias, and room to the list matched_devices.append((device_name, alias, room)) except FileNotFoundError: print(f"Log file '{log_file_path}' not found.") return None return matched_devices def main(): # List all devices starting with "MA_", their aliases, and rooms devices = list_ma_devices_with_aliases_and_rooms(log_file_path, device_pattern) if devices: print("Devices starting with 'MA_', their aliases, and rooms:") for device_name, alias, room in devices: print(f"Device: {device_name}, Alias: {alias}, Room: {room}") else: print("No devices starting with 'MA_' found.") if __name__ == "__main__": main()