Exemplo n.º 1
0
    def _notifDataCallback(self, notifName, notifParams):

        assert notifName == NOTIFDATA

        try:
            # log
            log.debug(
                "notifClient._notifDataCallback {0}:\n{1}".format(NOTIFDATA, FormatUtils.formatNamedTuple(notifParams))
            )

            # read MAC address from notification
            mac = tuple(notifParams.macAddress)

            # update role
            self._changeDeviceRole(mac, ROLE_DATA)

            # update counters
            self._incrementCounter(mac, COL_NOTIF_DATA)

            # parse packet
            if notifParams.srcPort == 0xF0B9:
                self.oap_dispatch.dispatch_pkt(NOTIFDATA, notifParams)
            else:
                raise SystemError("expected srcPort {0}".format(notifParams.srcPort))

        except Exception as err:
            output = []
            output += [type(err)]
            output += [err]
            output += [traceback.format_exc()]
            output = "\n".join([str(o) for o in output])
            log.error(output)
            print output
Exemplo n.º 2
0
 def _notifDataCallback(self, notifName, notifParams):
     
     assert notifName==NOTIFDATA
     
     try:
         # log
         log.debug(
             "notifClient._notifDataCallback {0}:\n{1}".format(
                 NOTIFDATA,
                 FormatUtils.formatNamedTuple(notifParams)
             )
         )
         
         # read MAC address from notification
         mac              = tuple(notifParams.macAddress)
         
         # update role
         self._changeDeviceRole(mac,ROLE_DATA)
         
         # update counters
         self._incrementCounter(mac,COL_NOTIF_DATA)
         
         # parse packet
         if notifParams.srcPort==0xf0b9:
             self.oap_dispatch.dispatch_pkt(NOTIFDATA, notifParams)
         else:
             raise SystemError("expected srcPort {0}".format(notifParams.srcPort))
     
     except Exception as err:
         output  = []
         output += [type(err)]
         output += [err]
         output += [traceback.format_exc()]
         output  = '\n'.join([str(o) for o in output])
         log.error(output)
         print output
Exemplo n.º 3
0
    def _dataCallback(self, notifName, notifParams):

        # log
        if isinstance(self.apiDef, IpMgrDefinition.IpMgrDefinition):
            # IpMgrSubscribe generates a named tuple
            log.debug("notifClient._dataCallback {0}:\n{1}".format(
                notifName, FormatUtils.formatNamedTuple(notifParams)))
        elif isinstance(self.apiDef, HartMgrDefinition.HartMgrDefinition):
            # HartMgrSubscriber generates a dictionary
            log.debug("notifClient._dataCallback {0}:\n{1}".format(
                notifName, FormatUtils.formatDictionnary(notifParams)))
        else:
            output = "apiDef of type {0} unexpected".format(type(self.apiDef))
            log.critical(output)
            print output
            raise SystemError(output)

        # record current time
        timeNow = time.time()

        # read MAC address from notification
        mac = self._getMacFromNotifParams(notifParams)

        # lock the data structure
        self.dataLock.acquire()

        # add mac/type to data, if necessary
        if mac not in self.data:
            self.data[mac] = {}
        if notifName not in self.data[mac]:
            self.data[mac][notifName] = 0

        # add mac/type to updates, if necessary
        if mac not in self.updates:
            self.updates[mac] = []
        if notifName not in self.updates[mac]:
            self.updates[mac].append(notifName)

        # increment counter
        self.data[mac][notifName] += 1

        # unlock the data structure
        self.dataLock.release()

        # transform HART OAP notification into equivalent IP version
        if isinstance(self.apiDef, HartMgrDefinition.HartMgrDefinition):
            # we are connected to a HART manager

            if (notifName in ['data']) and (len(notifParams['payload']) > 2):
                notifName = IpMgrSubscribe.IpMgrSubscribe.NOTIFDATA

                notifParams = IpMgrConnectorMux.IpMgrConnectorMux.Tuple_notifData(
                    utcSecs=int(notifParams['time'] / 1000),
                    utcUsecs=(notifParams['time'] % 1000) * 1000,
                    macAddress=mac,
                    srcPort=OAPMessage.OAP_PORT,
                    dstPort=OAPMessage.OAP_PORT,
                    data=tuple(notifParams['payload'][2:]),
                )

        # parse OAP packet
        if notifName in [IpMgrSubscribe.IpMgrSubscribe.NOTIFDATA]:
            try:
                self.oap_dispatch.dispatch_pkt(notifName, notifParams)
            except Exception as ex:
                traceback.print_exc()
