AI on demand in loop

 1'''
 2AI - AI_on_demand_in_loop.py with asynchronous mode.
 3
 4This example demonstrates the process of obtaining AI data in on demand mode.
 5Additionally, it utilizes a loop to retrieve AI data with 5 times from WifiDAQE3A.
 6
 7To begin with, it demonstrates the steps to open the AI and configure the AI parameters.
 8Next, it outlines the procedure for reading the AI on demand data.
 9Finally, it concludes by explaining how to close the AI.
10
11-------------------------------------------------------------------------------------
12Please change correct serial number or IP and port number BEFORE you run example code.
13
14For other examples please check:
15    https://github.com/WPC-Systems-Ltd/WPC_Python_driver_release/tree/main/examples
16See README.md file to get detailed usage of this example.
17
18Copyright (c) 2022-2025 WPC Systems Ltd. All rights reserved.
19'''
20
21## WPC
22from wpcsys import pywpc
23
24## Python
25import asyncio
26import sys
27sys.path.insert(0, 'src/')
28
29
30async def main():
31    ## Get Python driver version
32    print(f'{pywpc.PKG_FULL_NAME} - Version {pywpc.__version__}')
33
34    ## Create device handle
35    dev = pywpc.WifiDAQE3A()
36
37    ## Connect to device
38    try:
39        dev.connect("192.168.5.38")  ## Depend on your device
40    except Exception as err:
41        pywpc.printGenericError(err)
42        ## Release device handle
43        dev.close()
44        return
45
46    try:
47        ## Parameters setting
48        port = 0  ## Depend on your device
49        mode = 0
50        
51
52        ## Get firmware model & version
53        driver_info = await dev.Sys_getDriverInfo_async()
54        print(f"Model name: {driver_info[0]}, Firmware version: {driver_info[-1]} ")
55
56        ## Open AI
57        err = await dev.AI_open_async(port)
58        print(f"AI_open_async in port {port}, status: {err}")
59        
60
61        ## Set AI acquisition mode to on demand mode (0)
62        err = await dev.AI_setMode_async(port, mode)
63        print(f"AI_setMode_async {mode} in port {port}, status: {err}")
64
65        ## Read AI
66        for i in range(5):
67            ai_list = await dev.AI_readOnDemand_async(port)
68            print(f"data in port {port}: {ai_list}")
69
70        ## Close AI
71        err = await dev.AI_close_async(port)
72        print(f"AI_close_async in port {port}, status: {err}")
73    except Exception as err:
74        pywpc.printGenericError(err)
75
76    finally:
77        ## Disconnect device
78        dev.disconnect()
79
80        ## Release device handle
81        dev.close()
82
83
84def main_for_spyder(*args):
85    if asyncio.get_event_loop().is_running():
86        return asyncio.create_task(main(*args)).result()
87    else:
88        return asyncio.run(main(*args))
89
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