AI N samples once

  1'''
  2AI - AI_N_samples_once.py with asynchronous mode.
  3
  4This example demonstrates the process of obtaining AI data in N-sample mode.
  5Additionally, it gets AI data with points in once from STEM.
  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 streaming AI data.
  9Finally, it concludes by explaining how to close the AI.
 10
 11If your product is "STEM", please invoke the function `Sys_setAIOMode_async`and `AI_enableCS_async`.
 12Example: AI_enableCS_async is {0, 2}
 13Subsequently, the returned value of AI_readOnDemand_async and AI_readStreaming_async will be displayed as follows.
 14data:
 15          CH0, CH1, CH2, CH3, CH4, CH5, CH6, CH7, CH0, CH1, CH2, CH3, CH4, CH5, CH6, CH7
 16          |                                     |                                      |
 17          |---------------- CS0-----------------|---------------- CS2------------------|
 18[sample0]
 19[sample1]
 20   .
 21   .
 22   .
 23[sampleN]
 24
 25-------------------------------------------------------------------------------------
 26Please change correct serial number or IP and port number BEFORE you run example code.
 27
 28For other examples please check:
 29    https://github.com/WPC-Systems-Ltd/WPC_Python_driver_release/tree/main/examples
 30See README.md file to get detailed usage of this example.
 31
 32Copyright (c) 2022-2025 WPC Systems Ltd. All rights reserved.
 33'''
 34
 35## WPC
 36from wpcsys import pywpc
 37
 38## Python
 39import asyncio
 40import sys
 41sys.path.insert(0, 'src/')
 42
 43
 44async def main():
 45    ## Get Python driver version
 46    print(f'{pywpc.PKG_FULL_NAME} - Version {pywpc.__version__}')
 47
 48    ## Create device handle
 49    dev = pywpc.STEM()
 50
 51    ## Connect to device
 52    try:
 53        dev.connect("192.168.1.110")  ## Depend on your device
 54    except Exception as err:
 55        pywpc.printGenericError(err)
 56        ## Release device handle
 57        dev.close()
 58        return
 59
 60    try:
 61        ## Parameters setting
 62        slot = 1  ## Connect AIO module to slot
 63        mode = 1  ## 0: On demand, 1: N-samples, 2: Continuous
 64        sampling_rate = 1000
 65        samples = 200
 66        read_points = 200
 67        read_delay = 0.5  ## [sec]
 68        chip_select = [0, 1]
 69
 70        ## Get firmware model & version
 71        driver_info = await dev.Sys_getDriverInfo_async()
 72        print(f"Model name: {driver_info[0]}, Firmware version: {driver_info[-1]} ")
 73
 74        ## Get slot mode
 75        slot_mode = await dev.Sys_getMode_async(slot)
 76        print("Slot mode:", slot_mode)
 77
 78        ## If the slot mode is not set to "AIO", set the slot mode to "AIO"
 79        if slot_mode != "AIO":
 80            err = await dev.Sys_setAIOMode_async(slot)
 81            print(f"Sys_setAIOMode_async in slot {slot}, status: {err}")
 82
 83        ## Get slot mode
 84        slot_mode = await dev.Sys_getMode_async(slot)
 85        print("Slot mode:", slot_mode)
 86
 87        ## Open AI
 88        err = await dev.AI_open_async(slot)
 89        print(f"AI_open_async in slot {slot}, status: {err}")
 90
 91        ## Enable CS
 92        err = await dev.AI_enableCS_async(slot, chip_select)
 93        print(f"AI_enableCS_async in slot {slot}, status: {err}")
 94
 95        ## Set AI acquisition mode to N-samples mode (1)
 96        err = await dev.AI_setMode_async(slot, mode)
 97        print(f"AI_setMode_async {mode} in slot {slot}, status: {err}")
 98
 99        ## Set AI sampling rate
100        err = await dev.AI_setSamplingRate_async(slot, sampling_rate)
101        print(f"AI_setSamplingRate_async {sampling_rate} in slot {slot}, status: {err}")
102
103        ## Set AI # of samples
104        err = await dev.AI_setNumSamples_async(slot, samples)
105        print(f"AI_setNumSamples_async {samples} in slot {slot}, status: {err}")
106
107        ## Open AI streaming
108        err = await dev.AI_openStreaming_async(slot)
109        print(f"AI_openStreaming_async in slot {slot}, status: {err}")
110
111        ## Start AI streaming
112        err = await dev.AI_startStreaming_async(slot)
113        print(f"AI_startStreaming_async in slot {slot}, status: {err}")
114
115        ## Read AI
116        ai_2Dlist = await dev.AI_readStreaming_async(slot, read_points, read_delay)
117        print(f"number of samples = {len(ai_2Dlist)}")
118
119        ok = True
120        for i, ai_list in enumerate(ai_2Dlist):
121            ## Check for any missing data
122            if len(ai_list) != len(chip_select) * 8:
123                print(i, ai_list)
124                ok = False
125        if ok:
126            print('OK')
127        else:
128            print('NG')
129
130        ## Close AI streaming
131        err = await dev.AI_closeStreaming_async(slot)
132        print(f"AI_closeStreaming_async in slot {slot}, status: {err}")
133
134        ## Close AI
135        err = await dev.AI_close_async(slot)
136        print(f"AI_close_async in slot {slot}, status: {err}")
137    except Exception as err:
138        pywpc.printGenericError(err)
139
140    finally:
141        ## Disconnect device
142        dev.disconnect()
143
144        ## Release device handle
145        dev.close()
146
147
148def main_for_spyder(*args):
149    if asyncio.get_event_loop().is_running():
150        return asyncio.create_task(main(*args)).result()
151    else:
152        return asyncio.run(main(*args))
153
154
155if __name__ == '__main__':
156    asyncio.run(main())  ## Use terminal
157    # await main()  ## Use Jupyter or IPython(>=7.0)
158    # main_for_spyder()  ## Use Spyder