6This script demonstrates recording of variables using fast data
7acquisition (DAQ) approach. The recorded data is written to CSV
8file. If the 'openpyxl' module is installed, the data is also
9written to XLSX file. If 'pylab' module is installed, the acquired
12All the above functionality is grouped into functions, so you can
13easily take out only part of the script. This script can also be
14imported as a module to user's scripts, so it is easy to reuse
21import isystem.connect
as ic
28 isOpenPyXLInstalled =
True
29except (ImportError)
as ex:
30 isOpenPyXLInstalled =
False
34 isPyLabInstalled =
True
35except (ImportError)
as ex:
36 isPyLabInstalled =
False
40 print(
"Usage: dataRecorderWithDAQ.py <variableName1 samplingRateInSeconds1> ...")
42 print(
" If 'samplingRateInSeconds' == 0, the smallest possible sampling")
43 print(
" time is used. Supported values: 0.001, 0.01, 0.1, 1 second.")
44 print(
" See CDAQController::EDAQSampligFlags for all possible")
48 print(
"Example: dataRecorderWithDAQ.py main_loop_counter 0.1 g_baseStruct.i_base 0.01")
49 print(
" records main_loop_counter each 100 ms, and g_baseStruct.i_base with 10 ms period.")
54 This function initializes the target. Customize it according to
58 debugCtrl = ic.CDebugFacade(cmgr)
61 debugCtrl.runUntilFunction("main")
62 debugCtrl.waitUntilStopped()
69def realTimeToDAQTimeFlags(samplTime):
71 Converts the given sampling time in seconds to EDAQSamplingFlags.
74 return ic.CDAQController.daqSampleMax
75 elif samplTime < 0.01:
76 return ic.CDAQController.daqSample1ms
78 return ic.CDAQController.daqSample10ms
80 return ic.CDAQController.daqSample100ms
82 return ic.CDAQController.daqSample1s
85def recordVariables(cmgr,
88 recordingTimeInSeconds,
93 This function reads varibles and writes them to CSV file.
94 If isRecordToMemory ==
False, the amount of data that can be recorded
is
95 limited by the free disk size.
99 debugCtrl - iSYSTEM
's debugCtrl controller, which provides access to target
101 variables - array of two element arrays, where the first element contains
102 variable name and the second element contains sampling interval,
103 for example: [[
'main_loop_counter', 0.1], [
'g_baseStruct.i_base', 0]].
104 Sampling interval set to 0 means the smallest interval possible.
106 recordingTimeInSeconds - how long to record the data,
in seconds. Recording
107 can also be terminated by pressing the
'q' key
109 fileName - name of the output CSV file.
111 isRecordToMemory -
if True, then data
is also stored into memory
112 array
and returned
as function
return value. Be
113 aware of memory usage
in this case. If false,
114 an empty list
is returned.
116 isPrintToStdOut -
if True, each row
is printed to stdout during recording
119 List of rows, where each row
is a list containing time stamp
and recorded
120 values
in the same order
as variable names were specified. Example
for
121 two samples of three variables:
123 [0.1, 24, -525, 1.78]
127 daqCtrl = ic.CDAQController(cmgr)
130 daqInfo = daqCtrl.info()
131 if daqInfo.getMaxItems() == 0:
132 raise Exception(
"Data Acquisition (DAQ) system is not available.")
134 print(
'MaxItems = ', daqInfo.getMaxItems())
136 daqVariables = ic.DAQConfigVector()
137 for varSamplData
in variables:
138 varName = varSamplData[0]
139 samplTime = realTimeToDAQTimeFlags(varSamplData[1])
141 if varName.startswith(
'0x'):
143 memAddr = int(varName)
144 daqVariables.append(ic.CDAQConfigItem(4, 0, memAddr, samplTime))
147 daqVariables.append(ic.CDAQConfigItem(varName, samplTime))
150 daqTimeStart = daqCtrl.status().getTime()
152 daqCtrl.configure(daqVariables)
155 daqCtrl.enableGlobal(
True)
157 startTime = time.time()
158 endTime = startTime + recordingTimeInSeconds
160 numVars = len(variables)
163 with open(fileName,
'w')
as csvFile:
168 csvWriter = csv.writer(csvFile)
171 for varData
in variables:
172 varNames.append(varData[0])
174 csvWriter.writerow([
'Time'] + varNames)
179 row = [
''] * (1 + numVars)
181 while time.time() < endTime:
183 daqStatus = daqCtrl.status()
185 if daqStatus.getNumSamplesAvailable() > 0:
187 if daqStatus.getOverflow():
188 print(
'SAMPLING OVERFLOW!')
191 daqSamples = ic.DAQSampleVector()
192 daqCtrl.read(daqSamples)
195 for daqSample
in daqSamples:
197 sampleTime = daqSample.getTime() - daqTimeStart
198 columnIndex = daqSample.getIndex()+1
200 var = daqCtrl.getDataValue(daqSample)
202 if var.isTypeUnsigned()
or var.isTypeSigned():
203 value = var.getLong()
204 elif var.isTypeFloat():
205 value = var.getDouble()
206 elif var.isTypeAddress():
207 value = var.getAddress().m_aAddress
208 elif var.isTypeCompound():
212 if (sampleTime != lastTime):
217 csvWriter.writerow(row)
221 recordedData.append(row)
224 row = [
''] * (numVars+1)
228 lastTime = sampleTime
230 row[columnIndex] = value
234 csvWriter.writerow(row)
238 recordedData.append(row)
243def writeDataToXLSX(fileName, data, expressions):
244 book = openpyxl.Workbook()
245 sheet = book.create_sheet()
246 sheet.title =
'Variables'
249 sheet.append([
'Time'] + expressions)
259 if len(sys.argv) < 2:
271 for idx
in range(1, len(sys.argv), 2):
272 varName = sys.argv[idx]
273 varNames.append(varName)
274 samplingInfo.append([varName, float(sys.argv[idx + 1])])
276 cmgr = ic.ConnectionMgr()
277 cmgr.initLogger(
'daq',
'daqExample.log', ic.CLogger.PYTHON)
278 cmgr.connect(ic.CConnectionConfig().instanceId(winidea_id))
279 if not cmgr.isAttached():
280 print(
"The connection to winIDEA has not been established - exiting script.")
283 print(
"Established connection to winIDEA.")
284 debugCtrl = initTarget(cmgr)
287 recordingTimeInSeconds = 3
288 filePrefix =
'daqData'
289 isRecordToMemory =
True
290 isPrintToStdOut =
True
291 print(
'Recording ...')
293 daqResults = recordVariables(cmgr,
296 recordingTimeInSeconds,
301 if isOpenPyXLInstalled
and daqResults:
302 writeDataToXLSX(filePrefix +
'.xlsx', daqResults, varNames)
305 lineTypes = [
'k',
'r',
'g',
'b',
'k:',
'r:',
'g:',
'b:']
308 data = plab.array(daqResults).astype(
'S12')
311 for varName
in varNames:
312 plab.subplot(len(varNames), 1, plotIdx)
317 linesData = data[data[:, plotIdx] != b
'']
318 times = linesData[:, 0]
319 plab.plot(times, linesData[:, plotIdx], lineTypes[(plotIdx - 1)% len(lineTypes)])
328if __name__ ==
'__main__':