def saveCsvLogToBlob(self, fileName): to_location_path = fileName account_name = s().Data["blob"]["account_name"] account_key = s().Data["blob"]["account_key"] container_name = s().Data["blob"]["container"] cloud_account = CloudStorageAccount(account_name=account_name, account_key=account_key) append_blob_service = cloud_account.create_append_blob_service() append_blob_service.create_container(container_name) append_blob_service.set_container_acl( container_name, public_access=PublicAccess.Container) if append_blob_service.exists(container_name, self.fileName): append_blob_service.append_blob_from_path( container_name, self.fileName, self.fileName, progress_callback=self.progress_callback_w) else: cloud_account.create_block_blob_service().create_blob_from_path( container_name, self.fileName, to_location_path, progress_callback=self.progress_callback_w)
def do_findingProtectedMeterAndReset(profile): #1 flag for current base url from setting print('\n' + profile['baseurl']+'\t:') files = os.listdir() for fl in files: if fl.endswith(".csv"): os.remove(fl) #2 get meter status, failure retry count retriesCount = s().Data['retry_count_strategy'] while retriesCount > 0: try: #3 loging in currentWebsiteSession = sparkWebsite(profile['baseurl'], profile['username'], profile['password']) meterStates = currentWebsiteSession.METER.getReadLatestState()['readings'] state = 'state' sn = 'serial' addr = 'address' iii = 0 telegramMessage = [] # finding meter for meterstate in meterStates: #filter by protect and totalizer SN if str(meterstate[state]).lower() == "protect" and str(meterstate['serial']).find('SM100E')<0: iii += 1 gb = meterstate['ground_name'] print('%s Reset for SN: %-25s ADDR: %-50s on GB: %-50s ' % (iii, meterstate[sn], meterstate[addr], gb)) # do reset if do_resetprotect(meterstate[sn]): currentLog = log(meterstate) fn = currentLog.saveLogToCSV(gb, datetime.datetime.utcnow()) telegramMessage.append('\n%s\t %s\t %s\t %s' % (meterstate[sn], meterstate['ground_name'], meterstate[addr], meterstate['heartbeat_end'] )) currentLog.saveCSVtoSQLDB(gb) currentLog.saveCsvLogToBlob(fn) if len(telegramMessage) > 0: messg = '%s (%s meter/s)\n %s' % ( profile['baseurl'], len(telegramMessage), str('\n').join(telegramMessage) ) tb().sendMessageToAllRegisteredChannel(messg) telegramMessage.clear() retriesCount = 0 except Exception as e : print(e) retriesCount -= 1
def _getAllChatId(self): oo = {} try: updates = bot.get_updates(timeout=timeoutVal) if len(updates) < 1: return s().Data['telegram_chat_ids'] for item in updates: try: if (item['channel_post']['chat']['id']): oo[item['channel_post']['chat']['id']] = None if (item['message']['chat']['id']): oo[item['message']['chat']['id']] = None except: pass except Exception as e: print('telegram_bot: _getAllChatId: %s' % (e)) return oo.keys()
if __name__ == "__main__": # Read setting sparkCloudCredentials = s().Data['credentials'] start_time = datetime.datetime.now() runs = True # while runs: # delay # while datetime.datetime.now() < start_time: # time.sleep(15) for profile in sparkCloudCredentials: #0 skip disabled config if profile.get('disabled', False): continue do_findingProtectedMeterAndReset(profile)
def saveCSVtoSQLDB(self, siteName): cnxn = pyodbc.connect(s().Data['mssql']) cursor = cnxn.cursor() query = ''' Insert into SPARKMETER_RESET_PROTECT_LOG ( [address] ,[current_avg] ,[current_max] ,[current_min] ,[energy] ,[frequency] ,[ground_name] ,[ground_serial] ,[heartbeat_end] ,[serial] ,[state] ,[true_power_inst] ,[uptime] ,[user_power_limit] ,[voltage_avg] ,[voltage_max] ,[voltage_min] ,[access_user] ,[reset_datetime_utc]) values( '%s', %s, %s, %s, %s, %s, '%s', '%s', '%s', '%s', '%s', %s, %s, %s, %s, %s, %s, '%s', '%s0' ) ''' % ( self.MeterInfo["address"], self.MeterInfo["current_avg"], self.MeterInfo["current_max"], self.MeterInfo["current_min"], self.MeterInfo["energy"], self.MeterInfo["frequency"], self.MeterInfo["ground_name"], self.MeterInfo["ground_serial"], self.MeterInfo["heartbeat_end"], self.MeterInfo["serial"], self.MeterInfo["state"], self.MeterInfo["true_power_inst"], self.MeterInfo["uptime"], self.MeterInfo["user_power_limit"], self.MeterInfo["voltage_avg"], self.MeterInfo["voltage_max"], self.MeterInfo["voltage_min"], s().Data['program_name'], datetime.datetime.utcnow().isoformat()) cursor.execute(query) cursor.commit()
from utils.setting import setting as s import telegram, json bot = telegram.Bot(token=s().Data['telegram_bot_token']) timeoutVal = 100 class telegram_bot(): def sendDocToAllRegisteredChannel(self, filePath): uploadedFile = {} for Id in self._getAllChatId(): if filePath in uploadedFile.keys(): filePath = uploadedFile[filePath] fileId = self._sendDocument(Id, filePath) uploadedFile[filePath] = fileId def sendMessageToAllRegisteredChannel(self, message): for Id in self._getAllChatId(): try: self._sendMessage(Id, message) except: pass def _sendDocument(self, chatId, filePath): doc = bot.send_document(chat_id=chatId, document=open(filePath, 'rb', timeout=timeoutVal)) return doc[1]['document']['file_id'] def _sendMessage(self, chatId, message):