コード例 #1
0
ファイル: tools.py プロジェクト: mertz3hack/python-opcua
def uahistoryread():
    parser = argparse.ArgumentParser(description="Read history of a node")
    add_common_args(parser)
    parser.add_argument(
        "--starttime",
        default="",
        help=
        "Start time, formatted as YYYY-MM-DD [HH:MM[:SS]]. Default: current time"
    )
    parser.add_argument(
        "--endtime",
        default="",
        help=
        "End time, formatted as YYYY-MM-DD [HH:MM[:SS]]. Default: current time"
    )

    args = parse_args(parser, requirenodeid=True)

    client = Client(args.url, timeout=args.timeout)
    client.set_security_string(args.security)
    client.connect()
    try:
        node = get_node(client, args)
        starttime = str_to_datetime(args.starttime)
        endtime = str_to_datetime(args.endtime)
        print("Reading raw history of node {} at {}; start at {}, end at {}\n".
              format(node, args.url, starttime, endtime))
        print_history(node.read_raw_history(starttime, endtime))
    finally:
        client.disconnect()
    sys.exit(0)
コード例 #2
0
def cambiar_valor2(server,nodo,avg_fv,median_fv,std_fv,moda_fv,perc50_fv,mom2_fv,mom3_fv,mom4_fv,skew1_fv,skew2_fv,skew3_fv,kurt_fv,logger):
  client = Client(server)
  try:
      client.connect()#conecta el servidor
      var=client.get_node("ns=1;s="+nodo)#se obtiene el primer nodo
      variable2=var.get_children()
      tamano=np.size(variable2)
      #datetime_object = datetime.strptime(tiemp, '%d/%m/%Y %H:%M:%S')
      if tamano>0:
        variable2[10].set_value(avg_fv)
        variable2[11].set_value(median_fv)
        variable2[12].set_value(std_fv)
        variable2[13].set_value(moda_fv)
        variable2[14].set_value(perc50_fv)
        variable2[15].set_value(mom2_fv)
        variable2[16].set_value(mom3_fv)
        variable2[17].set_value(mom4_fv)
        variable2[18].set_value(skew1_fv)
        variable2[19].set_value(skew2_fv)
        variable2[20].set_value(skew3_fv)
        variable2[21].set_value(kurt_fv)
      else:
        logger.warning("No se encuentra el nodo en el servidor opc")
      
      client.disconnect()
  
  except: 
      logger.error("No se puede conectar con el servidor opc")
コード例 #3
0
 def exchange_connect_status(self):
     while True:
         source_times_tamp = datetime.datetime.utcnow().isoformat()
         try:
             # 不用同一个对象防止关闭同一个连接
             client = Client(f"opc.tcp://{self.ip}:{self.port}/")
             client.connect()
             client.disconnect()
             submit_status = 1
         except Exception as e:
             OPCScript.connect_status = Status.FAILED
             submit_status = 0
             print(e)
         msg = {
             "notification": 'HeatBeat',
             "parameters": {
                 "status":
                 submit_status,
                 "timestamp":
                 source_times_tamp,
                 "connectType":
                 "opc ua",
                 "processStatus":
                 True if
                 (threading.activeCount() >= 7 and submit_status == 1) or
                 (threading.activeCount() >= 5 and submit_status == 0) else
                 False
             }
         }
         need_send_to_device_hive.put(msg)
         time.sleep(5)
コード例 #4
0
ファイル: tools.py プロジェクト: sunyiex/python-opcua
def uals():
    parser = argparse.ArgumentParser(description="Browse OPC-UA node and print result")
    add_common_args(parser)
    #parser.add_argument("-l",
                        #dest="long_format",
                        #default=ua.AttributeIds.Value,
                        #help="use a long listing format")
    parser.add_argument("-d",
                        "--depth",
                        default=1,
                        type=int,
                        help="Browse depth")

    args = parser.parse_args()
    logging.basicConfig(format="%(levelname)s: %(message)s", level=getattr(logging, args.loglevel))

    client = Client(args.url, timeout=args.timeout)
    client.connect()
    try:
        node = client.get_node(args.nodeid)
        if args.path:
            node = node.get_child(args.path.split(","))
        print("Browsing node {} at {}\n".format(node, args.url))
        _lsprint(client, node.nodeid, args.depth - 1)

    finally:
        client.disconnect()
    sys.exit(0)
    print(args)