Exemplo n.º 4
0
    def _notifDataCallbackTunneled(self, notifName, notifParams):

        assert notifName == NOTIFDATA

        try:
            # log
            log.debug(
                "notifClient._notifDataCallbackTunneled {0}:\n{1}".format(
                    NOTIFDATA, FormatUtils.formatNamedTuple(notifParams)
                )
            )

            # modify notification to unwrap mesh-of-meshes tunneling protocol
            if notifParams.srcPort == MOM_UDP_PORT:

                bridgeMac = tuple(notifParams.macAddress)

                # update role
                self._changeDeviceRole(bridgeMac, ROLE_BRIDGE)

                if notifParams.dstPort == MOM_UDP_PORT:
                    # tunneled response

                    payload = list(notifParams.data)

                    # unwrap tunneling protocol
                    assert len(payload) > 1
                    dispatch = payload[0]
                    payload = payload[1:]

                    if dispatch == MOM_RESP_DISPATCH_SERIALRESP:
                        raise NotImplementedError
                    elif dispatch == MOM_RESP_DISPATCH_RPC:
                        assert len(payload) > 1
                        procId = payload[0]
                        payload = payload[1:]
                        if procId == MOM_RPC_getOperationalMotes:
                            self._handle_resp_getOperationalMotes(bridgeMac, payload)
                        else:
                            raise SystemError("unexpected procId {0}".format(procId))
                    elif dispatch == MOM_RESP_DISPATCH_SERIALNOTIF:
                        # parse unwrapped Serial API Notification
                        (notifName, notifDict) = self.apiDef.deserialize(
                            self.apiDef.NOTIFICATION,
                            self.apiDef.nameToId(self.apiDef.NOTIFICATION, ["notification"]),
                            payload,
                        )

                        # convert to tuple
                        notifTuple = IpMgrConnectorMux.IpMgrConnectorMux.notifTupleTable[notifName[-1]](**notifDict)

                        # update bridge, if possible
                        try:
                            dataMoteMac = notifTuple.macAddress
                        except:
                            pass
                        else:
                            self._updateDataColumn(mac=dataMoteMac, colname=COL_BRIDGE, colvalue=bridgeMac)

                        # dispatch
                        if notifName[1] == NOTIFEVENT:
                            self._notifEventCallback(notifName[2], notifTuple)
                        elif notifName[1] == NOTIFHEALTHREPORT:
                            self._notifHrCallback(NOTIFHEALTHREPORT, notifTuple)
                        else:
                            SystemError("Unexpected notifName {0}".format(notifName))

                    else:
                        raise SystemError("Unexpected dispatch byte {0}".format(dispatch))

                else:
                    # tunneled upstream data

                    dataMoteMac = notifParams.data[:8]
                    data = notifParams.data[8:]

                    # update bridge
                    self._updateDataColumn(mac=dataMoteMac, colname=COL_BRIDGE, colvalue=bridgeMac)

                    # unwrap tunneling protocol
                    notifParams = IpMgrConnectorMux.IpMgrConnectorMux.Tuple_notifData(
                        utcSecs=notifParams.utcSecs,
                        utcUsecs=notifParams.utcUsecs,
                        macAddress=dataMoteMac,
                        srcPort=notifParams.dstPort,
                        dstPort=notifParams.dstPort,
                        data=data,
                    )

                    # dispatch unwrapped data again
                    self._notifDataCallback(notifName, notifParams)
            else:
                self._notifDataCallback(notifName, notifParams)

        except Exception as err:
            output = []
            output += [type(err)]
            output += [err]
            output += [traceback.format_exc()]
            output = "\n".join([str(o) for o in output])
            log.error(output)
            print output
