Skip to content

hololinked.client.factory.ClientFactory

A factory class for creating clients to interact with Things over different protocols.

This object is not meant to be instantiated, but rather provides class methods for creating clients.

Documentation

Example:

from hololinked.client import ClientFactory

zmq_client = ClientFactory.zmq(server_id="server1", thing_id="thing1", access_point="IPC")
http_client = ClientFactory.http(url="https://example.com/thing-description")
mqtt_client = ClientFactory.mqtt(hostname="broker.example.com", port=8883, thing_id="thing1")
Source code in repo/hololinked/hololinked/client/factory.py
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
class ClientFactory:
    """
    A factory class for creating clients to interact with `Thing`s over different protocols.

    This object is not meant to be instantiated, but rather provides class methods for creating clients.

    [Documentation](https://docs.hololinked.dev/beginners-guide/articles/object-proxy/#__tabbed_1_1)

    Example:

    ```python
    from hololinked.client import ClientFactory

    zmq_client = ClientFactory.zmq(server_id="server1", thing_id="thing1", access_point="IPC")
    http_client = ClientFactory.http(url="https://example.com/thing-description")
    mqtt_client = ClientFactory.mqtt(hostname="broker.example.com", port=8883, thing_id="thing1")
    ```
    """

    __wrapper_assignments__ = ("__name__", "__qualname__", "__doc__")
    """Dunder attributes to be assigned onto dynamically populated properties, actions and events."""

    @staticmethod
    def zmq(
        server_id: str,
        thing_id: str,
        access_point: str = ZMQ_TRANSPORTS.IPC,
        **kwargs,
    ) -> ObjectProxy:
        """
        Create a ZMQ client for the specified server and thing.

        [Documentation](https://docs.hololinked.dev/beginners-guide/articles/object-proxy/#__tabbed_1_1)

        Provide the server ID and thing ID used to start the `Thing` instance, apart from the protocol or access point
        of the ZMQ transport mechanism. If a shorthand method like `Thing.run_with_zmq_server()` was used without
        specifying the server ID, the thing ID is the server ID by default.

        ```python
        thing = Thing("thing1")
        thing.run_with_zmq_server(access_point="IPC", forked=True)

        client = ClientFactory.zmq(
            server_id="thing1",
            thing_id="thing1",
            access_point="IPC"
        )
        ```

        ```python
        thing = Thing("thing1")
        thing.run_with_zmq_server(access_point="IPC", server_id="thing1-server", forked=True)

        client = ClientFactory.zmq(
            server_id="thing1-server",
            thing_id="thing1",
            access_point="IPC"
        )
        ```

        ```python
        thing = Thing("thing1")
        server = ZMQServer(thing, id="thing1-server", access_point="tcp://*:3569")
        server.run(forked=True)

        client = ClientFactory.zmq(
            server_id="thing1-server",
            thing_id="thing1",
            access_point="tcp://localhost:3569"
        )
        ```

        Parameters
        ----------
        server_id: str
            The ID of the server to connect to
        thing_id: str
            The ID of the thing to interact with
        access_point: str
            The ZMQ protocol to use for communication (`IPC` or `INPROC`) or `tcp://<host>:<port>` for TCP
        kwargs:
            Additional configuration options:

            - `logger`: `structlog.stdlib.BoundLogger`, optional.
                 A custom logger instance to use for logging
            - `ignore_TD_errors`: `bool`, default `False`.
                Whether to ignore errors while fetching the Thing Description (TD). Supported only for this runtime,
                not against a 3rd party Web of Things (WoT) implementation.
            - `skip_interaction_affordances`: `list[str]`, default `[]`.
                A list of interaction names to skip (any of property, action or event names)
            - `invokation_timeout`: `float`, optional, default `5.0`.
                The timeout for invokation requests (in seconds)
            - `execution_timeout`: `float`, optional, default `5.0`.
                The timeout for execution requests (in seconds)

        Returns
        -------
        ObjectProxy
            An `ObjectProxy` instance representing the remote `Thing` with ZMQ protocol.

        Raises
        ------
        ImportError
            if `pyzmq` is not installed - `pip install pyzmq`. Version should be less than 26.2 to support IPC in
            windows machines.
        ModuleNotFoundError
            if some other dependency of the ZMQ client is missing
        """
        from hololinked.client.zmq.consumed_interactions import (
            ReadMultipleProperties,
            WriteMultipleProperties,
            ZMQAction,
            ZMQEvent,
            ZMQProperty,
        )
        from hololinked.server.zmq import AsyncZMQClient, SyncZMQClient

        id = kwargs.get("id", f"{server_id}|{thing_id}|{access_point}|{uuid_hex()}")

        # configs
        ignore_TD_errors = kwargs.get("ignore_TD_errors", False)
        skip_interaction_affordances = kwargs.get("skip_interaction_affordances", [])
        invokation_timeout = kwargs.get("invokation_timeout", 5.0)
        execution_timeout = kwargs.get("execution_timeout", 5.0)
        logger = kwargs.get("logger", structlog.get_logger()).bind(
            component="client",
            client_id=id,
            protocol="zmq",
            thing_id=thing_id,
        )

        # ZMQ req-rep clients
        sync_zmq_client = SyncZMQClient(f"{id}|sync", server_id=server_id, logger=logger, access_point=access_point)
        async_zmq_client = AsyncZMQClient(f"{id}|async", server_id=server_id, logger=logger, access_point=access_point)

        # Fetch the TD
        Thing.get_thing_model  # noqa: B018  # type: Action
        FetchTDAffordance = Thing.get_thing_model.to_metadata()
        FetchTDAffordance.override_defaults(name="get_thing_description", thing_id=thing_id)
        FetchTD = ZMQAction(
            resource=FetchTDAffordance,
            sync_client=sync_zmq_client,
            async_client=async_zmq_client,
            invokation_timeout=invokation_timeout,
            execution_timeout=execution_timeout,
            owner_inst=None,
            logger=logger,
        )
        TD = FetchTD(
            ignore_errors=ignore_TD_errors,
            protocol=access_point.split("://")[0].upper() if access_point else "IPC",
            skip_names=skip_interaction_affordances,
        )  # dict[str, Any]

        # create ObjectProxy
        object_proxy = ObjectProxy(
            id=id,
            td=TD,
            logger=logger,
            invokation_timeout=invokation_timeout,
            execution_timeout=execution_timeout,
            security=kwargs.get("security", None),
        )

        # add properties
        for name in TD.get("properties", []):
            affordance = PropertyAffordance.from_TD(name, TD)
            consumed_property = ZMQProperty(
                resource=affordance,
                sync_client=sync_zmq_client,
                async_client=async_zmq_client,
                owner_inst=object_proxy,
                invokation_timeout=invokation_timeout,
                execution_timeout=execution_timeout,
                logger=logger,
            )
            ClientFactory.add_property(object_proxy, consumed_property)
            if hasattr(affordance, "observable") and affordance.observable:
                consumed_observable = ZMQEvent(
                    resource=affordance,
                    owner_inst=object_proxy,
                    logger=logger,
                )
                ClientFactory.add_event(object_proxy, consumed_observable)
        # add actions
        for action in TD.get("actions", []):
            affordance = ActionAffordance.from_TD(action, TD)
            consumed_action = ZMQAction(
                resource=affordance,
                sync_client=sync_zmq_client,
                async_client=async_zmq_client,
                owner_inst=object_proxy,
                invokation_timeout=invokation_timeout,
                execution_timeout=execution_timeout,
                logger=logger,
            )
            ClientFactory.add_action(object_proxy, consumed_action)
        # add events
        for event in TD.get("events", []):
            affordance = EventAffordance.from_TD(event, TD)
            consumed_event = ZMQEvent(
                resource=affordance,
                owner_inst=object_proxy,
                logger=logger,
            )
            ClientFactory.add_event(object_proxy, consumed_event)
        # add top level form handlers (for ZMQ even if said form exists or not)
        for opname, ophandler in zip(
            ["_get_properties", "_set_properties"],
            [ReadMultipleProperties, WriteMultipleProperties],
        ):
            setattr(
                object_proxy,
                opname,
                ophandler(
                    sync_client=sync_zmq_client,
                    async_client=async_zmq_client,
                    owner_inst=object_proxy,
                    invokation_timeout=invokation_timeout,
                    execution_timeout=execution_timeout,
                    logger=logger,
                ),
            )
        return object_proxy

    @staticmethod
    def http(url: str, **kwargs) -> ObjectProxy:
        """
        Create a HTTP client using the Thing Description (TD) available at the specified URL.

        [Documentation](https://docs.hololinked.dev/beginners-guide/articles/object-proxy/#__tabbed_1_1)

        ```python
        client = ClientFactory.http(
            url="https://example.com/thing-description",
            username="user",
            password="pass"
        )
        ```

        ```python
        thing = Thing("thing1")
        thing.run_with_http_server(port=8080, forked=True)

        client = ClientFactory.http(
            url="http://localhost:8080/thing1/resources/wot-td",
            ignore_TD_errors=True
        )
        ```

        Parameters
        ----------
        url: str
            The URL of the Thing Description (TD) to fetch.
        kwargs:
            Additional configuration options:

            - `logger`: `structlog.stdlib.BoundLogger`, optional.
                A custom logger instance to use for logging
            - `ignore_TD_errors`: `bool`, default `False`.
                Whether to ignore errors while fetching the Thing Description (TD)
            - `skip_interaction_affordances`: `list[str]`, default `[]`.
                A list of interaction names to skip (any of property, action or event names)
            - `invokation_timeout`: `float`, optional, default `5.0`.
                The timeout for operation invokation (in seconds), for example when invoking an action or
                reading/writing a property. This is a server-side timeout.
            - `execution_timeout`: `float`, optional, default `5.0`.
                The timeout for operation execution (in seconds) - the time it waits for an operation to be completed
                after invokation before timing out. This is a server-side timeout.
            - `connect_timeout`: `float`, optional, default `10.0`.
                The timeout for establishing a HTTP connection (in seconds). This is a client-side timeout.
            - `request_timeout`: `float`, optional, default `60.0`.
                The timeout for completing a HTTP request (in seconds) after the connection is established.
                This is a client-side timeout.
            - `security`: `BasicSecurity` | `APIKeySecurity` | `OAuthDirectAccessGrant`, optional.
                The security scheme to use for authentication. Not all schemes are supported for all protocols.
                See [here](https://docs.hololinked.dev/introduction/use-cases/).
            - `username`: `str`, optional.
                The username for HTTP Basic Authentication, shortcut for creating a `BasicSecurity` instance
            - `password`: `str`, optional.
                The password for HTTP Basic Authentication, shortcut for creating a `BasicSecurity` instance
            - `verify_ssl`: `bool` | `str`, default `True`.
                Whether to verify the server's TLS certificate, or the path to a CA bundle to verify it against.
                Pass `False` to accept untrusted certificates, for example a self signed one used in development.
                Note that `OAuthDirectAccessGrant` contacts the identity provider itself, so pass `verify_ssl`
                there as well if that endpoint also serves an untrusted certificate.
            - `ssl_context`: `ssl.SSLContext`, optional.
                A preconfigured SSL context, which takes precedence over `verify_ssl`.

        Returns
        -------
        ObjectProxy
            An `ObjectProxy` instance representing the remote Thing with HTTP protocol.
        """
        import httpx

        from hololinked.client.http.consumed_interactions import (
            HTTPAction,
            HTTPEvent,
            HTTPProperty,
        )

        # config
        skip_interaction_affordances = kwargs.get("skip_interaction_affordances", [])
        invokation_timeout = kwargs.get("invokation_timeout", 5.0)
        execution_timeout = kwargs.get("execution_timeout", 5.0)
        connect_timeout = kwargs.get("connect_timeout", 10.0)
        request_timeout = kwargs.get("request_timeout", 60.0)
        verify_ssl = kwargs.get("verify_ssl", True)
        ssl_context = kwargs.get("ssl_context", None)
        if ssl_context is None and isinstance(verify_ssl, str):
            ssl_context = ssl.create_default_context(cafile=verify_ssl)
        verify = ssl_context if ssl_context is not None else verify_ssl
        if verify is False:
            warnings.warn(
                "TLS certificate verification is disabled, the identity of the server is not checked.",
                category=UserWarning,
                stacklevel=2,
            )

        use_localhost = False
        if (
            "http://localhost" in url
            or "http://localhost" in url
            or "http://[::1]" in url
            or "http://[::1]" in url
            or "http://127.0.0.1" in url
        ):
            use_localhost = True

        # create clients
        req_rep_timeout = httpx.Timeout(
            connect=connect_timeout,
            read=request_timeout,
            write=request_timeout,
            pool=2,
        )
        sse_timeout = httpx.Timeout(
            connect=connect_timeout,
            # no heartbeats, indefinite read timeout for now
            read=None,
            write=request_timeout,
            pool=2,
        )

        req_rep_sync_client = httpx.Client(timeout=req_rep_timeout, verify=verify)
        req_rep_async_client = httpx.AsyncClient(timeout=req_rep_timeout, verify=verify)
        sse_sync_client = httpx.Client(timeout=sse_timeout, verify=verify)
        sse_async_client = httpx.AsyncClient(timeout=sse_timeout, verify=verify)

        # fetch TD
        url = (
            f"{url}?"
            + f"ignore_errors={str(kwargs.get('ignore_TD_errors', False)).lower()}"
            + (f"&skip_names={','.join(skip_interaction_affordances)}" if skip_interaction_affordances else "")
            + f"&use_localhost={str(use_localhost).lower()}"
        )

        # fetch TD
        headers = {"Content-Type": "application/json"}
        security = kwargs.pop("security", None)
        username = kwargs.pop("username", None)
        password = kwargs.pop("password", None)
        if not security and username and password:
            security = BasicSecurity(username=username, password=password)
        if security and not isinstance(security, OAuthDirectAccessGrant):
            headers[security.http_header_name] = security.http_header
        if security and isinstance(security, OAuthDirectAccessGrant):
            security = OAuth2Security(
                security,
                req_rep_sync_client=req_rep_sync_client,
                req_rep_async_client=req_rep_async_client,
            )
            security.login()
            headers[security.http_header_name] = security.http_header

        response = req_rep_sync_client.get(url, headers=headers)  # type: httpx.Response
        response.raise_for_status()

        TD = Serializers.json.loads(response.content)
        id = kwargs.get("id", f"client|{TD['id']}|HTTP|{uuid_hex()}")
        logger = kwargs.get("logger", structlog.get_logger()).bind(
            component="client",
            client_id=id,
            protocol="http",
            thing_id=TD["id"],
        )
        object_proxy = ObjectProxy(id, td=TD, logger=logger, security=security, **kwargs)

        for name in TD.get("properties", []):
            affordance = PropertyAffordance.from_TD(name, TD)
            consumed_property = HTTPProperty(
                resource=affordance,
                sync_client=req_rep_sync_client,
                async_client=req_rep_async_client,
                invokation_timeout=invokation_timeout,
                execution_timeout=execution_timeout,
                owner_inst=object_proxy,
                logger=logger,
            )
            ClientFactory.add_property(object_proxy, consumed_property)
            if affordance.observable:
                consumed_event = HTTPEvent(
                    resource=affordance,
                    sync_client=sse_sync_client,
                    async_client=sse_async_client,
                    invokation_timeout=invokation_timeout,
                    execution_timeout=execution_timeout,
                    owner_inst=object_proxy,
                    logger=logger,
                )
                ClientFactory.add_event(object_proxy, consumed_event)
        for action in TD.get("actions", []):
            affordance = ActionAffordance.from_TD(action, TD)
            consumed_action = HTTPAction(
                resource=affordance,
                sync_client=req_rep_sync_client,
                async_client=req_rep_async_client,
                invokation_timeout=invokation_timeout,
                execution_timeout=execution_timeout,
                owner_inst=object_proxy,
                logger=logger,
            )
            ClientFactory.add_action(object_proxy, consumed_action)
        for event in TD.get("events", []):
            affordance = EventAffordance.from_TD(event, TD)
            consumed_event = HTTPEvent(
                resource=affordance,
                sync_client=sse_sync_client,
                async_client=sse_async_client,
                invokation_timeout=invokation_timeout,
                execution_timeout=execution_timeout,
                owner_inst=object_proxy,
                logger=logger,
            )
            ClientFactory.add_event(object_proxy, consumed_event)

        return object_proxy

    @staticmethod
    def mqtt(
        hostname: str,
        port: int,
        thing_id: str,
        protocol_version: MQTTProtocolVersion | None = None,
        qos: int = 1,
        username: str | None = None,
        password: str | None = None,
        ssl_context: ssl.SSLContext | None = None,
        **kwargs,
    ) -> ObjectProxy:
        """
        Create an MQTT client against the specified broker for the specified thing ID.

        [Documentation](https://docs.hololinked.dev/beginners-guide/articles/object-proxy/#__tabbed_1_1)

        Parameters
        ----------
        hostname: str
            The hostname of the MQTT broker.
        port: int
            The port of the MQTT broker.
        thing_id: str
            The ID of the thing to consume events from.
        protocol_version: paho.mqtt.client.MQTTProtocolVersion, optional
            The MQTT protocol version, MQTTv5 when not given.
        qos: int
            The Quality of Service level for MQTT messages (0, 1, or 2).
        username: str, optional
            The username for authenticating with MQTT broker.
        password: str, optional
            The password for authenticating with MQTT broker.
        ssl_context: ssl.SSLContext, optional
            Secure sockets layer for encrypted communication with the MQTT broker.
        kwargs:
            Additional configuration options:

            - `logger`: `structlog.stdlib.BoundLogger`, optional.
                 A custom logger instance to use for logging

        Returns
        -------
        ObjectProxy
            An `ObjectProxy` instance representing the remote `Thing` with MQTT protocol.

        Raises
        ------
        TimeoutError
            If the Thing Description (TD) could not be fetched within the timeout period.
        """
        import aiomqtt

        from paho.mqtt.client import CallbackAPIVersion, MQTTProtocolVersion
        from paho.mqtt.client import Client as PahoMQTTClient

        from hololinked.client.mqtt.consumed_interactions import MQTTConsumer

        if protocol_version is None:
            protocol_version = MQTTProtocolVersion.MQTTv5

        id = kwargs.get("id", f"mqtt-client|{hostname}:{port}|{uuid_hex()}")
        logger = kwargs.get("logger", structlog.get_logger()).bind(
            component="client",
            client_id=id,
            protocol="mqtt",
            thing_id=thing_id,
        )

        td_received_event = threading.Event()
        TD = None

        def fetch_td(client: PahoMQTTClient, userdata, message: MQTTMessage) -> None:
            nonlocal TD, thing_id, logger
            if message.topic != f"{thing_id}/thing-description":
                return
            TD = Serializers.json.loads(message.payload)
            td_received_event.set()

        def on_connect(
            client: PahoMQTTClient,
            userdata: Any,
            connect_flags: Any,
            reason_code: list,
            properties: dict[str, Any],
        ) -> None:  # TODO fix signature
            nonlocal qos
            client.subscribe(f"{thing_id}/#", qos=qos)

        sync_client = PahoMQTTClient(
            callback_api_version=CallbackAPIVersion.VERSION2,
            client_id=id,
            clean_session=True if protocol_version != MQTTProtocolVersion.MQTTv5 else None,
            protocol=protocol_version,
        )
        if username and password:
            sync_client.username_pw_set(username=username, password=password)
        if ssl_context is not None:
            sync_client.tls_set_context(ssl_context)
        elif kwargs.get("ca_certs", None):
            sync_client.tls_set(ca_certs=kwargs.get("ca_certs", None))
        setattr(sync_client, "on_connect", on_connect)
        setattr(sync_client, "on_message", fetch_td)
        sync_client.connect(hostname, port)
        sync_client.loop_start()

        td_received_event.wait(timeout=10)
        if not TD:
            raise TimeoutError("Timeout while fetching Thing Description (TD) over MQTT")

        if not sync_client._ssl_context and port != 1883:
            warnings.warn(
                "MQTT used without TLS, if you intended to use TLS with a recognised CA & you saw this warning, considering "
                + "opening an issue at https://github.com/hololinked-dev/hololinked. ",
                category=RuntimeWarning,
            )

        async_client = aiomqtt.Client(
            hostname=hostname,
            port=port,
            username=username,
            password=password,
            protocol=protocol_version,
            tls_context=sync_client._ssl_context,
        )

        object_proxy = ObjectProxy(id=id, logger=logger, td=TD)

        for name in TD.get("properties", []):
            affordance = cast(PropertyAffordance, PropertyAffordance.from_TD(name, TD))
            consumed_property = MQTTConsumer(
                sync_client=sync_client,
                async_client=async_client,
                resource=affordance,
                qos=qos,
                logger=logger,
                owner_inst=object_proxy,
            )
            ClientFactory.add_event(object_proxy, consumed_property)
        for name in TD.get("events", []):
            affordance = cast(EventAffordance, EventAffordance.from_TD(name, TD))
            consumed_event = MQTTConsumer(
                sync_client=sync_client,
                async_client=async_client,
                resource=affordance,
                qos=qos,
                logger=logger,
                owner_inst=object_proxy,
            )
            ClientFactory.add_event(object_proxy, consumed_event)

        return object_proxy

    @staticmethod
    def add_action(client, action: ConsumedThingAction) -> None:
        """Add action to the client instance."""
        action.__name__ = action.resource.name
        action.__qualname__ = f"{client.__class__.__name__}.{action.resource.name}"
        action.__doc__ = action.resource.description or f"Invokes the action {action.resource.name} on the remote Thing"
        setattr(client, action.resource.name, action)

    @staticmethod
    def add_property(client, property: ConsumedThingProperty) -> None:
        """Add property to the client instance."""
        property.__name__ = property.resource.name
        property.__qualname__ = f"{client.__class__.__name__}.{property.resource.name}"
        property.__doc__ = (
            property.resource.description or f"Represents the property {property.resource.name} on the remote Thing"
        )
        setattr(client, property.resource.name, property)

    @staticmethod
    def add_event(client, event: ConsumedThingEvent) -> None:
        """Add event to the client instance."""
        event.__name__ = event.resource.name
        event.__qualname__ = f"{client.__class__.__name__}.{event.resource.name}"
        event.__doc__ = event.resource.description or f"Represents the event {event.resource.name} on the remote Thing"
        if hasattr(event.resource, "observable") and event.resource.observable:
            setattr(client, f"{event.resource.name}_change_event", event)
        else:
            setattr(client, event.resource.name, event)

