harbor-python 1.4.0__py3-none-any.whl → 1.6.1__py3-none-any.whl

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.
harbor/__init__.py CHANGED
@@ -5,12 +5,22 @@ from .data.mqtt_models import (
5
5
  HeartbeatEvent,
6
6
  LocalLivekitHeartbeatEvent,
7
7
  MotionDetectedEvent,
8
+ NoiseDetectedEvent,
9
+ Settings,
8
10
  SettingsEvent,
11
+ SettingsState,
12
+ UpdateCameraSettingsRequest,
9
13
  ViewerJoinedEvent,
10
14
  ViewerLeftEvent,
11
15
  )
12
16
  from .device import HarborDevice
13
- from .devices.camera import SPEAKER_STATES, STREAM_QUALITIES, HarborCamera
17
+ from .devices.camera import (
18
+ NIGHT_MODE_PREFERENCES,
19
+ SPEAKER_STATES,
20
+ STREAM_QUALITIES,
21
+ TEMPERATURE_SCALE_VALUES,
22
+ HarborCamera,
23
+ )
14
24
  from .devices.monitor import HarborMonitor
15
25
  from .events import (
16
26
  CameraEventUpdate,
@@ -20,6 +30,7 @@ from .events import (
20
30
  HeartbeatUpdate,
21
31
  LocalLivekitHeartbeatUpdate,
22
32
  MotionDetectedUpdate,
33
+ NoiseDetectedUpdate,
23
34
  RawEventUpdate,
24
35
  SettingsUpdate,
25
36
  ViewerInfo,
@@ -27,14 +38,27 @@ from .events import (
27
38
  ViewerLeftUpdate,
28
39
  parse_message,
29
40
  )
30
- from .exceptions import HarborCommandError
31
- from .mqtt import HarborMQTTClient
41
+ from .exceptions import HarborCommandError, HarborUnsupportedCommandError
42
+ from .mqtt import (
43
+ CLOCK_DISPLAY_PREFERENCE_KEY,
44
+ DEFAULT_NIGHT_MODE,
45
+ DEFAULT_TEMPERATURE_SCALE,
46
+ NIGHT_MODE_MODES,
47
+ NIGHT_MODE_PREFERENCE_KEY,
48
+ TEMPERATURE_SCALE_PREFERENCE_KEY,
49
+ TEMPERATURE_SCALES,
50
+ VIDEO_FLIP_PREFERENCE_KEY,
51
+ HarborMQTTClient,
52
+ NightMode,
53
+ TemperatureScale,
54
+ )
32
55
  from .state import HarborDeviceState, HarborEventState, HarborSourceType, HarborViewer
33
56
 
34
57
  __all__ = [
35
58
  "Harbor",
36
59
  "HarborCameraConfig",
37
60
  "HarborCommandError",
61
+ "HarborUnsupportedCommandError",
38
62
  "HarborMQTTClient",
39
63
  "HarborDevice",
40
64
  "HarborCamera",
@@ -50,19 +74,36 @@ __all__ = [
50
74
  "SettingsUpdate",
51
75
  "CameraEventUpdate",
52
76
  "MotionDetectedUpdate",
77
+ "NoiseDetectedUpdate",
53
78
  "ViewerInfo",
54
79
  "parse_message",
55
80
  "GetCameraSettingsRequest",
81
+ "UpdateCameraSettingsRequest",
56
82
  "HeartbeatEvent",
57
83
  "LocalLivekitHeartbeatEvent",
84
+ "Settings",
58
85
  "SettingsEvent",
86
+ "SettingsState",
59
87
  "ViewerJoinedEvent",
60
88
  "ViewerLeftEvent",
61
89
  "MotionDetectedEvent",
90
+ "NoiseDetectedEvent",
62
91
  "HarborSourceType",
63
92
  "HarborViewer",
64
93
  "HarborEventState",
65
94
  "HarborDeviceState",
95
+ "NightMode",
96
+ "NIGHT_MODE_MODES",
97
+ "NIGHT_MODE_PREFERENCE_KEY",
98
+ "NIGHT_MODE_PREFERENCES",
99
+ "DEFAULT_NIGHT_MODE",
100
+ "VIDEO_FLIP_PREFERENCE_KEY",
101
+ "CLOCK_DISPLAY_PREFERENCE_KEY",
102
+ "TemperatureScale",
103
+ "TEMPERATURE_SCALES",
104
+ "TEMPERATURE_SCALE_PREFERENCE_KEY",
105
+ "TEMPERATURE_SCALE_VALUES",
106
+ "DEFAULT_TEMPERATURE_SCALE",
66
107
  "SPEAKER_STATES",
67
108
  "STREAM_QUALITIES",
68
109
  ]
harbor/core.py CHANGED
@@ -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
 
@@ -103,16 +108,71 @@ class Harbor:
103
108
  async def set_night_mode(
104
109
  self,
105
110
  serial: str,
106
- night_mode: bool,
111
+ night_mode: NightMode,
107
112
  *,
108
113
  timeout: float = 10.0,
109
114
  ) -> None:
110
- """Turn camera night mode on or off and refresh its settings."""
115
+ """Set the camera night-mode preference and refresh its settings.
116
+
117
+ ``night_mode`` is one of ``"auto"``, ``"on"`` or ``"off"``.
118
+ """
111
119
  await self._get_client(serial).set_night_mode(
112
120
  night_mode,
113
121
  timeout=timeout,
114
122
  )
115
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
+
116
176
  async def handle_message(self, topic: str, payload: Any) -> None:
117
177
  """
118
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
 
@@ -119,13 +157,53 @@ class ViewerLeftEvent(HarborMQTTPayload):
119
157
 
120
158
 
121
159
  class MotionDetectedEvent(HarborMQTTPayload):
122
- """Payload for a motion detection event."""
160
+ """Payload for a ``motion-detected`` event.
161
+
162
+ Keys arrive in snake_case. ``duration`` is a unit-suffixed string such as
163
+ ``"10s"`` -- never parse it as a bare number, and never treat it as a hold
164
+ time; see :class:`NoiseDetectedEvent` for why.
165
+ """
166
+
167
+ active_config: str | None = None
168
+ duration: str | None = None
169
+ file_duration: str | None = None
170
+ filename: str | None = None
171
+ level: str | None = None
172
+ sensitivity: str | None = None
173
+ threshold: str | None = None
174
+ thumbnail: str | None = None
175
+ timestamp: str | None = None
176
+
177
+
178
+ class NoiseDetectedEvent(HarborMQTTPayload):
179
+ """Payload for a ``sound-anomaly-detected`` event.
180
+
181
+ The firmware topic calls this a sound anomaly; the app presents it as an
182
+ alert for "sudden, loud sounds" and "sustained noises", hence the noise
183
+ naming used here.
184
+
185
+ Field set verified against a live camera. The audio fields are dB strings
186
+ (``"-36.401137dB"``) and pair with the ``volume_baseline_current`` /
187
+ ``volume_baseline_reference`` / ``volume_threshold_effective`` values on
188
+ :class:`SettingsState`.
189
+
190
+ ``duration`` is a unit-suffixed string (``"10s"``) that matches
191
+ ``file_duration``, the length of the recorded clip named by ``filename``.
192
+ It describes a detection window that has already closed by the time this
193
+ message is published, so it must not be used to decide how long the
194
+ detection "stays on" -- the camera never publishes a cleared counterpart at
195
+ all.
196
+ """
123
197
 
124
198
  active_config: str | None = None
125
- duration: str | float | int | None = None
199
+ baseline: str | None = None
200
+ baseline_reference: str | None = None
201
+ duration: str | None = None
202
+ file_duration: str | None = None
126
203
  filename: str | None = None
127
204
  level: str | None = None
128
205
  sensitivity: str | None = None
129
206
  threshold: str | None = None
130
207
  thumbnail: str | None = None
131
208
  timestamp: str | None = None
209
+ user_offset: str | None = None
harbor/devices/camera.py CHANGED
@@ -1,6 +1,5 @@
1
1
  from __future__ import annotations
2
2
 
3
- import asyncio
4
3
  import logging
5
4
 
6
5
  from ..config import HarborCameraConfig
@@ -19,8 +18,10 @@ from ..state import HarborEventState, HarborViewer
19
18
 
20
19
  _LOGGER = logging.getLogger(__name__)
21
20
 
22
- DEFAULT_CAMERA_EVENT_KEYS = ("motion_detection", "cry_detection", "noise_detection")
23
- DEFAULT_EVENT_ACTIVE_SECONDS = 5.0
21
+ #: Detection events the camera can report. The firmware publishes exactly two
22
+ #: detection topics (``motion-detected`` and ``sound-anomaly-detected``), so
23
+ #: seeding anything else would create an entity that can never fire.
24
+ DEFAULT_CAMERA_EVENT_KEYS = ("motion_detection", "noise_detection")
24
25
 
25
26
  # Known values for enumerated state fields. The device reports these in
26
27
  # mixed/upper case (e.g. "PLAYING", "GOOD"); they are normalized to the
@@ -31,6 +32,13 @@ DEFAULT_EVENT_ACTIVE_SECONDS = 5.0
31
32
  UNKNOWN_ENUM_VALUE = "unknown"
32
33
  SPEAKER_STATES = frozenset({"idle", "muted", "off", "paused", "playing", "unknown"})
33
34
  STREAM_QUALITIES = frozenset({"excellent", "fair", "good", "poor", "unknown"})
35
+ # Accepted values for the writable night-mode preference, per the schema the
36
+ # firmware returns when it rejects an invalid value.
37
+ NIGHT_MODE_PREFERENCES = frozenset({"auto", "on", "off", "unknown"})
38
+ # Settings whose value is matched verbatim by the device, so unlike the state
39
+ # enums above they are stored with their case intact -- a consumer must be able
40
+ # to write back exactly what it read.
41
+ TEMPERATURE_SCALE_VALUES = frozenset({"F", "C"})
34
42
 
35
43
 
36
44
  class HarborCamera(HarborDevice):
@@ -40,7 +48,6 @@ class HarborCamera(HarborDevice):
40
48
  """Initialize the camera device."""
41
49
  super().__init__(config.serial, "camera")
42
50
  self.config = config
43
- self._event_reset_handles: dict[str, asyncio.TimerHandle] = {}
44
51
  self._unexpected_enum_values: set[tuple[str, str]] = set()
45
52
 
46
53
  for event_key in DEFAULT_CAMERA_EVENT_KEYS:
@@ -70,12 +77,65 @@ class HarborCamera(HarborDevice):
70
77
  self._apply_camera_event(event)
71
78
 
72
79
  def _apply_camera_settings(self, payload: SettingsEvent) -> None:
73
- """Apply camera controls exposed by a settings payload."""
74
- if payload.settings is not None and payload.settings.preference_stream_paused is not None:
75
- self.state.values["camera_on"] = not payload.settings.preference_stream_paused
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
+ )
76
107
  if payload.state is not None and payload.state.video_night_mode is not None:
77
108
  self.state.values["night_mode"] = payload.state.video_night_mode
78
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
+
79
139
  def _apply_local_livekit_heartbeat(
80
140
  self,
81
141
  payload,
@@ -161,29 +221,24 @@ class HarborCamera(HarborDevice):
161
221
  self.state.values["num_viewers"] = len(self.state.viewers)
162
222
 
163
223
  def _apply_camera_event(self, event: CameraEventUpdate) -> None:
164
- """Apply a transient camera event update."""
224
+ """Record a camera detection event.
225
+
226
+ Detections are edge triggers with no cleared counterpart, so this only
227
+ stamps when the event last fired.
228
+
229
+ Earlier versions synthesized an ``is_on`` flag and held it open for a
230
+ duration parsed from the payload. That never worked: the firmware
231
+ reports ``"10s"``, which failed to parse and silently fell back to a
232
+ fixed 5s, so a 10-second detection was reported as a 5-second one and
233
+ every event looked identical. Holding the real value would not have
234
+ helped either -- the window has already closed by the time the message
235
+ is published.
236
+ """
165
237
  event_state = self._ensure_camera_event(event.event_key, topic=event.topic)
166
238
  event_state.topic = event.topic
167
239
  event_state.last_seen = event.timestamp
168
240
  event_state.last_payload = event.raw_payload
169
241
 
170
- if handle := self._event_reset_handles.pop(event.event_key, None):
171
- handle.cancel()
172
-
173
- if event.explicit_state is False:
174
- event_state.is_on = False
175
- return
176
-
177
- event_state.is_on = True
178
- active_seconds = event.active_seconds
179
- if active_seconds <= 0:
180
- active_seconds = DEFAULT_EVENT_ACTIVE_SECONDS
181
-
182
- loop = asyncio.get_running_loop()
183
- self._event_reset_handles[event.event_key] = loop.call_later(
184
- active_seconds,
185
- lambda: asyncio.create_task(self._async_reset_event(event.event_key)),
186
- )
187
242
  _LOGGER.debug(
188
243
  "Camera %s received event on topic %s: %s",
189
244
  self.serial,
@@ -191,19 +246,6 @@ class HarborCamera(HarborDevice):
191
246
  event.raw_payload,
192
247
  )
193
248
 
194
- def shutdown(self) -> None:
195
- """Release camera resources."""
196
- for handle in self._event_reset_handles.values():
197
- handle.cancel()
198
- self._event_reset_handles.clear()
199
-
200
- async def _async_reset_event(self, event_key: str) -> None:
201
- """Reset a transient event to off after its active period."""
202
- self._event_reset_handles.pop(event_key, None)
203
- if event_state := self.state.events.get(event_key):
204
- event_state.is_on = False
205
- await self._emit_update()
206
-
207
249
  def _ensure_camera_event(
208
250
  self,
209
251
  event_key: str,
@@ -227,8 +269,6 @@ class HarborCamera(HarborDevice):
227
269
 
228
270
  def _event_name_from_key(event_key: str) -> str:
229
271
  """Return a user-facing event name for an event key."""
230
- if event_key == "cry_detection":
231
- return "Cry detected"
232
272
  if event_key == "motion_detection":
233
273
  return "Motion detected"
234
274
  if event_key == "noise_detection":