PyBLNET 0.9.5__tar.gz → 0.11.0__tar.gz

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.
Files changed (31) hide show
  1. {PyBLNET-0.9.5 → pyblnet-0.11.0}/PKG-INFO +86 -85
  2. {PyBLNET-0.9.5 → pyblnet-0.11.0}/README.md +5 -5
  3. pyblnet-0.11.0/pyblnet/__init__.py +14 -0
  4. {PyBLNET-0.9.5 → pyblnet-0.11.0}/pyblnet/blnet.py +25 -4
  5. {PyBLNET-0.9.5 → pyblnet-0.11.0}/pyblnet/blnet_conn.py +117 -36
  6. {PyBLNET-0.9.5 → pyblnet-0.11.0}/pyblnet/blnet_parser.py +33 -6
  7. {PyBLNET-0.9.5 → pyblnet-0.11.0}/pyblnet/blnet_web.py +77 -25
  8. pyblnet-0.11.0/pyproject.toml +41 -0
  9. PyBLNET-0.9.5/PyBLNET.egg-info/PKG-INFO +0 -95
  10. PyBLNET-0.9.5/PyBLNET.egg-info/SOURCES.txt +0 -27
  11. PyBLNET-0.9.5/PyBLNET.egg-info/dependency_links.txt +0 -1
  12. PyBLNET-0.9.5/PyBLNET.egg-info/requires.txt +0 -2
  13. PyBLNET-0.9.5/PyBLNET.egg-info/top_level.txt +0 -1
  14. PyBLNET-0.9.5/pyblnet/__init__.py +0 -20
  15. PyBLNET-0.9.5/pyblnet/tests/__init__.py +0 -0
  16. PyBLNET-0.9.5/pyblnet/tests/test_parser.py +0 -28
  17. PyBLNET-0.9.5/pyblnet/tests/test_structure/580500.alternative.htm +0 -0
  18. PyBLNET-0.9.5/pyblnet/tests/test_structure/580500.htm +0 -1
  19. PyBLNET-0.9.5/pyblnet/tests/test_structure/580600.htm +0 -0
  20. PyBLNET-0.9.5/pyblnet/tests/test_structure/__init__.py +0 -0
  21. PyBLNET-0.9.5/pyblnet/tests/test_structure/blnet_mock_server.py +0 -279
  22. PyBLNET-0.9.5/pyblnet/tests/test_structure/main.htm +0 -63
  23. PyBLNET-0.9.5/pyblnet/tests/test_structure/main.html +0 -63
  24. PyBLNET-0.9.5/pyblnet/tests/test_structure/par.htm +0 -0
  25. PyBLNET-0.9.5/pyblnet/tests/test_structure/server_control.py +0 -59
  26. PyBLNET-0.9.5/pyblnet/tests/test_web.py +0 -204
  27. PyBLNET-0.9.5/pyblnet/tests/web_raw/__init__.py +0 -0
  28. PyBLNET-0.9.5/pyblnet/tests/web_raw/web_state.py +0 -151
  29. PyBLNET-0.9.5/setup.cfg +0 -4
  30. PyBLNET-0.9.5/setup.py +0 -53
  31. {PyBLNET-0.9.5 → pyblnet-0.11.0}/LICENSE.txt +0 -0
@@ -1,95 +1,96 @@
1
- Metadata-Version: 2.1
1
+ Metadata-Version: 2.5
2
2
  Name: PyBLNET
3
- Version: 0.9.5
3
+ Version: 0.11.0
4
4
  Summary: Automate wireless communication to UVR1611 via BL-NET
5
- Home-page: https://github.com/nielstron/pyblnet/
6
- Author: nielstron
7
- Author-email: n.muendler@web.de
8
- License: MIT
9
- Keywords: python uvr1611 blnet technische alternative home automation iot
5
+ Keywords: python,uvr1611,blnet,technische alternative,home automation,iot
6
+ Author-email: nielstron <n.muendler@posteo.de>
7
+ Requires-Python: >=3.10
8
+ Description-Content-Type: text/markdown
10
9
  Classifier: Development Status :: 4 - Beta
11
10
  Classifier: Intended Audience :: Developers
12
11
  Classifier: Topic :: Software Development :: Object Brokering
