diff --git a/core/envisalink.py b/core/envisalink.py index cf6083c..420386c 100644 --- a/core/envisalink.py +++ b/core/envisalink.py @@ -1,4 +1,4 @@ -import time, datetime, sys +import time, datetime, sys, re from tornado import gen from tornado.tcpclient import TCPClient from tornado.iostream import IOStream, StreamClosedError @@ -98,36 +98,60 @@ def send_command(self, code, data, checksum = True): pass @gen.coroutine - def handle_line(self, input): - if input != '': - if config.ENVISALINKLOGRAW == True: - logger.debug('RX RAW < "' + str(input).strip() + '"') + def handle_line(self, rawinput): + if rawinput == '': + return + + input = rawinput.strip() + if config.ENVISALINKLOGRAW == True: + logger.debug('RX RAW < "' + str(input) + '"') + + if re.match(r'^\d\d:\d\d:\d\d ',input): + evltime = input[:8] + input = input[9:] - code=int(input[:3]) - parameters=input[3:][:-4] + if not re.match(r'^[0-9a-fA-F]{5,}$', input): + logger.warning('Received invalid TPI message: ' + repr(rawinput)); + return + + code = int(input[:3]) + parameters = input[3:][:-2] + try: event = getMessageType(int(code)) - message = self.format_event(event, parameters) - logger.debug('RX < ' +str(code)+' - '+message) + except KeyError: + logger.warning('Received unknown TPI code: "%s", parameters: "%s"' % + (input[:3], parameters)) + return - try: - handler = "handle_%s" % evl_ResponseTypes[code]['handler'] - except KeyError: - handler = "handle_event" + rcksum = int(input[-2:], 16) + ccksum = int(get_checksum(input[:3],parameters), 16) + if rcksum != ccksum: + logger.warning('Received invalid TPI checksum %02X vs %02X: "%s"' % + (rcksum, ccksum, input)) + return - try: - func = getattr(self, handler) - if handler != 'handle_login': - events.put('proxy', None, input) - except AttributeError: - raise CodeError("Handler function doesn't exist") + message = self.format_event(event, parameters) + logger.debug('RX < ' +str(code)+' - '+message) - func(code, parameters, event, message) - try: - line = yield self._connection.read_until(self._terminator) - self.handle_line(line) - except StreamClosedError: - #we don't need to handle this, the callback has been set for closed connections. - pass + try: + handler = "handle_%s" % event['handler'] + except KeyError: + handler = "handle_event" + + try: + func = getattr(self, handler) + if handler != 'handle_login': + events.put('proxy', None, rawinput) + except AttributeError: + raise CodeError("Handler function doesn't exist") + + func(code, parameters, event, message) + try: + line = yield self._connection.read_until(self._terminator) + self.handle_line(line) + except StreamClosedError: + #we don't need to handle this, the callback has been set for closed connections. + pass def format_event(self, event, parameters): if 'type' in event: