Example #1
0
    def __init__(self,
                 bot,
                 host=BROKER_HOST,
                 port=BROKER_PORT,
                 subscriptions=None):
        """
        Create an instance and connect to broker.

        :param bot: reference to the `Bot` instance.
        :param host: the hoststring for the broker.
        :param port: the port of the broker.
        :param subscriptions: a dictionary in the form `topic name (string) => function to execute (callback)`. callback must be 
        able to receive three arguments - namely `client_id`, `userdata`, `message`.
        """
        self._bot = bot

        self._host = host
        self._port = port

        self._client = Client()
        self._client.connect(self._host, self._port, 60)

        self._subscribed_thread = None

        if subscriptions:
            self._subscribe(subscriptions)
Example #2
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 #3
0
    def on_start(self):
        self._publish_clock = None
        self.mqtt_broker_bridged = False
        self._associated = True
        self.association_code = None
        self.mqtt = Client(client_id=MQTT_CLIENT_ID)
        self.mqtt.enable_logger()
        self.mqtt.will_set(client_state_topic(MQTT_CLIENT_ID),
                           "0",
                           qos=2,
                           retain=True)
        self.mqtt.on_connect = self.on_connect
        self.mqtt.connect(MQTT_BROKER_HOST,
                          port=MQTT_BROKER_PORT,
                          keepalive=MQTT_BROKER_KEEP_ALIVE_SECS)
        self.mqtt.loop_start()
        self.set_up_GPIO_and_device_status_popup()
        self.associated_status_popup = self._build_associated_status_popup()
        self.associated_status_popup.bind(on_open=self.update_popup_associated)

        self._remote = None
        self._popup_remote = None
        self.pairing_popup = self._build_pairing_popup()

        self._update_remotes_ui()

        self.discoverswitch = self.root.ids.discoverswitch
        self.discoverswitch.bind(active=self.toggle_discovery)

        Clock.schedule_interval(self._poll_associated, 0.1)
Example #4
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 #5
0
    def __init__(self, hass, host: str, config: dict, **options):
        """Initialize the Xiaomi/Aqara device."""
        super().__init__(daemon=True)
        self.hass = hass
        self.host = host
        self.options = options
        # if mqtt server connected
        self.enabled = False
        self.available = False

        self._mqttc = Client()
        self._mqttc.on_connect = self.on_connect
        self._mqttc.on_disconnect = self.on_disconnect
        self._mqttc.on_message = self.on_message

        self._debug = options.get('debug', '')  # for fast access
        self.parent_scan_interval = (-1 if options.get('parent') is None
                                     else options['parent'])
        self.default_devices = config['devices'] if config else None

        self.devices = {}
        self.updates = {}
        self.setups = {}
        self._device_state_attributes = {}
        self._info_ts = None
Example #6
0
    def __init__(self, host: str, token: str, config: dict, **options):
        super().__init__(daemon=True)

        self.host = host
        self.options = options

        self.miio = SyncmiIO(host, token)

        self.mqtt = Client()
        self.mqtt.on_connect = self.on_connect
        self.mqtt.on_disconnect = self.on_disconnect
        self.mqtt.on_message = self.on_message

        self._ble = options.get('ble')  # for fast access
        self._debug = options.get('debug', '')  # for fast access
        self.parent_scan_interval = (-1 if options.get('parent') is None
                                     else options['parent'])
        self.default_devices = config['devices'] if config else None

        if 'true' in self._debug:
            self.miio.debug = True

        self.devices = {}
        self.updates = {}
        self.setups = {}
        self.stats = {}
