forked from NikolayRag/Yi4kAPI
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathyiAPI.py
134 lines (84 loc) · 2.24 KB
/
yiAPI.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
import logging
import socket, json, threading
from .yiAPICommand import *
from .yiAPIListener import *
class YiAPI():
#private commands
startSession= YiAPICommandGen(257)
stopSession= YiAPICommandGen(258)
ip= '192.168.42.1'
sock= None
tick= 0
sessionId= 0
rtsp= None
commandTimeout= 10
connectionTimeout= .5
connectionTries= 10
listener= None
@staticmethod
def defaults(ip):
if ip:
YiAPI.ip= ip
def __init__(self, _ip=None):
if _ip:
self.ip= _ip
#sometimes camera couldnt be connected after a pause. Try to connect several times.
for i in range(0,self.connectionTries):
try:
self.sock= socket.create_connection((self.ip,7878),self.connectionTimeout)
break
except:
None
if not self.sock:
logging.critical('Not connected')
return
self.sock.settimeout(None)
self.listener= YiAPIListener(self.sock)
res= self.cmd(self.startSession)
if res<0:
self.sock= None
else:
self.sessionId= res
#shoud be called at very end to tell camera it's released
def close(self):
self.cmd(self.stopSession)
if self.sock:
self.sock.close()
self.sock= None
'''
Run predefined _command.
if _vals provided, it's a value assigned to YiAPICommand.values respectively.
'''
def cmd(self, _command, _val=None):
if not self.sock:
logging.error('Camera disconnected')
return -99999
runCmd= _command.makeCmd({'token':self.sessionId, 'heartbeat':self.tick}, _val)
self.listener.instantCB(runCmd)
timeoutCmd= threading.Timer(self.commandTimeout, runCmd.blockingEvent.set)
timeoutCmd.start()
if not self.cmdSend(runCmd.cmdSend):
logging.critical('Socket error while sending')
runCmd.blockingEvent.set()
self.sock= None
runCmd.blockingEvent.wait()
timeoutCmd.cancel()
if 'rtsp' in runCmd.resultDict:
self.rtsp = runCmd.resultDict['rtsp']
logging.debug('Result %s' % runCmd.resultDict)
return runCmd.result()
'''
Sent YiAPICommandGen co camera.
'''
def cmdSend(self, _cmdDict):
logging.debug("Send %s" % _cmdDict)
try:
self.sock.sendall( bytes(json.dumps(_cmdDict),'ascii') )
except:
return
self.tick+= 1
return True
def setCB(self, _type=None, _cb=None):
if not self.listener:
return
return self.listener.setCB(_type, _cb)