コード例 #5
0
ファイル: tests_server.py プロジェクト: zwjsoft/python-opcua
 def test_find_servers2(self):
     client = Client(self.discovery.endpoint.geturl())
     client.connect()
     try:
         servers = client.find_servers()
         # Use 2 different RegistrationServices, as it does not allow duplicate registrations.
         with RegistrationService() as regService1, RegistrationService() as regService2:
             # Register to server with uri1
             new_app_uri1 = "urn:freeopcua:python:server:test_discovery1"
             self.srv.application_uri = new_app_uri1
             regService1.register_to_discovery(self.srv, self.discovery.endpoint.geturl(), period=0)
             # Register to server with uri2
             new_app_uri2 = "urn:freeopcua:python:test_discovery2"
             self.srv.application_uri = new_app_uri2
             regService2.register_to_discovery(self.srv, self.discovery.endpoint.geturl(), period=0)
             # Check for 2 registrations
             time.sleep(0.1)  # let server register registration
             new_servers = client.find_servers()
             self.assertEqual(len(new_servers) - len(servers) , 2)
             self.assertFalse(new_app_uri1 in [s.ApplicationUri for s in servers])
             self.assertFalse(new_app_uri2 in [s.ApplicationUri for s in servers])
             self.assertTrue(new_app_uri1 in [s.ApplicationUri for s in new_servers])
             self.assertTrue(new_app_uri2 in [s.ApplicationUri for s in new_servers])
             # now do a query with filter
             new_servers = client.find_servers(["urn:freeopcua:python:server"])
             self.assertEqual(len(new_servers) - len(servers) , 0)
             self.assertTrue(new_app_uri1 in [s.ApplicationUri for s in new_servers])
             self.assertFalse(new_app_uri2 in [s.ApplicationUri for s in new_servers])
             # now do a query with filter
             new_servers = client.find_servers(["urn:freeopcua:python"])
             self.assertEqual(len(new_servers) - len(servers) , 2)
             self.assertTrue(new_app_uri1 in [s.ApplicationUri for s in new_servers])
             self.assertTrue(new_app_uri2 in [s.ApplicationUri for s in new_servers])
     finally:
         client.disconnect()
コード例 #6
0
ファイル: tools.py プロジェクト: thephez/python-opcua
def uasubscribe():
    parser = argparse.ArgumentParser(description="Subscribe to a node and print results")
    add_common_args(parser)
    parser.add_argument("-t",
                        "--eventtype",
                        dest="eventtype",
                        default="datachange",
                        choices=['datachange', 'event'],
                        help="Event type to subscribe to")

    args = parse_args(parser, requirenodeid=True)

    client = Client(args.url, timeout=args.timeout)
    client.connect()
    try:
        node = get_node(client, args)
        handler = SubHandler()
        sub = client.create_subscription(500, handler)
        if args.eventtype == "datachange":
            sub.subscribe_data_change(node)
        else:
            sub.subscribe_events(node)
        embed()
    finally:
        client.disconnect()
    sys.exit(0)
    print(args)
コード例 #7
0
def main_c():
    # url = "opc.tcp://127.0.0.1:12345/"
    # # url = "opc.tcp://127.0.0.1:12346/test"
    # c = Client(url)
    # try:
    #     c.connect()
    #     root = c.get_root_node()
    #     print("\r\nBrower:")
    #     brower_child2(root.get_child(["0:Objects"]), -1, ["Server"])
    # except Exception as e:
    #     print("Client Exception:", e)
    # finally:
    #     c.disconnect()
    url = "opc.tcp://127.0.0.1:12345/"
    # url = "opc.tcp://127.0.0.1:12346/test"
    c = Client(url)
    try:
        c.connect()
        root = c.get_root_node()
        print("\r\nBrower:")
        brower_child2(root.get_child(["0:Objects"]), -1, ["Server"])
    except Exception as e:
        print("Client Exception:", e)
    finally:
        c.disconnect()
コード例 #8
0
ファイル: tools.py プロジェクト: mertz3hack/python-opcua
def uasubscribe():
    parser = argparse.ArgumentParser(
        description="Subscribe to a node and print results")
    add_common_args(parser)
    parser.add_argument("-t",
                        "--eventtype",
                        dest="eventtype",
                        default="datachange",
                        choices=['datachange', 'event'],
                        help="Event type to subscribe to")

    args = parse_args(parser, requirenodeid=False)
    if args.eventtype == "datachange":
        _require_nodeid(parser, args)
    else:
        # FIXME: this is broken, someone may have written i=84 on purpose
        if args.nodeid == "i=84" and args.path == "":
            args.nodeid = "i=2253"

    client = Client(args.url, timeout=args.timeout)
    client.set_security_string(args.security)
    client.connect()
    try:
        node = get_node(client, args)
        handler = SubHandler()
        sub = client.create_subscription(500, handler)
        if args.eventtype == "datachange":
            sub.subscribe_data_change(node)
        else:
            sub.subscribe_events(node)
        embed()
    finally:
        client.disconnect()
    sys.exit(0)
    print(args)
コード例 #9
0
ファイル: aas.py プロジェクト: julianBac/openAAS_workshop
def getSubModel(endpointStr, subModel_NodeId):

    client = Client(endpointStr)
    subModel = None
    try:
        client.connect()
        #    nsarray = client.get_node(ua.NodeId(2255, 0))
        #    nsList = nsarray.get_value()
        #    i=-1
        #    for entry in nsList:
        #     i = i + 1

        #      if entry == "http://acplt.org/openaas/":
        #        nsopenaas_subModelType = i
        #
        #        break
        #    if i!= -1:

        #      print("Looking for AAS at entry point %s,%s" % (subModel_NodeId))

        path = client.get_node(subModel_NodeId)
        print("path is %s" % path)
        print("1")
        subModelInst = subModel.fromOPCUANodes(
            path)  #in line 259, classmethod of 'subModel' exists
        print("2")  #no print out of "2" during tests
        for statement in subModelInst.statements:
            print(statement.Name)
    finally:
        client.disconnect()
        return subModel
