def __init__(self, host="localhost"): self.subscribed_topic2method = { "scrolly/write_scroll": self.write_scroll, "scrolly/write": self.write, "scrolly/power": self.power, "scrolly/brightness": self.set_brightness } scroll.flip(x=True, y=True) scroll.set_brightness(0.2) scroll.clear() scroll.write_string("on") scroll.show() status_topic = "scrolly/status" self.mos = mosquitto.Mosquitto() self.mos.will_set(status_topic, "offline") self.mos.on_message = self.on_message self.debug("connecting to " + host) self.mos.connect(host) self.mos.publish("scrolly/power", 1) self.mos.publish(status_topic, "online") self.mos.subscribe("scrolly/#") self.stop_event = threading.Event() # start thread that is waiting for action in bluedot app th = threading.Thread(target=self._shutdown_on_bluedot_press_waiter) th.start() self.mos.loop_forever()
def __init__(self, session_token, username): self.status = "" self.status_msg = "" self.chat_msg = "" self.chat_log = [] self.window = None self.log = None self.status = None self.chat = None self.HAS_COLORS = False self.CAN_CHANGE_COLORS = False self.USER_FORMAT = (-1, -1) self.DIV_CHAR = "=" self.USER_NAME = "" self.USERS = [] self.SESSION_TOKEN = session_token self.USER_NAME = username self.client = mosquitto.Mosquitto(username) self.client.on_connect = self.on_connect self.client.on_message = self.on_message self.client.on_disconnect = self.on_disconnect # local #self.client.connect("127.0.0.1",port=1883) # server self.client.connect("184.154.221.154", port=1883)
def setUpClass(self): self.client = mosquitto.Mosquitto("pubsubclient_ut", clean_session=True, obj=self) self.client.connect(settings.server_ip) self.client.on_message = on_message self.client.subscribe("outTopic", 0)
def main(): # Start with all off p.pinAllOff() signal.signal(signal.SIGTERM, term_handler) broker = "pi-server" port = 1883 mypid = os.getpid() sub_uniq = "subclient_"+str(mypid) mqtts = mosquitto.Mosquitto(sub_uniq) mqtts.on_connect = on_connect mqtts.on_message = on_message while True: mqtts.connect(broker, port, 60) mqtts.subscribe("relay/#", 0) try: rc = 0 while rc == 0: rc = mqtts.loop() # syslog.syslog('Try: Exception caught rc:' +str(rc)) except Exception as inst: p.pinAllOff() print type(inst) print inst.args print inst mqtts.disconnect() syslog.syslog(syslog.LOG_ERR, 'Except: Exception caught'+str(inst)) return 4
def main(): ## Command line arguments parser = argparse.ArgumentParser() parser.add_argument("--host", default="test.mosquitto.org") args = parser.parse_args() brokerHost = args.host ## setup MQTT client client = mosquitto.Mosquitto() client.on_message = on_message client.on_disconnect = on_disconnect try: client.connect(brokerHost) except: print("failed to connect") on_disconnect(client, None, None) ## subscribe to topics for ctopic in topicconfig.outlet_topics: client.subscribe(ctopic['topic']) while True: client.loop()
def main(): ser = open_AIS_connection() ser.close() ser.open() rc = 0 mqttc = mosquitto.Mosquitto() mqttc.on_connect = on_connect # mqttc.on_publish = on_publish try: mqttc.connect("winter.ceit.uq.edu.au", 1883, 60) except: logger.error('Cannot connect to MQTT server') sys.exit(1) while mqttc.loop() == 0: try: line = ser.readline() logger.debug('Raw AIS: %s', line) if line.startswith('!AIVDM,'): logger.debug('Useful line: %s', line) s = process_line(line) if len(s) > 0: logger.debug('Processed line: %s', s) mqttc.publish("/uq/ferry/raw", line, 0) mqttc.publish("/uq/ferry/JSON", s, 0) except KeyboardInterrupt: logger.info('Program closed via keyboard') sys.exit(0) except: pass ser.close()
def __init__(self, server): self.server = server self.client = mosquitto.Mosquitto("Daidokoro-monitor", userdata=self) self.connected = False self.on_connect = None def on_connect(mosq, self, rc): if rc != 0: log("Cannot connect to server. Exit.") sys.exit(255) log("Connected successfully.") self.connected = True if self.on_connect: self.on_connect() def on_disconnect(mosq, self, rc): log("Disconnected. Try to connect again.") self.connected = False self.reconnect() self.client.on_connect = on_connect self.client.on_disconnect = on_disconnect
def __init__(self, clientid="", msg_cb=None): if paho: self.client = mqtt.Client(clientid, protocol=mqtt.MQTTv31) self.client.on_message = msg_cb else: self.client = mosquitto.Mosquitto(clientid) self.client.connect("localhost", 1883, 60 * 60)
def __init__(self, file=None, host=None): """ Make a database writing librarian, listening to packets from host, and writing into the the sqlite3 file specified. Defaults provided match my own personal environment. If the database file is not found, or does not contain the appropriate tables and indexes, it is created """ self.log = logging.getLogger("alexandria.Librarian") if file is None: file = config['library_file'] try: self.conn = sqlite3.connect(file) except sqlite3.OperationalError as ex: self.log.error(ex) raise ex self.log.debug("library exists, validating schema") self.cur = self.conn.cursor() try: self.cur.execute('select * from karlnet_sensor') except sqlite3.OperationalError as ex: if string.find(str(ex), "no such table: karlnet_sensor") != -1: self.log.debug( "karlnet_sensor table didn't exist, creating it!") self.cur.execute(config['create_sql']) self.cur.execute(config['create_index']) self.log.debug("library is valid, connecting to mq") if host is None: host = config['mq_host'] # FIXME - get clientid here... clientid = "karlnet_alexandria@%s/%d" % (socket.gethostname(), os.getpid()) self.mqttc = mosquitto.Mosquitto(clientid, obj=self) self.log.info( "Valid library and messaging is up, starting to write books!")
def main(): parser = argparse.ArgumentParser(description="homA device simulator", add_help=False) parser.add_argument("-h", "--host", dest="host", type=str, help="MQTT host", default="localhost") parser.add_argument("-p", "--port", dest="port", type=int, help="MQTT port", default="1883") args = parser.parse_args() client = mosquitto.Mosquitto("simulate") client.on_connect = on_connect client.on_message = on_message client.connect(args.host, args.port) while True: rc = client.loop() if rc != 0: break
def main(): ## Command line arguments parser = argparse.ArgumentParser() parser.add_argument("--host", default="192.168.8.2") args = parser.parse_args() brokerHost = args.host fridgelyse = FridgeAnalys(nsamples=4) ## setup MQTT client client = mosquitto.Mosquitto() client.on_message = on_message client.on_disconnect = on_disconnect client.on_connect = on_connect client.user_data_set(fridgelyse) client.will_set(mqtttopics['fridgilysestatus'], 'offline', qos=0, retain=True) client.connect(brokerHost) client.subscribe(mqtttopics['rawsamples']) client.subscribe(mqtttopics['door']) while True: client.loop() fridgelyse.publishBottlesOut(client)
def main(server, devicename): global LOOP_DELAY #1 - connects & register MQTT client c = mosquitto.Mosquitto(MQTT_ID + "/" + devicename) c.on_connect = on_connect try: c.connect(server[0], server[1], 60) except: print("failed to connect to {0}:{1} mqtt server".format(*server)); sys.exit(3) c.loop_start() #2 - loop & send measures while(True): cpu = psutil.cpu_percent(interval=.5) mem = hashme(psutil.virtual_memory()) swap = hashme(psutil.swap_memory()) net = hashme(psutil.net_io_counters(), ('bytes_sent','bytes_recv')) batt = hashme(batinfo.battery(), ('capacity','status','charge_full','charge_now'), norm=False) print(cpu, mem, swap, net, batt) c.publish('/devices/xps13/metrics/cpu' , cpu, 0) c.publish('/devices/xps13/metrics/mem' , json.dumps(mem) , 0) c.publish('/devices/xps13/metrics/swap', json.dumps(swap), 0) c.publish('/devices/xps13/metrics/net' , json.dumps(net) , 0) c.publish('/devices/xps13/metrics/batt', json.dumps(batt), 0) time.sleep(LOOP_DELAY)
def __init__(self): bingo_flag = True self.tasklist = [] self.tlLock = threading.Lock() self.projSet = {} self.mqtt_broker_host = macro.MQTT_BROKER_HOST self.mqtt_broker_port = macro.MQTT_BROKER_PORT self.simfile = None self.flag = False self.latency = {} self.failure = {} self.checkFSDir() try: self.load_conf() self.load_simfile() except: print 'Load cfg failed' bingo_flag = False self.mqttc = mosquitto.Mosquitto() self.mqttc.connect(self.mqtt_broker_host, self.mqtt_broker_port, 60, True) self.mqttc.on_message = self.on_message self.mqttc.on_connect = self.on_connect self.taskThread = checkThread.ckThread(self.tlLock, self.tasklist, self.mqttc, self.projSet) self.taskThread.start() if bingo_flag: print 'Init success!'
def get_client(args): client = mqtt.Mosquitto(clean_session=True) if args.mqtt_login: client.username_pw_set(args.mqtt_login, password=args.mqtt_password) if args.mqtt_tls: client.tls_set() return client
def __init__(self, client_id, host="localhost", port=1883, topic_template="/ef/machine/%s/stats/%s", keepalive=60, topics=STATS): self.host = host self.port = port self.topic_template = topic_template self.client_id = client_id self.client = mosquitto.Mosquitto(client_id) self.client.on_message = on_message self.client.on_connect = on_connect self.client.connect(host, port, keepalive) for name in topics: topic = topic_template % (client_id, name) topic_diff = topic + "/diff" print "subscribing to topic", topic, "and", topic_diff self.client.subscribe(topic, 0) self.client.subscribe(topic_diff, 0)
def setUp(self): super().setUp() self.client.subscribe(self.topic, qos=1) self.publisher = mosquitto.Mosquitto('publisher') self.publisher.username_pw_set('foo_pub', '123456') self.publisher.connect(self.host, self.port) self.mock_callbacks(self.publisher)
def __init__(self): self.client = mosquitto.Mosquitto("test-client") self.client.connect("sandbox") #self.loop = gevent.spawn(self.looper) self.produce = gevent.spawn(self.producer) while True: gevent.sleep(1)
def __init__(self, subscribe_channels=[]): self.client = mosquitto.Mosquitto() self.client.connect("127.0.0.1", 1883) self.client.on_message = self._on_mqtt_message self.client.loop_start() for channel_str in subscribe_channels: channel = self._parse_channel(channel_str) self.client.subscribe("/devices/%s/controls/%s" % channel) print "/devices/%s/controls/%s" % channel
def subscriber(): client = mqtt.Mosquitto() client.on_connect = on_connect client.on_message = on_message client.connect(MQTT_HOST, MQTT_PORT, 10) while True: rc = client.loop() if rc != 0: break
def __init__(self, client_id, host="localhost", port=1883, topic_template="/ef/machine/%s/stats/%s", keepalive=60): transport.Checker.__init__(self) self.host = host self.port = port self.topic_template = topic_template self.client_id = client_id self.client = mosquitto.Mosquitto(client_id + "client") self.client.connect(host, port, keepalive)
def __init__(self, cipher, server, topic, client_id): self._client = mosquitto.Mosquitto(client_id) self._mqtt_thread = threading.Thread(target=self._run) self._keep_running = True self._topic = topic self._server = server self._token_queue = Queue.Queue() self._cipher = cipher self._connect() self._mqtt_thread.start()
def __init__(self, host="127.0.0.1"): #create an mqtt client mypid = os.getpid() client_uniq = "two_queue_" + str(mypid) self.pubsu = mosquitto.Mosquitto(client_uniq) self.pubsu.connect(host) self.pubsu.on_message = self.on_message self.channels = set() self.received = False self.message = ""
def main(): client = mosquitto.Mosquitto("smartbus") client.on_connect = on_connect client.on_message = on_message client.connect(MQTT_HOST, MQTT_PORT) while True: rc = client.loop() if rc != 0: break
def setUp(self): self.host = 'localhost' self.port = 1883 self.topic = '/foobar' self.client = mosquitto.Mosquitto('test-%d' % time()) self.client.username_pw_set('testios', '123456') self.client.connect(self.host, self.port) self.mock_callbacks(self.client)
def runMain(self): clientid = "karlnet_pachube@%s/%d" % (socket.gethostname(), os.getpid()) mqttc = mosquitto.Mosquitto(clientid, obj=self) mqttc.connect("localhost") mqttc.subscribe("karlnet/readings/#") mqttc.on_message = self.on_message while True: mqttc.loop()
def main(): ## Command line arguments parser = argparse.ArgumentParser() parser.add_argument("--host", default="192.168.7.2") parser.add_argument("-d") args = parser.parse_args() devicePath = args.d gotDevicePath = (devicePath != None) brokerHost = args.host ## setup MQTT client client = mosquitto.Mosquitto() client.on_message = on_message client.on_disconnect = on_disconnect try: client.connect(brokerHost) except: print("failed to connect") on_disconnect(client, None, None) ## subscribe to topics for ctopic in topicconfig.cat_topics: client.subscribe(ctopic['topic']) ## winkekatze winkeKatze = WinkekatzeConnection() print("Connecting to Arduino.... ", end="") if (gotDevicePath): winkeKatze.connect(devicePath, 9600) else: tryToConnectArduino(winkeKatze) if winkeKatze.isConnected: print("done.") else: print("ERROR!") client.user_data_set(winkeKatze) while True: if not winkeKatze.isConnected: print("Arduino not connected.") if (gotDevicePath): winkeKatze.connect(devicePath, 9600) else: tryToConnectArduino(winkeKatze, "ttyACM", 5) if winkeKatze.isConnected: print("Reconnected!") else: time.sleep(1) client.loop()
def main(): OLDHASH = "" mqttc = mosquitto.Mosquitto() mqttc.connect("test.mosquitto.org") while 1 == 1: result = get_currenttime() if result['apihash'] != OLDHASH: OLDHASH = result['apihash'] mqttc.publish("/labsud/city/currenttime", json.dumps(result)) time.sleep(5)
def main(): mqttc = mosquitto.Mosquitto("limitlessD") mqttc.on_message = on_message mqttc.on_connect = on_connect mqttc.connect("127.0.0.1", 1883, 60, False) mqttc.subscribe("limitless", 0) while mqttc.loop() == 0: pass
def main(): mqttClient = mosquitto.Mosquitto() mqttClient.connect("localhost", 1883) mqttClient.loop_start() rpc_client = mqttrpc.client.TMQTTRPCClient(mqttClient) mqttClient.on_message = rpc_client.on_mqtt_message resp = rpc_client.call('wbrules', 'Editor', 'List', {'path': '/'}) print resp raw_input()
def __init__(self): self.mqtt = mosquitto.Mosquitto('bowen') self.mqtt.on_message = self.on_message self.isConnect = False #start the mosquitto broker mqttBroker.onDisconnect = self.onDisconnect mqttBroker.onConnect = self.onConnect mqttBroker.onCmdRun = self.onCmdRun self.userUtil = UserUtil() print "Current Os id is " + str(os.getpid())