示例#1
0
 def publish(self, topic, value, qos=None, retain=None):
     """
     Publishes a value to a given topic, uses pre-loaded values for QoS and retain
     """
     qos = qos if qos is not None else self.qos
     retain = retain if retain is not None else self.retain
     Mosquitto.publish(self, topic, str(value), qos, retain)
示例#2
0
 def connect(self):
     """
     Connects to the Mosquitto broker with the pre-configured parameters
     """
     if self.set_will:
         self.will_set(self.status_topic, "0", self.qos, self.retain)
     _Mosquitto.connect(self, self.host, self.port, self.keepalive)
示例#3
0
 def publish(self, topic, value, qos=None, retain=None):
     """
     Publishes a value to a given topic, uses pre-loaded values for QoS and retain
     """
     qos = qos if qos is not None else self.qos
     retain = retain if retain is not None else self.retain
     Mosquitto.publish(self, topic, str(value), qos, retain)
示例#4
0
 def connect(self):
     """
     Connects to the Mosquitto broker with the pre-configured parameters
     """
     if self.set_will:
         self.will_set(self.status_topic, "0", self.qos, self.retain)
     _Mosquitto.connect(self, self.host, self.port, self.keepalive)
示例#5
0
	def __init__(self, config):
		self.config = config
		Mosquitto.__init__( self, config['client'] )

		self.__init_mqtt_callbacks()
		self.connect(config['server'])
		self.__init_channels(config['channels'])
		self.live = threading.Thread( target = self.live_threaded )
		self.live.start()
示例#6
0
 def connect(self):
     """
     Connects to the Mosquitto broker with the pre-configured parameters
     """
     self.on_connect = self._on_connect
     self.on_message = self._on_message
     self.on_disconnect = self._on_disconnect
     self.on_subscribe = self._on_subscribe
     self.on_log = self._on_log
     if self.set_will:
         self.will_set(self.status_topic % self._client_id, "0", self.qos, self.retain)
     self.log(logging.INFO, "Connecting to MQTT broker")
     Mosquitto.connect(self, self.host, self.port, self.keepalive)
示例#7
0
 def connect(self):
     """
     Connects to the Mosquitto broker with the pre-configured parameters
     """
     self.on_connect = self._on_connect
     self.on_message = self._on_message
     self.on_disconnect = self._on_disconnect
     self.on_subscribe = self._on_subscribe
     self.on_log = self._on_log
     if self.set_will:
         self.will_set(self.status_topic % self._client_id, "0", self.qos,
                       self.retain)
     self.log(logging.INFO, "Connecting to MQTT broker")
     Mosquitto.connect(self, self.host, self.port, self.keepalive)
示例#8
0
class LogSender(object):

    def __init__(self):
        '''
        Constructor
        '''
        self.client = Mosquitto(str(random.randint(100000, 999999)))
    
    def connect(self):
        self.client.connect(MqttConfig.MQTT_SERVER_URL)
    
    def sendLog(self, topic, logMessage):
        try:
            logJson = json.dumps(logMessage, default=lambda o: o.__dict__, indent=2)
            retVal = self.client.publish(topic, logJson, 1)
            if retVal[0] != 0:
                self.connect()
        except ValueError:
            pass
示例#9
0
class MqttTransport(BaseTransport):
    def __init__(self, beaver_config, logger=None):
        """
        Mosquitto client initilization. Once this this transport is initialized
        it has invoked a connection to the server
        """
        super(MqttTransport, self).__init__(beaver_config, logger=logger)

        self._client = Mosquitto(beaver_config.get('mqtt_clientid'),
                                 clean_session=True)
        self._topic = beaver_config.get('mqtt_topic')
        self._client.connect(host=beaver_config.get('mqtt_hostname'),
                             port=beaver_config.get('mqtt_port'),
                             keepalive=beaver_config.get('mqtt_keepalive'))

        def on_disconnect(mosq, obj, rc):
            if rc == 0:
                logger.debug('Mosquitto has successfully disconnected')
            else:
                logger.debug('Mosquitto unexpectedly disconnected')

        self._client.on_disconnect = on_disconnect

    def callback(self, filename, lines, **kwargs):
        """publishes lines one by one to the given topic"""
        timestamp = self.get_timestamp(**kwargs)
        if kwargs.get('timestamp', False):
            del kwargs['timestamp']

        for line in lines:
            try:
                import warnings
                with warnings.catch_warnings():
                    warnings.simplefilter('error')
                    self._client.publish(
                        self._topic,
                        self.format(filename, line, timestamp, **kwargs), 0)
            except Exception, e:
                try:
                    raise TransportException(e.strerror)
                except AttributeError:
                    raise TransportException(
                        'Unspecified exception encountered')
