def __init__(self, ini_file, overriding_port: int = None):
        self.args = ConfigArgumentParser().parse_args(["--ini", ini_file])
        #addr = Address(self.args.ini.address)
        #if overriding_port:
        #    addr.addrPort = overriding_port
        #print('Address: {0}'.format(addr.addrPort))
        if overriding_port:
            ip, port = self.args.ini['address'].split(':')
            self.args.ini['address'] = ip + ':' + str(overriding_port)
        self.this_device = LocalDeviceObject(ini=self.args.ini)
        BIPSimpleApplication.__init__(self, self.this_device,
                                      self.args.ini['address'])
        self.taskman = TaskManager()
        self.datatype_map = {
            'b': Boolean,
            'u': lambda x: Unsigned(int(x)),
            'i': lambda x: Integer(int(x)),
            'r': lambda x: Real(float(x)),
            'd': lambda x: Double(float(x)),
            'o': OctetString,
            'c': CharacterString,
            'bs': BitString,
            'date': Date,
            'time': Time,
            'id': ObjectIdentifier,
        }

        thread_handle = threading.Thread(target=self.run_thread)
        thread_handle.daemon = True
        thread_handle.start()
Esempio n. 2
0
def main():
    """
    Main function, called when run as an application.
    """
    global server_address

    # check the version
    if (sys.version_info[:2] != (2, 5)):
        sys.stderr.write("Python 2.5 only\n")
        sys.exit(1)

    # parse the command line arguments
    parser = ArgumentParser(description=__doc__)
    parser.add_argument(
        "host",
        nargs='?',
        help="address of host (default %r)" % (SERVER_HOST, ),
        default=SERVER_HOST,
    )
    parser.add_argument(
        "port",
        nargs='?',
        type=int,
        help="server port (default %r)" % (SERVER_PORT, ),
        default=SERVER_PORT,
    )
    args = parser.parse_args()

    if _debug: _log.debug("initialization")
    if _debug: _log.debug("    - args: %r", args)

    # extract the server address and port
    host = args.host
    port = args.port
    server_address = (host, port)
    if _debug: _log.debug("    - server_address: %r", server_address)

    # build the stack
    this_console = ConsoleClient()
    if _debug: _log.debug("    - this_console: %r", this_console)

    this_middle_man = MiddleMan()
    if _debug: _log.debug("    - this_middle_man: %r", this_middle_man)

    this_director = TCPClientDirector()
    if _debug: _log.debug("    - this_director: %r", this_director)

    bind(this_console, this_middle_man, this_director)
    bind(MiddleManASE(), this_director)

    # create a task manager for scheduled functions
    task_manager = TaskManager()
    if _debug: _log.debug("    - task_manager: %r", task_manager)

    # don't wait to connect
    this_director.connect(server_address)

    if _debug: _log.debug("running")

    run()
Esempio n. 3
0
    def __init__(
        self,
        bacpypes_inifile,
        brickbacnet_config,
        sqlite_db,
    ):
        self.logger = logging.getLogger('bacnet_discovery')
        self.logger.setLevel(logging.WARNING)
        config = configparser.ConfigParser()
        config.read(bacpypes_inifile)
        config = config["BACpypes"]
        self.address_mask = config["address"]  # TODO: What does this do?
        self.this_device = LocalDeviceObject(
            objectName=config["objectName"],
            objectIdentifier=int(config["objectIdentifier"]),
            maxApduLengthAccepted=int(config["maxApduLengthAccepted"]),
            segmentationSupported=config["segmentationSupported"],
            vendorIdentifier=int(config["vendorIdentifier"]),
            vendorName="brick-community",
        )
        self.sqlite_db = sqlite_db

        BIPSimpleApplication.__init__(self, self.this_device,
                                      config["address"])
        self.taskman = TaskManager()
        self.object_custom_fields = brickbacnet_config['object_custom_fields']
Esempio n. 4
0
    def __init__(self):
        if _debug: TimeMachine._debug("__init__")
        global time_machine

        # pass along initialization
        _TaskManager.__init__(self)

        # initialize the time
        self.current_time = None
        self.time_limit = None

        # a little error checking
        if time_machine:
            raise RuntimeError("time machine already created")

        # save a reference
        time_machine = self
