pyopengate 0.1.0__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.
pyopengate/__init__.py ADDED
@@ -0,0 +1,48 @@
1
+ """Async Python client library for the OpenGate gate-opening API."""
2
+
3
+ from .client import OpenGateClient
4
+ from .const import (
5
+ API_BASE_URL,
6
+ CALL_ERROR_MESSAGES,
7
+ DEFAULT_DEVICE_TYPE,
8
+ DEFAULT_DEVICE_VERSION,
9
+ DEFAULT_EXT,
10
+ DEFAULT_PLATFORM,
11
+ PARKING_LOT_ERROR_MESSAGES,
12
+ SUBSCRIPTION_LABELS,
13
+ )
14
+ from .exceptions import (
15
+ OpenGateAuthError,
16
+ OpenGateCallError,
17
+ OpenGateConnectionError,
18
+ OpenGateError,
19
+ )
20
+ from .models import (
21
+ OpenGateAccountSnapshot,
22
+ OpenGateAddress,
23
+ OpenGateCallRecord,
24
+ OpenGateGate,
25
+ )
26
+
27
+ __version__ = "0.1.0"
28
+
29
+ __all__ = [
30
+ "API_BASE_URL",
31
+ "CALL_ERROR_MESSAGES",
32
+ "DEFAULT_DEVICE_TYPE",
33
+ "DEFAULT_DEVICE_VERSION",
34
+ "DEFAULT_EXT",
35
+ "DEFAULT_PLATFORM",
36
+ "PARKING_LOT_ERROR_MESSAGES",
37
+ "SUBSCRIPTION_LABELS",
38
+ "OpenGateAccountSnapshot",
39
+ "OpenGateAddress",
40
+ "OpenGateAuthError",
41
+ "OpenGateCallError",
42
+ "OpenGateCallRecord",
43
+ "OpenGateClient",
44
+ "OpenGateConnectionError",
45
+ "OpenGateError",
46
+ "OpenGateGate",
47
+ "__version__",
48
+ ]
pyopengate/client.py ADDED
@@ -0,0 +1,619 @@
1
+ """Async HTTP client for OpenGate (https://api.opengate.io)."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import asyncio
6
+ import json
7
+ import logging
8
+ import time
9
+ from types import TracebackType
10
+ from typing import Any
11
+ from urllib.parse import quote
12
+
13
+ import aiohttp
14
+
15
+ from .const import (
16
+ API_BASE_URL,
17
+ CALL_ERROR_MESSAGES,
18
+ DEFAULT_DEVICE_TYPE,
19
+ DEFAULT_DEVICE_VERSION,
20
+ DEFAULT_PLATFORM,
21
+ DEFAULT_TIMEOUT_SECONDS,
22
+ PARKING_LOT_ERROR_MESSAGES,
23
+ POST_MIN_INTERVAL_SECONDS,
24
+ )
25
+ from .exceptions import (
26
+ OpenGateAuthError,
27
+ OpenGateCallError,
28
+ OpenGateConnectionError,
29
+ )
30
+ from .models import (
31
+ OpenGateAccountSnapshot,
32
+ OpenGateAddress,
33
+ OpenGateCallRecord,
34
+ OpenGateGate,
35
+ parse_call_history,
36
+ )
37
+
38
+ _LOGGER = logging.getLogger(__name__)
39
+
40
+
41
+ class OpenGateClient:
42
+ """Async client for the OpenGate REST API."""
43
+
44
+ def __init__(
45
+ self,
46
+ session: aiohttp.ClientSession | None = None,
47
+ uqid: str | None = None,
48
+ *,
49
+ base_url: str = API_BASE_URL,
50
+ timeout: float = DEFAULT_TIMEOUT_SECONDS,
51
+ ) -> None:
52
+ """Initialize the client.
53
+
54
+ If ``session`` is omitted, a dedicated ``aiohttp.ClientSession`` is created
55
+ lazily and closed when using ``async with OpenGateClient(...)`` or calling
56
+ ``await client.async_close()``.
57
+ """
58
+ self._session = session
59
+ self._owns_session = session is None
60
+ self._uqid = uqid
61
+ self._base_url = base_url.rstrip("/")
62
+ self._timeout = aiohttp.ClientTimeout(total=timeout)
63
+ self._post_lock = asyncio.Lock()
64
+ self._last_post_time: float = 0.0
65
+
66
+ async def __aenter__(self) -> OpenGateClient:
67
+ """Enter async context manager."""
68
+ self._ensure_session()
69
+ return self
70
+
71
+ async def __aexit__(
72
+ self,
73
+ exc_type: type[BaseException] | None,
74
+ exc_val: BaseException | None,
75
+ exc_tb: TracebackType | None,
76
+ ) -> None:
77
+ """Exit async context manager and close owned session."""
78
+ await self.async_close()
79
+
80
+ def _ensure_session(self) -> aiohttp.ClientSession:
81
+ """Return active ClientSession, creating one if this client owns it."""
82
+ if self._session is None or self._session.closed:
83
+ self._session = aiohttp.ClientSession()
84
+ self._owns_session = True
85
+ return self._session
86
+
87
+ async def async_close(self) -> None:
88
+ """Close the underlying aiohttp session if owned by this client."""
89
+ if self._owns_session and self._session is not None and not self._session.closed:
90
+ await self._session.close()
91
+
92
+ @property
93
+ def uqid(self) -> str | None:
94
+ """Return the current uqid authentication token."""
95
+ return self._uqid
96
+
97
+ def set_uqid(self, uqid: str) -> None:
98
+ """Update the uqid authentication token."""
99
+ self._uqid = uqid
100
+
101
+ async def _throttle_post(self) -> None:
102
+ """Enforce the 1 req/sec client-side throttle on POST requests."""
103
+ async with self._post_lock:
104
+ now = time.monotonic()
105
+ elapsed = now - self._last_post_time
106
+ if self._last_post_time > 0 and elapsed < POST_MIN_INTERVAL_SECONDS:
107
+ await asyncio.sleep(POST_MIN_INTERVAL_SECONDS - elapsed)
108
+ self._last_post_time = time.monotonic()
109
+
110
+ async def _parse_response(self, response: aiohttp.ClientResponse) -> Any:
111
+ """Parse an OpenGate API response and raise typed errors."""
112
+ if response.status in (401, 403):
113
+ raise OpenGateAuthError(f"Authentication failed (HTTP {response.status})")
114
+
115
+ text = await response.text()
116
+ if response.status >= 400:
117
+ raise OpenGateConnectionError(
118
+ f"OpenGate API returned HTTP {response.status}: {text[:200]}"
119
+ )
120
+
121
+ stripped = text.strip()
122
+ if stripped in ("denied", '"denied"'):
123
+ raise OpenGateAuthError("OpenGate API returned 'denied'; token may be expired")
124
+
125
+ if not stripped:
126
+ return None
127
+
128
+ try:
129
+ data = json.loads(stripped)
130
+ except json.JSONDecodeError:
131
+ return stripped
132
+
133
+ if data == "denied":
134
+ raise OpenGateAuthError("OpenGate API returned 'denied'; token may be expired")
135
+
136
+ return data
137
+
138
+ async def _get(
139
+ self,
140
+ path: str,
141
+ params: dict[str, Any] | None = None,
142
+ *,
143
+ authenticated: bool = True,
144
+ ) -> Any:
145
+ """Perform a GET request against the OpenGate API."""
146
+ query_params: dict[str, str] = {}
147
+ if authenticated:
148
+ if not self._uqid:
149
+ raise OpenGateAuthError("No uqid token configured")
150
+ query_params["uqid"] = self._uqid
151
+ if params:
152
+ for key, value in params.items():
153
+ if value is not None:
154
+ query_params[key] = str(value)
155
+
156
+ url = f"{self._base_url}{path}"
157
+ headers = {"Accept": "application/json"}
158
+ session = self._ensure_session()
159
+
160
+ try:
161
+ async with session.get(
162
+ url,
163
+ params=query_params,
164
+ headers=headers,
165
+ timeout=self._timeout,
166
+ ) as response:
167
+ return await self._parse_response(response)
168
+ except (OpenGateAuthError, OpenGateConnectionError):
169
+ raise
170
+ except (aiohttp.ClientError, TimeoutError) as err:
171
+ raise OpenGateConnectionError(f"Error communicating with OpenGate: {err}") from err
172
+
173
+ async def _post(
174
+ self,
175
+ path: str,
176
+ body: dict[str, Any] | None = None,
177
+ *,
178
+ authenticated: bool = True,
179
+ ) -> Any:
180
+ """Perform a POST request with JSON body and 1 req/sec client throttle."""
181
+ await self._throttle_post()
182
+ payload = dict(body or {})
183
+ if authenticated:
184
+ if not self._uqid:
185
+ raise OpenGateAuthError("No uqid token configured")
186
+ payload["uqid"] = self._uqid
187
+
188
+ url = f"{self._base_url}{path}"
189
+ headers = {
190
+ "Accept": "application/json",
191
+ "Content-Type": "application/json",
192
+ "Cache-Control": "no-cache",
193
+ }
194
+ session = self._ensure_session()
195
+
196
+ try:
197
+ async with session.post(
198
+ url,
199
+ json=payload,
200
+ headers=headers,
201
+ timeout=self._timeout,
202
+ ) as response:
203
+ return await self._parse_response(response)
204
+ except (OpenGateAuthError, OpenGateConnectionError):
205
+ raise
206
+ except (aiohttp.ClientError, TimeoutError) as err:
207
+ raise OpenGateConnectionError(f"Error communicating with OpenGate: {err}") from err
208
+
209
+ async def _put(
210
+ self,
211
+ path: str,
212
+ body: dict[str, Any] | None = None,
213
+ *,
214
+ authenticated: bool = True,
215
+ ) -> Any:
216
+ """Perform a PUT request with JSON body."""
217
+ payload = dict(body or {})
218
+ if authenticated:
219
+ if not self._uqid:
220
+ raise OpenGateAuthError("No uqid token configured")
221
+ payload["uqid"] = self._uqid
222
+
223
+ url = f"{self._base_url}{path}"
224
+ headers = {
225
+ "Accept": "application/json",
226
+ "Content-Type": "application/json",
227
+ "Cache-Control": "no-cache",
228
+ }
229
+ session = self._ensure_session()
230
+
231
+ try:
232
+ async with session.put(
233
+ url,
234
+ json=payload,
235
+ headers=headers,
236
+ timeout=self._timeout,
237
+ ) as response:
238
+ return await self._parse_response(response)
239
+ except (OpenGateAuthError, OpenGateConnectionError):
240
+ raise
241
+ except (aiohttp.ClientError, TimeoutError) as err:
242
+ raise OpenGateConnectionError(f"Error communicating with OpenGate: {err}") from err
243
+
244
+ # ------------------------------------------------------------------
245
+ # Authentication (SMS OTP & session validation)
246
+ # ------------------------------------------------------------------
247
+
248
+ async def async_generate_sms_code(self, ext: str, phone: str) -> Any:
249
+ """Request an SMS OTP code for the given country code and phone number."""
250
+ clean_ext = ext.lstrip("+").strip()
251
+ clean_phone = phone.strip()
252
+ result = await self._post(
253
+ "/sms/generateSmsCode",
254
+ {"ext": clean_ext, "phone": clean_phone},
255
+ authenticated=False,
256
+ )
257
+ if not result:
258
+ raise OpenGateConnectionError("Failed to request SMS verification code")
259
+ return result
260
+
261
+ async def async_verify_sms_code(
262
+ self,
263
+ ext: str,
264
+ phone: str,
265
+ sms_code: str,
266
+ *,
267
+ platform: str = DEFAULT_PLATFORM,
268
+ device_version: str = DEFAULT_DEVICE_VERSION,
269
+ device_type: str = DEFAULT_DEVICE_TYPE,
270
+ ) -> dict[str, Any]:
271
+ """Verify an SMS OTP code and return the user profile including uqid."""
272
+ clean_ext = ext.lstrip("+").strip()
273
+ clean_phone = phone.strip()
274
+ result = await self._post(
275
+ "/sms/verifySmsCode",
276
+ {
277
+ "ext": clean_ext,
278
+ "phone": clean_phone,
279
+ "smsCode": sms_code.strip(),
280
+ "platform": platform,
281
+ "deviceVersion": device_version,
282
+ "deviceType": device_type,
283
+ },
284
+ authenticated=False,
285
+ )
286
+ if not isinstance(result, dict) or not result.get("uqid"):
287
+ raise OpenGateAuthError("Invalid SMS verification code")
288
+ self._uqid = str(result["uqid"])
289
+ return result
290
+
291
+ async def async_is_logged(self) -> dict[str, Any]:
292
+ """Validate the current uqid and return the user profile."""
293
+ result = await self._get("/customers/isLogged")
294
+ if not isinstance(result, dict) or not (result.get("uqid") or result.get("_id")):
295
+ raise OpenGateAuthError("Invalid or expired OpenGate session")
296
+ return result
297
+
298
+ # ------------------------------------------------------------------
299
+ # Discovery & polling
300
+ # ------------------------------------------------------------------
301
+
302
+ async def async_get_addresses_raw(self) -> list[dict[str, Any]]:
303
+ """Return the raw list of addresses and nested gates from GET /addresses."""
304
+ result = await self._get("/addresses")
305
+ if isinstance(result, list):
306
+ return [item for item in result if isinstance(item, dict)]
307
+ raise OpenGateConnectionError(
308
+ f"Unexpected /addresses payload type: {type(result).__name__}"
309
+ )
310
+
311
+ async def async_get_gates_raw(self) -> list[dict[str, Any]]:
312
+ """Return the raw flat list of gates from GET /gates."""
313
+ result = await self._get("/gates")
314
+ if isinstance(result, list):
315
+ return [item for item in result if isinstance(item, dict)]
316
+ return []
317
+
318
+ async def async_reset_addresses_cache(self) -> Any:
319
+ """Ask the OpenGate backend to reset its cached address list."""
320
+ return await self._get("/addresses/resetCache")
321
+
322
+ async def async_get_call_history_raw(
323
+ self,
324
+ gate_phone: str,
325
+ address_id: str,
326
+ ) -> list[dict[str, Any]]:
327
+ """Fetch raw call history entries for a gate (requires address manager role)."""
328
+ encoded_phone = quote(gate_phone, safe="")
329
+ result = await self._get(
330
+ f"/gates/callHistory/{encoded_phone}",
331
+ {"addressId": address_id},
332
+ )
333
+ if isinstance(result, list):
334
+ return [item for item in result if isinstance(item, dict)]
335
+ return []
336
+
337
+ async def async_get_call_history(
338
+ self,
339
+ gate_phone: str,
340
+ address_id: str,
341
+ ) -> list[OpenGateCallRecord]:
342
+ """Fetch parsed call history entries sorted newest-first."""
343
+ raw = await self.async_get_call_history_raw(gate_phone, address_id)
344
+ return parse_call_history(raw)
345
+
346
+ async def async_fetch_snapshot(
347
+ self,
348
+ *,
349
+ poll_call_history: bool = True,
350
+ ) -> OpenGateAccountSnapshot:
351
+ """Fetch user profile, addresses, gates, and optional manager call history."""
352
+ user_info = await self.async_is_logged()
353
+ raw_addresses = await self.async_get_addresses_raw()
354
+
355
+ user_id = str(user_info.get("_id", ""))
356
+ is_admin = bool(user_info.get("isAdmin", False))
357
+
358
+ addresses: dict[str, OpenGateAddress] = {}
359
+ gates: dict[str, OpenGateGate] = {}
360
+
361
+ for raw_addr in raw_addresses:
362
+ addr_id = str(raw_addr.get("_id", ""))
363
+ if not addr_id:
364
+ continue
365
+
366
+ addr = OpenGateAddress.from_dict(raw_addr, user_id=user_id)
367
+ raw_gates = raw_addr.get("gates") or []
368
+
369
+ # Mirror mobile app behavior: hide parkinglot gates for non-admins
370
+ if addr.subscription_type != "parkinglot" or is_admin:
371
+ for raw_gate in raw_gates:
372
+ if not isinstance(raw_gate, dict):
373
+ continue
374
+ gate_id = str(raw_gate.get("_id", ""))
375
+ if not gate_id:
376
+ continue
377
+ phone = str(raw_gate.get("phone") or "")
378
+
379
+ call_history: list[OpenGateCallRecord] = []
380
+ if poll_call_history and addr.is_manager and phone:
381
+ try:
382
+ call_history = await self.async_get_call_history(phone, addr_id)
383
+ except OpenGateAuthError:
384
+ raise
385
+ except OpenGateConnectionError as err:
386
+ _LOGGER.debug(
387
+ "Failed to fetch call history for gate %s: %s",
388
+ gate_id,
389
+ err,
390
+ )
391
+
392
+ gate = OpenGateGate.from_dict(
393
+ raw_gate,
394
+ address_id=addr_id,
395
+ address_name=addr.address,
396
+ is_call_distance_allowed=addr.is_call_distance_allowed,
397
+ is_manager=addr.is_manager,
398
+ call_history=call_history,
399
+ )
400
+ addr.gates.append(gate)
401
+ gates[gate_id] = gate
402
+
403
+ addresses[addr_id] = addr
404
+
405
+ # Fallback: query /gates if /addresses yielded no gates
406
+ if not gates:
407
+ try:
408
+ standalone_gates = await self.async_get_gates_raw()
409
+ except OpenGateAuthError:
410
+ raise
411
+ except OpenGateConnectionError as err:
412
+ _LOGGER.debug("Fallback /gates call failed: %s", err)
413
+ standalone_gates = []
414
+
415
+ if standalone_gates:
416
+ fallback_addr_id = f"account_{user_id or 'default'}"
417
+ fallback_gates: list[OpenGateGate] = []
418
+ for raw_gate in standalone_gates:
419
+ gate_id = str(raw_gate.get("_id", ""))
420
+ if not gate_id or gate_id in gates:
421
+ continue
422
+ gate = OpenGateGate.from_dict(
423
+ raw_gate,
424
+ address_id=fallback_addr_id,
425
+ address_name="OpenGate Account",
426
+ )
427
+ fallback_gates.append(gate)
428
+ gates[gate_id] = gate
429
+
430
+ if fallback_gates:
431
+ addresses[fallback_addr_id] = OpenGateAddress(
432
+ address_id=fallback_addr_id,
433
+ address="OpenGate Account",
434
+ subscription_type="unknown",
435
+ subscription_label="Unknown",
436
+ left_days=None,
437
+ is_manager=False,
438
+ is_call_distance_allowed=False,
439
+ is_just_call=False,
440
+ is_renew=False,
441
+ asked_to_stop_subscription=False,
442
+ gates=fallback_gates,
443
+ raw={},
444
+ )
445
+
446
+ return OpenGateAccountSnapshot(
447
+ user_info=user_info,
448
+ addresses=addresses,
449
+ gates=gates,
450
+ )
451
+
452
+ # ------------------------------------------------------------------
453
+ # Gate & parking lot opening
454
+ # ------------------------------------------------------------------
455
+
456
+ async def async_call_gate(
457
+ self,
458
+ gate_id: str,
459
+ *,
460
+ call_type: str | None = "manualCall",
461
+ user_location: dict[str, float] | None = None,
462
+ ) -> Any:
463
+ """Trigger a gate call via GET /gates/callNow."""
464
+ params: dict[str, Any] = {"gateId": gate_id}
465
+ if call_type:
466
+ params["type"] = call_type
467
+ if user_location is not None:
468
+ params["userLocation"] = json.dumps(user_location, separators=(",", ":"))
469
+
470
+ result = await self._get("/gates/callNow", params)
471
+ if isinstance(result, str) and result in CALL_ERROR_MESSAGES:
472
+ raise OpenGateCallError(result, CALL_ERROR_MESSAGES[result])
473
+ return result
474
+
475
+ async def async_is_gate_opened_succeed(self, gate_phone: str) -> Any:
476
+ """Check whether the last call to a gate succeeded."""
477
+ return await self._get("/gates/isGateOpenedSucceed", {"phone": gate_phone})
478
+
479
+ async def async_open_parking_lot(
480
+ self,
481
+ latitude: float,
482
+ longitude: float,
483
+ ) -> dict[str, Any]:
484
+ """Trigger a nearby parking lot barrier via POST /parkinglots/opengate."""
485
+ result = await self._post(
486
+ "/parkinglots/opengate",
487
+ {
488
+ "type": "app",
489
+ "userLocation": {
490
+ "latitude": latitude,
491
+ "longitude": longitude,
492
+ },
493
+ },
494
+ )
495
+ if isinstance(result, dict):
496
+ status = result.get("status")
497
+ if isinstance(status, str) and status in PARKING_LOT_ERROR_MESSAGES:
498
+ raise OpenGateCallError(status, PARKING_LOT_ERROR_MESSAGES[status])
499
+ return result
500
+ return {"result": result}
501
+
502
+ # ------------------------------------------------------------------
503
+ # Authorized customers & manager management
504
+ # ------------------------------------------------------------------
505
+
506
+ async def async_get_authorized_customers(
507
+ self,
508
+ address_id: str,
509
+ gate_phone: str,
510
+ *,
511
+ sort: str = "endDate",
512
+ show_only_end_subscription: bool = False,
513
+ ) -> list[dict[str, Any]]:
514
+ """List authorized phone numbers for an address/gate."""
515
+ encoded_id = quote(address_id, safe="")
516
+ result = await self._get(
517
+ f"/addresses/allAuthorizedCustomers/{encoded_id}",
518
+ {
519
+ "sort": sort,
520
+ "showOnlyEndSubscription": str(show_only_end_subscription).lower(),
521
+ "gatePhone": gate_phone,
522
+ "isApp": "true",
523
+ },
524
+ )
525
+ if isinstance(result, list):
526
+ return [item for item in result if isinstance(item, dict)]
527
+ return []
528
+
529
+ async def async_add_authorized_customer(
530
+ self,
531
+ *,
532
+ address_id: str,
533
+ phone: str,
534
+ gate_phone: str,
535
+ nickname: str = "",
536
+ car_id: str = "",
537
+ start_date: str | None = None,
538
+ end_date: str | None = None,
539
+ is_free_entrance: bool = False,
540
+ ) -> Any:
541
+ """Add an authorized customer phone number to a gate."""
542
+ body: dict[str, Any] = {
543
+ "_id": address_id,
544
+ "phone": phone,
545
+ "gatePhone": gate_phone,
546
+ "nickname": nickname,
547
+ "carId": car_id,
548
+ "isFreeEntrance": is_free_entrance,
549
+ }
550
+ if start_date is not None:
551
+ body["startDate"] = start_date
552
+ if end_date is not None:
553
+ body["endDate"] = end_date
554
+ result = await self._put("/addresses/addPhoneToAuthorizedCustomers", body)
555
+ if result == "notHaveCashForSms":
556
+ raise OpenGateCallError(
557
+ "notHaveCashForSms",
558
+ "Insufficient SMS credit in OpenGate account to notify the authorized customer.",
559
+ )
560
+ return result
561
+
562
+ async def async_remove_authorized_customer(
563
+ self,
564
+ *,
565
+ address_id: str,
566
+ phone: str,
567
+ gate_phone: str,
568
+ ) -> Any:
569
+ """Remove an authorized customer phone number from a gate."""
570
+ return await self._put(
571
+ "/addresses/removeAuthorizedCustomer",
572
+ {
573
+ "_id": address_id,
574
+ "phone": phone,
575
+ "gatePhone": gate_phone,
576
+ },
577
+ )
578
+
579
+ async def async_get_managers(self, address_id: str) -> list[dict[str, Any]]:
580
+ """List parking managers for an address."""
581
+ result = await self._get(
582
+ "/addresses/getAllManagersParking",
583
+ {"addressId": address_id, "comeFrom": "app"},
584
+ )
585
+ if isinstance(result, list):
586
+ return [item for item in result if isinstance(item, dict)]
587
+ return []
588
+
589
+ async def async_add_manager(
590
+ self,
591
+ *,
592
+ address_id: str,
593
+ phone: str,
594
+ nickname: str = "",
595
+ ) -> Any:
596
+ """Add a manager to an address."""
597
+ return await self._put(
598
+ "/addresses/addNewManagerToParking",
599
+ {"_id": address_id, "phone": phone, "nickname": nickname},
600
+ )
601
+
602
+ async def async_remove_manager(
603
+ self,
604
+ *,
605
+ address_id: str,
606
+ phone: str,
607
+ ) -> Any:
608
+ """Remove a manager from an address."""
609
+ result = await self._put(
610
+ "/addresses/removeManagerFromParking",
611
+ {"_id": address_id, "phone": phone},
612
+ )
613
+ if result == "managerIsAPlaceYouCantRemove":
614
+ raise OpenGateCallError(
615
+ "managerIsAPlaceYouCantRemove",
616
+ "Removal request was sent to the installer; "
617
+ "this manager cannot be removed directly.",
618
+ )
619
+ return result
pyopengate/const.py ADDED
@@ -0,0 +1,42 @@
1
+ """Constants for pyopengate."""
2
+
3
+ from __future__ import annotations
4
+
5
+ API_BASE_URL = "https://api.opengate.io"
6
+
7
+ DEFAULT_EXT = "972"
8
+ DEFAULT_PLATFORM = "android"
9
+ DEFAULT_DEVICE_VERSION = "14"
10
+ DEFAULT_DEVICE_TYPE = "pyopengate"
11
+ DEFAULT_TIMEOUT_SECONDS = 15.0
12
+
13
+ # Matches the mobile app's 1 req/sec client-side POST throttle
14
+ POST_MIN_INTERVAL_SECONDS = 1.0
15
+
16
+ # Known error responses from GET /gates/callNow
17
+ CALL_ERROR_MESSAGES: dict[str, str] = {
18
+ "trialEnd": "Subscription or trial has expired. Please renew in the OpenGate app.",
19
+ "blocked": "Gate phone number was identified as non-gate and blocked by OpenGate.",
20
+ "gateNotClooseToAddress": "Cannot open gates that are too far from the registered address.",
21
+ "clocksModeIsActive_protectGate": (
22
+ "Shabbat clock mode is active; gate opening is currently disabled."
23
+ ),
24
+ "limitedCallDistance": (
25
+ "Distance limit is active; you must be close to the gate or provide coordinates."
26
+ ),
27
+ }
28
+
29
+ # Known error statuses from POST /parkinglots/opengate
30
+ PARKING_LOT_ERROR_MESSAGES: dict[str, str] = {
31
+ "notFrontOfParkinglot": "Not detected in front of an OpenGate parking lot barrier.",
32
+ "notInTheCorrectSideOfGate": "Not on the correct side of the parking lot gate.",
33
+ }
34
+
35
+ # Subscription type labels
36
+ SUBSCRIPTION_LABELS: dict[str, str] = {
37
+ "free": "Free / Trial",
38
+ "family": "Family",
39
+ "building": "Building",
40
+ "parking": "Annual Parking",
41
+ "parkinglot": "Paid Parking Lot",
42
+ }
@@ -0,0 +1,24 @@
1
+ """Exceptions for pyopengate."""
2
+
3
+ from __future__ import annotations
4
+
5
+
6
+ class OpenGateError(Exception):
7
+ """Base exception for OpenGate API errors."""
8
+
9
+
10
+ class OpenGateAuthError(OpenGateError):
11
+ """Raised when authentication fails or uqid is invalid/expired."""
12
+
13
+
14
+ class OpenGateConnectionError(OpenGateError):
15
+ """Raised when unable to connect to or parse response from OpenGate API."""
16
+
17
+
18
+ class OpenGateCallError(OpenGateError):
19
+ """Raised when OpenGate rejects a gate, parking-lot, or management request."""
20
+
21
+ def __init__(self, code: str, message: str | None = None) -> None:
22
+ """Initialize with error code and human-readable message."""
23
+ self.code = code
24
+ super().__init__(message or f"OpenGate rejected the request: {code}")
pyopengate/models.py ADDED
@@ -0,0 +1,204 @@
1
+ """Typed data models for pyopengate."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from dataclasses import dataclass, field
6
+ from datetime import UTC, datetime
7
+ from typing import Any
8
+
9
+ from .const import SUBSCRIPTION_LABELS
10
+
11
+
12
+ def parse_datetime(value: Any) -> datetime | None:
13
+ """Parse an ISO-8601 string or epoch timestamp into a UTC datetime."""
14
+ if not value:
15
+ return None
16
+ if isinstance(value, datetime):
17
+ return value.astimezone(UTC) if value.tzinfo else value.replace(tzinfo=UTC)
18
+ if isinstance(value, (int, float)):
19
+ ts = value / 1000.0 if value > 1e12 else float(value)
20
+ return datetime.fromtimestamp(ts, tz=UTC)
21
+ if isinstance(value, str):
22
+ raw = value.strip()
23
+ if raw.endswith("Z"):
24
+ raw = f"{raw[:-1]}+00:00"
25
+ try:
26
+ parsed = datetime.fromisoformat(raw)
27
+ except ValueError:
28
+ return None
29
+ return parsed.astimezone(UTC) if parsed.tzinfo else parsed.replace(tzinfo=UTC)
30
+ return None
31
+
32
+
33
+ def parse_coordinates(raw_gate: dict[str, Any]) -> tuple[float | None, float | None]:
34
+ """Extract (latitude, longitude) from GeoJSON gateLoc."""
35
+ gate_loc = raw_gate.get("gateLoc")
36
+ if isinstance(gate_loc, dict):
37
+ coords = gate_loc.get("coordinates")
38
+ if isinstance(coords, (list, tuple)) and len(coords) >= 2:
39
+ try:
40
+ # GeoJSON order is [longitude, latitude]
41
+ lng = float(coords[0])
42
+ lat = float(coords[1])
43
+ return lat, lng
44
+ except (TypeError, ValueError):
45
+ pass
46
+ return None, None
47
+
48
+
49
+ def clean_sip_phone(value: Any) -> str | None:
50
+ """Normalize sipPhone where OpenGate uses 'false' or '' to indicate none."""
51
+ if not value or str(value).lower() == "false":
52
+ return None
53
+ return str(value)
54
+
55
+
56
+ @dataclass(slots=True)
57
+ class OpenGateCallRecord:
58
+ """Normalized call history entry for a gate."""
59
+
60
+ call_id: str
61
+ user_phone: str | None
62
+ gate_phone: str | None
63
+ nickname: str | None
64
+ speed: int | float | None
65
+ created_at: datetime | None
66
+ raw: dict[str, Any] = field(default_factory=dict)
67
+
68
+ @classmethod
69
+ def from_dict(cls, item: dict[str, Any]) -> OpenGateCallRecord:
70
+ """Create an OpenGateCallRecord from an API dictionary."""
71
+ return cls(
72
+ call_id=str(item.get("_id", "")),
73
+ user_phone=item.get("userPhone"),
74
+ gate_phone=item.get("gatePhone"),
75
+ nickname=item.get("nickname") or None,
76
+ speed=item.get("speed"),
77
+ created_at=parse_datetime(item.get("createdDate")),
78
+ raw=item,
79
+ )
80
+
81
+
82
+ def parse_call_history(items: list[dict[str, Any]]) -> list[OpenGateCallRecord]:
83
+ """Parse call history items sorted newest-first."""
84
+ records = [OpenGateCallRecord.from_dict(item) for item in items if isinstance(item, dict)]
85
+ records.sort(
86
+ key=lambda rec: rec.created_at or datetime.min.replace(tzinfo=UTC),
87
+ reverse=True,
88
+ )
89
+ return records
90
+
91
+
92
+ @dataclass(slots=True)
93
+ class OpenGateGate:
94
+ """Normalized OpenGate gate model."""
95
+
96
+ gate_id: str
97
+ address_id: str
98
+ address_name: str
99
+ name: str
100
+ phone: str
101
+ sip_phone: str | None
102
+ call_distance: int | None
103
+ latitude: float | None
104
+ longitude: float | None
105
+ is_call_distance_allowed: bool
106
+ is_manager: bool
107
+ call_history: list[OpenGateCallRecord] = field(default_factory=list)
108
+ raw: dict[str, Any] = field(default_factory=dict)
109
+
110
+ @classmethod
111
+ def from_dict(
112
+ cls,
113
+ raw_gate: dict[str, Any],
114
+ *,
115
+ address_id: str,
116
+ address_name: str,
117
+ is_call_distance_allowed: bool = False,
118
+ is_manager: bool = False,
119
+ call_history: list[OpenGateCallRecord] | None = None,
120
+ ) -> OpenGateGate:
121
+ """Create an OpenGateGate from an API dictionary."""
122
+ gate_id = str(raw_gate.get("_id", ""))
123
+ phone = str(raw_gate.get("phone") or "")
124
+ name = str(raw_gate.get("name") or phone or f"Gate {gate_id[:6]}")
125
+ lat, lng = parse_coordinates(raw_gate)
126
+ return cls(
127
+ gate_id=gate_id,
128
+ address_id=address_id,
129
+ address_name=address_name,
130
+ name=name,
131
+ phone=phone,
132
+ sip_phone=clean_sip_phone(raw_gate.get("sipPhone")),
133
+ call_distance=raw_gate.get("callDistance"),
134
+ latitude=lat,
135
+ longitude=lng,
136
+ is_call_distance_allowed=is_call_distance_allowed,
137
+ is_manager=is_manager,
138
+ call_history=call_history or [],
139
+ raw=raw_gate,
140
+ )
141
+
142
+
143
+ @dataclass(slots=True)
144
+ class OpenGateAddress:
145
+ """Normalized OpenGate address model."""
146
+
147
+ address_id: str
148
+ address: str
149
+ subscription_type: str
150
+ subscription_label: str
151
+ left_days: int | float | None
152
+ is_manager: bool
153
+ is_call_distance_allowed: bool
154
+ is_just_call: bool
155
+ is_renew: bool
156
+ asked_to_stop_subscription: bool
157
+ gates: list[OpenGateGate] = field(default_factory=list)
158
+ raw: dict[str, Any] = field(default_factory=dict)
159
+
160
+ @classmethod
161
+ def from_dict(
162
+ cls,
163
+ raw_addr: dict[str, Any],
164
+ *,
165
+ user_id: str = "",
166
+ gates: list[OpenGateGate] | None = None,
167
+ ) -> OpenGateAddress:
168
+ """Create an OpenGateAddress from an API dictionary."""
169
+ addr_id = str(raw_addr.get("_id", ""))
170
+ sub_list = raw_addr.get("subscription")
171
+ sub_type = ""
172
+ if isinstance(sub_list, list) and sub_list:
173
+ sub_type = str(sub_list[0])
174
+ elif isinstance(sub_list, str):
175
+ sub_type = sub_list
176
+
177
+ managers = raw_addr.get("managers") or []
178
+ is_manager = bool(user_id and user_id in managers)
179
+ left_days_raw = raw_addr.get("leftDays")
180
+ left_days = left_days_raw if isinstance(left_days_raw, (int, float)) else None
181
+
182
+ return cls(
183
+ address_id=addr_id,
184
+ address=str(raw_addr.get("address") or f"Address {addr_id[:6]}"),
185
+ subscription_type=sub_type,
186
+ subscription_label=SUBSCRIPTION_LABELS.get(sub_type, sub_type or "Unknown"),
187
+ left_days=left_days,
188
+ is_manager=is_manager,
189
+ is_call_distance_allowed=bool(raw_addr.get("isCallDistanceAllowed", False)),
190
+ is_just_call=bool(raw_addr.get("isJustCall", False)),
191
+ is_renew=bool(raw_addr.get("isRenew", False)),
192
+ asked_to_stop_subscription=bool(raw_addr.get("askedToStopSubscription", False)),
193
+ gates=gates or [],
194
+ raw=raw_addr,
195
+ )
196
+
197
+
198
+ @dataclass(slots=True)
199
+ class OpenGateAccountSnapshot:
200
+ """Full snapshot of an OpenGate account's profile, addresses, and gates."""
201
+
202
+ user_info: dict[str, Any]
203
+ addresses: dict[str, OpenGateAddress]
204
+ gates: dict[str, OpenGateGate]
pyopengate/py.typed ADDED
File without changes
@@ -0,0 +1,92 @@
1
+ Metadata-Version: 2.5
2
+ Name: pyopengate
3
+ Version: 0.1.0
4
+ Summary: Async Python client library for the OpenGate gate-opening API.
5
+ Project-URL: Homepage, https://github.com/bentekkie/pyopengate
6
+ Project-URL: Repository, https://github.com/bentekkie/pyopengate
7
+ Project-URL: Issues, https://github.com/bentekkie/pyopengate/issues
8
+ Author: Ben Tekkie
9
+ License: MIT
10
+ License-File: LICENSE
11
+ Keywords: aiohttp,async,gate,home-assistant,opengate,smart-home
12
+ Classifier: Development Status :: 3 - Alpha
13
+ Classifier: Intended Audience :: Developers
14
+ Classifier: License :: OSI Approved :: MIT License
15
+ Classifier: Operating System :: OS Independent
16
+ Classifier: Programming Language :: Python :: 3
17
+ Classifier: Programming Language :: Python :: 3.12
18
+ Classifier: Programming Language :: Python :: 3.13
19
+ Classifier: Topic :: Home Automation
20
+ Classifier: Typing :: Typed
21
+ Requires-Python: >=3.12
22
+ Requires-Dist: aiohttp>=3.9.0
23
+ Provides-Extra: dev
24
+ Requires-Dist: pytest-asyncio>=0.24; extra == 'dev'
25
+ Requires-Dist: pytest>=8.0; extra == 'dev'
26
+ Requires-Dist: ruff>=0.6; extra == 'dev'
27
+ Description-Content-Type: text/markdown
28
+
29
+ # pyopengate
30
+
31
+ Async Python client library for the [OpenGate](https://opengate.io) cellular and parking gate opening API (`https://api.opengate.io`).
32
+
33
+ Built with `aiohttp` and typed dataclasses, designed for standalone automation scripts and the [ha-opengate](https://github.com/bentekkie/ha-opengate) Home Assistant Marketplace integration.
34
+
35
+ ## Installation
36
+
37
+ ```bash
38
+ pip install pyopengate
39
+ ```
40
+
41
+ ## Quick Start
42
+
43
+ ### Authenticate with SMS OTP
44
+
45
+ ```python
46
+ import asyncio
47
+ from pyopengate import OpenGateClient
48
+
49
+ async def main() -> None:
50
+ async with OpenGateClient() as client:
51
+ await client.async_generate_sms_code(ext="972", phone="0501234567")
52
+ code = input("Enter SMS OTP code: ")
53
+ profile = await client.async_verify_sms_code(
54
+ ext="972",
55
+ phone="0501234567",
56
+ sms_code=code,
57
+ )
58
+ print("Authenticated uqid:", profile["uqid"])
59
+
60
+ asyncio.run(main())
61
+ ```
62
+
63
+ ### List Gates & Trigger Opening
64
+
65
+ ```python
66
+ import asyncio
67
+ from pyopengate import OpenGateClient
68
+
69
+ async def main() -> None:
70
+ async with OpenGateClient(uqid="YOUR_UQID") as client:
71
+ snapshot = await client.async_fetch_snapshot()
72
+ for gate in snapshot.gates.values():
73
+ print(gate.gate_id, gate.name, gate.address_name)
74
+
75
+ first_gate = next(iter(snapshot.gates.values()))
76
+ await client.async_call_gate(first_gate.gate_id)
77
+
78
+ asyncio.run(main())
79
+ ```
80
+
81
+ ## Supported Features
82
+
83
+ - SMS OTP login (`/sms/generateSmsCode`, `/sms/verifySmsCode`) and session validation (`/customers/isLogged`)
84
+ - Typed account snapshot parsing (`/addresses`, `/gates`, `/gates/callHistory/<gatePhone>`)
85
+ - Remote gate triggering (`/gates/callNow`) with typed rejection errors (`trialEnd`, `blocked`, `gateNotClooseToAddress`, `clocksModeIsActive_protectGate`, `limitedCallDistance`)
86
+ - Parking lot gate triggering (`/parkinglots/opengate`)
87
+ - Manager actions: authorized customers and parking managers management
88
+ - Client-side 1 req/sec `POST` throttling matching the OpenGate mobile client
89
+
90
+ ## License
91
+
92
+ MIT
@@ -0,0 +1,10 @@
1
+ pyopengate/__init__.py,sha256=SGGT13G17DC7RweggzUO-txdkNZT1jjvYa4ckx5Mk-k,1047
2
+ pyopengate/client.py,sha256=A2m_bTvnC6Si5A4ZtXKSgBi4T7wI88rx3EieltHtEAU,22138
3
+ pyopengate/const.py,sha256=Vao1gv_eHL2WJIZAHueWKINeVO51qsgmtkRQRuvRUuQ,1465
4
+ pyopengate/exceptions.py,sha256=fsUZZ7Fg9UHpokjHIM8NDcJifkFebD2Nbsi8w2-Rddo,763
5
+ pyopengate/models.py,sha256=mB-aa4c2dufCichdx4nqJWlydzMU64DD7T1LVcaCoTY,6803
6
+ pyopengate/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
7
+ pyopengate-0.1.0.dist-info/METADATA,sha256=1fxJ1vbumi4eX-rTCnDH5l9EjYdOKt6UTmBYZDYyPHU,3127
8
+ pyopengate-0.1.0.dist-info/WHEEL,sha256=2iZrJkDIkeDh0k9SikKMqFuRP-ua6mb4Ir1AsER4BEw,87
9
+ pyopengate-0.1.0.dist-info/licenses/LICENSE,sha256=sOfi28wKdrevLteqnpFJkavJshssWrp4OynIORncw7A,1067
10
+ pyopengate-0.1.0.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: hatchling 1.33.0
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Ben Tekkie
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.