Exemplo n.º 1
0
    def do_whois(self, args):
        """whois [ <addr>] [ <lolimit> <hilimit> ]"""
        args = args.split()
        if _debug: WhoIsIAmConsoleCmd._debug("do_whois %r", args)

        try:
            # build a request
            request = WhoIsRequest()
            if (len(args) == 1) or (len(args) == 3):
                request.pduDestination = Address(args[0])
                del args[0]
            else:
                request.pduDestination = GlobalBroadcast()

            if len(args) == 2:
                request.deviceInstanceRangeLowLimit = int(args[0])
                request.deviceInstanceRangeHighLimit = int(args[1])
            if _debug: WhoIsIAmConsoleCmd._debug("    - request: %r", request)

            # make an IOCB
            iocb = IOCB(request)
            if _debug: WhoIsIAmConsoleCmd._debug("    - iocb: %r", iocb)

            # give it to the application
            this_application.request_io(iocb)

        except Exception as err:
            WhoIsIAmConsoleCmd._exception("exception: %r", err)
Exemplo n.º 2
0
    def do_whois(self, args):
        """whois [ <addr>] [ <lolimit> <hilimit> ]"""
        args = args.split()
        if _debug: WhoIsIAmConsoleCmd._debug("do_whois %r", args)

        try:
            # build a request
            request = WhoIsRequest()
            if (len(args) == 1) or (len(args) == 3):
                request.pduDestination = Address(args[0])
                del args[0]
            else:
                request.pduDestination = GlobalBroadcast()

            if len(args) == 2:
                request.deviceInstanceRangeLowLimit = int(args[0])
                request.deviceInstanceRangeHighLimit = int(args[1])
            if _debug: WhoIsIAmConsoleCmd._debug("    - request: %r", request)

            # make an IOCB
            iocb = IOCB(request)
            if _debug: WriteSomethingConsoleCmd._debug("    - iocb: %r", iocb)

            # give it to the application
            this_application.request_io(iocb)

        except Exception as err:
            WhoIsIAmConsoleCmd._exception("exception: %r", err)
Exemplo n.º 3
0
    def do_whois(self, addr=None, lolimit=None, hilimit=None):
        """whois [ <addr>] [ <lolimit> <hilimit> ]"""

        try:
            # build a request
            request = WhoIsRequest()
            if (addr is None):
                request.pduDestination = GlobalBroadcast()
            else:
                request.pduDestination = Address(addr)

            if lolimit is not None:
                request.deviceInstanceRangeLowLimit = int(lolimit)
            if hilimit is not None:
                request.deviceInstanceRangeHighLimit = int(hilimit)
            if _debug: logger.debug("    - request: %r", request)

            # make an IOCB
            iocb = IOCB(request)
            if _debug: logger.debug("    - iocb: %r", iocb)

            # give it to the application
            self.request_io(iocb)

        except Exception as err:
            logger.debug("exception: %r", err)
Exemplo n.º 4
0
    def do_whois(self, args):
        if _debug: ThreadedHTTPRequestHandler._debug("do_whois %r", args)

        try:
            # build a request
            request = WhoIsRequest()
            if (len(args) == 1) or (len(args) == 3):
                request.pduDestination = Address(args[0])
                del args[0]
            else:
                request.pduDestination = GlobalBroadcast()

            if len(args) == 2:
                request.deviceInstanceRangeLowLimit = int(args[0])
                request.deviceInstanceRangeHighLimit = int(args[1])
            if _debug: ThreadedHTTPRequestHandler._debug("    - request: %r", request)

            # make an IOCB
            iocb = IOCB(request)
            if _debug: ThreadedHTTPRequestHandler._debug("    - iocb: %r", iocb)

            # give it to the application
            this_application.request_io(iocb)

            # no result -- it would be nice if these were the matching I-Am's
            result = {}

        except Exception as err:
            ThreadedHTTPRequestHandler._exception("exception: %r", err)
            result = { "exception": str(err) }

        # write the result
        json.dump(result, self.wfile)
Exemplo n.º 5
0
def whois_request(args, console=None):
    """
    This function creates a whois request.

    Usage: whois [ <address> ] [ <lowlimit> <highlimit> ]

    :param args: list of parameters
    :param console: console object
    :return: request
    """

    # create request
    request = WhoIsRequest()

    # check if address was set
    if len(args) in (1, 3):
        request.pduDestination = Address(args[0])
        del args[0]

    # send broadcast otherwise
    else:
        request.pduDestination = GlobalBroadcast()

    # check if limits were set
    if len(args) == 2:
        request.deviceInstanceRangeLowLimit = int(args[0])
        request.deviceInstanceRangeHighLimit = int(args[0])

    # return created request
    return request