示例#10
0
class MosquittoTransport(BaseTransport):

    def __init__(self, beaver_config, file_config, logger=None):
        """
        Mosquitto client initilization. Once this this transport is initialized
        it has invoked a connection to the server
        """
        super(MosquittoTransport, self).__init__(beaver_config, file_config, logger=logger)

        self._file_config = file_config
        self._client = Mosquitto(beaver_config.get('mqtt_clientid'), clean_session=True)
        self._topic = beaver_config.get('mqtt_topic')
        self._client.connect(
            host=beaver_config.get('mqtt_hostname'),
            port=beaver_config.get('mqtt_port'),
            keepalive=beaver_config.get('mqtt_keepalive')
        )

        def on_disconnect(mosq, obj, rc):
            if rc == 0:
                logger.debug('Mosquitto has successfully disconnected')
            else:
                logger.debug('Mosquitto unexpectedly disconnected')

        self._client.on_disconnect = on_disconnect

    def callback(self, filename, lines, **kwargs):
        """publishes lines one by one to the given topic"""
        timestamp = self.get_timestamp(**kwargs)
        if kwargs.get('timestamp', False):
            del kwargs['timestamp']

        for line in lines:
            try:
                import warnings
                with warnings.catch_warnings():
                    warnings.simplefilter('error')
                    self._client.publish(self._topic, self.format(filename, line, timestamp, **kwargs), 0)
            except Exception, e:
                try:
                    raise TransportException(e.strerror)
                except AttributeError:
                    raise TransportException('Unspecified exception encountered')
示例#11
0
 def subscribe(self, topics):
     """
     Publishes a value to a given topic, uses pre-loaded values for QoS and retain
     """
     if not isinstance(topics, list):
         topics = [topics]
     for topic in topics:
         rc, mid = Mosquitto.subscribe(self, topic, 0)
         self._subscriptions[mid] = topic
         self.log(logging.INFO, "Sent subscription request to topic %s" % topic)
示例#12
0
 def subscribe(self, topics):
     """
     Publishes a value to a given topic, uses pre-loaded values for QoS and retain
     """
     if not isinstance(topics, list):
         topics = [topics]
     for topic in topics:
         rc, mid = Mosquitto.subscribe(self, topic, 0)
         self._subscriptions[mid] = topic
         self.log(logging.INFO,
                  "Sent subscription request to topic %s" % topic)
示例#13
0
    def __init__(self, beaver_config, logger=None):
        """
        Mosquitto client initilization. Once this this transport is initialized
        it has invoked a connection to the server
        """
        super(MqttTransport, self).__init__(beaver_config, logger=logger)

        self._client = Mosquitto(beaver_config.get('mqtt_clientid'),
                                 clean_session=True)
        self._topic = beaver_config.get('mqtt_topic')
        self._client.connect(host=beaver_config.get('mqtt_hostname'),
                             port=beaver_config.get('mqtt_port'),
                             keepalive=beaver_config.get('mqtt_keepalive'))

        def on_disconnect(mosq, obj, rc):
            if rc == 0:
                logger.debug('Mosquitto has successfully disconnected')
            else:
                logger.debug('Mosquitto unexpectedly disconnected')

        self._client.on_disconnect = on_disconnect
