Example #1
9
 def mqtt(self):
     if not hasattr(self, '_mqtt_client'):
         self.responses = {}
         self.ready = False
         client = MQTTClient()
         client.username_pw_set(self.apikey)
         client.on_connect = self._on_connect
         client.on_message = self._on_message
         client.on_subscribe = self._on_subscribe
         client.connect(self.client.endpoint.replace('mqtt://', ''))
         self._mqtt_client = client
         # Start the loop and wait for the connection to be ready
         self._mqtt_client.loop_start()
         while not self.ready:
             time.sleep(.1)
     return self._mqtt_client
Example #2
0
def main():
    print("Hello! this is aggry! I send wonderful data :)")

    client = Client(client_id="aggry")
    client.on_connect = on_connect
    client.on_message = on_message

    if debug:
        client.on_log = on_log
    else:
        print("Debug mode disabled by configuration.")

    # Swarm does not handle dependencies
    sleep(2)

    try:
        rc = client.connect("broker", 1883, 60)
    except:
        # just try again
        print("connect: trying again...")
        sleep(4)
        client.connect("broker", 1883, 60)

    # main loop
    client.loop_forever()
Example #3
0
    def create_client(self,
                      host,
                      port,
                      username,
                      password,
                      clientid,
                      cafile=None):
        """Creating an MQTT Client Object"""
        client = MqttClient(clientid)

        if username and password:
            client.username_pw_set(username=username, password=password)
        else:
            self.logger.warn("Proceeding without username and password")

        if cafile:
            client.tls_set(ca_certs=cafile)
        else:
            self.logger.warn("Proceeding without certificate file")

        try:
            client.on_connect = self.on_connect
            client.on_message = self.on_message
            client.connect(host=host, port=port)
        except OSError as error:
            self.logger.error(error)

        return client
Example #4
0
        def setMqttClient(client: Client):
            client.on_message = on_message
            client.on_connect = on_connect

            client.connect(server, port)
            client.loop_start()
            self.client = client
Example #5
0
def main():
    global args, write_api
    parser = ArgumentParser(description=__doc__)
    parser.add_argument("--host",
                        default='localhost',
                        help='hostname of mqtt broker')
    parser.add_argument(
        "-t",
        action='append',
        default=['velogen/raw'],
        help='MQTT topic to subscribe to. Can be put multiple times.')
    parser.add_argument("-d", action='store_true', help='enable debug output')
    parser.add_argument("--user", default=None, help="username")
    parser.add_argument("--pw", default=None, help="password")

    args = parser.parse_args()

    client = Client()
    client.on_connect = on_connect
    client.on_disconnect = on_disconnect
    client.on_message = on_message
    if args.user is not None and args.pw is not None:
        client.username_pw_set(args.user, args.pw)
    client.connect(args.host)

    # For influxdb2 only
    db = InfluxDBClient(url='http://localhost:8086', token=token, debug=args.d)
    write_api = db.write_api(write_options=SYNCHRONOUS)

    while True:
        client.loop(timeout=1.0)
Example #6
0
    def _are_valid_credentials(self, username, password):
        """Checks whether credentials are valid"""
        def _on_connect(client, userdata, flags, rc):
            """A callback that matches the MQTT client signature, that triggers when connection was established"""
            userdata.set_return_code(rc)
            client.disconnect()

            client.loop_stop()
            client.should_stop = True

        con_result = ConnectionResult()
        client = Client(userdata=con_result)

        client.username_pw_set(username, password)
        client.on_connect = _on_connect

        start_time = time.time()
        client.should_stop = False
        client.connect_async(self.host, self.port)
        client.loop_start()

        while not client.should_stop and time.time(
        ) - start_time < self.timeout:
            time.sleep(0.001)

        return con_result.did_succeed
Example #7
0
def get_client(project_id: str, cloud_region: str, registry_id: str,
               device_id: str, password: str, mqtt_bridge_hostname: str,
               mqtt_bridge_port: str, ca_certs: str):
    client_id = 'projects/{}/locations/{}/registries/{}/devices/{}'.format(
        project_id, cloud_region, registry_id, device_id)

    secho('Client ID: ', fg='bright_green', nl=False)
    echo('\'{}\''.format(client_id))

    client = Client(client_id=client_id)

    client.username_pw_set(username='******', password=password)
    client.tls_set(ca_certs=ca_certs, tls_version=ssl.PROTOCOL_TLSv1_2)

    # Assign callbacks
    client.on_connect = on_connect
    client.on_publish = on_publish
    client.on_disconnect = on_disconnect
    client.on_message = on_message

    # Connect to MQTT bridge
    client.connect(mqtt_bridge_hostname, mqtt_bridge_port)

    client.loop_start()

    return client