Exemplo n.º 6
0
    def do_whois(self, args):
        """whois [ <addr> ] [ <lolimit> <hilimit> ]"""
        args = args.split()
        if _debug: TestConsoleCmd._debug("do_whois %r", args)

        try:
            # build a request
            request = WhoIsRequest()
            if (len(args) == 1) or (len(args) == 3):
                request.pduDestination = Address(args[0])
                del args[0]
            else:
                request.pduDestination = GlobalBroadcast()

            if len(args) == 2:
                loLimit = int(args[0])
                hiLimit = int(args[1])

                request.deviceInstanceRangeLowLimit = int(args[0])
                request.deviceInstanceRangeHighLimit = int(args[1])
            if _debug: TestConsoleCmd._debug("    - request: %r", request)
        
            # give it to the application
            this_application.Request(request)

        except Exception, e:
            TestConsoleCmd._exception("exception: %r", e)
Exemplo n.º 7
0
    def whois(self, *args, global_broadcast=False):
        """
        Build a WhoIs request

        :param args: string built as [ <addr>] [ <lolimit> <hilimit> ] **optional**
        :returns: discoveredDevices as a defaultdict(int)

        Example::

            whois(global_broadcast=True) # WhoIs broadcast globally.  Every device will respond with an IAm
            whois('2:5')                 # WhoIs looking for the device at (Network 2, Address 5)
            whois('10 1000')             # WhoIs looking for devices in the ID range (10 - 1000)

        """
        if not self._started:
            raise ApplicationNotStarted(
                "BACnet stack not running - use startApp()")

        if args:
            args = args[0].split()
        msg = args if args else "any"

        self._log.debug("do_whois {!r}".format(msg))

        # build a request
        request = WhoIsRequest()
        if (len(args) == 1) or (len(args) == 3):
            request.pduDestination = Address(args[0])
            del args[0]
        else:
            if global_broadcast:
                request.pduDestination = GlobalBroadcast()
            else:
                request.pduDestination = LocalBroadcast()

        if len(args) == 2:
            try:
                request.deviceInstanceRangeLowLimit = int(args[0])
                request.deviceInstanceRangeHighLimit = int(args[1])
            except ValueError:
                pass
        self._log.debug("{:>12} {}".format("- request:", request))

        iocb = IOCB(request)  # make an IOCB
        self.this_application._last_i_am_received = []
        # pass to the BACnet stack
        deferred(self.this_application.request_io, iocb)

        iocb.wait()  # Wait for BACnet response

        if iocb.ioResponse:  # successful response
            apdu = iocb.ioResponse

        if iocb.ioError:  # unsuccessful: error/reject/abort
            pass

        time.sleep(3)
        self.discoveredDevices = self.this_application.i_am_counter
        return self.this_application._last_i_am_received
Exemplo n.º 8
0
    def whois(self, *args):
        """
        Build a WhoIs request

        :param args: string built as [ <addr>] [ <lolimit> <hilimit> ] **optional**
        :returns: discoveredDevices as a defaultdict(int)

        Example::

            whois()             # WhoIs broadcast globally.  Every device will respond with an IAm
            whois('2:5')        # WhoIs looking for the device at (Network 2, Address 5)
            whois('10 1000')    # WhoIs looking for devices in the ID range (10 - 1000) 

        """
        if not self._started:
            raise ApplicationNotStarted("BACnet stack not running - use startApp()")

        if args:
            args = args[0].split()
        msg = args if args else "any"

        self._log.debug("do_whois {!r}".format(msg))

        # build a request
        request = WhoIsRequest()
        if (len(args) == 1) or (len(args) == 3):
            request.pduDestination = Address(args[0])
            del args[0]
        else:
            request.pduDestination = GlobalBroadcast()

        if len(args) == 2:
            request.deviceInstanceRangeLowLimit = int(args[0])
            request.deviceInstanceRangeHighLimit = int(args[1])
        self._log.debug("{:>12} {}".format("- request:", request))

        iocb = IOCB(request)  # make an IOCB

        # pass to the BACnet stack
        self.this_application.request_io(iocb)

        iocb.wait()  # Wait for BACnet response

        if iocb.ioResponse:  # successful response
            apdu = iocb.ioResponse

        if iocb.ioError:  # unsuccessful: error/reject/abort
            pass

        self.discoveredDevices = self.this_application.i_am_counter
        return self.discoveredDevices
