Skip to content

DriftClient

Drift Python Client Class

Source code in drift_client/drift_client.py
 36
 37
 38
 39
 40
 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
class DriftClient:
    """Drift Python Client Class"""

    # pylint: disable=too-many-arguments

    def __init__(self, host: str, password: str, **kwargs):
        """
        Drift Client for easy access to Compute Devices on the Drift Platform

        Args:
            host: hostname or IP of Compute Device
            password: password to access data
        Keyword Args:
            user (str): A user of the platform. Default: "panda"
            org (str): An organisation name. Default: "panda"
            secure (bool): Use HTTPS protocol to access data: Default: False
            minio_port (int): Minio port. Default: 9000
            reduct_port (int): Reduct port. Default: 8383
            influx_port (int): InfluxDB port. Default: 8086,
            mqtt_port (int): MQTT port. Default: 1883
            loop: asyncio loop for integration into async code
            timeout (float): Timeout for requests. Default: 30 seconds
        """
        if password is None or password == "":
            raise ValueError("Password is required")

        user = kwargs["user"] if "user" in kwargs else "panda"
        org = kwargs["org"] if "org" in kwargs else "panda"
        secure = kwargs["secure"] if "secure" in kwargs else False
        influx_port = kwargs["influx_port"] if "influx_port" in kwargs else 8086
        minio_port = kwargs["minio_port"] if "minio_port" in kwargs else 9000
        reduct_storage_port = (
            kwargs["reduct_storage_port"] if "reduct_storage_port" in kwargs else 8383
        )
        mqtt_port = kwargs["mqtt_port"] if "mqtt_port" in kwargs else 1883
        loop = kwargs["loop"] if "loop" in kwargs else None
        timeout = kwargs["timeout"] if "timeout" in kwargs else 30

        self._mqtt_client = MQTTClient(
            f"mqtt://{host}:{mqtt_port}",
            client_id=f"drift_client_{int(time.time() * 1000)}",
        )

        self._influx_client = InfluxDBClient(
            f"{('https://' if secure else 'http://')}{host}:{influx_port}",
            org,
            password,
            False,
            timeout,
        )  # TBD!!! --> SSL handling!

        try:
            self._blob_storage = ReductStoreClient(
                f"{('https://' if secure else 'http://')}{host}:{reduct_storage_port}",
                password,
                timeout,
                loop,
            )
            return
        except ReductError as err:  # pylint: disable=broad-except
            if err.status_code == 599:
                logger.warning(
                    "ReductStore not available. Using MinIO Storage instead."
                )
            else:
                raise err

        # Minio as fallback if ReductStore is not available
        self._blob_storage = MinIOClient(
            f"{('https://' if secure else 'http://')}{host}:{minio_port}",
            user,
            password,
            False,
        )  # TBD!!! --> SSL handling!

    def get_topics(self) -> List[str]:
        """Returns list of topics (measurements in InfluxDB)

        Returns:
            List of topics available

        Examples:
            >>> client = DriftClient("127.0.0.1", "PASSWORD")
            >>> client.get_topics() # => ['topic-1', 'topic-2', ...]
        """

        topics = self._influx_client.query_measurements()
        return topics

    @deprecation.deprecated(
        deprecated_in="0.2.0",
        removed_in="1.0.0",
        details="use drift_client.get_topic_data method instead",
    )
    def get_list(self, topics: List[str], timeframe: List[str]) -> Dict[str, List[str]]:
        """Returns list of history data from initialised Device

        Args:
            topics: List of topic names, e.g. `["sensor-1", "sensor-2"]`
            timeframe: List with begin and end of request timeframe,
                Format: `2022-02-07 10:00:00`

        Returns:
            List of item names available
        :rtype: List[str]

        Examples:
            >>> client = DriftClient("127.0.0.1", "PASSWORD")
            >>> client.get_list(["topic-1", "topic-2", "topic-3"],
            >>>         ["2022-02-03 10:00:00", "2022-02-03 10:00:10"])
            >>> # => {"topic-1": ['topic-1/1644750600291.dp',
            >>> #                  'topic-1/1644750601291.dp', ...] ... }
        """
        data = {}
        for topic in topics:
            influxdb_values = self._influx_client.query_data(
                topic, timeframe[0], timeframe[1], fields="status"
            )

            if not influxdb_values:
                break

            data[topic] = []
            for timestamp, _ in influxdb_values["status"]:
                data[topic].append(f"{topic}/{int(timestamp * 1000)}.dp")

        return data

    def get_package_names(
        self,
        topic: str,
        start: Union[float, datetime, str],
        stop: Union[float, datetime, str],
    ) -> List[str]:
        """Returns list of history data from initialised Device

        Args:
            topic: Topic name
            start: Begin of request timeframe,
                Format: ISO string, datetime or float timestamp
            stop: End of request timeframe,
                Format: ISO string, datetime or float timestamp

        Returns:
            List with item names available

        Examples:
            >>> client = DriftClient("127.0.0.1", "PASSWORD")
            >>> client.get_package_names("topic-1",
            >>>         "2022-02-03 10:00:00", "2022-02-03 10:00:10")
            >>> # => ['topic-1/1644750600291.dp',
            >>> #                  'topic-1/1644750601291.dp', ...]
        """
        start = _convert_type(start)
        stop = _convert_type(stop)

        package_list = []
        influxdb_values = self._influx_client.query_data(
            topic, start, stop, fields="status"
        )

        if influxdb_values:
            for timestamp, _ in influxdb_values["status"]:
                package_list.append(f"{topic}/{int(timestamp * 1000)}.dp")

        # Check if package_list is available (works only for Reduct Storage)
        return self._blob_storage.check_package_list(package_list)

    def get_item(self, path: str) -> DriftDataPackage:
        """Returns requested single historic data from initialised Device
        Args:
            path: path of item in storage
        Raises:
            ValueError: In case of broken WaveletBuffer
        Returns:
            Parsed Drift Package

        Examples:
            >>> client = DriftClient("127.0.0.1", "PASSWORD")
            >>> client.get_item("topic-1/1644750605291.dp")
        """
        blob = self._blob_storage.fetch_data(path)
        return DriftDataPackage(blob)

    def walk(
        self,
        topic: str,
        start: Union[float, datetime, str],
        stop: Union[float, datetime, str],
        **kwargs,
    ) -> Iterator[DriftDataPackage]:
        """Walks through history data for selected topic

        Args:
            topic: Topic name
            start: Begin of request timeframe,
                Format: ISO string, datetime or float timestamp
            stop: End of request timeframe,
                Format: ISO string, datetime or float timestamp
        KwArgs:
            ttl: Time to live for the query only for ReductStore
        Returns:
            Iterator with DriftDataPackage
        Raises:
            DriftClientError: if failed to fetch data

        Examples:
            >>> client = DriftClient("127.0.0.1", "PASSWORD")
            >>> for pkg in  client.walk("topic-1", "2022-02-03 10:00:00",
                "2022-02-03 10:00:10")
            >>>     print(pkg)
        """

        if self._blob_storage.name() == "minio":
            packages = self.get_package_names(topic, start, stop)
            for package in packages:
                yield self.get_item(package)
        else:
            start = _convert_type(start)
            stop = _convert_type(stop)
            for package in self._blob_storage.walk(topic, start, stop, **kwargs):
                yield DriftDataPackage(package)

    def subscribe_data(self, topic: str, handler: Callable[[DriftDataPackage], None]):
        """Subscribes to selected topic from initialised Device

        Args:
            topic: MQTT topic
            handler: Handler - own handler function to be used, e.g.
                `def package_handler(package):`

        Examples:
            >>> def package_handler(package: DriftDataPackage) -> None:
            >>>    print(package.meta)
            >>>
            >>> client = DriftClient("127.0.0.1", "PASSWORD")
            >>> client.subscribe_data("topic-1", package_handler)
        """

        def package_handler(message):
            try:
                output = DriftDataPackage(message.payload)
            except DecodeError as exc:
                raise DecodeError("Payload is no Drift Package") from exc
            handler(output)

        self._mqtt_client.connect()
        self._mqtt_client.subscribe(topic, package_handler)

        self._mqtt_client.loop_forever()

    def publish_data(self, topic: str, payload: bytes):
        """Publishes payload to selected topic on initialised Device
        Args:
            topic: MQTT topic
            payload: Stringified data, defaults to None

        Examples
            >>> client = DriftClient("127.0.0.1", "PASSWORD")
            >>> client.publish_data("topic-2", b"hello")
        """
        if not self._mqtt_client.is_connected():
            self._mqtt_client.connect()
            self._mqtt_client.loop_start()

        self._mqtt_client.publish(topic, payload)

    def get_metrics(
        self,
        topic: str,
        start: Union[float, datetime, str],
        stop: Union[float, datetime, str],
        names: Optional[List[str]] = None,
    ) -> List[Dict[str, Any]]:
        """Reads history metrics from timeseries database

        Args:
            topic: MQTT topic
            start: Begin of request timeframe,
                Format: ISO string, datetime or float timestamp
            stop: End of request timeframe,
                Format: ISO string, datetime or float timestamp
            names: Name of metrics, if None get all metrics for the topic

        Examples

            >>> client = DriftClient("127.0.0.1", "PASSWORD")
            >>> client.get_metrics("topic", "2022-02-03 10:00:00",
            >>>    "2022-02-03 10:00:10", names=["status", "field"])
            >>> #=> [{"status": 0, "field": 0.1231}, ....]
        """

        start = _convert_type(start)
        stop = _convert_type(stop)

        aligned_data = {}
        influxdb_values = self._influx_client.query_data(
            topic, start, stop, fields=names
        )

        for field, values in influxdb_values.items():
            for dt, value in values:
                if dt not in aligned_data:
                    aligned_data[dt] = {}

                aligned_data[dt][field] = value

        data = []
        for dt, fields in aligned_data.items():
            fields["time"] = dt
            data.append(fields)

        return data