Esempio n. 5
0
    def __init__(self):
        if _debug: TimeMachine._debug("__init__")
        global time_machine

        # pass along initialization
        _TaskManager.__init__(self)

        # initialize the time
        self.current_time = None
        self.time_limit = None

        # a little error checking
        if time_machine:
            raise RuntimeError("time machine already created")

        # save a reference
        time_machine = self
Esempio n. 6
0
def main():
    """
    Main function, called when run as an application.
    """
    global server_address

    # parse the command line arguments
    parser = ArgumentParser(description=__doc__)
    parser.add_argument(
        "host",
        nargs='?',
        help="address of host",
        default=default_server_host,
    )
    parser.add_argument(
        "port",
        nargs='?',
        type=int,
        help="server port",
        default=default_server_port,
    )
    args = parser.parse_args()

    if _debug: _log.debug("initialization")
    if _debug: _log.debug("    - args: %r", args)

    # extract the server address and port
    host = args.host
    port = args.port
    server_address = (host, port)
    if _debug: _log.debug("    - server_address: %r", server_address)

    # build the stack
    this_console = ConsoleClient()
    if _debug: _log.debug("    - this_console: %r", this_console)

    this_middle_man = MiddleMan()
    if _debug: _log.debug("    - this_middle_man: %r", this_middle_man)

    this_director = TCPClientDirector()
    if _debug: _log.debug("    - this_director: %r", this_director)

    bind(this_console, this_middle_man, this_director)
    bind(MiddleManASE(), this_director)

    # create a task manager for scheduled functions
    task_manager = TaskManager()
    if _debug: _log.debug("    - task_manager: %r", task_manager)

    # don't wait to connect
    this_director.connect(server_address)

    if _debug: _log.debug("running")

    run()
Esempio n. 7
0
    def ReadProperty(self, obj, arrayIndex=None):
        if _debug: ActiveCOVSubscriptions._debug("ReadProperty %s arrayIndex=%r", obj, arrayIndex)

        # get the current time from the task manager
        current_time = TaskManager().get_time()
        if _debug: ActiveCOVSubscriptions._debug("    - current_time: %r", current_time)

        # start with an empty sequence
        cov_subscriptions = SequenceOf(COVSubscription)()

        # the obj is a DeviceObject with a reference to the application
        for cov in obj._app.active_cov_subscriptions:
            # calculate time remaining
            if not cov.lifetime:
                time_remaining = 0
            else:
                time_remaining = int(cov.taskTime - current_time)

                # make sure it is at least one second
                if not time_remaining:
                    time_remaining = 1

            recipient_process = RecipientProcess(
                recipient=Recipient(
                    address=DeviceAddress(
                        networkNumber=cov.client_addr.addrNet or 0,
                        macAddress=cov.client_addr.addrAddr,
                        ),
                    ),
                processIdentifier=cov.proc_id,
                )

            cov_subscription = COVSubscription(
                recipient=recipient_process,
                monitoredPropertyReference=ObjectPropertyReference(
                    objectIdentifier=cov.obj_id,
                    propertyIdentifier=cov.obj_ref._monitored_property_reference,
                    ),
                issueConfirmedNotifications=cov.confirmed,
                timeRemaining=time_remaining,
                # covIncrement=???,
                )
            if _debug: ActiveCOVSubscriptions._debug("    - cov_subscription: %r", cov_subscription)

            # add the list
            cov_subscriptions.append(cov_subscription)

        return cov_subscriptions
    def __init__(self, 
                 logger: Logger, 
                 ini_file: str = None, 
                 config_file: str = None,
                 debug: bool = False
                 ) -> None:
        path = os.path.dirname(bnet_base.__file__)
        self.ini_file = path + '/' + ini_file
        self.config_file = path + '/' + config_file
        self.debug = debug
        self.logger = logger
        self.logger.debug(f"init: bacpypes with {self.ini_file}")

        cmd_line_args_simulated = []
        if self.debug:
            cmd_line_args_simulated.append("--debug")
            cmd_line_args_simulated.append(__name__)
        cmd_line_args_simulated.append("--ini")
        cmd_line_args_simulated.append(self.ini_file)
        self.args = ConfigArgumentParser().parse_args(cmd_line_args_simulated)

        # load our reliable config file that has ports, names, types, etc.
        self.bacnet_config = json.load(open(self.config_file, 'r'))
        self.logger.debug(f"loaded {self.bacnet_config.get('name')}")
        
        # make a device object
        self.device = LocalDeviceObject(ini=self.args.ini) 

        # Overwrite the IP address in the .ini file to match what this machine
        # is configured for (to work, it must be a static IP on the same
        # subnet as the reliable / bacnet devices: 192.168.1.XXX/24
        self.logger.debug(f"init: this host config IP {self.args.ini.address}")

        # make an application to get callbacks from bacpypes
        self.app = BIPSimpleApplication(self.device, self.args.ini.address)
        enable_sleeping() # backpypes core threads: must do since django is multi threaded
        self.taskman = TaskManager()