Exemplo n.º 5
0
    def _dataCallback(self, notifName, notifParams):

        # log
        if isinstance(self.apiDef, IpMgrDefinition.IpMgrDefinition):
            # IpMgrSubscribe generates a named tuple
            log.debug("notifClient._dataCallback {0}:\n{1}".format(
                notifName, FormatUtils.formatNamedTuple(notifParams)))
        elif isinstance(self.apiDef, HartMgrDefinition.HartMgrDefinition):
            # HartMgrSubscriber generates a dictionary
            log.debug("notifClient._dataCallback {0}:\n{1}".format(
                notifName, FormatUtils.formatDictionnary(notifParams)))
        else:
            output = "apiDef of type {0} unexpected".format(type(self.apiDef))
            log.critical(output)
            print output
            raise SystemError(output)

        # record current time
        timeNow = time.time()

        # read MAC address from notification
        mac = self._getMacFromNotifParams(notifParams)

        # lock the data structure
        self.dataLock.acquire()

        # add mac/type to data, if necessary
        if mac not in self.data:
            self.data[mac] = {}
        if notifName not in self.data[mac]:
            self.data[mac][notifName] = 0

        # add mac/type to updates, if necessary
        if mac not in self.updates:
            self.updates[mac] = []
        if notifName not in self.updates[mac]:
            self.updates[mac].append(notifName)

        # increment counter
        self.data[mac][notifName] += 1

        # transform HART OAP notification into equivalent IP version
        if isinstance(self.apiDef, HartMgrDefinition.HartMgrDefinition):
            # we are connected to a HART manager

            if (notifName in ['data']) and (len(notifParams['payload']) > 2):
                notifName = IpMgrSubscribe.IpMgrSubscribe.NOTIFDATA

                notifParams = IpMgrConnectorMux.IpMgrConnectorMux.Tuple_notifData(
                    utcSecs=int(notifParams['time'] / 1000),
                    utcUsecs=(notifParams['time'] % 1000) * 1000,
                    macAddress=mac,
                    srcPort=OAPMessage.OAP_PORT,
                    dstPort=OAPMessage.OAP_PORT,
                    data=tuple(notifParams['payload'][2:]),
                )

        # calculate latency
        try:
            if notifName in [
                    IpMgrSubscribe.IpMgrSubscribe.NOTIFDATA,
                    IpMgrSubscribe.IpMgrSubscribe.NOTIFIPDATA,
            ]:
                try:
                    latency = self.latencyCalculator.getLatency(
                        float(notifParams.utcSecs) +
                        (float(notifParams.utcUsecs) / 1000000.0), timeNow)
                    # lat. current
                    if COL_LAT_CUR not in self.data[mac]:
                        self.data[mac][COL_LAT_CUR] = '-'
                    if COL_LAT_CUR not in self.updates[mac]:
                        self.updates[mac].append(COL_LAT_CUR)
                    self.data[mac][COL_LAT_CUR] = latency
                    # lat. min
                    if (((COL_LAT_MIN in self.data[mac]) and
                         (latency < self.data[mac][COL_LAT_MIN]))
                            or ((COL_LAT_MIN not in self.data[mac]))
                            or ((COL_LAT_MIN in self.data[mac]) and
                                (self.data[mac][COL_LAT_MIN] == '-'))):
                        if COL_LAT_MIN not in self.data[mac]:
                            self.data[mac][COL_LAT_MIN] = '-'
                        if COL_LAT_MIN not in self.updates[mac]:
                            self.updates[mac].append(COL_LAT_MIN)
                        self.data[mac][COL_LAT_MIN] = latency
                    # max
                    if (((COL_LAT_MAX in self.data[mac]) and
                         (latency > self.data[mac][COL_LAT_MAX]))
                            or ((COL_LAT_MAX not in self.data[mac]))
                            or ((COL_LAT_MAX in self.data[mac]) and
                                (self.data[mac][COL_LAT_MAX] == '-'))):
                        if COL_LAT_MAX not in self.data[mac]:
                            self.data[mac][COL_LAT_MAX] = '-'
                        if COL_LAT_MAX not in self.updates[mac]:
                            self.updates[mac].append(COL_LAT_MAX)
                        self.data[mac][COL_LAT_MAX] = latency
                except RuntimeError:
                    # can happen if latency calculator hasn't acquired lock yet
                    pass
        except Exception as err:
            print err

        # unlock the data structure
        self.dataLock.release()

        # parse OAP packet
        if notifName in [IpMgrSubscribe.IpMgrSubscribe.NOTIFDATA]:
            self.oap_dispatch.dispatch_pkt(notifName, notifParams)
