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