Skip to content

Commit

Permalink
bugfixes
Browse files Browse the repository at this point in the history
  • Loading branch information
Sebastian committed Jun 7, 2019
1 parent 56d826d commit 1d0467d
Show file tree
Hide file tree
Showing 4 changed files with 98 additions and 77 deletions.
2 changes: 1 addition & 1 deletion RTOC/LoggerPlugin.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
# LoggerPlugin v2.3
# LoggerPlugin v2.4
import traceback
import time
import sys
Expand Down
20 changes: 16 additions & 4 deletions RTOC/RTLogger/RT_data.py
Original file line number Diff line number Diff line change
Expand Up @@ -57,7 +57,9 @@ def __init__(self, t, hFunction, useqtimer=False):
def _handle_function(self):
try:
self._hFunction()
except Exception:
except Exception as error:
logging.info(traceback.format_exc())
logging.info(error)
logging.info('Backup failed')
if QTimer is not None and self._useqtimer:
self._thread = QTimer()
Expand Down Expand Up @@ -1126,7 +1128,7 @@ def _addSQLSignal(self, sigID, signal):
dev = self._SQLdeviceExists(devicename)
if dev is False:
self._SQLcreateDevice(signal[0], devicename)
if not self.signalExists(signalname, devicename):
if not self._SQLsignalExists(signalname, devicename):
sigID = self._SQLcreateSignal(sigID, signalname, devicename, x, y, unit)
# add data
sql = 'UPDATE '+SIGNAL_TABLE_NAME+' SET X = ARRAY'+str(x)+'::NUMERIC[] WHERE ID ='+str(sigID)+';'
Expand All @@ -1146,6 +1148,16 @@ def _SQLdeviceExists(self, devicename):
sig = False
return sig

def _SQLsignalExists(self, signalname):
existtest = "SELECT EXISTS (select ID from "+SIGNAL_TABLE_NAME + \
" where NAME = '"+str(signalname)+"');"
sig = self._execute_n_fetchall(existtest)
if sig is not None and sig != []:
sig = bool(sig[0][0])
else:
sig = False
return sig

