Exemplo n.º 1
0
    def __init__(self, address, vlan):
        if _debug:
            ApplicationLayerStateMachine._debug("__init__ %r %r", address,
                                                vlan)
        ClientStateMachine.__init__(self)

        # build a name, save the address
        self.name = "app @ %s" % (address, )
        self.address = Address(address)

        # a network service access point will be needed
        self.nsap = NetworkServiceAccessPoint()
        if _debug:
            ApplicationLayerStateMachine._debug("    - nsap: %r", self.nsap)

        # bind this as a client of the network service access point
        bind(self, self.nsap)

        # create a node, added to the network
        self.node = Node(self.address, vlan)
        if _debug:
            ApplicationLayerStateMachine._debug("    - node: %r", self.node)

        # bind the stack to the local network
        self.nsap.bind(self.node)
Exemplo n.º 2
0
    def __init__(self, local_address, local_network, vlan_address, vlan_network):
        if _debug: VLANRouter._debug("__init__ %r %r %r %r", local_address, local_network, vlan_address, vlan_network)

        # a network service access point will be needed
        self.nsap = NetworkServiceAccessPoint()

        # give the NSAP a generic network layer service element
        self.nse = NetworkServiceElement()
        bind(self.nse, self.nsap)

        # create a generic BIP stack, bound to the Annex J server 
        # on the UDP multiplexer
        self.bip = BIPSimple()
        self.annexj = AnnexJCodec()
        self.mux = UDPMultiplexer(local_address)

        # bind the bottom layers
        bind(self.bip, self.annexj, self.mux.annexJ)

        # bind the BIP stack to the local network
        self.nsap.bind(self.bip, local_network, local_address)

        # create a vlan node
        self.vlan_node = Node(vlan_address)

        # bind the stack to the vlan network
        self.nsap.bind(self.vlan_node, vlan_network)
Exemplo n.º 3
0
    def __init__(self, vlan_device: LocalDeviceObject, vlan_address: Address) -> None:
        if _debug:
            _VLANApplication._debug("__init__ %r %r", vlan_device, vlan_address)
        Application.__init__(self, localDevice=vlan_device, aseID=None)

        # include a application decoder
        self._asap = ApplicationServiceAccessPoint()

        # pass the device object to the state machine access point so it
        # can know if it should support segmentation
        self._smap = StateMachineAccessPoint(vlan_device)

        # the segmentation state machines need access to the same device
        # information cache as the application
        self._smap.deviceInfoCache = self.deviceInfoCache

        # a network service access point will be needed
        self._nsap = NetworkServiceAccessPoint()

        # give the NSAP a generic network layer service element
        self._nse = NetworkServiceElement()
        bind(self._nse, self._nsap)

        # bind the top layers
        bind(self, self._asap, self._smap, self._nsap)

        # create a vlan node at the assigned address
        self._vlan_node = Node(vlan_address)

        # bind the stack to the node, no network number
        self._nsap.bind(self._vlan_node)
Exemplo n.º 4
0
    def __init__(self, vlan_device, vlan_address, aseID=None):
        if _debug: VLANApplication._debug("__init__ %r %r aseID=%r", vlan_device, vlan_address, aseID)
        ApplicationIOController.__init__(self, vlan_device, vlan_address, aseID=aseID)

        # include a application decoder
        self.asap = ApplicationServiceAccessPoint()

        # pass the device object to the state machine access point so it
        # can know if it should support segmentation
        self.smap = StateMachineAccessPoint(vlan_device)

        # the segmentation state machines need access to the same device
        # information cache as the application
        self.smap.deviceInfoCache = self.deviceInfoCache

        # a network service access point will be needed
        self.nsap = NetworkServiceAccessPoint()

        # give the NSAP a generic network layer service element
        self.nse = NetworkServiceElement()
        bind(self.nse, self.nsap)

        # bind the top layers
        bind(self, self.asap, self.smap, self.nsap)

        # create a vlan node at the assigned address
        self.vlan_node = Node(vlan_address)

        # bind the stack to the node, no network number
        self.nsap.bind(self.vlan_node, address=vlan_address)

        # keep track of requests to line up responses
        self._request = None

        if _debug: VLANApplication._debug("    - nsap.local_address: %r", self.nsap.local_address)
Exemplo n.º 5
0
    def __init__(self, vlan_device, vlan_address, aseID=None):
        if _debug:
            VLANApplication._debug("__init__ %r %r aseID=%r", vlan_device,
                                   vlan_address, aseID)
        Application.__init__(self, vlan_device, local_address, aseID)

        # include a application decoder
        self.asap = ApplicationServiceAccessPoint()

        # pass the device object to the state machine access point so it
        # can know if it should support segmentation
        self.smap = StateMachineAccessPoint(vlan_device)

        # a network service access point will be needed
        self.nsap = NetworkServiceAccessPoint()

        # give the NSAP a generic network layer service element
        self.nse = NetworkServiceElement()
        bind(self.nse, self.nsap)

        # bind the top layers
        bind(self, self.asap, self.smap, self.nsap)

        # create a vlan node at the assigned address
        self.vlan_node = Node(vlan_address)

        # bind the stack to the node, no network number
        self.nsap.bind(self.vlan_node)