Functions

zmq staticmethod

zmq(server_id: str, thing_id: str, access_point: str = ZMQ_TRANSPORTS.IPC, **kwargs) -> ObjectProxy

Create a ZMQ client for the specified server and thing.

Documentation

Provide the server ID and thing ID used to start the Thing instance, apart from the protocol or access point of the ZMQ transport mechanism. If a shorthand method like Thing.run_with_zmq_server() was used without specifying the server ID, the thing ID is the server ID by default.

thing = Thing("thing1")
thing.run_with_zmq_server(access_point="IPC", forked=True)

client = ClientFactory.zmq(
    server_id="thing1",
    thing_id="thing1",
    access_point="IPC"
)
thing = Thing("thing1")
thing.run_with_zmq_server(access_point="IPC", server_id="thing1-server", forked=True)

client = ClientFactory.zmq(
    server_id="thing1-server",
    thing_id="thing1",
    access_point="IPC"
)
thing = Thing("thing1")
server = ZMQServer(thing, id="thing1-server", access_point="tcp://*:3569")
server.run(forked=True)

client = ClientFactory.zmq(
    server_id="thing1-server",
    thing_id="thing1",
    access_point="tcp://localhost:3569"
)

Parameters:

Name Type Description Default

server_id

str

The ID of the server to connect to

