Skip to content

Class definition

Module

Bases: PviObject

class representing modules

SNMP : can be used but is not necessary

Typical usage example:

cpu = Cpu( device, 'myArsim', CD='/IP=127.0.0.1' )
module = Module( cpu, 'bigmod' )
Source code in pvi\pvi_objects\Module.py
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
class Module(PviObject):
    '''class representing modules

    SNMP : can be used but is not necessary

    Typical usage example:
    ```
    cpu = Cpu( device, 'myArsim', CD='/IP=127.0.0.1' )
    module = Module( cpu, 'bigmod' )
    ```
    '''

    _BUFFER_SIZE_SMALL: int = 1024
    _BUFFER_SIZE_MEDIUM: int = 4096
    _ANSL_LOGGER_ACCESS_NOT_SUPPORTED: int = 12058

    # ------------------------------------------------------------------

    def __init__(self, parent: PviObject, name: str, **objectDescriptor: Union[str, int, float]):
        '''
        Args:
            parent : CPU object
            name : name of module
            objectDescriptor : see PVI documentation for more details
        '''
        if parent.type != T_POBJ_TYPE.POBJ_CPU:
            raise PviError(12009, self)
        if 'CD' not in objectDescriptor:
            objectDescriptor.update({'CD': name})
        super().__init__(parent, T_POBJ_TYPE.POBJ_MODULE, name, **objectDescriptor)
        self._uploaded: Optional[Callable] = None
        self._progress: Optional[Callable] = None


    def __repr__(self) -> str:
        return f"Module( name={self._name}, linkID={self._linkID} )"


    def _call_callback(self, callback: Optional[Callable], *args) -> None:
        """
        Call a callback with flexible signature (1 or 2 parameters).
        If callback accepts 2 params: callback(self, *args).
        If callback accepts 1 param:  callback(*args).
        Does nothing when callback is None.
        """
        if callback is None:
            return
        sig = inspect.signature(callback)
        if len(sig.parameters) == 2:
            callback(self, *args)
        else:
            callback(*args)


    def _read_response_bytes(self, wParam, dataLen: int, extra: int = 0) -> bytes:
        """
        Read PVI response into a buffer and return raw bytes.

        Args:
            wParam:   wParam from the event
            dataLen:  number of bytes reported by the event
            extra:    optional extra bytes added to the buffer (default 0)
        Raises:
            PviError: if PviXReadResponse returns non-zero
        """
        s = create_string_buffer(dataLen + extra)
        self._result = PviXReadResponse(self._hPvi, wParam, s, sizeof(s))
        if self._result != 0:
            raise PviError(self._result, self)
        return s.raw


    @staticmethod
    def _parse_xml(data: Union[str, bytes]) -> ET.Element:
        """
        Parse XML and return root Element.
        Raises:
            ValueError: wraps ET.ParseError with descriptive message
        """
        try:
            return ET.fromstring(data)
        except ET.ParseError as exc:
            raise ValueError(f"Invalid XML data: {exc}") from exc

    # ------------------------------------------------------------------

    def _eventUploadStream(self, wParam, responseInfo, dataLen: int) -> None:
        '''(internal) upload a data module as stream'''
        raw = self._read_response_bytes(wParam, dataLen)        
        self._call_callback(self._uploaded, raw)                


    def _eventUploadLogData(self, wParam, responseInfo, dataLen: int) -> None:
        '''(internal) upload XML logger data (ANSL only)'''
        raw = self._read_response_bytes(wParam, dataLen, extra=256)  
        cleaned = raw.replace(b'\x00', b'')
        logger = self._parse_xml(cleaned)                            

        entries: List[Dict[str, Any]] = []
        for entry in logger:
            cols = {'Version', 'RecordId', 'OriginRecordId', 'EventId',
                    'AddDataSize', 'AddDataFormat', 'Severity', 'Info'}
            for c in cols:
                try:
                    entry.attrib[c] = str(int(entry.attrib[c]))
                except (KeyError, ValueError):
                    pass
            try:
                entry.attrib['TimestampUtc'] = str(
                    datetime.fromtimestamp(float(entry.attrib['TimestampUtc'])))
            except (KeyError, ValueError):
                pass
            entries.append(entry.attrib)

        self._call_callback(self._uploaded, entries)           


    def _eventUploadModData(self, wParam, responseInfo, dataLen: int) -> None:
        '''(internal) upload logger data (INA2000)
        see GUID 75bf0748-45f2-4610-a68d-53760ab5fa98
        '''
        patternParameterPairs = re.compile(r'\s*([A-Z]{1,4}=\w*)\s*')
        raw = self._read_response_bytes(wParam, dataLen)        

        entries: List[Dict[str, Any]] = []
        data = raw.split(b'\x00')
        n = 0
        noOfEntries = int(data[0][3:])
        while n < noOfEntries * 3:
            n += 1
            entry: Dict[str, Any] = {}
            for m in patternParameterPairs.findall(str(data[n])):
                if m.startswith('TIME'):    entry['date']  = datetime.fromtimestamp(int(m[5:]))
                elif m.startswith('ID'):    entry['id']    = int(m[3:])
                elif m.startswith('E'):     entry['error'] = int(m[2:])
                elif m.startswith('INFO'):  entry['info']  = int(m[5:])
                elif m.startswith('LEV'):   entry['level'] = int(m[4:])
                elif m.startswith('TASK'):  entry['task']  = str(data[5:])
            n += 1; entry['ascii'] = data[n]
            n += 1; entry['bin']   = data[n]
            entries.append(entry)

        self._call_callback(self._uploaded, entries)            


    def _eventProceeding(self, wParam, responseInfo) -> None:
        '''(internal) return proceeding info'''
        proceedingInfo = T_PROCEEDING_INFO()
        self._result = PviXReadResponse(self._hPvi, wParam, byref(proceedingInfo), sizeof(proceedingInfo))
        if self._result == 0:
            self._call_callback(self._progress, int(proceedingInfo.Percent))  
        else:
            raise PviError(self._result, self)


    def upload(self, **kwargs: Union[str, Callable]) -> None:
        '''
        uploadLoggerData
        loads logger data if module is a logger module else load binary data

        Args:
            kwargs:
                uploaded - callback - is fired when module was uploaded
                progress - callback(int) - returns percentage of progress
                MT - Moduletype e.g. 'BRT', '_LOGM'
        '''
        arguments = ''
        loggerModule = False
        for key, value in kwargs.items():
            if key == 'uploaded':
                if callable(value):
                    self._uploaded = value
                else:
                    raise TypeError("only type 'callable' for argument 'uploaded' allowed !")
            elif key == 'progress':
                if callable(value):
                    self._progress = value
                else:
                    raise TypeError("only type 'callable' for argument 'progress' allowed !")
            elif key == 'MT' and value == '_LOGM':
                loggerModule = True
            else:
                arguments += f"{key}={value}"

        if loggerModule:
            s = create_string_buffer(b'\000' * self._BUFFER_SIZE_MEDIUM)         
            self._result = PviXRead(self._hPvi, self._linkID, POBJ_ACC_LN_XML_LOGM_INFO,
                                    None, 0, byref(s), sizeof(s))
            if self._result == 0:
                xmlTree = self._parse_xml(str(s, 'ascii').rstrip('\x00'))        
                loggerVersion = xmlTree.attrib.get('Version', '1000').encode('ascii')
                s = create_string_buffer(b'DN=10000000 VI=' + loggerVersion)
                self._result = PviXReadArgumentRequest(self._hPvi, self._linkID,
                    POBJ_ACC_LN_XML_LOGM_DATA, byref(s), sizeof(s), PVI_HMSG_NIL, SET_PVIFUNCTION, 0)
                if self._result:
                    raise PviError(self._result)
            elif self._result == self._ANSL_LOGGER_ACCESS_NOT_SUPPORTED:        
                s = create_string_buffer(b'DN=100000')  # maximum possible is undocumented
                self._result = PviXReadArgumentRequest(self._hPvi, self._linkID,
                    POBJ_ACC_MOD_DATA, byref(s), sizeof(s), PVI_HMSG_NIL, SET_PVIFUNCTION, 0)
                if self._result:
                    raise PviError(self._result)
            else:
                raise PviError(self._result)
        else:
            s = create_string_buffer(bytes(arguments, 'ascii'))
            self._result = PviXReadArgumentRequest(self._hPvi, self._linkID,
                POBJ_ACC_UPLOAD_STM, byref(s), sizeof(s), PVI_HMSG_NIL, SET_PVIFUNCTION, 0)
            if self._result:
                raise PviError(self._result)


    def delete(self) -> None:
        """
        delete Module from CPU

        Raises:
            PviError : PVI-Error

        Returns:
            None
        """
        s = create_string_buffer(b'LD=Delete')        
        self._result = PviXWrite( self._hPvi, self._linkID, POBJ_ACC_STATUS, byref(s), sizeof(s), None, 0 )  
        if self._result:
            raise PviError(self._result, self)        

    @property
    def moduleInfo(self) -> dict:
        """read the Module type information"""
        s = create_string_buffer(b'\000' * self._BUFFER_SIZE_SMALL)              
        self._result = PviXRead(self._hPvi, self._linkID, POBJ_ACC_MOD_TYPE,
                                None, 0, byref(s), sizeof(s))
        if self._result == 0:
            ret: Dict[str, Any] = {}
            ret.update(dictFromParameterPairString(str(s, 'ascii').rstrip('\x00')))
            ret['MT'] = ModuleType(int(ret.get('MT', 0)))
            return ret
        else:
            raise PviError(self._result, self)

    @property
    def moduleInfoExtended(self) -> dict:
        """read the extended Module type information"""
        s = create_string_buffer(b'\000' * self._BUFFER_SIZE_MEDIUM)             
        self._result = PviXRead(self._hPvi, self._linkID, POBJ_ACC_LN_XML_MOD_INFO,
                                None, 0, byref(s), sizeof(s))
        if self._result == 0:
            root = self._parse_xml(str(s, 'ascii').rstrip('\x00'))               
            module_info: Dict[str, Any] = {}
            if root.tag == 'ModInfo':
                module_info = dict(root.attrib)
                module_info['ModulType'] = ModuleType(int(module_info.get('ModulType', '0x00'), 16)).name
                module_info['MemType']   = MemoryType(int(module_info.get('MemType',   '0x100'), 16)).name
                module_info['Time']      = datetime.strptime(module_info.get('Time', ''), "%Y-%m-%d-%H-%M-%S.%f")
                version  = f"{int(module_info.get('Version',  '0')):02x}"
                version += f"{int(module_info.get('Revision', '0')):02x}"
                module_info['Version'] = f'{version[0]}.{version[1]}{version[2]}.{version[3]}'
                del module_info['Revision']
            return module_info
        else:
            raise PviError(self._result, self)

