Преглед на файлове

Initial serial_interface implementation

master
Dirk Alders преди 4 години
родител
ревизия
e30211c70c
променени са 1 файла, в които са добавени 122 реда и са изтрити 0 реда
  1. 122
    0
      __init__.py

+ 122
- 0
__init__.py Целия файл

@@ -0,0 +1,122 @@
1
+#!/usr/bin/env python
2
+# -*- coding: utf-8 -*-
3
+#
4
+"""
5
+serial_interface (Serial Interface Module)
6
+==========================================
7
+
8
+**Author:**
9
+
10
+* Dirk Alders <sudo-dirk@mount-mockery.de>
11
+
12
+**Description:**
13
+
14
+    This Module supports a common interface for a serial port
15
+
16
+**Submodules:**
17
+
18
+* :mod:`mmod.module.sub1`
19
+* :class:`mmod.module.sub2`
20
+* :func:`mmod.module.sub2`
21
+
22
+**Unittest:**
23
+
24
+        See also the :download:`unittest <../../serial_interface/_testresults_/unittest.pdf>` documentation.
25
+"""
26
+__DEPENDENCIES__ = ['stringtools']
27
+
28
+import stringtools
29
+
30
+import logging
31
+import serial
32
+import time
33
+
34
+logger_name = 'SERIAL_INTERFACE'
35
+logger = logging.getLogger(logger_name)
36
+
37
+
38
+class serial_interface(object):
39
+    """
40
+    Class to send and receive data via a serial port.
41
+
42
+    .. note:: All parameters are given to the standard :py:class:`serial.Serial` library
43
+    """
44
+    LOG_PREFIX = 'SER:'
45
+
46
+    def __init__(self, *args, **kwargs):
47
+        self._args = args
48
+        self._kwargs = kwargs
49
+        self.com = None
50
+        self.open()
51
+
52
+    def open(self):
53
+        """
54
+        This opens the serial port.
55
+
56
+        :returns: True if the port has been successfully opened
57
+        :rtype: bool
58
+        """
59
+        if self.com is not None:
60
+            self.close()
61
+        try:
62
+            self.com = serial.Serial(*self._args, **self._kwargs)
63
+        except:
64
+            self.com = None
65
+            logger.warning('%s Unable to open comport (%s)', self.LOG_PREFIX, self._args[0])
66
+            return False
67
+        else:
68
+            logger.debug('%s Opening comport (%s)', self.LOG_PREFIX, self._args[0])
69
+        return True
70
+
71
+    def close(self):
72
+        """
73
+        This closes the serial port.
74
+        """
75
+        if self.com is not None:
76
+            logger.debug('%s Closing comport (%s)', self.LOG_PREFIX, self._args[0])
77
+            self.com.close()
78
+            self.com = None
79
+
80
+    def bytes_in_queue(self):
81
+        """
82
+        This returns the number of available bytes for receiption.
83
+
84
+        :returns: Number of bytes in queue
85
+        :rtype: int
86
+        """
87
+        if self.com is not None:
88
+            return self.com.inWaiting()
89
+        else:
90
+            return 0
91
+
92
+    def receive(self, max_length=None):
93
+        """
94
+        This receives data from the serial interface.
95
+
96
+        :param int length: An optinal number of bytes to be received. None will return all available bytes.
97
+        :returns: The received data
98
+        :rtype: str
99
+        """
100
+        length = self.bytes_in_queue()
101
+        if max_length is not None:
102
+            length = min(length, max_length)
103
+        if self.com is not None and length > 0:
104
+            data = self.com.read(length)
105
+            self._handle_debug('RX <- ', data)
106
+            return data
107
+
108
+    def send(self, data):
109
+        """
110
+        This sends data via the serial interface.
111
+
112
+        :param str data: The data to be send
113
+        """
114
+        if self.com is not None:
115
+            self._handle_debug('TX -> ', data)
116
+            self.com.write(data)
117
+
118
+    def _handle_debug(self, msg, data):
119
+        logger.debug('%s ' + msg + stringtools.hexlify(data), self.LOG_PREFIX)
120
+
121
+    def __del__(self):
122
+        self.close()

Loading…
Отказ
Запис