Exemplo n.º 6
0
 def _notifDataCallbackTunneled(self, notifName, notifParams):
     
     assert notifName==NOTIFDATA
     
     try:
         # log
         log.debug(
             "notifClient._notifDataCallbackTunneled {0}:\n{1}".format(
                 NOTIFDATA,
                 FormatUtils.formatNamedTuple(notifParams)
             )
         )
         
         # modify notification to unwrap mesh-of-meshes tunneling protocol
         if notifParams.srcPort==MOM_UDP_PORT:
             
             bridgeMac         = tuple(notifParams.macAddress)
             
             # update role
             self._changeDeviceRole(bridgeMac,ROLE_BRIDGE)
             
             if notifParams.dstPort==MOM_UDP_PORT:
                 # tunneled response
                 
                 payload  = list(notifParams.data)
                 
                 # unwrap tunneling protocol
                 assert(len(payload)>1)
                 dispatch = payload[0]
                 payload  = payload[1:]
                 
                 if   dispatch==MOM_RESP_DISPATCH_SERIALRESP:
                     raise NotImplementedError
                 elif dispatch==MOM_RESP_DISPATCH_RPC:
                     assert(len(payload)>1)
                     procId    = payload[0]
                     payload   = payload[1:]
                     if procId==MOM_RPC_getOperationalMotes:
                         self._handle_resp_getOperationalMotes(bridgeMac,payload)
                     else:
                         raise SystemError("unexpected procId {0}".format(procId))
                 elif dispatch==MOM_RESP_DISPATCH_SERIALNOTIF:
                     # parse unwrapped Serial API Notification
                     (notifName,notifDict) = self.apiDef.deserialize(
                         self.apiDef.NOTIFICATION,
                         self.apiDef.nameToId(
                             self.apiDef.NOTIFICATION,
                             ['notification',]
                         ),
                         payload,
                     )
                     
                     # convert to tuple
                     notifTuple     = IpMgrConnectorMux.IpMgrConnectorMux.notifTupleTable[notifName[-1]](**notifDict)
                     
                     # update bridge, if possible
                     try:
                         dataMoteMac     = notifTuple.macAddress
                     except:
                         pass
                     else:
                         self._updateDataColumn(
                             mac         = dataMoteMac,
                             colname     = COL_BRIDGE,
                             colvalue    = bridgeMac,
                         )
                     
                     # dispatch
                     if   notifName[1]==NOTIFEVENT:
                         self._notifEventCallback(notifName[2],notifTuple)
                     elif notifName[1]==NOTIFHEALTHREPORT:
                         self._notifHrCallback(NOTIFHEALTHREPORT, notifTuple)
                     else:
                         SystemError("Unexpected notifName {0}".format(notifName))
                     
                 else:
                     raise SystemError("Unexpected dispatch byte {0}".format(dispatch))
                 
             else:
                 # tunneled upstream data
                 
                 dataMoteMac        = notifParams.data[:8]
                 data               = notifParams.data[8:]
                 
                 # update bridge
                 self._updateDataColumn(
                     mac            = dataMoteMac,
                     colname        = COL_BRIDGE,
                     colvalue       = bridgeMac,
                 )
                 
                 # unwrap tunneling protocol
                 notifParams = IpMgrConnectorMux.IpMgrConnectorMux.Tuple_notifData(
                     utcSecs        = notifParams.utcSecs,
                     utcUsecs       = notifParams.utcUsecs,
                     macAddress     = dataMoteMac,
                     srcPort        = notifParams.dstPort,
                     dstPort        = notifParams.dstPort,
                     data           = data,
                 )
                 
                 # dispatch unwrapped data again
                 self._notifDataCallback(notifName,notifParams)
         else:
             self._notifDataCallback(notifName,notifParams)
     
     except Exception as err:
         output  = []
         output += [type(err)]
         output += [err]
         output += [traceback.format_exc()]
         output  = '\n'.join([str(o) for o in output])
         log.error(output)
         print output
