def updateDIYs(user_id, dev_id): if user_id == 'empty' or dev_id == 'empty': LOG.writeLn("user_id or dev_id is empty") exit() phpFileNm = "call_from_DIYs.php" fileName = COM.gJsonDir + 'device.json' f = open(fileName, 'r') data = f.read() print(data) f.close() url = 'https://frogmon.synology.me/svr_api/' url = '%s%s' % (url, phpFileNm) r = requests.post(url, data={ 'user_id': user_id, 'product_id': dev_id, 'status_json': data }) print(r.url) if (XMLPaser.getHeader(r.content) != 0): LOG.writeLn("sendModuleStat send Error ") else: actionJson = XMLPaser.decodeAction(r.content) if actionJson == '': print('no Actions') else: GLOB.saveJsonData(COM.gJsonDir + 'action.json', actionJson)
def confUpdate(self): self.sleep_period = int( GLOB.readConfig(configFileNM, 'FLOWERCARE', 'period', '300')) self.miflora_cache_timeout = self.sleep_period - 1 self.used_adapter = GLOB.readConfig(configFileNM, 'FLOWERCARE', 'adapter', 'hci0') self.reporting_mode = 'json' self.daemon_enabled = True self.user_id = GLOB.readConfig(configFileNM, 'SETUP', 'user_id', '0') self.device_id = GLOB.readConfig(configFileNM, 'AGENT', 'id', '0') self.default_base_topic = 'miflora' self.local_id = GLOB.readConfig(configFileNM, 'WEATHER', 'location0', '') # Check configuration if self.reporting_mode not in [ 'mqtt-json', 'mqtt-homie', 'json', 'mqtt-smarthome', 'homeassistant-mqtt', 'thingsboard-json', 'wirenboard-mqtt' ]: LOG.writeLn( 'Configuration parameter reporting_mode set to an invalid value ' ) sys.exit(1) if (self.device_id == '0' or self.user_id == '0'): LOG.writeLn('setup.ini file load error') sys.exit(1) #LOG.writeLn('Configuration accepted') print('** USER = %s' % self.user_id) print('** PRODUCT = %s' % self.device_id) print('** interval = %d' % self.sleep_period) print('** location = %s' % self.local_id) print('--------------------------------------------------') print('')
def encodeStatJson(self, fileNM, data): rc = -1 try: dict = json.loads('{}') dict['DEV_ID'] = data[0] dict['MODE'] = data[1] dict['ALARM'] = data[2] dict['TEMP'] = data[3] dict['HUMI'] = data[4] dict['MOIST'] = data[5] dict['COND'] = data[6] dict['CDS'] = data[7] dict['BATTERY'] = data[8] dict['REMOTE'] = data[9] dict['LIGHT'] = data[10] dict['PUMP'] = data[11] dict['FAN'] = data[12] dict['HEATER'] = data[13] dict['LASTUPDT'] = data[14] dict['TEAMVIEWER'] = data[15] dict['LOCAL_IP'] = GLOB.get_ip_address() print(json.dumps(dict, ensure_ascii=False, indent="\t")) #os.remove(fileNM) with open(fileNM, 'w', encoding='utf-8') as make_file: json.dump(dict, make_file, ensure_ascii=False, indent="\t") print("out values [%s,%s,%s,%s,%s]" % (data[9], data[10], data[11], data[12], data[13])) rc = 0 except Exception as e: LOG.writeLn("[ERROR]: %s" % e) return rc
def chkSensor(self): for [name, mac] in GLOB.itemConfig(configFileNM, 'DEVICE'): if not GLOB.isMacAddress(mac): LOG.writeLn( 'The MAC address "{}" seems to be in the wrong format. Please check your configuration' ) sys.exit(1) if '@' in name: name_pretty, location_pretty = name.split('@') else: name_pretty, location_pretty = name, '' name_clean = GLOB.clean_identifier(name_pretty) location_clean = GLOB.clean_identifier(location_pretty) flora = dict() print('Adding sensor to device list and testing connection ...') print('Name: "{}"'.format(name_pretty)) #print_line('Attempting initial connection to Mi Flora sensor "{}" ({})'.format(name_pretty, mac), console=False, sd_notify=True) flora_poller = MiFloraPoller( mac=mac, backend=GatttoolBackend, cache_timeout=self.miflora_cache_timeout, retries=3, adapter=self.used_adapter) flora['poller'] = flora_poller flora['name_pretty'] = name_pretty flora['mac'] = flora_poller._mac flora['refresh'] = self.sleep_period flora['location_clean'] = location_clean flora['location_pretty'] = location_pretty flora['stats'] = {"count": 0, "success": 0, "failure": 0} try: flora_poller.fill_cache() flora_poller.parameter_value(MI_LIGHT) flora['firmware'] = flora_poller.firmware_version() except (IOError, BluetoothBackendException): LOG.writeLn( 'Initial connection to Mi Flora sensor "{}" ({}) failed.') else: print('Internal name: "{}"'.format(name_clean)) print('Device name: "{}"'.format(flora_poller.name())) print('MAC address: {}'.format(flora_poller._mac)) print('Firmware: {}'.format(flora_poller.firmware_version())) #LOG.writeLn('Initial connection to Mi Flora sensor "{}" ({}) successful') print() self.flores[name_clean] = flora return self.flores
def copyFileList(srcPath, destPath): print("copyFileList (%s=>%s)" % (srcPath, destPath)) if not GLOB.folderExitst(srcPath): return False try: files = os.listdir(destPath) print(files) for afile in files: os.remove(destPath + afile) files = os.listdir(srcPath) for afile in files: shutil.copy(srcPath + afile, destPath + afile) return True except Exception as e: LOG.writeLn("[face_copy ERROR]: %s" % e) return False
def makeJson(): data = {} data['DEV_ID'] = mProduct_id data['VERSION'] = mVersion data['INTERVAL'] = mInterval_sec data['RES_X'] = mResolution_x data['RES_Y'] = mResolution_y data['ROTATION'] = mRotation data['START_TIME'] = mStart_time data['END_TIME'] = mEnd_time data['DAY_COUNT'] = mCount data['LOCAL_IP'] = GLOB.get_ip_address() LOG.writeLn('json file save:%s' % COM.gJsonDir + 'device.json') with open(COM.gJsonDir + 'device.json', 'w', encoding='utf-8') as make_file: json.dump(data, make_file, indent="\t")
def jsonAppend(fileNM, name): rc = -1 try: if GLOB.fileExist(fileNM): with open(fileNM, 'a', encoding='utf-8') as f: data = ', {"DOOR_OPEN_TIME" : "%s", "NAME" : "%s" }' % ( COM.gstrYMDHMS, name) f.write(data) else: with open(fileNM, 'w', encoding='utf-8') as f: data = '{"DOOR_OPEN_TIME" : "%s", "NAME" : "%s" }' % ( COM.gstrYMDHMS, name) f.write(data) rc = 0 except Exception as e: LOG.writeLn("[jsonAppend ERROR]: %s" % e) return rc
def callWeather(local_id): if local_id == '' or local_id == 'empty': LOG.writeLn("[callWeather] local_id is empty") exit() phpFileNm = "get_weather_info.php" url = 'http://frogmon.synology.me/svr_api/' url = "%s%s?position=%s" % (url, phpFileNm, local_id) try: r = requests.get(url=url, timeout=3) #print(r.url) #print('--------------------') #s = r.content.decode("UTF-8").strip() #print(s) return XMLPaser.decodeWeather(r.content) except: LOG.writeLn("[callWeather] Error : %s" % r.url)
def on_message(client, userdata, msg): strJson = msg.payload.decode() #print(msg.topic+" "+str(msg.payload)) #토픽과 메세지를 출력한다. LOG.writeLn("[MQTT] "+ msg.topic+" "+ strJson) #토픽과 메세지를 출력한다. try: if GLOB.saveJsonData(COM.gJsonDir+"action.json", strJson) == 0: remote = '0' grp1 = GLOB.getJsonVal(strJson, 'light', '99') if (grp1 != '99') : GLOB.writeConfig(controlFileNM, 'CONTROL', 'light', grp1) remote = '1' grp2 = GLOB.getJsonVal(strJson, 'heater', '99') if (grp2 != '99') : GLOB.writeConfig(controlFileNM, 'CONTROL', 'heater', grp2) remote = '1' grp3 = GLOB.getJsonVal(strJson, 'fan', '99') if (grp3 != '99') : GLOB.writeConfig(controlFileNM, 'CONTROL', 'fan', grp3) remote = '1' grp4 = GLOB.getJsonVal(strJson, 'pump', '99') if (grp4 != '99') : GLOB.writeConfig(controlFileNM, 'CONTROL', 'pump', grp4) remote = '1' active = GLOB.getJsonVal(strJson, 'active', '99') if (active != '99') : remote = active GLOB.writeConfig(controlFileNM, 'CONTROL', 'active', remote) #print("grp data %s %s" % (grp1, grp2)) if GLOB.appendWATERsControlInfo(COM.gJsonDir+"device.json", GLOB.readConfig(controlFileNM, 'CONTROL', 'active', '0') , GLOB.readConfig(controlFileNM, 'CONTROL', 'light', '0') , GLOB.readConfig(controlFileNM, 'CONTROL', 'pump', '0') , GLOB.readConfig(controlFileNM, 'CONTROL', 'fan', '0') , GLOB.readConfig(controlFileNM, 'CONTROL', 'heater', '0') ) == 0 : REQUEST.updateDIYs(user_id, dev_id) except Exception as e : LOG.writeLn("[MQTT] : error : %s" % e)
def callPollution(local_id): if local_id == '' or local_id == 'empty': LOG.writeLn("[callPollution] local_id is empty") exit() phpFileNm = "seindex.php" url = 'http://58.229.176.179/' url = "%s%s?position=%s" % (url, phpFileNm, local_id) try: r = requests.get(url=url, timeout=3) #print(r.url) #print('--------------------') s = r.content.decode("UTF-8") s = s.replace('<h1>', '') s = s.replace('</h1>', '') s = s.replace(' ', '') rc = s.split(',') return rc except: LOG.writeLn("[callPollution] Error : %s" % r.url)
def on_message(client, userdata, msg): strJson = msg.payload.decode() LOG.writeLn("[MQTT] " + msg.topic + " " + strJson) #토픽과 메세지를 출력한다. try: if GLOB.saveJsonData(COM.gJsonDir + "action.json", strJson) == 0: remote = '0' grp1 = GLOB.getJsonVal(strJson, 'interval', '0') if (grp1 != '0'): GLOB.writeConfig(configFileNM, 'SETUP', 'interval', grp1) remote = '1' grp2 = GLOB.getJsonVal(strJson, 'resolution_x', '0') if (grp2 != '0'): GLOB.writeConfig(configFileNM, 'SETUP', 'resolution_x', grp2) remote = '1' grp3 = GLOB.getJsonVal(strJson, 'resolution_y', '0') if (grp3 != '0'): GLOB.writeConfig(configFileNM, 'SETUP', 'resolution_y', grp3) remote = '1' grp4 = GLOB.getJsonVal(strJson, 'rotation', '99') if (grp4 != '99'): GLOB.writeConfig(configFileNM, 'SETUP', 'rotation', grp4) remote = '1' grp5 = GLOB.getJsonVal(strJson, 'start_time', '99') if (grp5 != '99'): GLOB.writeConfig(configFileNM, 'SETUP', 'start_time', grp5) remote = '1' grp6 = GLOB.getJsonVal(strJson, 'end_time', '99') if (grp6 != '99'): GLOB.writeConfig(configFileNM, 'SETUP', 'end_time', grp6) remote = '1' print('grps = %s %s %s %s %s %s [%s]' % (grp1, grp2, grp3, grp4, grp5, grp6, remote)) if remote == '1': if GLOB.appendTIMELAPsControlInfo( COM.gJsonDir + "device.json", GLOB.readConfig(configFileNM, 'SETUP', 'interval', '0'), GLOB.readConfig(configFileNM, 'SETUP', 'resolution_x', '0'), GLOB.readConfig(configFileNM, 'SETUP', 'resolution_y', '0'), GLOB.readConfig(configFileNM, 'SETUP', 'rotation', '0'), GLOB.readConfig(configFileNM, 'SETUP', 'start_time', '0'), GLOB.readConfig(configFileNM, 'SETUP', 'end_time', '0')) == 0: REQUEST.updateDIYs(user_id, dev_id) LOG.writeLn("[MQTT] Command recive and reboot in 3 sec") time.sleep(3) GLOB.run_command("sudo reboot") except Exception as e: LOG.writeLn("[MQTT] : error : %s" % e)
def on_connect(client, userdata, flags, rc): LOG.writeLn("[MQTT] Connected with result code "+str(rc)) #client.subscribe("$SYS/#") client.subscribe("%s" % mSub_nm) #구독 "nodemcu"
if GLOB.appendWATERsControlInfo(COM.gJsonDir+"device.json", GLOB.readConfig(controlFileNM, 'CONTROL', 'active', '0') , GLOB.readConfig(controlFileNM, 'CONTROL', 'light', '0') , GLOB.readConfig(controlFileNM, 'CONTROL', 'pump', '0') , GLOB.readConfig(controlFileNM, 'CONTROL', 'fan', '0') , GLOB.readConfig(controlFileNM, 'CONTROL', 'heater', '0') ) == 0 : REQUEST.updateDIYs(user_id, dev_id) except Exception as e : LOG.writeLn("[MQTT] : error : %s" % e) print('') print('--------------------------------------------------') print('** Welcome to FROGMON corp.') print("** Let's make it together") print("** ") print('** USER = %s' % user_id) print('** PRODUCT = %s' % dev_id) print('** CHNNEL_ID = %s' % mSub_nm) print('--------------------------------------------------') print('') client = mqtt.Client() #client 오브젝트 생성 client.on_connect = on_connect #콜백설정 client.on_message = on_message #콜백설정 try: client.connect(mSvr_addr, int(mSvr_port), 60) #라즈베리파이3 MQTT 브로커에 연결 client.loop_forever() except Exception as e : LOG.writeLn("[MQTT] : error : %s" % e)
print('** NOW times = %s' % COM.gstrYMDHMS) print('** INTERVAL = %s' % mInterval_sec) print('** RES_X = %s' % mResolution_x) print('** RES_Y = %s' % mResolution_y) print('** ROTATION = %s' % mRotation) print('** START_TIME = %s' % mStart_time) print('** END_TIME = %s' % mEnd_time) print('--------------------------------------------------') print('') # pi camera Setting camera = PiCamera() camera.resolution = (mResolution_x, mResolution_y) camera.rotation = mRotation LOG.writeLn("[timeLapse] process run") # Main Process while True: try: GLOB.setUpdateTime() GLOB.appendTIMELAPsControlInfo(COM.gJsonDir + "device.json", mInterval_sec, mResolution_x, mResolution_y, mRotation, mStart_time, mEnd_time) REQUEST.updateDIYs(mUser_id, mProduct_id) if (int(COM.gHH) >= mStart_time) and (int(COM.gHH) <= mEnd_time): camera.start_preview() imgFileNm = COM.gHomeDir + 'pictures/pic_%s.jpg' % COM.gstrYMDHMS # make picture camera.capture(imgFileNm) camera.stop_preview()
from frogmon.uCommon import COM from frogmon.uLogger import LOG from frogmon.uGlobal import GLOB GLOB.directoryInit('pi', "DOORs") metrixImg = COM.gHomeDir + "metrix.png" camera = PiCamera() camera.resolution = (320, 180) camera.rotation = 180 print('') print('--------------------------------------------------') print('** Welcome to FROGMON corp.') print("** Let's make it together") print("** ") print('** Image File = %s' % metrixImg) print('--------------------------------------------------') print('') LOG.writeLn("[doorImage] process run") while True: try: camera.start_preview() sleep(0.5) camera.capture(metrixImg) #LOG.writeLn("[doorImage] get picture") camera.stop_preview() except Exception as e: LOG.writeLn("[doorImage] Error : %s" % e)
def atOnce(self): self.chkSensor() GLOB.setUpdateTime() self.confUpdate() for [flora_name, flora] in self.flores.items(): data = dict() attempts = 2 flora['poller']._cache = None flora['poller']._last_read = None flora['stats']['count'] = flora['stats']['count'] + 1 #print_line('Retrieving data from sensor "{}" ...'.format(flora['name_pretty'])) while attempts != 0 and not flora['poller']._cache: try: flora['poller'].fill_cache() flora['poller'].parameter_value(MI_LIGHT) except (IOError, BluetoothBackendException): attempts = attempts - 1 if attempts > 0: LOG.writeLn('Retrying ...') flora['poller']._cache = None flora['poller']._last_read = None if not flora['poller']._cache: flora['stats']['failure'] = flora['stats']['failure'] + 1 LOG.writeLn( 'Failed to retrieve data from Mi Flora sensor "{}" ({}), success rate: {:.0%}' .format( flora['name_pretty'], flora['mac'], flora['stats']['success'] / flora['stats']['count'])) print() continue else: flora['stats']['success'] = flora['stats']['success'] + 1 for param, _ in mParameters.items(): data[param] = flora['poller'].parameter_value(param) rc = -1 try: data['timestamp'] = COM.gstrDATE data['name'] = flora_name data['name_pretty'] = flora['name_pretty'] data['mac'] = flora['mac'] data['firmware'] = flora['firmware'] #print('Data for "{}": {}'.format(flora_name, json.dumps(data))) with open(COM.gJsonDir + flora_name + '.json', 'w', encoding="utf-8") as make_file: json.dump(data, make_file, ensure_ascii=False, indent="\t") #to make device.json file datas = [] datas.append(self.device_id) datas.append(GLOB.readConfig(configFileNM, 'SETUP', 'mod', '')) datas.append( GLOB.readConfig(configFileNM, 'AGENT', 'alarm', '0')) datas.append(str(data['temperature'])) datas.append('0') datas.append(str(data['moisture'])) datas.append(str(data['conductivity'])) datas.append(str(data['light'])) datas.append(str(data['battery'])) datas.append( GLOB.readConfig(controlFileNM, 'CONTROL', 'active', '0')) # active datas.append( GLOB.readConfig(controlFileNM, 'CONTROL', 'light', '0')) # LED 조명 datas.append( GLOB.readConfig(controlFileNM, 'CONTROL', 'pump', '0')) # 워터펌프 datas.append( GLOB.readConfig(controlFileNM, 'CONTROL', 'fan', '0')) # 팬 datas.append( GLOB.readConfig(controlFileNM, 'CONTROL', 'heater', '0')) # 히터 datas.append(COM.gstrYMDHMS) datas.append(GLOB.loadTeamviewerID()) rc = self.encodeStatJson(COM.gJsonDir + 'device.json', datas) if rc == 0: LOG.writeLn( '%s [%s] %s %s %s %s %s' % (data['name'], data['battery'], data['temperature'], data['moisture'], data['light'], data['conductivity'], data['mac'])) except Exception as e: LOG.writeLn("[ERROR][FLOWERCARE] : %s" % e) if rc == 0: if GLOB.appendWATERsControlInfo( COM.gJsonDir + "device.json", GLOB.readConfig(controlFileNM, 'CONTROL', 'active', '0'), GLOB.readConfig(controlFileNM, 'CONTROL', 'light', '0'), GLOB.readConfig(controlFileNM, 'CONTROL', 'pump', '0'), GLOB.readConfig(controlFileNM, 'CONTROL', 'fan', '0'), GLOB.readConfig(controlFileNM, 'CONTROL', 'heater', '0')) == 0: REQUEST.updateDIYs(self.user_id, self.device_id)
print('') print('--------------------------------------------------') print('** Welcome to FROGMON corp.') print("** Let's make it together") print("** ") print("** face path check : %s" % path) print("** faceLog Path check : %s" % faceLogPath) print("** metrixImg path check : %s" % metrixImg) print(file_list) print('--------------------------------------------------') print('') timer = 0 LOG.writeLn("[doorDetector] process run") while True: time.sleep(0.1) if GLOB.fileExist(metrixImg): timer = timer + 1 if timer > 600: LOG.writeLn("[doorDetector] Alive Check (%d)" % mLstImgFileSize) timer = 0 curntImgFileSize = os.path.getsize(metrixImg) if (curntImgFileSize > 0) and (mLstImgFileSize != curntImgFileSize): mLstImgFileSize = curntImgFileSize GLOB.setUpdateTime() GPIO.output(led_pin, 0) try: detectFace = 0
STAT_FAN = 0 STAT_HEATER = 0 cntLoadError = 0 def clearControlFile(): GLOB.writeConfig(controlFileNM, 'CONTROL', 'light' , '0') GLOB.writeConfig(controlFileNM, 'CONTROL', 'pump' , '0') GLOB.writeConfig(controlFileNM, 'CONTROL', 'fan' , '0') GLOB.writeConfig(controlFileNM, 'CONTROL', 'heater', '0') try: GPIO.output(LIGHT, GPIO.HIGH) time.sleep(1) LOG.writeLn("[CONTROL] : h/w Control Start %s" % GLOB.readConfig(configFileNM, 'AGENT', 'id', '0')) while (True): time.sleep(1) try: STAT_LIGHT = int(GLOB.readConfig(controlFileNM, 'CONTROL', 'light' , '99')) #0:ON/OFF, 1: LED 켜기, 0: LED 끄기 STAT_PUMP = int(GLOB.readConfig(controlFileNM, 'CONTROL', 'pump' , '99')) #0:ON/OFF, 1: PUMP 켜기, 0: PUMP 끄기 STAT_FAN = int(GLOB.readConfig(controlFileNM, 'CONTROL', 'fan' , '99')) #0:ON/OFF, 1: FAN 켜기, 0: FAN 끄기 STAT_HEATER = int(GLOB.readConfig(controlFileNM, 'CONTROL', 'heater', '99')) #0:ON/OFF, 1: HEATER 켜기, 0: HEATER 끄기 if (max(STAT_LIGHT, STAT_PUMP, STAT_FAN, STAT_HEATER) == 99): LOG.writeLn("[CONTROL] : config load error then continues") cntLoadError = cntLoadError + 1 if (cntLoadError > 10) : clearControlFile()
start_str = "UUID=\"" example_uuid = "6784-3407" uuid_start = line.index(start_str) + len(start_str) uuid_end = uuid_start + len(example_uuid) return line[uuid_start:uuid_end] checkDir = 0 while True: time.sleep(1) try: output = run_command("sudo blkid | grep -v boot | grep -v mm") if len(output) > 0: # ['/dev/sda1: LABEL="KINGSTON" UUID="6784-3407" TYPE="vfat" PARTUUID="459720e1-01"'] for usb_device in output: if not GLOB.folderExitst(mUsbDir): run_command("sudo mkdir %s" % mUsbDir) command = "sudo mount --uuid %s %s -o iocharset=utf8" % ( uuid_from_line(usb_device), mUsbDir) print(command) run_command(command) break if copyFileList("/mnt/usb_stick/faces/", mFaceDir): LOG.writeLn("[face_copy]: Sucess!!") time.sleep(5) run_command("sudo reboot") except Exception as e: print("usb not detected or faces not found: %s" % e)