def get(args): if len(args) != 4: verdict(CHECKER_ERROR, "Wrong args count", "Wrong args count for get()") host, flag_id, flag_data, vuln = args trace("get(%s, %s, %s, %s)" % (host, flag_id, flag_data, vuln)) mqtt_client = MqttClient(host) sys.exit(mqtt_client.check_connect(username=flag_id, password=flag_data))
def check(args): if len(args) != 1: verdict(CHECKER_ERROR, "Wrong args count", "Wrong args count for check()") host = args[0] trace("check(%s)" % host) module_client = ThermometerModule(host) result = module_client.check_index() if result != OK: sys.exit(result) mqtt_client = MqttClient(host) sys.exit(mqtt_client.check_connect())
def main(): args = get_arguments() server = args.server port = int(args.port) topic = args.topic print('Parameters') print(f'Server: {server}') print(f'Port: {port}') print(f'Topic: {topic}') print() client = MqttClient() client.run(server, port, [topic])
def dbusLoop(): dbus.mainloop.glib.DBusGMainLoop(set_as_default=True) lora = lora_protocol.LoRaWAN() mqtt = MqttClient() try: mainloop.run() except KeyboardInterrupt: try: mqtt.TearDown() lora.TearDown() mainloop.quit() except dbus.exceptions.DBusException: pass endProgram(0)
def publish(file_path, topic): client = MqttClient(config.HOST, config.USER, config.PW) start = time.time() list_of_payloads = split_by_size(file_path) success = client.send_multiple_messages(list_of_payloads, topic) end = time.time() if success: mssg = '\nAll segments sent!' else: mssg = '\nAn error was found while publishing' elapsed = end - start print(mssg) print('Elapsed time:', elapsed, 'seconds')
class mqttInfluxDBBridge(threading.Thread): def __init__(self): threading.Thread.__init__(self) self.mqtt_client = None self.influxdbClient = InfluxDBConnector() self.topicToSubscribe = [] logger.info("create mqtt - InfluxDB - Bridge") self.mqttListenerDict = {} def run(self): while True: self.mqtt_client.mqtt_run() def connectToDataBase(self, ip, port, userName, password, dataBase): self.influxdbClient.connect_to_database(ip=ip, port=port, userName=userName, password=password, dataBase=dataBase) def connectToMqttBroker(self, ip, port, certspath): self.mqtt_client = MqttClient(ip, port) if certspath: self.mqtt_client.set_secure_connection(certspath) self.mqtt_client.connect_to_broker() def add_mqtt_topic(self, topic, measurement_name, host_name): listener_obj = mqttListener(topic=topic, influxInst=self.influxdbClient, measurementName=measurement_name, hostName=host_name) self.mqttListenerDict[topic] = listener_obj self.mqtt_client.add_listener( topic=topic, listener=listener_obj.mqtt_message_to_InfluxDB) def get_all_subscribed_Topics(self): return self.mqttListenerDict.keys() def remove_subscribed(self, topic): if topic in self.mqttListenerDict: self.mqtt_client.unsubscribe_topic(topic) # del self.mqttListenerDict[topic] self.mqttListenerDict.pop(topic) def create_database(self, name): self.influxdbClient.create_database(name) def list_database(self): return self.influxdbClient.list_databases() def get_received_message_counter(self): return self.mqtt_client.get_received_messages_counter()
def __init__(self): self.device_serial = self.get_device_serial() self.device_controller = DeviceController(devices_config) self.devices = self.device_controller.get_devices_info() topics = [self.device_serial + "/#"] print(self.devices) self.mqtt_client = MqttClient(mqtt_config, topics, self.onMessageReceivedCallback) self.mqtt_client.connect(self.device_serial) self.loop_thread = threading.Thread(target=self.mqtt_client.loop, daemon=True) self.publish_thread = threading.Thread( target=self.publish_device_data_periodically, daemon=True)
def main(): logger.info(f"Starting server") settings = load_settings() client: Optional[TransportClient] = None if settings.mqtt: client = MqttClient(host_name, settings.mqtt) if settings.signalr: client = SignalRClient(settings.signalr) if not client: raise Exception("No transport client was created") client.start(on_request_receive) while is_running: ip_address = get_host_ip() update_known_printers(settings) status = HostStatus(online=True, ip=ip_address, host=host_name, update_s=settings.printer_check_period_s, printers=[ p.info() for p in printers.values() if p.info().model is not None ]) client.publish(status) time.sleep(settings.printer_check_period_s)
def main(): print("Getting IP address") ip_address = get_ip_address('wlan0') print("IP address " + ip_address) ser = serial.Serial('/dev/ttyUSB0', 9600) print("Serial connected ") renderer_client = RendererClient(ip_address) print("Connecting MQTT client") mqtt_client = MqttClient(on_connect, on_message, (renderer_client, ser)) print("Proceeed to drawing part") while (True): sensorData = ser.readline() while (sensorData): renderer_client.setSensorData(sensorData) mqtt_client.publish("SENSOR", renderer_client.getState()) sensorData = ser.readline()
def main(): args = get_arguments() server = args.server port = int(args.port) topic = args.topic print('Parameters') print(f'Server: {server}') print(f'Port: {port}') print(f'Topic: {topic}') print() client = MqttClient() client.connect(server, port, 60) while True: timestamp = datetime.utcnow() num = random() * 100 msg = { 'timestamp': timestamp.strftime("%Y-%m-%d %H:%M:%S"), 'value': num} print(f'Publishing: {msg}') client.publish(topic, json.dumps(msg)) time.sleep(3)
def send_mqtt_msgs(service_info, msgs, interval_sec): client = MqttClient() client.connect(service_info['host'], service_info['protocol']['port'], 60) for msg in msgs: client.publish(service_info['protocol']['publish']['default_topic'], json.dumps(msg)) time.sleep(interval_sec)
def put(args): if len(args) != 4: verdict(CHECKER_ERROR, "Wrong args count", "Wrong args count for put()") host, flag_id, flag_data, vuln = args trace("put(%s, %s, %s, %s)" % (host, flag_id, flag_data, vuln)) if vuln == "1": mqtt_client = MqttClient(host) result = mqtt_client.register_sensor(flag_id) if result != OK: sys.exit(result) module_client = ThermometerModule(host) sys.exit(module_client.authorize_sensor(flag_id, flag_data)) if vuln == "2": module_client = ThermometerModule(host) sys.exit( module_client.create_mqtt_client(username=flag_id, password=flag_data)) verdict(CHECKER_ERROR, "Unknown vuln number for put()", "Unknown vuln number '%s' for put" % vuln)
def pub_soil_moisture(): """ 发布土壤湿度信息 """ mqtt_cli = MqttClient('pub_soil_moisture') mqtt_cli.mqtt_connect() soil_moisture = detect_dry_or_wet() or '1' topic = local_conf.mqtt_broker['PUB_SOIL_MOISTURE_TOPIC_PREFIX'] +\ stpi_config.PLANT_ID +\ '/' +\ str(int(time.time())) mqtt_cli.mqtt_publish(topic, soil_moisture, qos=2) return
def pub_temp_humi(): """ 发布温湿度信息 """ temp, humi = get_temp_humi() if not temp and not humi: return mqtt_cli = MqttClient('pub_soil_moisture') mqtt_cli.mqtt_connect() topic = local_conf.mqtt_broker['PUB_TEMP_HUMI_TOPIC_PREFIX'] +\ stpi_config.PLANT_ID +\ '/' +\ str(int(time.time())) payload = str(int(temp)) + '_' + str(int(humi)) mqtt_cli.mqtt_publish(topic, payload, qos=2) return
log.debug(f'skipping {fn}') masterGraph = PatchableGraph() brokerHost = 'mosquitto-frontdoor.default.svc.cluster.local' brokerPort = 10210 debugPageData = { # schema in index.ts 'server': f'{brokerHost}:{brokerPort}', 'messagesSeen': 0, 'subscribed': [], } mqtt = MqttClient(clientId='mqtt_to_rdf', brokerHost='mosquitto-ext.default.svc.cluster.local', brokerPort=1883) # deprecated internalMqtt = MqttClient(clientId='mqtt_to_rdf', brokerHost=brokerHost, brokerPort=brokerPort) srcs = [] for src in sorted(config.subjects(RDF.type, ROOM['MqttStatementSource'])): srcs.append( MqttStatementSource(src, config, masterGraph, mqtt=mqtt, internalMqtt=internalMqtt, debugPageData=debugPageData)) log.info(f'set up {len(srcs)} sources')
def sub_watering_cmd(): """ 启动mqtt监听 """ mqtt_cli2 = MqttClient('sub_watering_cmd') mqtt_cli2.mqtt_connect() mqtt_cli2.mqtt_subscribe(local_conf.mqtt_broker['SUB_WATERING_TOPIC'])
self.bot.bot.sendMessage(chat_id=chat_id, text=text + c.MSG_REPLY) log.info("Sendweb @%s: %s", chat_id, text) if __name__ == "__main__": log.info("Starting Infobot v%s", c.VERSION) config_path = sys.argv[-1] log.info("Processing config from `%s`", config_path) config = load_from_file(config_path) mqtt_conf = config["mqtt"] mqtt = MqttClient( name="infobot", broker=mqtt_conf["host"], port=mqtt_conf["port"], username=mqtt_conf["username"], password=mqtt_conf["password"], ) bot = Updater(token=config["telegram"]["token"], use_context=True) infobot = Infobot(mqtt, bot, config) try: infobot.serve() except KeyboardInterrupt: log.debug("Interactive quit") sys.exit() finally: log.info("Quitting")
time.sleep(0.1) return time.time() # ----------------------------------------- # Run the program # ----------------------------------------- if __name__ == '__main__': # logging.debug("--- Start ---") logging.info("--- Start --- {0}s warten bis alles da ist ...".format( config["main"]["wait"])) time.sleep(config["main"]["wait"]) # # MQTT-Login #TODO: User/Passwort & ClientID über die Config collection = Collection(config) mqtt = MqttClient(config) mqtt.loop_start() while True: # # jetzt ist es gerade ... t0 = time.time() t0_str = time.strftime("%d.%m.%Y %H:%M:%S") logging.info("--- {0} ----------".format(t0_str)) # # Daten besorgen collection.collect_data() data = collection.get_all_data() # TODO: ggf. die einzelnen Werte # # MQTT senden mqtt.pup_data(data)
def main(): client = MqttClient(config.HOST, config.USER, config.PW)
sys.exit(status) if __name__ == '__main__': try: logging.basicConfig( filemode="a", format="%(asctime)s [%(levelname)s] [%(threadName)s] %(message)s", datefmt="%Y-%m-%d %H:%M:%S", level=LOGLEVEL) # Check whether .env file exists (otherwise, we will assume that they will be already set) if (os.path.exists('.env')): logging.debug('.env file found - loading...') load_dotenv(join(dirname(__file__), '.env')) if (os.environ.get('LORAWAN_APP_SERVER')): mqtt = MqttClient() flask = FlaskServer() else: logging.error('Needed environment variables not found - closing') except KeyboardInterrupt: try: logging.info("CTRL + C pressed") # flask.TearDown() except: logging.error("ERROR") endProgram(0)
message: str = None): if messageJson is not None: message = json.dumps(messageJson) self.settings.mqtt.publish(topic.encode('ascii'), message.encode('ascii')) if __name__ == '__main__': arg = docopt(""" Usage: rdf_to_mqtt.py [options] -v Verbose """) verboseLogging(arg['-v']) mqtt = MqttClient(clientId='rdf_to_mqtt', brokerPort=1883) port = 10008 reactor.listenTCP(port, cyclone.web.Application([ (r"/()", cyclone.web.StaticFileHandler, { "path": ".", "default_filename": "index.html" }), (r'/output', OutputPage), (r'/stats/(.*)', StatsHandler, { 'serverName': 'rdf_to_mqtt' }), ], mqtt=mqtt, debug=arg['-v']),
if body['addr'] == 'zz:zz:zz:zz:zz:zz' and body['key'] == 'top': log.info('unlock for %r', body['addr']) self.settings.mqtt.publish( espName + b"/switch/strike/command", b'ON') if __name__ == '__main__': arg = docopt(""" Usage: front_door_lock.py [options] -v Verbose """) verboseLogging(arg['-v']) masterGraph = PatchableGraph() mqtt = MqttClient(brokerPort=10210) autoclose = AutoLock(masterGraph, mqtt) def toGraph(payload): log.info('mqtt->graph %r', payload) masterGraph.patchObject(ctx, ROOM['frontDoorLock'], ROOM['state'], stateFromMqtt(payload)) sub = mqtt.subscribe(espName + b"/switch/strike/state") sub.subscribe(on_next=toGraph) def setEspState(payload): log.info('esp state change %r', payload) masterGraph.patchObject(ctx, ROOM['frontDoorLock'], ROOM['espMqttConnection'], ROOM['mqtt' + payload.decode('ascii').capitalize()]) sub = mqtt.subscribe(espName + b"/status")
config = load_from_file(args.config) else: log.info("Using config from environment variables") # These are taken from https://github.com/roataway/api-documentation and are # assumed constant config = { "host": os.getenv("MQTT_HOST", "opendata.dekart.com"), "port": os.getenv("MQTT_PORT", 1945), "username": os.getenv("MQTT_USER", None), "password": os.getenv("MQTT_PASS", None), } mqtt = MqttClient( name="roatarest", broker=config["host"], port=config["port"], username=config["username"], password=config["password"], ) subscriber = Subscriber(mqtt) subscriber.serve() app = Flask("roatarest") app.add_url_rule("/", "index", subscriber.index) app.add_url_rule("/route/<route_id>/trackers", "tracker_route", subscriber.get_route_tracker) # these two might be unnecessary, leaving them enabled for now, let's see if there is an # actual demand for these app.add_url_rule("/tracker/<tracker_id>", "tracker",
b_state.tweeting = True tt = threading.Thread(target=tweet, args=(time, button_size,)) tt.start() else: print("chatter!") def on_connect(client, userdata, rc): print("Connected MQTT with result code "+str(rc)) b.isr(mraa.EDGE_FALLING, on_click, on_click) def upload_image(filename): t_up = Twitter(domain='upload.twitter.com', auth=auth) with open(filename, "rb") as imagefile: imagedata = imagefile.read() m_id = t_up.media.upload(media=imagedata)["media_id_string"] print m_id return m_id if __name__ == '__main__': # Button b = mraa.Gpio(14) b.dir(mraa.DIR_IN) b.mode(mraa.MODE_PULLUP) # MQTT client = MqttClient(os.environ['MQTT_URL']) client.on_connect = on_connect client.connect() client.loop_forever()
from ble_device import BleDevice from mqtt_client import MqttClient from handler import Handler mac = "xx:xx:xx:xx:xx:xx" thing_id = "1" ip = "xxx.xxx.xxx.xxx" port = 1883 client_name = "Client" #file_name = "data.txt" minutes = 0.5 thing = BleDevice(mac, thing_id) mqtt = MqttClient(ip, port, client_name) handler = Handler() thing.connect() mqtt.connect() handler.mqtt_setup(mqtt) #handler.open_file(file_name) #thing.print_svc_char() thing.setup() thing.set_handler(handler) thing.get_data(minutes) thing.disconnect() mqtt.disconnect()
if messageJson is not None: message = json.dumps(messageJson) self.settings.mqtt.publish(topic.encode('ascii'), message.encode('ascii')) if __name__ == '__main__': arg = docopt(""" Usage: rdf_to_mqtt.py [options] -v Verbose """) verboseLogging(arg['-v']) mqtt = MqttClient(clientId='rdf_to_mqtt', brokerHost='mosquitto-ext.default.svc.cluster.local', brokerPort=1883) port = 10008 reactor.listenTCP(port, cyclone.web.Application([ (r"/()", cyclone.web.StaticFileHandler, { "path": ".", "default_filename": "index.html" }), (r'/output', OutputPage), (r'/stats/(.*)', StatsHandler, { 'serverName': 'rdf_to_mqtt' }), ], mqtt=mqtt,
import json import time from random import random from datetime import datetime from mqtt_client import MqttClient server = 'localhost' port = 1883 topic = 'ingestion/test/' client = MqttClient() client.connect(server, port, 60) while True: timestamp = datetime.utcnow() num = random() * 100 msg = {'timestamp': timestamp.strftime("%Y-%m-%d %H:%M:%S"), 'value': num} print(f'Publishing: {msg}') client.publish(topic, json.dumps(msg)) time.sleep(3)
def connectToMqttBroker(self, ip, port, certspath): self.mqtt_client = MqttClient(ip, port) if certspath: self.mqtt_client.set_secure_connection(certspath) self.mqtt_client.connect_to_broker()
if body['addr'] == 'zz:zz:zz:zz:zz:zz' and body['key'] == 'top': log.info('unlock for %r', body['addr']) self.settings.mqtt.publish( espName + b"/switch/strike/command", b'ON') if __name__ == '__main__': arg = docopt(""" Usage: front_door_lock.py [options] -v Verbose """) verboseLogging(arg['-v']) masterGraph = PatchableGraph() mqtt = MqttClient(brokerPort=10010) autoclose = AutoLock(masterGraph, mqtt) def toGraph(payload): log.info('mqtt->graph %r', payload) masterGraph.patchObject(ctx, ROOM['frontDoorLock'], ROOM['state'], stateFromMqtt(payload)) mqtt.subscribe(espName + b"/switch/strike/state").subscribe(on_next=toGraph) def setEspState(payload): log.info('esp state change %r', payload) masterGraph.patchObject(ctx, ROOM['frontDoorLock'], ROOM['espMqttConnection'], ROOM['mqtt' + payload.decode('ascii').capitalize()]) mqtt.subscribe(espName + b"/status").subscribe(on_next=setEspState)
from mqtt2datapoint_converter import Mqtt2DataPointConverter from mqtt_client import MqttClient logging.basicConfig(level=os.environ.get("LOGLEVEL", "DEBUG")) def load_config(): with open('../config.json') as json_file: return json.load(json_file) def on_mqtt_message(topic, json_data): try: datapoints = Mqtt2DataPointConverter(config) \ .for_topic(topic) \ .with_json_data(json_data) \ .create_datapoint_db_mappings() for database in datapoints.keys(): influxDbClient.write_datapoints_to_database(datapoints[database], database) except Exception: logging.exception("Failed to process message on topic %s" % topic) config = load_config() influxDbClient = InfluxDbClient(config) mqttClient = MqttClient(config) mqttClient.on_message_callback(on_mqtt_message) mqttClient.start()
class SmartHomeController: device_controller = None mqtt_client = None device_serial = None devices = None loop_thread = None publish_thread = None def __init__(self): self.device_serial = self.get_device_serial() self.device_controller = DeviceController(devices_config) self.devices = self.device_controller.get_devices_info() topics = [self.device_serial + "/#"] print(self.devices) self.mqtt_client = MqttClient(mqtt_config, topics, self.onMessageReceivedCallback) self.mqtt_client.connect(self.device_serial) self.loop_thread = threading.Thread(target=self.mqtt_client.loop, daemon=True) self.publish_thread = threading.Thread( target=self.publish_device_data_periodically, daemon=True) def onMessageReceivedCallback(self, mqttc, user_data, msg): if (msg.topic == (self.device_serial + "/devices/info/req")): self.mqtt_client.publish( self.device_serial + "/devices/info", json.dumps(self.device_controller.get_devices_info())) return device = msg.topic.split("/")[1] devices_names = list(self.devices.keys()) if (device in devices_names): # Set device state message = msg.payload.decode("utf-8") active = None if (message == "On"): active = True if (message == "Off"): active = False self.device_controller.set_device_active(device, active) self.mqtt_client.publish( self.device_serial + "/devices/" + device + "/status", json.dumps(self.device_controller.get_devices_info()[device])) def publish_device_data_periodically(self): # Periodically send devices info while True: self.mqtt_client.publish( self.device_serial + "/devices/info", json.dumps(self.device_controller.get_devices_info())) time.sleep(10) def run(self): # Start threads and wacth their status while True: loop_thread_alive = sh.loop_thread.isAlive() publish_thread_alive = sh.publish_thread.isAlive() print("loop thread active: " + str(loop_thread_alive)) print("publish thread active: " + str(publish_thread_alive)) if not loop_thread_alive: sh.loop_thread.start() if not publish_thread_alive: sh.publish_thread.start() time.sleep(1) @staticmethod def get_device_serial(): device_serial = "0000000000000000" with open('/proc/cpuinfo', 'r') as f: device_serial = f.read() search = re.search(r"\nSerial\s+:\s+(?P<serial>[0-9a-f]{16})", device_serial) if search is None: raise BaseException("Cannot find device serial!") return search.group("serial")
import datetime import os import time from flask import Flask, request, render_template, jsonify, send_from_directory from conf import MODEL_FOLDER_PATH from conf import RESOURCE_DIR_PATH from conf import MQTT_BROKER_HOST from conf import MQTT_BROKER_PORT from mqtt_client import MqttClient client = MqttClient(MQTT_BROKER_HOST, MQTT_BROKER_PORT) app = Flask(__name__) ALLOWED_EXTENSIONS = {'txt', 'png', 'jpg', 'JPG', 'PNG'} # file EXTENSIONS check def allowed_file(filename): return '.' in filename and filename.rsplit('.', 1)[1] in ALLOWED_EXTENSIONS @app.route('/') def hello_world(): cur_time = datetime.datetime.now() str_cur_time = cur_time.strftime("%Y-%m-%d %H:%M:%S") return render_template('Home.html', time=str_cur_time) # test page
dash() dash() dash() word_space() gpio = mraa.Gpio(13) gpio.dir(mraa.DIR_OUT) # boot time ring gpio.write(1) time.sleep(1.0) gpio.write(0) # MQTT mqtt_client = MqttClient(os.environ['MQTT_URL']) mqtt_client.on_connect = on_mqtt_connect mqtt_client.connect() mqtt_client.loop_start() # Twitter auth = OAuth(ACCESS_TOKEN, ACCESS_TOKEN_SECRET, CONSUMER_KEY, CONSUMER_SECRET) t = Twitter(auth=auth) message = "AC Control Box started at " + str(datetime.datetime.now()) while True: try: t.statuses.update(status=message) print "Tweeted!" break