提交 97d735cd authored 作者: zw.wang's avatar zw.wang

feat: 视频信息插入mysql

上级 d4a61efc
...@@ -2,3 +2,5 @@ ...@@ -2,3 +2,5 @@
This is the Python SDK to interact with Hikvision iSC platform using Hikvision's open API. This is the Python SDK to interact with Hikvision iSC platform using Hikvision's open API.
## CONFIG
...@@ -76,37 +76,34 @@ def query(cursor_dict=False): ...@@ -76,37 +76,34 @@ def query(cursor_dict=False):
return in_func return in_func
@query(cursor_dict=True)
def get_camera_sn(cursor, conn):
sql = '''
select
device_number camera_sn,
biz_type,
name camera_name
from camera.video_config
'''
# where device_number = 'E57379052'
cursor.execute(sql)
return cursor.fetchall()
@query(cursor_dict=True)
def get_camera_video_url(cursor, conn, table, camera_sn, date):
sql = '''
select video_url, id video_id, status, start_date, end_date, file_name
from {}
where date = %s and device_serial = %s
'''.format(table)
cursor.execute(sql, [date, camera_sn])
return cursor.fetchall()
@query() @query()
def set_video_data_status(cursor, conn, table, video_id): def insert_video_info(cursor, conn, device_code, file_name, start_time, end_time,
recovered_time, date, video_url, video_resolution, status=0):
sql = ''' sql = '''
update {} insert video_data_motion_test (
set status = 0 device_code, file_name, start_date, end_date,
where id = %s recovered_time, date,
'''.format(table) video_url, video_resolution,
cursor.execute(sql, [video_id]) biz_type, service_type,
expired_time, status, update_time)
value (%(device_code)s, %(file_name)s, %(start_date)s, %(end_date)s,
%(recovered_time)s, %(date)s,
%(video_url)s, %(video_resolution)s,
1, 1,
date_add(now(),interval 31 day), %(status)s, now()
)
'''
cursor.execute(sql, {
'device_code': device_code,
'file_name': file_name,
'start_date': start_time,
'end_date': end_time,
'video_url': video_url,
'video_resolution': video_resolution,
'recovered_time': recovered_time,
'date': date,
'status': status
})
video_id = cursor.lastrowid
conn.commit() conn.commit()
return video_id
...@@ -14,6 +14,7 @@ from hikvision_isc_client.db import rabbitmq_connect ...@@ -14,6 +14,7 @@ from hikvision_isc_client.db import rabbitmq_connect
from hikvision_isc_client.client import HikVisionClient from hikvision_isc_client.client import HikVisionClient
from hikvision_isc_client.utils import aliyun_oss from hikvision_isc_client.utils import aliyun_oss
from hikvision_isc_client.utils.record_utils import record_thread, get_video_duration, time_to_seconds from hikvision_isc_client.utils.record_utils import record_thread, get_video_duration, time_to_seconds
from hikvision_isc_client.db.mysql import insert_video_info
tz = pytz.timezone('Asia/Shanghai') tz = pytz.timezone('Asia/Shanghai')
...@@ -60,18 +61,20 @@ class StreamRecorder: ...@@ -60,18 +61,20 @@ class StreamRecorder:
(conn, thrds) = args (conn, thrds) = args
body = json.loads(body) body = json.loads(body)
delivery_tag = method_frame.delivery_tag delivery_tag = method_frame.delivery_tag
t = threading.Thread(target=do_work, args=(conn, ch, delivery_tag, body)) t = threading.Thread(target=do_work, args=(
conn, ch, delivery_tag, body))
t.start() t.start()
thrds.append(t) thrds.append(t)
threads = [] threads = []
on_message_callback = functools.partial(on_message, args=(self.connection, threads)) on_message_callback = functools.partial(
on_message, args=(self.connection, threads))
self.channel.basic_qos(prefetch_count=1) self.channel.basic_qos(prefetch_count=1)
self.channel.basic_consume(on_message_callback=on_message_callback, self.channel.basic_consume(on_message_callback=on_message_callback,
queue=self.queue_name) queue=self.queue_name)
log.info(' [*] Waiting for messages. To exit press CTRL+C') log.info('[*] Waiting for messages. To exit press CTRL+C')
try: try:
self.channel.start_consuming() self.channel.start_consuming()
except KeyboardInterrupt: except KeyboardInterrupt:
...@@ -86,16 +89,26 @@ class StreamRecorder: ...@@ -86,16 +89,26 @@ class StreamRecorder:
self.connection.close() self.connection.close()
def process_message(self, body): def process_message(self, body):
file_name = self.recorder( record_result = self.recorder(
body['camera_index'], body['camera_index'],
datetime.strptime(body['start_time'], '%Y-%m-%dT%H:%M:%S').astimezone(tz), datetime.strptime(body['start_time'], '%Y-%m-%dT%H:%M:%S').astimezone(tz),
datetime.strptime(body['end_time'], '%Y-%m-%dT%H:%M:%S').astimezone(tz) datetime.strptime(body['end_time'], '%Y-%m-%dT%H:%M:%S').astimezone(tz)
) )
video_info = get_video_duration(file_name)
video_info, error_log = get_video_duration(record_result['file_name'])
url = '' url = ''
if file_name and os.path.isfile(file_name): file_name = record_result['file_name'].split('/')[-1]
url = aliyun_oss.oss_upload_file('isc_record/' + file_name.split('/')[-1], file_name) if record_result['file_name'] and os.path.isfile(record_result['file_name']):
log.info('video_info: %s, url: %s', video_info, url) url = aliyun_oss.oss_upload_file('isc_record/' + file_name,
record_result['file_name'])
os.remove(record_result['file_name'])
video_id = insert_video_info(body['camera_code'], file_name, body['start_time'],
body['end_time'], recovered_time=record_result['recovered_time'],
date=body['start_time'].split('T')[0].replace('-', ''),
video_url=url, video_resolution=video_info['resolution'],
status=1 if record_result['is_completed'] else 2)
log.info('video_info: %s, url: %s, video_id: %s', video_info, url, video_id)
return True return True
@staticmethod @staticmethod
...@@ -111,14 +124,17 @@ class StreamRecorder: ...@@ -111,14 +124,17 @@ class StreamRecorder:
playback_stream = playback_urls[0] playback_stream = playback_urls[0]
else: else:
return return
part_num = 1 part_num = retry_count = 0
is_completed = False
part_files_set = set() part_files_set = set()
file_name = os.path.join(video_path, 'rtmp_{}_{}.mp4'.format( file_name = os.path.join(video_path, 'rtmp_{}_{}.mp4'.format(
start_time.astimezone(pytz.utc).strftime('%Y%m%dT%H%M%S'), start_time.astimezone(pytz.utc).strftime('%Y%m%dT%H%M%S'),
end_time.astimezone(pytz.utc).strftime('%Y%m%dT%H%M%S') end_time.astimezone(pytz.utc).strftime('%Y%m%dT%H%M%S')
)) ))
while True: while retry_count < 6:
# 重试六次
retry_count += 1
complete_duration = (end_time - start_time).total_seconds() complete_duration = (end_time - start_time).total_seconds()
file_info, _ = StreamRecorder.stream_record( file_info, _ = StreamRecorder.stream_record(
...@@ -139,16 +155,25 @@ class StreamRecorder: ...@@ -139,16 +155,25 @@ class StreamRecorder:
start_time = new_start_time start_time = new_start_time
part_num += 1 part_num += 1
retry_count = 0
else: else:
part_files_set.add(file_info['file_name']) part_files_set.add(file_info['file_name'])
is_completed = True
start_time = end_time
break break
part_files = sorted(list(part_files_set)) part_files = sorted(list(part_files_set))
if len(part_files) > 1: if len(part_files) > 1:
concat(part_files, file_name, removed=True) concat(part_files, file_name, removed=True)
elif len(part_files) == 1: elif len(part_files) == 1:
shutil.move(part_files[0], file_name) shutil.move(part_files[0], file_name)
log.info('The download is complete, file %s', file_name) log.info('The download is complete, file %s', file_name)
return file_name return {
'file_name': file_name,
'is_completed': is_completed,
'recovered_time': start_time,
'retry_count': retry_count
}
@staticmethod @staticmethod
def stream_record(stream, start_time, end_time): def stream_record(stream, start_time, end_time):
......
...@@ -5,7 +5,7 @@ with open('README.md', 'r') as fh: ...@@ -5,7 +5,7 @@ with open('README.md', 'r') as fh:
setuptools.setup( setuptools.setup(
name='hikvision-isc-client', name='hikvision-isc-client',
version='0.0.1', version='0.0.2',
author='', author='',
author_email='', author_email='',
description='Client to interact with Hikvision iSC platform using open API', description='Client to interact with Hikvision iSC platform using open API',
......
Markdown 格式
0%
您添加了 0 到此讨论。请谨慎行事。
请先完成此评论的编辑!
注册 或者 后发表评论