Completed
Pull Request — master (#13)
by Jeffrey
03:21
created

KissSerial.close()   A

Complexity

Conditions 3

Size

Total Lines 5

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 3
c 1
b 0
f 0
dl 0
loc 5
rs 9.4285
1
#!/usr/bin/env python
2
# -*- coding: utf-8 -*-
3
4
"""KISS Core Classes."""
5
6
# These imports are for python3 compatability 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
from apex.kiss import constants as kiss_constants
15
16
from .kiss import Kiss
17
18
__author__ = 'Jeffrey Phillips Freeman (WI2ARD)'
19
__maintainer__ = 'Jeffrey Phillips Freeman (WI2ARD)'
20
__email__ = '[email protected]'
21
__license__ = 'Apache License, Version 2.0'
22
__copyright__ = 'Copyright 2016, Syncleus, Inc. and contributors'
23
__credits__ = []
24
25
26
class KissSerial(Kiss):
27
28
    """KISS Serial Object Class."""
29
30
    logger = logging.getLogger(__name__)
31
    logger.setLevel(kiss_constants.LOG_LEVEL)
32
    console_handler = logging.StreamHandler()
33
    console_handler.setLevel(kiss_constants.LOG_LEVEL)
34
    formatter = logging.Formatter(kiss_constants.LOG_FORMAT)
35
    console_handler.setFormatter(formatter)
36
    logger.addHandler(console_handler)
37
    logger.propagate = False
38
39
    frame_buffer = []
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
        self.strip_df_start = strip_df_start
56
        self.exit_kiss = False
57
58
        self.logger.info('Using interface_mode=Serial')
59
60
    def __enter__(self):
61
        return self
62
63
    def __exit__(self, exc_type, exc_val, exc_tb):
64
        self.serial.close()
65
66
    def __del__(self):
67
        if self.serial and self.serial.isOpen():
68
            self.serial.close()
69
70
    def _read_interface(self):
71
        read_data = self.serial.read(kiss_constants.READ_BYTES)
72
        waiting_data = self.serial.inWaiting()
73
        if waiting_data:
74
            read_data += self.serial.read(waiting_data)
75
        return map(ord, read_data)
76
77
    def _write_interface(self, data):
78
        self.serial.write(data)
79
80
    def start(self, mode_init=None, **kwargs):
81
        """
82
        Initializes the KISS device and commits configuration.
83
84
        See http://en.wikipedia.org/wiki/KISS_(TNC)#Command_codes
85
        for configuration names.
86
87
        :param **kwargs: name/value pairs to use as initial config values.
88
        """
89
        self.logger.debug('kwargs=%s', kwargs)
90
91
        self.serial = serial.Serial(port=self.com_port, baudrate=self.baud, parity=self.parity,
92
                                    stopbits=self.stop_bits, bytesize=self.byte_size)
93
        self.serial.timeout = kiss_constants.SERIAL_TIMEOUT
94
        if mode_init is not None:
95
            self.serial.write(mode_init)
96
            self.exit_kiss = True
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
        # If no settings specified, default to config values similar
105
        # to those that ship with Xastir.
106
        # if not kwargs:
107
        #    kwargs = kiss.constants.DEFAULT_KISS_CONFIG_VALUES
108
109
    def close(self):
110
        if not self.serial:
111
            raise RuntimeError('Attempting to close before the class has been started.')
112
        elif self.serial.isOpen():
113
            self.serial.close()
114