コード例 #10
0
 def test_nocrypto(self):
     clt = Client(self.uri_no_crypto)
     clt.connect()
     try:
         clt.get_objects_node().get_children()
     finally:
         clt.disconnect()
コード例 #11
0
ファイル: tools.py プロジェクト: sightmachine/python-opcua
def uaread():
    parser = argparse.ArgumentParser(description="Read attribute of a node, per default reads value of a node")
    add_common_args(parser)
    parser.add_argument("-a",
                        "--attribute",
                        dest="attribute",
                        type=int,
                        default=ua.AttributeIds.Value,
                        help="Set attribute to read")
    parser.add_argument("-t",
                        "--datatype",
                        dest="datatype",
                        default="python",
                        choices=['python', 'variant', 'datavalue'],
                        help="Data type to return")

    args = parse_args(parser, requirenodeid=True)

    client = Client(args.url, timeout=args.timeout)
    client.set_security_string(args.security)
    client.connect()

    try:
        node = get_node(client, args)
        attr = node.get_attribute(args.attribute)
        if args.datatype == "python":
            print(attr.Value.Value)
        elif args.datatype == "variant":
            print(attr.Value)
        else:
            print(attr)
    finally:
        client.disconnect()
    sys.exit(0)
    print(args)
コード例 #12
0
ファイル: tools.py プロジェクト: sightmachine/python-opcua
def uaclient():
    parser = argparse.ArgumentParser(description="Connect to server and start python shell. root and objects nodes are available. Node specificed in command line is available as mynode variable")
    add_common_args(parser)
    parser.add_argument("-c",
                        "--certificate",
                        help="set client certificate")
    parser.add_argument("-k",
                        "--private_key",
                        help="set client private key")
    args = parse_args(parser)

    client = Client(args.url, timeout=args.timeout)
    _configure_client_with_args(client, args)
    if args.certificate:
        client.load_client_certificate(args.certificate)
    if args.private_key:
        client.load_private_key(args.private_key)
    client.connect()
    try:
        root = client.get_root_node()
        objects = client.get_objects_node()
        mynode = get_node(client, args)
        embed()
    finally:
        client.disconnect()
    sys.exit(0)
コード例 #13
0
def uaclient():
    parser = argparse.ArgumentParser(
        description=
        "Connect to server and start python shell. root and objects nodes are available. Node specificed in command line is available as mynode variable"
    )
    add_common_args(parser)
    parser.add_argument("-c", "--certificate", help="set client certificate")
    parser.add_argument("-k", "--private_key", help="set client private key")
    args = parse_args(parser)

    client = Client(args.url, timeout=args.timeout)
    client.set_security_string(args.security)
    if args.certificate:
        client.load_client_certificate(args.certificate)
    if args.private_key:
        client.load_private_key(args.private_key)
    client.connect()
    try:
        root = client.get_root_node()
        objects = client.get_objects_node()
        mynode = get_node(client, args)
        embed()
    finally:
        client.disconnect()
    sys.exit(0)
コード例 #14
0
 def test_find_servers2(self):
     client = Client(self.discovery.endpoint.geturl())
     client.connect()
     try:
         servers = client.find_servers()
         new_app_uri1 = "urn:freeopcua:python:server:test_discovery1"
         self.srv.application_uri = new_app_uri1
         self.srv.register_to_discovery(self.discovery.endpoint.geturl(), period=0)
         new_app_uri2 = "urn:freeopcua:python:test_discovery2"
         self.srv.application_uri = new_app_uri2
         self.srv.register_to_discovery(self.discovery.endpoint.geturl(), period=0)
         time.sleep(0.1) # let server register registration
         new_servers = client.find_servers()
         self.assertEqual(len(new_servers) - len(servers) , 2)
         self.assertFalse(new_app_uri1 in [s.ApplicationUri for s in servers])
         self.assertFalse(new_app_uri2 in [s.ApplicationUri for s in servers])
         self.assertTrue(new_app_uri1 in [s.ApplicationUri for s in new_servers])
         self.assertTrue(new_app_uri2 in [s.ApplicationUri for s in new_servers])
         # now do a query with filer
         new_servers = client.find_servers(["urn:freeopcua:python:server"])
         self.assertEqual(len(new_servers) - len(servers) , 0)
         self.assertTrue(new_app_uri1 in [s.ApplicationUri for s in new_servers])
         self.assertFalse(new_app_uri2 in [s.ApplicationUri for s in new_servers])
         # now do a query with filer
         new_servers = client.find_servers(["urn:freeopcua:python"])
         self.assertEqual(len(new_servers) - len(servers) , 2)
         self.assertTrue(new_app_uri1 in [s.ApplicationUri for s in new_servers])
         self.assertTrue(new_app_uri2 in [s.ApplicationUri for s in new_servers])
     finally:
         client.disconnect()
