Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 15 additions & 2 deletions pyblnet/blnet.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,10 +12,17 @@
"""
from .blnet_web import BLNETWeb
from .blnet_conn import BLNETDirect
from .blnet_parser import ANALOG_UNITS

from urllib.parse import urlparse


# Units of the values only available via BLNETDirect, speed is a level 0-30
UNITS = {"speed": None, "energy": "kWh", "power": "kW"}
# Analog input type for the units shown by the web interface
WEB_UNIT_TYPES = {unit: input_type for input_type, unit in ANALOG_UNITS.items() if unit is not None}


class BLNET(object):
"""
General high-level BLNET interface.
Expand Down Expand Up @@ -68,7 +75,7 @@ def __init__(
# especially not if not prefixed with http://
# see https://docs.python.org/3/library/urllib.parse.html#urllib.parse.urlparse
host = urlparse(address).hostname or address
self.blnet_direct = BLNETDirect(host, ta_port)
self.blnet_direct = BLNETDirect(host, ta_port, timeout=timeout)

def fetch(self, node=None):
"""
Expand All @@ -88,6 +95,8 @@ def fetch(self, node=None):
blnet_session.set_node(node)
data["analog"] = self._convert_web(blnet_session.read_analog_values())
data["digital"] = self._convert_web(blnet_session.read_digital_values())
for entry in data["analog"].values():
entry["type"] = WEB_UNIT_TYPES.get(entry.get("unit_of_measurement"))
if self.blnet_direct:
direct = self.blnet_direct.get_latest(self.max_retries)[0]
# Override values for analog and digital as values are
Expand All @@ -100,12 +109,16 @@ def fetch(self, node=None):
if value is None:
continue
data[domain][id] = {"value": value}
if domain == "analog":
input_type = direct["analog_types"][id]
data[domain][id]["type"] = input_type
data[domain][id]["unit_of_measurement"] = ANALOG_UNITS.get(input_type)

for domain in ["speed", "energy", "power"]:
for id, value in direct[domain].items():
if value is None:
continue
data[domain][id] = {"value": value}
data[domain][id] = {"value": value, "unit_of_measurement": UNITS[domain]}
return data

def turn_on(self, digital_id, can_node=None):
Expand Down
129 changes: 103 additions & 26 deletions pyblnet/blnet_conn.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@
"""
from builtins import str, int
from socket import socket, getaddrinfo, SOCK_STREAM, IPPROTO_TCP
import functools
import struct
from time import sleep
from datetime import datetime
Expand All @@ -27,11 +28,37 @@
END_READ = b"\xAD"
RESET_DATA = b"\xAF"
WAIT_TIME = 0xBA
# Seconds to wait when the BL-Net has no new data yet. Real devices answer
# GET_LATEST with "no data" for up to about 5 seconds after a read.
NO_DATA_WAIT = 2
MAX_RETRYS = 10
# Length of a WAIT_TIME reply: 0xBA, seconds to wait, checksum
WAIT_SIZE = 3
DATASET_SIZE = 61
LATEST_SIZE = 56


def _reset_on_error(method):
"""
Close the connection and forget the read state if a read fails,
so that the next call starts with a fresh connection.
Malformed replies are raised as ConnectionError.
"""

@functools.wraps(method)
def wrapper(self, *args, **kwargs):
try:
return method(self, *args, **kwargs)
except (struct.error, IndexError, ValueError) as ex:
self._reset()
raise ConnectionError(f"Invalid reply from BL-Net: {ex}") from ex
except BaseException:
self._reset()
raise

return wrapper


class BLNETDirect(object):
"""
A class for establishing a direct connection to the BLNET (rather than
Expand Down Expand Up @@ -62,6 +89,7 @@ def __init__(self, address, port: int = 40000, reset: bool = False, timeout: flo
self._count = None
self._check_mode()

@_reset_on_error
def get_count(self):
"""
Get the number of datasets in the bootloader memory
Expand Down Expand Up @@ -128,20 +156,18 @@ def get_count(self):
else:
raise ConnectionError("Could not retreive count")

@_reset_on_error
def _get_data(self, max_count=None):
data = []
try:
count = self._start_read()
if isinstance(max_count, int):
count = min(max_count, count)
for _ in range(0, count):
data.append(self._fetch_data())
self._end_read(True)
return data
finally:
self._end_read(False)
return data
count = self._start_read()
if isinstance(max_count, int):
count = min(max_count, count)
for _ in range(0, count):
data.append(self._fetch_data())
self._end_read(True)
return data

@_reset_on_error
def _check_mode(self):
"""
Check if Bootloader Mode is supported
Expand Down Expand Up @@ -170,7 +196,8 @@ def _connect(self):
self._socket.settimeout(self._timeout)
self._socket.connect(sockaddr)
break
except:
except OSError:
self._socket.close()
self._socket = None
if self._socket is None:
raise ConnectionError("Could not connect to BLNET")
Expand All @@ -182,26 +209,67 @@ def _disconnect(self):
self._socket.close()
self._socket = None

def _reset(self):
"""
Close the connection if open and forget the read state
"""
if self._socket is not None:
self._disconnect()
self._count = None
self._address = None

def _query(self, command, length):
"""
Send a command to the bootloader and wait for the response
if response is less then 32 bytes long return immediately
@param commmand: string only ascii (needs byte length == string length)
@param length: int length of response
@throws ConnectionError error when querying
@throws ConnectionError BL-Net closed the connection
@return Binary: byte string
"""
if len(command) == self._socket.send(command):
data = b""
# get response until length or less than 32 bytes
while True:
data += self._socket.recv(length)
if len(data) <= 32 or len(data) >= length:
break
return data

self._disconnect()
raise ConnectionError("Error while querying command {}".format(command))
self._socket.sendall(command)
data = b""
# get response until length or less than 32 bytes
while True:
received = self._socket.recv(length)
if not received:
raise ConnectionError("BL-Net closed the connection")
data += received
if len(data) <= 32 or len(data) >= length:
break
return data

def _recv_exact(self, length):
"""
Receive exactly length bytes
@throws ConnectionError BL-Net closed the connection
@return Binary: byte string
"""
data = b""
while len(data) < length:
received = self._socket.recv(length - len(data))
if not received:
raise ConnectionError("BL-Net closed the connection")
data += received
return data

def _query_latest(self, command):
"""
Send a GET_LATEST command and receive the complete reply.
The BL-Net may send a reply in several TCP segments, so the length
is derived from its first byte and the reply is read completely.
Reading only part of it would leave the rest in the socket and
shift every following reply by some bytes.
@return Binary: byte string, a "no data", "wait" or data reply
"""
self._socket.sendall(command)
first = self._recv_exact(1)
if first[0] == GET_LATEST:
# no new data available yet
return first
if first[0] == WAIT_TIME:
return first + self._recv_exact(WAIT_SIZE - 1)
return first + self._recv_exact(self._actual_size - 1)

def _start_read(self):
"""
Expand Down Expand Up @@ -309,6 +377,7 @@ def _end_read(self, success=True):
self._address = None
self._disconnect()

@_reset_on_error
def get_latest(self, max_retries=MAX_RETRYS):
"""
Fetch latest (current) data from the BLNet
Expand All @@ -328,9 +397,12 @@ def get_latest(self, max_retries=MAX_RETRYS):
# try 4 times
sleeps = []
for n in range(0, max_retries):
data = self._query(command, self._actual_size)
data = self._query_latest(command)

if self._checksum(data):
if data == bytes([GET_LATEST]):
# no new data available yet ("Synchronisation" in TA's spec)
sleep(NO_DATA_WAIT)
elif self._checksum(data):
binary = struct.unpack("<{}".format("B" * len(data)), data)

if binary[0] == WAIT_TIME:
Expand All @@ -343,6 +415,11 @@ def get_latest(self, max_retries=MAX_RETRYS):
info["got"][frame] = n
frames.update(self._split_latest(data, frame))
break
else:
# Unexpected bytes may still be on their way, reconnect
# so that they can't end up in the next reply
self._disconnect()
self._connect()
else:
# BL-Net did not send data for this frame within max_retries
info["timeout"].append(frame)
Expand Down
18 changes: 18 additions & 0 deletions pyblnet/blnet_parser.py
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,22 @@
INT32_MASK = 0xFFFFFFFF
INT32_SIGN = 0x80000000

# Names of the analog input types, unused and undocumented types have none
ANALOG_TYPES = {
TYPE_DIGITAL: "digital",
TYPE_TEMP: "temperature",
TYPE_VOLUME: "volume_flow",
TYPE_RADIATION: "radiation",
TYPE_RAS: "temperature",
}
# Units of the analog input types, as the web interface shows them
ANALOG_UNITS = {
"digital": None,
"temperature": "°C",
"volume_flow": "l/h",
"radiation": "W/m²",
}


class BLNETParser:
def __init__(self, data):
Expand Down Expand Up @@ -73,7 +89,9 @@ def __init__(self, data):
analog = struct.unpack("<{}{}".format("H" * 16, "x" * (len(data) - 32)), data)

self.analog = {}
self.analog_types = {}
for channel in range(0, 16):
self.analog_types[channel + 1] = ANALOG_TYPES.get(analog[channel] & TYPE_MASK)
value = self._convert_analog(analog[channel])
self.analog[channel + 1] = None if value is None else round(value, 3)

Expand Down
Loading
Loading