harbor-python 1.3.0__tar.gz → 1.5.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: harbor-python
3
- Version: 1.3.0
3
+ Version: 1.5.0
4
4
  Summary: Async local client for Harbor Sleep Cameras
5
5
  Project-URL: Homepage, https://github.com/Harbor-Systems/harbor-python
6
6
  Project-URL: Repository, https://github.com/Harbor-Systems/harbor-python
@@ -133,6 +133,84 @@ settings = await harbor.get_camera_settings("CAMERA_SERIAL")
133
133
  print(settings.settings)
134
134
  ```
135
135
 
136
+ ### Camera controls
137
+
138
+ ```python
139
+ await harbor.set_camera_on("CAMERA_SERIAL", False) # privacy: pause the stream
140
+ await harbor.set_night_mode("CAMERA_SERIAL", "auto") # "auto" | "on" | "off"
141
+ await harbor.set_video_flip("CAMERA_SERIAL", True) # rotate the image 180°
142
+ await harbor.set_clock_display("CAMERA_SERIAL", False) # clock overlay on the video
143
+ await harbor.set_temperature_scale("CAMERA_SERIAL", "C") # "F" | "C"
144
+ await harbor.update_camera_settings(
145
+ "CAMERA_SERIAL", {"preference_video_ir_brightness": 40}
146
+ )
147
+ ```
148
+
149
+ Each control writes one preference and refreshes device state, so
150
+ `camera.state.values` reflects the change once the call returns:
151
+
152
+ | `camera.state.values[...]` | Type | Setting |
153
+ |---------------------------|------|---------|
154
+ | `camera_on` | `bool` | `preference_stream_paused` (inverted) |
155
+ | `night_mode_preference` | `"auto"` \| `"on"` \| `"off"` | `preference_video_night_mode` |
156
+ | `night_mode` | `bool` | runtime IR state (read-only, see below) |
157
+ | `video_flip` | `bool` | `preference_video_flip` |
158
+ | `clock_display` | `bool` | `preference_video_has_clock_display` |
159
+ | `temperature_scale` | `"F"` \| `"C"` | `preference_temperature_scale` |
160
+
161
+ `set_video_flip` and `set_clock_display` take real booleans — `1`/`0` and
162
+ `"true"` raise `ValueError` rather than being sent as a number or string,
163
+ which the firmware would reject.
164
+
165
+ The enum setters validate against the firmware's own option list, exported as
166
+ `NIGHT_MODE_MODES` and `TEMPERATURE_SCALES`. Matching is exact: `"f"` raises
167
+ `ValueError`, because the device compares the string verbatim. State values
168
+ preserve case for the same reason — what you read back is always something you
169
+ can write.
170
+
171
+ #### Night mode
172
+
173
+ Night mode is a **three-way preference**, not a boolean — `"auto"`, `"on"` or
174
+ `"off"` (default `"auto"`). Passing a bool raises `ValueError` rather than
175
+ guessing at a mode. A camera exposes two separate night-mode values:
176
+
177
+ | `camera.state.values[...]` | Type | Meaning |
178
+ |---------------------------|------|---------|
179
+ | `night_mode_preference` | `"auto"` \| `"on"` \| `"off"` | The setting. This is what `set_night_mode` writes and what reads back. |
180
+ | `night_mode` | `bool` | Whether IR is engaged *right now*. Read-only and device-driven — under `"auto"` it flips on its own as light levels change. |
181
+
182
+ Consumers building a UI entity should bind it to `night_mode_preference`, since
183
+ `night_mode` moves independently of any command.
184
+
185
+ ### Command errors
186
+
187
+ A rejected command raises `HarborCommandError`, which carries the parsed
188
+ `status` and the firmware's per-field `errors` list:
189
+
190
+ ```python
191
+ from harbor import HarborCommandError, HarborUnsupportedCommandError
192
+
193
+ try:
194
+ await harbor.set_night_mode("CAMERA_SERIAL", "on")
195
+ except HarborUnsupportedCommandError:
196
+ ... # firmware has no such command; permanent, so stop offering the feature
197
+ except HarborCommandError as err:
198
+ print(err.status, err.errors) # e.g. "REQUEST_MALFORMED", [{"error_code": "INVALID_VALUE", ...}]
199
+ ```
200
+
201
+ `HarborUnsupportedCommandError` is a subclass of `HarborCommandError`, raised
202
+ only on a `RESOURCE_NOT_FOUND` status. That means the firmware has no handler
203
+ for the command at all, so retrying can never succeed.
204
+
205
+ ### Firmware compatibility
206
+
207
+ Commands are verified against real hardware, most recently a camera running
208
+ `os_version` **2.8.0** / `app_version` **2.8.0-rc1+c1b0a32**: `ping`,
209
+ `get-settings`, `update-settings`, `pause-stream`, `unpause-stream`,
210
+ `set-night-mode-ir-brightness`, `update-operating-mode`, `set-scheduled-reboot`
211
+ and `list-viewers` all respond `OK`. See `mqtt_home_assistant.md` for the full
212
+ audit and payload shapes.
213
+
136
214
  ## WHIP Endpoint
137
215
 
138
216
  Harbor cameras allow custom WHIP endpoints. This tells the camera where to stream and works with tools that support WHIP, including go2rtc and Frigate.
@@ -104,6 +104,84 @@ settings = await harbor.get_camera_settings("CAMERA_SERIAL")
104
104
  print(settings.settings)
105
105
  ```
106
106
 