13
12
  Classifier: License :: OSI Approved :: MIT License
14
- Classifier: Programming Language :: Python :: 3.4
15
- Classifier: Programming Language :: Python :: 3.5
16
- Classifier: Programming Language :: Python :: 3.6
17
- Classifier: Programming Language :: Python :: 3.7
18
- Classifier: Programming Language :: Python :: 3.8
19
- Classifier: Programming Language :: Python :: 3.9
20
13
  Classifier: Programming Language :: Python :: 3.10
21
14
  Classifier: Programming Language :: Python :: 3.11
22
- Requires-Python: >=3
23
- Description-Content-Type: text/markdown
15
+ Classifier: Programming Language :: Python :: 3.12
16
+ Classifier: Programming Language :: Python :: 3.13
17
+ Classifier: Programming Language :: Python :: 3.14
18
+ Classifier: Programming Language :: Python :: 3.15
24
19
  License-File: LICENSE.txt
20
+ Requires-Dist: requests
21
+ Requires-Dist: pytest ; extra == "test"
22
+ Project-URL: Homepage, https://github.com/PyBLNET/pyblnet/
23
+ Provides-Extra: test
24
+ Import-Name: pyblnet
25
+
26
+ # PyBLNET - a very basic python BL-NET bridge
27
+ ![PyPI - Version](https://img.shields.io/pypi/v/pyblnet)
28
+ ![PyPI - Python Version](https://img.shields.io/pypi/pyversions/pyblnet)
29
+ [![Build status](https://github.com/nielstron/pyblnet/actions/workflows/build.yml/badge.svg)](https://github.com/nielstron/pyblnet/actions/workflows/build.yml)
30
+ [![Coverage Status](https://coveralls.io/repos/github/nielstron/pyblnet/badge.svg?branch=master)](https://coveralls.io/github/nielstron/pyblnet?branch=master)
31
+
32
+ A package that connects to the BL-NET that is connected itself to a UVR1611 device by Technische Alternative.
33
+ It is able to read digital and analog values as well as to set switches to ON/OFF/AUTO.
34
+
35
+ Documentation on the modules and their methods can be found with the methods and modules themselves.
36
+
37
+ Two interfaces to BLNet exist and both are supported:
38
+ - Webinterface - Class BLnetWeb
39
+ - BLNet-Direct protocol [1] - Class BLNETDirect
40
+
41
+ However, as of now, there is no testing on the BLNet-Direct protocol *of any kind*, so enabling it is discouraged until the interface is fixed.
42
+ Parsing the data via the web interface is the preferred way of accessing the BLNet for now.
43
+
44
+ The class BLNET is a wrapper around the two classes. When initializing the class, the two interfaces can be activated/deactivated.
45
+ BLNetDirect provides 'analog', 'digital', 'speed', 'energy', 'power', whereas BLnetWeb supports 'analog' and 'digital' only.
46
+ If both are active, BLNetDirect has priority.
47
+ Setting switches and reading their manual/auto state is only possible via the BLNetWeb interface.
48
+
49
+ ### Usage
50
+
51
+ ```python
52
+ from pyblnet import blnet_test, BLNET, BLNETWeb, BLNETDirect
53
+
54
+ ip = '192.168.178.10'
55
+
56
+ # Check if there is a blnet at given address
57
+ blnet_test(ip) # -> True/False
58
+
59
+ # Convenient high level interface
60
+ blnet = BLNET(ip, password='pass', timeout=5)
61
+
62
+ # Control a switch by its ID
63
+ blnet.turn_on(10)
64
+ blnet.turn_auto(10)
65
+ blnet.turn_off(10)
66
+
67
+ # Fetch data (contains all available data using enabled interfaces)
68
+ print(blnet.fetch())
69
+
70
+ # The low level modules are also available
71
+ # note that the direct use of these modules is discouraged though
72
+
73
+ # Fetch the latest data via web interface
74
+ # Note that manual log in and log out are required
75
+ # when not using the with statement
76
+ with BLNETWeb(ip, password='pass', timeout=5) as blnet_session:
77
+ print(blnet_session.read_analog_values())
78
+ print(blnet_session.read_digital_values())
79
+
80
+ # For publishing values
81
+ blnet_session.set_digital_value('10', 'AUS')
82
+ # Note that without explicit log out,
83
+ # the BLNET will block any further web access for the next 150s
84
+ # this is handled automatically when using the with statement
85
+
86
+ # Fetch data via the Protocol developed by TA
87
+ blnet = BLNETDirect(ip)
88
+ # Fetching the latest data
89
+ print(blnet.get_latest())
90
+ # Still inofficial because unexplicably failing often
91
+ print(blnet._get_data(1))
92
+ ```
93
+
94
+
95
+ [1] Technische Alternative, "Schnittstelle Winsol <> Bootloader" (2006), archived copy: http://web.archive.org/web/20160122124754/http://www.haus-terra.at:80/heizung/download/Schnittstelle/Schnittstelle_PC_Bootloader.pdf
25
96
 
26
- # PyBLNET - a very basic python BL-NET bridge
27
- [![Build status](https://github.com/nielstron/pyblnet/actions/workflows/build.yml/badge.svg)](https://github.com/nielstron/pyblnet/actions/workflows/build.yml)
28
- [![Coverage Status](https://coveralls.io/repos/github/nielstron/pyblnet/badge.svg?branch=master)](https://coveralls.io/github/nielstron/pyblnet?branch=master)
29
-
30
- A package that connects to the BL-NET that is connected itself to a UVR1611 device by Technische Alternative.
31
- It is able to read digital and analog values as well as to set switches to ON/OFF/AUTO.
32
-
33
- Documentation on the modules and their methods can be found with the methods and modules themselves.
34
-
35
- Two interfaces to BLNet exist and both are supported:
36
- - Webinterface - Class BLnetWeb
37
- - BLNet-Direct protocol [1] - Class BLNETDirect
38
-
39
- However, as of now, there is no testing on the BLNet-Direct protocol *of any kind*, so enabling it is discouraged until the interface is fixed.
40
- Parsing the data via the web interface is the preferred way of accessing the BLNet for now.
41
-
42
- The class BLNET is a wrapper around the two classes. When initializing the class, the two interfaces can be activated/deactivated.
43
- BLNetDirect provides 'analog', 'digital', 'speed', 'energy', 'power', whereas BLnetWeb supports 'analog' and 'digital' only.
44
- If both are active, BLNetDirect has priority.
45
- Setting switches and reading their manual/auto state is only possible via the BLNetWeb interface.
46
-
47
- ### Usage
48
-
49
- ```python
50
- from pyblnet import test_blnet, BLNET, BLNETWeb, BLNETDirect
51
-
52
- ip = '192.168.178.10'
53
-
54
- # Check if there is a blnet at given address
55
- test_blnet(ip) # -> True/False
56
-
57
- # Convenient high level interface
58
- blnet = BLNET(ip, password='pass', timeout=5)
59
-
60
- # Control a switch by its ID
61
- blnet.turn_on(10)
62
- blnet.turn_auto(10)
63
- blnet.turn_off(10)
64
-
65
- # Fetch data (contains all available data using enabled interfaces)
66
- print(blnet.fetch())
67
-
68
-
69
-
70
- # The low level modules are also available
71
- # note that the direct use of these modules is discouraged though
72
-
73
- # Fetch the latest data via web interface
74
- # Note that manual log in and log out are required
75
- # when not using the with statement
76
- with BLNETWeb(ip, password='pass', timeout=5) as blnet_session:
77
- print(blnet_session.read_analog_values())
78
- print(blnet_session.read_digital_values())
79
-
80
- # For publishing values
81
- blnet_session.set_digital_value('10', 'AUS')
82
- # Note that without explicit log out,
83
- # the BLNET will block any further web access for the next 150s
84
- # this is handled automatically when using the with statement
85
-
86
- # Fetch data via the Protocol developed by TA
87
- blnet = BLNETDirect(ip)
88
- # Fetching the latest data
89
- print(blnet.get_latest())
90
- # Still inofficial because unexplicably failing often
91
- print(blnet._get_data(1))
92
- ```
93
-
94
-
95
- [1] https://www.haus-terra.at/heizung/download/Schnittstelle/Schnittstelle_PC_Bootloader.pdf
@@ -1,4 +1,6 @@
1
1
  # PyBLNET - a very basic python BL-NET bridge
2
+ ![PyPI - Version](https://img.shields.io/pypi/v/pyblnet)
3
+ ![PyPI - Python Version](https://img.shields.io/pypi/pyversions/pyblnet)
2
4
  [![Build status](https://github.com/nielstron/pyblnet/actions/workflows/build.yml/badge.svg)](https://github.com/nielstron/pyblnet/actions/workflows/build.yml)
3
5
  [![Coverage Status](https://coveralls.io/repos/github/nielstron/pyblnet/badge.svg?branch=master)](https://coveralls.io/github/nielstron/pyblnet?branch=master)
4
6
 
@@ -22,12 +24,12 @@ Setting switches and reading their manual/auto state is only possible via the BL
22
24
  ### Usage
23
25
 
24
26
  ```python
25
- from pyblnet import test_blnet, BLNET, BLNETWeb, BLNETDirect
27
+ from pyblnet import blnet_test, BLNET, BLNETWeb, BLNETDirect
26
28
 
27
29
  ip = '192.168.178.10'
28
30
 
29
31
  # Check if there is a blnet at given address
30
- test_blnet(ip) # -> True/False
32
+ blnet_test(ip) # -> True/False
31
33
 
32
34
  # Convenient high level interface
33
35
  blnet = BLNET(ip, password='pass', timeout=5)
@@ -40,8 +42,6 @@ blnet.turn_off(10)
40
42
  # Fetch data (contains all available data using enabled interfaces)
41
43
  print(blnet.fetch())
42
44
 
43
-
44
-
45
45
  # The low level modules are also available
46
46
  # note that the direct use of these modules is discouraged though
47
47
 
@@ -67,4 +67,4 @@ print(blnet._get_data(1))
67
67
  ```
68
68
 
69
69
 
70
- [1] https://www.haus-terra.at/heizung/download/Schnittstelle/Schnittstelle_PC_Bootloader.pdf
70
+ [1] Technische Alternative, "Schnittstelle Winsol <> Bootloader" (2006), archived copy: http://web.archive.org/web/20160122124754/http://www.haus-terra.at:80/heizung/download/Schnittstelle/Schnittstelle_PC_Bootloader.pdf
@@ -0,0 +1,14 @@
1
+ #!/usr/bin/env python
2
+ # -*- coding: utf-8 -*-
3
+
4
+ import warnings
5
+
6
+ try:
7
+ from .blnet_web import BLNETWeb, blnet_test
8
+ from .blnet_conn import BLNETDirect
9
+ from .blnet import BLNET
10
+ except ImportError as e:
11
+ warnings.warn(ImportWarning(e))
12
+
13
+ VERSION = (0, 11, 0)
14
+
@@ -12,10 +12,17 @@ as possible.
12
12
  """
13
13
  from .blnet_web import BLNETWeb
14
14
  from .blnet_conn import BLNETDirect
15
+ from .blnet_parser import ANALOG_UNITS
15
16
 
16
17
  from urllib.parse import urlparse
17
18
 
18
19
 
20
+ # Units of the values only available via BLNETDirect, speed is a level 0-30
21
+ UNITS = {"speed": None, "energy": "kWh", "power": "kW"}
22
+ # Analog input type for the units shown by the web interface
23
+ WEB_UNIT_TYPES = {unit: input_type for input_type, unit in ANALOG_UNITS.items() if unit is not None}
24
+
25
+
19
26
  class BLNET(object):
20
27
  """
21
28
  General high-level BLNET interface.
@@ -68,7 +75,7 @@ class BLNET(object):
68
75
  # especially not if not prefixed with http://
69
76
  # see https://docs.python.org/3/library/urllib.parse.html#urllib.parse.urlparse
70
77
  host = urlparse(address).hostname or address
71
- self.blnet_direct = BLNETDirect(host, ta_port)
78
+ self.blnet_direct = BLNETDirect(host, ta_port, timeout=timeout)
72
79
 
73
80
  def fetch(self, node=None):
74
81
  """
@@ -88,6 +95,8 @@ class BLNET(object):
88
95
  blnet_session.set_node(node)
89
96
  data["analog"] = self._convert_web(blnet_session.read_analog_values())
90
97
  data["digital"] = self._convert_web(blnet_session.read_digital_values())
98
+ for entry in data["analog"].values():
99
+ entry["type"] = WEB_UNIT_TYPES.get(entry.get("unit_of_measurement"))
91
100
  if self.blnet_direct:
92
101
  direct = self.blnet_direct.get_latest(self.max_retries)[0]
93
102
  # Override values for analog and digital as values are
@@ -96,11 +105,20 @@ class BLNET(object):
96
105
  for id, value in direct[domain].items():
97
106
  if data[domain].get(id) is not None:
98
107
  data[domain][id]["value"] = value
108
+ elif not self.blnet_web:
109
+ if value is None:
110
+ continue
111
+ data[domain][id] = {"value": value}
112
+ if domain == "analog":
113
+ input_type = direct["analog_types"][id]
114
+ data[domain][id]["type"] = input_type
115
+ data[domain][id]["unit_of_measurement"] = ANALOG_UNITS.get(input_type)
116
+
99
117
  for domain in ["speed", "energy", "power"]:
100
118
  for id, value in direct[domain].items():
101
119
  if value is None:
102
120
  continue
103
- data[domain][id] = {"value": value}
121
+ data[domain][id] = {"value": value, "unit_of_measurement": UNITS[domain]}
104
122
  return data
105
123
 
106
124
  def turn_on(self, digital_id, can_node=None):
@@ -162,8 +180,11 @@ class BLNET(object):
162
180
  if cached is None:
163
181
  cached = self.fetch()
164
182
  for key, v in cached[type].items():
165
- if str(v["name"]) == str(name) or str(v["id"]) == str(id):
166
- val = v[ret]
183
+ # values fetched only via blnet_direct have no name
184
+ if (name is not None and str(v.get("name")) == str(name)) or (
185
+ id is not None and str(key) == str(id)
186
+ ):
187
+ val = v.get(ret)
167
188
  dic = v
168
189
 
169
190
  return val, dic, cached
@@ -10,6 +10,7 @@ https://github.com/berwinter/uvr1611/blob/master/lib/backend/blnet-connection.in
10
10
  """
11
11
  from builtins import str, int
12
12
  from socket import socket, getaddrinfo, SOCK_STREAM, IPPROTO_TCP
13
+ import functools
13
14
  import struct
14
15
  from time import sleep
15
16
  from datetime import datetime
@@ -27,11 +28,37 @@ READ_DATA = 0xAC
27
28
  END_READ = b"\xAD"
28
29
  RESET_DATA = b"\xAF"
29
30
  WAIT_TIME = 0xBA
31
+ # Seconds to wait when the BL-Net has no new data yet. Real devices answer
32
+ # GET_LATEST with "no data" for up to about 5 seconds after a read.
33
+ NO_DATA_WAIT = 2
30
34
  MAX_RETRYS = 10
35
+ # Length of a WAIT_TIME reply: 0xBA, seconds to wait, checksum
36
+ WAIT_SIZE = 3
31
37
  DATASET_SIZE = 61
32
38
  LATEST_SIZE = 56
33
39
 
34
40
 
41
+ def _reset_on_error(method):
42
+ """
43
+ Close the connection and forget the read state if a read fails,
44
+ so that the next call starts with a fresh connection.
45
+ Malformed replies are raised as ConnectionError.
46
+ """
47
+
48
+ @functools.wraps(method)
49
+ def wrapper(self, *args, **kwargs):
50
+ try:
51
+ return method(self, *args, **kwargs)
52
+ except (struct.error, IndexError, ValueError) as ex:
53
+ self._reset()
54
+ raise ConnectionError(f"Invalid reply from BL-Net: {ex}") from ex
55
+ except BaseException:
56
+ self._reset()
57
+ raise
58
+
59
+ return wrapper
60
+
61
+
35
62
  class BLNETDirect(object):
36
63
  """
37
64
  A class for establishing a direct connection to the BLNET (rather than
@@ -41,12 +68,13 @@ class BLNETDirect(object):
41
68
  www.haus-terra.at/heizung/download/Schnittstelle/Schnittstelle_PC_Bootloader.pdf
42
69
  """
43
70
 
44
- def __init__(self, address, port=40000, reset=False):
71
+ def __init__(self, address, port: int = 40000, reset: bool = False, timeout: float = 60):
45
72
  """
46
73
  Constructor
47
- @param address: string, Address of the BL-Net device
48
- @param port: integer, Port of the bl-net device for connection
49
- @param reset: boolean, delete data on BL-Net after data receive
74
+ :param address: string, Address of the BL-Net device
75
+ :param port: integer, Port of the bl-net device for connection
76
+ :param reset: boolean, delete data on BL-Net after data receive
77
+ :param timeout: float, timeout in seconds for the connection
50
78
  """
51
79
  assert isinstance(address, str)
52
80
  assert isinstance(port, int)
@@ -54,11 +82,14 @@ class BLNETDirect(object):
54
82
  self.address = address
55
83
  self.port = port
56
84
  self.reset = reset
85
+ # 0 would make the socket non-blocking, treat it like None (no timeout)
86
+ self._timeout = timeout or None
57
87
  self._mode = None
58
88
  self._socket = None
59
89
  self._count = None
60
90
  self._check_mode()
61
91
 
92
+ @_reset_on_error
62
93
  def get_count(self):
63
94
  """
64
95
  Get the number of datasets in the bootloader memory
@@ -87,7 +118,7 @@ class BLNETDirect(object):
87
118
  self._fetch_size = 4 + 61 * frame_count
88
119
  elif self._mode == DL_MODE:
89
120
  (_, device, start_address, end_address, checksum) = struct.unpack(
90
- "<5sB3s3sB"
121
+ "<5sB3s3sB", data
91
122
  )
92
123
  self._address_inc = 64
93
124
  self._can_frames = 1
@@ -95,7 +126,7 @@ class BLNETDirect(object):
95
126
  self._fetch_size = 65
96
127
  elif self._mode == DL2_MODE:
97
128
  (_, device, start_address, end_address, checksum) = struct.unpack(
98
- "<5s2s3s3sB"
129
+ "<5s2s3s3sB", data
99
130
  )
100
131
  self._address_inc = 128
101
132
  self._can_frames = 1
@@ -125,20 +156,18 @@ class BLNETDirect(object):
125
156
  else:
126
157
  raise ConnectionError("Could not retreive count")
127
158
 
159
+ @_reset_on_error
128
160
  def _get_data(self, max_count=None):
129
161
  data = []
130
- try:
131
- count = self._start_read()
132
- if isinstance(max_count, int):
133
- count = min(max_count, count)
134
- for _ in range(0, count):
135
- data.append(self._fetch_data())
136
- self._end_read(True)
137
- return data
138
- finally:
139
- self._end_read(False)
140
- return data
162
+ count = self._start_read()
163
+ if isinstance(max_count, int):
164
+ count = min(max_count, count)
165
+ for _ in range(0, count):
166
+ data.append(self._fetch_data())
167
+ self._end_read(True)
168
+ return data
141
169
 
170
+ @_reset_on_error
142
171
  def _check_mode(self):
143
172
  """
144
173
  Check if Bootloader Mode is supported
@@ -164,9 +193,11 @@ class BLNETDirect(object):
164
193
  for (family, socktype, proto, _, sockaddr) in available:
165
194
  try:
166
195
  self._socket = socket(family, socktype, proto)
196
+ self._socket.settimeout(self._timeout)
167
197
  self._socket.connect(sockaddr)
168
198
  break
169
- except:
199
+ except OSError:
200
+ self._socket.close()
170
201
  self._socket = None
171
202
  if self._socket is None:
172
203
  raise ConnectionError("Could not connect to BLNET")
@@ -178,26 +209,67 @@ class BLNETDirect(object):
178
209
  self._socket.close()
179
210
  self._socket = None
180
211
 
212
+ def _reset(self):
213
+ """
214
+ Close the connection if open and forget the read state
215
+ """
216
+ if self._socket is not None:
217
+ self._disconnect()
218
+ self._count = None
219
+ self._address = None
220
+
181
221
  def _query(self, command, length):
182
222
  """
183
223
  Send a command to the bootloader and wait for the response
184
224
  if response is less then 32 bytes long return immediately
185
225
  @param commmand: string only ascii (needs byte length == string length)
186
226
  @param length: int length of response
187
- @throws ConnectionError error when querying
227
+ @throws ConnectionError BL-Net closed the connection
188
228
  @return Binary: byte string
189
229
  """
190
- if len(command) == self._socket.send(command):
191
- data = b""
192
- # get response until length or less than 32 bytes
193
- while True:
194
- data += self._socket.recv(length)
195
- if len(data) <= 32 or len(data) >= length:
196
- break
197
- return data
198
-
199
- self._disconnect()
200
- raise ConnectionError("Error while querying command {}".format(command))
230
+ self._socket.sendall(command)
231
+ data = b""
232
+ # get response until length or less than 32 bytes
233
+ while True:
234
+ received = self._socket.recv(length)
235
+ if not received:
236
+ raise ConnectionError("BL-Net closed the connection")
237
+ data += received
238
+ if len(data) <= 32 or len(data) >= length:
239
+ break
240
+ return data
241
+
242
+ def _recv_exact(self, length):
243
+ """
244
+ Receive exactly length bytes
245
+ @throws ConnectionError BL-Net closed the connection
246
+ @return Binary: byte string
247
+ """
248
+ data = b""
249
+ while len(data) < length:
250
+ received = self._socket.recv(length - len(data))
251
+ if not received:
252
+ raise ConnectionError("BL-Net closed the connection")
253
+ data += received
254
+ return data
255
+
256
+ def _query_latest(self, command):
257
+ """
258
+ Send a GET_LATEST command and receive the complete reply.
259
+ The BL-Net may send a reply in several TCP segments, so the length
260
+ is derived from its first byte and the reply is read completely.
261
+ Reading only part of it would leave the rest in the socket and
262
+ shift every following reply by some bytes.
263
+ @return Binary: byte string, a "no data", "wait" or data reply
264
+ """
265
+ self._socket.sendall(command)
266
+ first = self._recv_exact(1)
267
+ if first[0] == GET_LATEST:
268
+ # no new data available yet
269
+ return first
270
+ if first[0] == WAIT_TIME:
271
+ return first + self._recv_exact(WAIT_SIZE - 1)
272
+ return first + self._recv_exact(self._actual_size - 1)
201
273
 
202
274
  def _start_read(self):
203
275
  """
@@ -305,6 +377,7 @@ class BLNETDirect(object):
305
377
  self._address = None
306
378
  self._disconnect()
307
379
 
380
+ @_reset_on_error
308
381
  def get_latest(self, max_retries=MAX_RETRYS):
309
382
  """
310
383
  Fetch latest (current) data from the BLNet
@@ -315,7 +388,7 @@ class BLNETDirect(object):
315
388
  self._connect()
316
389
  self.get_count()
317
390
  frames = {}
318
- info = {"sleep": {}, "got": {}}
391
+ info = {"sleep": {}, "got": {}, "timeout": []}
319
392
 
320
393
  # for all frames
321
394
  for frame in range(0, self._can_frames):
@@ -324,9 +397,12 @@ class BLNETDirect(object):
324
397
  # try 4 times
325
398
  sleeps = []
326
399
  for n in range(0, max_retries):
327
- data = self._query(command, self._actual_size)
400
+ data = self._query_latest(command)
328
401
 
329
- if self._checksum(data):
402
+ if data == bytes([GET_LATEST]):
403
+ # no new data available yet ("Synchronisation" in TA's spec)
404
+ sleep(NO_DATA_WAIT)
405
+ elif self._checksum(data):
330
406
  binary = struct.unpack("<{}".format("B" * len(data)), data)
331
407
 
332
408
  if binary[0] == WAIT_TIME:
@@ -339,9 +415,14 @@ class BLNETDirect(object):
339
415
  info["got"][frame] = n
340
416
  frames.update(self._split_latest(data, frame))
341
417
  break
342
- # TODO this looks suspicious
343
- if n == max_retries - 1:
344
- frames[frame] = "timeout"
418
+ else:
419
+ # Unexpected bytes may still be on their way, reconnect
420
+ # so that they can't end up in the next reply
421
+ self._disconnect()
422
+ self._connect()
423
+ else:
424
+ # BL-Net did not send data for this frame within max_retries
425
+ info["timeout"].append(frame)
345
426
  info["sleep"][frame] = sleeps
346
427
  self._end_read(True)
347
428
  if len(frames) > 0:
@@ -3,7 +3,7 @@
3
3
  """
4
4
  Created on 09.08.2018
5
5
 
6
- This is basically a python port of of a script by berwinter
6
+ This is basically a python port of a script by berwinter
7
7
  https://github.com/berwinter/uvr1611/blob/master/lib/backend/blnet-connection.inc.php
8
8
 
9
9
  author: Niels
@@ -30,10 +30,28 @@ TYPE_VOLUME = 0x3000
30
30
  TYPE_RADIATION = 0x4000
31
31
  TYPE_RAS = 0x7000
32
32
  RAS_POSITIVE_MASK = 0x01FF
33
+ # Temperature input without sensor (or with a broken wire): all value bits set, 409.5 °C
34
+ TEMP_NO_SENSOR = TYPE_TEMP | POSITIVE_VALUE_MASK
33
35
  # 32 bit
34
36
  INT32_MASK = 0xFFFFFFFF
35
37
  INT32_SIGN = 0x80000000
36
38
 
39
+ # Names of the analog input types, unused and undocumented types have none
40
+ ANALOG_TYPES = {
41
+ TYPE_DIGITAL: "digital",
42
+ TYPE_TEMP: "temperature",
43
+ TYPE_VOLUME: "volume_flow",
44
+ TYPE_RADIATION: "radiation",
45
+ TYPE_RAS: "temperature",
46
+ }
47
+ # Units of the analog input types, as the web interface shows them
48
+ ANALOG_UNITS = {
49
+ "digital": None,
50
+ "temperature": "°C",
51
+ "volume_flow": "l/h",
52
+ "radiation": "W/m²",
53
+ }
54
+
37
55
 
38
56
  class BLNETParser:
39
57
  def __init__(self, data):
@@ -71,8 +89,11 @@ class BLNETParser:
71
89
  analog = struct.unpack("<{}{}".format("H" * 16, "x" * (len(data) - 32)), data)
72
90
 
73
91
  self.analog = {}
92
+ self.analog_types = {}
74
93
  for channel in range(0, 16):
75
- self.analog[channel + 1] = round(self._convert_analog(analog[channel]), 3)
94
+ self.analog_types[channel + 1] = ANALOG_TYPES.get(analog[channel] & TYPE_MASK)
95
+ value = self._convert_analog(analog[channel])
96
+ self.analog[channel + 1] = None if value is None else round(value, 3)
76
97
 
77
98
  self.digital = {}
78
99
  for channel in range(0, 16):
@@ -107,7 +128,12 @@ class BLNETParser:
107
128
  """
108
129
 
109
130
  mask = value & TYPE_MASK
110
- if mask == TYPE_TEMP:
131
+ if mask == TYPE_NONE:
132
+ # input is unused
133
+ return None
134
+ elif value == TEMP_NO_SENSOR:
135
+ return None
136
+ elif mask == TYPE_TEMP:
111
137
  return self._calculate_value(value, 0.1)
112
138
  elif mask == TYPE_VOLUME:
113
139
  return self._calculate_value(value, 4)
@@ -118,7 +144,8 @@ class BLNETParser:
118
144
  return 0
119
145
  elif mask == TYPE_RAS:
120
146
  return self._calculate_value(value, 0.1, RAS_POSITIVE_MASK)
121
- elif mask in [TYPE_RADIATION, TYPE_NONE] or True:
147
+ else:
148
+ # TYPE_RADIATION and types not covered by the interface spec
122
149
  return self._calculate_value(value)
123
150
 
124
151
  def _convert_digital(self, value, position):
@@ -144,7 +171,7 @@ class BLNETParser:
144
171
  Check if heat meter is activated on a given position
145
172
  @return its energy
146
173
  """
147
- if active & position:
174
+ if active & (1 << position):
148
175
  kwh = self._calculate_value(kwh, 0.1, INT16_POSITIVE_MASK)
149
176
  return round(mwh * 1000 + kwh, 3)
150
177
  else:
@@ -155,7 +182,7 @@ class BLNETParser:
155
182
  checks if heat meter is activated at given position
156
183
  @return its power
157
184
  """
158
- if active & position:
185
+ if active & (1 << position):
159
186
  value = self._calculate_value(value, 1 / 2560, INT32_MASK, INT32_SIGN)
160
187
  value = round(value, 3)
161
188
  return value