Ejemplo n.º 1
0
def mqtt_on_message(arg0, arg1, arg2=None):
    msg = arg2 or arg1

    print >>sys.stderr, msg.topic

    if msg.topic == retain_hack_topic:
        print >>config_file, json.dumps(process_table(table), indent=True)
        sys.exit(0)

    if msg.retain:
        if not topic_matches_sub("/devices/+/controls/name", msg.topic):
            if get_dev_name(msg.topic) not in table:
                table[get_dev_name(msg.topic)] = {} # {"meta_type": "text"}

        dname = get_dev_name(msg.topic)
        if topic_matches_sub("/devices/+/controls/+/meta/type", msg.topic):
            table[dname]["meta_type"] = msg.payload
            # FIXME: crazy read-onlys
            if "readonly" not in table[dname]:
                if msg.payload in ["switch", "pushbutton", "range", "rgb"]:
                    table[dname]["readonly"] = False
                else:
                    table[dname]["readonly"] = True
        elif topic_matches_sub("/devices/+/controls/+", msg.topic):
            table[dname]["value"] = msg.payload
        elif topic_matches_sub("/devices/+/controls/+/meta/readonly", msg.topic):
            if int(msg.payload) == 1:
                table[dname]["readonly"] = True
Ejemplo n.º 2
0
    def on_mqtt_message(self, mosq, obj, msg):
        try:
            #~ print "on_mqtt_message " , msg.topic
            parts = msg.topic.split('/')

            if mosquitto.topic_matches_sub(
                    '/devices/%s/meta/+' % self.mqtt_device_id, msg.topic):
                name = parts[4]
                self.on_config_parameter_received(name, msg.payload)

            elif msg.topic == self.random_topic:
                self.on_initial_retained_received()
            elif mosquitto.topic_matches_sub('/devices/+/controls/+/on',
                                             msg.topic):

                device_id = parts[2]
                control = parts[4]

                for device in self.devices:
                    if device.device_id == device_id:
                        ret = device.update_control(control, msg.payload)
                        if ret is not None:
                            self.client.publish(
                                "/devices/%s/controls/%s" %
                                (device_id, control), ret, 0, True)

                        break
                else:
                    print "unknown device id ", device_id

        except:
            import traceback
            traceback.print_exc()
Ejemplo n.º 3
0
    def on_mqtt_message(self, arg0, arg1, arg2=None):
        st = time.time()
        if arg2 is None:
            mosq, obj, msg = None, arg0, arg1
        else:
            mosq, obj, msg = arg0, arg1, arg2
        # if msg.retain:
        #     return

        if mosquitto.topic_matches_sub(VALUES_MASK, msg.topic):
            self.control_values[self._get_channel(
                msg.topic)].value = msg.payload
        elif mosquitto.topic_matches_sub(ERRORS_MASK, msg.topic):
            self.control_values[self._get_channel(
                msg.topic)].error = msg.payload or None
Ejemplo n.º 4
0
    def on_mqtt_message(self, mosq, obj, msg):
        """ return True if the message was indeed an rpc call"""

        if not mosquitto.topic_matches_sub('/rpc/v1/+/+/+/%s/reply' % self.rpc_client_id, msg.topic):
            return


        parts = msg.topic.split('/')
        driver_id = parts[3]
        service_id = parts[4]
        method_id = parts[5]
        client_id = parts[6]


        result = MQTTRPC10Response.from_json(msg.payload.decode('utf8'))

        future = self.futures.pop((driver_id, service_id, method_id, result._id), None)
        if future is None:
            return True

        if result.error:
            future.set_exception(MQTTRPCError(result.error['message'], result.error['code'], result.error['data']))

        future.set_result(result.result)

        return True
Ejemplo n.º 5
0
    def on_mqtt_message(self, mosq, obj, msg):
        """ return True if the message was indeed an rpc call"""

        if not mosquitto.topic_matches_sub(
                '/rpc/v1/+/+/+/%s/reply' % self.rpc_client_id, msg.topic):
            return

        parts = msg.topic.split('/')
        driver_id = parts[3]
        service_id = parts[4]
        method_id = parts[5]
        client_id = parts[6]

        result = MQTTRPC10Response.from_json(msg.payload.decode('utf8'))

        future = self.futures.pop(
            (driver_id, service_id, method_id, result._id), None)
        if future is None:
            return True

        if result.error:
            future.set_exception(
                MQTTRPCError(result.error['message'], result.error['code'],
                             result.error['data']))

        future.set_result(result.result)

        return True
