def GENERAL(arg): try: m.logger.debug(str(arg)) Phrase({'TYPE': arg[0]}) # speak phrase if nothing else. except Exception as e: m.logger.error(str(e)) MainException()
def RUTIME(arg): try: m.logger.debug(str(arg)) if arg[0] == '': arg[0] = 'HM' Phrase({'TYPE': 'RUTIME_' + arg[0]}) except: MainException()
def command(): """get and run command by GET method" "/cmnd?RUN={module}&args={args}" "args=HR;AA --- etc." curl localhost:8083/cmnd?RUN=TIME\&args=HM curl localhost:8083/cmnd?RUN=TIME curl localhost:8083/cmnd?RUN=TEMP\&args=IN curl localhost:8083/cmnd?RUN=WEATHER curl localhost:8083/cmnd?RUN=SPENDINGS curl localhost:8083/cmnd?RUN=ALLEVENTSTODAY curl localhost:8083/cmnd?RUN=MORNING curl localhost:8083/cmnd?RUN=ESP\&args="6;color;green" curl localhost:8083/cmnd?RUN=ESP\&args="6;rf433;light;off" """ global p, m RUN, args = request.args.get('RUN'), request.args.get('args') m.logger.debug('PARAMS: ' + str(RUN) + ' : ' + str(args)) if RUN is None: m.logger.error('no module in RUN') return jsonify({'status': 'ERROR', 'message': 'no module in RUN'}) if RUN not in globals(): # trying phrase ok, message = GENERAL([RUN]) if ok: m.logger.info('API RUN : Phrase = {} : OK'.format(str(RUN))) return jsonify({ 'status': ok, 'message': 'Phrase = {}'.format(str(RUN)), 'text': message }) else: m.logger.error('API RUN = {}, module not loaded'.format(str(RUN))) return jsonify({ 'status': ok, 'message': 'RUN = {}, module not loaded'.format(str(RUN)), 'text': message }) else: # module loaded args = args.split(';') if args is not None else [] # must be array m.logger.info('API RUN : {}, args = {}'.format(RUN, str(args))) try: resp = globals()[RUN](args) return jsonify({ 'status': 'OK', 'message': resp, 'command': 'RUN : {}, args = {}'.format(RUN, str(args)) }) except Exception as e: m.logger.error(str(e)) MainException() return jsonify({'status': 'ERROR', 'message': str(e)})
def GENERAL(arg): try: m.logger.debug(str(arg)) return [True, Phrase({'TYPE': arg[0]})] # speak phrase if nothing else. except Exception as e: m.logger.error(str(e)) MainException() return [False, str(e)]
def PrintWeather(lcd): global print_weather try: w = WEATHER() if not w.timeout: lcd.PrintPos((1, 0), str(int(w.temp_out)).zfill(2) + '/' + str(int(w.temp_today)).zfill(2)) sleep(1) lcd.Print(str(w.forecast)[:14].ljust(14) + str(w.temp_in).ljust(2)) else: logger.error('timeout reading weather') print_weather = datetime.now() except Exception as e: logger.error('error in weather module : ' + str(e)) MainException()
def Event(args): module, p = args.split('_')[0], args.split('_')[1:] m.logger.info('module ' + module + ', args ' + str(p)) try: if len(args.split('_')) == 1 and module in globals(): # no arguments try: globals()[module](['']) except: m.logger.error('error in module ' + module) MainException() elif module in globals(): m.logger.info('module imported') globals()[module](p) else: m.logger.info('>>> to general') GENERAL([module]) except: m.logger.error('error in module ' + module + ' ' + str(sys.exc_info()))
def pa_reAuth(): global p, timer while True: try: PA_service() except: error = str(MainException()) # in case nothing returned if True in [ error.find(i) != -1 for i in [ 'PyiCloud2SARequiredError', 'PyiCloudAPIResponseError', 'Unauthorized' ] ]: while True: p.iCloudApi = iCloudConnect() if re_authenticate(p.iCloudApi): break # passing existing api / not authenticated sleep(30) # time between attempts else: logger.info('waiting 1 min and retrying...') if timer.reminders.Awake(): Speak('error in P. A. service') sleep(60)
PrintWeather(lcd) sleep(1) attempt = 1 except: # if connection to serail lost - it can be reassigned the port try: lcd = LCD() lost = True except Exception as e: attempt += 1 if attempt > 5: logger.fatal(str(e)) return logger.error('attempt' + str(attempt) + ' ' + str(e)) sleep(5) # sys.exit() if __name__ == '__main__': if '-nodaemon' in sys.argv: Start() else: with daemon.DaemonContext(files_preserve=[ logger.handlers[0].stream, ]): try: Start() except: MainException()
def PA_service(): global timer logger.info('PA service started') Speak('starting P.A. service') #esp = ESP() if p.icloud.do: p.iCloudApi = iCloudConnect() # keeping connected API for later EV = Events(iCloudCal(p.iCloudApi, datetime.datetime.today())) logger.info('iCAL scan ' + str(EV.inputs)) logger.info('EVENTS: ' + EV.log) logger.info('reminders at ' + ', '.join([ str(v).split(' ')[1].split('.')[0] for v in sorted(EV.reminders.keys()) ])) else: logger.info('no iCloud integration') p.last_scan = datetime.datetime.now() p.last_reminder = datetime.datetime.now() # start listining App port logger.info('starting app') threading.Thread(target=App).start() logger.info('starting pinging iPhone') iPhone = PING(4, 15) # 4 attempts with 15 sec gap items = OBJECT({ 'lamp': OBJECT({'status': False}), 'iPhone': OBJECT({'status': iPhone.Status()}) }) TW = Twilight() os.system('curl http://192.168.1.176/control/color/yellow') ping_pause_time = 5 # starting # ev_last = '' while True: now = datetime.datetime.now() # rereading SUN times if timer.CheckTime(0, 0): if timer.Sun.CheckDelay(): TW.today() logger.info('Sun times reset : {}'.format( str(TW.twilight_times))) os.system('curl http://192.168.1.176/control/color/off') # calendar if p.icloud.do: if timer.iCloud_cal.CheckDelay(): #rescan calendar try: EV = Events( iCloudCal(p.iCloudApi, datetime.datetime.today())) #if ev_last != EV.log: logger.info('EVENTS: ' + EV.log) logger.info('reminders at ' + ', '.join([ str(v).split(' ')[1].split('.')[0] for v in sorted(EV.reminders.keys()) ])) # ev_last = EV.log except Exception as e: logger.error(str(e)) # ERROR - Service Unavailable (503) # ERROR - statusCode = Throttled, unknown error, http status code = 520 if str(e).find('503') != -1 or str(e).find( '520') != -1 or str(e).find( 'Please wait a few minutes then try again' ) != -1: logger.error(str(e)) logger.error( 'Throttling / service not available > holding for 1 h' ) timer.iCloud_cal.last_scan = datetime.datetime.now( ) + datetime.timedelta(minutes=60) timer.iCloud_photo.last_scan = datetime.datetime.now( ) + datetime.timedelta(minutes=60) continue logger.error('error in iCloud - re-connecting...,') try: p.iCloudApi = iCloudConnect() logger.info(' - DONE. Checking EV...,') EV = Events( iCloudCal(p.iCloudApi, datetime.datetime.today())) logger.info(' - DONE') except: logger.error(' all bad :( skipping till next update') sleep(60) continue #rescan photos if p.icloud_photo.do: if timer.iCloud_photo.CheckDelay(): try: logger.debug('rescanning Photo Library') get_Photos(p.iCloudApi) # rest args default except Exception as e: logger.error(str(e)) if timer.reminders.Awake(): Speak( "There is error with syncronizing photographs. I am trying to remounting the drive" ) MainException() os.system( "sudo mount -t cifs //shrimp.local/ssd_shrimp/ /mnt/shrimp_ssd/ -o vers=1.0,username=pi,password=impervious" ) try: get_Photos(p.iCloudApi) # rest args default if timer.reminders.Awake(): Speak("looks like remounting drive worked.") except: if timer.reminders.Awake(): Speak("no luck. check yourself, Alex") if p.icloud.do: if timer.reminders.Awake(): if timer.reminders.CheckDelay( ): # don't repereat witin 1 min and dont speak at night if datetime.datetime( now.year, now.month, now.day, now.hour, now.minute ) in EV.reminders.keys( ): # and DistanceToPoint(p.iCloudApi, 'HOME') <=200: next_event = [ v for k, v in EV.reminders.items() if k == datetime.datetime(now.year, now.month, now.day, now.hour, now.minute) ][0] min_left = int(([ k for k, v in EV.starts.items() if v == next_event ][0] - now).seconds / 60) + 1 reminder = 'reminder_' + next_event.replace( ' ', '-') + '_' + str(min_left) logger.info(reminder) REMINDER( reminder.replace('reminder_', '').split('_') ) # for backwards compatibility #!!! remove later if timer.iPhone.Awake(): if timer.iPhone.CheckDelay(ping_pause_time): ping_pause_time = iPhonePING(TW, items, iPhone) sleep(5) # increments logger.debug(str(now))