required

thing_id

str

The ID of the thing to interact with

required

access_point

str

The ZMQ protocol to use for communication (IPC or INPROC) or tcp://<host>:<port> for TCP

IPC

kwargs

Additional configuration options:

  • logger: structlog.stdlib.BoundLogger, optional. A custom logger instance to use for logging
  • ignore_TD_errors: bool, default False. Whether to ignore errors while fetching the Thing Description (TD). Supported only for this runtime, not against a 3rd party Web of Things (WoT) implementation.
  • skip_interaction_affordances: list[str], default []. A list of interaction names to skip (any of property, action or event names)
  • invokation_timeout: float, optional, default 5.0. The timeout for invokation requests (in seconds)
  • execution_timeout: float, optional, default 5.0. The timeout for execution requests (in seconds)
{}

Returns:

Type Description
ObjectProxy

An ObjectProxy instance representing the remote Thing with ZMQ protocol.

Raises:

Type Description
ImportError

if pyzmq is not installed - pip install pyzmq. Version should be less than 26.2 to support IPC in windows machines.

ModuleNotFoundError

if some other dependency of the ZMQ client is missing

Source code in repo/hololinked/hololinked/client/factory.py
@staticmethod
def zmq(
    server_id: str,
    thing_id: str,
    access_point: str = ZMQ_TRANSPORTS.IPC,
    **kwargs,
) -> ObjectProxy:
    """
    Create a ZMQ client for the specified server and thing.

    [Documentation](https://docs.hololinked.dev/beginners-guide/articles/object-proxy/#__tabbed_1_1)

    Provide the server ID and thing ID used to start the `Thing` instance, apart from the protocol or access point
    of the ZMQ transport mechanism. If a shorthand method like `Thing.run_with_zmq_server()` was used without
    specifying the server ID, the thing ID is the server ID by default.

    ```python
    thing = Thing("thing1")
    thing.run_with_zmq_server(access_point="IPC", forked=True)

    client = ClientFactory.zmq(
        server_id="thing1",
        thing_id="thing1",
        access_point="IPC"
    )
    ```

    ```python
    thing = Thing("thing1")
    thing.run_with_zmq_server(access_point="IPC", server_id="thing1-server", forked=True)

    client = ClientFactory.zmq(
        server_id="thing1-server",
        thing_id="thing1",
        access_point="IPC"
    )
    ```

    ```python
    thing = Thing("thing1")
    server = ZMQServer(thing, id="thing1-server", access_point="tcp://*:3569")
    server.run(forked=True)

    client = ClientFactory.zmq(
        server_id="thing1-server",
        thing_id="thing1",
        access_point="tcp://localhost:3569"
    )
    ```

    Parameters
    ----------
    server_id: str
        The ID of the server to connect to
    thing_id: str
        The ID of the thing to interact with
    access_point: str
        The ZMQ protocol to use for communication (`IPC` or `INPROC`) or `tcp://<host>:<port>` for TCP
    kwargs:
        Additional configuration options:

        - `logger`: `structlog.stdlib.BoundLogger`, optional.
             A custom logger instance to use for logging
        - `ignore_TD_errors`: `bool`, default `False`.
            Whether to ignore errors while fetching the Thing Description (TD). Supported only for this runtime,
            not against a 3rd party Web of Things (WoT) implementation.
        - `skip_interaction_affordances`: `list[str]`, default `[]`.
            A list of interaction names to skip (any of property, action or event names)
        - `invokation_timeout`: `float`, optional, default `5.0`.
            The timeout for invokation requests (in seconds)
        - `execution_timeout`: `float`, optional, default `5.0`.
            The timeout for execution requests (in seconds)

    Returns
    -------
    ObjectProxy
        An `ObjectProxy` instance representing the remote `Thing` with ZMQ protocol.

    Raises
    ------
    ImportError
        if `pyzmq` is not installed - `pip install pyzmq`. Version should be less than 26.2 to support IPC in
        windows machines.
    ModuleNotFoundError
        if some other dependency of the ZMQ client is missing
    """
    from hololinked.client.zmq.consumed_interactions import (
        ReadMultipleProperties,
        WriteMultipleProperties,
        ZMQAction,
        ZMQEvent,
        ZMQProperty,
    )
    from hololinked.server.zmq import AsyncZMQClient, SyncZMQClient

    id = kwargs.get("id", f"{server_id}|{thing_id}|{access_point}|{uuid_hex()}")

    # configs
    ignore_TD_errors = kwargs.get("ignore_TD_errors", False)
    skip_interaction_affordances = kwargs.get("skip_interaction_affordances", [])
    invokation_timeout = kwargs.get("invokation_timeout", 5.0)
    execution_timeout = kwargs.get("execution_timeout", 5.0)
    logger = kwargs.get("logger", structlog.get_logger()).bind(
        component="client",
        client_id=id,
        protocol="zmq",
        thing_id=thing_id,
    )

    # ZMQ req-rep clients
    sync_zmq_client = SyncZMQClient(f"{id}|sync", server_id=server_id, logger=logger, access_point=access_point)
    async_zmq_client = AsyncZMQClient(f"{id}|async", server_id=server_id, logger=logger, access_point=access_point)

    # Fetch the TD
    Thing.get_thing_model  # noqa: B018  # type: Action
    FetchTDAffordance = Thing.get_thing_model.to_metadata()
    FetchTDAffordance.override_defaults(name="get_thing_description", thing_id=thing_id)
    FetchTD = ZMQAction(
        resource=FetchTDAffordance,
        sync_client=sync_zmq_client,
        async_client=async_zmq_client,
        invokation_timeout=invokation_timeout,
        execution_timeout=execution_timeout,
        owner_inst=None,
        logger=logger,
    )
    TD = FetchTD(
        ignore_errors=ignore_TD_errors,
        protocol=access_point.split("://")[0].upper() if access_point else "IPC",
        skip_names=skip_interaction_affordances,
    )  # dict[str, Any]

    # create ObjectProxy
    object_proxy = ObjectProxy(
        id=id,
        td=TD,
        logger=logger,
        invokation_timeout=invokation_timeout,
        execution_timeout=execution_timeout,
        security=kwargs.get("security", None),
    )

    # add properties
    for name in TD.get("properties", []):
        affordance = PropertyAffordance.from_TD(name, TD)
        consumed_property = ZMQProperty(
            resource=affordance,
            sync_client=sync_zmq_client,
            async_client=async_zmq_client,
            owner_inst=object_proxy,
            invokation_timeout=invokation_timeout,
            execution_timeout=execution_timeout,
            logger=logger,
        )
        ClientFactory.add_property(object_proxy, consumed_property)
        if hasattr(affordance, "observable") and affordance.observable:
            consumed_observable = ZMQEvent(
                resource=affordance,
                owner_inst=object_proxy,
                logger=logger,
            )
            ClientFactory.add_event(object_proxy, consumed_observable)
    # add actions
    for action in TD.get("actions", []):
        affordance = ActionAffordance.from_TD(action, TD)
        consumed_action = ZMQAction(
            resource=affordance,
            sync_client=sync_zmq_client,
            async_client=async_zmq_client,
            owner_inst=object_proxy,
            invokation_timeout=invokation_timeout,
            execution_timeout=execution_timeout,
            logger=logger,
        )
        ClientFactory.add_action(object_proxy, consumed_action)
    # add events
    for event in TD.get("events", []):
        affordance = EventAffordance.from_TD(event, TD)
        consumed_event = ZMQEvent(
            resource=affordance,
            owner_inst=object_proxy,
            logger=logger,
        )
        ClientFactory.add_event(object_proxy, consumed_event)
    # add top level form handlers (for ZMQ even if said form exists or not)
    for opname, ophandler in zip(
        ["_get_properties", "_set_properties"],
        [ReadMultipleProperties, WriteMultipleProperties],
    ):
        setattr(
            object_proxy,
            opname,
            ophandler(
                sync_client=sync_zmq_client,
                async_client=async_zmq_client,
                owner_inst=object_proxy,
                invokation_timeout=invokation_timeout,
                execution_timeout=execution_timeout,
                logger=logger,
            ),
        )
    return object_proxy

