def run(self): with open(self.setting_json) as f: data = json.load(f) cur_cmd = data['command'] while True: with open(self.setting_json) as f: status = json.load(f) print(self.command, '--------------------------------------------------') if status['status'] == 'run' and status['command'] == 'Inspection': if self.command == 'Inspection': self.rt_ins_helmet() else: print("newthread-----这个线程逻辑有错误") elif status['status'] == 'run' and status[ 'command'] == 'StartIdentify': if self.command == 'StartIdentify': self.rt_face_dec() else: print("newthread-----这个线程逻辑有错误") elif status['status'] == 'run' and status['command'] == 'Test': self.send_test() elif status['status'] == 'run' and setting( gParam.Event_Setting_Json )['status'] == 'run' and self.command == 'Event': self.send_event() elif status['status'] == 'stop' or cur_cmd != status['command']: print('newthread-----报文发送线程结束') break else: print("newthread-----又有逻辑漏洞") time.sleep(self.period / 2.0)
def main(): event = Event(e_smoking=True) event.TaskID = '4396' event.start() t_send = NewThread('Event', '4396', 4, tctimeClient) v_cap.video_path = gParam.Video_Path v_cap.video = 'smoking.mp4' setting(status='run', writing=True) setting(address=gParam.Event_Setting_Json, status='run', writing=True) t_send.start() time.sleep(30) setting(status='stop', writing=True) setting(address=gParam.Event_Setting_Json, status='stop', writing=True)
def run(self): while True: cur_time = time.time() with open(gParam.PeriodIns_Setting_Json) as f: status = json.load(f) if not self.TaskID in status.keys(): break if cur_time < self.starttime: time.sleep(60) else: self.ins_helmet.period = int(self.period) self.ins_helmet.name = self.TaskID setting(status='run', command='Inspection', url=self.url, writing=True) ins_send = NewThread('Inspection', self.TaskID, int(self.period), self.t_send) ins_send.start() while True: cur_time = time.time() if cur_time > self.endtime: setting(status='stop', command='none', writing=True) with open(gParam.PeriodIns_Setting_Json) as f: status_periodins = json.load(f) status_periodins.pop(self.TaskID) print(self.TaskID, "该任务设置已取消") with open(gParam.PeriodIns_Setting_Json, 'w') as f: json.dump(status_periodins, f) break else: time.sleep(10) print("stoppableThread-----线程结束", self.TaskID)
def event_ins(): event = Event(e_helmet=True) event.TaskID = '10010-4396' v_cap.start() event.start() v_cap.video_path = False t_send = NewThread('Event', '10010-4396', 5, tctimeClient) t_send.period = 7 # 开启事件响应功能 由于是测试 设置一分钟自动关闭 setting(status='run', writing=True) setting(address=gParam.Event_Setting_Json, status='run', writing=True) t_send.start() time.sleep(60) setting(status='stop', writing=True) setting(address=gParam.Event_Setting_Json, status='stop', writing=True)
def capvideo(self): while True: status = {} with open(self.setting_path) as f: status = json.load(f) if status['status'] == 'run': try: if self.video_path and self.video != None: print('videocap-----video_path', self.video_path) path = os.path.join(self.video_path, self.video) cap = cv2.VideoCapture(path) elif self.video_path and self.video == None: print("videocap-----系统已自动关闭图像抓取,请指定url或视频名后再打开") setting(status='stop', writing=True) continue else: print("尝试连接摄像头", status['addr']) cap = cv2.VideoCapture(status['addr']) print('videocap-----连接摄像头成功') except: print('videocap-----连接摄像头失败') setting(status='stop', writing=True) continue count_num = 0 print('---------------------------------------') while cap.isOpened(): count_num += 1 cur_time = str(time.time()) name = cur_time + '.jpg' ret, frame = cap.read() if (count_num % 18 == 0): try: path = os.path.join(self.videosplit_path, name) cv2.imwrite(path, frame) # print('抓取图像', name) time.sleep(0.5) except: print("videocap-----存储抓取的图像时出错") if ret == False: setting(status='stop', command='none', writing=True) data = {} with open(self.setting_path) as f: data = json.load(f) if data['status'] == 'stop': cap.release() print('--------------------------------------') print('videocap-----停止抓取图像') break else: print("videocap-----心跳响应") time.sleep(2)
def functional(): while True: time.sleep(2) try: json_data = '' while True: json_data_part = tctimeClient.recv(BUFFSIZE).decode('gbk') if '}]}' in json_data_part: print("----------------------同步报文接收完毕") json_data = json_data + json_data_part break elif (len(json_data_part) < 1000): print("接收到了报文:^_^---") json_data = json_data_part break else: print("===================同步报文未接收完毕") json_data = json_data + json_data_part pass # json_data = tctimeClient.recv(BUFFSIZE).decode('gbk') print('received functional data', json_data) if len(json_data) < 10: print("json_data的长度小于10") continue try: json_data = json.loads(json_data.strip()) except: print("无法解析发来的json_data") continue try: command = json_data['Command'] except: print("无法查看发来json_data的命令是什么") continue if command == 'rt_register': print("rt_register-----------------") pass elif command == 'OPParas': """ 由机器人平台向我们分析平台发送人为指定的参数,包括施工总人数,红帽人数(施工经理人数)、蓝帽人数、黄帽人数 如果是没有指定这些参数,需要我们设置一个默认值(这一点被原作者废弃) """ print("----------------OPParas----------") TaskID = json_data['TaskID'] # json.dumps()可以将字典转为字符串 ins.set_opparas(json.dumps(json_data)) rt_data = ins.rt_opparas(TaskID).encode() tctimeClient.send(rt_data) print('-------发送参数设置的即时相应报文完毕---------') continue elif command == 'Stop': """ 根据接口协议,这个命令需要我们立刻停止当前分析工作,并返回响应 """ TaskID = json_data['TaskID'] setting(status='stop', command='stop', writing=True) # 生成对应Stop命令的回传数据,默认一切正常 rt_data = ins.rt_stop().encode() tctimeClient.send(rt_data) continue elif command == 'Inspection': """按照接口协议,发来的json串包含如下内容 json:{ Command: "Inspection" TaskID: string InspecType: string, 123中的一个,分别对应立即,指定时间执行和取消之前的设置 InspecPeriod: int, 周期执行间隔 InspecStart: string, 指定开始时间 InspecEnd: string, 指定结束时间 } 希望我们有及时响应,判断是否正常执行;有异步响应,返回json串如下 rt json:{ Command: "rt_Inspection" TaskID: string OpNumber: int, 施工总人数 OpRed: int, 红帽人数 OpBlue: int, 蓝帽人数 OpYellow: int, 黄帽人数 Image: string, 经标注过的图像, base64格式 } """ print('-----------Inspection-------------') TaskID = json_data['TaskID'] print(ins.DataBase[TaskID]) url = ins.DataBase[TaskID]['Url'] # 先把即时响应返回去 rt_data = ins.ack_inspection(TaskID).encode() tctimeClient.send(rt_data) print("Inspection 即时报文发送完毕") # 改addr,改属性,改status command setting(url=url, writing=True) if ins.DataBase[TaskID]['DeviceType'] == 'video': v_cap.video_path = gParam.Video_Path v_cap.video = '1.mp4' else: v_cap.video_path = False # 首先根据发来的消息修改巡检设置和redis缓存key t_helmet.period = int(json_data['InspecPeriod']) t_helmet.name = json_data['TaskID'] # 开始检测 if json_data['InspecType'] == "1": # 立即执行安全帽检测 setting(status='run', command='Inspection', writing=True) # 创建线程,后台异步发送检测信息 ins_send = NewThread('Inspection', TaskID, int(json_data['InspecPeriod']), tctimeClient) ins_send.start() elif json_data['InspecType'] == "2": # 修改周期巡检专属配置文件,添加TaskID with open(gParam.PeriodIns_Setting_Json) as f: status_periodins = json.load(f) status_periodins[TaskID] = True with open(gParam.PeriodIns_Setting_Json, 'w') as f: json.dump(status_periodins, f) ins_settime = StoppableThread(TaskID, json_data['InspecStart'], json_data['InspecEnd'], json_data['InspecPeriod'], tctimeClient, url) ins_settime.start() elif json_data['InspecType'] == "3": with open(gParam.PeriodIns_Setting_Json) as f: status_periodins = json.load(f) status_periodins.pop(TaskID) print(TaskID, "该任务设置已取消") with open(gParam.PeriodIns_Setting_Json, 'w') as f: json.dump(status_periodins, f) else: print("tcpclient出现了逻辑错误") continue elif command == 'SyncIdentify': """根据接口协议,这一步是为了同步照片库,身份信息 传过来的是一个字符串数组 PersonList:[ { code: 工号, type: 职务, pic: base64格式的照片 }, {...}, {...} ] 我们应做出及时响应 """ print('-----------SyncIdentify-------------') if type(json_data['PersonList']) == str: person_data = eval(json_data['PersonList']) else: person_data = json_data['PersonList'] result = person_write(person_data) # features_write() ins.syncIdentify() rt_data = ins.rt_syncIdentify(ErrorCodeList=result) tctimeClient.send(rt_data.encode()) continue elif command == 'StartIdentify': """根据接口协议,这一步要识别现场人员,然后不断的异步返回信息 收到的json_data:{ Command: string, StartIdentify TaskID: string DeviceType: string, 设备类型,摄像头"camer"或者录像"recorder" VideoType: string, 视频类型, "mp4"文件流或者"rtsp"实时流 IP: string, IP端口 Port: int, 端口 Url: string, URL地址 PersonCount: int, 需要识别出的人员个数 WaitMinutes: int, 最大等待时间 } 即时响应,看是否连接成功 异步响应: json_data:{ Command: string, "rt_StartIdentify" TaskID: string, Retval: string, "OK" or "Error" MatchInfo: string, JSON格式的字符串, 当Retval=="OK"时才有 Reason: string, 错误原因 DismatchPic: string, 数据库没有但是现场有的人的图片 } 其中: MatchInfo: "{ pic: base64, 识别时的截图 matches:[{ matchPic: base64, 照片库中的匹配照片 matchCode: string, matchType: string, matchPercent: int, 相似度 }, {...}, {...}] }" Reason:"{ ErrorCode: string, 错误号 ErrorMessage: string, 出错原因 }" """ # 返回即时信息 rt_data = ins.ack_startIdentify().encode() tctimeClient.send(rt_data) # 改addr, 改属性,改status command TaskID = json_data['TaskID'] addr = json_data['Url'] setting(url=addr, writing=True) # 具体类型的指定,接口文档说的很不清楚,需要进一步的考虑 if json_data['VideoType'] == 'rtsp': print("tcpclient-----使用rtsp流,有可能出现无效rtsp流现象,注意日志") v_cap.video_path = False f_dectect.TaskID = TaskID f_dectect.time_limit = 60 * int(json_data['WaitMinutes']) f_dectect.PersonCount = int(json_data['PersonCount']) f_dectect.period = 1 setting(status='run', command='StartIdentify', writing=True) # 创建线程,后台异步发送人脸识别信息 ins_send = NewThread(command='StartIdentify', TaskID=TaskID, period=4, t_send=tctimeClient) ins_send.start() elif command == 'StopIdentify': setting(status='stop', command='StopIdentify', url='rtsp://*****:*****@192.168.0.64/video1', writing=True) ins.StopIdentify() rt_data = ins.ack_stopidentify().encode() tctimeClient.send(rt_data) print("发送停止StopIdentify响应报文") continue else: pass except: print("这次没接收到指令") pass # 专为测试而生 print("----------------------END-------------------")
def detect_face(self): while True: status = {} with open(self.setting_json) as f: status = json.load(f) if status['status'] == 'run' and status[ 'command'] == 'StartIdentify': start_time = time.time() person_count = 0 while True: # print("facedetect-----已经开启") try: """ 取出视频流的最新截图,从中截取人脸,保存人脸文件到gParam.Face_Path """ lists = [] lists = os.listdir(self.videosplit_path) try: lists.sort(key=lambda fn: os.path.getmtime( os.path.join(self.videosplit_path, fn))) # frame_name = os.path.join(self.videosplit_path, lists[-1]) frame_name = os.path.join(self.videosplit_path, "1581607991.216811.jpg") except: frame_name = None print('frame_name = None') facename_list = self.clip_face(frame_name) # time.sleep(0.3) # print('frame_name:', frame_name) # print('facename_list', facename_list) except: print("有错误") for facename in facename_list: finding, repeating, err_img_path, MatchInfo = self.face_identify( facename) # 根据返回信息决定如何发送报文 # 正常找到照片对应员工 if finding == True and repeating == False: rt_data = { 'Command': 'rt_StartIdentify', 'TaskID': self.TaskID, 'Retval': 'OK', 'MatchInfo': json.dumps(MatchInfo) } rt_data = json.dumps(rt_data) if type(rt_data) == str: rt_data = rt_data.encode() self.rq.lpush(self.TaskID, rt_data) time.sleep(1) # 没有找到与图片对应的数据库照片 elif finding == False and repeating == False: reason = { 'ErrorCode': '0002', 'ErrorMessage': 'find unmatched person' } rt_data = { 'Command': 'rt_StartIdentify', 'TaskID': self.TaskID, 'Retval': 'Error', 'Reason': json.dumps(reason), 'DismatchPic': MatchInfo['pic'] } rt_data = json.dumps(rt_data) if type(rt_data) == str: rt_data = rt_data.encode() self.rq.lpush(self.TaskID, rt_data) time.sleep(1) elif finding == False and repeating == True: print('facedetect-----err_img_path---------', err_img_path) else: pass # 判断有没有超时 cur_time = time.time() # print('time-----------------', cur_time-start_time) if cur_time - start_time > self.time_limit: # 发送retval为error的报文,并主动停止 if self.person_num == []: rt_data = self.ins.rt_startidentify( self.TaskID, Retval='Error', Reason='TimeOut') if type(rt_data) == str: rt_data = rt_data.encode() self.rq.lpush(self.TaskID, rt_data) else: errormessage = 'just match ' + str( len(self.person_num)) reason = { 'ErrorCode': '0003', 'ErrorMessage': errormessage } rt_data = { 'Command': 'rt_StartIdentify', 'TaskID': self.TaskID, 'Retval': 'Error', 'Reason': json.dumps(reason) } rt_data = json.dumps(rt_data) if type(rt_data) == str: rt_data = rt_data.encode() self.rq.lpush(self.TaskID, rt_data) print("facedetect-----time out! Stop!") setting(status='stop', command='none', writing=True) with open(self.setting_json) as f: data = json.load(f) if not (data['status'] == 'run' and data['command'] == 'StartIdentify'): print("facedetect-----停止人脸识别") # 将本地文件中的截取的视频流图片删除,节省空间 lists = os.listdir(self.videosplit_path) lists.sort(reverse=True, key=lambda fn: os.path.getmtime( self.videosplit_path + "/" + fn)) try: for i in lists[3:]: os.remove(os.path.join(self.videosplit_path, i)) print("facedetect-----清理冗余文件") except: print("facedetect-----无冗余文件") while self.rq.llen(self.TaskID) > 0: self.rq.rpop(self.TaskID) print('facedetect-----清理redis缓存成功') self.update() break # 现在是根据这里的设定来决定多长时间截取一次人脸 time.sleep(self.period) else: print("facedetect-----未开启人脸识别") time.sleep(3)