Exemplo n.º 9
0
    def whois(self, *args):
        """
        Creation of a whois requests
        Requets is given to the app

        :param args: string built as [ <addr>] [ <lolimit> <hilimit> ] **optional**
        :returns: discoveredDevices as a defaultdict(int)

        Example::

            whois()
            #will create a broadcast whois request and every device will response by a Iam
            whois('2:5')
            #will create a whois request aimed at device 5
            whois('10 1000')
            #will create a whois request looking for device ID 10 to 1000

        """
        if args:
            args = args[0].split()

        if not args:
            msg = "any"
        else:
            msg = args

        log_debug("do_whois %r" % msg)

        try:
            # build a request
            request = WhoIsRequest()
            if (len(args) == 1) or (len(args) == 3):
                request.pduDestination = Address(args[0])
                del args[0]
            else:
                request.pduDestination = GlobalBroadcast()

            if len(args) == 2:
                request.deviceInstanceRangeLowLimit = int(args[0])
                request.deviceInstanceRangeHighLimit = int(args[1])
            log_debug("    - request: %r" % request)

            # give it to the application
            self.this_application.request(request)

        except Exception as error:
            log_exception("exception: %r" % error)

        self.discoveredDevices = self.this_application.i_am_counter

        return self.discoveredDevices
Exemplo n.º 10
0
def get_iam(app, device_id, target_address = None):
    request = WhoIsRequest()
    
    request.deviceInstanceRangeLowLimit = device_id
    request.deviceInstanceRangeHighLimit = device_id
    
    if target_address is not None:
        request.pduDestination = Address(target_address)
    else:
        request.pduDestination = GlobalBroadcast()
        
    result = app.make_request(request, expected_device_id=device_id)
    
    return result
Exemplo n.º 11
0
def get_iam(app, device_id, target_address = None):
    request = WhoIsRequest()
    
    request.deviceInstanceRangeLowLimit = device_id
    request.deviceInstanceRangeHighLimit = device_id
    
    if target_address is not None:
        request.pduDestination = Address(target_address)
    else:
        request.pduDestination = GlobalBroadcast()
        
    result = app.make_request(request, expected_device_id=device_id)
    
    return result
Exemplo n.º 12
0
    def get_device(self, address):
        """
        This function returns device identifier if known.

        :param address: device address
        :return: device identifier
        """

        # check if address is known
        if not 'id' in self.known_devices.get(address, {}):
            # create request
            request = WhoIsRequest()

            # set destination to address
            request.pduDestination = Address(address)

            self._debug('   - request: %s', request)

            # queue request
            self.requests.put(request)

            # exit
            return

        # get device
        device = self.known_devices[address]

        # return device
        return device['id']
Exemplo n.º 13
0
def broadcast():

    try:
        device_list = list()
        localaddress = list()
        ips = getIPs()
        print "found local ip as ", ips
        for ip in ips:
            str(ip)
            localaddress = ip + "/24"

        # make a device object
        this_device = LocalDeviceObject(
            objectName="BEMOSS",
            objectIdentifier=
            599,  #change if there exists a bacnet device with same identifier
            maxApduLengthAccepted=1024,
            segmentationSupported="segmentedBoth",
            vendorIdentifier=99,
        )

        # Device application
        this_application = Application(this_device, localaddress)

        request = WhoIsRequest()
        request.pduDestination = GlobalBroadcast()

        def time_out():
            time.sleep(5)
            stop()

        thread = threading.Thread(target=time_out)
        thread.start()

        this_application.request(request)
        this_application.found_address = list()
        this_application.found_deviceidentifier = list()
        run()
        #time.sleep(10)
        this_application.release = True
        this_application.update = False
        address, deviceidentifier = this_application.updator()

        todelete = list()
        for i in range(0, len(deviceidentifier)):
            if deviceidentifier[i] == 0:
                todelete.append(i)
        for i in todelete:
            del address[i], deviceidentifier[
                i]  #Deleting identified bacnet router
        Remote_address = list(set(address))  #Removing repeatition
        Identifier = list(set(deviceidentifier))  #Removing repeatition

        print "destination address list is ", Remote_address
        print "object instance of that address", Identifier

        return this_application, Remote_address, Identifier
    except Exception, e:
        _log.exception("an error has occurred: %s", e)
        return None
Exemplo n.º 14
0
 def ping_device(self, target_address):
     """Ping a device with a whois to potentially setup routing."""
     request = WhoIsRequest()
     request.pduDestination = Address(target_address)
     
     iocb = IOCB(request, self.async_call)
     self.this_application.submit_request(iocb)