Example #7
0
 def __init__(self,
              broker="10.129.7.199",
              port=1883,
              username="******",
              password="******",
              client_id="12345"):
     self.broker = broker
     self.port = port
     self.username = username
     self.password = password
     self.payload = None
     self.client_id = client_id
     self.num = 1
     self.flag = 0
     try:
         # self.mqttc=Client(clean_session=False,client_id="12345")
         self.mqttc = Client(client_id=self.client_id)
         self.mqttc.on_connect = self.on_connect
         self.mqttc.on_publish = self.on_publish
         self.mqttc.on_subscribe = self.on_subscribe
         self.mqttc.username_pw_set(self.username, self.password)
         self.mqttc.connect(self.broker, port=self.port)
         self.mqttc.loop_start()
     except:
         print(
             "mqtt_client_connect error: mqttc connect failed Please check Broker and Port...."
         )
 def __init__(self, gateway, config, connector_type):
     super().__init__()
     self.__log = log
     self.config = config
     self.__connector_type = connector_type
     self.statistics = {'MessagesReceived': 0, 'MessagesSent': 0}
     self.__gateway = gateway
     self.__broker = config.get('broker')
     self.__mapping = config.get('mapping')
     self.__server_side_rpc = config.get('serverSideRpc')
     self.__service_config = {
         "connectRequests": None,
         "disconnectRequests": None
     }
     self.__attribute_updates = []
     self.__get_service_config(config)
     self.__sub_topics = {}
     client_id = ''.join(
         random.choice(string.ascii_lowercase) for _ in range(23))
     self._client = Client(client_id)
     self.setName(
         config.get(
             "name",
             self.__broker.get(
                 "name", 'Mqtt Broker ' + ''.join(
                     random.choice(string.ascii_lowercase)
                     for _ in range(5)))))
     if "username" in self.__broker["security"]:
         self._client.username_pw_set(self.__broker["security"]["username"],
                                      self.__broker["security"]["password"])
     if "caCert" in self.__broker["security"] or self.__broker[
             "security"].get("type", "none").lower() == "tls":
         ca_cert = self.__broker["security"].get("caCert")
         private_key = self.__broker["security"].get("privateKey")
         cert = self.__broker["security"].get("cert")
         if ca_cert is None:
             self._client.tls_set_context(
                 ssl.SSLContext(ssl.PROTOCOL_TLSv1_2))
         else:
             try:
                 self._client.tls_set(ca_certs=ca_cert,
                                      certfile=cert,
                                      keyfile=private_key,
                                      cert_reqs=ssl.CERT_REQUIRED,
                                      tls_version=ssl.PROTOCOL_TLSv1_2,
                                      ciphers=None)
             except Exception as e:
                 self.__log.error(
                     "Cannot setup connection to broker %s using SSL. Please check your configuration.\nError: %s",
                     self.get_name(), e)
             self._client.tls_insecure_set(False)
     self._client.on_connect = self._on_connect
     self._client.on_message = self._on_message
     self._client.on_subscribe = self._on_subscribe
     self.__subscribes_sent = {}  # For logging the subscriptions
     self._client.on_disconnect = self._on_disconnect
     self._client.on_log = self._on_log
     self._connected = False
     self.__stopped = False
     self.daemon = True
Example #9
0
    def __init__(self,
                 host: str,
                 token: str,
                 config: dict,
                 ble: bool = True,
                 zha: bool = False):
        super().__init__(daemon=True)

        self.host = host
        self.ble = ble
        self.zha = zha

        self.miio = Device(host, token)

        self.mqtt = Client()
        self.mqtt.on_connect = self.on_connect
        self.mqtt.on_disconnect = self.on_disconnect
        self.mqtt.on_message = self.on_message
        self.mqtt.connect_async(host)

        self._debug = config['debug'] if 'debug' in config else ''
        self._disable_buzzer = config.get('buzzer') is False
        self._config = config
        self.default_devices = config['devices']

        self.devices = {}
        self.updates = {}
        self.setups = {}
    def on_start(self):
        self._publish_clock = None
        self.mqtt_broker_bridged = False
        self._associated = True
        self.association_code = None
        self.mqtt = Client(client_id=MQTT_CLIENT_ID)
        self.mqtt.will_set(client_state_topic(MQTT_CLIENT_ID), "0",
                           qos=2, retain=True)
        self.mqtt.on_connect = self.on_connect
        self.mqtt.connect(MQTT_BROKER_HOST, port=MQTT_BROKER_PORT,
                          keepalive=MQTT_BROKER_KEEP_ALIVE_SECS)
        self.mqtt.loop_start()
        self.set_up_GPIO_and_device_status_popup()
        self.associated_status_popup = self._build_associated_status_popup()
        self.associated_status_popup.bind(on_open=self.update_popup_associated)

        k = "2d19784349d26a0853b4c54397d7ff07"
        owm =  pyowm.OWM(k)
        observation = owm.weather_at_place('Cleveland, US')
        w = observation.get_weather()
        self.temperature = w.get_temperature('fahrenheit')['temp_min']

        if w.get_rain() > 50:
            self.rain = True
        else:
            self.rain = False

        if w.get_snow():
            self.snow = True
        else:
            self.snow = False

        Clock.schedule_interval(self._poll_associated, 0.1)
