forked from xyyangkun/python-dvr
-
Notifications
You must be signed in to change notification settings - Fork 0
/
solarcam.py
217 lines (187 loc) · 7.56 KB
/
solarcam.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
from time import sleep
from dvrip import DVRIPCam, SomethingIsWrongWithCamera
from pathlib import Path
import subprocess
import json
from datetime import datetime
class SolarCam:
cam = None
logger = None
def __init__(self, host_ip, user, password, logger):
self.logger = logger
self.cam = DVRIPCam(
host_ip,
user=user,
password=password,
)
def login(self, num_retries=10):
for i in range(num_retries):
try:
self.logger.debug("Try login...")
self.cam.login()
self.logger.debug(
f"Success! Connected to Camera. Waiting few seconds to let Camera fully boot..."
)
# waiting until camera is ready
sleep(10)
return
except SomethingIsWrongWithCamera:
self.logger.debug("Could not connect...Camera could be offline")
self.cam.close()
if i == 9:
raise ConnectionRefusedError(
f"Could not connect {num_retries} times...aborting"
)
sleep(2)
def logout(self):
self.cam.close()
def get_time(self):
return self.cam.get_time()
def set_time(self, time=None):
if time is None:
time = datetime.now()
return self.cam.set_time(time=time)
def get_local_files(self, start, end, filetype):
return self.cam.list_local_files(start, end, filetype)
def dump_local_files(
self, files, blacklist_path, download_dir, target_filetype=None
):
with open(f"{blacklist_path}.dmp", "a") as outfile:
for file in files:
target_file_path = self.generateTargetFilePath(
file["FileName"], download_dir
)
outfile.write(f"{target_file_path}\n")
if target_filetype:
target_file_path_convert = self.generateTargetFilePath(
file["FileName"], download_dir, extention=f"{target_filetype}"
)
outfile.write(f"{target_file_path_convert}\n")
def generateTargetFilePath(self, filename, downloadDir, extention=""):
fileExtention = Path(filename).suffix
filenameSplit = filename.split("/")
filenameDisk = f"{filenameSplit[3]}_{filenameSplit[5][:8]}".replace(".", "-")
targetPathClean = f"{downloadDir}/{filenameDisk}"
if extention != "":
return f"{targetPathClean}{extention}"
return f"{targetPathClean}{fileExtention}"
def convertFile(self, sourceFile, targetFile):
if (
subprocess.run(
f"ffmpeg -framerate 15 -i {sourceFile} -b:v 1M -c:v libvpx-vp9 -c:a libopus {targetFile}",
stdout=subprocess.DEVNULL,
stderr=subprocess.DEVNULL,
shell=True,
).returncode
!= 0
):
self.logger.debug(f"Error converting video. Check {sourceFile}")
self.logger.debug(f"File successfully converted: {targetFile}")
Path(sourceFile).unlink()
self.logger.debug(f"Orginal file successfully deleted: {sourceFile}")
def save_files(self, download_dir, files, blacklist=None, target_filetype=None):
self.logger.debug(f"Start downloading files")
for file in files:
target_file_path = self.generateTargetFilePath(
file["FileName"], download_dir
)
target_file_path_convert = None
if target_filetype:
target_file_path_convert = self.generateTargetFilePath(
file["FileName"], download_dir, extention=f"{target_filetype}"
)
if Path(f"{target_file_path}").is_file():
self.logger.debug(f"File already exists: {target_file_path}")
continue
if (
target_file_path_convert
and Path(f"{target_file_path_convert}").is_file()
):
self.logger.debug(
f"Converted file already exists: {target_file_path_convert}"
)
continue
if blacklist:
if target_file_path in blacklist:
self.logger.debug(f"File is on the blacklist: {target_file_path}")
continue
if target_file_path_convert and target_file_path_convert in blacklist:
self.logger.debug(
f"File is on the blacklist: {target_file_path_convert}"
)
continue
self.logger.debug(f"Downloading {target_file_path}...")
self.cam.download_file(
file["BeginTime"], file["EndTime"], file["FileName"], target_file_path
)
self.logger.debug(f"Finished downloading {target_file_path}...")
if target_file_path_convert:
self.logger.debug(f"Converting {target_file_path_convert}...")
self.convertFile(target_file_path, target_file_path_convert)
self.logger.debug(f"Finished converting {target_file_path_convert}.")
self.logger.debug(f"Finish downloading files")
def move_cam(self, direction, step=5):
match direction:
case "up":
self.cam.ptz_step("DirectionUp", step=step)
case "down":
self.cam.ptz_step("DirectionDown", step=step)
case "left":
self.cam.ptz_step("DirectionLeft", step=step)
case "right":
self.cam.ptz_step("DirectionRight", step=step)
case _:
self.logger.debug(f"No direction found")
def mute_cam(self):
print(
self.cam.send(
1040,
{
"fVideo.Volume": [
{"AudioMode": "Single", "LeftVolume": 0, "RightVolume": 0}
],
"Name": "fVideo.Volume",
},
)
)
def set_volume(self, volume):
print(
self.cam.send(
1040,
{
"fVideo.Volume": [
{
"AudioMode": "Single",
"LeftVolume": volume,
"RightVolume": volume,
}
],
"Name": "fVideo.Volume",
},
)
)
def get_battery(self):
data = self.cam.send_custom(
1610,
{"Name": "OPTUpData", "OPTUpData": {"UpLoadDataType": 5}},
size=260,
)[87:-2].decode("utf-8")
json_data = json.loads(data)
return {
"BatteryPercent": json_data["Dev.ElectCapacity"]["percent"],
"Charging": json_data["Dev.ElectCapacity"]["electable"],
}
def get_storage(self):
# get available storage in gb
storage_result = []
data = self.cam.send(1020, {"Name": "StorageInfo"})
for storage_index, storage in enumerate(data["StorageInfo"]):
for partition_index, partition in enumerate(storage["Partition"]):
s = {
"Storage": storage_index,
"Partition": partition_index,
"RemainingSpace": int(partition["RemainSpace"], 0) / 1024,
"TotalSpace": int(partition["TotalSpace"], 0) / 1024,
}
storage_result.append(s)
return storage_result