示例#14
0
    def __init__(self, beaver_config, logger=None):
        """
        Mosquitto client initilization. Once this this transport is initialized
        it has invoked a connection to the server
        """
        super(MosquittoTransport, self).__init__(beaver_config, logger=logger)

        self._client = Mosquitto(beaver_config.get('mqtt_clientid'), clean_session=True)
        self._topic = beaver_config.get('mqtt_topic')
        self._client.connect(
            host=beaver_config.get('mqtt_hostname'),
            port=beaver_config.get('mqtt_port'),
            keepalive=beaver_config.get('mqtt_keepalive')
        )

        def on_disconnect(mosq, obj, rc):
            if rc == 0:
                logger.debug('Mosquitto has successfully disconnected')
            else:
                logger.debug('Mosquitto unexpectedly disconnected')

        self._client.on_disconnect = on_disconnect
示例#15
0
    def __init__(self, client_id):
        client = Mosquitto(client_id, False, self)
        client.will_set(DAEMON_STATUS, OFF, qos=2, retain=True)

        def on_connect(client, self, rc):
            logging.info("MQTT Connected")
            client.publish(DAEMON_STATUS, ON, qos=2, retain=True)
            client.subscribe('home/#')

        def on_disconnect(client, self, rc):
            logging.info("MQTT Disconnected")

        def on_message(client, self, message):
            if self.onMessage is not None:
                self.onMessage(message.topic, message.payload)

        client.on_connect = on_connect
        client.on_disconnect = on_disconnect
        client.on_message = on_message

        self.client = client

        self.publish_queue = Queue()
        self.onMessage = None
def main(args=None):

    global old_config, config_file, retain_hack_topic, hostname, port

    if args is None:
        parser = argparse.ArgumentParser(description="Config generator/updater for wb-mqtt-mbgate")
        parser.add_argument("-c", "--config", help="config file to create/update",
                            type=str, default="")
        parser.add_argument("-f", "--force-create", help="force creating new config file",
                            action="store_true")
        parser.add_argument("-s", "--server", help="MQTT server hostname", type=str, default="localhost")
        parser.add_argument("-p", "--port", help="MQTT server port", type=int, default=1883)

        args = parser.parse_args()

    if args.config == "":
        config_file = sys.stdout
    else:
        if not args.force_create:
            try:
                old_config = json.loads(open(args.config, "r").read())
                if "remap_values" in old_config["registers"]:
                    global remap_values
                    remap_values = old_config["registers"]["remap_values"]
                    del old_config["registers"]["remap_values"]

            except:
                print "Failed to open config"
                pass
        config_file = open(args.config, "w")

    client_id = str(time.time()) + str(random.randint(0, 100000))

    client = Mosquitto(client_id)

    hostname = args.server
    port = args.port

    client.connect(args.server, args.port)

    client.on_message = mqtt_on_message

    client.subscribe("/devices/+/controls/+/meta/+")

    # apply retained-hack to be sure that all data is received
    retain_hack_topic = "/tmp/%s/retain_hack" % (client_id)
    client.subscribe(retain_hack_topic)
    client.publish(retain_hack_topic, '1')

    while 1:
        rc = client.loop()
        if rc != 0:
            break
示例#17
0
 def publish(self, topic, value):
     """
     Publishes a value to a given topic, uses pre-loaded values for QoS and retain
     """
     _Mosquitto.publish(self, topic, str(value), self.qos, self.retain)
示例#18
0
        collection = [
            get('Bid'),
            get('Ask'),
            get('High'),
            get('Low'),
            get('Direction'),
            get('Last'),
        ]

        message = '/'.join(
            (c[0].childNodes[0].nodeValue for c in collection)).encode('utf-8')

        print message
        if dates.get(symbol, None) != collection[-1]:
            mq.publish('rates/%s' % symbol, message, qos=1, retain=True)
            dates[symbol] = collection[-1]


if __name__ == '__main__':
    args = parser.parse_args()
    mq = Mosquitto('fxrates')
    mq.connect(args.hostname, args.port, 60)
    try:
        while True:
            sleep(.1)
            getFXRate(mq)
    except KeyboardInterrupt:
        print 'closing...'
        mq.disconnect()
示例#19
0
#!/usr/bin/python
from mosquitto import Mosquitto