http staticmethod

http(url: str, **kwargs) -> ObjectProxy

Create a HTTP client using the Thing Description (TD) available at the specified URL.

Documentation

client = ClientFactory.http(
    url="https://example.com/thing-description",
    username="user",
    password="pass"
)
thing = Thing("thing1")
thing.run_with_http_server(port=8080, forked=True)

client = ClientFactory.http(
    url="http://localhost:8080/thing1/resources/wot-td",
    ignore_TD_errors=True
)

Parameters:

Name Type Description Default

url

str

The URL of the Thing Description (TD) to fetch.

required

kwargs

Additional configuration options:

  • logger: structlog.stdlib.BoundLogger, optional. A custom logger instance to use for logging
  • ignore_TD_errors: bool, default False. Whether to ignore errors while fetching the Thing Description (TD)
  • skip_interaction_affordances: list[str], default []. A list of interaction names to skip (any of property, action or event names)
  • invokation_timeout: float, optional, default 5.0. The timeout for operation invokation (in seconds), for example when invoking an action or reading/writing a property. This is a server-side timeout.
  • execution_timeout: float, optional, default 5.0. The timeout for operation execution (in seconds) - the time it waits for an operation to be completed after invokation before timing out. This is a server-side timeout.
  • connect_timeout: float, optional, default 10.0. The timeout for establishing a HTTP connection (in seconds). This is a client-side timeout.
  • request_timeout: float, optional, default 60.0. The timeout for completing a HTTP request (in seconds) after the connection is established. This is a client-side timeout.
  • security: BasicSecurity | APIKeySecurity | OAuthDirectAccessGrant, optional. The security scheme to use for authentication. Not all schemes are supported for all protocols. See here.
  • username: str, optional. The username for HTTP Basic Authentication, shortcut for creating a BasicSecurity instance
  • password: str, optional. The password for HTTP Basic Authentication, shortcut for creating a BasicSecurity instance
  • verify_ssl: bool | str, default True. Whether to verify the server's TLS certificate, or the path to a CA bundle to verify it against. Pass False to accept untrusted certificates, for example a self signed one used in development. Note that OAuthDirectAccessGrant contacts the identity provider itself, so pass verify_ssl there as well if that endpoint also serves an untrusted certificate.
  • ssl_context: ssl.SSLContext, optional. A preconfigured SSL context, which takes precedence over verify_ssl.
{}

