Tutorial single loop thread

 1'''
 2Tutorial - single_loop_thread.py with asynchronous mode.
 3
 4This example project demonstrates how to use thread to get RTC from EDriveST.
 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-2025 WPC Systems Ltd. All rights reserved.
14'''
15
16## WPC
17from wpcsys import pywpc
18
19## Python
20import asyncio
21import threading
22import time
23import sys
24sys.path.insert(0, 'src/')
25
26
27async def getRTC(handle, delay=1):
28    data = await handle.Sys_getRTC_async()
29    print("RTC Time:" + str(data))
30    await asyncio.sleep(delay)  ## delay [sec]
31
32
33def RTC_thread(handle, delay=1):
34    while True:
35        asyncio.run(getRTC(handle, delay))
36        time.sleep(delay)  ## delay [sec]
37
38
39async def main():
40    ## Get Python driver version
41    print(f'{pywpc.PKG_FULL_NAME} - Version {pywpc.__version__}')
42
43    ## Create device handle
44    dev = pywpc.EDriveST()
45
46    ## Connect to device
47    try:
48        dev.connect("192.168.1.110")  ## Depend on your device
49    except Exception as err:
50        pywpc.printGenericError(err)
51        ## Release device handle
52        dev.close()
53        return
54
55    ## Perform two sync thread to query data
56    try:
57        ## Get firmware model & version
58        driver_info = await dev.Sys_getDriverInfo_async()
59        print(f"Model name: {driver_info[0]}, Firmware version: {driver_info[-1]} ")
60
61        _threadRTC = threading.Thread(target=RTC_thread, args=[dev, 1])
62        _threadRTC.start()
63    except Exception as err:
64        pywpc.printGenericError(err)
65
66    ## This part will execute immediately because the sync thread is running in parallel.
67    '''
68    # Disconnect device
69    dev.disconnect()
70
71    # Release device handle
72    dev.close()
73    '''
74
75
76def main_for_spyder(*args):
77    if asyncio.get_event_loop().is_running():
78        return asyncio.create_task(main(*args)).result()
79    else:
80        return asyncio.run(main(*args))
81
82
83if __name__ == '__main__':
84    asyncio.run(main())  ## Use terminal
85    # await main()  ## Use Jupyter or IPython(>=7.0)
86    # main_for_spyder()  ## Use Spyder