Exemplo n.º 15
0
        def ping_device(self, target_address):
            """Ping a device with a whois to potentially setup routing."""
            request = WhoIsRequest()
            request.pduDestination = Address(target_address)

            iocb = IOCB(request, self.async_call)
            self.this_application.submit_request(iocb)
Exemplo n.º 16
0
    def who_is(self, low_device_id=None, high_device_id=None, target_address=None):
        _log.debug("Sending WhoIs: low_id: {low} high: {high} address: {address}".format(
            low=low_device_id, high=high_device_id, address=target_address))
        request = WhoIsRequest()

        if low_device_id is not None:
            request.deviceInstanceRangeLowLimit = low_device_id
        if high_device_id is not None:
            request.deviceInstanceRangeHighLimit = high_device_id

        if target_address is not None:
            request.pduDestination = Address(target_address)
        else:
            request.pduDestination = GlobalBroadcast()

        iocb = self.iocb_class(request)
        self.bacnet_application.submit_request(iocb)
Exemplo n.º 17
0
    def whois(self, *args):
        """
        Creation of a whois requests
        Requets is given to the app
        
        :param args: string built as [ <addr>] [ <lolimit> <hilimit> ] **optional**  
        :returns: discoveredDevices as a defaultdict(int)
        
        Example::
            
            whois() 
            #will create a broadcast whois request and every device will response by a Iam
            whois('2:5') 
            #will create a whois request aimed at device 5
            whois('10 1000')
            #will create a whois request looking for device ID 10 to 1000
            
        """
        if args:        
            args = args[0].split()
        if _debug: WhoisIAm._debug("do_whois %r" % args)

        try:
            # build a request
            request = WhoIsRequest()
            if (len(args) == 1) or (len(args) == 3):
                request.pduDestination = Address(args[0])
                del args[0]
            else:
                request.pduDestination = GlobalBroadcast()

            if len(args) == 2:
                request.deviceInstanceRangeLowLimit = int(args[0])
                request.deviceInstanceRangeHighLimit = int(args[1])
            if _debug: WhoisIAm._debug("    - request: %r" % request)

            # give it to the application
            self.this_application.request(request)

        except Exception as e:
            WhoisIAm._exception("exception: %r" % e)

        self.discoveredDevices = self.this_application.i_am_counter
      
        return self.discoveredDevices
Exemplo n.º 18
0
 def ping_target(self, address):    
     #Some devices (mostly RemoteStation addresses behind routers) will not be reachable without 
     # first establishing the route to the device. Sending a directed WhoIsRequest is will
     # settle that for us when the response comes back. 
     request = WhoIsRequest()
     request.pduDestination = address
     
     iocb = IOCB(request)
     this_application.submit_request(iocb)
Exemplo n.º 19
0
 def ping_device(self, target_address, device_id):
     """Ping a device with a whois to potentially setup routing."""
     _log.debug("Pinging " + target_address)
     request = WhoIsRequest()
     request.deviceInstanceRangeLowLimit = device_id
     request.deviceInstanceRangeHighLimit = device_id
     request.pduDestination = GlobalBroadcast()
     iocb = IOCB(request, self.async_call)
     self.this_application.submit_request(iocb)
Exemplo n.º 20
0
    def ping_target(self, address):
        #Some devices (mostly RemoteStation addresses behind routers) will not be reachable without
        # first establishing the route to the device. Sending a directed WhoIsRequest is will
        # settle that for us when the response comes back.
        request = WhoIsRequest()
        request.pduDestination = address

        iocb = IOCB(request)
        this_application.submit_request(iocb)
Exemplo n.º 21
0
    def who_is(self, low_device_id=None, high_device_id=None, target_address=None):
        _log.debug("Sending WhoIs: low_id: {low} high: {high} address: {address}".format(low=low_device_id,
                                                                                         high=high_device_id,
                                                                                         address=target_address))
        request = WhoIsRequest()

        if low_device_id is not None:
            request.deviceInstanceRangeLowLimit = low_device_id
        if high_device_id is not None:
            request.deviceInstanceRangeHighLimit = high_device_id

        if target_address is not None:
            request.pduDestination = Address(target_address)
        else:
            request.pduDestination = GlobalBroadcast()

        iocb = self.iocb_class(request)
        self.this_application.submit_request(iocb)
    def do_whois(self, device=None):
        try:
            device = {} if device is None else device
            request = WhoIsRequest()
            address = device.get("address")
            low_limit = device.get("idLowLimit")
            high_limit = device.get("idHighLimit")
            if address is not None:
                request.pduDestination = Address(address)
            else:
                request.pduDestination = GlobalBroadcast()
            if low_limit is not None and high_limit is not None:
                request.deviceInstanceRangeLowLimit = int(low_limit)
                request.deviceInstanceRangeHighLimit = int(high_limit)
            iocb = IOCB(request)
            deferred(self.request_io, iocb)

        except Exception as e:
            log.exception(e)