Ejemplo n.º 6
0
    def on_mqtt_message(self, mosq, obj, msg):
        """ return True if the message was indeed an rpc call"""
        print msg.topic
        print msg.payload

        if not mosquitto.topic_matches_sub("/rpc/v1/+/+/+/%s/reply" % self.rpc_client_id, msg.topic):
            return

        parts = msg.topic.split("/")
        driver_id = parts[3]
        service_id = parts[4]
        method_id = parts[5]
        client_id = parts[6]

        result = MQTTRPC10Response.from_json(msg.payload)

        future = self.futures.pop((driver_id, service_id, method_id, result._id), None)
        if future is None:
            return True

        if result.error:
            future.set_exception(RuntimeError(result.error))

        future.set_result(result.result)

        return True
    def on_mqtt_message(self, mosq, obj, msg):
        if self.rpc_client.on_mqtt_message(mosq, obj, msg):
            return

        if not self.live_mode:
            return

        if not mosquitto.topic_matches_sub('/devices/+/controls/+', msg.topic):
            return

        parts = msg.topic.split('/')
        device_id = parts[2]
        control_id = parts[4]

        channel_id = self.channel_map.get((device_id, control_id))
        if channel_id:
            try:
                self.live_queue.put_nowait(
                    (datetime.datetime.now(), channel_id, msg.payload))
            except Queue.Full, exc:
                logging.info("Setting live_mode to false")
                self.live_mode = False

                # do not call Queue methods inside 'with' block!
                # Queue.join() won't work after clearing in this way
                with self.live_queue.mutex:
                    self.live_queue.queue.clear()
    def on_mqtt_message(self, mosq, obj, msg):
        if self.rpc_client.on_mqtt_message(mosq, obj, msg):
            return


        if not self.live_mode:
            return

        if not mosquitto.topic_matches_sub('/devices/+/controls/+', msg.topic):
            return

        parts = msg.topic.split('/')
        device_id = parts[2]
        control_id = parts[4]

        channel_id  = self.channel_map.get((device_id, control_id))
        if channel_id:
            try:
                self.live_queue.put_nowait((datetime.datetime.now(), channel_id, msg.payload))
            except Queue.Full, exc:
                logging.info("Setting live_mode to false")
                self.live_mode = False

                # do not call Queue methods inside 'with' block!
                # Queue.join() won't work after clearing in this way
                with self.live_queue.mutex:
                    self.live_queue.queue.clear()
Ejemplo n.º 9
0
def on_message(mosq, userdata, msg):

    sock = userdata['sock']
    host = userdata['carbon_server']
    port = userdata['carbon_port']
    lines = []
    now = int(time.time())

    map = userdata['map']
    # Find out how to handle the topic in this message: slurp through
    # our map 
    for t in map:
        if mosquitto.topic_matches_sub(t, msg.topic):
            # print "%s matches MAP(%s) => %s" % (msg.topic, t, map[t])

            # Must we rename the received msg topic into a different
            # name for Carbon? In any case, replace MQTT slashes (/)
            # by Carbon periods (.)
            (type, remap) = map[t]
            if remap is None:
                carbonkey = msg.topic.replace('/', '.')
            else:
                carbonkey = remap.replace('/', '.')
            logging.debug("CARBONKEY is [%s]" % carbonkey)

            if type == 'n':
                '''Number: obtain a float from the payload'''
                try:
                    number = float(msg.payload)
                    lines.append("%s %f %d" % (carbonkey, number, now))
                except ValueError:
                    logging.info("Topic %s contains non-numeric payload [%s]" % 
                            (msg.topic, msg.payload))
                    return

            elif type == 'j':
                '''JSON: try and load the JSON string from payload and use
                   subkeys to pass to Carbon'''
                try:
                    st = json.loads(msg.payload)
                    for k in st:
                        if is_number(st[k]):
                            lines.append("%s.%s %f %d" % (carbonkey, k, float(st[k]), now))
                except:
                    logging.info("Topic %s contains non-JSON payload [%s]" %
                            (msg.topic, msg.payload))
                    return

            else:
                logging.info("Unknown mapping key [%s]", type)
                return

            message = '\n'.join(lines) + '\n'
            logging.debug("%s", message)

            sock.sendto(message, (host, port))