__init__(host, password, **kwargs)

Drift Client for easy access to Compute Devices on the Drift Platform

Parameters:

Name Type Description Default
host str

hostname or IP of Compute Device

required
password str

password to access data

required

Keyword Args: user (str): A user of the platform. Default: "panda" org (str): An organisation name. Default: "panda" secure (bool): Use HTTPS protocol to access data: Default: False minio_port (int): Minio port. Default: 9000 reduct_port (int): Reduct port. Default: 8383 influx_port (int): InfluxDB port. Default: 8086, mqtt_port (int): MQTT port. Default: 1883 loop: asyncio loop for integration into async code timeout (float): Timeout for requests. Default: 30 seconds

Source code in drift_client/drift_client.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
def __init__(self, host: str, password: str, **kwargs):
    """
    Drift Client for easy access to Compute Devices on the Drift Platform

    Args:
        host: hostname or IP of Compute Device
        password: password to access data
    Keyword Args:
        user (str): A user of the platform. Default: "panda"
        org (str): An organisation name. Default: "panda"
        secure (bool): Use HTTPS protocol to access data: Default: False
        minio_port (int): Minio port. Default: 9000
        reduct_port (int): Reduct port. Default: 8383
        influx_port (int): InfluxDB port. Default: 8086,
        mqtt_port (int): MQTT port. Default: 1883
        loop: asyncio loop for integration into async code
        timeout (float): Timeout for requests. Default: 30 seconds
    """
    if password is None or password == "":
        raise ValueError("Password is required")

    user = kwargs["user"] if "user" in kwargs else "panda"
    org = kwargs["org"] if "org" in kwargs else "panda"
    secure = kwargs["secure"] if "secure" in kwargs else False
    influx_port = kwargs["influx_port"] if "influx_port" in kwargs else 8086
    minio_port = kwargs["minio_port"] if "minio_port" in kwargs else 9000
    reduct_storage_port = (
        kwargs["reduct_storage_port"] if "reduct_storage_port" in kwargs else 8383
    )
    mqtt_port = kwargs["mqtt_port"] if "mqtt_port" in kwargs else 1883
    loop = kwargs["loop"] if "loop" in kwargs else None
    timeout = kwargs["timeout"] if "timeout" in kwargs else 30

    self._mqtt_client = MQTTClient(
        f"mqtt://{host}:{mqtt_port}",
        client_id=f"drift_client_{int(time.time() * 1000)}",
    )

    self._influx_client = InfluxDBClient(
        f"{('https://' if secure else 'http://')}{host}:{influx_port}",
        org,
        password,
        False,
        timeout,
    )  # TBD!!! --> SSL handling!

    try:
        self._blob_storage = ReductStoreClient(
            f"{('https://' if secure else 'http://')}{host}:{reduct_storage_port}",
            password,
            timeout,
            loop,
        )
        return
    except ReductError as err:  # pylint: disable=broad-except
        if err.status_code == 599:
            logger.warning(
                "ReductStore not available. Using MinIO Storage instead."
            )
        else:
            raise err

    # Minio as fallback if ReductStore is not available
    self._blob_storage = MinIOClient(
        f"{('https://' if secure else 'http://')}{host}:{minio_port}",
        user,
        password,
        False,
    )  # TBD!!! --> SSL handling!