コード例 #15
0
ファイル: tools.py プロジェクト: kevincolyar/python-opcua
def uaclient():
    parser = argparse.ArgumentParser(description="Connect to server and start python shell. root and objects nodes are available. Node specificed in command line is available as mynode variable")
    add_common_args(parser)
    parser.add_argument("-c",
                        "--certificate",
                        help="set client certificate")
    parser.add_argument("-k",
                        "--private_key",
                        help="set client private key")
    args = parser.parse_args()
    logging.basicConfig(format="%(levelname)s: %(message)s", level=getattr(logging, args.loglevel))

    client = Client(args.url, timeout=args.timeout)
    client.connect()
    if args.certificate:
        client.load_certificate(args.certificate)
    if args.private_key:
        client.load_certificate(args.private_key)
    try:
        root = client.get_root_node()
        objects = client.get_objects_node()
        mynode = client.get_node(args.nodeid)
        if args.path:
            mynode = mynode.get_child(args.path.split(","))
        embed()
    finally:
        client.disconnect()
    sys.exit(0)
コード例 #16
0
ファイル: tools.py プロジェクト: kevincolyar/python-opcua
def uahistoryread():
    parser = argparse.ArgumentParser(description="Read history of a node")
    add_common_args(parser)
    parser.add_argument("--starttime",
                        default="",
                        help="Start time, formatted as YYYY-MM-DD [HH:MM[:SS]]. Default: current time")
    parser.add_argument("--endtime",
                        default="",
                        help="End time, formatted as YYYY-MM-DD [HH:MM[:SS]]. Default: current time")

    args = parser.parse_args()
    if args.nodeid == "i=84" and args.path == "":
        parser.print_usage()
        print("uahistoryread: error: A NodeId or BrowsePath is required")
        sys.exit(1)
    logging.basicConfig(format="%(levelname)s: %(message)s", level=getattr(logging, args.loglevel))

    client = Client(args.url, timeout=args.timeout)
    client.connect()
    try:
        node = client.get_node(args.nodeid)
        if args.path:
            node = node.get_child(args.path.split(","))
        starttime = str_to_datetime(args.starttime)
        endtime = str_to_datetime(args.endtime)
        print("Reading raw history of node {} at {}; start at {}, end at {}\n".format(node, args.url, starttime, endtime))
        print_history(node.read_raw_history(starttime, endtime))
    finally:
        client.disconnect()
    sys.exit(0)
コード例 #17
0
def uahistoryread():
    parser = argparse.ArgumentParser(description="Read history of a node")
    add_common_args(parser)
    parser.add_argument(
        "--starttime", default="", help="Start time, formatted as YYYY-MM-DD [HH:MM[:SS]]. Default: current time"
    )
    parser.add_argument(
        "--endtime", default="", help="End time, formatted as YYYY-MM-DD [HH:MM[:SS]]. Default: current time"
    )

    args = parse_args(parser, requirenodeid=True)

    client = Client(args.url, timeout=args.timeout)
    client.set_security_string(args.security)
    client.connect()
    try:
        node = get_node(client, args)
        starttime = str_to_datetime(args.starttime)
        endtime = str_to_datetime(args.endtime)
        print(
            "Reading raw history of node {} at {}; start at {}, end at {}\n".format(node, args.url, starttime, endtime)
        )
        print_history(node.read_raw_history(starttime, endtime))
    finally:
        client.disconnect()
    sys.exit(0)
コード例 #18
0
ファイル: tools.py プロジェクト: kevincolyar/python-opcua
def uasubscribe():
    parser = argparse.ArgumentParser(description="Subscribe to a node and print results")
    add_common_args(parser)
    parser.add_argument("-t",
                        "--eventtype",
                        dest="eventtype",
                        default="datachange",
                        choices=['datachange', 'event'],
                        help="Event type to subscribe to")

    args = parser.parse_args()
    if args.nodeid == "i=84" and args.path == "":
        parser.print_usage()
        print("uaread: error: The NodeId or BrowsePath of a variable is required")
        sys.exit(1)
    logging.basicConfig(format="%(levelname)s: %(message)s", level=getattr(logging, args.loglevel))

    client = Client(args.url, timeout=args.timeout)
    client.connect()
    try:
        node = client.get_node(args.nodeid)
        if args.path:
            node = node.get_child(args.path.split(","))
        handler = SubHandler()
        sub = client.create_subscription(500, handler)
        if args.eventtype == "datachange":
            sub.subscribe_data_change(node)
        else:
            sub.subscribe_events(node)
        embed()
    finally:
        client.disconnect()
    sys.exit(0)
    print(args)
コード例 #19
0
    def start_loop(self):
        interrupted = False
        while not interrupted:
            client_sigshelf_server = None
            try:
                client_sigshelf_server = Client(CLIENT_SIGSHELF_SERVER)
                client_sigshelf_server.connect()
                self.root_sig_shelf = client_sigshelf_server.get_root_node()
                logger.info("Started Sigmatek Shelf loop")
                while True:
                    self.fetch_shelf_data()
                    time.sleep(INTERVAL)

            except KeyboardInterrupt:
                logger.info("KeyboardInterrupt, gracefully closing")
                if client_sigshelf_server:
                    client_sigshelf_server.disconnect()
                pr_client.disconnect()
                interrupted = True

            except Exception as e:
                logger.warning(
                    "Exception Sigmatek Shelf loop, Reconnecting in 60 seconds: {}"
                    .format(e))
                time.sleep(60)