Example #8
0
def main():
    global args
    parser = ArgumentParser(description=__doc__)
    parser.add_argument(
        "--host", default='localhost',
        help='hostname of mqtt broker'
    )
    parser.add_argument(
        "--topic", default='velogen/raw',
        help='comma separated list of MQTT topics to subscribe to'
    )
    args = parser.parse_args()

    c = Client()
    c.on_connect = on_connect
    c.on_disconnect = on_disconnect
    c.on_message = on_message
    c.connect(args.host)

    atexit.register(commit)

    while True:
        ts = datetime.now().timestamp()
        for tp, rts in rx_ts_dict.items():
            if rts is not None:
                # dump to file after 30 s of silence
                if ts - rts > 30:
                    clean_write(tp)
                    rx_ts_dict[tp] = None
        c.loop(1.0)
Example #9
0
    def _run(self):
        '''
        The main function of this task.
        '''
        # join function input buffer, it's a shared memory
        join_in_buf = [None] * len(self.idf_confs)

        def on_connect(client, userdata, rc):
            log.info('ESM connect to mqtt broker with return code %s', rc)

            # create odf publish partial function
            for conf in self.odf_confs:
                conf['pub'] = partial(client.publish, conf['topic'])

            for idx, idf in enumerate(self.idf_confs):
                topic = idf['topic']
                client.subscribe(topic)
                client.message_callback_add(
                    topic,
                    self._msg_callback(
                        idf.get('func'), self.join_func.get('func'),
                        self.odf_confs, join_in_buf, idx))

        mqtt_conn = Client()
        mqtt_conn.on_connect = on_connect
        mqtt_conn.connect(config.mqtt_conf['host'],
                          port=config.mqtt_conf['port'])
        mqtt_conn.loop_forever()
Example #10
0
def init_client():
    #variabili di sistema settate 
    access_key = os.environ["AWS_ACCESS_KEY_ID"]
    secret_key = os.environ["AWS_SECRET_ACCESS_KEY"]
    port = 443

    region = "us-east-2"

    # This is specific to your AWS account
    host = "a3pwbt0axh6wnd-ats.iot.us-east-2.amazonaws.com".format(region)

    extra_headers = functools.partial(
        get_amazon_auth_headers,
        access_key,
        secret_key,
        region,
        host,
        port,
    )

    client = Client(transport="websockets")
  
    client.ws_set_options(headers=extra_headers)
    
    # Use client as normal from here
    client.on_connect = on_connect
    client.on_message = on_message
    client.on_publish = on_publish

    client.tls_set()
    client.connect(host, 443,60)
    
    return client
Example #11
0
def ensure_mqtt(host):
    mqtt_client = MQTTClient()
    mqtt_client.on_connect = mqtt_on_connect
    mqtt_client.message_callback_add('embrace/sensors', mqtt_on_message_sensor)
    mqtt_client.message_callback_add('embrace/topology',
                                     mqtt_on_message_topology)
    mqtt_client.connect(host, 1883, 60)
    return mqtt_client
Example #12
0
def set_up(host, port, subscribe_to_topics_func):
    global _instance, _subscribe_to_topics_func
    _subscribe_to_topics_func = subscribe_to_topics_func
    _instance = Client()
    _instance.on_connect = _on_connect
    _instance.on_message = _on_message
    _instance.connect(host, port)
    _instance.loop_start()
Example #13
0
def main():
    influxdb_client = InfluxDBClient(INFLUXDB_HOST, INFLUXDB_PORT, INFLUXDB_USERNAME, INFLUXDB_PASSWORD, INFLUXDB_DATABASE) #First the database is initialized
    mqtt_client = MQTTClient( MQTT_CLIENT_ID, userdata=influxdb_client) #Then we create a client object
    mqtt_client.username_pw_set(MQTT_USERNAME, MQTT_PASSWORD) #and set the username and password for the MQTT client
    mqtt_client.tls_set()
    mqtt_client.on_connect = mqtt_connect_callback #We tell the client which functions are to be run on connecting
    mqtt_client.on_message = mqtt_message_callback #and on receiving a message
    mqtt_client.connect(MQTT_HOST, MQTT_PORT) #we can connect to the broker with the broker host and port
    mqtt_client.loop_forever()