Returns:

Type Description
ObjectProxy

An ObjectProxy instance representing the remote Thing with HTTP protocol.

Source code in repo/hololinked/hololinked/client/factory.py
@staticmethod
def http(url: str, **kwargs) -> ObjectProxy:
    """
    Create a HTTP client using the Thing Description (TD) available at the specified URL.

    [Documentation](https://docs.hololinked.dev/beginners-guide/articles/object-proxy/#__tabbed_1_1)

    ```python
    client = ClientFactory.http(
        url="https://example.com/thing-description",
        username="user",
        password="pass"
    )
    ```

    ```python
    thing = Thing("thing1")
    thing.run_with_http_server(port=8080, forked=True)

    client = ClientFactory.http(
        url="http://localhost:8080/thing1/resources/wot-td",
        ignore_TD_errors=True
    )
    ```

    Parameters
    ----------
    url: str
        The URL of the Thing Description (TD) to fetch.
    kwargs:
        Additional configuration options:

        - `logger`: `structlog.stdlib.BoundLogger`, optional.
            A custom logger instance to use for logging
        - `ignore_TD_errors`: `bool`, default `False`.
            Whether to ignore errors while fetching the Thing Description (TD)
        - `skip_interaction_affordances`: `list[str]`, default `[]`.
            A list of interaction names to skip (any of property, action or event names)
        - `invokation_timeout`: `float`, optional, default `5.0`.
            The timeout for operation invokation (in seconds), for example when invoking an action or
            reading/writing a property. This is a server-side timeout.
        - `execution_timeout`: `float`, optional, default `5.0`.
            The timeout for operation execution (in seconds) - the time it waits for an operation to be completed
            after invokation before timing out. This is a server-side timeout.
        - `connect_timeout`: `float`, optional, default `10.0`.
            The timeout for establishing a HTTP connection (in seconds). This is a client-side timeout.
        - `request_timeout`: `float`, optional, default `60.0`.
            The timeout for completing a HTTP request (in seconds) after the connection is established.
            This is a client-side timeout.
        - `security`: `BasicSecurity` | `APIKeySecurity` | `OAuthDirectAccessGrant`, optional.
            The security scheme to use for authentication. Not all schemes are supported for all protocols.
            See [here](https://docs.hololinked.dev/introduction/use-cases/).
        - `username`: `str`, optional.
            The username for HTTP Basic Authentication, shortcut for creating a `BasicSecurity` instance
        - `password`: `str`, optional.
            The password for HTTP Basic Authentication, shortcut for creating a `BasicSecurity` instance
        - `verify_ssl`: `bool` | `str`, default `True`.
            Whether to verify the server's TLS certificate, or the path to a CA bundle to verify it against.
            Pass `False` to accept untrusted certificates, for example a self signed one used in development.
            Note that `OAuthDirectAccessGrant` contacts the identity provider itself, so pass `verify_ssl`
            there as well if that endpoint also serves an untrusted certificate.
        - `ssl_context`: `ssl.SSLContext`, optional.
            A preconfigured SSL context, which takes precedence over `verify_ssl`.

    Returns
    -------
    ObjectProxy
        An `ObjectProxy` instance representing the remote Thing with HTTP protocol.
    """
    import httpx

    from hololinked.client.http.consumed_interactions import (
        HTTPAction,
        HTTPEvent,
        HTTPProperty,
    )

    # config
    skip_interaction_affordances = kwargs.get("skip_interaction_affordances", [])
    invokation_timeout = kwargs.get("invokation_timeout", 5.0)
    execution_timeout = kwargs.get("execution_timeout", 5.0)
    connect_timeout = kwargs.get("connect_timeout", 10.0)
    request_timeout = kwargs.get("request_timeout", 60.0)
    verify_ssl = kwargs.get("verify_ssl", True)
    ssl_context = kwargs.get("ssl_context", None)
    if ssl_context is None and isinstance(verify_ssl, str):
        ssl_context = ssl.create_default_context(cafile=verify_ssl)
    verify = ssl_context if ssl_context is not None else verify_ssl
    if verify is False:
        warnings.warn(
            "TLS certificate verification is disabled, the identity of the server is not checked.",
            category=UserWarning,
            stacklevel=2,
        )

    use_localhost = False
    if (
        "http://localhost" in url
        or "http://localhost" in url
        or "http://[::1]" in url
        or "http://[::1]" in url
        or "http://127.0.0.1" in url
    ):
        use_localhost = True

    # create clients
    req_rep_timeout = httpx.Timeout(
        connect=connect_timeout,
        read=request_timeout,
        write=request_timeout,
        pool=2,
    )
    sse_timeout = httpx.Timeout(
        connect=connect_timeout,
        # no heartbeats, indefinite read timeout for now
        read=None,
        write=request_timeout,
        pool=2,
    )

    req_rep_sync_client = httpx.Client(timeout=req_rep_timeout, verify=verify)
    req_rep_async_client = httpx.AsyncClient(timeout=req_rep_timeout, verify=verify)
    sse_sync_client = httpx.Client(timeout=sse_timeout, verify=verify)
    sse_async_client = httpx.AsyncClient(timeout=sse_timeout, verify=verify)

    # fetch TD
    url = (
        f"{url}?"
        + f"ignore_errors={str(kwargs.get('ignore_TD_errors', False)).lower()}"
        + (f"&skip_names={','.join(skip_interaction_affordances)}" if skip_interaction_affordances else "")
        + f"&use_localhost={str(use_localhost).lower()}"
    )

    # fetch TD
    headers = {"Content-Type": "application/json"}
    security = kwargs.pop("security", None)
    username = kwargs.pop("username", None)
    password = kwargs.pop("password", None)
    if not security and username and password:
        security = BasicSecurity(username=username, password=password)
    if security and not isinstance(security, OAuthDirectAccessGrant):
        headers[security.http_header_name] = security.http_header
    if security and isinstance(security, OAuthDirectAccessGrant):
        security = OAuth2Security(
            security,
            req_rep_sync_client=req_rep_sync_client,
            req_rep_async_client=req_rep_async_client,
        )
        security.login()
        headers[security.http_header_name] = security.http_header

    response = req_rep_sync_client.get(url, headers=headers)  # type: httpx.Response
    response.raise_for_status()

    TD = Serializers.json.loads(response.content)
    id = kwargs.get("id", f"client|{TD['id']}|HTTP|{uuid_hex()}")
    logger = kwargs.get("logger", structlog.get_logger()).bind(
        component="client",
        client_id=id,
        protocol="http",
        thing_id=TD["id"],
    )
    object_proxy = ObjectProxy(id, td=TD, logger=logger, security=security, **kwargs)

    for name in TD.get("properties", []):
        affordance = PropertyAffordance.from_TD(name, TD)
        consumed_property = HTTPProperty(
            resource=affordance,
            sync_client=req_rep_sync_client,
            async_client=req_rep_async_client,
            invokation_timeout=invokation_timeout,
            execution_timeout=execution_timeout,
            owner_inst=object_proxy,
            logger=logger,
        )
        ClientFactory.add_property(object_proxy, consumed_property)
        if affordance.observable:
            consumed_event = HTTPEvent(
                resource=affordance,
                sync_client=sse_sync_client,
                async_client=sse_async_client,
                invokation_timeout=invokation_timeout,
                execution_timeout=execution_timeout,
                owner_inst=object_proxy,
                logger=logger,
            )
            ClientFactory.add_event(object_proxy, consumed_event)
    for action in TD.get("actions", []):
        affordance = ActionAffordance.from_TD(action, TD)
        consumed_action = HTTPAction(
            resource=affordance,
            sync_client=req_rep_sync_client,
            async_client=req_rep_async_client,
            invokation_timeout=invokation_timeout,
            execution_timeout=execution_timeout,
            owner_inst=object_proxy,
            logger=logger,
        )
        ClientFactory.add_action(object_proxy, consumed_action)
    for event in TD.get("events", []):
        affordance = EventAffordance.from_TD(event, TD)
        consumed_event = HTTPEvent(
            resource=affordance,
            sync_client=sse_sync_client,
            async_client=sse_async_client,
            invokation_timeout=invokation_timeout,
            execution_timeout=execution_timeout,
            owner_inst=object_proxy,
            logger=logger,
        )
        ClientFactory.add_event(object_proxy, consumed_event)

    return object_proxy

