-
-
Notifications
You must be signed in to change notification settings - Fork 11
/
vapix.py
242 lines (197 loc) · 8.1 KB
/
vapix.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
"""Python library to enable Axis devices to integrate with Home Assistant."""
import asyncio
import logging
from packaging import version
import httpx
from .api_discovery import ApiDiscovery
from .applications import (
APPLICATION_STATE_RUNNING,
Applications,
PARAM_CGI_KEY as APPLICATIONS_PARAM,
PARAM_CGI_VALUE as APPLICATIONS_MINIMUM_VERSION,
)
from .applications.fence_guard import FenceGuard
from .applications.loitering_guard import LoiteringGuard
from .applications.motion_guard import MotionGuard
from .applications.vmd4 import Vmd4
from .basic_device_info import BasicDeviceInfo, API_DISCOVERY_ID as BASIC_DEVICE_INFO_ID
from .configuration import Configuration
from .errors import raise_error, PathNotFound, RequestError, Unauthorized
from .light_control import LightControl, API_DISCOVERY_ID as LIGHT_CONTROL_ID
from .mqtt import MqttClient, API_DISCOVERY_ID as MQTT_ID
from .param_cgi import Params
from .port_management import IoPortManagement, API_DISCOVERY_ID as IO_PORT_MANAGEMENT_ID
from .port_cgi import Ports
from .pwdgrp_cgi import URL_GET as PWDGRP_URL, Users
from .stream_profiles import StreamProfiles, API_DISCOVERY_ID as STREAM_PROFILES_ID
LOGGER = logging.getLogger(__name__)
class Vapix:
"""Vapix parameter request."""
def __init__(self, config: Configuration) -> None:
"""Store local reference to device config."""
self.config = config
self.session = httpx.AsyncClient(
auth=httpx.DigestAuth(config.username, config.password),
verify=config.verify_ssl,
)
self.api_discovery = None
self.applications = None
self.basic_device_info = None
self.fence_guard = None
self.light_control = None
self.loitering_guard = None
self.motion_guard = None
self.mqtt = None
self.params = None
self.ports = None
self.stream_profiles = None
self.users = None
self.vmd4 = None
async def close(self):
"""Close session."""
if self.session:
await self.session.aclose()
self.session = None
@property
def firmware_version(self) -> str:
"""Firmware version of device."""
if self.basic_device_info:
return self.basic_device_info.version
return self.params.firmware_version
@property
def product_number(self) -> str:
"""Product number of device."""
if self.basic_device_info:
return self.basic_device_info.prodnbr
return self.params.prodnbr
@property
def product_type(self) -> str:
"""Product type of device."""
if self.basic_device_info:
return self.basic_device_info.prodtype
return self.params.prodtype
@property
def serial_number(self) -> str:
"""Serial number of device."""
if self.basic_device_info:
return self.basic_device_info.serialnumber
return self.params.system_serialnumber
@property
def streaming_profiles(self) -> list:
"""List streaming profiles."""
if self.stream_profiles:
return list(self.stream_profiles.values())
return self.params.stream_profiles()
async def initialize(self) -> None:
"""Initialize Vapix functions."""
await self.initialize_api_discovery()
await self.initialize_param_cgi(preload_data=False)
await self.initialize_applications()
async def _initialize_api_attribute(self, api_class, api_attr: str) -> None:
"""Initialize API and load data."""
api_instance = api_class(self.request)
try:
await api_instance.update()
except Unauthorized: # Probably a viewer account
pass
else:
setattr(self, api_attr, api_instance)
async def initialize_api_discovery(self) -> None:
"""Load API list from API Discovery."""
self.api_discovery = ApiDiscovery(self.request)
try:
await self.api_discovery.update()
except PathNotFound: # Device doesn't support API discovery
return
tasks = []
for api_id, api_class, api_attr in (
(BASIC_DEVICE_INFO_ID, BasicDeviceInfo, "basic_device_info"),
(IO_PORT_MANAGEMENT_ID, IoPortManagement, "ports"),
(LIGHT_CONTROL_ID, LightControl, "light_control"),
(MQTT_ID, MqttClient, "mqtt"),
(STREAM_PROFILES_ID, StreamProfiles, "stream_profiles"),
):
if api_id in self.api_discovery:
tasks.append(self._initialize_api_attribute(api_class, api_attr))
if tasks:
await asyncio.gather(*tasks)
async def initialize_param_cgi(self, preload_data: bool = True) -> None:
"""Load data from param.cgi."""
self.params = Params(self.request)
tasks = []
if preload_data:
tasks.append(self.params.update())
else:
tasks.append(self.params.update_properties())
if not self.basic_device_info:
tasks.append(self.params.update_brand())
if not self.ports:
tasks.append(self.params.update_ports())
if not self.stream_profiles:
tasks.append(self.params.update_stream_profiles())
if tasks:
await asyncio.gather(*tasks)
if not self.light_control and self.params.light_control:
await self._initialize_api_attribute(LightControl, "light_control")
if not self.ports:
self.ports = Ports(self.params, self.request)
async def initialize_applications(self):
"""Load data for applications on device."""
self.applications = Applications(self.request)
if (
self.params
and f"root.{APPLICATIONS_PARAM}" in self.params
and version.parse(self.params.embedded_development)
>= version.parse(APPLICATIONS_MINIMUM_VERSION)
):
try:
await self.applications.update()
except Unauthorized: # Probably a viewer account
return
tasks = []
for app_class, app_attr in (
(FenceGuard, "fence_guard"),
(LoiteringGuard, "loitering_guard"),
(MotionGuard, "motion_guard"),
(Vmd4, "vmd4"),
):
if (
app_class.APPLICATION_NAME in self.applications
and self.applications[app_class.APPLICATION_NAME].status
== APPLICATION_STATE_RUNNING
):
tasks.append(self._initialize_api_attribute(app_class, app_attr))
if tasks:
await asyncio.gather(*tasks)
async def initialize_users(self) -> None:
"""Load device user data and initialize user management."""
users = await self.request("get", PWDGRP_URL)
self.users = Users(users, self.request)
async def request(self, method: str, path: str, **kwargs: dict) -> str:
"""Make a request to the API."""
url = self.config.url + path
LOGGER.debug("%s %s", url, kwargs)
try:
response = await self.session.request(method, url, **kwargs)
response.raise_for_status()
LOGGER.debug("Response: %s from %s", response.text, self.config.host)
if "application/json" in response.headers.get("Content-Type"):
result = response.json()
if "error" in result:
return {}
return result
if response.text.startswith("# Error:"):
return ""
return response.text
except httpx.HTTPStatusError as errh:
LOGGER.debug("%s, %s", response, errh)
raise_error(response.status_code)
except httpx.TimeoutException as errt:
LOGGER.debug("%s", errt)
raise RequestError("Timeout: {}".format(errt))
except httpx.TransportError as errc:
LOGGER.debug("%s", errc)
raise RequestError("Connection error: {}".format(errc))
except httpx.RequestError as err:
LOGGER.debug("%s", err)
raise RequestError("Unknown error: {}".format(err))