コード例 #20
0
    def start_loop(self):
        interrupted = False
        while not interrupted:
            client_sigvib_server = None
            try:
                client_sigvib_server = Client(CLIENT_SIGVIB_SERVER)
                client_sigvib_server.connect()
                self.root_sig_vib = client_sigvib_server.get_root_node()
                logger.info("Started Sigmatek Vibration loop")
                while True:
                    # Send vibration if timeout is reached or difference exceeds 0.005m/s
                    self.fetch_vibration_x()
                    self.fetch_vibration_y()
                    time.sleep(INTERVAL)

            except KeyboardInterrupt:
                logger.info("KeyboardInterrupt, gracefully closing")
                if client_sigvib_server:
                    client_sigvib_server.disconnect()
                pr_client.disconnect()
                interrupted = True

            except Exception as e:
                logger.warning(
                    "Exception Sigmatek Vibration loop, Reconnecting in 60 seconds: {}"
                    .format(e))
                time.sleep(60)
コード例 #21
0
    def start_loop(self):
        interrupted = False
        while not interrupted:
            client_pixtend_server = None
            try:
                client_pixtend_server = Client(CLIENT_PIXTEND_SERVER)
                client_pixtend_server.connect()
                self.root_pixtend = client_pixtend_server.get_root_node()
                logger.info("Started PiXtend loop")

                while True:
                    # upsert_panda_state()
                    self.fetch_conbelt_state()
                    self.fetch_conbelt_dist()
                    # self.fetch_light_state() #TODO doesn't work right now
                    # self.fetch_belt_state()  #TODO what is that metric?
                    time.sleep(INTERVAL)
            except KeyboardInterrupt:
                logger.info("KeyboardInterrupt, gracefully closing")
                if client_pixtend_server:
                    client_pixtend_server.disconnect()
                pr_client.disconnect()
                interrupted = True

            except Exception as e:
                logger.warning(
                    "Exception PiXtend loop, Reconnecting in 60 seconds: {}".
                    format(e))
                time.sleep(60)
コード例 #22
0
 def test_nocrypto(self):
     clt = Client(self.uri_no_crypto)
     clt.connect()
     try:
         clt.get_objects_node().get_children()
     finally:
         clt.disconnect()
コード例 #23
0
def cambiar_valor(server,nodo,tiemp,TFD,TFRS,RGTFD,RGTFRS,RGRS,RT,SP,EC,EE,logger):
  client = Client(server)
  try:
      client.connect()#conecta el servidor
      var=client.get_node("ns=1;s="+nodo)#se obtiene el primer nodo
      variable2=var.get_children()
      tamano=np.size(variable2)
      datetime_object = datetime.strptime(tiemp, '%d/%m/%Y %H:%M:%S')
      if tamano>0:
        variable2[0].set_value(datetime_object)
        variable2[1].set_value(TFD)
        variable2[2].set_value(TFRS)
        variable2[3].set_value(RGTFD)
        variable2[4].set_value(RGTFRS)
        variable2[5].set_value(RGRS)
        variable2[6].set_value(RT)
        variable2[7].set_value(SP)
        variable2[8].set_value(EC)
        variable2[9].set_value(EE)
      else:
        logger.warning("No se encuentra el nodo en el servidor opc")
      
      client.disconnect()
  
  except: 
      logger.error("No se puede conectar con el servidor opc")
コード例 #24
0
ファイル: tools.py プロジェクト: billtsay/win-demo-opcua
def uasubscribe():
    parser = argparse.ArgumentParser(description="Subscribe to a node and print results")
    add_common_args(parser)
    parser.add_argument("-t",
                        "--eventtype",
                        dest="eventtype",
                        default="datachange",
                        choices=['datachange', 'event'],
                        help="Event type to subscribe to")

    args = parse_args(parser, requirenodeid=False)
    if args.eventtype == "datachange":
        _require_nodeid(parser, args)
    else:
        # FIXME: this is broken, someone may have written i=84 on purpose
        if args.nodeid == "i=84" and args.path == "":
            args.nodeid = "i=2253"

    client = Client(args.url, timeout=args.timeout)
    client.set_security_string(args.security)
    client.connect()
    try:
        node = get_node(client, args)
        handler = SubHandler()
        sub = client.create_subscription(500, handler)
        if args.eventtype == "datachange":
            sub.subscribe_data_change(node)
        else:
            sub.subscribe_events(node)
        embed()
    finally:
        client.disconnect()
    sys.exit(0)
    print(args)
コード例 #25
0
def run():
    configs = get_configs()
    
    patterns = configs["measures"].split(":")
    tout = configs["connection_timeout"].strip()
    timeout = 1 if len(tout) <= 0 else int(tout)

    client = Client(configs["connection"], timeout=timeout)
    
    try:
        client.connect()
        measures = []
        root = client.get_root_node()
        collect_measures(measures, patterns, root)
        
        for x in root.get_children():
            print x.get_browse_name().Name
            
        for m in measures:
            print m
            
        time.sleep(30)
    except Exception as ex:
        print ex
    finally:
        client.disconnect()