107
+ ### Camera controls
108
+
109
+ ```python
110
+ await harbor.set_camera_on("CAMERA_SERIAL", False) # privacy: pause the stream
111
+ await harbor.set_night_mode("CAMERA_SERIAL", "auto") # "auto" | "on" | "off"
112
+ await harbor.set_video_flip("CAMERA_SERIAL", True) # rotate the image 180°
113
+ await harbor.set_clock_display("CAMERA_SERIAL", False) # clock overlay on the video
114
+ await harbor.set_temperature_scale("CAMERA_SERIAL", "C") # "F" | "C"
115
+ await harbor.update_camera_settings(
116
+ "CAMERA_SERIAL", {"preference_video_ir_brightness": 40}
117
+ )
118
+ ```
119
+
120
+ Each control writes one preference and refreshes device state, so
121
+ `camera.state.values` reflects the change once the call returns:
122
+
123
+ | `camera.state.values[...]` | Type | Setting |
124
+ |---------------------------|------|---------|
125
+ | `camera_on` | `bool` | `preference_stream_paused` (inverted) |
126
+ | `night_mode_preference` | `"auto"` \| `"on"` \| `"off"` | `preference_video_night_mode` |
127
+ | `night_mode` | `bool` | runtime IR state (read-only, see below) |
128
+ | `video_flip` | `bool` | `preference_video_flip` |
129
+ | `clock_display` | `bool` | `preference_video_has_clock_display` |
130
+ | `temperature_scale` | `"F"` \| `"C"` | `preference_temperature_scale` |
131
+
132
+ `set_video_flip` and `set_clock_display` take real booleans — `1`/`0` and
133
+ `"true"` raise `ValueError` rather than being sent as a number or string,
134
+ which the firmware would reject.
135
+
136
+ The enum setters validate against the firmware's own option list, exported as
137
+ `NIGHT_MODE_MODES` and `TEMPERATURE_SCALES`. Matching is exact: `"f"` raises
138
+ `ValueError`, because the device compares the string verbatim. State values
139
+ preserve case for the same reason — what you read back is always something you
140
+ can write.
141
+
142
+ #### Night mode
143
+
144
+ Night mode is a **three-way preference**, not a boolean — `"auto"`, `"on"` or
145
+ `"off"` (default `"auto"`). Passing a bool raises `ValueError` rather than
146
+ guessing at a mode. A camera exposes two separate night-mode values:
147
+
148
+ | `camera.state.values[...]` | Type | Meaning |
149
+ |---------------------------|------|---------|
150
+ | `night_mode_preference` | `"auto"` \| `"on"` \| `"off"` | The setting. This is what `set_night_mode` writes and what reads back. |
151
+ | `night_mode` | `bool` | Whether IR is engaged *right now*. Read-only and device-driven — under `"auto"` it flips on its own as light levels change. |
152
+
153
+ Consumers building a UI entity should bind it to `night_mode_preference`, since
154
+ `night_mode` moves independently of any command.
155
+
156
+ ### Command errors
157
+
158
+ A rejected command raises `HarborCommandError`, which carries the parsed
159
+ `status` and the firmware's per-field `errors` list:
160
+
161
+ ```python
162
+ from harbor import HarborCommandError, HarborUnsupportedCommandError
163
+
164
+ try:
165
+ await harbor.set_night_mode("CAMERA_SERIAL", "on")
166
+ except HarborUnsupportedCommandError:
167
+ ... # firmware has no such command; permanent, so stop offering the feature
168
+ except HarborCommandError as err:
169
+ print(err.status, err.errors) # e.g. "REQUEST_MALFORMED", [{"error_code": "INVALID_VALUE", ...}]
170
+ ```
171
+
172
+ `HarborUnsupportedCommandError` is a subclass of `HarborCommandError`, raised
173
+ only on a `RESOURCE_NOT_FOUND` status. That means the firmware has no handler
174
+ for the command at all, so retrying can never succeed.
175
+
176
+ ### Firmware compatibility
177
+
178
+ Commands are verified against real hardware, most recently a camera running
179
+ `os_version` **2.8.0** / `app_version` **2.8.0-rc1+c1b0a32**: `ping`,
180
+ `get-settings`, `update-settings`, `pause-stream`, `unpause-stream`,
181
+ `set-night-mode-ir-brightness`, `update-operating-mode`, `set-scheduled-reboot`
182
+ and `list-viewers` all respond `OK`. See `mqtt_home_assistant.md` for the full
183
+ audit and payload shapes.
184
+
107
185
  ## WHIP Endpoint
108
186
 
109
187
  Harbor cameras allow custom WHIP endpoints. This tells the camera where to stream and works with tools that support WHIP, including go2rtc and Frigate.
@@ -5,12 +5,21 @@ from .data.mqtt_models import (
5
5
  HeartbeatEvent,
6
6
  LocalLivekitHeartbeatEvent,
7
7
  MotionDetectedEvent,
8
+ Settings,
8
9
  SettingsEvent,
10
+ SettingsState,
11
+ UpdateCameraSettingsRequest,
9
12
  ViewerJoinedEvent,
10
13
  ViewerLeftEvent,
11
14
  )
12
15
  from .device import HarborDevice
13
- from .devices.camera import SPEAKER_STATES, STREAM_QUALITIES, HarborCamera
16
+ from .devices.camera import (
17
+ NIGHT_MODE_PREFERENCES,
18
+ SPEAKER_STATES,
19
+ STREAM_QUALITIES,
20
+ TEMPERATURE_SCALE_VALUES,
21
+ HarborCamera,
22
+ )
14
23
  from .devices.monitor import HarborMonitor