get_item(path)

Returns requested single historic data from initialised Device Args: path: path of item in storage Raises: ValueError: In case of broken WaveletBuffer Returns: Parsed Drift Package

Examples:

>>> client = DriftClient("127.0.0.1", "PASSWORD")
>>> client.get_item("topic-1/1644750605291.dp")
Source code in drift_client/drift_client.py
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
def get_item(self, path: str) -> DriftDataPackage:
    """Returns requested single historic data from initialised Device
    Args:
        path: path of item in storage
    Raises:
        ValueError: In case of broken WaveletBuffer
    Returns:
        Parsed Drift Package

    Examples:
        >>> client = DriftClient("127.0.0.1", "PASSWORD")
        >>> client.get_item("topic-1/1644750605291.dp")
    """
    blob = self._blob_storage.fetch_data(path)
    return DriftDataPackage(blob)

get_list(topics, timeframe)

Returns list of history data from initialised Device

Parameters:

Name Type Description Default
topics List[str]

List of topic names, e.g. ["sensor-1", "sensor-2"]

required
timeframe List[str]

List with begin and end of request timeframe, Format: 2022-02-07 10:00:00

required

Returns:

Type Description
Dict[str, List[str]]

List of item names available

:rtype: List[str]

Examples:

>>> client = DriftClient("127.0.0.1", "PASSWORD")
>>> client.get_list(["topic-1", "topic-2", "topic-3"],
>>>         ["2022-02-03 10:00:00", "2022-02-03 10:00:10"])
>>> # => {"topic-1": ['topic-1/1644750600291.dp',
>>> #                  'topic-1/1644750601291.dp', ...] ... }
Source code in drift_client/drift_client.py
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
@deprecation.deprecated(
    deprecated_in="0.2.0",
    removed_in="1.0.0",
    details="use drift_client.get_topic_data method instead",
)
def get_list(self, topics: List[str], timeframe: List[str]) -> Dict[str, List[str]]:
    """Returns list of history data from initialised Device

    Args:
        topics: List of topic names, e.g. `["sensor-1", "sensor-2"]`
        timeframe: List with begin and end of request timeframe,
            Format: `2022-02-07 10:00:00`

    Returns:
        List of item names available
    :rtype: List[str]

    Examples:
        >>> client = DriftClient("127.0.0.1", "PASSWORD")
        >>> client.get_list(["topic-1", "topic-2", "topic-3"],
        >>>         ["2022-02-03 10:00:00", "2022-02-03 10:00:10"])
        >>> # => {"topic-1": ['topic-1/1644750600291.dp',
        >>> #                  'topic-1/1644750601291.dp', ...] ... }
    """
    data = {}
    for topic in topics:
        influxdb_values = self._influx_client.query_data(
            topic, timeframe[0], timeframe[1], fields="status"
        )

        if not influxdb_values:
            break

        data[topic] = []
        for timestamp, _ in influxdb_values["status"]:
            data[topic].append(f"{topic}/{int(timestamp * 1000)}.dp")

    return data