Ejemplo n.º 10
0
def on_message(mosq, userdata, msg):

    sock = userdata['sock']
    host = userdata['carbon_server']
    port = userdata['carbon_port']
    lines = []
    now = int(time.time())

    map = userdata['map']
    # Find out how to handle the topic in this message: slurp through
    # our map 
    for t in map:
        if mosquitto.topic_matches_sub(msg.topic, t):
            # print "%s matches MAP(%s) => %s" % (msg.topic, t, map[t])

            # Must we rename the received msg topic into a different
            # name for Carbon? In any case, replace MQTT slashes (/)
            # by Carbon periods (.)
            (type, remap) = map[t]
            if remap is None:
                carbonkey = msg.topic.replace('/', '.')
            else:
                carbonkey = remap.replace('/', '.')
            logging.debug("CARBONKEY is [%s]" % carbonkey)

            if type == 'n':
                '''Number: obtain a float from the payload'''
                try:
                    number = float(msg.payload)
                    lines.append("%s %f %d" % (carbonkey, number, now))
                except ValueError:
                    logging.info("Topic %s contains non-numeric payload [%s]" % 
                            (msg.topic, msg.payload))
                    return

            elif type == 'j':
                '''JSON: try and load the JSON string from payload and use
                   subkeys to pass to Carbon'''
                try:
                    st = json.loads(msg.payload)
                    for k in st:
                        if is_number(st[k]):
                            lines.append("%s.%s %f %d" % (carbonkey, k, float(st[k]), now))
                except:
                    logging.info("Topic %s contains non-JSON payload [%s]" %
                            (msg.topic, msg.payload))
                    return

            else:
                logging.info("Unknown mapping key [%s]", type)
                return

            message = '\n'.join(lines) + '\n'
            logging.debug("%s", message)

            sock.sendto(message, (host, port))
Ejemplo n.º 11
0
    def on_mqtt_message(self, arg0, arg1, arg2=None):
        if arg2 is None:
            mosq, obj, msg = None, arg0, arg1
        else:
            mosq, obj, msg = arg0, arg1, arg2

        if mosquitto.topic_matches_sub(VALUES_MASK, msg.topic):
            parts = msg.topic.split('/')
            device_id = parts[2]
            control_id = parts[4]

            self.control_values[(device_id, control_id)] = msg.payload
Ejemplo n.º 12
0
    def on_mqtt_message(self, mosq, obj, msg):
        try:
            #~ print "on_mqtt_message " , msg.topic
            parts = msg.topic.split('/')

            if mosquitto.topic_matches_sub('/devices/%s/meta/+' % self.mqtt_device_id, msg.topic):
                name = parts[4]
                self.on_config_parameter_received(name, msg.payload)




            elif msg.topic == self.random_topic:
                self.on_initial_retained_received()
            elif mosquitto.topic_matches_sub('/devices/+/controls/+/on' , msg.topic):

                device_id = parts[2]
                control = parts[4]




                for device in self.devices:
                    if device.device_id == device_id:
                        ret = device.update_control(control, msg.payload)
                        if ret is not None:
                            self.client.publish("/devices/%s/controls/%s" % (device_id, control), ret, 0, True)


                        break
                else:
                    print "unknown device id ", device_id

        except:
            import traceback
            traceback.print_exc()
Ejemplo n.º 13
0
    def _on_mqtt_message(self, mosq, obj, msg):
        logging.debug("got mqtt message on topic %s" % msg.topic)
        if not mosquitto.topic_matches_sub('/devices/+/controls/#', msg.topic):
            return

        parts = msg.topic.split('/')
        device_id = parts[2].decode('utf8')
        control_id = parts[4].decode('utf8')

        channel = (device_id, control_id)

        # ignore retained values
        if msg.retain:
            return

        logging.debug("%s/%s <= %s" % (channel[0], channel[1], msg.payload))
        self.on_channel_value(self._format_channel(channel), msg.payload)
Ejemplo n.º 14
0
 def _deliver_message(self, message):
     for sub in self._subscriptions:
         if topic_matches_sub(sub, message.topic):
             self.on_message(self, self._userdata, message)