コード例 #26
0
ファイル: test_server.py プロジェクト: vmatutea/python-opcua
 def wrapper(self):
     try:
         client = Client(URL)
         client.connect()
         func(self, client)
     finally:
         client.disconnect()
コード例 #27
0
ファイル: tests.py プロジェクト: tander67/python-opcua
class TestClient(unittest.TestCase, CommonTests):
    '''
    Run common tests on client side
    Of course we need a server so we start a server in another 
    process using python Process module
    Tests that can only be run on client side must be defined here
    '''
    @classmethod
    def setUpClass(self):
        # start our own server
        self.srv = Server() 
        self.srv.set_endpoint('opc.tcp://localhost:%d' % port_num1)
        add_server_methods(self.srv)
        self.srv.start()

        # start client
        self.clt = Client('opc.tcp://localhost:%d' % port_num1)
        self.clt.connect()
        self.opc = self.clt

    @classmethod
    def tearDownClass(self):
        self.clt.disconnect()
        # stop the server in its own process
        self.srv.stop()

    def test_service_fault(self):
        request = ua.ReadRequest()
        request.TypeId = ua.FourByteNodeId(999) # bad type!
        with self.assertRaises(Exception):
            self.clt.bclient._send_request(request)
コード例 #28
0
def main():
    client = Client("opc.tcp://localhost:4840/freeopcua/server/")

    try:
        client.connect()

        # Client has a few methods to get proxy to UA nodes that should always be in address space such as Root or Objects
        root = client.get_root_node()
        print("Objects node is: ", root)
        print("Children of root are: ", root.get_children())

        msclt = SubHandler()
        sub = client.create_subscription(100, msclt)

        ## subscribe to events
        myevent = root.get_child(
            ["0:Types", "0:EventTypes", "0:BaseEventType", "2:ThresholdEvent"])
        print("MyFirstEventType is: ", myevent)
        handle = sub.subscribe_events(obj, myevent)

        myevent2 = root.get_child(
            ["0:Types", "0:EventTypes", "0:BaseEventType"])
        print("MyFirstEventType is: ", myevent2)
        handle = sub.subscribe_events(obj, myevent2)

        while True:
            sleep(0.1)

        sub.unsubscribe(handle)
        sub.delete()
    finally:
        client.disconnect()
コード例 #29
0
ファイル: tools.py プロジェクト: plieningerweb/python-opcua
def uals():
    parser = argparse.ArgumentParser(description="Browse OPC-UA node and print result")
    add_common_args(parser)
    parser.add_argument("-l",
                        dest="long_format",
                        const=3,
                        nargs="?",
                        type=int,
                        help="use a long listing format")
    parser.add_argument("-d",
                        "--depth",
                        default=1,
                        type=int,
                        help="Browse depth")

    args = parse_args(parser)
    if args.long_format is None:
        args.long_format = 1

    client = Client(args.url, timeout=args.timeout)
    client.set_security_string(args.security)
    client.connect()
    try:
        node = get_node(client, args)
        print("Browsing node {} at {}\n".format(node, args.url))
        if args.long_format == 0:
            _lsprint_0(node, args.depth - 1)
        elif args.long_format == 1:
            _lsprint_1(node, args.depth - 1)
        else:
            _lsprint_long(node, args.depth - 1)
    finally:
        client.disconnect()
    sys.exit(0)
    print(args)
コード例 #30
0
ファイル: tools.py プロジェクト: sightmachine/python-opcua
def uals():
    parser = argparse.ArgumentParser(description="Browse OPC-UA node and print result")
    add_common_args(parser)
    parser.add_argument("-l",
                        dest="long_format",
                        const=3,
                        nargs="?",
                        type=int,
                        help="use a long listing format")
    parser.add_argument("-d",
                        "--depth",
                        default=1,
                        type=int,
                        help="Browse depth")

    args = parse_args(parser)
    if args.long_format is None:
        args.long_format = 1

    client = Client(args.url, timeout=args.timeout)
    _configure_client_with_args(client, args)
    client.connect()
    try:
        node = get_node(client, args)
        print("Browsing node {0} at {1}\n".format(node, args.url))
        if args.long_format == 0:
            _lsprint_0(node, args.depth - 1)
        elif args.long_format == 1:
            _lsprint_1(node, args.depth - 1)
        else:
            _lsprint_long(node, args.depth - 1)
    finally:
        client.disconnect()
    sys.exit(0)
    print(args)
