refactor format mqtt format parser
parent
b4cf0e874a
commit
799043dc0a
|
@ -129,13 +129,24 @@ def setup(hass, config):
|
|||
return True
|
||||
|
||||
|
||||
class JsonFmtParser(object):
|
||||
""" Implements a json parser on xpath"""
|
||||
def __init__(self, jsonpath):
|
||||
self._expr = jsonpath_rw.parse(jsonpath)
|
||||
class FmtParser(object):
|
||||
""" wrapper for all supported formats """
|
||||
|
||||
class _JsonFmtParser(object):
|
||||
""" Implements a json parser on xpath"""
|
||||
def __init__(self, jsonpath):
|
||||
self._expr = jsonpath_rw.parse(jsonpath)
|
||||
def __call__(self, payload):
|
||||
match = self._expr.find(json.loads(payload))
|
||||
return match[0].value if len(match) > 0 else None
|
||||
|
||||
def __init__(self, fmt):
|
||||
if fmt.startswith('json:'):
|
||||
self._parser = FmtParser._JsonFmtParser(fmt[5:])
|
||||
else:
|
||||
self._parser = lambda x: x
|
||||
def __call__(self, payload):
|
||||
match = self._expr.find(json.loads(payload))
|
||||
return match[0].value if len(match) > 0 else None
|
||||
return self._parser(payload)
|
||||
|
||||
|
||||
# This is based on one of the paho-mqtt examples:
|
||||
|
|
|
@ -47,12 +47,7 @@ class MqttSensor(Entity):
|
|||
self._state_topic = state_topic
|
||||
self._qos = qos
|
||||
self._unit_of_measurement = unit_of_measurement
|
||||
self._state_format = state_format
|
||||
|
||||
if self._state_format.startswith('json:'):
|
||||
self._parser = mqtt.JsonFmtParser(self._state_format[5:])
|
||||
else:
|
||||
self._parser = lambda x: x
|
||||
self._parser = mqtt.FmtParser(state_format)
|
||||
|
||||
def message_received(topic, payload, qos):
|
||||
""" A new MQTT message has been received. """
|
||||
|
|
|
@ -55,13 +55,7 @@ class MqttSwitch(SwitchDevice):
|
|||
self._payload_on = payload_on
|
||||
self._payload_off = payload_off
|
||||
self._optimistic = optimistic
|
||||
|
||||
self._state_format = state_format
|
||||
|
||||
if self._state_format.startswith('json:'):
|
||||
self._parser = mqtt.JsonFmtParser(self._state_format[5:])
|
||||
else:
|
||||
self._parser = lambda x: x
|
||||
self._parser = mqtt.FmtParser(state_format)
|
||||
|
||||
def message_received(topic, payload, qos):
|
||||
""" A new MQTT message has been received. """
|
||||
|
|
Loading…
Reference in New Issue