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)
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)
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
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)
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)
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')
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
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')
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)
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..."
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)
#!/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()
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()