Exemplo n.º 6
0
    def __init__(self, address, vlan):
        if _debug:
            ApplicationLayerStateMachine._debug("__init__ %r %r", address,
                                                vlan)

        # build a name, save the address
        self.name = "app @ %s" % (address, )
        self.address = Address(address)

        # build a local device object
        local_device = TestDeviceObject(
            objectName=self.name,
            objectIdentifier=('device', int(address)),
            vendorIdentifier=999,
        )

        # build an address and save it
        self.address = Address(address)
        if _debug:
            ApplicationLayerStateMachine._debug("    - address: %r",
                                                self.address)

        # continue with initialization
        ApplicationServiceElement.__init__(self)
        ClientStateMachine.__init__(self, name=local_device.objectName)

        # include a application decoder
        self.asap = ApplicationServiceAccessPoint()

        # pass the device object to the state machine access point so it
        # can know if it should support segmentation
        self.smap = StateMachineAccessPoint(local_device)

        # the segmentation state machines need access to some device
        # information cache, usually shared with the application
        self.smap.deviceInfoCache = DeviceInfoCache()

        # a network service access point will be needed
        self.nsap = NetworkServiceAccessPoint()

        # give the NSAP a generic network layer service element
        self.nse = NetworkServiceElement()
        bind(self.nse, self.nsap)

        # bind the top layers
        bind(self, self.asap, self.smap, self.nsap)

        # create a node, added to the network
        self.node = Node(self.address, vlan)
        if _debug:
            ApplicationLayerStateMachine._debug("    - node: %r", self.node)

        # bind the stack to the local network
        self.nsap.bind(self.node)
Exemplo n.º 7
0
    def bind(self, vlan, address, net):
        if _debug: VLANRouter._debug("bind %r %r %r", vlan, address, net)

        # create a VLAN node for the router with the given address
        vlan_node = Node(Address(address))

        # add it to the VLAN
        vlan.add_node(vlan_node)

        # bind the router stack to the vlan network through this node
        self.nsap.bind(vlan_node, net)
        if _debug: _log.debug("    - bound to vlan")
Exemplo n.º 8
0
    def add_network(self, address, vlan, net):
        if _debug: RouterNode._debug("add_network %r %r %r", address, vlan, net)

        # convert the address to an Address
        address = Address(address)

        # create a node, added to the network
        node = Node(address, vlan)
        if _debug: RouterNode._debug("    - node: %r", node)

        # bind the BIP stack to the local network
        self.nsap.bind(node, net)
Exemplo n.º 9
0
    def __init__(self, objectName, deviceInstance, address, aseID=None):
        if _debug:
            VLANApplication._debug("__init__ %r %r %r aseID=%r", objectName,
                                   deviceInstance, address, aseID)

        # make an address
        vlan_address = Address(address)
        _log.debug("    - vlan_address: %r", vlan_address)

        # make a device object
        vlan_device = LocalDeviceObject(
            objectName=objectName,
            objectIdentifier=("device", deviceInstance),
            maxApduLengthAccepted=1024,
            segmentationSupported="noSegmentation",
            vendorIdentifier=15,
        )
        _log.debug("    - vlan_device: %r", vlan_device)

        # continue with the initialization
        Application.__init__(self, vlan_device, vlan_address, aseID)

        # include a application decoder
        self.asap = ApplicationServiceAccessPoint()

        # pass the device object to the state machine access point so it
        # can know if it should support segmentation
        self.smap = StateMachineAccessPoint(vlan_device)

        # the segmentation state machines need access to the same device
        # information cache as the application
        self.smap.deviceInfoCache = self.deviceInfoCache

        # a network service access point will be needed
        self.nsap = NetworkServiceAccessPoint()

        # give the NSAP a generic network layer service element
        self.nse = NetworkServiceElement()
        bind(self.nse, self.nsap)

        # bind the top layers
        bind(self, self.asap, self.smap, self.nsap)

        # create a vlan node at the assigned address
        self.vlan_node = Node(vlan_address)
        if _debug:
            VLANApplication._debug("    - vlan_node: %r", self.vlan_node)

        # bind the stack to the node, no network number
        self.nsap.bind(self.vlan_node)
        if _debug:
            VLANApplication._debug("    - node bound")
Exemplo n.º 10
0
    def __init__(self, address, vlan):
        if _debug: SnifferStateMachine._debug("__init__ %r %r", address, vlan)
        ClientStateMachine.__init__(self)

        # save the name and address
        self.name = address
        self.address = Address(address)

        # create a promiscuous node, added to the network
        self.node = Node(self.address, vlan, promiscuous=True)
        if _debug: SnifferStateMachine._debug("    - node: %r", self.node)

        # bind this to the node
        bind(self, self.node)
Exemplo n.º 11
0
    def __init__(self, node_count):
        if _debug: TNetwork._debug("__init__ %r", node_count)
        StateMachineGroup.__init__(self)

        self.vlan = Network(broadcast_address=0)

        for i in range(node_count):
            node = Node(i + 1, self.vlan)

            # bind a client state machine to the node
            csm = ClientStateMachine()
            bind(csm, node)

            # add it to this group
            self.append(csm)
Exemplo n.º 12
0
    def __init__(self, vlan):
        if _debug: SnifferNode._debug("__init__ %r", vlan)

        # save the name and give it a blank address
        self.name = "sniffer"
        self.address = Address()

        # continue with initialization
        Client.__init__(self)

        # create a promiscuous node, added to the network
        self.node = Node(self.address, vlan, promiscuous=True)
        if _debug: SnifferNode._debug("    - node: %r", self.node)

        # bind this to the node
        bind(self, self.node)