Exemplo n.º 7
0
 def _dataCallback(self, notifName, notifParams):
 
     # log
     if   isinstance(self.apiDef,IpMgrDefinition.IpMgrDefinition):
         # IpMgrSubscribe generates a named tuple
         log.debug(
             "notifClient._dataCallback {0}:\n{1}".format(
                 notifName,
                 FormatUtils.formatNamedTuple(notifParams)
             )
         )
     elif isinstance(self.apiDef,HartMgrDefinition.HartMgrDefinition):
         # HartMgrSubscriber generates a dictionary
         log.debug(
             "notifClient._dataCallback {0}:\n{1}".format(
                 notifName,
                 FormatUtils.formatDictionnary(notifParams)
             )
         )
     else:
         output = "apiDef of type {0} unexpected".format(type(self.apiDef))
         log.critical(output)
         print output
         raise SystemError(output)
     
     # record current time
     timeNow = time.time()
     
     # read MAC address from notification
     mac = self._getMacFromNotifParams(notifParams)
     
     # lock the data structure
     self.dataLock.acquire()
     
     # add mac/type to data, if necessary
     if mac not in self.data:
         self.data[mac] = {}
     if notifName not in self.data[mac]:
         self.data[mac][notifName] = 0
         
     # add mac/type to updates, if necessary
     if mac not in self.updates:
         self.updates[mac] = []
     if notifName not in self.updates[mac]:
         self.updates[mac].append(notifName)
     
     # increment counter
     self.data[mac][notifName] += 1
     
     # unlock the data structure
     self.dataLock.release()
     
     # transform HART OAP notification into equivalent IP version
     if isinstance(self.apiDef,HartMgrDefinition.HartMgrDefinition):
         # we are connected to a HART manager
         
         if (notifName in ['data']) and (len(notifParams['payload'])>2):
             notifName = IpMgrSubscribe.IpMgrSubscribe.NOTIFDATA
             
             notifParams  = IpMgrConnectorMux.IpMgrConnectorMux.Tuple_notifData(
                 utcSecs       = int(notifParams['time']/1000),
                 utcUsecs      = (notifParams['time']%1000)*1000,
                 macAddress    = mac,
                 srcPort       = OAPMessage.OAP_PORT,
                 dstPort       = OAPMessage.OAP_PORT,
                 data          = tuple(notifParams['payload'][2:]),
             )
     
     # parse OAP packet
     if notifName in [IpMgrSubscribe.IpMgrSubscribe.NOTIFDATA]:
         try:
             self.oap_dispatch.dispatch_pkt(notifName, notifParams)
         except Exception as ex:
             traceback.print_exc()
