diff --git a/homeassistant/components/mqtt/__init__.py b/homeassistant/components/mqtt/__init__.py index 24a19494d41..b2884a0ff34 100644 --- a/homeassistant/components/mqtt/__init__.py +++ b/homeassistant/components/mqtt/__init__.py @@ -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: diff --git a/homeassistant/components/sensor/mqtt.py b/homeassistant/components/sensor/mqtt.py index f2608bd1657..64a8852d06e 100644 --- a/homeassistant/components/sensor/mqtt.py +++ b/homeassistant/components/sensor/mqtt.py @@ -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. """ diff --git a/homeassistant/components/switch/mqtt.py b/homeassistant/components/switch/mqtt.py index a94ebe6b6b1..eeb4551b921 100644 --- a/homeassistant/components/switch/mqtt.py +++ b/homeassistant/components/switch/mqtt.py @@ -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. """