mqtt staticmethod

mqtt(hostname: str, port: int, thing_id: str, protocol_version: MQTTProtocolVersion | None = None, qos: int = 1, username: str | None = None, password: str | None = None, ssl_context: SSLContext | None = None, **kwargs) -> ObjectProxy

Create an MQTT client against the specified broker for the specified thing ID.

Documentation

Parameters:

Name Type Description Default

hostname

str

The hostname of the MQTT broker.

required

port

int

The port of the MQTT broker.

required

thing_id

str

The ID of the thing to consume events from.

required

protocol_version

MQTTProtocolVersion | None

The MQTT protocol version, MQTTv5 when not given.

None

qos

int

The Quality of Service level for MQTT messages (0, 1, or 2).

1

username

str | None

The username for authenticating with MQTT broker.

None

password

str | None

The password for authenticating with MQTT broker.

None

ssl_context

SSLContext | None

Secure sockets layer for encrypted communication with the MQTT broker.

None

kwargs

Additional configuration options:

  • logger: structlog.stdlib.BoundLogger, optional. A custom logger instance to use for logging
{}

Returns:

Type Description
ObjectProxy

An ObjectProxy instance representing the remote Thing with MQTT protocol.

Raises:

Type Description
TimeoutError

If the Thing Description (TD) could not be fetched within the timeout period.

