AI continuous with logger

  1'''
  2AI - AI_continuous_with_logger.py with asynchronous mode.
  3
  4This example demonstrates the process of obtaining AI data in continuous mode with 8 channels from STEM.
  5Then, save data into CSV file.
  6
  7To begin with, it demonstrates the steps to open the AI and configure the AI parameters.
  8Next, it outlines the procedure for reading and saving 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-2024 WPC Systems Ltd. All rights reserved.
 33'''
 34
 35## Python
 36import asyncio
 37
 38## WPC
 39
 40from wpcsys import pywpc
 41
 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.STEM()
 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    try:
 60        ## Parameters setting
 61        slot = 1 ## Connect AIO module to slot
 62        mode = 2 ## 0 : On demand, 1 : N-samples, 2 : Continuous.
 63        sampling_rate = 200
 64        read_points = 200
 65        read_delay = 0.2 ## second
 66        chip_select = [0, 1]
 67
 68        ## Get firmware model & version
 69        driver_info = await dev.Sys_getDriverInfo_async()
 70        print("Model name: " + driver_info[0])
 71        print("Firmware version: " + driver_info[-1])
 72
 73        ## Open file with WPC_test.csv
 74        err = dev.Logger_openFile("WPC_test.csv")
 75        print(f"Logger_openFile, status: {err}")
 76
 77        ## Write header into CSV file
 78        err = dev.Logger_writeHeader(["CH0","CH1","CH2","CH3","CH4","CH5","CH6","CH7"])
 79        print(f"Logger_writeHeader, status: {err}")
 80
 81        ## Get slot mode
 82        slot_mode = await dev.Sys_getMode_async(slot)
 83        print("Slot mode:", slot_mode)
 84
 85        ## If the slot mode is not set to "AIO", set the slot mode to "AIO"
 86        if slot_mode != "AIO":
 87            err = await dev.Sys_setAIOMode_async(slot)
 88            print(f"Sys_setAIOMode_async in slot {slot}, status: {err}")
 89
 90        ## Get slot mode
 91        slot_mode = await dev.Sys_getMode_async(slot)
 92        print("Slot mode:", slot_mode)
 93
 94        ## Open AI
 95        err = await dev.AI_open_async(slot)
 96        print(f"AI_open_async in slot {slot}, status: {err}")
 97
 98        ## Enable CS
 99        err = await dev.AI_enableCS_async(slot, chip_select)
100        print(f"AI_enableCS_async in slot {slot}, status: {err}")
101
102        ## Set AI acquisition mode to continuous mode (2)
103        err = await dev.AI_setMode_async(slot, mode)
104        print(f"AI_setMode_async {mode} in slot {slot}, status: {err}")
105
106        ## Set AI sampling rate
107        err = await dev.AI_setSamplingRate_async(slot, sampling_rate)
108        print(f"AI_setSamplingRate_async {sampling_rate} in slot {slot}, status: {err}")
109
110        ## Open AI streaming
111        err = await dev.AI_openStreaming_async(slot)
112        print(f"AI_openStreaming_async in slot {slot}, status: {err}")
113
114        ## Start AI streaming
115        err = await dev.AI_startStreaming_async(slot)
116        print(f"AI_startStreaming_async in slot {slot}, status: {err}")
117
118        ## Wait for acquisition
119        await asyncio.sleep(1) ## delay [s]
120
121        ## Close AI streaming
122        err = await dev.AI_closeStreaming_async(slot)
123        print(f"AI_closeStreaming_async in slot {slot}, status: {err}")
124
125        data_len = 1
126        while data_len > 0:
127            ## Read data acquisition
128            ai_2Dlist = await dev.AI_readStreaming_async(slot, read_points, read_delay)
129            print(f"number of samples = {len(ai_2Dlist)}" )
130
131            ## Write data into CSV file
132            dev.Logger_write2DList(ai_2Dlist)
133
134            ## Update data len
135            data_len = len(ai_2Dlist)
136
137        ## Close AI
138        err = await dev.AI_close_async(slot)
139        print(f"AI_close_async in slot {slot}, status: {err}")
140    except Exception as err:
141        pywpc.printGenericError(err)
142
143    ## Disconnect device
144    dev.disconnect()
145
146    ## Release device handle
147    dev.close()
148
149    return
150
151def main_for_spyder(*args):
152    if asyncio.get_event_loop().is_running():
153        return asyncio.create_task(main(*args)).result()
154    else:
155        return asyncio.run(main(*args))
156if __name__ == '__main__':
157    asyncio.run(main()) ## Use terminal
158    # await main() ## Use Jupyter or IPython(>=7.0)
159    # main_for_spyder() ## Use Spyder