[{"element_type":"text","content":"\n  \n        \u003cp\u003eI wanted to control a Dual Govee Smart Plug and saw one of Lady Ada shows, showing off her latest design the STHS34PF80\u0026nbsp; ID #6426.\u0026nbsp; So built one that would control a Govee Dual Smart Plug.\u003c/p\u003e\n\u003cp\u003eREQUIRED: you must have a Govee account and apply for a Govee API key thru the phone app only.\u0026nbsp; You make a request and they will email you an API key... Don't loose it.\u0026nbsp; You can over load their API so keep your request to a minimum.\u0026nbsp; They will throttle you account if you get carried away.\u003c/p\u003e\n\u003cp\u003eObject of this project:\u0026nbsp; I wanted to control a Govee Dual Smart Plug.\u0026nbsp; The plug is used to turn on all my Adafruit projects in my office.\u0026nbsp; So when I leave they all turn off and back on when I enter my office.\u0026nbsp; This sensor is fairly sensitive and I can be about 10-12 feet away when it senses me.\u0026nbsp; The sensitivity various with room temperature.\u0026nbsp; Its not perfect, Its like the sensor gets use to you in the room and starts to ignore you unless you move around a lot or leave the room for a bit.\u0026nbsp; Its sensing the heat around the room\u0026nbsp;\u003c/p\u003e\n\u003cp\u003eProgramming:\u0026nbsp; I can NOT take total credit for programming this.\u0026nbsp; I spent many, many hours coding and working with Copilot.\u0026nbsp; Together we came up with what appears solid.\u0026nbsp; I spent about 3 weeks on and off working on this project.\u0026nbsp; You can add your own ideas in.\u0026nbsp;\u0026nbsp;\u003c/p\u003e\n\u003cp\u003eParts are:\u003c/p\u003e\n\u003cul\u003e\n\u003cli\u003e\u003ca href=\"https://www.adafruit.com/product/6426\"\u003eAdafruit STHS34PF80 IR Presence / Motion Sensor - STEMMA QT / Qwiic ID 6426\u003c/a\u003e\u003c/li\u003e\n\u003cli\u003eAdafruit ESP32-S3 Revers TFT Feather ID 5691\u003c/li\u003e\n\u003cli\u003eStemma QT / QWii JST SH 4-Pin\u0026nbsp; ID 4399\u003c/li\u003e\n\u003c/ul\u003e\n\u003cp\u003eOS is CircuitPython version 10.0.3 as of 2-2026\u003c/p\u003e\n\u003cp\u003eThe object of this project design was simple\u003c/p\u003e\n\u003cul\u003e\n\u003cli\u003eDisplay the current date and time since it will be sitting on my desk\u003c/li\u003e\n\u003cli\u003eInitialize the time and sensor\u003c/li\u003e\n\u003cli\u003eDisplay option below for 5 seconds. If a selection is not made then select the last selected mode.\n\u003cul\u003e\n\u003cli\u003eThree buttons in the from to\u0026nbsp;\n\u003cul\u003e\n\u003cli\u003eButton D0 to select Outlet A\u003c/li\u003e\n\u003cli\u003eButton D1 to select Outlet B\u003c/li\u003e\n\u003cli\u003eButton D2 to select Both Outlets A \u0026amp; B\u003c/li\u003e\n\u003c/ul\u003e\n\u003c/li\u003e\n\u003cli\u003eOnce a option is selected lock out the buttons until the unit is rebooted or power off.\u0026nbsp;\u0026nbsp;\u003c/li\u003e\n\u003c/ul\u003e\n\u003c/li\u003e\n\u003cli\u003eOnce the unit has power one it should display the following\n\u003cul\u003e\n\u003cli\u003eDate and time\u003c/li\u003e\n\u003cli\u003eA green pixel (i am alive) flashes\u0026nbsp;\n\u003cul\u003e\n\u003cli\u003eFlashes blue every 30 seconds to insure the Internet is still alive\u003c/li\u003e\n\u003cli\u003eTurns red if the internet goes down and returns green once alive again\u003c/li\u003e\n\u003c/ul\u003e\n\u003c/li\u003e\n\u003cli\u003eDisplay which Outlet is on or off\u0026nbsp; \u0026nbsp;Green for ON, Red for OFF\n\u003cul\u003e\n\u003cli\u003eA ON, A OFF | B ON, B OFF | Both On, Both OFF\u003c/li\u003e\n\u003c/ul\u003e\n\u003c/li\u003e\n\u003cli\u003eDisplay in english\u0026nbsp; Plug A On/Off | Plug B On/Off | Plug Both On/Off\u003c/li\u003e\n\u003c/ul\u003e\n\u003c/li\u003e\n\u003cli\u003eIf the sensor detects movement or present it will send a Govee Smart Plug command out the internet\u003c/li\u003e\n\u003cli\u003eIf the sensor no longer sees movement or presents then the following happens\n\u003cul\u003e\n\u003cli\u003eProgram wait for 10 cycles and if movement or presents is detected resets to true\u003c/li\u003e\n\u003cli\u003eIf after 10 cycles and no movement or presents is detected then a countdown timer is started\u003c/li\u003e\n\u003cli\u003eThe count down timer will be displayed in the lower left for 150secs.\u0026nbsp;\n\u003cul\u003e\n\u003cli\u003eShould the timer count to zero the Govee command to turn off is sent out to the internet\u003c/li\u003e\n\u003cli\u003eIf for the sensor see movement or presents then the timer is reset and terminated until there is no movement or presents.\u003c/li\u003e\n\u003c/ul\u003e\n\u003c/li\u003e\n\u003c/ul\u003e\n\u003c/li\u003e\n\u003cli\u003eTurn off the Display at 10pm and turn it back on at 8am.\u0026nbsp; Just to save the display wear.\u003c/li\u003e\n\u003cli\u003eI used the Ruiz Brothers 3D Case (IoT Battery Monitor) and modified the size of the face \u0026amp; rear place to make room for the IR Sensor.\u0026nbsp; I used FreeCad to make the modification. I liked how the case back panel snapped in and I didn't know how this was done do I slice the case in half and added about 1/2\" to the original .stp file.\u0026nbsp; Came out great.\u0026nbsp; I hope the Reiz Brothers don't mind, you guys ROCK!\u003c/li\u003e\n\u003c/ul\u003e\n\u003cp\u003eBelow is the code I used and I am still very new at all this so if you think I did something wrong let me know\u003c/p\u003e\n      \n","metadata":{}},{"element_type":"code","content":"import time\nimport board\nimport wifi\nimport os\nimport digitalio\nimport displayio\nimport terminalio\nimport microcontroller\nimport neopixel\nimport adafruit_ntp\nimport rtc\nfrom adafruit_display_text import label\nimport adafruit_connection_manager\nimport adafruit_requests\nimport adafruit_sths34pf80\nfrom presence_plug_controller import PresencePlugController\n\n# --- Control Display Backlight ---\ndisplay_is_off = False\n\n# --- Wi-Fi ---\nSSID = os.getenv(\"CIRCUITPY_WIFI_SSID\")\nPASS = os.getenv(\"CIRCUITPY_WIFI_PASSWORD\")\nGOVEE_KEY = os.getenv(\"GOVEE_API_KEY\")\n\n# --- Timezone ---\nval = os.getenv(\"TZ_OFFSET\", \"-7\")\ntry:\n    TZ_OFFSET = int(val.strip().replace('\"', '').replace(\"'\", \"\"))\nexcept Exception:\n    TZ_OFFSET = -7\n\n# --- Govee Devices ---\nGOVEE_DEVICES = {\n    \"A\": {\"device\": os.getenv(\"DEVICE_1\"), \"model\": os.getenv(\"MODEL_1\")},\n    \"B\": {\"device\": os.getenv(\"DEVICE_2\"), \"model\": os.getenv(\"MODEL_2\")},\n    \"C\": {\"device\": os.getenv(\"DEVICE_3\"), \"model\": os.getenv(\"MODEL_3\")},\n}\n\n# --- Buttons ---\nbutton_a = digitalio.DigitalInOut(board.BUTTON)\nbutton_a.switch_to_input(pull=digitalio.Pull.UP)\n\nbutton_b = digitalio.DigitalInOut(board.D1)\nbutton_b.switch_to_input(pull=digitalio.Pull.DOWN)\n\nbutton_c = digitalio.DigitalInOut(board.D2)\nbutton_c.switch_to_input(pull=digitalio.Pull.DOWN)\n\n# --- Button state tracking ---\nlast_button_a = False\nlast_button_b = False\nlast_button_c = False\n\ndef check_button_selection():\n    global last_button_a, last_button_b, last_button_c\n\n    current_a = not button_a.value\n    current_b = button_b.value\n    current_c = button_c.value\n\n    selection = None\n\n    if current_a and not last_button_a:\n        selection = \"A\"\n    elif current_b and not last_button_b:\n        selection = \"B\"\n    elif current_c and not last_button_c:\n        selection = \"C\"\n\n    last_button_a = current_a\n    last_button_b = current_b\n    last_button_c = current_c\n\n    if selection:\n        microcontroller.nvm[0] = ord(selection)\n        return selection\n\n    return None\n\n# --- NeoPixel Heartbeat ---\npixel = neopixel.NeoPixel(board.NEOPIXEL, 1, brightness=0.2)\nheartbeat = False\nlast_heartbeat = time.monotonic()\n\n# --- LED ---\nled = digitalio.DigitalInOut(board.LED)\nled.switch_to_output(value=False)\n\n# --- Display ---\ndisplay = board.DISPLAY\n\ngroup = displayio.Group()\ndisplay.root_group = group\n\ntext_label = label.Label(terminalio.FONT, text=\"Initializing...\", x=10, y=display.height - 30, scale=2)\ngroup.append(text_label)\n\nstatus_label = label.Label(\n    terminalio.FONT,\n    text=\"\",\n    scale=4,\n    color=0xFFFFFF,\n    anchor_point=(0.5, 0.5),\n    anchored_position=(display.width // 2, display.height // 2)\n)\ngroup.append(status_label)\n\ncountdown_label = label.Label(\n    terminalio.FONT,\n    text=\"\",\n    scale=2,\n    color=0xFFFF00,\n    anchor_point=(1.0, 1.0),\n    anchored_position=(display.width - 5, display.height - 5)\n)\ngroup.append(countdown_label)\n\n# --- Date/Time Label ---\ndatetime_label = label.Label(\n    terminalio.FONT,\n    text=\"\",\n    scale=2,\n    color=0x00FFFF,\n    anchor_point=(0.5, 0.0),\n    anchored_position=(display.width // 2, 5)\n)\ngroup.append(datetime_label)\n\n# --- TFT Heartbeat Dot ---\nheartbeat_bitmap = displayio.Bitmap(6, 6, 2)\nheartbeat_palette = displayio.Palette(2)\nheartbeat_palette[0] = 0x000000\nheartbeat_palette[1] = 0x00FF00\n\nfor x in range(6):\n    for y in range(6):\n        heartbeat_bitmap[x, y] = 1\n\nheartbeat_tile = displayio.TileGrid(\n    heartbeat_bitmap,\n    pixel_shader=heartbeat_palette,\n    x=display.width - 10,\n    y=10\n)\ngroup.append(heartbeat_tile)\n\ntft_heartbeat = False\nlast_tft_heartbeat = time.monotonic()\n\n# --- Internet health state ---\ninternet_ok = True\nping_flash_until = 0\n\n# --- Connect Wi-Fi ---\nprint(f\"Connecting to {SSID}...\")\nwifi.radio.connect(SSID, PASS)\nprint(\"Connected to Wi-Fi:\", wifi.radio.ipv4_address)\n\n# --- Create ONE socket pool ---\npool = adafruit_connection_manager.get_radio_socketpool(wifi.radio)\n\n# --- NTP Time Sync ---\nprint(\"Syncing time with NTP...\")\nntp = adafruit_ntp.NTP(pool, tz_offset=TZ_OFFSET)\nrtc.RTC().datetime = ntp.datetime\nprint(\"Time synced:\", time.localtime())\n\n# --- HTTPS session ---\nssl_context = adafruit_connection_manager.get_radio_ssl_context(wifi.radio)\nrequests = adafruit_requests.Session(pool, ssl_context)\nrequests.timeout = 5\n\n# --- Sensor ---\ni2c = board.I2C()\nsths = adafruit_sths34pf80.STHS34PF80(i2c)\n\n# --- Controller ---\ncontroller = PresencePlugController(\n    sensor=sths,\n    requests=requests,\n    devices=GOVEE_DEVICES,\n    api_key=GOVEE_KEY\n)\n\ncontroller.set_display_label(text_label)\ncontroller.set_status_label(status_label)\ncontroller.set_countdown_label(countdown_label)\ncontroller.set_led(led)\n\n# --- Prompt for button selection ---\nselection = None\nselection_locked = False\ntext_label.text = \"Select an option\\nButton A, B, or C\"\ntext_label.y = display.height - 45\nstatus_label.text = \"\"\nstart_time = time.monotonic()\nwhile (time.monotonic() - start_time) \u003c 5:\n    selection = check_button_selection()\n    if selection:\n        print(f\"Button pressed during prompt: {selection}\")\n        controller.set_active_device(selection)\n        button_a.switch_to_input()\n        button_b.switch_to_input()\n        button_c.switch_to_input()\n        selection_locked = True\n        break\n    time.sleep(0.05)\n\n# --- Restore last plug selection ---\ntry:\n    if not selection:\n        stored = microcontroller.nvm[0]\n        if stored in (ord(\"A\"), ord(\"B\"), ord(\"C\")):\n            default_key = chr(stored)\n            print(f\"Restoring last selected plug: {default_key}\")\n            controller.set_active_device(default_key)\n        else:\n            print(f\"NVM[0] invalid: {stored} — defaulting to A\")\n            controller.set_active_device(\"A\")\nexcept IndexError:\n    if not selection:\n        print(\"NVM[0] not initialized — defaulting to A\")\n        controller.set_active_device(\"A\")\n\n# --- Keepalive timer ---\nlast_ping = time.monotonic()\n\n# --- Clock update timer ---\nlast_clock_update = 0\n\n# --- Main loop ---\nprint(\"Starting motion detection loop...\")\nprint(\"Raw NVM[0] value:\", microcontroller.nvm[0])\n\ntext_label.y = display.height - 15\n\nwhile True:\n    if not selection_locked:\n        selection = check_button_selection()\n        if selection:\n            print(\"Button pressed:\", selection)\n            if selection == \"A\":\n                controller.set_active_device(\"A\")\n            elif selection == \"B\":\n                controller.set_active_device(\"B\")\n            elif selection == \"C\":\n                print(\"[DEBUG] Calling set_both_outlets(turn_on=True) from code.py\")\n                if hasattr(controller, \"set_both_outlets\"):\n                    controller.set_both_outlets(turn_on=True)\n                else:\n                    print(\"set_both_outlets() not implemented in controller!\")\n            button_a.switch_to_input()\n            button_b.switch_to_input()\n            button_c.switch_to_input()\n            selection_locked = True\n            time.sleep(0.5)\n\n    # --- Wi-Fi keepalive every 30 seconds ---\n    now = time.monotonic()\n    if now - last_ping \u003e 30:\n        try:\n            print(\"Pinging Wi-Fi...\")\n            ping_flash_until = time.monotonic() + 0.5\n            requests.get(\"http://connectivitycheck.gstatic.com/generate_204\", timeout=3)\n            print(\"Ping OK\")\n            internet_ok = True\n        except Exception as e:\n            print(\"Ping failed:\", e)\n            internet_ok = False\n        last_ping = now\n\n    # --- TFT Heartbeat Logic ---\n    now = time.monotonic()\n    if not internet_ok:\n        heartbeat_palette[1] = 0xFF0000\n        last_tft_heartbeat = now\n    else:\n        if now \u003c ping_flash_until:\n            heartbeat_palette[1] = 0x0000FF\n        else:\n            if now - last_tft_heartbeat \u003e 1:\n                tft_heartbeat = not tft_heartbeat\n                heartbeat_palette[1] = 0x00FF00 if tft_heartbeat else 0x000000\n                last_tft_heartbeat = now\n\n    # --- NeoPixel Heartbeat ---\n    now = time.monotonic()\n    if not internet_ok:\n        pixel[0] = (50, 0, 0)\n    elif now \u003c ping_flash_until:\n        pixel[0] = (0, 0, 50)\n    else:\n        if now - last_heartbeat \u003e 1:\n            heartbeat = not heartbeat\n            pixel[0] = (0, 50, 0) if heartbeat else (0, 0, 0)\n            last_heartbeat = now\n\n    # --- Date/Time Display (update once per second) ---\n    now = time.monotonic()\n    if now - last_clock_update \u003e= 1:\n        now_struct = time.localtime()\n\n        hour_12 = now_struct.tm_hour % 12\n        if hour_12 == 0:\n            hour_12 = 12\n        am_pm = \"a\" if now_struct.tm_hour \u003c 12 else \"p\"\n\n        month_names = [\n            \"Jan\", \"Feb\", \"Mar\", \"Apr\", \"May\", \"Jun\",\n            \"Jul\", \"Aug\", \"Sep\", \"Oct\", \"Nov\", \"Dec\"\n        ]\n\n        day = now_struct.tm_mday\n        if 11 \u003c= day \u003c= 13:\n            suffix = \"th\"\n        else:\n            suffix = {1: \"st\", 2: \"nd\", 3: \"rd\"}.get(day % 10, \"th\")\n\n        month_str = month_names[now_struct.tm_mon - 1]\n\n        datetime_label.text = \"{} {}{} {:2d}:{:02d}{}\".format(\n            month_str, day, suffix,\n            hour_12, now_struct.tm_min, am_pm\n        )\n\n        last_clock_update = now\n\n    # --- Auto display sleep/wake ---\n    hour = now_struct.tm_hour\n    if (hour \u003e= 22 or hour \u003c 6):\n        if not display_is_off:\n            print(\"Turning display OFF for night mode\")\n            display.brightness = 0.0\n            display_is_off = True\n    else:\n        if display_is_off:\n            print(\"Turning display ON for daytime\")\n            display.brightness = 1.0\n            display_is_off = False\n\n    controller.update()\n    time.sleep(0.02)","metadata":{"language":"auto","linenums":false,"filename":""}},{"element_type":"code","content":"import time\nimport json\nimport wifi\nimport os\n\nclass PresencePlugController:\n\n    def __init__(self, sensor, requests, devices, api_key,\n                 debounce_sec=0.12, timeout_sec=120, min_api_interval=5):\n        self.sensor = sensor\n        self.requests = requests\n        self.devices = devices\n        self.api_key = api_key\n        self.debounce_sec = debounce_sec\n        self.timeout_sec = timeout_sec\n        self.min_api_interval = min_api_interval\n\n        self.device_id = None\n        self.model_id = None\n        self.current_key = None\n\n        self.last_change_candidate = 0\n        self.last_motion_time = 0\n        self.last_api_time = 0\n        self.motion_state = False\n        self.last_raw = self.sensor.presence\n\n        self.display_label = None\n        self.status_label = None\n        self.countdown_label = None\n        self.led = None\n\n        self.candidate_state = None\n        self.committed_state = None\n        self.last_candidate_change = 0.0\n        self.consecutive_false_count = 0\n        self.required_consecutive_false = 10\n\n        self.device_states = {key: None for key in self.devices}\n\n    # --- UI hooks ---\n    def set_status_label(self, lbl):\n        self.status_label = lbl\n\n    def set_countdown_label(self, lbl):\n        self.countdown_label = lbl\n\n    def set_display_label(self, label_obj):\n        self.display_label = label_obj\n\n    def set_led(self, led_obj):\n        self.led = led_obj\n\n\n    def set_both_outlets(self, turn_on=True):\n        print(f\"[DEBUG] set_both_outlets called with turn_on={turn_on}\")\n        \"\"\"\n        Send a Govee API command to turn both outlets ON or OFF at the same time.\n        \"\"\"\n        headers = {\n            \"Content-Type\": \"application/json\",\n            \"Govee-API-Key\": self.api_key\n        }\n        # Hardcoded device/model for both outlets (update if needed)\n        device_id = \"2A:FE:60:74:F4:54:97:7A\"\n        model_id = \"H5082\"\n        value = \"on\" if turn_on else \"off\"\n        body = {\n            \"device\": device_id,\n            \"model\": model_id,\n            \"cmd\": {\n                \"name\": \"turn\",\n                \"value\": value\n            }\n        }\n        # Update display label immediately\n        if self.display_label:\n            self.display_label.text = f\"Both Plugs {'On' if turn_on else 'Off'}\"\n        print(f\"Sending BOTH OUTLETS {value.upper()} command: {body}\")\n        try:\n            response = self.requests.put(\n                \"https://developer-api.govee.com/v1/devices/control\",\n                headers=headers,\n                data=json.dumps(body),\n                timeout=5\n            )\n            print(\"Status:\", response.status_code)\n            print(\"Response:\", response.text)\n            if self.status_label:\n                self.status_label.text = f\"Both {value.upper()}\"\n                self.status_label.color = 0x00FF00 if turn_on else 0xFF0000\n        except Exception as e:\n            print(\"Govee BOTH OUTLETS command failed:\", e)\n              \n\n    # --- Device selection ---\n    def set_active_device(self, key):\n        if key in self.devices:\n            self.device_id = self.devices[key][\"device\"]\n            self.model_id = self.devices[key][\"model\"]\n            self.current_key = key\n            print(f\"Switched to Plug {key}: {self.device_id}\")\n\n            self.update_display(\"Off\")\n\n            if self.status_label:\n                if key == \"C\":\n                    self.status_label.text = \"Both OFF\"\n                else:\n                    self.status_label.text = f\"{key} OFF\"\n                self.status_label.color = 0xFF0000\n\n            self.motion_state = False\n            self.device_states[key] = None\n        else:\n            print(f\"Device key {key} not found\")\n\n    def update_display(self, state):\n        if self.display_label and self.current_key:\n            if self.current_key == \"C\":\n                self.display_label.text = f\"Both Plugs {state}\"\n            else:\n                self.display_label.text = f\"Plug {self.current_key} {state}\"\n\n    # --- Govee payload ---\n    def build_payload(self, value):\n        return {\n            \"device\": self.device_id,\n            \"model\": self.model_id,\n            \"cmd\": {\n                \"name\": \"toggle\",\n                \"value\": value\n            }\n        }\n\n    # --- Govee API with Wi-Fi keepalive ---\n    def send_govee_put(self, value):\n        desired_state = \"on\" if value == \"1_1\" else \"off\"\n\n        if self.status_label:\n            outlet = self.current_key if self.current_key else \"?\"\n            # Show 'Both ON/OFF' for C, 'A ON/OFF' or 'B ON/OFF' for A/B\n            if outlet == \"C\":\n                if value == \"1_1\":\n                    self.status_label.text = \"Both ON\"\n                    self.status_label.color = 0x00FF00\n                else:\n                    self.status_label.text = \"Both OFF\"\n                    self.status_label.color = 0xFF0000\n            elif outlet in (\"A\", \"B\"):\n                if value == \"1_1\":\n                    self.status_label.text = f\"{outlet} ON\"\n                    self.status_label.color = 0x00FF00\n                else:\n                    self.status_label.text = f\"{outlet} OFF\"\n                    self.status_label.color = 0xFF0000\n            else:\n                if value == \"0_1\":\n                    self.status_label.text = f\"Outlet {outlet} ON\"\n                    self.status_label.color = 0x00FF00\n                else:\n                    self.status_label.text = f\"Outlet {outlet} OFF\"\n                    self.status_label.color = 0xFF0000\n\n        current_state = self.device_states.get(self.current_key)\n        if current_state == desired_state:\n            print(f\"Skipping redundant '{desired_state}' command for device {self.current_key}\")\n            return\n\n        now = time.monotonic()\n        if now - self.last_api_time \u003c self.min_api_interval:\n            print(\"Skipping API call: too soon\")\n            return\n        self.last_api_time = now\n\n        # Wi-Fi keepalive before API call\n        try:\n            print(\"Pinging Wi-Fi before PUT...\")\n            self.requests.get(\n                \"http://connectivitycheck.gstatic.com/generate_204\",\n                timeout=3\n            )\n        except Exception as e:\n            print(\"Ping failed, reconnecting:\", e)\n            try:\n                wifi.radio.connect(os.getenv(\"CIRCUITPY_WIFI_SSID\"),\n                                   os.getenv(\"CIRCUITPY_WIFI_PASSWORD\"))\n                print(\"Reconnected Wi-Fi\")\n            except Exception as e2:\n                print(\"Reconnect failed:\", e2)\n                return\n\n        headers = {\n            \"Content-Type\": \"application/json\",\n            \"Govee-API-Key\": self.api_key\n        }\n        body = self.build_payload(value)\n        print(\"Sending PUT:\", body)\n\n        try:\n            response = self.requests.put(\n                \"https://developer-api.govee.com/v1/devices/control\",\n                headers=headers,\n                data=json.dumps(body),\n                timeout=5\n            )\n            print(\"Status:\", response.status_code)\n            print(\"Response:\", response.text)\n\n            self.device_states[self.current_key] = desired_state\n\n            if self.led:\n                self.led.value = (value == \"1_1\")\n\n            self.update_display(\"On\" if value == \"1_1\" else \"Off\")\n\n        except Exception as e:\n            print(\"Govee PUT failed:\", e)\n\n    # --- Presence logic ---\n    def update(self):\n        if not self.sensor.data_ready or not self.device_id:\n            return\n\n        now = time.monotonic()\n        raw = bool(self.sensor.presence or self.sensor.motion)\n\n        print(raw)\n\n        if self.candidate_state is None:\n            self.candidate_state = raw\n            self.last_candidate_change = now\n            self.consecutive_false_count = 0 if raw else 1\n\n        if raw:\n            self.consecutive_false_count = 0\n        else:\n            self.consecutive_false_count += 1\n\n        if raw:\n            candidate = True\n        else:\n            if self.consecutive_false_count \u003e= self.required_consecutive_false:\n                candidate = False\n            else:\n                candidate = self.candidate_state\n\n        if candidate != self.candidate_state:\n            self.candidate_state = candidate\n            self.last_candidate_change = now\n            return\n\n        if (now - self.last_candidate_change) \u003c self.debounce_sec:\n            return\n\n        if candidate != self.committed_state:\n            self.committed_state = candidate\n            print(\"Committed presence:\", self.committed_state)\n            if self.committed_state:\n                self.last_motion_time = now\n                if not self.motion_state:\n                    self.motion_state = True\n                # Turn ON selected outlet or both if 'C'\n                if self.current_key == \"C\":\n                    self.set_both_outlets(turn_on=True)\n                else:\n                    self.send_govee_put(\"1_1\")\n            else:\n                self.last_motion_time = now\n                # Do NOT turn off yet; wait for timeout before sending OFF command and updating label\n            return\n\n        if self.committed_state:\n            self.motion_state = True\n            if self.countdown_label:\n                self.countdown_label.text = \"\"\n            self.last_motion_time = now\n            return\n\n        if not self.committed_state and self.motion_state:\n            remaining = int(self.timeout_sec - (now - self.last_motion_time))\n            if remaining \u003c 0:\n                remaining = 0\n            if self.countdown_label:\n                self.countdown_label.text = f\"{remaining}s\"\n            # Do NOT update status label to OFF here; only after timeout\n        else:\n            if self.countdown_label:\n                self.countdown_label.text = \"\"\n\n        if self.motion_state and (now - self.last_motion_time \u003e= self.timeout_sec):\n            if self.current_key == \"C\":\n                print(\"Occupancy timeout reached -\u003e sending BOTH OFF\")\n                self.set_both_outlets(turn_on=False)\n            else:\n                print(f\"Occupancy timeout reached -\u003e sending {self.current_key} OFF\")\n                self.send_govee_put(\"1_0\")\n            self.motion_state = False\n            return","metadata":{"language":"auto","linenums":false,"filename":""}},{"element_type":"code","content":"CIRCUITPY_WIFI_SSID = \"SSID\"\nCIRCUITPY_WIFI_PASSWORD = \"Wi-Fi Password\"\nCIRCUITPY_WEB_API_PASSWORD = \"password\"\nCIRCUITPY_WEB_API_PORT = 80\nGOVEE_API_KEY = \"Govee User API Key\"\nDEVICE_1 = \"Govee Mac address\"\nMODEL_1 = \"H5082\"\nDST = \"True\"\nTZ_OFFSET = \"-7\"","metadata":{"language":"auto","linenums":false,"filename":""}},{"element_type":"user_image","content":"https://cdn-learn.adafruit.com/user_assets/assets/000/002/256/original/20260219_113602_2.jpg?1771530797","metadata":{}}]