refactor format mqtt format parser

pull/647/head
Oliver van Porten 2015-11-20 22:45:09 +01:00
parent b4cf0e874a
commit 799043dc0a
3 changed files with 19 additions and 19 deletions

View File

@ -129,13 +129,24 @@ def setup(hass, config):
return True return True
class JsonFmtParser(object): class FmtParser(object):
""" Implements a json parser on xpath""" """ wrapper for all supported formats """
def __init__(self, jsonpath):
self._expr = jsonpath_rw.parse(jsonpath) 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): def __call__(self, payload):
match = self._expr.find(json.loads(payload)) return self._parser(payload)
return match[0].value if len(match) > 0 else None
# This is based on one of the paho-mqtt examples: # This is based on one of the paho-mqtt examples:

View File

@ -47,12 +47,7 @@ class MqttSensor(Entity):
self._state_topic = state_topic self._state_topic = state_topic
self._qos = qos self._qos = qos
self._unit_of_measurement = unit_of_measurement self._unit_of_measurement = unit_of_measurement
self._state_format = state_format self._parser = mqtt.FmtParser(state_format)
if self._state_format.startswith('json:'):
self._parser = mqtt.JsonFmtParser(self._state_format[5:])
else:
self._parser = lambda x: x
def message_received(topic, payload, qos): def message_received(topic, payload, qos):
""" A new MQTT message has been received. """ """ A new MQTT message has been received. """

View File

@ -55,13 +55,7 @@ class MqttSwitch(SwitchDevice):
self._payload_on = payload_on self._payload_on = payload_on
self._payload_off = payload_off self._payload_off = payload_off
self._optimistic = optimistic self._optimistic = optimistic
self._parser = mqtt.FmtParser(state_format)
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
def message_received(topic, payload, qos): def message_received(topic, payload, qos):
""" A new MQTT message has been received. """ """ A new MQTT message has been received. """