-
Notifications
You must be signed in to change notification settings - Fork 24
/
dahua_rpc.py
303 lines (239 loc) · 8.85 KB
/
dahua_rpc.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
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Basic Dahua RPC wrapper.
Forked from https://gist.github.com/48072a72be3a169bc43549e676713201.git
Added ANPR Plate Number extraction by Naveen Sakthivel <https://github.com/naveenrobo>
Example:
from dahua_rpc import DahuaRpc
dahua = DahuaRpc(host="192.168.1.10", username="admin", password="password")
dahua.login()
# Get the current time on the device
print(dahua.current_time())
# Set display to 4 grids with first view group
dahua.set_split(mode=4, view=1)
# Make a raw RPC request to get serial number
print(dahua.request(method="magicBox.getSerialNo"))
# Get the ANPR Plate Numbers by using the following
object_id = dahua.get_traffic_info() # Get the object id
dahua.startFind(object_id=object_id) # Use the object id to find the Plate Numbers
response = json.dumps(dahua.do_find(object_id=object_id)) # Extract the Plate Numbers
Dependencies:
pip install requests
"""
import sys
import hashlib
import requests
from enum import Enum
if (sys.version_info > (3, 0)):
unicode = str
class DahuaRpc(object):
def __init__(self, host, username, password):
self.host = host
self.username = username
self.password = password
self.s = requests.Session()
self.session_id = None
self.id = 0
def request(self, method, params=None, object_id=None, extra=None, url=None):
"""Make a RPC request."""
self.id += 1
data = {'method': method, 'id': self.id}
if params is not None:
data['params'] = params
if object_id:
data['object'] = object_id
if extra is not None:
data.update(extra)
if self.session_id:
data['session'] = self.session_id
if not url:
url = "http://{}/RPC2".format(self.host)
r = self.s.post(url, json=data)
return r.json()
def login(self):
"""Dahua RPC login.
Reversed from rpcCore.js (login, getAuth & getAuthByType functions).
Also referenced:
https://gist.github.com/avelardi/1338d9d7be0344ab7f4280618930cd0d
"""
# login1: get session, realm & random for real login
url = 'http://{}/RPC2_Login'.format(self.host)
method = "global.login"
params = {'userName': self.username,
'password': "",
'clientType': "Web3.0"}
r = self.request(method=method, params=params, url=url)
self.session_id = r['session']
realm = r['params']['realm']
random = r['params']['random']
# Password encryption algorithm
# Reversed from rpcCore.getAuthByType
pwd_phrase = self.username + ":" + realm + ":" + self.password
if isinstance(pwd_phrase, unicode):
pwd_phrase = pwd_phrase.encode('utf-8')
pwd_hash = hashlib.md5(pwd_phrase).hexdigest().upper()
pass_phrase = self.username + ':' + random + ':' + pwd_hash
if isinstance(pass_phrase, unicode):
pass_phrase = pass_phrase.encode('utf-8')
pass_hash = hashlib.md5(pass_phrase).hexdigest().upper()
# login2: the real login
params = {'userName': self.username,
'password': pass_hash,
'clientType': "Web3.0",
'authorityType': "Default",
'passwordType': "Default"}
r = self.request(method=method, params=params, url=url)
if r['result'] is False:
raise LoginError(str(r))
def get_product_def(self):
method = "magicBox.getProductDefinition"
params = {
"name" : "Traffic"
}
r = self.request(method=method, params=params)
if r['result'] is False:
raise RequestError(str(r))
def keep_alive(self):
params = {
'timeout': 300,
'active': False
}
method = "global.keepAlive"
r = self.request(method=method, params=params)
if r['result'] is True:
return True
else:
raise RequestError(str(r))
def get_traffic_info(self):
method = "RecordFinder.factory.create"
params = {
"name" : "TrafficSnapEventInfo"
}
r = self.request(method=method, params=params)
if type(r['result']):
return r['result']
else:
raise RequestError(str(r))
def start_find(self,object_id):
method = "RecordFinder.startFind"
object_id = object_id
params = {
"condition" : {
"Time" : ["<>",1558925818,1559012218]
}
}
r = self.request(object_id=object_id,method=method, params=params)
if r['result'] is False:
raise RequestError(str(r))
def do_find(self,object_id):
method = "RecordFinder.doFind"
object_id = object_id
params = {
"count" : 50000
}
r = self.request(object_id=object_id,method=method, params=params)
if r['result'] is False:
raise RequestError(str(r))
else:
return r
def set_config(self, params):
"""Set configurations."""
method = "configManager.setConfig"
r = self.request(method=method, params=params)
if r['result'] is False:
raise RequestError(str(r))
def reboot(self):
"""Reboot the device."""
# Get object id
method = "magicBox.factory.instance"
params = ""
r = self.request(method=method, params=params)
object_id = r['result']
# Reboot
method = "magicBox.reboot"
r = self.request(method=method, params=params, object_id=object_id)
if r['result'] is False:
raise RequestError(str(r))
def current_time(self):
"""Get the current time on the device."""
method = "global.getCurrentTime"
r = self.request(method=method)
if r['result'] is False:
raise RequestError(str(r))
return r['params']['time']
def ntp_sync(self, address, port, time_zone):
"""Synchronize time with NTP."""
# Get object id
method = "netApp.factory.instance"
params = ""
r = self.request(method=method, params=params)
object_id = r['result']
# NTP sync
method = "netApp.adjustTimeWithNTP"
params = {'Address': address, 'Port': port, 'TimeZone': time_zone}
r = self.request(method=method, params=params, object_id=object_id)
if r['result'] is False:
raise RequestError(str(r))
def get_split(self):
"""Get display split mode."""
# Get object id
method = "split.factory.instance"
params = {'channel': 0}
r = self.request(method=method, params=params)
object_id = r['result']
# Get split mode
method = "split.getMode"
params = ""
r = self.request(method=method, params=params, object_id=object_id)
if r['result'] is False:
raise RequestError(str(r))
mode = int(r['params']['mode'][5:])
view = int(r['params']['group']) + 1
return mode, view
def attach_event(self, event = []):
"""Attach a event to current session"""
method = "eventManager.attach"
if(event is None):
return
params = {
'codes' : [*event]
}
r = self.request(method=method, params=params)
if r['result'] is False:
raise RequestError(str(r))
return r['params']
def listen_events(self, _callback= None):
""" Listen for envents. Attach an event before using this function """
url = "http://{host}/SubscribeNotify.cgi?sessionId={session}".format(host=self.host,session=self.session_id)
response = self.s.get(url, stream= True)
buffer = ""
for chunk in response.iter_content(chunk_size=1):
buffer += chunk.decode("utf-8")
if (buffer.endswith('</script>') is True):
if _callback:
_callback(buffer)
buffer = ""
def set_split(self, mode, view):
"""Set display split mode."""
if isinstance(mode, int):
mode = "Split{}".format(mode)
group = view - 1
# Get object id
method = "split.factory.instance"
params = {'channel': 0}
r = self.request(method=method, params=params)
object_id = r['result']
# Set split mode
method = "split.setMode"
params = {'displayType': "General",
'workMode': "Local",
'mode': mode,
'group': group}
r = self.request(method=method, params=params, object_id=object_id)
if r['result'] is False:
raise RequestError(str(r))
class LoginError(Exception):
pass
class RequestError(Exception):
pass