def _SQLcreateDevice(self, devID, devicename):
# logging.info('Creating new device: '+str(devicename))
timestamp = time.time()
Expand Down Expand Up @@ -1199,7 +1211,7 @@ def _SQLcreateEvent(self, devID, sigID, evID, strung, x, value, priority, eventi
devID = self._SQLgetDeviceID(devicename)
# check_sigID = self._SQLgetSignalID(devicename, signalname)
# if check_sigID == -1:
if not self.signalExists(signalname, devicename):
if not self._SQLsignalExists(signalname, devicename):
sigID = self._SQLcreateSignal(sigID, devicename, signalname)
# sigID = self._SQLgetSignalID(devicename, signalname)
if devID != -1 and sigID != -1:
Expand Down Expand Up @@ -1308,7 +1320,7 @@ def _SQLplot(self, x=[], y=[], sname="noName", dname="noDevice", unit="", c=Fals
if len(x) == len(y):
if not self._SQLdeviceExists(dname):
self._SQLcreateDevice(dname)
if not self.signalExists(sname, dname):
if not self._SQLsignalExists(sname, dname):
sigID = self._SQLcreateSignal(sname, dname)
self._SQLplotNewData(x, y, unit, dname, sname,
c, hold, autoResize)
Expand Down
108 changes: 55 additions & 53 deletions RTOC/RTLogger/telegramBot.py
Original file line number Diff line number Diff line change
Expand Up @@ -931,9 +931,7 @@ def signalsSelectRangeHandler(self, bot, chat_id):
xmin_s, xmax_s = self.signals_range[chat_id]
xmin_s = dt.datetime.fromtimestamp(xmin_s).strftime("%d.%m.%Y %H:%M:%S")
xmax_s = dt.datetime.fromtimestamp(xmax_s).strftime("%d.%m.%Y %H:%M:%S")
text = 'Hier kannst du einstellen, welchen Bereich ich darstellen soll.\nGib dazu jetzt das Startdatum und Enddatum in folgendem Format ein: "' + \
dt.datetime.fromtimestamp(time.time()-1000).strftime("%d.%m.%Y %H:%M:%S") + \
' - '+dt.datetime.fromtimestamp(time.time()).strftime("%d.%m.%Y %H:%M:%S")+'"'
text = 'Hier kannst du einstellen, welchen Bereich ich darstellen soll.\nWenn du nur ein Datum angibst, gehe ich davon aus, du willst die Daten ab diesem Zeitpunkt bis jetzt haben.\nWenn du einen Zeitraum angeben willst, trenne zwei Zeitpunkte mit einem "-". Du musst keine Uhrzeit angeben.\nBeispiel: "16.05.19 - 13.06.19 14:33"'
text += translate('RTOC', '\nAusgew\xe4hlter Zeitraum:\n{} - {}\nVerf\xfcgbarer Zeitraum:\n{} - {}\n').format(xmin_s, xmax_s, xmin, xmax)
commands = [translate('RTOC', 'Letzte Minute'), translate('RTOC', 'Letzten 10 Minuten'), translate('RTOC', 'Letzte Stunde'), translate('RTOC', 'Letzte 24h'), translate('RTOC', 'Letzte Woche'), translate('RTOC', 'Letzter Monat'), translate('RTOC', 'Alles')]
self.sendMenuMessage(bot, chat_id, commands, text)
Expand Down Expand Up @@ -964,56 +962,11 @@ def signalsSelectRangeHandlerAns(self, bot, chat_id, strung):
xmin = self.logger.database.getGlobalXmin() -100
xmax = self.logger.database.getGlobalXmax() +100
else:
if len(strung.split('-')) == 2:
times = strung.split('-')
while times[0].endswith(' '):
times[0] = times[0][0:-1]
while times[0].startswith(' '):
times[0] = times[0][1:]
while times[1].endswith(' '):
times[1] = times[1][0:-1]
while times[0].startswith(' '):
times[1] = times[1][1:]
foundXmin = False
foundXmax = False
for format in ['%d.%m.%Y %H:%M:%S', '%d.%m %H:%M:%S', '%d.%m %H:%M', '%d.%m.%Y %H:%M', '%d.%m.%Y', '%d.%m']:
try:
xmin = dt.datetime.strptime(times[0], format).timestamp()
foundXmin = True
break
except Exception:
pass
for format in ['%d.%m.%Y %H:%M:%S', '%d.%m %H:%M:%S', '%d.%m %H:%M', '%d.%m.%Y %H:%M', '%d.%m.%Y', '%d.%m']:
try:
xmax = dt.datetime.strptime(times[1], format).timestamp()
foundXmax = True
break
except Exception:
pass

if not foundXmin or not foundXmax:
# print(traceback.format_exc())
self.send_message(chat_id=chat_id,
text=translate('RTOC', 'Bitte sende mir einen Zeitraum, den ich verstehen kann:\n')+'"'+dt.datetime.fromtimestamp(time.time()-1000).strftime("%d.%m.%Y %H:%M:%S")+' - '+dt.datetime.fromtimestamp(time.time()).strftime("%d.%m.%Y %H:%M:%S")+'"')
return
else:
foundXmin = False
while strung.endswith(' '):
strung = strung[0:-1]
while strung.startswith(' '):
strung = strung[1:]
for format in ['%d.%m.%Y %H:%M:%S', '%d.%m %H:%M:%S', '%d.%m %H:%M', '%d.%m.%Y %H:%M', '%d.%m.%Y', '%d.%m']:
try:
xmin = dt.datetime.strptime(strung, format).timestamp()
xmax = time.time()
foundXmin = True
break
except Exception:
pass
if not foundXmin:
self.send_message(chat_id=chat_id,
text=translate('RTOC', 'Bitte sende mir einen Zeitraum, den ich verstehen kann:\n')+'"'+dt.datetime.fromtimestamp(time.time()-1000).strftime("%d.%m.%Y %H:%M:%S")+' - '+dt.datetime.fromtimestamp(time.time()).strftime("%d.%m.%Y %H:%M:%S")+'"')
return
found, xmin, xmax = _strToTimerange(strung)
if not found:
self.send_message(chat_id=chat_id,
text=translate('RTOC', 'Bitte sende mir einen Zeitraum, den ich verstehen kann.'))
return
self.signals_range[chat_id] = [xmin, xmax]
xmin = dt.datetime.fromtimestamp(xmin).strftime("%d.%m.%Y %H:%M:%S")
xmax = dt.datetime.fromtimestamp(xmax).strftime("%d.%m.%Y %H:%M:%S")
Expand Down Expand Up @@ -2030,3 +1983,52 @@ def executeUserAction(self, bot, chat_id, strung):
# Name angeben ...
#
# <--


def _strToTimestamp(datetimestr):
while datetimestr.endswith(' '):
datetimestr = datetimestr[0:-1]
while datetimestr.startswith(' '):
datetimestr = datetimestr[1:]
formats = []
dates = ['%d.%m.%Y', '%d.%m', '%m.%Y', '%d.%m.%y', '%m/%d', '%m/%d/%y',
'%m/%d/%Y', '%m-%d-%y', '%m-%d-%Y', '%d. %B %Y', '%B %Y']
times = ['%H:%M:%S', '%H:%M']

for d in dates:
formats += [d]
for t in times:
formats += [t]
formats += [d+' '+t]
formats += [t+' '+d]

for format in formats:
try:
ts = dt.datetime.strptime(datetimestr, format)
if 'y' not in format.lower():
ts = ts.replace(year=2019)
ts = ts.timestamp()

return True, ts
break
except Exception:
pass
return False, None


def _strToTimerange(rangestr):
if len(rangestr.split('-')) == 2:
times = rangestr.split('-')
foundXmin, xmin = _strToTimestamp(times[0])
foundXmax, xmax = _strToTimestamp(times[1])
if not foundXmin or not foundXmax:
return False, None, None
else:
return True, xmin, xmax
else:
xmax = time.time()
foundXmin, xmin = _strToTimestamp(rangestr)
if not foundXmin:
return False, None, None
else:
return True, xmin, xmax
45 changes: 26 additions & 19 deletions RTOC/jsonsocket.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
# jsonsocket.py v1.6
# jsonsocket.py v1.7

import json
import socket
Expand Down Expand Up @@ -26,6 +26,7 @@ class NoPasswordProtectionError(Exception):
expression -- input expression in which the error occurred
message -- explanation of the error
"""

def __init__(self, expression, message):
self.expression = expression
self.message = message
Expand All @@ -39,9 +40,10 @@ class WrongPasswordError(Exception):
expression -- input expression in which the error occurred
message -- explanation of the error
"""

def __init__(self, expression, message):
self.expression = expression
self.message = message
self.expression = expression
self.message = message


class PasswordProtectedError(Exception):
Expand All @@ -52,6 +54,7 @@ class PasswordProtectedError(Exception):
expression -- input expression in which the error occurred
message -- explanation of the error
"""

def __init__(self, expression, message):
self.expression = expression
self.message = message
Expand All @@ -69,6 +72,7 @@ def __init__(self, expression, message):
# self.expression = expression
# self.message = message

BACKLOG = 5


class Server(object):
Expand All @@ -83,11 +87,10 @@ class Server(object):
reuse_port (bool): Enable/disable reuse_port (default: True)
"""

backlog = 5
client = None

def __init__(self, host, port, keyword=None, reuse_port=True):
self.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.client = None

if reuse_port:
self.socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
self.socket.setsockopt(socket.SOL_SOCKET, socket.SO_KEEPALIVE, 1)
Expand All @@ -99,7 +102,7 @@ def __init__(self, host, port, keyword=None, reuse_port=True):
# self.socket.setblocking(0)
self.socket.settimeout(5.0)
self.socket.bind((host, port))
self.socket.listen(self.backlog)
self.socket.listen(BACKLOG)

self.keyword = keyword

Expand All @@ -112,8 +115,8 @@ def setKeyword(self, keyword=None):
"""
self.keyword = keyword

def __del__(self):
self.close()
# def __del__(self):
# self.close()

def accept(self):
"""
Expand Down Expand Up @@ -181,9 +184,10 @@ class Client(object):
keyword (str or None): Set a keyword for encrypted communication. Leaf blank for unsecure connection. (default: None)
"""

socket = None
keyword = None
host = None
def __init__(self):
self.socket = None
self.keyword = None
self.host = None

def setKeyword(self, keyword=None):
"""
Expand All @@ -194,8 +198,8 @@ def setKeyword(self, keyword=None):
"""
self.keyword = keyword

def __del__(self):
self.close()
# def __del__(self):
# self.close()

def connect(self, host, port, keyword=None, reuse_port=True):
"""
Expand All @@ -208,6 +212,7 @@ def connect(self, host, port, keyword=None, reuse_port=True):
reuse_port (bool): Enable/disable reuse_port (default: True)
"""
self.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

if reuse_port:
self.socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
self.socket.setsockopt(socket.SOL_SOCKET, socket.SO_KEEPALIVE, 1)
Expand Down Expand Up @@ -312,10 +317,10 @@ def _recv(socket, key=None):
# read the length of the data, letter by letter until we reach EOL
length_str = b''
try:
char = socket.recv(1)#.decode()
char = socket.recv(1) # .decode()
while char != b'\n':
length_str += char
char = socket.recv(1)#.decode()
char = socket.recv(1) # .decode()
except Exception:
print(traceback.format_exc())
return False
Expand All @@ -328,7 +333,7 @@ def _recv(socket, key=None):
total = 0
tagTotal = 0
nonceTotal = 0
if len(lens) ==1:
if len(lens) == 1:
total = int(lens[0])
# not encrypted
elif len(lens) == 3:
Expand Down Expand Up @@ -364,15 +369,17 @@ def _recv(socket, key=None):
logging.error(tb)
raise WrongPasswordError("SOCKET PASSWORD ERROR, The provided password is wrong!")
else:
raise NoPasswordProtectionError('SOCKET PASSWORD ERROR, No password provided!\nCannot receive data')
raise NoPasswordProtectionError(
'SOCKET PASSWORD ERROR, No password provided!\nCannot receive data')
else:
if len(tagView) == 0 and len(nonceView) == 0:
try:
return deserializeJSON(view)
except (TypeError, ValueError):
tb = traceback.format_exc()
logging.debug(tb)
raise PasswordProtectedError('JSON SOCKET ERROR, Data received was not in JSON format. Maybe the RTOC-Server is password-protected')
raise PasswordProtectedError(
'JSON SOCKET ERROR, Data received was not in JSON format. Maybe the RTOC-Server is password-protected')
else:
raise PasswordProtectedError('SOCKET ERROR, The server is password protected')

Expand Down

0 comments on commit 1d0467d

Please sign in to comment.