Skip to content

Commit

Permalink
cleaned jsonsocket
Browse files Browse the repository at this point in the history
telegramBot bugfixes
backup stability
  • Loading branch information
Sebastian committed Jun 3, 2019
1 parent 1714232 commit fd2a1c6
Show file tree
Hide file tree
Showing 9 changed files with 280 additions and 239 deletions.
227 changes: 96 additions & 131 deletions RTOC/LoggerPlugin.py

Large diffs are not rendered by default.

3 changes: 2 additions & 1 deletion RTOC/RTLogger/RTLogger.py
Original file line number Diff line number Diff line change
Expand Up @@ -84,7 +84,8 @@
"token": "",
"eventlevel": 0,
"chat_ids": {},
"inlineMenu": False
"inlineMenu": False,
"onlyAdmin": False
},
"tcp": {
"active": False,
Expand Down
5 changes: 4 additions & 1 deletion RTOC/RTLogger/RT_data.py
Original file line number Diff line number Diff line change
Expand Up @@ -55,7 +55,10 @@ def __init__(self, t, hFunction, useqtimer=False):
self._thread = Timer(self._t, self._handle_function)

def _handle_function(self):
self._hFunction()
try:
self._hFunction()
except Exception:
logging.info('Backup failed')
if QTimer is not None and self._useqtimer:
self._thread = QTimer()
self._thread.timeout.connect(self._handle_function)
Expand Down
2 changes: 1 addition & 1 deletion RTOC/RTLogger/ScriptFunctions.py
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ def generateCode(self, s, condition=False):
s = self.generateTriggerCode(s)
s = self.printfunction() + s
s = self.createFunction(s)
s = "import math\nimport numpy as np\nimport sys\nimport scipy as sp\ntry:\n\timport RTOC.RTLogger.scriptLibrary as rtoc\nexcept (ImportError,SystemError):\n\tfrom .RTLogger import scriptLibrary as rtoc\n\n" + init + "\n"+s
s = "import math\nimport numpy as np\nimport sys\nimport os\nimport scipy as sp\ntry:\n\timport RTOC.RTLogger.scriptLibrary as rtoc\nexcept (ImportError,SystemError):\n\tfrom .RTLogger import scriptLibrary as rtoc\n\n" + init + "\n"+s
return s

def replacePluginParameters(self, s):
Expand Down
28 changes: 14 additions & 14 deletions RTOC/RTLogger/plugins/Generator.py
Original file line number Diff line number Diff line change
Expand Up @@ -59,57 +59,57 @@ def __square(self):
self.gen_start = time.time()
if time.time() - self.gen_start >= 0.5/self.gen_freq:
if self._lastValue != self.gen_level:
self.stream(self._lastValue, self._sname, units=[""])
self.stream(self._lastValue, self._sname, unit=[""])
self._lastValue = self.gen_level + self.offset
self.stream(self._lastValue, self._sname, units=[""])
self.stream(self._lastValue, self._sname, unit=[""])

else:
if self._lastValue != 0:
self.stream(self._lastValue, self._sname, units=[""])
self.stream(self._lastValue, self._sname, unit=[""])
self._lastValue = 0 + self.offset
self.stream(self._lastValue, self._sname, units=[""])
self.stream(self._lastValue, self._sname, unit=[""])

def __sawtooth(self):
if time.time() - self.gen_start >= 1/self.gen_freq:
self.gen_start = time.time()
if self._lastValue != 0:
#self._lastValue += self.gen_level*(self.gen_freq)/self.samplerate
self._lastValue = self.gen_level
self.stream(self._lastValue, self._sname, units=[""])
self.stream(self._lastValue, self._sname, unit=[""])
self._lastValue = 0 + self.offset
self.stream(self._lastValue, self._sname, units=[""])
self.stream(self._lastValue, self._sname, unit=[""])
else:
self._lastValue = self.gen_level * \
((time.time() - self.gen_start*self.gen_freq)) + self.offset
self.stream(self._lastValue, self._sname, units=[""])
self.stream(self._lastValue, self._sname, unit=[""])

def __sinus(self):
self._lastValue = self.gen_level * \
math.sin((time.time()*self.gen_freq)*(2*math.pi) + self.phase) + self.offset
self.stream(self._lastValue, self._sname, units=[""])
self.stream(self._lastValue, self._sname, unit=[""])

def __noise(self):
self._lastValue = random.uniform(0, self.gen_level) + self.offset
self.stream(self._lastValue, self._sname, units=[""])
self.stream(self._lastValue, self._sname, unit=[""])

def __ac(self):
if time.time() - self.gen_start >= 1/self.gen_freq:
self.gen_start = time.time()
if time.time() - self.gen_start >= 0.5/self.gen_freq:
if self._lastValue != self.gen_level:
self.stream(self._lastValue, self._sname, units=[""])
self.stream(self._lastValue, self._sname, unit=[""])
self._lastValue = self.gen_level + self.offset
self.stream(self._lastValue, self._sname, units=[""])
self.stream(self._lastValue, self._sname, unit=[""])

else:
if self._lastValue != 0:
self.stream(self._lastValue, self._sname, units=[""])
self.stream(self._lastValue, self._sname, unit=[""])
self._lastValue = -self.gen_level - self.offset
self.stream(self._lastValue, self._sname, units=[""])
self.stream(self._lastValue, self._sname, unit=[""])

def __dc(self):
self._lastValue = self.gen_level + self.offset
self.stream(self._lastValue, self._sname, units=[""])
self.stream(self._lastValue, self._sname, unit=[""])

def setCallbacks(self):
#self.connect(self.widget.samplerate, SIGNAL("valueChanged()",self.changeSamplerate))
Expand Down
79 changes: 54 additions & 25 deletions RTOC/RTLogger/telegramBot.py
Original file line number Diff line number Diff line change
Expand Up @@ -132,20 +132,23 @@ def sendEvent(self, message, devicename, signalname, priority):
ptext = ['_Information_', '*Warnung*', '*_Fehler_*'][priority]
message = translate('RTOC', '{} von {}.{}:\n{}').format(ptext, devicename, signalname, message)
for id in self.logger.config['telegram']['chat_ids'].keys():
self.check_chat_id(id)
if priority >= self.logger.config['telegram']['chat_ids'][id]['eventlevel']:
try:
self.bot.send_message(chat_id=int(id), text=message,
parse_mode=ParseMode.MARKDOWN)
except Exception:
self.bot.send_message(chat_id=int(id), text=message)
self.send_message(chat_id=int(id), text=message, delete=False)
# try:
# self.bot.send_message(chat_id=int(id), text=message,
# parse_mode=ParseMode.MARKDOWN)
# except Exception:
# self.bot.send_message(chat_id=int(id), text=message)

def send_message_to_all(self, message):
for id in self.logger.config['telegram']['chat_ids'].keys():
try:
self.bot.send_message(chat_id=int(id), text=message,
parse_mode=ParseMode.MARKDOWN)
except Exception:
self.bot.send_message(chat_id=int(id), text=message)
self.send_message(chat_id=int(id), text=message, delete=False)
# try:
# self.bot.send_message(chat_id=int(id), text=message,
# parse_mode=ParseMode.MARKDOWN)
# except Exception:
# self.bot.send_message(chat_id=int(id), text=message)

def connect(self):
idler = Thread(target=self.connectThread)
Expand Down Expand Up @@ -233,6 +236,9 @@ def build_menu(self, buttons, n_cols, header_buttons=None, footer_buttons=None):
return menu

def send_message(self, chat_id, text, parse_mode=ParseMode.MARKDOWN, disable_notification=True, delete=True):
if self.logger.config['telegram']['onlyAdmin'] and not self.logger.config['telegram']['chat_ids'][str(chat_id)]['admin']:
logging.info('Aborted telegram answer, because telegram-option "onlyAdmin" is active.')
return
try:
lastMessage = self.bot.send_message(
chat_id, text=text, disable_notification=True, parse_mode=ParseMode.MARKDOWN)
Expand All @@ -250,7 +256,9 @@ def send_message(self, chat_id, text, parse_mode=ParseMode.MARKDOWN, disable_not
self.bot.delete_message(chat_id, message_id)

def sendMenuMessage(self, bot, chat_id, buttonlist, text='', description_text='', n_cols=1, backButton=True):

if self.logger.config['telegram']['onlyAdmin'] and not self.logger.config['telegram']['chat_ids'][str(chat_id)]['admin']:
logging.info('Aborted telegram answer, because telegram-option "onlyAdmin" is active.')
return
if backButton:
buttonlist.append(BACKBUTTON)
if not self.logger.config['telegram']['inlineMenu']:
Expand Down Expand Up @@ -382,7 +390,15 @@ def textHandler(self, bot, update, altStrung=None, alt_chat_id=None):

def menuHandler(self, bot, chat_id):
self.mode[chat_id] = 'menu'
commands = copy.deepcopy(list(self.userActions.keys()))
# commands = copy.deepcopy(list(self.userActions.keys()))
commands = []
admin = self.logger.config['telegram']['chat_ids'][str(chat_id)]['admin']
for c in self.userActions.keys():
if c.startswith('_'):
if admin:
commands += [c]
else:
commands += [c]
commands += self.createShortcutList(bot, chat_id)
commands += self.menuCommands
if self.logger.config['telegram']['chat_ids'][str(chat_id)]['admin']:
Expand All @@ -406,15 +422,14 @@ def menuHandlerAns(self, bot, chat_id, strung):
self.createEventHandler(bot, chat_id)
elif idx == 5:
self.automationHandler(bot, chat_id)
elif self.logger.config['telegram']['chat_ids'][str(chat_id)]['admin']:
if strung in self.adminMenuCommands:
idx = self.adminMenuCommands.index(strung)
if idx == 0:
self.settingsHandler(bot, chat_id)
elif strung in list(self.userActions.keys()):
self.executeUserAction(bot, chat_id, strung)
elif strung in self.createShortcutList(bot, chat_id):
self.callShortcut(bot, chat_id, strung)
elif self.logger.config['telegram']['chat_ids'][str(chat_id)]['admin'] and strung in self.adminMenuCommands:
idx = self.adminMenuCommands.index(strung)
if idx == 0:
self.settingsHandler(bot, chat_id)
else:
self.menuHandler(bot, chat_id)

Expand Down Expand Up @@ -762,9 +777,10 @@ def signalsHandlerAns(self, bot, chat_id, strung):
range = list(self.signals_range[chat_id])
self.send_message(chat_id=chat_id,
text=translate('RTOC', 'Ich erzeuge jetzt einen Graphen mit {} Signalen.\nDas kann eine Weile dauern').format(len(plot_signals)))
t = Thread(target=self.sendSignalPlot, args=(
bot, chat_id, plot_signals, *range))
t.start()
# t = Thread(target=self.sendSignalPlot, args=(
# bot, chat_id, plot_signals, *range))
# t.start()
self.sendSignalPlot(bot, chat_id, plot_signals, *range)
# self._teleThreads.append(t)
# self.signalsHandler(bot, chat_id)
else:
Expand Down Expand Up @@ -1044,11 +1060,14 @@ def settingsHandler(self, bot, chat_id):
if self.logger.config['postgresql']['active']:
commands += [translate('RTOC', 'Datenbank resamplen')]

# if self.logger.config['telegram']['active']:
# commands += [translate('RTOC', "*Telegram-Bot: An (!)*")]
# else:
# commands += [translate('RTOC', "Telegram-Bot: Aus")]

if self.logger.config['telegram']['active']:
commands += [translate('RTOC', "*Telegram-Bot: An (!)*")]
else:
commands += [translate('RTOC', "Telegram-Bot: Aus")]
if self.logger.config['telegram']['onlyAdmin']:
commands += [translate('RTOC', "OnlyAdmin: An")]
else:
commands += [translate('RTOC', "OnlyAdmin: Aus")]
ipadress = urllib.request.urlopen('https://ident.me').read().decode('utf8')
ipadress = translate('RTOC', '\nIP-Adresse: {}').format(ipadress)
obj_Disk = psutil.disk_usage('/')
Expand Down Expand Up @@ -1135,6 +1154,16 @@ def settingsHandlerAns(self, bot, chat_id, strung):
ok = self.logger.toggleTelegramBot(True)
start = True
name = 'Telegram-Bot'
elif strung == translate('RTOC', "OnlyAdmin: An"):
self.logger.config['telegram']['onlyAdmin'] = False
ok = True
start = False
name = 'OnlyAdmin-Modus'
elif strung == translate('RTOC', "OnlyAdmin: Aus"):
self.logger.config['telegram']['onlyAdmin'] = True
ok = True
start = True
name = 'OnlyAdmin-Modus'
elif strung == translate('RTOC', 'Datenbank herunterladen'):
path = self.logger.config['global']['documentfolder']+'/'
filepathes = self.logger.database.exportCSV(path+'telegram_export', True)
Expand Down
1 change: 1 addition & 0 deletions RTOC/RTOC_GUI/Actions.py
Original file line number Diff line number Diff line change
Expand Up @@ -661,6 +661,7 @@ def connectHost(self, host, name, password=''):
retry = False
return True
else:
print(status)
pyqtlib.info_message('End of the universe',
'You reached the end of the universe', "This shouldn't happen")
return False

0 comments on commit fd2a1c6

Please sign in to comment.