コード例 #31
0
ファイル: tools.py プロジェクト: plieningerweb/python-opcua
def uaread():
    parser = argparse.ArgumentParser(description="Read attribute of a node, per default reads value of a node")
    add_common_args(parser)
    parser.add_argument("-a",
                        "--attribute",
                        dest="attribute",
                        type=int,
                        default=ua.AttributeIds.Value,
                        help="Set attribute to read")
    parser.add_argument("-t",
                        "--datatype",
                        dest="datatype",
                        default="python",
                        choices=['python', 'variant', 'datavalue'],
                        help="Data type to return")

    args = parse_args(parser, requirenodeid=True)

    client = Client(args.url, timeout=args.timeout)
    client.set_security_string(args.security)
    client.connect()
    try:
        node = get_node(client, args)
        attr = node.get_attribute(args.attribute)
        if args.datatype == "python":
            print(attr.Value.Value)
        elif args.datatype == "variant":
            print(attr.Value)
        else:
            print(attr)
    finally:
        client.disconnect()
    sys.exit(0)
    print(args)
コード例 #32
0
ファイル: aas.py プロジェクト: yjy1120/openAAS_workshop
def getSubModel(endpointStr, subModel_NodeId):

    client = Client(endpointStr)
    try:
        client.connect()
        #    nsarray = client.get_node(ua.NodeId(2255, 0))
        #    nsList = nsarray.get_value()
        #    i=-1
        #    for entry in nsList:
        #     i = i + 1

        #      if entry == "http://acplt.org/openaas/":
        #        nsopenaas_subModelType = i
        #
        #        break
        #    if i!= -1:
        #      print("Looking for AAS at entry point %s,%s" % (subModel_NodeId))

        path = client.get_node(subModel_NodeId)
        print("path is %s" % path)
        subModelInst = subModel.fromOPCUANodes(node=path)
        for pvsContainer in subModelInst.PropertyValueStatementContainers:
            print(pvsContainer.Name)
    finally:
        client.disconnect()
        return subModel
コード例 #33
0
ファイル: aas.py プロジェクト: yjy1120/openAAS_workshop
def getPVSL(endpointStr, listId):

    client = Client(endpointStr)
    pvsl = None
    try:
        client.connect()
        nsarray = client.get_node(ua.NodeId(2255, 0))
        nsList = nsarray.get_value()
        i = -1
        for entry in nsList:
            i = i + 1
            if entry == "http://acplt.org/propertyValueStatement/Ov":
                #print(entry)
                nsopenaas_propertyValueStatement = i
                break
        if i != -1:
            entryPoint = listId
            print("Looking for AAS at entry point %s,%s" %
                  (nsopenaas_propertyValueStatement, listId))
            path = client.get_node(
                ua.NodeId(entryPoint, nsopenaas_propertyValueStatement))
            pvsl = propertyValueStatementContainer.fromOPCUANodes(path)
            for statement in pvsl.statements:
                print(statement.Name)
    finally:
        client.disconnect()
        return pvsl
コード例 #34
0
 def test_anonymous_rejection(self):
     # FIXME: how to make it fail???
     clt = Client(self.uri_crypto_no_anoymous)
     with self.assertRaises(ua.UaError) as exc_info:
         clt.connect()
         clt.disconnect()
     assert ua.StatusCodes.BadIdentityTokenRejected == exc_info.type.code
コード例 #35
0
def uageneratestructs():
    parser = argparse.ArgumentParser(
        description=
        "Generate a Python module from the xml structure definition (.bsd)")
    add_common_args(parser, require_node=True)
    parser.add_argument(
        "-o",
        "--output",
        dest="output_path",
        required=True,
        type=str,
        default=None,
        help="The python file to be generated.",
    )
    args = parse_args(parser, requirenodeid=True)

    client = Client(args.url, timeout=args.timeout)
    client.set_security_string(args.security)
    client.connect()
    try:
        node = get_node(client, args)
        generators, _ = client.load_type_definitions([node])
        generators[0].save_to_file(args.output_path, True)
    finally:
        client.disconnect()
    sys.exit(0)
コード例 #36
0
 def wrapper(self):
     try:
         client = Client(URL)
         client.connect()
         func(self, client)
     finally:
         client.disconnect()
コード例 #37
0
ファイル: tests_server.py プロジェクト: Joy963/python-opcua
 def test_find_servers2(self):
     client = Client(self.discovery.endpoint.geturl())
     client.connect()
     try:
         servers = client.find_servers()
         new_app_uri1 = "urn:freeopcua:python:server:test_discovery1"
         self.srv.application_uri = new_app_uri1
         self.srv.register_to_discovery(self.discovery.endpoint.geturl(), period=0)
         new_app_uri2 = "urn:freeopcua:python:test_discovery2"
         self.srv.application_uri = new_app_uri2
         self.srv.register_to_discovery(self.discovery.endpoint.geturl(), period=0)
         time.sleep(0.1) # let server register registration
         new_servers = client.find_servers()
         self.assertEqual(len(new_servers) - len(servers) , 2)
         self.assertFalse(new_app_uri1 in [s.ApplicationUri for s in servers])
         self.assertFalse(new_app_uri2 in [s.ApplicationUri for s in servers])
         self.assertTrue(new_app_uri1 in [s.ApplicationUri for s in new_servers])
         self.assertTrue(new_app_uri2 in [s.ApplicationUri for s in new_servers])
         # now do a query with filer
         new_servers = client.find_servers(["urn:freeopcua:python:server"])
         self.assertEqual(len(new_servers) - len(servers) , 0)
         self.assertTrue(new_app_uri1 in [s.ApplicationUri for s in new_servers])
         self.assertFalse(new_app_uri2 in [s.ApplicationUri for s in new_servers])
         # now do a query with filer
         new_servers = client.find_servers(["urn:freeopcua:python"])
         self.assertEqual(len(new_servers) - len(servers) , 2)
         self.assertTrue(new_app_uri1 in [s.ApplicationUri for s in new_servers])
         self.assertTrue(new_app_uri2 in [s.ApplicationUri for s in new_servers])
     finally:
         client.disconnect()
