KissSerial   A
last analyzed

Complexity

Total Complexity 18

Size/Duplication

Total Lines 83
Duplicated Lines 0 %

Importance

Changes 3
Bugs 0 Features 0
Metric Value
c 3
b 0
f 0
dl 0
loc 83
rs 10
wmc 18

8 Methods

Rating   Name   Duplication   Size   Complexity  
A _write_interface() 0 2 1
A __init__() 0 16 1
A __del__() 0 3 3
A __enter__() 0 2 1
A __exit__() 0 2 1
A _read_interface() 0 6 4
B connect() 0 25 4
A close() 0 7 3
1
#!/usr/bin/env python
2
# -*- coding: utf-8 -*-
3
4
"""KISS Core Classes."""
5
6
# These imports are for python3 compatibility inside python2
7
from __future__ import absolute_import
8
from __future__ import division
9
from __future__ import print_function
10
11
import logging
12
import serial
13
14
import six
15
16
from apex.kiss import constants as kiss_constants
17
18
from .kiss import Kiss
19
20
__author__ = 'Jeffrey Phillips Freeman (WI2ARD)'
21
__maintainer__ = 'Jeffrey Phillips Freeman (WI2ARD)'
22
__email__ = '[email protected]'
23
__license__ = 'Apache License, Version 2.0'
24
__copyright__ = 'Copyright 2016, Syncleus, Inc. and contributors'
25
__credits__ = []
26
27
28
class KissSerial(Kiss):
29
30
    """KISS Serial Object Class."""
31
32
    logger = logging.getLogger(__name__)
33
    logger.setLevel(kiss_constants.LOG_LEVEL)
34
    console_handler = logging.StreamHandler()
35
    console_handler.setLevel(kiss_constants.LOG_LEVEL)
36
    formatter = logging.Formatter(kiss_constants.LOG_FORMAT)
37
    console_handler.setFormatter(formatter)
38
    logger.addHandler(console_handler)
39
    logger.propagate = False
40
41
    def __init__(self, strip_df_start=True,
42
                 com_port=None,
43
                 baud=38400,
44
                 parity=serial.PARITY_NONE,
45
                 stop_bits=serial.STOPBITS_ONE,
46
                 byte_size=serial.EIGHTBITS):
47
        super(KissSerial, self).__init__(strip_df_start)
48
49
        self.com_port = com_port
50
        self.baud = baud
51
        self.parity = parity
52
        self.stop_bits = stop_bits
53
        self.byte_size = byte_size
54
        self.serial = None
55
56
        self.logger.info('Using interface_mode=Serial')
57
58
    def __enter__(self):
59
        return self
60
61
    def __exit__(self, exc_type, exc_val, exc_tb):
62
        self.serial.close()
63
64
    def __del__(self):
65
        if self.serial and self.serial.isOpen():
66
            self.serial.close()
67
68
    def _read_interface(self):
69
        read_data = self.serial.read(kiss_constants.READ_BYTES)
70
        waiting_data = self.serial.inWaiting()
71
        if waiting_data:
72
            read_data += self.serial.read(waiting_data)
73
        return [ord(c) if six.PY2 else c for c in read_data]
74
75
    def _write_interface(self, data):
76
        self.serial.write(data)
77
78
    def connect(self, mode_init=None, **kwargs):
79
        """
80
        Initializes the KISS device and commits configuration.
81
82
        See http://en.wikipedia.org/wiki/KISS_(TNC)#Command_codes
83
        for configuration names.
84
85
        :param **kwargs: name/value pairs to use as initial config values.
86
        """
87
        self.logger.debug('kwargs=%s', kwargs)
88
89
        self.serial = serial.Serial(port=self.com_port, baudrate=self.baud, parity=self.parity,
90
                                    stopbits=self.stop_bits, bytesize=self.byte_size)
91
        self.serial.timeout = kiss_constants.SERIAL_TIMEOUT
92
        if mode_init is not None:
93
            self.serial.write(mode_init)
94
            self.exit_kiss = True
95
        else:
96
            self.exit_kiss = False
97
98
        # Previous verious defaulted to Xastir-friendly configs. Unfortunately
99
        # those don't work with Bluetooth TNCs, so we're reverting to None.
100
        if kwargs:
101
            for name, value in kwargs.items():
102
                super(KissSerial, self)._write_setting(name, value)
103
104
    def close(self):
105
        super(KissSerial, self).close()
106
107
        if not self.serial:
108
            raise RuntimeError('Attempting to close before the class has been started.')
109
        elif self.serial.isOpen():
110
            self.serial.close()
111