Exemplo n.º 23
0
    def do_whois(self, address=None, lowlimit=None, highlimit=None):
        """whois [ <addr>] [ <lolimit> <hilimit> ]"""

        if _debug: self._debug("do_whois %r", (address, lowlimit, highlimit))

        try:
            # build a request
            request = WhoIsRequest()
            if address != None:
                request.pduDestination = Address(address)
            else:
                request.pduDestination = GlobalBroadcast()

            if address == None and isinstance(lowlimit, int) and isinstance(
                    highlimit(int)):
                request.deviceInstanceRangeLowLimit = int(lowlimit)
                request.deviceInstanceRangeHighLimit = int(highlimit)
            if _debug: self._debug("    - request: %r", request)

            # make an IOCB
            iocb = IOCB(request)
            if _debug: self._debug("    - iocb: %r", iocb)

            # give it to the application
            self.request_io(iocb)

            # build a key from the source and parameters
            key = (
                str(request.pduSource),
                request.deviceInstanceRangeLowLimit,
                request.deviceInstanceRangeHighLimit,
            )
            try:
                self.whois_counter[key] += 1
            except KeyError:
                self.whois_counter[key] = 1

        except Exception as err:
            self._exception("exception: %r", err)
Exemplo n.º 24
0
    def do_whois(self, args):
        """whois [ <addr>] [ <lolimit> <hilimit> ]"""
        args = args.split()
        if _debug: BacnetConsoleCmd._debug("do_whois %r", args)

        try:
            # build a request
            request = WhoIsRequest()
            if (len(args) == 1) or (len(args) == 3):
                request.pduDestination = Address(args[0])
                del args[0]
            else:
                request.pduDestination = GlobalBroadcast()

            if len(args) == 2:
                request.deviceInstanceRangeLowLimit = int(args[0])
                request.deviceInstanceRangeHighLimit = int(args[1])
            if _debug: BacnetConsoleCmd._debug("    - request: %r", request)

            # give it to the application
            thisApplication.request(request)

        except Exception, e:
            BacnetConsoleCmd._exception("exception: %r", e)
Exemplo n.º 25
0
    def do_whois(self, args):
        """
        whois [ <addr> ] [ <lolimit> <hilimit> ]

        Send a Who-Is Request and wait 3 seconds for the I-Am "responses" to
        be returned.
        """
        args = args.split()
        if _debug: DiscoverConsoleCmd._debug("do_whois %r", args)

        try:
            # build a request
            request = WhoIsRequest()
            if (len(args) == 1) or (len(args) == 3):
                request.pduDestination = Address(args[0])
                del args[0]
            else:
                request.pduDestination = GlobalBroadcast()

            if len(args) == 2:
                request.deviceInstanceRangeLowLimit = int(args[0])
                request.deviceInstanceRangeHighLimit = int(args[1])
            if _debug: DiscoverConsoleCmd._debug("    - request: %r", request)

            # make an IOCB
            iocb = IOCB(request)
            if _debug: DiscoverConsoleCmd._debug("    - iocb: %r", iocb)

            # give it to the application
            deferred(this_application.request_io, iocb)

            # sleep for responses
            time.sleep(3.0)

        except Exception as err:
            DiscoverConsoleCmd._exception("exception: %r", err)
Exemplo n.º 26
0
    def discover_devices(self, timeout=5):
        """ Send a WhoIsRequest and wait for timeout seconds to receive all responses.  """
        self.devices = {}
        req = WhoIsRequest(
        )  # How does this know it needs to store at devices?
        req.pduDestination = Address(
            "255.255.255.255")  # Global Broadcast address

        iocb = IOCB(req)
        self.request_io(iocb)
        iocb.set_timeout(5)
        iocb.wait()
        time.sleep(
            timeout)  # wait for 5 seconds so all the responses are received.

        self.update_device_metadata(self.devices)
        return self.devices