Exemplo n.º 13
0
    def __init__(self, address, vlan):
        if _debug: NetworkLayerNode._debug("__init__ %r %r", address, vlan)
        ClientStateMachine.__init__(self)

        # save the name and address
        self.name = address
        self.address = Address(address)

        # create a network layer encoder/decoder
        self.codec = NPDUCodec()
        if _debug: SnifferNode._debug("    - codec: %r", self.codec)

        # create a node, added to the network
        self.node = Node(self.address, vlan)
        if _debug: SnifferNode._debug("    - node: %r", self.node)

        # bind this to the node
        bind(self, self.codec, self.node)
Exemplo n.º 14
0
    def __init__(self, local_address: str):
        Network.__init__(self, broadcast_address=LocalBroadcast())

        # create the VLAN router, bind it to the local network
        address = Address(local_address)
        self._router = _VLANRouter(address, 0)

        self._address_index = 1
        # create a node for the router, address 1 on the VLAN
        router_node = Node(Address(self._address_index.to_bytes(4, "big")))
        self._address_index += 1

        self.add_node(router_node)

        # bind the router stack to the vlan network through this node
        self._router.bind(router_node, 1)
        self._router.start()

        self._sensors: Dict[int, Sensor] = {}
Exemplo n.º 15
0
    def __init__(self, localDevice, vlan):
        if _debug:
            ApplicationStateMachine._debug("__init__ %r %r", localDevice, vlan)

        # build an address and save it
        self.address = Address(localDevice.objectIdentifier[1])
        if _debug:
            ApplicationStateMachine._debug("    - address: %r", self.address)

        # continue with initialization
        Application.__init__(self, localDevice, self.address)
        StateMachine.__init__(self, name=localDevice.objectName)

        # include a application decoder
        self.asap = ApplicationServiceAccessPoint()

        # pass the device object to the state machine access point so it
        # can know if it should support segmentation
        self.smap = StateMachineAccessPoint(localDevice)

        # the segmentation state machines need access to the same device
        # information cache as the application
        self.smap.deviceInfoCache = self.deviceInfoCache

        # a network service access point will be needed
        self.nsap = NetworkServiceAccessPoint()

        # give the NSAP a generic network layer service element
        self.nse = NetworkServiceElement()
        bind(self.nse, self.nsap)

        # bind the top layers
        bind(self, self.asap, self.smap, self.nsap)

        # create a node, added to the network
        self.node = Node(self.address, vlan)

        # bind the network service to the node, no network number
        self.nsap.bind(self.node)

        # placeholder for the result block
        self.confirmed_private_result = None
Exemplo n.º 16
0
    def __init__(self,
                 vlan_device,
                 vlan_address,
                 aseID=None,
                 register_reader=None):
        if _debug:
            VLANApplication._debug("__init__ %r %r aseID=%r", vlan_device,
                                   vlan_address, aseID)
        Application.__init__(self, vlan_device, vlan_address, aseID)

        # include a application decoder
        self.asap = ApplicationServiceAccessPoint()

        # pass the device object to the state machine access point so it
        # can know if it should support segmentation
        self.smap = StateMachineAccessPoint(vlan_device)

        # the segmentation state machines need access to the same device
        # information cache as the application
        self.smap.deviceInfoCache = self.deviceInfoCache

        # a network service access point will be needed
        self.nsap = NetworkServiceAccessPoint()

        # give the NSAP a generic network layer service element
        self.nse = NetworkServiceElement()
        bind(self.nse, self.nsap)

        # bind the top layers
        bind(self, self.asap, self.smap, self.nsap)

        # create a vlan node at the assigned address
        self.vlan_node = Node(vlan_address)

        # bind the stack to the node, no network number
        self.nsap.bind(self.vlan_node)

        # set register reader class that will look into block of registers for all associated slaves
        self.register_reader = register_reader
Exemplo n.º 17
0
    def __init__(self, vlan_device, vlan_address, aseID=None):
        if _debug:
            VLANConsoleApplication._debug("__init__ %r %r aseID=%r",
                                          vlan_device, vlan_address, aseID)
        global args

        # normal initialization
        ApplicationIOController.__init__(self, vlan_device, aseID=aseID)

        # optional read property multiple
        if args.rpm:
            self.add_capability(ReadWritePropertyMultipleServices)

        # include a application decoder
        self.asap = ApplicationServiceAccessPoint()

        # pass the device object to the state machine access point so it
        # can know if it should support segmentation
        self.smap = StateMachineAccessPoint(vlan_device)

        # the segmentation state machines need access to the same device
        # information cache as the application
        self.smap.deviceInfoCache = self.deviceInfoCache

        # a network service access point will be needed
        self.nsap = NetworkServiceAccessPoint()

        # give the NSAP a generic network layer service element
        self.nse = NetworkServiceElement()
        bind(self.nse, self.nsap)

        # bind the top layers
        bind(self, self.asap, self.smap, self.nsap)

        # create a vlan node at the assigned address
        self.vlan_node = Node(vlan_address)

        # bind the stack to the node, no network number, no addresss
        self.nsap.bind(self.vlan_node)