Example #11
0
    def main(self):
        self.mqttc = Client()
        self.mqttc.will_set("{}/status".format(self.prefix),
                            'offline',
                            retain=True)
        self.mqttc.enable_logger()
        self.mqttc.username_pw_set(
            self.config.get('mqtt', {}).get('username', 'homeassistant'),
            self.config.get('mqtt', {}).get('password', ''))
        self.mqttc.on_connect = self.on_connect

        self.disc_config = {
            'state_topic':
            "{}/state".format(self.prefix),
            #'expire_after': 10,
            'name':
            self.config.get('name', '{} co2mini'.format(platform.node())),
            'unit_of_measurement':
            'ppm',
            'icon':
            'mdi:periodic-table-co2',
            'availability_topic':
            "{}/status".format(self.prefix),
            'payload_available':
            "online",
            'payload_not_available':
            "offline",
            'json_attributes_topic':
            "{}/attributes".format(self.prefix),
            'force_update':
            self.config.get('force_update', False),
            'unique_id':
            '{}:{}'.format(platform.node(),
                           self.config.get('device', '/dev/co2mini0')),
            'device': {
                'connections': [
                    ['usb', self.config.get('device', '/dev/co2mini0')],
                ],
                'identifiers': (platform.node()),
                'manufacturer':
                'Various',
                'model':
                'co2mini',
            }
        }

        self.sensor = CO2Meter(self.config.get('device', '/dev/co2mini0'),
                               self.sensor_callback)

        self.mqttc.connect(self.config.get('mqtt',
                                           {}).get('broker', '127.0.0.1'),
                           port=self.config.get('mqtt', {}).get('port', 1883),
                           keepalive=self.config.get('mqtt',
                                                     {}).get('keepalive', 60))
        self.mqttc.loop_start()

        while self.alive:
            self.alive = False
            time.sleep(10)
Example #12
0
 def connect(self, host="localhost", port=5000, topic="test"):
     print("Connected")
     self.client = Client()
     self.client.connect(host=host)
     self.client.on_message = self.recv_message
     self.client.on_subscribe = self.on_subscribe
     self.client.subscribe(topic)
     self.client.loop_forever()
 def __init__(self):
     self.received_lamp_state = None
     self.color_database = json.load(open('color.json'))
     self.client = Client(client_id='google_home')
     self.client.on_connect = self.on_connect
     self.client.connect('localhost', port=1883, keepalive=60)
     self._wait_for_lamp_state()
     self.client.loop_start()
Example #14
0
 def __init__(self) -> None:
     self.client = Client()
     self.client.on_connect = self.on_connect
     self.client.on_message = self.on_message
     self.client.on_publish = self.on_publish
     self.client.on_disconnect = self.on_disconnect
     self.client.on_unsubscribe = self.on_unsubscribe
     self.client.on_subscribe = self.on_subscribe
Example #15
0
 def __init__(self) -> None:
     self.uuid = str(uuid.uuid4())
     self.client = Client(self.uuid, True)
     self.telemetry_topic = os.environ['TELEMETRY_TOPIC']
     self.qos = 0
     self.client.connected_flag = False
     self.client.disconnect_flag = False
     self.client.bad_connection_flag = False
Example #16
0
    def get_mqtt_client(self, client_id: str) -> Client:
        """
        Returns an MQTT client for a given client ID

        Parameters:
            client_id: The client ID to use with the MQTT broker.
        """
        return Client(client_id)
Example #17
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 #18
0
def check_broker():
    from paho.mqtt.client import Client
    try:
        client = Client()
        client.connect('localhost', 1883)
        return True
    except Exception as e:
        return False