Source code in repo/hololinked/hololinked/client/factory.py
@staticmethod
def mqtt(
    hostname: str,
    port: int,
    thing_id: str,
    protocol_version: MQTTProtocolVersion | None = None,
    qos: int = 1,
    username: str | None = None,
    password: str | None = None,
    ssl_context: ssl.SSLContext | None = None,
    **kwargs,
) -> ObjectProxy:
    """
    Create an MQTT client against the specified broker for the specified thing ID.

    [Documentation](https://docs.hololinked.dev/beginners-guide/articles/object-proxy/#__tabbed_1_1)

    Parameters
    ----------
    hostname: str
        The hostname of the MQTT broker.
    port: int
        The port of the MQTT broker.
    thing_id: str
        The ID of the thing to consume events from.
    protocol_version: paho.mqtt.client.MQTTProtocolVersion, optional
        The MQTT protocol version, MQTTv5 when not given.
    qos: int
        The Quality of Service level for MQTT messages (0, 1, or 2).
    username: str, optional
        The username for authenticating with MQTT broker.
    password: str, optional
        The password for authenticating with MQTT broker.
    ssl_context: ssl.SSLContext, optional
        Secure sockets layer for encrypted communication with the MQTT broker.
    kwargs:
        Additional configuration options:

        - `logger`: `structlog.stdlib.BoundLogger`, optional.
             A custom logger instance to use for logging

    Returns
    -------
    ObjectProxy
        An `ObjectProxy` instance representing the remote `Thing` with MQTT protocol.

    Raises
    ------
    TimeoutError
        If the Thing Description (TD) could not be fetched within the timeout period.
    """
    import aiomqtt

    from paho.mqtt.client import CallbackAPIVersion, MQTTProtocolVersion
    from paho.mqtt.client import Client as PahoMQTTClient

    from hololinked.client.mqtt.consumed_interactions import MQTTConsumer

    if protocol_version is None:
        protocol_version = MQTTProtocolVersion.MQTTv5

    id = kwargs.get("id", f"mqtt-client|{hostname}:{port}|{uuid_hex()}")
    logger = kwargs.get("logger", structlog.get_logger()).bind(
        component="client",
        client_id=id,
        protocol="mqtt",
        thing_id=thing_id,
    )

    td_received_event = threading.Event()
    TD = None

    def fetch_td(client: PahoMQTTClient, userdata, message: MQTTMessage) -> None:
        nonlocal TD, thing_id, logger
        if message.topic != f"{thing_id}/thing-description":
            return
        TD = Serializers.json.loads(message.payload)
        td_received_event.set()

    def on_connect(
        client: PahoMQTTClient,
        userdata: Any,
        connect_flags: Any,
        reason_code: list,
        properties: dict[str, Any],
    ) -> None:  # TODO fix signature
        nonlocal qos
        client.subscribe(f"{thing_id}/#", qos=qos)

    sync_client = PahoMQTTClient(
        callback_api_version=CallbackAPIVersion.VERSION2,
        client_id=id,
        clean_session=True if protocol_version != MQTTProtocolVersion.MQTTv5 else None,
        protocol=protocol_version,
    )
    if username and password:
        sync_client.username_pw_set(username=username, password=password)
    if ssl_context is not None:
        sync_client.tls_set_context(ssl_context)
    elif kwargs.get("ca_certs", None):
        sync_client.tls_set(ca_certs=kwargs.get("ca_certs", None))
    setattr(sync_client, "on_connect", on_connect)
    setattr(sync_client, "on_message", fetch_td)
    sync_client.connect(hostname, port)
    sync_client.loop_start()

    td_received_event.wait(timeout=10)
    if not TD:
        raise TimeoutError("Timeout while fetching Thing Description (TD) over MQTT")

    if not sync_client._ssl_context and port != 1883:
        warnings.warn(
            "MQTT used without TLS, if you intended to use TLS with a recognised CA & you saw this warning, considering "
            + "opening an issue at https://github.com/hololinked-dev/hololinked. ",
            category=RuntimeWarning,
        )

    async_client = aiomqtt.Client(
        hostname=hostname,
        port=port,
        username=username,
        password=password,
        protocol=protocol_version,
        tls_context=sync_client._ssl_context,
    )

    object_proxy = ObjectProxy(id=id, logger=logger, td=TD)

    for name in TD.get("properties", []):
        affordance = cast(PropertyAffordance, PropertyAffordance.from_TD(name, TD))
        consumed_property = MQTTConsumer(
            sync_client=sync_client,
            async_client=async_client,
            resource=affordance,
            qos=qos,
            logger=logger,
            owner_inst=object_proxy,
        )
        ClientFactory.add_event(object_proxy, consumed_property)
    for name in TD.get("events", []):
        affordance = cast(EventAffordance, EventAffordance.from_TD(name, TD))
        consumed_event = MQTTConsumer(
            sync_client=sync_client,
            async_client=async_client,
            resource=affordance,
            qos=qos,
            logger=logger,
            owner_inst=object_proxy,
        )
        ClientFactory.add_event(object_proxy, consumed_event)

    return object_proxy