moduleInfo: dict property

read the Module type information

moduleInfoExtended: dict property

read the extended Module type information

__init__(parent, name, **objectDescriptor)

Parameters:

Name Type Description Default
parent

CPU object

required
name

name of module

required
objectDescriptor

see PVI documentation for more details

{}
Source code in pvi\pvi_objects\Module.py
114
115
116
117
118
119
120
121
122
123
124
125
126
127
def __init__(self, parent: PviObject, name: str, **objectDescriptor: Union[str, int, float]):
    '''
    Args:
        parent : CPU object
        name : name of module
        objectDescriptor : see PVI documentation for more details
    '''
    if parent.type != T_POBJ_TYPE.POBJ_CPU:
        raise PviError(12009, self)
    if 'CD' not in objectDescriptor:
        objectDescriptor.update({'CD': name})
    super().__init__(parent, T_POBJ_TYPE.POBJ_MODULE, name, **objectDescriptor)
    self._uploaded: Optional[Callable] = None
    self._progress: Optional[Callable] = None

delete()

delete Module from CPU

Raises:

Type Description
PviError

PVI-Error

Returns:

Type Description
None

None

Source code in pvi\pvi_objects\Module.py
308
309
310
311
312
313
314
315
316
317
318
319
320
321
def delete(self) -> None:
    """
    delete Module from CPU

    Raises:
        PviError : PVI-Error

    Returns:
        None
    """
    s = create_string_buffer(b'LD=Delete')        
    self._result = PviXWrite( self._hPvi, self._linkID, POBJ_ACC_STATUS, byref(s), sizeof(s), None, 0 )  
    if self._result:
        raise PviError(self._result, self)        