Exemplo n.º 27
0
    def broadcast(self,sender,topic,message):
        try:

            return_pipe = self.extract_pipe(message["reduced_return_pipe"])
            request = WhoIsRequest()
            request.pduDestination = GlobalBroadcast()
            self.this_application.request(request)
            self.this_application.release = True
            self.this_application.update = False
            addresslist = self.this_application.found_address
            addresslist=list(set(addresslist))
            #self.bemoss_publish(target=sender,topic='broadcast_response',message=addresslist)
            print "Printing address"
            print addresslist
            return_pipe.send(addresslist)

        except Exception as e:
            _log.exception("an error has occurred during bacnet discovery: %s", e)
            return []
Exemplo n.º 28
0
    def setup_device(self,
                     address,
                     max_apdu_len=1024,
                     seg_supported='segmentedBoth',
                     obj_id=599,
                     obj_name='sMap BACnet driver',
                     ven_id=15):

        _log.info('seg_supported ' + str(seg_supported))
        _log.info('max_apdu_len ' + str(max_apdu_len))
        _log.info('obj_id ' + str(obj_id))
        _log.info('obj_name ' + str(obj_name))
        _log.info('ven_id ' + str(ven_id))

        # Check to see if they gave a valid apdu length.
        if encode_max_apdu_response(max_apdu_len) is None:
            raise ValueError(
                'Invalid max_apdu_len: {} Valid options are 50, 128, 206, 480, 1024, and 1476'
                .format(max_apdu_len))

        this_device = LocalDeviceObject(
            objectName=obj_name,
            objectIdentifier=obj_id,
            maxApduLengthAccepted=max_apdu_len,
            segmentationSupported=seg_supported,
            vendorIdentifier=ven_id,
        )

        # build a bit string that knows about the bit names and leave it empty. We respond to NOTHING.
        pss = ServicesSupported()

        # set the property value to be just the bits
        this_device.protocolServicesSupported = pss.value

        self.this_application = BACnet_application(this_device, address)

        server_thread = threading.Thread(target=bacpypes.core.run)

        # exit the BACnet App thread when the main thread terminates
        server_thread.daemon = True
        request = WhoIsRequest()
        request.pduDestination = GlobalBroadcast()
        server_thread.start()
Exemplo n.º 29
0
    def broadcast(self):

        try:

            request = WhoIsRequest()
            request.pduDestination = GlobalBroadcast()
            self.this_application.request(request)
            thread = threading.Thread(target=10)
            self.this_application.request(request)
            self.this_application.release = True
            self.this_application.update = False
            addresslist = self.this_application.found_address
            addresslist = list(set(addresslist))
            return addresslist

        except Exception as e:
            _log.exception("an error has occurred during bacnet discovery: %s",
                           e)
            return []
    def ping(self) -> None:
        try:
            # build a request
            request = WhoIsRequest() 
            # ping all devices on network
            request.pduDestination = GlobalBroadcast() 
            # make an IOCB (input output callback)
            iocb = IOCB(request)
            self.app.request_io(iocb)
            self.logger.debug("ping: waiting for responses...")
            loopCount = 0
            while loopCount < 20 and not iocb.ioResponse:
                loopCount += 1
                run_once()
                asyncore.loop(timeout=0.2, count=1)
                time.sleep(0.2)
                self.logger.debug(f"ping: loopy {loopCount}")
            stop()

            # handle responses
            if iocb.ioResponse:
                self.logger.debug(f"ping: iocb response success!")
                apdu = iocb.ioResponse
                if not isinstance(apdu, IAmRequest):
                    self.logger.error(f"ping: Not an IAmRequest")
                    return
                device_type, device_instance = apdu.iAmDeviceIdentifier
                if device_type != 'device':
                    raise DecodingError("ping: invalid object type")
                self.logger.info(f"ping: pduSource={repr(apdu.pduSource)}")
                self.logger.info(f"ping: deviceId={str(apdu.iAmDeviceIdentifier)}")

            # do something for error/reject/abort
            if iocb.ioError:
                self.logger.error(f"ping: {str(iocb.ioError)}")

        except Exception as err:
            exc_type, exc_value, exc_traceback = sys.exc_info()
            traceback.print_tb(exc_traceback, file=sys.stdout)
            self.logger.critical(f"ping: {err}")
