def process(self, db): with self.lock: s = self.state cs = self.cmdState srcType = setting.getSourceType() if srcType == 'nightscout': srcName = 'NightScout' else: srcName = 'DexcomShare' if self.displayCommand(cs): pass elif s == State.NoInternet: oled.drawState('No Internet') elif s == State.InvalidParam: oled.drawState(srcName + '\nInvalid Parameter') elif s == State.DisplayValue: r = db.getDisplayValues() if r['val'] > 0: color = 255 with self.lock: config = setting.getCurrent() if r['val'] < config['low_alarm'] or r['val'] > config[ 'high_alarm'] or ( r['elapsed'] / 60) > config['no_signal_alarm_min']: self.emergency = True if self.dimmed: color = 0 else: color = 255 self.dimmed = not self.dimmed else: self.emergency = False oled.draw(srcType, r['elapsed'], r['val'], r['direction'], r['delta'], color) else: oled.drawState('Unknown') self.restoreState() with self.lock: if self.shouldReboot: os.system("shutdown -r now") self.shouldReboot = False
def sendLatestEntry(db): try: r = db.getDisplayValues() if r['val'] == 0: return config = setting.getCurrent() bot = telegram.Bot(token=config['tg_bot_token']) updates = bot.getUpdates() chatId = config['tg_chat_id'] if len(updates) > 0: latest = updates[-1] if latest.channel_post != None: chatId = latest.channel_post.chat.id setting.setTGChatId(chatId) elif latest.message != None: chatId = latest.message.chat.id setting.setTGChatId(chatId) m = int(r['elapsed'] / 60) d = r['direction'] if d == 'DoubleUp': dir = '⏫' elif d == 'SingleUp': dir = '⬆️' elif d == 'FortyFiveUp': dir = '↗️' elif d == 'FortyFiveDown': dir = '↘️' elif d == 'SingleDown': dir = '⬇️' elif d == 'DoubleDown': dir = '⏬' else: dir = '➡️' msg = '{2} {3}\n\n지난 시간: {0} 분\n변동량: {1}'.format( m, r['delta'], r['val'], dir) bot.sendMessage(chat_id=chatId, text=msg) except Exception as e: pass
def req(path, query, method, data={}): config = setting.getCurrent() API_HOST = config['ns_addr'] url = API_HOST + path session = requests.Session() retry = Retry(connect=3, backoff_factor=0.5) adapter = HTTPAdapter(max_retries=retry) session.mount('http://', adapter) session.mount('https://', adapter) try: if method == 'GET': return session.get(url, headers=headers) else: return session.post(url, headers=headers, data=data) except: pass
def process(self): try: db = database.Database() db.createTable() lastSentTime = 0 while True: if _data.fetchData(_state, db): _state.process(db) curTime = int(time.time()) config = setting.getCurrent() v = db.getDisplayValues() if v['val'] > config['low_alarm'] and v['val'] < config[ 'high_alarm']: period = config['tg_normal_period'] else: period = config['tg_urgent_period'] if curTime - lastSentTime > period * 60: tgutil.sendLatestEntry(db) lastSentTime = curTime else: oled.drawState('No Internet') with self.cond: self.cond.wait() # reboot automatically in 3 hours.. #elapsed = time.time() - startTime #if elapsed > 3 * 60 * 60: # os.system('shutdown -r now') except Exception as e: logger.exception('process crashed. Error: %s', e)
def getEntries(state, db): config = setting.getCurrent() try: param = { 'applicationId': 'd89443d2-327c-4a6f-89e5-496bbb0317db', 'accountName': config['ds_user'], 'password': config['ds_pass'] } resp = req( '/ShareWebServices/Services/General/LoginPublisherAccountByName', '', 'POST', json.dumps(param)) if resp is None: return # logger.info(resp.text) query = 'sessionID={0}&minutes=1440&maxCount=1'.format(resp.text[1:-1]) resp = req( '/ShareWebServices/Services/Publisher/ReadPublisherLatestGlucoseValues', query, 'POST') if resp is None: return # logger.info(resp.text) parsed = json.loads(resp.text) for e in parsed: entry = convertEntry(e) db.insertEntry('dexcomshare', entry['date'], entry['sgv'], entry['direction']) state.setState(state.DisplayValue) except Exception as e: logger.exception('request crashed. Error: %s', e) if config['ds_user'] == '' or config['ds_pass'] == '': state.setState(state.InvalidParam)