import os from PIL import Image import glob def get_latest_screenshot(directory, ext='jpg'): """Get the latest screenshot file from the given directory. Returns None if none found.""" if not os.path.isdir(directory): return None pattern = os.path.join(directory, f'*.{ext}') list_of_files = glob.glob(pattern) if not list_of_files: return None latest_file = max(list_of_files, key=os.path.getctime) return latest_file def process_image(image_path): """Process the image to decide if it's dark or light. Returns 'open', 'closed' or 'unknown'.""" if not image_path or not os.path.isfile(image_path): return 'unknown' try: with Image.open(image_path) as img: img = img.convert('RGB') # shrink to 2x2 to average quickly img = img.resize((2, 2)) pixels = list(img.getdata()) # average each channel avg = [sum(ch) / len(pixels) for ch in zip(*pixels)] luminance = sum(avg) / 3.0 return 'closed' if luminance < 128 else 'open' except Exception: return 'unknown' def get_brightness(image_path): """Return the average brightness (0-255) of the image, or None on error.""" if not image_path or not os.path.isfile(image_path): return None try: with Image.open(image_path) as img: img = img.convert('L') # sample more pixels for a smoother average img = img.resize((16, 16)) pixels = list(img.getdata()) if not pixels: return None return sum(pixels) / len(pixels) except Exception: return None # Directory where the screenshots are stored screenshot_directory = '/var/lib/motion/' # Get the latest screenshot latest_screenshot = get_latest_screenshot(screenshot_directory) # Process the image and determine hackspace status hackspace_status = process_image(latest_screenshot) print(f"The hackspace is {hackspace_status}.")