コード例 #38
0
 def test_get_endpointr(self):
     client = Client("opc.tcp://" + os.environ['TEST_IP'] + ":" +
                     os.environ['TEST_PORT'])
     client.connect()
     endpoints = client.get_endpoints()
     print(endpoints)
     client.disconnect()
コード例 #39
0
 def test_basic256sha256_longkey(self):
     clt = Client(self.uri_crypto2)
     try:
         clt.set_security_string("Basic256Sha256,Sign,../examples/certificate-example.der,../examples/private-key-example.pem")
         clt.connect()
         self.assertTrue(clt.get_objects_node().get_children())
     finally:
         clt.disconnect()
コード例 #40
0
 def test_basic128Rsa15_encrypt(self):
     clt = Client(self.uri_crypto)
     try:
         clt.set_security_string("Basic128Rsa15,SignAndEncrypt,examples/certificate-example.der,examples/private-key-example.pem")
         clt.connect()
         self.assertTrue(clt.get_objects_node().get_children())
     finally:
         clt.disconnect()
コード例 #41
0
 def test_basic256(self):
     client = Client("opc.tcp://" + os.environ['TEST_IP'] + ":" +
                     os.environ['TEST_PORT'])
     client.application_uri = "urn:127.0.0.1:ASNeG:FTestClient"
     client.set_security_string(
         "Basic128Rsa15,SignAndEncrypt,FTestClient.der,FTestClient.pem")
     client.connect()
     client.disconnect()
コード例 #42
0
def main(server_url, tag_id):
    client = Client(server_url)
    client.connect()

    node = client.get_node(tag_id)
    print(node)
    print(node.get_value())
    client.disconnect()
コード例 #43
0
 def test_basic256(self):
     clt = Client(self.uri_crypto)
     try:
         clt.set_security_string("Basic256,Sign,examples/example-certificate.der,examples/example-private-key.pem")
         clt.connect()
         self.assertTrue(clt.get_objects_node().get_children())
     finally:
         clt.disconnect()
コード例 #44
0
class TestBrowse(WebGatewayTestCase):
    def setUp(self):
        WebGatewayTestCase.setUp(self)

        self.opcua_client = Client(self.OPC_SERVER_URL)
        self.opcua_client.connect()

    def tearDown(self):

        self.opcua_client.disconnect()

        WebGatewayTestCase.tearDown(self)

    def test_browse_request(self):
        #
        # send browse request to the opc ua server
        #
        req = {
            "Header": {
                "MessageType": "GW_BrowseRequest",
                "ClientHandle": "client-handle",
                "SessionId": self.sessionId
            },
            "Body": {
                "RequestedMaxReferencesPerNode":
                "100",
                "NodesToBrowse": [{
                    "NodeId": {
                        "Namespace": "0",
                        "Id": "85"
                    },
                    "ReferenceTypeId": {
                        "Namespace": "0",
                        "Id": "33"
                    },
                    "BrowseDirection": "0",
                    "IncludeSubtypes": "TRUE",
                    "NodeClassMask": "16",
                    "ResultMask": "63"
                }]
            }
        }

        print("SEND: ", json.dumps(req, indent=4))
        self.ws.send(json.dumps(req))

        #
        # receive browse response from the opc ua server
        #
        str = self.ws.recv()
        print("RECV: ", str)
        res = json.loads(str)
        self.assertEqual(res['Header']['MessageType'], "GW_BrowseResponse")
        self.assertEqual(res['Header']['ClientHandle'], "client-handle")
        self.assertEqual(res['Header']['SessionId'], self.sessionId)
        self.assertEqual(res['Header']['StatusCode'], "0")
コード例 #45
0
class HelloClient:
    def __init__(self, endpoint):
        self.client = Client(endpoint)

    def __enter__(self):
        self.client.connect()
        return self.client

    def __exit__(self, exc_type, exc_val, exc_tb):
        self.client.disconnect()
コード例 #46
0
 def test_basic128Rsa15_encrypt(self):
     clt = Client(self.uri_crypto)
     try:
         clt.set_security_string(
             "Basic128Rsa15,SignAndEncrypt,examples/certificate-example.der,examples/private-key-example.pem"
         )
         clt.connect()
         self.assertTrue(clt.get_objects_node().get_children())
     finally:
         clt.disconnect()
コード例 #47
0
ファイル: simple.py プロジェクト: dejaniraai/packml
class HelloClient:
    def __init__(self, endpoint):
        self.client = Client(endpoint)

    def __enter__(self):
        self.client.connect()
        return self.client

    def __exit__(self, exc_type, exc_val, exc_tb):
        self.client.disconnect()