1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268
|
"""Parser for wiffi telegrams and server for wiffi devices."""
import asyncio
import json
class WiffiMetric:
"""Representation of wiffi metric reported in json telegram."""
def __init__(self, data):
"""Initialize the instance."""
self._id = int(data["name"])
self._name = data["homematic_name"]
self._metric_type = data["type"]
self._description = data["desc"]
self._unit_of_measurement = data["unit"]
self._value = convert_value(data)
@property
def id(self):
"""Return integer based metric id.
Called 'name' in the json telegram.
"""
return int(self._id)
@property
def name(self):
"""Return metric name.
Called 'homematic_name' in the json telegram.
"""
return self._name
@property
def is_number(self):
"""Return true if the metric value type is a float number."""
return self._metric_type == "number"
@property
def is_bool(self):
"""Return true if the metric value type is boolean."""
return self._metric_type == "boolean"
@property
def is_string(self):
"""Return true if the metric value type is a string."""
return self._metric_type == "string"
@property
def description(self):
"""Return metric description."""
return self._description
@property
def unit_of_measurement(self):
"""Return metric unit of measurement.
Returns an empty string for boolean and string metrics.
"""
return self._unit_of_measurement
@property
def value(self):
"""Return the metric value.
The returned value is either a float, bool or string depending on the
metric type.
"""
return self._value
def convert_value(var):
"""Convert the metric value from string into python type."""
if var["type"] == "number":
return float(var["value"])
if var["type"] == "boolean":
return var["value"] == "true"
if var["type"] == "string":
return var["value"]
print("can't convert unknown type {} for var {}".format(var["type"], var["name"]))
return None
class WiffiMetricFromSystemInfo:
"""Representation of wiffi metric reported in json telegram."""
def __init__(self, name, uom, metric_type, value):
"""Initialize the instance."""
self._name = name
self._metric_type = metric_type
self._unit_of_measurement = uom
if metric_type == "number":
self._value = float(value)
elif metric_type == "bool":
self._value = value == "true"
else:
self._value = value
@property
def id(self):
"""Return integer based metric id."""
return hash(self._name)
@property
def name(self):
"""Return metric name."""
return self._name
@property
def is_number(self):
"""Return true if the metric value type is a float number."""
return self._metric_type == "number"
@property
def is_bool(self):
"""Return true if the metric value type is boolean."""
return self._metric_type == "boolean"
@property
def is_string(self):
"""Return true if the metric value type is a string."""
return self._metric_type == "string"
@property
def description(self):
"""Return metric description."""
return self._name
@property
def unit_of_measurement(self):
"""Return metric unit of measurement.
Returns an empty string for boolean and string metrics.
"""
return self._unit_of_measurement
@property
def value(self):
"""Return the metric value.
The returned value is either a float, bool or string depending on the
metric type.
"""
return self._value
class WiffiDevice:
"""Representation of wiffi device properties reported in the json telegram."""
def __init__(self, moduletype, data, configuration_url):
"""Initialize the instance."""
self._moduletype = moduletype
self._mac_address = data["MAC-Adresse"]
self._dest_ip = data["Homematic_CCU_ip"]
self._wlan_ssid = data["WLAN_ssid"]
self._wlan_signal_strength = float(data["WLAN_Signal_dBm"])
self._sw_version = data["firmware"]
self._configuration_url = configuration_url
@property
def moduletype(self):
"""Return the wiffi device type, e.g. 'weatherman'."""
return self._moduletype
@property
def mac_address(self):
"""Return the mac address of the wiffi device."""
return self._mac_address
@property
def dest_ip(self):
"""Return the destination ip address for json telegrams."""
return self._dest_ip
@property
def wlan_ssid(self):
"""Return the configured WLAN ssid."""
return self._wlan_ssid
@property
def wlan_signal_strength(self):
"""Return the measured WLAN signal strength in dBm."""
return self._wlan_signal_strength
@property
def sw_version(self):
"""Return the firmware revision string of the wiffi device."""
return self._sw_version
@property
def configuration_url(self):
"""Return the URL to the web interface of the wiffi device."""
return self._configuration_url
class WiffiConnection:
"""Representation of a TCP connection between a wiffi device and the server.
The following behaviour has been observed with weatherman firmware 107:
For every json telegram which has to be sent by the wiffi device to the TCP
server, a new TCP connection will be opened. After 1 json telegram has been
transmitted, the connection will be closed again. The telegram is terminated
by a 0x04 character. Therefore we read until we receive a 0x04 character and
parse the whole telegram afterwards. Then we wait for the next telegram, but
the connection will be closed by the wiffi device. Therefore we get an
'IncompleteReadError exception which we will ignore. We don't close the
connection on our own, because the behaviour that the wiffi device closes
the connection after every telegram may change in the future.
"""
def __init__(self, server):
"""Initialize the instance."""
self._server = server
async def __call__(self, reader, writer):
"""Process callback from the TCP server if a new connection has been opened."""
peername = writer.get_extra_info("peername")
while not reader.at_eof():
try:
data = await reader.readuntil(
b"\x04"
) # read until separator \x04 received
await self.parse_msg(peername, data[:-1]) # omit separator with [:-1]
except asyncio.IncompleteReadError:
pass
async def parse_msg(self, peername, raw_data):
"""Parse received telegram which is terminated by 0x04."""
data = json.loads(raw_data.decode("utf-8"))
moduletype = data["modultyp"]
systeminfo = data["Systeminfo"]
configuration_url = f"http://{peername[0]}"
metrics = []
for var in data["vars"]:
metrics.append(WiffiMetric(var))
metrics.append(WiffiMetricFromSystemInfo("rssi", "dBm", "number", data["Systeminfo"]["WLAN_Signal_dBm"]))
metrics.append(WiffiMetricFromSystemInfo("uptime", "s", "number", data["Systeminfo"]["sec_seit_reset"]))
metrics.append(WiffiMetricFromSystemInfo("ssid", None, "string", data["Systeminfo"]["WLAN_ssid"]))
if self._server.callback is not None:
await self._server.callback(WiffiDevice(moduletype, systeminfo, configuration_url), metrics)
class WiffiTcpServer:
"""Manages TCP server for wiffi devices.
Opens a single port and listens for incoming TCP connections.
"""
def __init__(self, port, callback=None):
"""Initialize instance."""
self.port = port
self.callback = callback
self.server = None
async def start_server(self):
"""Start TCP server on configured port."""
self.server = await asyncio.start_server(WiffiConnection(self), port=self.port)
async def close_server(self):
"""Close TCP server."""
if self.server is not None:
self.server.close()
await self.server.wait_closed()
|