Esempio n. 9
0
    def resume_task(self, task):
        if _debug:
            TimeMachine._debug("resume_task @ %r: %r", self.current_time, task)

        _TaskManager.resume_task(self, task)
Esempio n. 10
0
    def resume_task(self, task):
        if _debug:
            TimeMachine._debug("resume_task %r", task)

        _TaskManager.resume_task(self, task)
Esempio n. 11
0
    def suspend_task(self, task):
        if _debug:
            TimeMachine._debug("suspend_task %r", task)

        _TaskManager.suspend_task(self, task)
Esempio n. 12
0
    def install_task(self, task):
        if _debug:
            TimeMachine._debug("install_task %r @ %r", task, task.taskTime)

        _TaskManager.install_task(self, task)
Esempio n. 13
0
    def process_task(self, task):
        if _debug:
            TimeMachine._debug("process_task %r", task)

        _TaskManager.process_task(self, task)
Esempio n. 14
0
    def resume_task(self, task):
        if _debug: TimeMachine._debug("resume_task %r", task)

        _TaskManager.resume_task(self, task)
Esempio n. 15
0
    def suspend_task(self, task):
        if _debug: TimeMachine._debug("suspend_task %r", task)

        _TaskManager.suspend_task(self, task)
Esempio n. 16
0
    def install_task(self, task):
        if _debug:
            TimeMachine._debug("install_task %r @ %r", task, task.taskTime)

        _TaskManager.install_task(self, task)
Esempio n. 17
0
    def _send_cov_notifications(self):
        if _debug: COVObjectMixin._debug("_send_cov_notifications")

        # check for subscriptions
        if not len(self._cov_subscriptions):
            return

        # get the current time from the task manager
        current_time = TaskManager().get_time()
        if _debug: COVObjectMixin._debug("    - current_time: %r", current_time)

        # create a list of values
        list_of_values = []
        for property_name in self._properties_reported:
            if _debug: COVObjectMixin._debug("    - property_name: %r", property_name)

            # get the class
            property_datatype = self.get_datatype(property_name)
            if _debug: COVObjectMixin._debug("        - property_datatype: %r", property_datatype)

            # build the value
            bundle_value = property_datatype(self._values[property_name])
            if _debug: COVObjectMixin._debug("        - bundle_value: %r", bundle_value)

            # bundle it into a sequence
            property_value = PropertyValue(
                propertyIdentifier=property_name,
                value=Any(bundle_value),
                )

            # add it to the list
            list_of_values.append(property_value)
        if _debug: COVObjectMixin._debug("    - list_of_values: %r", list_of_values)

        # loop through the subscriptions and send out notifications
        for cov in self._cov_subscriptions:
            if _debug: COVObjectMixin._debug("    - cov: %r", cov)

            # calculate time remaining
            if not cov.lifetime:
                time_remaining = 0
            else:
                time_remaining = int(cov.taskTime - current_time)

                # make sure it is at least one second
                if not time_remaining:
                    time_remaining = 1

            # build a request with the correct type
            if cov.confirmed:
                request = ConfirmedCOVNotificationRequest()
            else:
                request = UnconfirmedCOVNotificationRequest()

            # fill in the parameters
            request.pduDestination = cov.client_addr
            request.subscriberProcessIdentifier = cov.proc_id
            request.initiatingDeviceIdentifier = self._app.localDevice.objectIdentifier
            request.monitoredObjectIdentifier = cov.obj_id
            request.timeRemaining = time_remaining
            request.listOfValues = list_of_values
            if _debug: COVObjectMixin._debug("    - request: %r", request)

            # let the application send it
            self._app.cov_notification(cov, request)
