Completed
Push — master ( ba28db...d5fb87 )
by Jeffrey
03:31
created

KissTcp.connect()   A

Complexity

Conditions 1

Size

Total Lines 13

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 1
c 1
b 0
f 0
dl 0
loc 13
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 socket
13
14
from apex.kiss import constants as kiss_constants
15
from .kiss import Kiss
16
17
__author__ = 'Jeffrey Phillips Freeman (WI2ARD)'
18
__maintainer__ = 'Jeffrey Phillips Freeman (WI2ARD)'
19
__email__ = '[email protected]'
20
__license__ = 'Apache License, Version 2.0'
21
__copyright__ = 'Copyright 2016, Syncleus, Inc. and contributors'
22
__credits__ = []
23
__version__ = '0.0.2'
24
25
26
class KissTcp(Kiss):
27
28
    """KISS TCP 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,
42
                 strip_df_start=True,
43
                 host=None,
44
                 tcp_port=8000):
45
        super(KissTcp, self).__init__(strip_df_start)
46
47
        self.host = host
48
        self.tcp_port = tcp_port
49
        self.socket = None
50
51
        self.logger.info('Using interface_mode=TCP')
52
53
    def __enter__(self):
54
        return self
55
56
    def __exit__(self, exc_type, exc_val, exc_tb):
57
        self.socket.close()
58
59
    def _read_interface(self):
60
        return self.socket.recv(kiss_constants.READ_BYTES)
61
62
    def _write_interface(self, data):
63
        self.socket.write(data)
64
65
    def connect(self, mode_init=None, **kwargs):
66
        """
67
        Initializes the KISS device and commits configuration.
68
69
        See http://en.wikipedia.org/wiki/KISS_(TNC)#Command_codes
70
        for configuration names.
71
72
        :param **kwargs: name/value pairs to use as initial config values.
73
        """
74
        self.logger.debug('kwargs=%s', kwargs)
75
76
        address = (self.host, self.tcp_port)
77
        self.socket = socket.create_connection(address)
78
79
    def close(self):
80
        super(KissTcp, self).close()
81
82
        if not self.socket:
83
            raise RuntimeError('Attempting to close before the class has been started.')
84
85
        self.socket.shutdown()
86
        self.socket.close()
87
88
    def shutdown(self):
89
        self.socket.shutdown()
90