Exemplo n.º 31
0
    def whois(self, *args):
        """
        Build a WhoIs request

        :param args: string built as [ <addr>] [ <lolimit> <hilimit> ] **optional**
        :returns: discoveredDevices as a defaultdict(int)

        Example::

            whois()             # WhoIs broadcast globally.  Every device will respond with an IAm
            whois('2:5')        # WhoIs looking for the device at (Network 2, Address 5)
            whois('10 1000')    # WhoIs looking for devices in the ID range (10 - 1000) 

        """
        if not self._started:
            raise ApplicationNotStarted('BACnet stack not running - use startApp()')

        if args:
            args = args[0].split()
        msg = args if args else 'any'

        log_debug(WhoisIAm, "do_whois %r" % msg)


        # build a request
        request = WhoIsRequest()
        if (len(args) == 1) or (len(args) == 3):
            request.pduDestination = Address(args[0])
            del args[0]
        else:
            request.pduDestination = GlobalBroadcast()

        if len(args) == 2:
            request.deviceInstanceRangeLowLimit = int(args[0])
            request.deviceInstanceRangeHighLimit = int(args[1])
        log_debug(WhoisIAm, "    - request: %r" % request)


        iocb = IOCB(request)                            # make an IOCB

        self.this_application.request_io(iocb)          # pass to the BACnet stack

        iocb.wait()             # Wait for BACnet response

        if iocb.ioResponse:     # successful response
            apdu = iocb.ioResponse
#            # should be an ack
#            if not isinstance(apdu, IAmRequest) and not isinstance(apdu, WhoIsRequest):
#                log_debug(WhoisIAm,"    - not an ack")
#                return
#            # find the datatype
#            datatype = get_datatype(apdu.objectIdentifier[0], apdu.propertyIdentifier)
#            log_debug(WhoisIAm,"    - datatype: %r", datatype)
#            if not datatype:
#                raise TypeError("unknown datatype")
#                
#            # special case for array parts, others are managed by cast_out
#            if issubclass(datatype, Array) and (apdu.propertyArrayIndex is not None):
#                if apdu.propertyArrayIndex == 0:
#                    value = apdu.propertyValue.cast_out(Unsigned)
#                else:
#                    value = apdu.propertyValue.cast_out(datatype.subtype)
#            else:
#                value = apdu.propertyValue.cast_out(datatype)
#            log_debug(WhoisIAm,"    - value: %r", value)
#                
#            if isinstance(apdu, IAmRequest):
#                # build a key from the source, just use the instance number
#                key = (str(apdu.pduSource),
#                       apdu.iAmDeviceIdentifier[1],)
#                # count the times this has been received
#                self.i_am_counter[key] += 1
#    
#            # Given an Who Is request, cache it.
#            if isinstance(apdu, WhoIsRequest):
#                # build a key from the source and parameters
#                key = (str(apdu.pduSource),
#                       apdu.deviceInstanceRangeLowLimit,
#                       apdu.deviceInstanceRangeHighLimit,
#                       )
#
#            # count the times this has been received
#            self.who_is_counter[key] += 1

        if iocb.ioError:        # unsuccessful: error/reject/abort
            pass

        self.discoveredDevices = self.this_application.i_am_counter
        return self.discoveredDevices
Exemplo n.º 32
0
    # build a bit string that knows about the bit names
    pss = ServicesSupported()
    pss['whoIs'] = 1
    pss['iAm'] = 1

    # set the property value to be just the bits
    this_device.protocolServicesSupported = pss.value

    # make a simple application
    this_application = WhoIsIAmApplication(this_device, args.ini.address)
    _log.debug("running")

    request = WhoIsRequest()

    if args.address is not None:
        request.pduDestination = Address(args.address)
    else:
        request.pduDestination = GlobalBroadcast()

    if args.range is not None:
        request.deviceInstanceRangeLowLimit = int(args.range[0])
        request.deviceInstanceRangeHighLimit = int(args.range[1])

    #set timeout timer
    def time_out():
        time.sleep(args.timeout)
        stop()

    thread = threading.Thread(target=time_out)
    thread.start() 
Exemplo n.º 33
0
        objectName=args.ini.objectname,
        objectIdentifier=int(args.ini.objectidentifier),
        maxApduLengthAccepted=int(args.ini.maxapdulengthaccepted),
        segmentationSupported=args.ini.segmentationsupported,
        vendorIdentifier=int(args.ini.vendoridentifier),
    )

    # make a simple application
    this_application = SynchronousApplication(this_device, args.ini.address)

    _log.debug("starting build")

    target_address = Address(args.address)

    request = WhoIsRequest()
    request.pduDestination = target_address
    result = this_application.make_request(request)

    if not isinstance(result, IAmRequest):
        result.debug_contents()
        raise TypeError, "Error making WhoIs request"

    device_type, device_instance = result.iAmDeviceIdentifier
    if device_type != 'device':
        raise DecodingError, "invalid object type"

    _log.debug('pduSource = ' + repr(result.pduSource))
    _log.debug('iAmDeviceIdentifier = ' + str(result.iAmDeviceIdentifier))
    _log.debug('maxAPDULengthAccepted = ' + str(result.maxAPDULengthAccepted))
    _log.debug('segmentationSupported = ' + str(result.segmentationSupported))
    _log.debug('vendorID = ' + str(result.vendorID))