Esempio n. 18
0
def main():
    """
    Main function, called when run as an application.
    """
    global args, server_address

    # parse the command line arguments
    parser = ArgumentParser(description=__doc__)
    parser.add_argument(
        "host",
        nargs='?',
        help="address of host (default %r)" % (SERVER_HOST, ),
        default=SERVER_HOST,
    )
    parser.add_argument(
        "port",
        nargs='?',
        type=int,
        help="server port (default %r)" % (SERVER_PORT, ),
        default=SERVER_PORT,
    )
    parser.add_argument(
        "--hello",
        action="store_true",
        default=False,
        help="send a hello message",
    )
    parser.add_argument(
        "--connect-timeout",
        nargs='?',
        type=int,
        help="idle connection timeout",
        default=CONNECT_TIMEOUT,
    )
    parser.add_argument(
        "--idle-timeout",
        nargs='?',
        type=int,
        help="idle connection timeout",
        default=IDLE_TIMEOUT,
    )
    args = parser.parse_args()

    if _debug: _log.debug("initialization")
    if _debug: _log.debug("    - args: %r", args)

    # extract the server address and port
    host = args.host
    port = args.port
    server_address = (host, port)
    if _debug: _log.debug("    - server_address: %r", server_address)

    # build the stack
    this_console = ConsoleClient()
    if _debug: _log.debug("    - this_console: %r", this_console)

    this_middle_man = MiddleMan()
    if _debug: _log.debug("    - this_middle_man: %r", this_middle_man)

    this_director = TCPClientDirector(
        connect_timeout=args.connect_timeout,
        idle_timeout=args.idle_timeout,
    )
    if _debug: _log.debug("    - this_director: %r", this_director)

    bind(this_console, this_middle_man, this_director)
    bind(MiddleManASE(), this_director)

    # create a task manager for scheduled functions
    task_manager = TaskManager()
    if _debug: _log.debug("    - task_manager: %r", task_manager)

    # don't wait to connect
    deferred(this_director.connect, server_address)

    # send hello maybe
    if args.hello:
        deferred(this_middle_man.indication, PDU(b'Hello, world!\n'))

    if _debug: _log.debug("running")

    run()

    if _debug: _log.debug("fini")
Esempio n. 19
0
    def suspend_task(self, task):
        if _debug:
            TimeMachine._debug("suspend_task @ %r: %r", self.current_time,
                               task)

        _TaskManager.suspend_task(self, task)
Esempio n. 20
0
    def install_task(self, task):
        if _debug:
            TimeMachine._debug("install_task @ %r: %r @ %r", self.current_time,
                               task, task.taskTime)

        _TaskManager.install_task(self, task)
Esempio n. 21
0
    def process_task(self, task):
        if _debug:
            TimeMachine._debug("process_task @ %r: %r", self.current_time,
                               task)

        _TaskManager.process_task(self, task)
Esempio n. 22
0
from bacpypes.consolelogging import ConfigArgumentParser
from bacpypes.pdu import Address, GlobalBroadcast
from bacpypes.core import run, stop
from bacpypes.apdu import WhoIsRequest, IAmRequest, ReadPropertyRequest, ReadPropertyACK, UnconfirmedRequestSequence
from bacpypes.errors import DecodingError
from bacpypes.task import TaskManager
from bacpypes.object import get_datatype, get_object_class, DeviceObject
from bacpypes.primitivedata import Enumerated, Unsigned, Boolean, Integer, Real, Double
from bacpypes.constructeddata import Array

"""
Simple utility to scrape device registers and write them to a configuration file.
"""

#Make sure the TaskManager singleton exists...
task_manager = TaskManager()
_debug = 0
_log = ModuleLogger(globals())

@bacpypes_debugging
class SynchronousApplication(BIPSimpleApplication):
    def __init__(self, *args):
        SynchronousApplication._debug("__init__ %r", args)
        BIPSimpleApplication.__init__(self, *args)
        self.expect_confirmation = True

    def confirmation(self, apdu):
        self.apdu = apdu
        stop()
        
    def indication(self, apdu):
Esempio n. 23
0
    def process_task(self, task):
        if _debug: TimeMachine._debug("process_task %r", task)

        _TaskManager.process_task(self, task)