Exemplo n.º 18
0
def main():
    global args, this_application

    # parse the command line arguments
    parser = ArgumentParser(
        description=__doc__,
        formatter_class=argparse.RawDescriptionHelpFormatter,
    )

    # add an argument for interval
    parser.add_argument(
        "addr1",
        type=str,
        help="address of first network",
    )

    # add an argument for interval
    parser.add_argument(
        "net1",
        type=int,
        help="network number of first network",
    )

    # add an argument for interval
    parser.add_argument(
        "net2",
        type=int,
        help="network number of second network",
    )

    # add an argument for how many virtual devices
    parser.add_argument(
        "--count",
        type=int,
        help="number of virtual devices",
        default=1,
    )

    # add an argument for how many virtual devices
    parser.add_argument(
        "--rpm",
        help="enable read property multiple",
        action="store_true",
    )

    # add an argument for including the property list
    parser.add_argument(
        "--plist",
        help="enable property list property",
        action="store_true",
    )

    # now parse the arguments
    args = parser.parse_args()

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

    local_address = Address(args.addr1)
    local_network = args.net1
    vlan_network = args.net2

    # create the VLAN router, bind it to the local network
    router = VLANRouter(local_address, local_network)

    # create a VLAN
    vlan = Network(broadcast_address=LocalBroadcast())

    # create a node for the router, address 1 on the VLAN
    router_addr = Address(1)
    router_node = Node(router_addr)
    vlan.add_node(router_node)

    # bind the router stack to the vlan network through this node
    router.nsap.bind(router_node, vlan_network, router_addr)

    # send network topology
    deferred(router.nse.i_am_router_to_network)

    # add the dynamic property list
    if args.plist:
        RandomAnalogValueObject.properties.append(CurrentPropertyList())

    # register it now that all its properties are defined
    register_object_type(RandomAnalogValueObject, vendor_id=999)

    # console is the first device
    device_number = 2
    device_instance = vlan_network * 100 + device_number
    _log.debug("    - console device_instance: %r", device_instance)

    # make a vlan device object
    vlan_device = LocalDeviceObject(
        objectName="VLAN Console Node %d" % (device_instance, ),
        objectIdentifier=("device", device_instance),
        maxApduLengthAccepted=1024,
        segmentationSupported="noSegmentation",
        vendorIdentifier=15,
    )
    _log.debug("    - vlan_device: %r", vlan_device)

    vlan_address = Address(device_number)
    _log.debug("    - vlan_address: %r", vlan_address)

    # make the console application, add it to the network
    this_application = VLANConsoleApplication(vlan_device, vlan_address)
    vlan.add_node(this_application.vlan_node)
    _log.debug("    - this_application: %r", this_application)

    # make a console
    this_console = VLANConsoleCmd()
    if _debug:
        _log.debug("    - this_console: %r", this_console)

    # make a random value object
    ravo = RandomAnalogValueObject(
        objectIdentifier=("analogValue", 1),
        objectName="Random-1-%d" % (device_instance, ),
    )
    _log.debug("    - ravo: %r", ravo)

    # add it to the device
    this_application.add_object(ravo)

    # make some more devices
    for device_number in range(3, 3 + args.count - 1):
        # device identifier is assigned from the address
        device_instance = vlan_network * 100 + device_number
        _log.debug("    - device_instance: %r", device_instance)

        # make a vlan device object
        vlan_device = LocalDeviceObject(
            objectName="VLAN Node %d" % (device_instance, ),
            objectIdentifier=("device", device_instance),
            maxApduLengthAccepted=1024,
            segmentationSupported="noSegmentation",
            vendorIdentifier=15,
        )
        _log.debug("    - vlan_device: %r", vlan_device)

        vlan_address = Address(device_number)
        _log.debug("    - vlan_address: %r", vlan_address)

        # make the application, add it to the network
        vlan_app = VLANApplication(vlan_device, vlan_address)
        vlan.add_node(vlan_app.vlan_node)
        _log.debug("    - vlan_app: %r", vlan_app)

        # make a random value object
        ravo = RandomAnalogValueObject(
            objectIdentifier=("analogValue", 1),
            objectName="Random-1-%d" % (device_instance, ),
        )
        _log.debug("    - ravo: %r", ravo)

        # add it to the device
        vlan_app.add_object(ravo)

    # enable sleeping will help with threads
    enable_sleeping()

    _log.debug("running")

    run()

    _log.debug("fini")
Exemplo n.º 19
0
if _debug: _log.debug("initialization")
if _debug: _log.debug("    - args: %r", args)

local_address = Address(args.addr1)
local_network = args.net1
vlan_address = Address(args.addr2)
vlan_network = args.net2

# create the VLAN router, bind it to the local network
router = VLANRouter(local_address, local_network)

# create a VLAN
vlan = Network()

# create a node for the router, address 1 on the VLAN
router_node = Node(Address(1))
vlan.add_node(router_node)

# bind the router stack to the vlan network through this node
router.nsap.bind(router_node, vlan_network)

# device identifier is assigned from the address
device_instance = vlan_network * 100 + int(args.addr2)
_log.debug("    - device_instance: %r", device_instance)