Exemplo n.º 34
0
        objectIdentifier=int(args.ini.objectidentifier),
        maxApduLengthAccepted=int(args.ini.maxapdulengthaccepted),
        segmentationSupported=args.ini.segmentationsupported,
        vendorIdentifier=int(args.ini.vendoridentifier),
        )


    # make a simple application
    this_application = SynchronousApplication(this_device, args.ini.address)

    _log.debug("starting build")
    
    target_address = Address(args.address)
    
    request = WhoIsRequest()
    request.pduDestination = target_address
    result = this_application.make_request(request)
    
    if not isinstance(result, IAmRequest):
        result.debug_contents()
        raise TypeError("Error making WhoIs request")
        
    
    device_type, device_instance = result.iAmDeviceIdentifier
    if device_type != 'device':
        raise DecodingError("invalid object type")
    
    _log.debug('pduSource = ' + repr(result.pduSource))
    _log.debug('iAmDeviceIdentifier = ' + str(result.iAmDeviceIdentifier))
    _log.debug('maxAPDULengthAccepted = ' + str(result.maxAPDULengthAccepted))
    _log.debug('segmentationSupported = ' + str(result.segmentationSupported))
Exemplo n.º 35
0
    def do_whois(self, args):

        NOT_IMPLEMENTED = True
        if NOT_IMPLEMENTED:
            self.send_header('Content-Type', 'text/plain')
            self.end_headers()
            self.wfile.write(NotImplementedError('WhoIs not implemented'))
            return

        if _debug:
            HTTPRequestHandler._debug("do_whois %r", args)

        try:
            # build a request
            request = WhoIsRequest()
            if (len(args) == 1) or (len(args) == 3):
                request.pduDestination = Address(args[0])
                del args[0]
            else:
                request.pduDestination = GlobalBroadcast()

            if len(args) == 2:
                request.deviceInstanceRangeLowLimit = int(args[0])
                request.deviceInstanceRangeHighLimit = int(args[1])
            if _debug:
                HTTPRequestHandler._debug("    - request: %r", request)

            # make an IOCB
            iocb = IOCB(request)
            timeout = int(self.headers.get('X-bacnet-timeout', 5))
            iocb.set_timeout(timeout, err=TimeoutError)
            if _debug:
                HTTPRequestHandler._debug("    - iocb: %r", iocb)

            # Give it to the application
            deferred(this_application.request_io, iocb)
            iocb.wait()

            if iocb.ioError:
                if _debug:
                    HTTPRequestHandler._debug("    - error: %r", iocb.ioError)
                result = {"error": str(iocb.ioError)}

            else:
                if _debug:
                    HTTPRequestHandler._debug(
                        "    - response: %r", iocb.ioResponse
                    )
                apdu = iocb.ioResponse

                # find the datatype
                datatype = get_datatype(
                    apdu.objectIdentifier[0], apdu.propertyIdentifier
                )
                if _debug:
                    HTTPRequestHandler._debug("    - datatype: %r", datatype)
                if not datatype:
                    raise TypeError("unknown datatype")

                # special case for array parts, others are managed by cast_out
                if issubclass(datatype, Array) and (
                    apdu.propertyArrayIndex is not None
                ):
                    if apdu.propertyArrayIndex == 0:
                        datatype = Unsigned
                    else:
                        datatype = datatype.subtype
                    if _debug:
                        HTTPRequestHandler._debug(
                            "    - datatype: %r", datatype
                        )

                # convert the value to a dict if possible
                value = apdu.propertyValue.cast_out(datatype)
                if hasattr(value, "dict_contents"):
                    value = value.dict_contents(as_class=OrderedDict)
                if _debug:
                    HTTPRequestHandler._debug("    - value: %r", value)

                result = {"value": value}

        except Exception as err:
            HTTPRequestHandler._exception("exception: %r", err)
            result = {"exception": str(err)}
            self.send_header('Content-Type', 'application/json')
            self.end_headers()
            result_bytes = json.dumps(result).encode("utf-8")
            self.wfile.write(result_bytes)
            return

        # encode the results as JSON, convert to bytes
        result_bytes = json.dumps(result).encode("utf-8")

        # write the result
        self.send_header('Content-Type', 'application/json')
        self.end_headers()
        self.wfile.write(result_bytes)
        return