Exemplo n.º 8
0
 def _dataCallback(self, notifName, notifParams):
     
     # log
     if   isinstance(self.apiDef,IpMgrDefinition.IpMgrDefinition):
         # IpMgrSubscribe generates a named tuple
         log.debug(
             "notifClient._dataCallback {0}:\n{1}".format(
                 notifName,
                 FormatUtils.formatNamedTuple(notifParams)
             )
         )
     elif isinstance(self.apiDef,HartMgrDefinition.HartMgrDefinition):
         # HartMgrSubscriber generates a dictionary
         log.debug(
             "notifClient._dataCallback {0}:\n{1}".format(
                 notifName,
                 FormatUtils.formatDictionnary(notifParams)
             )
         )
     else:
         output = "apiDef of type {0} unexpected".format(type(self.apiDef))
         log.critical(output)
         print output
         raise SystemError(output)
     
     # record current time
     timeNow = time.time()
     
     # read MAC address from notification
     mac = self._getMacFromNotifParams(notifParams)
     
     # lock the data structure
     self.dataLock.acquire()
     
     # add mac/type to data, if necessary
     if mac not in self.data:
         self.data[mac] = {}
     if notifName not in self.data[mac]:
         self.data[mac][notifName] = 0
         
     # add mac/type to updates, if necessary
     if mac not in self.updates:
         self.updates[mac] = []
     if notifName not in self.updates[mac]:
         self.updates[mac].append(notifName)
     
     # increment counter
     self.data[mac][notifName] += 1
     
     # transform HART OAP notification into equivalent IP version
     if isinstance(self.apiDef,HartMgrDefinition.HartMgrDefinition):
         # we are connected to a HART manager
         
         if (notifName in ['data']) and (len(notifParams['payload'])>2):
             notifName = IpMgrSubscribe.IpMgrSubscribe.NOTIFDATA
             
             notifParams = IpMgrConnectorMux.IpMgrConnectorMux.Tuple_notifData(
                 utcSecs       = int(notifParams['time']/1000),
                 utcUsecs      = (notifParams['time']%1000)*1000,
                 macAddress    = mac,
                 srcPort       = OAPMessage.OAP_PORT,
                 dstPort       = OAPMessage.OAP_PORT,
                 data          = tuple(notifParams['payload'][2:]),
             )
     
     # calculate latency
     try:
         if notifName in [IpMgrSubscribe.IpMgrSubscribe.NOTIFDATA,
                          IpMgrSubscribe.IpMgrSubscribe.NOTIFIPDATA,]:
             try:
                 latency = self.latencyCalculator.getLatency(
                         float(notifParams.utcSecs)+(float(notifParams.utcUsecs)/1000000.0),
                         timeNow)
                 # lat. current
                 if COL_LAT_CUR not in self.data[mac]:
                     self.data[mac][COL_LAT_CUR] = '-'
                 if COL_LAT_CUR not in self.updates[mac]:
                     self.updates[mac].append(COL_LAT_CUR)
                 self.data[mac][COL_LAT_CUR] = latency
                 # lat. min
                 if (
                     (
                        (COL_LAT_MIN in self.data[mac])
                        and
                        (latency<self.data[mac][COL_LAT_MIN])
                     )
                     or
                     (
                        (COL_LAT_MIN not in self.data[mac])
                     )
                     or
                     (
                        (COL_LAT_MIN in self.data[mac])
                        and
                        (self.data[mac][COL_LAT_MIN]=='-')
                     )
                    ):
                     if COL_LAT_MIN not in self.data[mac]:
                         self.data[mac][COL_LAT_MIN] = '-'
                     if COL_LAT_MIN not in self.updates[mac]:
                         self.updates[mac].append(COL_LAT_MIN)
                     self.data[mac][COL_LAT_MIN] = latency
                 # max
                 if (
                     (
                        (COL_LAT_MAX in self.data[mac])
                        and
                        (latency>self.data[mac][COL_LAT_MAX])
                     )
                     or
                     (
                        (COL_LAT_MAX not in self.data[mac])
                     )
                     or
                     (
                        (COL_LAT_MAX in self.data[mac])
                        and
                        (self.data[mac][COL_LAT_MAX]=='-')
                     )
                    ):
                     if COL_LAT_MAX not in self.data[mac]:
                         self.data[mac][COL_LAT_MAX] = '-'
                     if COL_LAT_MAX not in self.updates[mac]:
                         self.updates[mac].append(COL_LAT_MAX)
                     self.data[mac][COL_LAT_MAX] = latency
             except RuntimeError:
                 # can happen if latency calculator hasn't acquired lock yet
                 pass
     except Exception as err:
         print err
     
     # unlock the data structure
     self.dataLock.release()
     
     # parse OAP packet
     if notifName in [IpMgrSubscribe.IpMgrSubscribe.NOTIFDATA]:
         self.oap_dispatch.dispatch_pkt(notifName, notifParams)