def createDaemon(): try: pid = os.fork() if pid > 0: # exit first parent sys.exit(0) except OSError as e: util.Logprint(5, e.errno + e.strerror) # util.log(e.errno) # util.log(e.strerror) sys.exit(1) # decouple from parent environment os.chdir("/") os.setsid() os.umask(0) # do second fork try: pid = os.fork() if pid > 0: # exit from second parent, print eventual PID before sys.exit(0) except OSError, e: # util.log(e.errno) # util.log(e.strerror) util.Logprint(5, e.errno + e.strerror) sys.exit(1)
def process_IN_CLOSE_WRITE(self, event): with open('/home/nvidia/Horus/config.cnf') as json_data: cnf = json.load(json_data) db = create_engine(cnf['db']) imagename = util.OnlyNumber(event.pathname) sqlInsert = 'insert into tb_camera(timestamp,img_id,frequency) values(%s,%s,%s)' % ( imagename, imagename, timeF) db.execute(sqlInsert) if len(imagename) > 14: currenttime = imagename[:14] global cur_time if cmp(currenttime, cur_time) == 0: pass else: cur_time = currenttime insert_simulation = 'insert into tb_simulation(time,injure_count,injure_count_2,death_count,damage_cost,damage_count,scrap,accident_count,period) values(%s,%d,%d,%d,%d,%d,%d,%d,%d)' % ( cur_time, 3, 5, 4, 10000, 6, 8, 15, 19) db.execute(insert_simulation) r = darknet.detect(event.pathname) util.Logprint(1, imagename + ":" + str(r)) util.move_single_image(cnf['cap_path'], cnf['arc_path'], imagename + ".jpg")
def startListener(): util.Logprint(1, '开启文件夹监听') # watch manager wm = pyinotify.WatchManager() sys.path.append("..") with open('/home/nvidia/Horus/config.cnf') as f: cnf = json.load(f) wm.add_watch(cnf['cap_path'], pyinotify.ALL_EVENTS, rec=True) # event handler eh = MyEventHandler() # notifier notifier = pyinotify.Notifier(wm, eh) notifier.loop()
def sendFile(self, socket, filepath): if os.path.isfile(filepath): filesize = struct.calcsize('128sl') #定义打包规则 #定义文件头信息,包含文件名和文件大小 fhead = struct.pack('128sl', os.path.basename(filepath), os.stat(filepath).st_size) socket.send(fhead) fo = open(filepath, 'rb') while True: filedata = fo.read(1024) if not filedata: break socket.send(filedata) fo.close() else: sys.path.append("..") import util util.Logprint(4, 'no such log file')
def deal_command(self, socket, data): sys.path.append("..") import util if '0x01' in data: #打开摄像头 util.Logprint(2, data) cmd = '/home/nvidia/Horus/opencamera' subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT) elif '0x02' in data: #自定义命令 util.Logprint(2, data) cus_command = data.split(':')[1] if cus_command != '': os.system(cus_command) elif '0x03' in data: util.Logprint(2, data) #关闭摄像头 pids = psutil.pids() for pid in pids: p = psutil.Process(pid) # if "python" in p.name(): # ss=p.cmdline() # if len(ss)>0: # if ss[1]=="/home/nvidia/Horus/opencamera.py": # util.kill(pid) # util.Logprint(1,data) if "opencamera" in p.name(): util.kill(pid) elif '0x04' in data: #发送日志 # Communicate().sendFile(socket,config.LOG_PATH) pass elif '0x05' in data: import util #更新config的level值 util.Logprint(2, data) #设置config key = data.split(':')[1] value = data.split(':')[2] #修改K-V with open('/home/nvidia/Horus/config.cnf') as f: cnf = json.load(f) cnf[key] = value jsonstr = json.dumps(cnf, ensure_ascii=False, sort_keys=True) util.replace('/home/nvidia/Horus/config.cnf', jsonstr) elif '0x06' in data: util.Logprint(2, data) #打开环境传感器 global envid envid = Communicate().createnvDaemon() elif '0x07' in data: util.Logprint(2, data) #关闭环境传感器 util.kill(envid) elif '0x08' in data: util.Logprint(2, data) obddata = data[5:] if util.is_json(obddata): with open('/home/nvidia/Horus/config.cnf') as json_data: cnf = json.load(json_data) db = create_engine(cnf['db']) s = json.loads(obddata) insert_data = "insert into tb_obd(timestamp,longitude,latitude,altitude,speed) values (%s,%s,%s,%s,%s)" % ( s["timestamp"], s["longitude"], s["latitude"], s["altitude"], s["speed"]) db.execute(insert_data) elif '0x09' in data: util.Logprint(2, data) pids = psutil.pids() for pid in pids: p = psutil.Process(pid) if "python" in p.name(): ss = p.cmdline() if len(ss) > 0: if ss[1] == "Horus.py": util.kill(pid) util.Logprint(1, data) if "Horus" in p.name(): util.kill(pid) # elif 'test' in data: util.Logprint(1, data) #心跳测试和数据库表的条目查询 Communicate().dbquery(socket) pass else: util.Logprint(1, data) #手机端json数据 if util.is_json(data): with open('/home/nvidia/Horus/config.cnf') as json_data: cnf = json.load(json_data) db = create_engine(cnf['db']) s = json.loads(data) insert_data = "insert into tb_mobile_sensor(timestamp,accx,accy,accz,gpsLongitude,gpsLatitude,gpsAltitude,gpsSpeed,gpsBearing,light,deviceID,frequency) values (%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s)" % ( s["time"], s["accx"], s["accy"], s["accz"], s["longitude"], s["latitude"], s["altitude"], s["speed"], s["bearing"], s["lightx"], s["deviceID"], s["frequency"]) db.execute(insert_data)
def evsensor(): # print('called') sys.path.append("..") import util try: # process command line arguments debug = False args = arg_parse() if args.debug: debug = False # reset bluetooth functionality try: if debug: print "-- reseting bluetooth device" ble.reset_hci() if debug: print "-- reseting bluetooth device : success" except Exception as e: util.Logprint(4, "error enabling bluetooth device") # print "error enabling bluetooth device" # print str(e) sys.exit(1) # initialize bluetooth socket try: if debug: print "-- open bluetooth device" sock = ble.bluez.hci_open_dev(conf.BT_DEV_ID) if debug: print "-- ble thread started" except Exception as e: util.Logprint(4, "error accessing bluetooth device") # print "error accessing bluetooth device: ", str(conf.BT_DEV_ID) # print str(e) sys.exit(1) # set ble scan parameters try: if debug: print "-- set ble scan parameters" ble.hci_le_set_scan_parameters(sock) if debug: print "-- set ble scan parameters : success" except Exception as e: util.Logprint(4, "failed to set scan parameter!!") # print "failed to set scan parameter!!" # print str(e) sys.exit(1) # start ble scan try: if debug: print "-- enable ble scan" ble.hci_le_enable_scan(sock) if debug: print "-- ble scan started" except Exception as e: util.Logprint(4, "failed to activate scan!!") # print "failed to activate scan!!" # print str(e) sys.exit(1) global flag_scanning_started flag_scanning_started = True util.Logprint(1, "envsensor_observer : complete initialization") # print ("envsensor_observer : complete initialization") # print "" # preserve old filter setting old_filter = sock.getsockopt(ble.bluez.SOL_HCI, ble.bluez.HCI_FILTER, 14) # perform a device inquiry on bluetooth device #0 # The inquiry should last 8 * 1.28 = 10.24 seconds # before the inquiry is performed, bluez should flush its cache of # previously discovered devices flt = ble.bluez.hci_filter_new() ble.bluez.hci_filter_all_events(flt) ble.bluez.hci_filter_set_ptype(flt, ble.bluez.HCI_EVENT_PKT) sock.setsockopt(ble.bluez.SOL_HCI, ble.bluez.HCI_FILTER, flt) # activate timer for sensor status evaluation with open('/home/nvidia/Horus/config.cnf') as f: cnf = json.load(f) timer = threading.Timer( int(cnf['check_sensor_state_interval_seconds']), eval_sensor_state) timer.setDaemon(True) timer.start() global flag_update_sensor_status while True: # parse ble event parse_events(sock) if flag_update_sensor_status: # print_sensor_state() flag_update_sensor_status = False except Exception as e: # print "Exception: " + str(e) import traceback traceback.print_exc() sys.exit(1) finally: if flag_scanning_started: # restore old filter setting sock.setsockopt(ble.bluez.SOL_HCI, ble.bluez.HCI_FILTER, old_filter) ble.hci_le_disable_scan(sock)