Example #19
0
def main():
    try:
        client = Client("Misol")  # create new instance
        client.connect("192.168.1.3")  # connect to broker

        client.publish("/devices/misol/meta/name",
                       "Misol Meteostation",
                       qos=0,
                       retain=True)

        for order, topic in enumerate(TOPICS, 1):
            publish(client, topic, order)

        log.debug("Connected to MQTT")

        s = Serial('/dev/ttyUSB0', 9600, timeout=60)

        log.debug("Connected to serial")

        while True:
            log.debug("Start Read")

            raw = s.read(21)

            checksum = sum(i for i in raw[:16]) & 0xFF
            assert checksum == raw[16], "Wrong checksum"

            wd = wdata.from_buffer_copy(raw)
            rwd: RawWeatherData = wd.rawdata

            wind = ((wd.rawdata.WSP8 << 8) + wd.rawdata.WIND) / 8 * 1.12
            uvi = next((i for i, v in enumerate(UVI) if rwd.UVI <= v), 13)

            payload = {
                'wind_direction': (wd.rawdata.DIR8 << 8) + wd.rawdata.DIR,
                'battery_low': rwd.BAT,
                'temperature': (rwd.TMP - 400) / 10.0,
                'humidity': rwd.HM,
                'wind_speed': round(wind),
                'wind_gust': round(rwd.GUST * 1.12),
                'rain': rwd.RAIN,
                'uvi': uvi,
                'light': round(rwd.LIGHT / 10.0),
                'bar': round(rwd.BAR / 100.0, 2),
                'last_update': int(time.time())
            }

            for k, v in payload.items():
                info = client.publish(f"{BASE}/{k}", v, retain=True)
                assert info.rc == MQTT_ERR_SUCCESS, f"MQTT Error: {info.rc}"

            log.debug("Updated MQTT")

    except AssertionError as e:
        log.error(e)

    except:
        log.exception("Exception")
 def __init__(self, broker: str, port: int):
     """
     Instantiate the device
     :param broker: MQTT broker
     :param port: Port of the broker
     """
     self.broker = broker
     self.port = port
     self.client = Client(client_id="FakeThermometer")
Example #21
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)
Example #22
0
 def __init__(self):
     self.client = Client("sample-subscriber")
     self.client.on_connect = self.on_connect
     self.client.on_message = self.on_message
     self.client.on_subscribe = self.on_subscribe
     self.client.username_pw_set(username=config.RABBITMQ_USERNAME,
                                 password=config.RABBITMQ_PASSWORD)
     self.client.connect(config.RABBITMQ_HOST, config.RABBITMQ_PORT, 60)
     self.client.subscribe(config.RABBITMQ_TOPIC)
 def __init__(self):
     """
     Instantiate the service
     """
     self.service = Client(client_id=f"EMailService{randrange(1, 100000)}")
     self.service.on_message = partial(self.my_on_message,
                                       email_service=self.service)
     self.user_lock = Lock()
     self.service_lock = Lock()
Example #24
0
 def __init__(self, broker: str, port: int):
     """
     Instantiate the device
     :param broker: Mqtt broker
     :param port: Port of the broker
     """
     self.broker = broker
     self.port = port
     self.client = Client(client_id=f"FakeThermometer{randrange(1, 100000)}")
Example #25
0
    def __init__(self, sampling_rate=1000):
        self.sampling_rate = sampling_rate

        self.thread_delay = sampling_rate / 1000 / 3
        self.mqtt_client = Client(client_id="pcmonitor")

        self.cpu_component = None
        self.mem_component = None
        self.net_component = None
Example #26
0
 def __init__(self):
     """
     Instantiate the service
     """
     self.service = Client(
         client_id=f"TelegramService{randrange(1, 100000)}")
     self.service.on_message = self.my_on_message
     self.char_id_lock = Lock()
     self.service_lock = Lock()
 def __init__(self, broker: str, port: int):
     """
     Instantiate the device
     :param broker: MQTT broker
     :param port: Port of the broker
     """
     self.broker = broker
     self.port = port
     self.client = Client(client_id=f"FakeSmartHome{randrange(1, 100000)}")
     self.client.on_message = self.my_on_message
 def __init__(self):
     """
     Instantiate the service
     """
     self.service = Client(client_id=f"AlarmService{randrange(1, 100000)}")
     self.service.on_message = partial(self.my_on_message,
                                       led=self.service,
                                       service=self.service)
     self.lock = Lock()
     self.device_lock = Lock()
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 #30
0
def main():
    client = Client(protocol=MQTTv311)
    client.username_pw_set(USERNAME, password=PASSWORD)
    client.connect(HOST, port=PORT, keepalive=60)

    while True:
        data = read_sensor_data()
        print(data)
        client.publish(TOPIC, payload=dumps(data))
        sleep(5)