get_metrics(topic, start, stop, names=None)

Reads history metrics from timeseries database

Parameters:

Name Type Description Default
topic str

MQTT topic

required
start Union[float, datetime, str]

Begin of request timeframe, Format: ISO string, datetime or float timestamp

required
stop Union[float, datetime, str]

End of request timeframe, Format: ISO string, datetime or float timestamp

required
names Optional[List[str]]

Name of metrics, if None get all metrics for the topic

None

Examples

>>> client = DriftClient("127.0.0.1", "PASSWORD")
>>> client.get_metrics("topic", "2022-02-03 10:00:00",
>>>    "2022-02-03 10:00:10", names=["status", "field"])
>>> #=> [{"status": 0, "field": 0.1231}, ....]
Source code in drift_client/drift_client.py
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
def get_metrics(
    self,
    topic: str,
    start: Union[float, datetime, str],
    stop: Union[float, datetime, str],
    names: Optional[List[str]] = None,
) -> List[Dict[str, Any]]:
    """Reads history metrics from timeseries database

    Args:
        topic: MQTT topic
        start: Begin of request timeframe,
            Format: ISO string, datetime or float timestamp
        stop: End of request timeframe,
            Format: ISO string, datetime or float timestamp
        names: Name of metrics, if None get all metrics for the topic

    Examples

        >>> client = DriftClient("127.0.0.1", "PASSWORD")
        >>> client.get_metrics("topic", "2022-02-03 10:00:00",
        >>>    "2022-02-03 10:00:10", names=["status", "field"])
        >>> #=> [{"status": 0, "field": 0.1231}, ....]
    """

    start = _convert_type(start)
    stop = _convert_type(stop)

    aligned_data = {}
    influxdb_values = self._influx_client.query_data(
        topic, start, stop, fields=names
    )

    for field, values in influxdb_values.items():
        for dt, value in values:
            if dt not in aligned_data:
                aligned_data[dt] = {}

            aligned_data[dt][field] = value

    data = []
    for dt, fields in aligned_data.items():
        fields["time"] = dt
        data.append(fields)

    return data