Example #14
0
 def __subscribe(self):
     ip_list = self.settings.get("slaves", ["127.0.0.1"])
     for ip in ip_list:
         client = Client()
         client.connect(ip, 1883, self.settings.get("mqtt_timeout", 60))
         client.on_connect = self.__on_connect
         client.on_message = self.__on_message
         client.loop_start()
         self.client_list.append(client)
def publish_job():
    """ 打卡任务 """
    client = Client()
    client.on_connect = on_connect
    with open('captured_packet.json', encoding='utf-8') as f:
        packet_info = json.load(f)
    # 连接代理服务器
    print('🙈 正在连接代理服务器...')
    client.connect(packet_info['dst host'], 1883)
    client.loop_forever()
Example #16
0
def main():
    influxdb_client = InfluxDBClient(INFLUXDB_HOST, INFLUXDB_PORT,
                                     INFLUXDB_USERNAME, INFLUXDB_PASSWORD,
                                     INFLUXDB_DATABASE)
    mqtt_client = MQTTClient(MQTT_CLIENT_ID, userdata=influxdb_client)
    mqtt_client.username_pw_set(MQTT_USERNAME, MQTT_PASSWORD)
    mqtt_client.tls_set()
    mqtt_client.on_connect = mqtt_connect_callback
    mqtt_client.on_message = mqtt_message_callback
    mqtt_client.connect(MQTT_HOST, MQTT_PORT)
    mqtt_client.loop_forever()
Example #17
0
def get_client(name, signals, *args, **kwargs):
    '''
    Create a MQTT client and bind connect, disconnect, and message callbacks.
    '''
    client = Client(*args, **kwargs)
    client.connected = threading.Event()
    client.on_connect = ft.partial(on_connect, name)
    client.on_disconnect = ft.partial(
        lambda *args, **kwargs: logging.debug('disconnected'))
    client.on_message = ft.partial(on_message, 'dropbot', signals)
    return client
Example #18
0
def test_traffic_mqtt():
    client = Client(client_id="test")
    client.on_connect = on_connect
    client.username_pw_set(username="******", password="******")
    client.connect(host="52.164.202.250", port=1883)
    client.loop_start()
    t.sleep(5)

    t.sleep(2)
    client.disconnect()
    t.sleep(2)
Example #19
0
def setup_mqtt_client():
    def on_connect(client, *args):
        client.subscribe(MQTT_TOPIC)

    temp_client = Client()
    temp_client.username_pw_set(**MQTT_CREDS)
    temp_client.on_connect = on_connect
    temp_client.on_message = on_message
    temp_client.connect(MQTT_BROKER, 1883, 60)

    return temp_client
Example #20
0
 def loop(self, ip, port, clientId='', username='', password='', **kwargs):
     if MqttConnect.mqtt:
         MqttConnect.mqtt.loop_stop()
     mqtt = Client(clientId)
     mqtt.username_pw_set(username, password)
     mqtt.connect(ip, int(port))
     mqtt.on_log = self.on_log
     mqtt.on_connect = self.on_connect
     mqtt.on_message = self.on_message
     mqtt.loop_start()
     MqttConnect.mqtt = mqtt
Example #21
0
def send_to_mqtt(packet, db = "testcargo"):
    packet['database'] = db
    client = Client(client_id="test")
    client.on_connect = on_connect
    client.username_pw_set(username="******", password="******")
    client.connect(host="52.164.202.250", port=1883)
    client.loop_start()
    t.sleep(5)
    transmit(client)
    t.sleep(2)
    client.disconnect()
    t.sleep(2)
Example #22
0
def run_mqtt_listener():
    mqtt_broker_url = '167.86.108.163'
    MQTT_HOST = os.getenv('MQTT_HOST', mqtt_broker_url)
    client_name = 'mqtt-csw-importer'
    topic = 'update_csw'

    print("Sono partito")
    print("->167.86.108.163")
    print("->mqtt-csw-importer")

    def _on_connect(client, userdata, flags, rc):
        print("Connesso con successo al topic", topic)

    def _on_log(client, userdata, level, buf):
        # print("log", level, buf)
        pass

    def _on_message(client, userdata, message):
        message = str(message.payload.decode("utf-8"))
        payload = json.loads(message)['rndt_xml']
        print('received event', payload)
        print(
            '----ENDED------------------------------------------------------')
        cmd = 'pycsw-admin.py -c load_records -f /etc/pycsw/pycsw.cfg  -p /home/pycsw/datatemp'
        filename = "/home/pycsw/datatemp/temp1.xml"
        try:
            with open(filename, 'w') as file:
                file.write(payload)
            execute(cmd)
            # execute('rm -f ' + filename)
        except Exception as e:
            print('Exception', e)

    try:
        client = Client(client_id='{}_{}'.format(client_name,
                                                 random.randint(1, 10000)),
                        clean_session=True)

        print('Connecting to MQTT broker at ')
        client.connect(MQTT_HOST)
    except ConnectionRefusedError as e:
        print('Connection refused by MQTT broker at ')
        raise ConnectionRefusedError
    client.on_connect = _on_connect
    client.on_message = _on_message
    client.on_log = _on_log

    client.subscribe(topic)

    client.loop_forever()
    # client.loop_start()
    print('loop started')
