owlsensor 0.1__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
owlsensor/__init__.py ADDED
File without changes
owlsensor/serial_cm.py ADDED
@@ -0,0 +1,191 @@
1
+ """
2
+ Reading data from particulate matter sensors with a serial interface.
3
+ """
4
+ import time
5
+ import threading
6
+ import logging
7
+
8
+ import serial
9
+
10
+ STARTBLOCK = "SB"
11
+ RECORD_LENGTH = "RL"
12
+ # Ofsets of the PM data (always 2 byte)
13
+ CURRENT = "Current"
14
+ BAUD_RATE = "BAUD"
15
+ BYTE_ORDER = "BO",
16
+ LSB = "lsb"
17
+ MSB = "msb"
18
+ DTR_ON = "DTR"
19
+ DTR_OFF = "NOT_DTR"
20
+ MULTIPLIER = "MP"
21
+ TIMEOUT = "TO"
22
+
23
+ # Owl CM160 settings
24
+ OWL_CM160 = {
25
+ "TheOWL": "CM160",
26
+ STARTBLOCK: bytes([0x42, 0x4d, 0x00, 0x14]),
27
+ RECORD_LENGTH: 24,
28
+ CURRENT: 8,
29
+ BAUD_RATE: 250000,
30
+ BYTE_ORDER: MSB,
31
+ MULTIPLIER: 0.07,
32
+ TIMEOUT: 2
33
+ }
34
+
35
+ SUPPORTED_SENSORS = {
36
+ "TheOWL,CM160": OWL_CM160
37
+ }
38
+
39
+ CMVALS=[CURRENT]
40
+
41
+ LOGGER = logging.getLogger(__name__)
42
+
43
+
44
+ class CMDataCollector():
45
+ """Controls the serial interface and reads data from the sensor."""
46
+
47
+ # pylint: disable=too-many-instance-attributes
48
+ def __init__(self,
49
+ serialdevice,
50
+ configuration,
51
+ power_control=DTR_ON,
52
+ scan_interval=0):
53
+ """Initialize the data collector based on the given parameters."""
54
+
55
+ self.record_length = configuration[RECORD_LENGTH]
56
+ self.start_sequence = configuration[STARTBLOCK]
57
+ self.byte_order = configuration[BYTE_ORDER]
58
+ self.multiplier = configuration[MULTIPLIER]
59
+ self.timeout = configuration[TIMEOUT]
60
+ self.scan_interval = scan_interval
61
+ self.listeners = []
62
+ self.power_control = power_control
63
+ self.sensordata = {}
64
+ self.config = configuration
65
+ self.data = None
66
+ self.last_poll = None
67
+ self.start_func = None
68
+ self.stop_func = None
69
+
70
+ self.ser = serial.Serial(port=serialdevice,
71
+ baudrate=configuration[BAUD_RATE],
72
+ parity=serial.PARITY_NONE,
73
+ stopbits=serial.STOPBITS_ONE,
74
+ bytesize=serial.EIGHTBITS,
75
+ timeout=0.5)
76
+
77
+ # Update date in using a background thread
78
+ if self.scan_interval > 0:
79
+ thread = threading.Thread(target=self.refresh, args=())
80
+ thread.daemon = True
81
+ thread.start()
82
+
83
+ def refresh(self):
84
+ """Background refreshing thread."""
85
+ while True:
86
+ self.read_data()
87
+ time.sleep(self.scan_interval)
88
+
89
+ # pylint: disable=too-many-branches
90
+ def read_data(self):
91
+ """Read data from serial interface and return it as a dictionary.
92
+
93
+ There is some caching implemented the sensor won't be polled twice
94
+ within a 15 second interval. If data is requested within 15 seconds
95
+ after it has been read, the data from the last read_data operation will
96
+ be returned again
97
+ """
98
+
99
+ mytime = time.time()
100
+ if (self.last_poll is not None) and \
101
+ (mytime - self.last_poll) <= 15:
102
+ return self._data
103
+
104
+ # Start function that can do several things (e.g. turning the
105
+ # sensor on)
106
+ if self.start_func:
107
+ self.start_func(self.ser)
108
+
109
+ res = None
110
+ finished = False
111
+ sbuf = bytearray()
112
+ starttime = time.time()
113
+ checkCode = int(0);
114
+ expectedCheckCode = int()
115
+ #it is necessary to reset input buffer because data is cotinously received by the system and placed in the device buffer when serial is open.
116
+ #But "Home Assistant" code read it only from time to time so the data we read here would be placed in the past.
117
+ #Better is to clean the buffer and read new data from "present" time.
118
+ self.ser.reset_input_buffer()
119
+ while not finished:
120
+ mytime = time.time()
121
+ if mytime - starttime > self.timeout:
122
+ LOGGER.error("read timeout after %s seconds, read %s bytes",
123
+ self.timeout, len(sbuf))
124
+ return {}
125
+
126
+ if self.ser.inWaiting() > 0:
127
+ sbuf += self.ser.read(1)
128
+ if len(sbuf) == len(self.start_sequence):
129
+ if sbuf == self.start_sequence:
130
+ LOGGER.debug("Found start sequence %s",
131
+ self.start_sequence)
132
+ else:
133
+ LOGGER.debug("Start sequence not yet found")
134
+ # Remove first character
135
+ sbuf = sbuf[1:]
136
+
137
+ if len(sbuf) == self.record_length:
138
+ #Check the control sum if it is known how to do it
139
+ if self.config == PLANTOWER1:
140
+ for c in sbuf[0:(self.record_length-2)]:
141
+ checkCode += c
142
+ expectedCheckCode = sbuf[30]*256 + sbuf[31]
143
+ if checkCode != expectedCheckCode:
144
+ #because of data inconsistency clean the buffer
145
+ LOGGER.error("PM sensor data sum error %d, expected %d", checkCode, expectedCheckCode)
146
+ sbuf = []
147
+ checkCode = 0
148
+ continue
149
+
150
+ #if it is ok then send it for interpretation
151
+ res = self.parse_buffer(sbuf)
152
+ LOGGER.debug("Finished reading data %s", sbuf)
153
+ finished = True
154
+
155
+ else:
156
+ time.sleep(.5)
157
+ LOGGER.debug("Serial waiting for data, buffer length=%s",
158
+ len(sbuf))
159
+
160
+ if self.stop_func:
161
+ self.stop_func(self.ser)
162
+
163
+ self._data = res
164
+ self.last_poll = time.time()
165
+ return res
166
+
167
+ def parse_buffer(self, sbuf):
168
+ """Parse the buffer and return the CM values."""
169
+ res = {}
170
+ for pmname in CMVALS:
171
+ offset = self.config[pmname]
172
+ if offset is not None:
173
+ if self.byte_order == MSB:
174
+ res[pmname] = sbuf[offset] * \
175
+ 256 + sbuf[offset + 1]
176
+ else:
177
+ res[pmname] = sbuf[offset + 1] * \
178
+ 256 + sbuf[offset]
179
+
180
+ res[pmname] = round(res[pmname] * self.multiplier, 1)
181
+
182
+ return res
183
+
184
+ def supported_values(self) -> list:
185
+ """Returns the list of supported values for the actual device"""
186
+ res = []
187
+ for pmname in CMVALS:
188
+ offset = self.config[pmname]
189
+ if offset is not None:
190
+ res.append(pmname)
191
+ return res
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2023 Pascal Brunot
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,21 @@
1
+ Metadata-Version: 2.1
2
+ Name: owlsensor
3
+ Version: 0.1
4
+ Summary: Library to read data from OWL Energy meters
5
+ Home-page: https://github.com/PBrunot/owlsensor
6
+ Author: Pascal Brunot
7
+ Author-email: pbr-dev@gmail.com
8
+ License: MIT
9
+ Keywords: serial owl cm160 energy_meter homeautomation
10
+ Classifier: Development Status :: 3 - Alpha
11
+ Classifier: Intended Audience :: Developers
12
+ Classifier: Topic :: System :: Hardware :: Hardware Drivers
13
+ Classifier: License :: OSI Approved :: MIT License
14
+ Classifier: Programming Language :: Python :: 3
15
+ Classifier: Programming Language :: Python :: 3.4
16
+ Classifier: Programming Language :: Python :: 3.5
17
+ Description-Content-Type: text/x-rst
18
+ License-File: LICENSE
19
+ Requires-Dist: pyserial >=3
20
+
21
+ This package is designed for integrating into Home Assistant a serial-connected OWL energy meter.
@@ -0,0 +1,7 @@
1
+ owlsensor/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
2
+ owlsensor/serial_cm.py,sha256=sY-wY-XY8qe406lkcY6q_KE27QY2vp8DJ_ehoAJh0BQ,6547
3
+ owlsensor-0.1.dist-info/LICENSE,sha256=zO0Kn9_4x_mTcq8F_qHpFcT5FfHjtZusfzQmyzcJv-c,1070
4
+ owlsensor-0.1.dist-info/METADATA,sha256=r4OobPhclkJ5pPpR_iamV3RtieKUcEg0dDcNmpyxAn8,807
5
+ owlsensor-0.1.dist-info/WHEEL,sha256=R06PA3UVYHThwHvxuRWMqaGcr-PuniXahwjmQRFMEkY,91
6
+ owlsensor-0.1.dist-info/top_level.txt,sha256=bBZKOvuoXB-czUcp0cSeR8EmD2hVzDEqmucOBabtmXs,10
7
+ owlsensor-0.1.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (75.5.0)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
@@ -0,0 +1 @@
1
+ owlsensor