Tutorial multiple loops async

 1'''
 2Tutorial - multiple_loops_async.py with asynchronous mode.
 3
 4This example project demonstrates how to use two async thread to get RTC & print string from USBDAQF1DSNK.
 5
 6-------------------------------------------------------------------------------------
 7Please change correct serial number or IP and port number BEFORE you run example code.
 8
 9For other examples please check:
10    https://github.com/WPC-Systems-Ltd/WPC_Python_driver_release/tree/main/examples
11See README.md file to get detailed usage of this example.
12
13Copyright (c) 2022-2024 WPC Systems Ltd. All rights reserved.
14'''
15
16## Python
17import asyncio
18
19## WPC
20
21from wpcsys import pywpc
22
23async def readRTC_loop(handle, delay=1):
24    while True:
25        rtc = await handle.Sys_getRTC_async()
26        print(f"RTC Time: {rtc}")
27        await asyncio.sleep(delay) ## delay [s]
28
29async def printString_loop(handle, delay=1):
30    while True:
31        print("WPC Systems Ltd")
32        await asyncio.sleep(delay) ## delay [s]
33
34async def main():
35    ## Get Python driver version
36    print(f'{pywpc.PKG_FULL_NAME} - Version {pywpc.__version__}')
37
38    ## Create device handle
39    dev = pywpc.USBDAQF1DSNK()
40
41    ## Connect to device
42    try:
43        dev.connect("default") ## Depend on your device
44    except Exception as err:
45        pywpc.printGenericError(err)
46        ## Release device handle
47        dev.close()
48        return
49
50    try:
51        ## Get firmware model & version
52        driver_info = await dev.Sys_getDriverInfo_async()
53        print("Model name: " + driver_info[0])
54        print("Firmware version: " + driver_info[-1])
55
56        await asyncio.gather(readRTC_loop(dev, delay=1), printString_loop(dev, delay=2)) ## delay (second)
57    except Exception as err:
58        pywpc.printGenericError(err)
59
60    ## This part never execute because the async thread.
61
62    ## Disconnect device
63    dev.disconnect()
64
65    ## Release device handle
66    dev.close()
67
68    return
69
70def main_for_spyder(*args):
71    if asyncio.get_event_loop().is_running():
72        return asyncio.create_task(main(*args)).result()
73    else:
74        return asyncio.run(main(*args))
75
76if __name__ == '__main__':
77    asyncio.run(main()) ## Use terminal
78    # await main() ## Use Jupyter or IPython(>=7.0)
79    # main_for_spyder() ## Use Spyder