get_package_names(topic, start, stop)

Returns list of history data from initialised Device

Parameters:

Name Type Description Default
topic str

Topic name

required
start Union[float, datetime, str]

Begin of request timeframe, Format: ISO string, datetime or float timestamp

required
stop Union[float, datetime, str]

End of request timeframe, Format: ISO string, datetime or float timestamp

required

Returns:

Type Description
List[str]

List with item names available

Examples:

>>> client = DriftClient("127.0.0.1", "PASSWORD")
>>> client.get_package_names("topic-1",
>>>         "2022-02-03 10:00:00", "2022-02-03 10:00:10")
>>> # => ['topic-1/1644750600291.dp',
>>> #                  'topic-1/1644750601291.dp', ...]
Source code in drift_client/drift_client.py
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
def get_package_names(
    self,
    topic: str,
    start: Union[float, datetime, str],
    stop: Union[float, datetime, str],
) -> List[str]:
    """Returns list of history data from initialised Device

    Args:
        topic: Topic name
        start: Begin of request timeframe,
            Format: ISO string, datetime or float timestamp
        stop: End of request timeframe,
            Format: ISO string, datetime or float timestamp

    Returns:
        List with item names available

    Examples:
        >>> client = DriftClient("127.0.0.1", "PASSWORD")
        >>> client.get_package_names("topic-1",
        >>>         "2022-02-03 10:00:00", "2022-02-03 10:00:10")
        >>> # => ['topic-1/1644750600291.dp',
        >>> #                  'topic-1/1644750601291.dp', ...]
    """
    start = _convert_type(start)
    stop = _convert_type(stop)

    package_list = []
    influxdb_values = self._influx_client.query_data(
        topic, start, stop, fields="status"
    )

    if influxdb_values:
        for timestamp, _ in influxdb_values["status"]:
            package_list.append(f"{topic}/{int(timestamp * 1000)}.dp")

    # Check if package_list is available (works only for Reduct Storage)
    return self._blob_storage.check_package_list(package_list)

get_topics()

Returns list of topics (measurements in InfluxDB)

Returns:

Type Description
List[str]

List of topics available

Examples:

>>> client = DriftClient("127.0.0.1", "PASSWORD")
>>> client.get_topics() # => ['topic-1', 'topic-2', ...]
Source code in drift_client/drift_client.py
111
112
113
114
115
116
117
118
119
120
121
122
123
def get_topics(self) -> List[str]:
    """Returns list of topics (measurements in InfluxDB)

    Returns:
        List of topics available

    Examples:
        >>> client = DriftClient("127.0.0.1", "PASSWORD")
        >>> client.get_topics() # => ['topic-1', 'topic-2', ...]
    """

    topics = self._influx_client.query_measurements()
    return topics