Example #23
0
def get_mqtt_payload(topic):
    mqttBroker = "localhost"
    client = Client("Temperature_Inside")

    if topic == "PYWATERING":
        client.on_connect = on_connect_st
    elif topic == "PLANT1":
        client.on_connect = on_connect_plant1
    elif topic == "PLANT2":
        client.on_connect = on_connect_plant2
    elif topic == "PLANT3":
        client.on_connect = on_connect_plant3
    elif topic == "PLANT4":
        client.on_connect = on_connect_plant4

    client.on_message = on_message
    client.username_pw_set(username=uname, password=passwd)
    client.connect("localhost")
    client.loop_start()
    time.sleep(2)
    client.loop_stop()
    return global_message
Example #24
0
 def mqtt(self):
     if not hasattr(self, '_mqtt_client'):
         self.responses = {}
         self.ready = False
         client = MQTTClient()
         client.username_pw_set(self.apikey)
         client.on_connect = self._on_connect
         client.on_message = self._on_message
         client.on_subscribe = self._on_subscribe
         client.connect(self.client.endpoint.replace('mqtt://', ''))
         self._mqtt_client = client
         # Start the loop and wait for the connection to be ready
         self._mqtt_client.loop_start()
         while not self.ready:
             time.sleep(.1)
     return self._mqtt_client
Example #25
0
def mqtt_handler():
    global mqtt_client
    Client.connected_flag = False
    mqtt_client = Client()
    mqtt_client.on_connect = on_connect
    mqtt_client.on_message = on_message
    mqtt_client.loop_start()
    mqtt_client.connect(host=MQTT_ADDR, port=MQTT_PRT)
    while not mqtt_client.connected_flag:  # wait in loop
        print("In wait loop")
        time.sleep(1)

    # subscribe all rooms, using MQTT single layer wildcard
    mqtt_client.subscribe(topic='%s/+' % ORDER_STATUS)
    mqtt_client.loop_forever()
    mqtt_client.disconnect()
Example #26
0
def run_client(settings):
    def on_connect(*args, **kwargs):
        print("connected")

    def on_message(*args, **kwargs):
        print("message received", args, kwargs)

    client = MQTTClient()
    client.on_connect = on_connect
    client.on_message = on_message
    client.connect(server, settings["mqtt_settings"]["port"], 60)
    t0 = time.time()
    while True:
        time.sleep(1)
        client.loop()
        td = time.time() - t0
        f = lambda x: np.log(x / 10) * 10 + 50
        data = '{"meat_temp": %.1f, "oven_temp": %.1f}' % (f(td), f(td + 100))
        print("publishing data")
        client.publish("test_topic", data)
Example #27
0
def mqtt_handler():
    global mqtt_client
    Client.connected_flag = False
    mqtt_client = Client()

    # set mosquitto broker password and username
    mqtt_client.username_pw_set(username=USERNAME, password=PASSWORD)
    # set TLS cert for the client
    mqtt_client.tls_set(ca_certs=TLS_CERT)
    mqtt_client.tls_insecure_set(True)

    mqtt_client.on_connect = on_connect
    mqtt_client.on_message = on_message
    mqtt_client.loop_start()
    mqtt_client.connect(host=MQTT_ADDR, port=MQTT_PRT)
    while not mqtt_client.connected_flag:  # wait in loop
        print("In wait loop")
        time.sleep(1)
    mqtt_client.subscribe(topic='%s/+' % ORDER_STATUS)
    mqtt_client.loop_forever()
    mqtt_client.disconnect()