publish_key = "demo"
subscribe_key = "demo"
channel_name = "F"
client_uuid = "2fb96def5"
mqtt_hostname = "mqtt.pubnub.com"
mqtt_connect = publish_key + "/" + subscribe_key + "/" + client_uuid
mqtt_topic = publish_key + "/" + subscribe_key + "/" + channel_name
mosq_object = Mosquitto(mqtt_connect)


def on_message(mosq, obj, msg):
    print(msg.payload, msg.topic)


mosq_object.on_message = on_message
mosq_object.connect(mqtt_hostname)
mosq_object.publish(mqtt_topic, "Hello World!")
mosq_object.subscribe(mqtt_topic)
mosq_object.loop_forever()
示例#20
0
 def publish(self, topic, value):
     """
     Publishes a value to a given topic, uses pre-loaded values for QoS and retain
     """
     _Mosquitto.publish(self, topic, str(value), self.qos, self.retain)
示例#21
0
 def __init__(self):
     '''
     Constructor
     '''
     self.client = Mosquitto(str(random.randint(100000, 999999)))
    def setup(self, hostname, port):
        mq = Mosquitto(self.name)
        mq.connect(hostname, port, 60)
        mq.subscribe('chat')
        mq.subscribe('rates/AUDUSD')
        mq.subscribe('rates/USDCHF')
        mq.subscribe('rates/EURUSD')
        mq.subscribe('rates/PLNUSD')
        mq.subscribe('rates/GBPUSD')
        mq.on_message = self.message
        mq.on_connect = connect_cb
        mq.on_subscribe = subscribe_cb
        mq.on_unsubscribe = unsubscribe_cb
        mq.on_publish = publish_cb
        #mq.on_message = message_cb
        mq.on_disconnect = disconnect_cb

        self.mq = mq

        Clock.schedule_interval(lambda *x: mq.loop(), .01)
示例#23
0
def main():
    """start mqtt server and subscribe the topic"""
    # check the number of arguments
    if len(argv) != 6:
        print "usage: %s [hostname] [port] [keepalive] [client_id] [topic]" % argv[
            0]
        exit(1)

    try:
        mqtt_client = Mosquitto(argv[4])

        # set callback
        mqtt_client.on_message = cb_on_message

        # connect to MQTT broker
        # client.connect(hostname, port=1883, keepalive=60)
        mqtt_client.connect(argv[1], argv[2], int(argv[3]))

        # subscribe the topic
        mqtt_client.subscribe(argv[5])
        print "%s subscribing topic '%s' from %s:%s" % (argv[4], argv[5],
                                                        argv[1], argv[2])

        while True:
            # call loop method frequently
            # client.loop(timeout=-1); 0 to return immediately; -1 to return
            # after 1 second.
            result = mqtt_client.loop()
            if result != 0:
                # rc != 0; loop failed
                print "Loop failed (%s), disconnecting..." % result
                mqtt_client.disconnect()
                break

    except KeyboardInterrupt:
        # disconnect from the broker
        mqtt_client.disconnect()
        print "Disconnected..."
示例#24
0
def on_connect(mosq, obj, rc):
    mosq.subscribe("8dev/response", 0)
    print("rc: "+str(rc))

def on_message(mosq, obj, msg):
    print("response:"+msg.topic+" "+str(msg.qos)+" "+str(msg.payload))

def on_publish(mosq, obj, mid):
    print("mid: "+str(mid))

def on_subscribe(mosq, obj, mid, granted_qos):
    print("Subscribed: "+str(mid)+" "+str(granted_qos))

def on_log(mosq, obj, level, string):
    print(string)

mqttc = Mosquitto()
mqttc.on_message = on_message
mqttc.on_connect = on_connect
mqttc.on_publish = on_publish
mqttc.on_subscribe = on_subscribe
# Uncomment to enable debug messages
#mqttc.on_log = on_log
#mqttc.connect("test.mosquitto.org", 1883, 60)
mqttc.connect("192.168.101.96", 1883, 60)
while True:
    mqttc.loop(1, 1)
    cmd = raw_input("Enter command for remote: ")
    mqttc.publish("8dev/cmd", cmd)
    mqttc.loop(1, 2)