15
24
  from .events import (
16
25
  CameraEventUpdate,
@@ -27,12 +36,27 @@ from .events import (
27
36
  ViewerLeftUpdate,
28
37
  parse_message,
29
38
  )
30
- from .mqtt import HarborMQTTClient
39
+ from .exceptions import HarborCommandError, HarborUnsupportedCommandError
40
+ from .mqtt import (
41
+ CLOCK_DISPLAY_PREFERENCE_KEY,
42
+ DEFAULT_NIGHT_MODE,
43
+ DEFAULT_TEMPERATURE_SCALE,
44
+ NIGHT_MODE_MODES,
45
+ NIGHT_MODE_PREFERENCE_KEY,
46
+ TEMPERATURE_SCALE_PREFERENCE_KEY,
47
+ TEMPERATURE_SCALES,
48
+ VIDEO_FLIP_PREFERENCE_KEY,
49
+ HarborMQTTClient,
50
+ NightMode,
51
+ TemperatureScale,
52
+ )
31
53
  from .state import HarborDeviceState, HarborEventState, HarborSourceType, HarborViewer
32
54
 
33
55
  __all__ = [
34
56
  "Harbor",
35
57
  "HarborCameraConfig",
58
+ "HarborCommandError",
59
+ "HarborUnsupportedCommandError",
36
60
  "HarborMQTTClient",
37
61
  "HarborDevice",
38
62
  "HarborCamera",
@@ -51,9 +75,12 @@ __all__ = [
51
75
  "ViewerInfo",
52
76
  "parse_message",
53
77
  "GetCameraSettingsRequest",
78
+ "UpdateCameraSettingsRequest",
54
79
  "HeartbeatEvent",
55
80
  "LocalLivekitHeartbeatEvent",
81
+ "Settings",
56
82
  "SettingsEvent",
83
+ "SettingsState",
57
84
  "ViewerJoinedEvent",
58
85
  "ViewerLeftEvent",
59
86
  "MotionDetectedEvent",
@@ -61,6 +88,18 @@ __all__ = [
61
88
  "HarborViewer",
62
89
  "HarborEventState",
63
90
  "HarborDeviceState",
91
+ "NightMode",
92
+ "NIGHT_MODE_MODES",
93
+ "NIGHT_MODE_PREFERENCE_KEY",
94
+ "NIGHT_MODE_PREFERENCES",
95
+ "DEFAULT_NIGHT_MODE",
96
+ "VIDEO_FLIP_PREFERENCE_KEY",
97
+ "CLOCK_DISPLAY_PREFERENCE_KEY",
98
+ "TemperatureScale",
99
+ "TEMPERATURE_SCALES",
100
+ "TEMPERATURE_SCALE_PREFERENCE_KEY",
101
+ "TEMPERATURE_SCALE_VALUES",
102
+ "DEFAULT_TEMPERATURE_SCALE",
64
103
  "SPEAKER_STATES",
65
104
  "STREAM_QUALITIES",
66
105
  ]
@@ -4,7 +4,12 @@ from typing import Any
4
4
  from .config import HarborCameraConfig
5
5
  from .data.mqtt_models import SettingsEvent
6
6
  from .device import HarborDevice
7
- from .mqtt import DEFAULT_INITIAL_COMMANDS, HarborMQTTClient
7
+ from .mqtt import (
8
+ DEFAULT_INITIAL_COMMANDS,
9
+ HarborMQTTClient,
10
+ NightMode,
11
+ TemperatureScale,
12
+ )
8
13
 
9
14
  _LOGGER = logging.getLogger(__name__)
10
15
 
@@ -85,6 +90,89 @@ class Harbor:
85
90
  """Request the camera settings payload."""
86
91
  return await self._get_client(serial).get_settings(timeout=timeout)
87
92
 
93
+ async def set_camera_on(
94
+ self,
95
+ serial: str,
96
+ camera_on: bool,
97
+ *,
98
+ viewer_id: str | None = None,
99
+ timeout: float = 10.0,
100
+ ) -> None:
101
+ """Turn a camera stream on or off and refresh its settings."""
102
+ await self._get_client(serial).set_camera_on(
103
+ camera_on,
104
+ viewer_id=viewer_id,
105
+ timeout=timeout,
106
+ )
107
+
108
+ async def set_night_mode(
109
+ self,
110
+ serial: str,
111
+ night_mode: NightMode,
112
+ *,
113
+ timeout: float = 10.0,
114
+ ) -> None:
115
+ """Set the camera night-mode preference and refresh its settings.
116
+
117
+ ``night_mode`` is one of ``"auto"``, ``"on"`` or ``"off"``.
118
+ """
119
+ await self._get_client(serial).set_night_mode(
120
+ night_mode,
121
+ timeout=timeout,
122
+ )
123
+
124
+ async def set_temperature_scale(
125
+ self,
126
+ serial: str,
127
+ temperature_scale: TemperatureScale,
128
+ *,
129
+ timeout: float = 10.0,
130
+ ) -> None:
131
+ """Set the camera temperature unit (``"F"`` or ``"C"``)."""
132
+ await self._get_client(serial).set_temperature_scale(
133
+ temperature_scale,
134
+ timeout=timeout,
135
+ )
136
+
137
+ async def set_video_flip(
138
+ self,
139
+ serial: str,
140
+ video_flip: bool,
141
+ *,
142
+ timeout: float = 10.0,
143
+ ) -> None:
144
+ """Rotate the camera image 180 degrees and refresh its settings."""
145
+ await self._get_client(serial).set_video_flip(
146
+ video_flip,
147
+ timeout=timeout,
148
+ )
149
+
150
+ async def set_clock_display(
151
+ self,
152
+ serial: str,
153
+ clock_display: bool,
154
+ *,
155
+ timeout: float = 10.0,
156
+ ) -> None:
157
+ """Show or hide the video clock overlay and refresh its settings."""
158
+ await self._get_client(serial).set_clock_display(
159
+ clock_display,
160
+ timeout=timeout,
161
+ )
162
+
163
+ async def update_camera_settings(
164
+ self,
165
+ serial: str,
166
+ settings: dict[str, Any],
167
+ *,
168
+ timeout: float = 10.0,
169
+ ) -> None:
170
+ """Write camera preferences and refresh its settings."""
171
+ await self._get_client(serial).update_settings(
172
+ settings,
173
+ timeout=timeout,
174
+ )
175
+
88
176
  async def handle_message(self, topic: str, payload: Any) -> None:
89
177
  """
90
178
  Central message handler.
@@ -45,7 +45,12 @@ class HeartbeatEvent(HarborMQTTPayload):
45
45
 
46
46
 
47
47
  class Settings(HarborMQTTPayload):
48
- """Camera settings included with a settings event."""
48
+ """Camera settings included with a settings event.
49
+
50
+ These are the writable *preferences*. Send changes with the
51
+ ``update-settings`` command; do not confuse them with the device-driven
52
+ runtime values in :class:`SettingsState`.
53
+ """
49
54
 
50
55
  log_level: str | None = None
51
56
  preference_ai: dict[str, Any] = Field(default_factory=dict)
@@ -56,36 +61,55 @@ class Settings(HarborMQTTPayload):
56
61
  preference_connection_bssid: str | None = None
57
62
  preference_display_name: str | None = None
58
63
  preference_moment_length: int | None = None
64
+ preference_no_alert_windows: list[Any] = Field(default_factory=list)
59
65
  preference_operating_mode: str | None = None
60
66
  preference_scheduled_reboot: str | None = None
61
67
  preference_silence_alerting_until: str | None = None
68
+ preference_stream_config: dict[str, Any] = Field(default_factory=dict)
62
69
  preference_stream_paused: bool | None = None
70
+ preference_temperature_calibration_offset: float | None = None
71
+ preference_temperature_scale: str | None = None
72
+ preference_video_brightness_low_light: int | None = None
63
73
  preference_video_clock_display_tz_abbrev: str | None = None
64
74
  preference_video_clock_display_tz_offset: int | None = None
65
75
  preference_video_flip: bool | None = None
66
76
  preference_video_has_clock_display: bool | None = None
67
77
  preference_video_ir_brightness: int | None = None
78
+ #: Night-mode *preference*: one of ``"auto"``, ``"on"`` or ``"off"``
79
+ #: (default ``"auto"``). This is what ``update-settings`` writes.
68
80
  preference_video_night_mode: str | None = None
69
81
 
70
82
 
71
83
  class SettingsState(HarborMQTTPayload):
72
- """Runtime state attached to a settings event."""
84
+ """Runtime state attached to a settings event.
85
+
86
+ Read-only observations owned by the device. Nothing here can be written;
87
+ use :class:`Settings` for that.
88
+ """
73
89
 
74
90
  application_state: int | None = None
75
91
  network_bars: int | None = None
76
92
  stream_state: int | None = None
77
93
  temperature: float | None = None
94
+ #: Whether IR night vision is engaged *right now*. Device-driven: under
95
+ #: the ``"auto"`` preference it flips on its own as light levels change,
96
+ #: so it reflects the camera, not the last command sent.
78
97
  video_night_mode: bool | None = None
98
+ volume_baseline_current: float | None = None
99
+ volume_baseline_reference: float | None = None
100
+ volume_threshold_effective: float | None = None
79
101
 
80
102
 
81
103
  class SettingsEvent(HarborMQTTPayload):
82
104
  """Payload for a settings event."""
83
105
 
84
106
  client: str | None = None
107
+ errors: list[Any] = Field(default_factory=list)
85
108
  is_updating: bool | None = Field(default=None, alias="isUpdating")
86
109
  seq: str | None = None
87
110
  settings: Settings | None = None
88
111
  state: SettingsState | None = None
112
+ status: str | None = None
89
113
  triggered_by: str | None = Field(default=None, alias="triggeredBy")
90
114
  updated: dict[str, Any] = Field(default_factory=dict)
91
115
 
@@ -98,6 +122,20 @@ class GetCameraSettingsRequest(HarborMQTTPayload):
98
122
  triggered_by: str = Field(alias="triggeredBy")
99
123
 
100
124
 
125
+ class UpdateCameraSettingsRequest(HarborMQTTPayload):
126
+ """Payload for the update-settings camera command.
127
+
128
+ ``settings`` carries only the preference keys being changed; the camera
129
+ merges them into its existing configuration and echoes back the applied
130
+ subset.
131
+ """
132
+
133
+ seq: str
134
+ settings: dict[str, Any]
135
+ client: str
136
+ triggered_by: str = Field(alias="triggeredBy")
137
+
138
+
101
139
  class ViewerJoinedEvent(HarborMQTTPayload):
102
140
  """Payload for a viewer joined event."""
103
141
 
@@ -4,11 +4,13 @@ import asyncio
4
4
  import logging
5
5
 
6
6
  from ..config import HarborCameraConfig
7
+ from ..data.mqtt_models import SettingsEvent
7
8
  from ..device import HarborDevice
8
9
  from ..events import (
9
10
  CameraEventUpdate,
10
11
  HarborEvent,
11
12
  LocalLivekitHeartbeatUpdate,
13
+ SettingsUpdate,
12
14
  ViewerInfo,
13
15
  ViewerJoinedUpdate,
14
16
  ViewerLeftUpdate,
@@ -29,6 +31,13 @@ DEFAULT_EVENT_ACTIVE_SECONDS = 5.0
29
31
  UNKNOWN_ENUM_VALUE = "unknown"
30
32
  SPEAKER_STATES = frozenset({"idle", "muted", "off", "paused", "playing", "unknown"})
31
33
  STREAM_QUALITIES = frozenset({"excellent", "fair", "good", "poor", "unknown"})
34
+ # Accepted values for the writable night-mode preference, per the schema the
35
+ # firmware returns when it rejects an invalid value.
36
+ NIGHT_MODE_PREFERENCES = frozenset({"auto", "on", "off", "unknown"})
37
+ # Settings whose value is matched verbatim by the device, so unlike the state
38
+ # enums above they are stored with their case intact -- a consumer must be able
39
+ # to write back exactly what it read.
40
+ TEMPERATURE_SCALE_VALUES = frozenset({"F", "C"})
32
41
 
33
42
 
34
43
  class HarborCamera(HarborDevice):
@@ -58,6 +67,8 @@ class HarborCamera(HarborDevice):
58
67
  match event:
59
68
  case LocalLivekitHeartbeatUpdate(payload=payload, viewers=viewers):
60
69
  self._apply_local_livekit_heartbeat(payload, viewers)
70
+ case SettingsUpdate(payload=payload):
71
+ self._apply_camera_settings(payload)
61
72
  case ViewerJoinedUpdate(viewer=viewer):
62
73
  self._apply_viewer_joined(viewer)
63
74
  case ViewerLeftUpdate(viewer_id=viewer_id):
@@ -65,6 +76,66 @@ class HarborCamera(HarborDevice):
65
76
  case CameraEventUpdate():
66
77
  self._apply_camera_event(event)
67
78
 
79
+ def _apply_camera_settings(self, payload: SettingsEvent) -> None:
80
+ """Apply camera controls exposed by a settings payload.
81
+
82
+ Night mode is two distinct values and both are surfaced:
83
+ ``night_mode_preference`` is the ``auto``/``on``/``off`` setting a
84
+ command writes and reads back, while ``night_mode`` is the runtime
85
+ observation of whether IR is engaged right now — which the device
86
+ flips on its own under the ``auto`` preference.
87
+ """
88
+ if payload.settings is not None:
89
+ if payload.settings.preference_stream_paused is not None:
90
+ self.state.values["camera_on"] = not payload.settings.preference_stream_paused
91
+ if payload.settings.preference_video_flip is not None:
92
+ self.state.values["video_flip"] = payload.settings.preference_video_flip
93
+ if payload.settings.preference_video_has_clock_display is not None:
94
+ self.state.values["clock_display"] = payload.settings.preference_video_has_clock_display
95
+ if payload.settings.preference_video_night_mode is not None:
96
+ self.state.values["night_mode_preference"] = self._normalize_enum_value(
97
+ "night_mode_preference",
98
+ payload.settings.preference_video_night_mode,
99
+ NIGHT_MODE_PREFERENCES,
100
+ )
101
+ if payload.settings.preference_temperature_scale is not None:
102
+ self.state.values["temperature_scale"] = self._normalize_choice_value(
103
+ "temperature_scale",
104
+ payload.settings.preference_temperature_scale,
105
+ TEMPERATURE_SCALE_VALUES,
106
+ )
107
+ if payload.state is not None and payload.state.video_night_mode is not None:
108
+ self.state.values["night_mode"] = payload.state.video_night_mode
109
+
110
+ def _normalize_choice_value(
111
+ self,
112
+ field_name: str,
113
+ value: str | None,
114
+ known_values: frozenset[str],
115
+ ) -> str | None:
116
+ """Clamp a settings value to a known member, preserving its case.
117
+
118
+ Used for preferences the device matches verbatim (``"F"``, not
119
+ ``"f"``), so what a consumer reads back is exactly what it can write.
120
+ Unlike :meth:`_normalize_enum_value` this never lowercases.
121
+ """
122
+ if value is None:
123
+ return None
124
+ if not value.strip():
125
+ return None
126
+ if value not in known_values:
127
+ if (field_name, value) not in self._unexpected_enum_values:
128
+ self._unexpected_enum_values.add((field_name, value))
129
+ _LOGGER.warning(
130
+ "Camera %s reported unexpected %s value %r (known values: %s)",
131
+ self.serial,
132
+ field_name,
133
+ value,
134
+ sorted(known_values),
135
+ )
136
+ return UNKNOWN_ENUM_VALUE
137
+ return value
138
+
68
139
  def _apply_local_livekit_heartbeat(
69
140
  self,
70
141
  payload,
@@ -293,52 +293,52 @@ def parse_message(
293
293
  }
294
294
 
295
295
  if event_key == "heartbeat":
296
- if typed_payload := _validate_payload(HeartbeatEvent, raw_payload, topic):
297
- return HeartbeatUpdate(payload=typed_payload, **base_kwargs)
296
+ if heartbeat_payload := _validate_payload(HeartbeatEvent, raw_payload, topic):
297
+ return HeartbeatUpdate(payload=heartbeat_payload, **base_kwargs)
298
298
  return RawEventUpdate(payload=raw_payload, **base_kwargs)
299
299
 
300
300
  if event_key == "local_livekit_heartbeat":
301
- if typed_payload := _validate_payload(LocalLivekitHeartbeatEvent, raw_payload, topic):
301
+ if livekit_payload := _validate_payload(LocalLivekitHeartbeatEvent, raw_payload, topic):
302
302
  return LocalLivekitHeartbeatUpdate(
303
- payload=typed_payload,
304
- viewers=_extract_viewers_from_local_livekit(typed_payload),
303
+ payload=livekit_payload,
304
+ viewers=_extract_viewers_from_local_livekit(livekit_payload),
305
305
  **base_kwargs,
306
306
  )
307
307
  return RawEventUpdate(payload=raw_payload, **base_kwargs)
308
308
 
309
309
  if event_key == "viewer_joined":
310
- if typed_payload := _validate_payload(ViewerJoinedEvent, raw_payload, topic):
310
+ if viewer_joined_payload := _validate_payload(ViewerJoinedEvent, raw_payload, topic):
311
311
  return ViewerJoinedUpdate(
312
- payload=typed_payload,
312
+ payload=viewer_joined_payload,
313
313
  viewer=_extract_viewer_info_from_payload(raw_payload)
314
314
  or _extract_viewer_info(
315
- typed_payload.viewer_id,
316
- typed_payload.identity,
317
- typed_payload.client,
318
- typed_payload.is_local,
319
- typed_payload.role,
315
+ viewer_joined_payload.viewer_id,
316
+ viewer_joined_payload.identity,
317
+ viewer_joined_payload.client,
318
+ viewer_joined_payload.is_local,
319
+ viewer_joined_payload.role,
320
320
  ),
321
321
  **base_kwargs,
322
322
  )
323
323
  return RawEventUpdate(payload=raw_payload, **base_kwargs)
324
324
 
325
325
  if event_key == "viewer_left":
326
- if typed_payload := _validate_payload(ViewerLeftEvent, raw_payload, topic):
326
+ if viewer_left_payload := _validate_payload(ViewerLeftEvent, raw_payload, topic):
327
327
  return ViewerLeftUpdate(
328
- payload=typed_payload,
328
+ payload=viewer_left_payload,
329
329
  viewer_id=_extract_viewer_id_from_payload(raw_payload)
330
330
  or _coalesce_string(
331
- typed_payload.viewer_id,
332
- typed_payload.identity,
333
- typed_payload.client,
331
+ viewer_left_payload.viewer_id,
332
+ viewer_left_payload.identity,
333
+ viewer_left_payload.client,
334
334
  ),
335
335
  **base_kwargs,
336
336
  )
337
337
  return RawEventUpdate(payload=raw_payload, **base_kwargs)
338
338
 
339
339
  if event_key in {"settings", "get_settings"}:
340
- if typed_payload := _validate_payload(SettingsEvent, raw_payload, topic):
341
- return SettingsUpdate(payload=typed_payload, **base_kwargs)
340
+ if settings_payload := _validate_payload(SettingsEvent, raw_payload, topic):
341
+ return SettingsUpdate(payload=settings_payload, **base_kwargs)
342
342
  return RawEventUpdate(payload=raw_payload, **base_kwargs)
343
343
 
344
344
  if source_type == "camera":
@@ -346,9 +346,9 @@ def parse_message(
346
346
  explicit_state = extract_explicit_event_state(raw_payload)
347
347
 
348
348
  if event_key == "motion_detection":
349
- if typed_payload := _validate_payload(MotionDetectedEvent, raw_payload, topic):
349
+ if motion_payload := _validate_payload(MotionDetectedEvent, raw_payload, topic):
350
350
  return MotionDetectedUpdate(
351
- payload=typed_payload,
351
+ payload=motion_payload,
352
352
  active_seconds=active_seconds,
353
353
  explicit_state=explicit_state,
354
354
  **base_kwargs,
@@ -0,0 +1,55 @@
1
+ from __future__ import annotations
2
+
3
+ from typing import Any
4
+
5
+ #: Status returned when the firmware has no handler registered for a command.
6
+ #: This is permanent for a given firmware build, not a transient failure.
7
+ RESOURCE_NOT_FOUND_STATUS = "RESOURCE_NOT_FOUND"
8
+
9
+
10
+ class HarborCommandError(Exception):
11
+ """Raised when a Harbor camera rejects a command.
12
+
13
+ ``status`` is the parsed ``status`` field of the camera response (upper
14
+ cased), or ``None`` when the camera reported a bare ``error`` with no
15
+ status. ``errors`` holds the per-field ``errors`` array the firmware
16
+ returns for validation failures, each entry carrying ``error_code``,
17
+ ``key``, ``value`` and the accepted ``schema``.
18
+ """
19
+
20
+ def __init__(self, command: str, response: Any) -> None:
21
+ self.command = command
22
+ self.response = response
23
+ self.status = _parse_status(response)
24
+ self.errors = _parse_errors(response)
25
+ super().__init__(f"Harbor camera rejected command {command!r}: {response!r}")
26
+
27
+
28
+ class HarborUnsupportedCommandError(HarborCommandError):
29
+ """Raised when the camera firmware has no handler for a command.
30
+
31
+ The camera answered ``RESOURCE_NOT_FOUND``, which means this firmware
32
+ build does not implement the command at all. Retrying cannot succeed, so
33
+ consumers should skip the feature (for example, decline to create an
34
+ entity) rather than surface a failure on every use.
35
+ """
36
+
37
+
38
+ def _parse_status(response: Any) -> str | None:
39
+ """Return the upper-cased status string from a camera response."""
40
+ if not isinstance(response, dict):
41
+ return None
42
+ status = response.get("status")
43
+ if status is None:
44
+ return None
45
+ return str(status).upper()
46
+
47
+
48
+ def _parse_errors(response: Any) -> list[Any]:
49
+ """Return the per-field error details from a camera response."""
50
+ if not isinstance(response, dict):
51
+ return []
52
+ errors = response.get("errors")
53
+ if isinstance(errors, list):
54
+ return errors
55
+ return []
@@ -5,13 +5,22 @@ import json
5
5
  import logging
6
6
  import sys
7
7
  from collections.abc import Awaitable, Callable
8
- from typing import TYPE_CHECKING, Any
8
+ from typing import TYPE_CHECKING, Any, Literal
9
9
  from uuid import uuid4
10
10
 
11
11
  from aiomqtt import Client, MqttError
12
12
 
13
13
  from .config import HarborCameraConfig
14
- from .data.mqtt_models import GetCameraSettingsRequest, SettingsEvent
14
+ from .data.mqtt_models import (
15
+ GetCameraSettingsRequest,
16
+ SettingsEvent,
17
+ UpdateCameraSettingsRequest,
18
+ )
19
+ from .exceptions import (
20
+ RESOURCE_NOT_FOUND_STATUS,
21
+ HarborCommandError,
22
+ HarborUnsupportedCommandError,
23
+ )
15
24
  from .utils import get_camera_host, get_ssl_cache_key, get_ssl_context
16
25
 
17
26
  if TYPE_CHECKING:
@@ -19,12 +28,44 @@ if TYPE_CHECKING:
19
28
 
20
29
  _LOGGER = logging.getLogger(__name__)
21
30
 
31
+ #: Night mode is a three-way preference on the device, not an on/off switch.
32
+ NightMode = Literal["auto", "on", "off"]
33
+
34
+ #: Unit the camera reports temperatures in. Case-sensitive on the wire.
35
+ TemperatureScale = Literal["F", "C"]
36
+
22
37
  DEFAULT_CONNECTION_GRACE_PERIOD = 90.0
23
38
  DEFAULT_COMMAND_QOS = 2
24
39
  DEFAULT_REQUEST_TIMEOUT = 10.0
25
40
  GET_SETTINGS_COMMAND = "get-settings"
41
+ UPDATE_SETTINGS_COMMAND = "update-settings"
42
+ PAUSE_STREAM_COMMAND = "pause-stream"
43
+ UNPAUSE_STREAM_COMMAND = "unpause-stream"
26
44
  DEFAULT_INITIAL_COMMANDS = (GET_SETTINGS_COMMAND,)
27
45
 
46
+ #: Settings key holding the writable night-mode preference.
47
+ NIGHT_MODE_PREFERENCE_KEY = "preference_video_night_mode"
48
+
49
+ #: Accepted night-mode values, as reported by the firmware itself: rejecting an
50
+ #: invalid value returns ``{"options": ["auto", "on", "off"], "default": "auto"}``.
51
+ #: Night mode is a three-way preference, not a boolean.
52
+ NIGHT_MODE_MODES: tuple[NightMode, ...] = ("auto", "on", "off")
53
+ DEFAULT_NIGHT_MODE: NightMode = "auto"
54
+
55
+ #: Settings key for rotating the video image 180 degrees. Genuinely a boolean:
56
+ #: the firmware reports ``{"default": false, "type": "boolean"}``.
57
+ VIDEO_FLIP_PREFERENCE_KEY = "preference_video_flip"
58
+
59
+ #: Settings key for the on-video clock overlay. Genuinely a boolean:
60
+ #: the firmware reports ``{"default": true, "type": "boolean"}``.
61
+ CLOCK_DISPLAY_PREFERENCE_KEY = "preference_video_has_clock_display"
62
+
63
+ #: Settings key for the temperature unit. Firmware schema:
64
+ #: ``{"default": "F", "options": ["F", "C"], "type": "string"}``.
65
+ TEMPERATURE_SCALE_PREFERENCE_KEY = "preference_temperature_scale"
66
+ TEMPERATURE_SCALES: tuple[TemperatureScale, ...] = ("F", "C")
67
+ DEFAULT_TEMPERATURE_SCALE: TemperatureScale = "F"
68
+
28
69
 
29
70
  class HarborMQTTClient:
30
71
  def __init__(
@@ -360,7 +401,7 @@ class HarborMQTTClient:
360
401
  request = GetCameraSettingsRequest(
361
402
  seq=seq or _generate_seq(),
362
403
  client=client or self.client_id or f"harbor-client-{self.config.serial}",
363
- triggered_by=triggered_by or "harbor-python",
404
+ triggeredBy=triggered_by or "harbor-python",
364
405
  )
365
406
  return request.model_dump(by_alias=True)
366
407
 
@@ -410,6 +451,169 @@ class HarborMQTTClient:
410
451
  )
411
452
  return SettingsEvent.model_validate(response)
412
453
 
454
+ async def set_camera_on(
455
+ self,
456
+ camera_on: bool,
457
+ *,
458
+ viewer_id: str | None = None,
459
+ timeout: float = DEFAULT_REQUEST_TIMEOUT,
460
+ ) -> None:
461
+ """Turn the camera stream on or off and refresh its settings."""
462
+ command = UNPAUSE_STREAM_COMMAND if camera_on else PAUSE_STREAM_COMMAND
463
+ await self._request_camera_control(
464
+ command,
465
+ {"viewer_id": viewer_id or self.client_id or f"harbor-client-{self.config.serial}"},
466
+ timeout=timeout,
467
+ )
468
+ await self._refresh_settings_after_command(command, timeout=timeout)
469
+
470
+ async def set_night_mode(
471
+ self,
472
+ night_mode: NightMode,
473
+ *,
474
+ timeout: float = DEFAULT_REQUEST_TIMEOUT,
475
+ ) -> None:
476
+ """Set the camera night-mode preference and refresh its settings.
477
+
478
+ ``night_mode`` is one of ``"auto"``, ``"on"`` or ``"off"`` — the
479
+ device models night mode as a three-way preference, so booleans are
480
+ rejected rather than guessed at. ``"auto"`` lets the camera engage IR
481
+ on its own in low light; the resulting runtime state is reported
482
+ separately as ``SettingsState.video_night_mode``.
483
+ """
484
+ _require_choice(
485
+ "night_mode",
486
+ night_mode,
487
+ NIGHT_MODE_MODES,
488
+ "Night mode is a three-way preference, not a boolean.",
489
+ )
490
+ await self.update_settings({NIGHT_MODE_PREFERENCE_KEY: night_mode}, timeout=timeout)
491
+
492
+ async def set_temperature_scale(
493
+ self,
494
+ temperature_scale: TemperatureScale,
495
+ *,
496
+ timeout: float = DEFAULT_REQUEST_TIMEOUT,
497
+ ) -> None:
498
+ """Set the unit the camera reports temperatures in.
499
+
500
+ ``temperature_scale`` is ``"F"`` or ``"C"``, upper case — the device
501
+ matches the value exactly.
502
+ """
503
+ _require_choice("temperature_scale", temperature_scale, TEMPERATURE_SCALES)
504
+ await self.update_settings(
505
+ {TEMPERATURE_SCALE_PREFERENCE_KEY: temperature_scale},
506
+ timeout=timeout,
507
+ )
508
+
509
+ async def set_video_flip(
510
+ self,
511
+ video_flip: bool,
512
+ *,
513
+ timeout: float = DEFAULT_REQUEST_TIMEOUT,
514
+ ) -> None:
515
+ """Rotate the camera image 180 degrees, or restore it upright."""
516
+ await self.update_settings(
517
+ {VIDEO_FLIP_PREFERENCE_KEY: _require_bool("video_flip", video_flip)},
518
+ timeout=timeout,
519
+ )
520
+
521
+ async def set_clock_display(
522
+ self,
523
+ clock_display: bool,
524
+ *,
525
+ timeout: float = DEFAULT_REQUEST_TIMEOUT,
526
+ ) -> None:
527
+ """Show or hide the clock overlay burned into the video."""
528
+ await self.update_settings(
529
+ {CLOCK_DISPLAY_PREFERENCE_KEY: _require_bool("clock_display", clock_display)},
530
+ timeout=timeout,
531
+ )
532
+
533
+ async def update_settings(
534
+ self,
535
+ settings: dict[str, Any],
536
+ *,
537
+ client: str | None = None,
538
+ triggered_by: str | None = None,
539
+ timeout: float = DEFAULT_REQUEST_TIMEOUT,
540
+ ) -> None:
541
+ """Write camera preferences via the update-settings command.
542
+
543
+ ``settings`` maps preference keys (as they appear under ``settings``
544
+ in a ``get-settings`` response) to their new values. The camera
545
+ validates each key and returns a per-field ``errors`` array when a
546
+ value is out of range, which is surfaced on
547
+ :class:`~harbor.exceptions.HarborCommandError`.
548
+ """
549
+ request = UpdateCameraSettingsRequest(
550
+ seq=_generate_seq(),
551
+ settings=settings,
552
+ client=client or self.client_id or f"harbor-client-{self.config.serial}",
553
+ triggeredBy=triggered_by or "harbor-python",
554
+ )
555
+ payload = request.model_dump(by_alias=True)
556
+ await self._request_camera_control(
557
+ UPDATE_SETTINGS_COMMAND,
558
+ payload,
559
+ seq=payload["seq"],
560
+ timeout=timeout,
561
+ )
562
+ await self._refresh_settings_after_command(
563
+ UPDATE_SETTINGS_COMMAND,
564
+ timeout=timeout,
565
+ )
566
+
567
+ async def _request_camera_control(
568
+ self,
569
+ command: str,
570
+ payload: dict[str, Any],
571
+ *,
572
+ seq: str | None = None,
573
+ timeout: float,
574
+ ) -> Any:
575
+ """Run a camera control command and reject error responses.
576
+
577
+ A ``RESOURCE_NOT_FOUND`` status means this firmware build has no
578
+ handler for the command, which no amount of retrying will fix, so it
579
+ is raised as :class:`HarborUnsupportedCommandError` to let consumers
580
+ skip the feature instead of failing on every use.
581
+ """
582
+ response = await self.request_command(command, payload, seq=seq, timeout=timeout)
583
+ if not isinstance(response, dict):
584
+ return response
585
+
586
+ status = response.get("status")
587
+ status_text = None if status is None else str(status).upper()
588
+ if not (response.get("error") or response.get("errors") or (status_text is not None and status_text != "OK")):
589
+ return response
590
+
591
+ if status_text == RESOURCE_NOT_FOUND_STATUS:
592
+ _LOGGER.warning(
593
+ "Harbor: camera %s firmware does not support command %s",
594
+ self.config.serial,
595
+ command,
596
+ )
597
+ raise HarborUnsupportedCommandError(command, response)
598
+ raise HarborCommandError(command, response)
599
+
600
+ async def _refresh_settings_after_command(
601
+ self,
602
+ command: str,
603
+ *,
604
+ timeout: float,
605
+ ) -> None:
606
+ """Refresh settings without turning a successful command into a failure."""
607
+ try:
608
+ await self.get_settings(timeout=timeout)
609
+ except (ConnectionError, MqttError, TimeoutError):
610
+ _LOGGER.debug(
611
+ "Unable to refresh settings after Harbor command %s for camera %s",
612
+ command,
613
+ self.config.serial,
614
+ exc_info=True,
615
+ )
616
+
413
617
  def __del__(self) -> None:
414
618
  if self._stop_event and not self._stop_event.is_set():
415
619
  self._stop_event.set()
@@ -418,3 +622,26 @@ class HarborMQTTClient:
418
622
  def _generate_seq() -> str:
419
623
  """Generate a request sequence string echoed by Harbor responses."""
420
624
  return uuid4().hex
625
+
626
+
627
+ def _require_choice(name: str, value: Any, choices: tuple[str, ...], hint: str = "") -> str:
628
+ """Reject a value outside the set the firmware accepts for a setting.
629
+
630
+ Matching is exact: the device compares the string verbatim, so a
631
+ differently-cased value would be rejected on the wire anyway.
632
+ """
633
+ if not isinstance(value, str) or value not in choices:
634
+ message = f"{name} must be one of {choices!r}, got {value!r}"
635
+ raise ValueError(f"{message}. {hint}" if hint else message)
636
+ return value
637
+
638
+
639
+ def _require_bool(name: str, value: Any) -> bool:
640
+ """Reject non-boolean input for a setting the device types as a boolean.
641
+
642
+ ``1``/``0`` are ``int`` and would serialize as numbers, which the firmware
643
+ rejects, so they are refused here with a clearer message.
644
+ """
645
+ if not isinstance(value, bool):
646
+ raise ValueError(f"{name} must be a bool, got {value!r}")
647
+ return value
@@ -1,6 +1,6 @@
1
1
  [project]
2
2
  name = "harbor-python"
3
- version = "1.3.0"
3
+ version = "1.5.0"
4
4
  description = "Async local client for Harbor Sleep Cameras"
5
5
  authors = [{name="Andres Garcia"},{name = "Lash-L"}]
6
6
  readme = "README.md"
File without changes
File without changes