Example #28
0
    def connauth(host, clientid=None, user=None, passwd=None, **kw):
        """
        connauth helps in checking if a client can connect to a broker with specific client id and/or credentials

        :param host:     Host to connect to
        :param clientid: Client ID to use. If not specified paho-mqtt generates a random id.
        :param user:     User name of the client. If None or empty, connection is attempted without user, pwd
        :param passwd:   Password of the client. If None, only user name is sent
        :param kw:       Client.connect() keyword arguments (excluding host)
        :return:         Two comma separated values - The result code and it's string representation
        """
        rc = {"rc": None}
        c = Client(clientid, userdata=rc)
        if user is not None and user is not "":
            c.username_pw_set(user, passwd)
        c.on_connect = SimpleMqttClient._on_connauth

        #print("connecting to ({})".format(host))
        r = c.connect(host, **kw)
        #print("connect() returned r.__class__ = ({}), r = ({})".format(r.__class__, r))

        r = c.loop_forever()
        return rc["rc"], connack_string(rc["rc"])
Example #29
0
    def connauth(host, client_id=None, user=None, passwd=None, **kw):
        """
        Helper to check if a client can connect to a broker with specific
        client ID and/or credentials.

        :param host: Host to connect to
        :param client_id: Client ID to use. If not specified paho-mqtt
                        generates a random id.
        :param user: User name of the client. If None or empty, connection is
                     attempted without username and password
        :param passwd: Password of the client. If None, only user name is sent
        :param kw: Client.connect() keyword arguments (excluding host)
        :return: Two comma separated values. The result code and its string
                 representation
        """
        return_code = {"rc": None}
        client = Client(client_id, userdata=return_code)
        if user is not None and user != "":
            client.username_pw_set(user, passwd)
        client.on_connect = SimpleMqttClient._on_connauth

        client.connect(host, **kw)
        client.loop_forever()
        return return_code["rc"], connack_string(return_code["rc"])
Example #30
0
def create_client(
    hostname: str = leader_hostname,
    last_will: Optional[dict] = None,
    client_id: Optional[str] = None,
    keepalive=60,
    max_retries=3,
) -> Client:
    """
    Create a MQTT client and connect to a host.
    """

    def on_connect(client: Client, userdata, flags, rc: int, properties=None):
        if rc > 1:
            from pioreactor.logging import create_logger

            logger = create_logger("pubsub.create_client", to_mqtt=False)
            logger.error(f"Connection failed with error code {rc=}: {connack_string(rc)}")

    client = Client(client_id=client_id)
    client.on_connect = on_connect

    if last_will is not None:
        client.will_set(**last_will)

    for retries in range(1, max_retries + 1):
        try:
            client.connect(hostname, keepalive=keepalive)
        except (socket.gaierror, OSError):
            if retries == max_retries:
                break
            time.sleep(retries * 2)
        else:
            client.loop_start()
            break

    return client
Example #31
0
def main():
    parser = argparse.ArgumentParser(description=help_text)
    parser.add_argument('-l',
                        '--log-level',
                        action='store',
                        type=str,
                        dest='log_level',
                        help='Log level',
                        default='INFO')

    args = parser.parse_args()
    numeric_level = getattr(logging, args.log_level.upper(), None)
    if not isinstance(numeric_level, int):
        raise ValueError('Invalid log level: %s' % args.log_level)
    coloredlogs.install(level=numeric_level)
    logger.info('Log level set to %s', args.log_level)

    client = Client()
    client.username_pw_set("****", "****")
    client.on_connect = on_connect
    client.on_message = on_message

    client.connect(MQTT_ADRESS, MQTT_PORT, 60)
    client.loop_forever()
Example #32
0
    def __init__(self, client_id, config, wait=True):
        """
        initialize mqtt client
        :param client_id: client id
        :param config: keeper configuration
        :param wait: whether to wait for connection
        """

        self.logger = Logger()
        user = config.get("mqtt.user")
        pwd = config.get("mqtt.pass")
        client = Client(client_id=client_id)
        client.on_connect = self._on_connect
        client.on_disconnect = self._on_disconnect
        client.on_message = self._on_message
        client.enable_logger(self.logger)
        if user and pwd:
            client.username_pw_set(user, pwd)

        client.connect_async(config["mqtt.broker"], config["mqtt.port"], 30)
        self.client = client
        self.connected = False
        self.manager = None
        self.wait = wait
from paho.mqtt.client import Client

def on_connect(client, userdata, rc):
    client.subscribe("#")
def on_message(client, userdata, msg):
    print(msg.topic+" "+str(msg.payload))
client = Client()
client.on_message = on_message
client.on_connect = on_connect
client.connect("broker.mqttdashboard.com")
client.loop_forever()