upload(**kwargs)

uploadLoggerData loads logger data if module is a logger module else load binary data

Parameters:

Name Type Description Default
kwargs Union[str, Callable]

uploaded - callback - is fired when module was uploaded progress - callback(int) - returns percentage of progress MT - Moduletype e.g. 'BRT', '_LOGM'

{}
Source code in pvi\pvi_objects\Module.py
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
def upload(self, **kwargs: Union[str, Callable]) -> None:
    '''
    uploadLoggerData
    loads logger data if module is a logger module else load binary data

    Args:
        kwargs:
            uploaded - callback - is fired when module was uploaded
            progress - callback(int) - returns percentage of progress
            MT - Moduletype e.g. 'BRT', '_LOGM'
    '''
    arguments = ''
    loggerModule = False
    for key, value in kwargs.items():
        if key == 'uploaded':
            if callable(value):
                self._uploaded = value
            else:
                raise TypeError("only type 'callable' for argument 'uploaded' allowed !")
        elif key == 'progress':
            if callable(value):
                self._progress = value
            else:
                raise TypeError("only type 'callable' for argument 'progress' allowed !")
        elif key == 'MT' and value == '_LOGM':
            loggerModule = True
        else:
            arguments += f"{key}={value}"

    if loggerModule:
        s = create_string_buffer(b'\000' * self._BUFFER_SIZE_MEDIUM)         
        self._result = PviXRead(self._hPvi, self._linkID, POBJ_ACC_LN_XML_LOGM_INFO,
                                None, 0, byref(s), sizeof(s))
        if self._result == 0:
            xmlTree = self._parse_xml(str(s, 'ascii').rstrip('\x00'))        
            loggerVersion = xmlTree.attrib.get('Version', '1000').encode('ascii')
            s = create_string_buffer(b'DN=10000000 VI=' + loggerVersion)
            self._result = PviXReadArgumentRequest(self._hPvi, self._linkID,
                POBJ_ACC_LN_XML_LOGM_DATA, byref(s), sizeof(s), PVI_HMSG_NIL, SET_PVIFUNCTION, 0)
            if self._result:
                raise PviError(self._result)
        elif self._result == self._ANSL_LOGGER_ACCESS_NOT_SUPPORTED:        
            s = create_string_buffer(b'DN=100000')  # maximum possible is undocumented
            self._result = PviXReadArgumentRequest(self._hPvi, self._linkID,
                POBJ_ACC_MOD_DATA, byref(s), sizeof(s), PVI_HMSG_NIL, SET_PVIFUNCTION, 0)
            if self._result:
                raise PviError(self._result)
        else:
            raise PviError(self._result)
    else:
        s = create_string_buffer(bytes(arguments, 'ascii'))
        self._result = PviXReadArgumentRequest(self._hPvi, self._linkID,
            POBJ_ACC_UPLOAD_STM, byref(s), sizeof(s), PVI_HMSG_NIL, SET_PVIFUNCTION, 0)
        if self._result:
            raise PviError(self._result)