utils.py 1.98 KB
Newer Older
Bach Dániel committed
1 2 3
from twisted.protocols.basic import LineReceiver
import json
import logging
4 5
import platform

Bach Dániel committed
6

Bach Dániel committed
7
logger = logging.getLogger()
8
system = platform.system()
Bach Dániel committed
9 10 11


class SerialLineReceiverBase(LineReceiver, object):
12
    MAX_LENGTH = 1024*1024*128
Bach Dániel committed
13

14 15 16 17 18 19 20
    def __init__(self, *args, **kwargs):
        if system == "FreeBSD":
            self.delimiter = '\n'
        else:
            self.delimiter = '\r'
        super(SerialLineReceiverBase, self).__init__(*args, **kwargs)

Bach Dániel committed
21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42
    def send_response(self, response, args):
        self.transport.write(json.dumps({'response': response,
                                         'args': args}) + '\r\n')

    def send_command(self, command, args):
        self.transport.write(json.dumps({'command': command,
                                         'args': args}) + '\r\n')

    def handle_command(self, command, args):
        raise NotImplementedError("Subclass must implement abstract method")

    def handle_response(self, response, args):
        raise NotImplementedError("Subclass must implement abstract method")

    def lineReceived(self, data):
        try:
            data = json.loads(data)
            args = data.get('args', {})
            if not isinstance(args, dict):
                args = {}
            command = data.get('command', None)
            response = data.get('response', None)
Bach Dániel committed
43
            logger.debug('[serial] valid json: %s' % (data, ))
Bach Dániel committed
44
        except (ValueError, KeyError) as e:
Bach Dániel committed
45
            logger.error('[serial] invalid json: %s (%s)' % (data, e))
Bach Dániel committed
46 47 48
            return

        if command is not None and isinstance(command, unicode):
Bach Dániel committed
49
            logger.debug('received command: %s (%s)' % (command, args))
Bach Dániel committed
50 51 52
            try:
                self.handle_command(command, args)
            except Exception as e:
Bach Dániel committed
53
                logger.exception(u'Unhandled exception: ')
Bach Dániel committed
54
        elif response is not None and isinstance(response, unicode):
Bach Dániel committed
55
            logger.debug('received reply: %s (%s)' % (response, args))
Bach Dániel committed
56
            self.handle_response(response, args)