# make a vlan device object
vlan_device = \
    LocalDeviceObject(
        objectName="VLAN Node %d" % (device_instance,),
        objectIdentifier=('device', device_instance),
        maxApduLengthAccepted=1024,
Exemplo n.º 20
0
def main():
    # parse the command line arguments
    # parser = ArgumentParser(
    #     description=__doc__,
    #     formatter_class=argparse.RawDescriptionHelpFormatter,
    #     )
    #
    # # add an argument for interval
    # parser.add_argument('addr1', type=str,
    #       help='address of first network',
    #       )
    #
    # # add an argument for interval
    # parser.add_argument('net1', type=int,
    #       help='network number of first network',
    #       )
    #
    # # add an argument for interval
    # parser.add_argument('addr2', type=str,
    #       help='address of second network',
    #       )
    #
    # # add an argument for interval
    # parser.add_argument('net2', type=int,
    #       help='network number of second network',
    #       )
    #
    # # now parse the arguments
    # args = parser.parse_args()
    #
    # if _debug: _log.debug("initialization")
    # if _debug: _log.debug("    - args: %r", args)

    # local_address = Address(args.addr1)
    # local_network = args.net1
    # vlan_address = Address(args.addr2)
    # vlan_network = args.net2
    local_address = Address('130.91.139.93')
    local_network = 0
    vlan_address = Address(5)
    vlan_network = 9997

    # create the VLAN router, bind it to the local network
    router = VLANRouter(local_address, local_network)

    # create a VLAN
    vlan = Network()

    # create a node for the router, address 1 on the VLAN
    router_node = Node(Address(1))
    vlan.add_node(router_node)

    # bind the router stack to the vlan network through this node
    router.nsap.bind(router_node, vlan_network)

    # device identifier is assigned from the address
    # device_instance = vlan_network * 100 + int(args.addr2)
    device_instance = vlan_network * 100 + 5  # vlan_address
    device_instance2 = vlan_network * 100 + 6
    _log.debug("    - device_instance: %r", device_instance)

    # make a vlan device object
    # vlan_device = \
    #     LocalDeviceObject(
    #         objectName="VLAN Node %d" % (device_instance,),
    #         objectIdentifier=('device', device_instance),
    #         maxApduLengthAccepted=1024,
    #         segmentationSupported='noSegmentation',
    #         vendorIdentifier=15,
    #         )
    #ADDED
    vlan_device = \
        LocalDeviceObject(
            objectName='laptopBehindNetwork',
            objectIdentifier=device_instance,
            maxApduLengthAccepted=1024,
            segmentationSupported='noSegmentation',
            vendorIdentifier=15,
            )
    vlan_device2 = \
        LocalDeviceObject(
            objectName='laptopBehindNetwork2',
            objectIdentifier=device_instance2,
            maxApduLengthAccepted=1024,
            segmentationSupported='noSegmentation',
            vendorIdentifier=15,
        )
    #ADDED
    _log.debug("    - vlan_device: %r", vlan_device)

    # make the application, add it to the network
    vlan_app = VLANApplication(vlan_device, vlan_address)
    vlan.add_node(vlan_app.vlan_node)

    vlan_app2 = VLANApplication(vlan_device2, Address(6))
    vlan.add_node(vlan_app2.vlan_node)
    _log.debug("    - vlan_app: %r", vlan_app)

    #ADDED
    services_supported = vlan_app.get_services_supported()

    # let the device object know
    vlan_device.protocolServicesSupported = services_supported.value

    services_supported = vlan_app2.get_services_supported()

    # let the device object know
    vlan_device2.protocolServicesSupported = services_supported.value
    #ADDED

    # make a random value object
    # ravo = RandomAnalogValueObject(
    #     objectIdentifier=('analogValue', 1),
    #     objectName='Device%d/Random1' % (device_instance,),
    #     )
    ravo = ModbusAnalogInputObject(
        objectIdentifier=('analogInput', 1),
        objectName='Device%d/Modbus1' % (device_instance, ),
    )
    _log.debug("    - ravo1: %r", ravo)

    # add it to the device
    vlan_app.add_object(ravo)

    # make a random value object
    ravo = RandomAnalogValueObject(
        objectIdentifier=('analogValue', 1),
        objectName='Device%d/Random1' % (device_instance2, ),
    )

    # add it to the device
    vlan_app2.add_object(ravo)

    _log.debug("running")

    print('run')
    run()

    _log.debug("fini")
Exemplo n.º 21
0
def main():
    global args, this_device, this_application

    # parse the command line arguments
    parser = ConfigArgumentParser(
        description=__doc__,
        formatter_class=argparse.RawDescriptionHelpFormatter,
        )

    # add an argument for interval
    parser.add_argument('net1', type=int,
        help='network number of IPv4 network',
        )

    # add an argument for interval
    parser.add_argument('net2', type=int,
        help='network number of VLAN network',
        )

    # add an argument for interval
    parser.add_argument('addr2', type=str,
        help='address on the VLAN network',
        )

    # now parse the arguments
    args = parser.parse_args()

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

    local_network = args.net1
    local_address = Address(args.ini.address)
    if _debug: _log.debug("    - local_network, local_address: %r, %r", local_network, local_address)

    vlan_network = args.net2
    vlan_address = Address(args.addr2)
    if _debug: _log.debug("    - vlan_network, vlan_address: %r, %r", vlan_network, vlan_address)

    # create the VLAN router, bind it to the local network
    router = VLANRouter(local_address, local_network)

    # create a VLAN
    vlan = Network(broadcast_address=LocalBroadcast())

    # create a node for the router, address 1 on the VLAN
    router_node = Node(Address(1))
    vlan.add_node(router_node)

    # bind the router stack to the vlan network through this node
    router.nsap.bind(router_node, vlan_network)
    
    # send network topology
    deferred(router.nse.i_am_router_to_network)

    # make a vlan device object
    this_device = \
        LocalDeviceObject(
            objectName=args.ini.objectname,
            objectIdentifier=("device", int(args.ini.objectidentifier)),
            maxApduLengthAccepted=1024,
            segmentationSupported='noSegmentation',
            vendorIdentifier=15,
            )
    _log.debug("    - this_device: %r", this_device)

    # make the application, add it to the network
    this_application = VLANApplication(this_device, vlan_address)
    vlan.add_node(this_application.vlan_node)
    _log.debug("    - this_application: %r", this_application)

    # make a console
    this_console = WhoIsIAmConsoleCmd()
    if _debug: _log.debug("    - this_console: %r", this_console)

    _log.debug("running")

    run()

    _log.debug("fini")
Exemplo n.º 22
0
def main():
    # parse the command line arguments
    parser = ArgumentParser(
        description=__doc__,
        formatter_class=argparse.RawDescriptionHelpFormatter,
    )

    # add an argument for interval
    parser.add_argument(
        'addr1',
        type=str,
        help='address of first network',
    )

    # add an argument for interval
    parser.add_argument(
        'net1',
        type=int,
        help='network number of first network',
    )

    # add an argument for interval
    parser.add_argument(
        'addr2',
        type=str,
        help='address of second network',
    )

    # add an argument for interval
    parser.add_argument(
        'net2',
        type=int,
        help='network number of second network',
    )

    # now parse the arguments
    args = parser.parse_args()

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

    local_address = Address(args.addr1)
    local_network = args.net1
    vlan_address = Address(args.addr2)
    vlan_network = args.net2

    # create the VLAN router, bind it to the local network
    router = VLANRouter(local_address, local_network)

    # create a VLAN
    vlan = Network(broadcast_address=LocalBroadcast())

    # create a node for the router, address 1 on the VLAN
    router_node = Node(Address(1))
    vlan.add_node(router_node)

    # bind the router stack to the vlan network through this node
    router.nsap.bind(router_node, vlan_network)

    # send network topology
    deferred(router.nse.i_am_router_to_network)

    # device identifier is assigned from the address
    device_instance = vlan_network * 100 + int(args.addr2)
    _log.debug("    - device_instance: %r", device_instance)

    # make a vlan device object
    vlan_device = \
        LocalDeviceObject(
            objectName="VLAN Node %d" % (device_instance,),
            objectIdentifier=('device', device_instance),
            maxApduLengthAccepted=1024,
            segmentationSupported='noSegmentation',
            vendorIdentifier=15,
            )
    _log.debug("    - vlan_device: %r", vlan_device)

    # make the application, add it to the network
    vlan_app = VLANApplication(vlan_device, vlan_address)
    vlan.add_node(vlan_app.vlan_node)
    _log.debug("    - vlan_app: %r", vlan_app)

    # make a random value object
    ravo = RandomAnalogValueObject(
        objectIdentifier=('analogValue', 1),
        objectName='Device%d/Random1' % (device_instance, ),
    )
    _log.debug("    - ravo1: %r", ravo)

    # add it to the device
    vlan_app.add_object(ravo)

    _log.debug("running")

    run()

    _log.debug("fini")
Exemplo n.º 23
0
def main():
    global args

    # parse the command line arguments
    parser = ArgumentParser(description=__doc__)

    # arguments for first network
    parser.add_argument(
        'lan',
        type=str,
        help='MQTT network name',
    )
    parser.add_argument(
        'addr1',
        type=str,
        help='address on MQTT network',
    )
    parser.add_argument(
        'net1',
        type=int,
        help='network number of MQTT network',
    )

    # VLAN arguments
    parser.add_argument(
        'net2',
        type=int,
        help='network number of VLAN',
    )
    parser.add_argument(
        '--count',
        type=int,
        help='number of virtual devices',
        default=1,
    )

    # additional options for the MQTT client
    parser.add_argument(
        '--host',
        type=str,
        default=bacpypes_mqtt.default_broker_host,
        help='broker host address',
    )
    parser.add_argument(
        '--port',
        type=int,
        default=bacpypes_mqtt.default_broker_port,
        help='broker port',
    )
    parser.add_argument(
        '--keepalive',
        type=int,
        default=bacpypes_mqtt.default_broker_keepalive,
        help=
        "maximum period in seconds allowed between communications with the broker",
    )

    # now parse the arguments
    args = parser.parse_args()

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

    # create the VLAN router, bind it to the local network
    router = VLANRouter(args.lan, Address(args.addr1), args.net1)

    # create a VLAN
    vlan = Network(broadcast_address=LocalBroadcast())

    # create a node for the router, address 1 on the VLAN
    router_node = Node(Address(1))
    vlan.add_node(router_node)

    # bind the router stack to the vlan network through this node
    router.nsap.bind(router_node, args.net2)

    # make some devices
    for device_number in range(2, 2 + args.count):
        # device identifier is assigned from the address
        device_instance = args.net2 * 100 + device_number
        _log.debug("    - device_instance: %r", device_instance)

        # make a vlan device object
        vlan_device = \
            LocalDeviceObject(
                objectName="VLAN Node %d" % (device_instance,),
                objectIdentifier=('device', device_instance),
                maxApduLengthAccepted=1024,
                segmentationSupported='noSegmentation',
                vendorIdentifier=15,
                )
        _log.debug("    - vlan_device: %r", vlan_device)

        vlan_address = Address(device_number)
        _log.debug("    - vlan_address: %r", vlan_address)

        # make the application, add it to the network
        vlan_app = VLANApplication(vlan_device, vlan_address)
        vlan.add_node(vlan_app.vlan_node)
        _log.debug("    - vlan_app: %r", vlan_app)

        # make a random value object
        ravo = RandomAnalogValueObject(
            objectIdentifier=('analogValue', 1),
            objectName='Random-1-%d' % (device_instance, ),
        )
        _log.debug("    - ravo: %r", ravo)

        # add it to the device
        vlan_app.add_object(ravo)

    # start up the client
    router.mse.startup()

    _log.debug("running")

    run()

    # shutdown the client
    router.mse.shutdown()

    _log.debug("fini")
Exemplo n.º 24
0
def main():
    # parse the command line arguments
    args = ConfigArgumentParser(description=__doc__).parse_args()

    # local_address = Address('130.91.139.93/22')
    # local_network = 0
    # vlan_network = 9997

    local_address = Address(args.ini.localip)
    local_network = int(args.ini.localnetwork)
    vlan_network = int(args.ini.vlannetwork)
    foreign_address = Address(args.ini.bbmdip)
    mb_timeout = verify_ini_vars(args.ini, 'modbustimeout', 1000)
    mbtcp_timeout = verify_ini_vars(args.ini, 'mbtcpservertimeout', 5000)
    max_apdu_len = verify_ini_vars(args.ini, 'maxapdulength', 1024)
    segmentation_support = verify_ini_vars(args.ini, 'segmentationsupport', 'noSegmentation')
    vendor_id = verify_ini_vars(args.ini, 'vendorid', 15)
    bcnt_obj_update_interval = verify_ini_vars(args.ini, 'bacnetobjectupdateinterval', 1000)
    default_cov_inc = verify_ini_vars(args.ini, 'defaultcovincrement', 0.0)
    reboot_check_time = verify_ini_vars(args.ini, 'rebootchecktime', 1800000)
    # modbus_only = verify_ini_vars(args.ini, 'modbusonly', 0)
    modbus_translation = verify_ini_vars(args.ini, 'modbustranslation', 1)
    modbus_translation = True if modbus_translation == 1 else False
    # modbus_word_order = verify_ini_vars(args.ini, 'modbuswordorder', 0)
    # modbus_word_order = 'lsw' if modbus_word_order == 0 else 'msw'

    # if not modbus_only:
    reboot_queue = queue.Queue()
    reboot_queue.put_nowait(_time())

    # create the VLAN router, bind it to the local network
    router = VLANRouter(local_address, local_network, foreign_address, rebootQueue=reboot_queue)

    # create a VLAN
    vlan = Network()

    # create a node for the router, address 1 on the VLAN
    router_node = Node(Address(1))
    vlan.add_node(router_node)

    # bind the router stack to the vlan network through this node
    router.nsap.bind(router_node, vlan_network)

    mb_to_bank_queue = queue.Queue()
    bank_to_bcnt_queue = queue.Queue()

    object_val_dict = {}
    mb_req_dict = {}
    unq_ip_last_resp_dict = {}
    dev_dict = {}
    app_dict = {}

    for fn in os.listdir(sys.path[0] + '/DeviceList'):
        if fn.endswith('.json'):  # and fn.startswith('DRL'):
            print(sys.path[0] + '/DeviceList/' + fn)
            json_raw_str = open(sys.path[0] + '/DeviceList/' + fn, 'r')
            map_dict = json.load(json_raw_str)
            good_inst = modbusregisters.add_meter_instance_to_dicts(map_dict, mb_to_bank_queue, object_val_dict,
                                                                    mb_req_dict, unq_ip_last_resp_dict)
            json_raw_str.close()

            if good_inst:
                try:
                    dev_inst = map_dict['deviceInstance']
                    dev_ip = map_dict['deviceIP']
                    dev_mb_id = map_dict['modbusId']
                except KeyError:
                    _log.debug("json key error for %s", fn)
                    continue

                dev_name = map_dict.get('deviceName', 'default device name')
                dev_desc = map_dict.get('deviceDescription', 'UTILITY; Feeds: BUILDING_EQUATION; From: '
                                                             'ELECTRIC_LINES; Serno: SERIAL_NUMBER; IP: METER_IP; '
                                                             'MBid: MODBUS_ID')
                dev_map_name = map_dict.get('mapName', 'default map')
                dev_map_rev = map_dict.get('mapRev', 'default map rev')
                dev_meter_model = map_dict.get('meterModelName', 'default meter model')
                dev_mb_port = map_dict.get('modbusPort', 502)
                dev_cov = map_dict.get('covSubscribe', 'no')
                dev_mb_resp_word_order = map_dict.get('meterRespWordOrder', 'lsw')

                dev_dict[dev_inst] = modbusbacnetclasses.ModbusLocalDevice(
                    objectName=dev_name,
                    objectIdentifier=('device', dev_inst),
                    description=dev_desc,
                    maxApduLengthAccepted=max_apdu_len,
                    segmentationSupported=segmentation_support,
                    vendorIdentifier=vendor_id,
                    deviceIp=dev_ip,
                    modbusId=dev_mb_id,
                    modbusMapName=dev_map_name,
                    modbusMapRev=dev_map_rev,
                    deviceModelName=dev_meter_model,
                    modbusPort=dev_mb_port,
                    meterRespWordOrder=dev_mb_resp_word_order,
                )

                if dev_cov == 'yes':
                    app_dict[dev_inst] = ModbusCOVVLANApplication(dev_dict[dev_inst],
                                                                  ip_to_bcnt_address(dev_ip, dev_mb_id))
                else:
                    app_dict[dev_inst] = ModbusVLANApplication(dev_dict[dev_inst],
                                                               ip_to_bcnt_address(dev_ip, dev_mb_id))
                vlan.add_node(app_dict[dev_inst].vlan_node)

                services_supported = app_dict[dev_inst].get_services_supported()
                dev_dict[dev_inst].protocolServicesSupported = services_supported.value

                val_types = {'holdingRegisters': 3, 'inputRegisters': 4, 'coilBits': 1, 'inputBits': 2}

                # create objects for device
                for val_type, mb_func in val_types.items():
                    if val_type not in map_dict or val_type not in ['holdingRegisters', 'inputRegisters']:
                        continue

                    mb_dev_wo = map_dict[val_type].get('wordOrder', 'lsw')
                    mb_dev_poll_time = map_dict[val_type].get('pollingTime', 30000)

                    for register in map_dict[val_type]['registers']:
                        try:
                            if register['poll'] == 'no':
                                continue
                            obj_inst = register['objectInstance']
                            obj_reg_start = register['start']
                            obj_reg_format = register['format']
                        except KeyError:
                            continue

                        obj_name = register.get('objectName', 'default object name')
                        obj_description = register.get('objectDescription', 'default object description')
                        obj_cov_inc = register.get('covIncrement', default_cov_inc)

                        if obj_reg_format in modbusregisters.one_register_formats:
                            obj_num_regs = 1
                        elif obj_reg_format in modbusregisters.two_register_formats:
                            obj_num_regs = 2
                        elif obj_reg_format in modbusregisters.three_register_formats:
                            obj_num_regs = 3
                        elif obj_reg_format in modbusregisters.four_register_formats:
                            obj_num_regs = 4
                        else:
                            continue
                        obj_units_id = register.get('unitsId', 95)  # 95 is noUnits
                        obj_pt_scale = register.get('pointScale', [0, 1, 0, 1])
                        obj_eq_m = (obj_pt_scale[3] - obj_pt_scale[2]) / (obj_pt_scale[1] - obj_pt_scale[0])
                        obj_eq_b = obj_pt_scale[2] - obj_eq_m * obj_pt_scale[0]

                        maio = modbusbacnetclasses.ModbusAnalogInputObject(
                            objectIdentifier=('analogInput', obj_inst),
                            objectName=obj_name,
                            description=obj_description,
                            modbusFunction=mb_func,
                            registerStart=obj_reg_start,
                            numberOfRegisters=obj_num_regs,
                            registerFormat=obj_reg_format,
                            wordOrder=mb_dev_wo,
                            # modbusScaling=[obj_eq_m, obj_eq_b],
                            modbusScaling=ArrayOf(Real)([obj_eq_m, obj_eq_b]),
                            units=obj_units_id,
                            covIncrement=obj_cov_inc,
                            updateInterval=int(mb_dev_poll_time / 10.0),
                            resolution=0.0,
                            reliability='communicationFailure',
                            statusFlags=[0, 1, 0, 0],
                            modbusCommErr='noTcpConnection',
                            eventState='normal',
                            outOfService=False,
                        )

                        # _log.debug("    - maio: %r", maio)
                        app_dict[dev_inst].add_object(maio)

    print('init modbus bank')
    obj_val_bank = modbusregisters.ModbusFormatAndStorage(mb_to_bank_queue, bank_to_bcnt_queue, object_val_dict)

    print('init modbus req launcher')
    mb_req_launcher = modbusregisters.ModbusRequestLauncher(mb_req_dict, unq_ip_last_resp_dict)

    print('init check for reboot')
    reboot_task = RebootWithNoTraffic(reboot_queue, time_to_check=reboot_check_time)

    print('init update bacnet objects task')
    update_objects = modbusbacnetclasses.UpdateObjectsFromModbus(bank_to_bcnt_queue, app_dict,
                                                                 bcnt_obj_update_interval)

    print('start bank and launcher')
    obj_val_bank.start()
    mb_req_launcher.start()
    # end if not modbus only

    if B_RPI_GPIO_EXISTS:
        print('init led heartbeat task')
        led_heartbeat = LEDHeartbeat(heartbeat_on_time=1000, pin_board_num=11)
    else:
        print('no heartbeat here')

    # set up forked modbus server
    socketserver.TCPServer.allow_reuse_address = True

    ModbusRequestHandler = modbusserver.make_modbus_request_handler(app_dict, mb_timeout=mb_timeout,
                                                                    tcp_timeout=mbtcp_timeout,
                                                                    mb_translation=modbus_translation)

    modbusserver.ThreadedTCPServer.daemon_threads = True
    modbusserver.ThreadedTCPServer.allow_reuse_address = True
    modbus_thread_server = modbusserver.ThreadedTCPServer((str(args.ini.localip).split('/')[0], 502),
                                                          ModbusRequestHandler)

    mb_server_thread = threading.Thread(target=modbus_thread_server.serve_forever)
    mb_server_thread.daemon = True
    print('modbus server start')
    mb_server_thread.start()

    _log.debug("running")
    print('bacnet start')
    run()

    modbus_thread_server.socket.close()
    print('PiGateway finish')
    _log.debug("fini")