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 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 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 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 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)
exit() import sys, os import time import datetime import glob import subprocess import shutil from frogmon.uConfig import CONF from frogmon.uLogger import LOG from frogmon.uCommon import COM from frogmon.uGlobal import GLOB # 프로그램 시작 GLOB.directoryInit(GLOB.whoami(), "DOORs") configFileNM = COM.gHomeDir + COM.gSetupFile controlFileNM = COM.gHomeDir + COM.gControlFile user_id = GLOB.readConfig(configFileNM, 'SETUP', 'user_id', '0') dev_id = GLOB.readConfig(configFileNM, 'AGENT', 'id', '0') # 함수 정의 mWhoami = GLOB.whoami() mUsbDir = "/mnt/usb_stick" mFaceDir = COM.gHomeDir + "faces/" GLOB.folderMaker(mFaceDir) print("whoami = %s" % mWhoami)
# uLogger.py #-*- coding:utf-8 -*- import sys import logging import logging.handlers import sdnotify from frogmon.uCommon import COM from frogmon.uGlobal import GLOB from unidecode import unidecode from colorama import Fore, Back, Style GLOB.folderMaker(COM.gLogDir) #logger instance create logger = logging.getLogger(__name__) #logger formatter create formatter = logging.Formatter('[%(asctime)s] %(message)s') #handler create (stream, file) streamHandler = logging.StreamHandler() fileHandler = logging.FileHandler(COM.gLogDir + 'syslog_%s.log' % COM.gstrYMD) #logger instance에 fomatter create streamHandler.setFormatter(formatter) fileHandler.setFormatter(formatter) #logger instance에 handler create logger.addHandler(streamHandler) logger.addHandler(fileHandler) #Log Level Setting
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()
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") # init configFileNM = COM.gHomeDir + COM.gSetupFile mUser_id = GLOB.readConfig(configFileNM, 'SETUP', 'user_id', 'empty') mProduct_id = GLOB.readConfig(configFileNM, 'SETUP', 'product_id', 'empty') mVersion = GLOB.readConfig(configFileNM, 'SETUP', 'version', 'ver 1.0') mInterval_sec = int(GLOB.readConfig(configFileNM, 'SETUP', 'interval', '600')) mResolution_x = int( GLOB.readConfig(configFileNM, 'SETUP', 'resolution_x', '640')) mResolution_y = int( GLOB.readConfig(configFileNM, 'SETUP', 'resolution_y', '480')) mRotation = int(GLOB.readConfig(configFileNM, 'SETUP', 'rotation', '0')) mStart_time = int(GLOB.readConfig(configFileNM, 'SETUP', 'start_time', '0')) mEnd_time = int(GLOB.readConfig(configFileNM, 'SETUP', 'end_time', '23')) mCount = 0 GLOB.setUpdateTime() makeJson()
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("another process running!") exit() #프로그램 시작 import paho.mqtt.client as mqtt from frogmon.uCommon import COM from frogmon.uGlobal import GLOB from frogmon.uRequest import REQUEST from frogmon.uLogger import LOG #from frogmon.ulogger import LOG configFileNM = COM.gHomeDir+COM.gSetupFile controlFileNM = COM.gHomeDir+COM.gControlFile mSvr_addr = GLOB.readConfig(configFileNM, 'MQTT', 'host_addr', 'frogmon.synology.me') mSvr_port = GLOB.readConfig(configFileNM, 'MQTT', 'host_port', '8359') user_id = GLOB.readConfig(configFileNM, 'SETUP', 'user_id', '0') dev_id = GLOB.readConfig(configFileNM, 'AGENT', 'id', '0') mSub_nm = "DIYs/%s/%s" % (user_id, dev_id) #mSub_nm = "%s" % (user_id) #서버로부터 CONNTACK 응답을 받을 때 호출되는 콜백 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" #서버로부터 publish message를 받을 때 호출되는 콜백
# 중복 실행 방지 from tendo import singleton try: me = singleton.SingleInstance() except: print("another process running!") exit() from picamera import PiCamera from time import sleep 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('')
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)
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 # 프로그램 시작 GLOB.directoryInit('pi', "DOORs") path = COM.gHomeDir + "faces/" faceLogPath = COM.gHomeDir + "facelog/" metrixImg = COM.gHomeDir + "metrix.png" GLOB.folderMaker(path) GLOB.folderMaker(faceLogPath) GLOB.folderMaker(COM.gJsonDir) #from frogmon.ulogger import LOG configFileNM = COM.gHomeDir + COM.gSetupFile controlFileNM = COM.gHomeDir + COM.gControlFile user_id = GLOB.readConfig(configFileNM, 'SETUP', 'user_id', '0') dev_id = GLOB.readConfig(configFileNM, 'AGENT', 'id', '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')
def __init__(self, params): DefaultDelegate.__init__(self) #func is caled on notifications def handleNotification(self, cHandle, data): print("Notification : " + data.decode("utf-8")) ############################################# # Main starts here ############################################# scanner = Scanner().withDelegate(ScanDelegate()) devices = scanner.scan(10.0) cnt = 0 dev_str='' if not GLOB.iniSectionRemove(configFileNM, 'DEVICE'): print('ini Section Delete Error ') if not GLOB.iniSectionAdd(configFileNM, 'DEVICE'): print('ini Section Add Error ') for dev in devices: #print("Device %s (%s), RSSI=%d dB" % (dev.addr, dev.addrType, dev.rssi)) for (adtype, desc, value) in dev.getScanData(): # Check iBeacon UUID # 255 is manufacturer data (1 is Flags, 9 is Name) #print(" (AD Type=%d) %s = %s" % (adtype, desc, value)) if adtype is 2 and TARGET_UUID in value: cnt = cnt+1 target_dev = dev print("%d) Device %s (%s), RSSI=%d dB" % (cnt, dev.addr, dev.addrType, dev.rssi))