|
| 1 | +import asyncio |
| 2 | +import random |
| 3 | +import time |
| 4 | + |
| 5 | +import pandas |
| 6 | + |
| 7 | +from influxdb_client_3 import InfluxDBClient3 |
| 8 | + |
| 9 | +from config import Config |
| 10 | + |
| 11 | + |
| 12 | +async def fibio(iterations, grit=0.5): |
| 13 | + """ |
| 14 | + example coroutine to run parallel with query_async |
| 15 | + :param iterations: |
| 16 | + :param grit: |
| 17 | + :return: |
| 18 | + """ |
| 19 | + n0 = 1 |
| 20 | + n1 = 1 |
| 21 | + vals = [n0, n1] |
| 22 | + for _ in range(iterations): |
| 23 | + val = n0 + n1 |
| 24 | + n0 = n1 |
| 25 | + n1 = val |
| 26 | + print(val) |
| 27 | + vals.append(val) |
| 28 | + await asyncio.sleep(grit) |
| 29 | + return vals |
| 30 | + |
| 31 | + |
| 32 | +def write_data(client: InfluxDBClient3, measurement): |
| 33 | + """ |
| 34 | + Synchronous write - only for preparing data |
| 35 | + :param client: |
| 36 | + :param measurement: |
| 37 | + :return: |
| 38 | + """ |
| 39 | + ids = ['s3b1', 'dq41', 'sgw22'] |
| 40 | + lp_template = f"{measurement},id=%s speed=%f,alt=%f,bearing=%f %d" |
| 41 | + data_size = 10 |
| 42 | + data = [] |
| 43 | + interval = 10 * 1_000_000_000 |
| 44 | + ts = time.time_ns() - (interval * data_size) |
| 45 | + for _ in range(data_size): |
| 46 | + data.append(lp_template % (ids[random.randint(0, len(ids) - 1)], |
| 47 | + random.random() * 300, |
| 48 | + random.random() * 2000, |
| 49 | + random.random() * 360, ts)) |
| 50 | + ts += interval |
| 51 | + |
| 52 | + client.write(data) |
| 53 | + |
| 54 | + |
| 55 | +async def query_data(client: InfluxDBClient3, measurement): |
| 56 | + """ |
| 57 | + Query asynchronously - should not block other coroutines |
| 58 | + :param client: |
| 59 | + :param measurement: |
| 60 | + :return: |
| 61 | + """ |
| 62 | + query = f"SELECT * FROM \"{measurement}\" WHERE time >= now() - interval '5 minutes' ORDER BY time DESC" |
| 63 | + print(f"query start: {pandas.Timestamp(time.time_ns())}") |
| 64 | + table = await client.query_async(query) |
| 65 | + print(f"query returned: {pandas.Timestamp(time.time_ns())}") |
| 66 | + return table.to_pandas() |
| 67 | + |
| 68 | + |
| 69 | +async def main(): |
| 70 | + config = Config() |
| 71 | + client = InfluxDBClient3( |
| 72 | + host=config.host, |
| 73 | + token=config.token, |
| 74 | + database=config.database, |
| 75 | + org=config.org |
| 76 | + ) |
| 77 | + measurement = 'example_uav' |
| 78 | + write_data(client, measurement) |
| 79 | + |
| 80 | + # run both coroutines simultaneously |
| 81 | + result = await asyncio.gather(fibio(10, 0.2),query_data(client, measurement)) |
| 82 | + print(f"fibio sequence = {result[0]}") |
| 83 | + print(f"data set =\n{result[1]}") |
| 84 | + |
| 85 | + |
| 86 | +if __name__ == "__main__": |
| 87 | + asyncio.run(main()) |
0 commit comments