publish_data(topic, payload)

Publishes payload to selected topic on initialised Device Args: topic: MQTT topic payload: Stringified data, defaults to None

Examples >>> client = DriftClient("127.0.0.1", "PASSWORD") >>> client.publish_data("topic-2", b"hello")

Source code in drift_client/drift_client.py
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
def publish_data(self, topic: str, payload: bytes):
    """Publishes payload to selected topic on initialised Device
    Args:
        topic: MQTT topic
        payload: Stringified data, defaults to None

    Examples
        >>> client = DriftClient("127.0.0.1", "PASSWORD")
        >>> client.publish_data("topic-2", b"hello")
    """
    if not self._mqtt_client.is_connected():
        self._mqtt_client.connect()
        self._mqtt_client.loop_start()

    self._mqtt_client.publish(topic, payload)

subscribe_data(topic, handler)

Subscribes to selected topic from initialised Device

Parameters:

Name Type Description Default
topic str

MQTT topic

required
handler Callable[[DriftDataPackage], None]

Handler - own handler function to be used, e.g. def package_handler(package):

required

Examples:

>>> def package_handler(package: DriftDataPackage) -> None:
>>>    print(package.meta)
>>>
>>> client = DriftClient("127.0.0.1", "PASSWORD")
>>> client.subscribe_data("topic-1", package_handler)
Source code in drift_client/drift_client.py
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
def subscribe_data(self, topic: str, handler: Callable[[DriftDataPackage], None]):
    """Subscribes to selected topic from initialised Device

    Args:
        topic: MQTT topic
        handler: Handler - own handler function to be used, e.g.
            `def package_handler(package):`

    Examples:
        >>> def package_handler(package: DriftDataPackage) -> None:
        >>>    print(package.meta)
        >>>
        >>> client = DriftClient("127.0.0.1", "PASSWORD")
        >>> client.subscribe_data("topic-1", package_handler)
    """

    def package_handler(message):
        try:
            output = DriftDataPackage(message.payload)
        except DecodeError as exc:
            raise DecodeError("Payload is no Drift Package") from exc
        handler(output)

    self._mqtt_client.connect()
    self._mqtt_client.subscribe(topic, package_handler)

    self._mqtt_client.loop_forever()

walk(topic, start, stop, **kwargs)

Walks through history data for selected topic

Parameters:

Name Type Description Default
topic str

Topic name

required
start Union[float, datetime, str]

Begin of request timeframe, Format: ISO string, datetime or float timestamp

required
stop Union[float, datetime, str]

End of request timeframe, Format: ISO string, datetime or float timestamp

required

KwArgs: ttl: Time to live for the query only for ReductStore Returns: Iterator with DriftDataPackage Raises: DriftClientError: if failed to fetch data

Examples:

>>> client = DriftClient("127.0.0.1", "PASSWORD")
>>> for pkg in  client.walk("topic-1", "2022-02-03 10:00:00",
    "2022-02-03 10:00:10")
>>>     print(pkg)
Source code in drift_client/drift_client.py
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
def walk(
    self,
    topic: str,
    start: Union[float, datetime, str],
    stop: Union[float, datetime, str],
    **kwargs,
) -> Iterator[DriftDataPackage]:
    """Walks through history data for selected topic

    Args:
        topic: Topic name
        start: Begin of request timeframe,
            Format: ISO string, datetime or float timestamp
        stop: End of request timeframe,
            Format: ISO string, datetime or float timestamp
    KwArgs:
        ttl: Time to live for the query only for ReductStore
    Returns:
        Iterator with DriftDataPackage
    Raises:
        DriftClientError: if failed to fetch data

    Examples:
        >>> client = DriftClient("127.0.0.1", "PASSWORD")
        >>> for pkg in  client.walk("topic-1", "2022-02-03 10:00:00",
            "2022-02-03 10:00:10")
        >>>     print(pkg)
    """

    if self._blob_storage.name() == "minio":
        packages = self.get_package_names(topic, start, stop)
        for package in packages:
            yield self.get_item(package)
    else:
        start = _convert_type(start)
        stop = _convert_type(stop)
        for package in self._blob_storage.walk(topic, start, stop, **kwargs):
            yield DriftDataPackage(package)