freeopcua / python-opcua Goto Github PK
View Code? Open in Web Editor NEWLGPL Pure Python OPC-UA Client and Server
Home Page: http://freeopcua.github.io/
License: GNU Lesser General Public License v3.0
LGPL Pure Python OPC-UA Client and Server
Home Page: http://freeopcua.github.io/
License: GNU Lesser General Public License v3.0
This bug report is for brainstorming and ideas for better command line after initial work from @alkor
General
uadiscover
uals:
uaread:
uawrite
uasubscribe:
other ideas?
Hi
Just run the below client code connect with kepware server on the server side and restart the server again and again
the below code will handle exceptions
but the application will stuck after some time on
Exception in thread Thread-4:
Traceback (most recent call last):
File "/usr/local/lib/python3.4/threading.py", line 920, in _bootstrap_inner
self.run()
File "/home/kashp/Desktop/pythonopc/pythonopcua2/python-opcua-master/opcua/client.py", line 40, in run
self.client.open_secure_channel(renew=True)
File "/home/kashp/Desktop/pythonopc/pythonopcua2/python-opcua-master/opcua/client.py", line 145, in open_secure_channel
result = self.bclient.open_secure_channel(params)
File "/home/kashp/Desktop/pythonopc/pythonopcua2/python-opcua-master/opcua/binary_client.py", line 202, in open_secure_channel
self._write_socket(hdr, asymhdr, seqhdr, request)
File "/home/kashp/Desktop/pythonopc/pythonopcua2/python-opcua-master/opcua/binary_client.py", line 141, in _write_socket
self._socket.write(alle)
File "/home/kashp/Desktop/pythonopc/pythonopcua2/python-opcua-master/opcua/utils.py", line 88, in write
self.socket.sendall(data)
BrokenPipeError: [Errno 32] Broken pipe
In utils.py at line 88 i also tried to put exception even after exception the application is hang
Please help me with this issue
def client_connect():
try:
global client
client = Client("opc.tcp://192.168.190.129:49320")
client.connect()
root = client.get_root_node()
global state
state = root.get_child(["0:Objects", "2:Simulation.Warehouse.Scanner.PKG_W_DATA[1,1]" ])
global fast
fast = root.get_child(["Objects", "2:Simulation.Warehouse.Scanner.PKG_C_DATA[1,1]"])
handler = SubHandler()
f = open('check1.txt','w')
sub = client.create_subscription(100, handler)
sub2 = client.create_subscription(100, handler)
handle = sub.subscribe_data_change(state)
handle2 = sub.subscribe_data_change(fast)
except socket.error as e:
if client.keepalive != None:
print ("stopping client")
client.keepalive.stop()
print ("Server Seems to be Down Retrying.......", e)
time.sleep (5)
main_fun()
except socket.timeout:
print("time out error")
main_fun()
def main_fun():
client_connect()
count=1
while(1):
#f.write('gin lo ji %s \n '%count)
#f.flush()
dv_id = ua.DataValue(ua.Variant(randint(1,10000), ua.VariantType.UInt16))
dv_data = ua.DataValue(ua.Variant(randint(1,10000), ua.VariantType.UInt16))
try:
state.set_value(dv_id)
fast.set_value(dv_data)
print (state.get_value(),fast.get_value())
except Exception as e:
print ("teste", e)
if client.keepalive != None:
print ("stopping client")
client.keepalive.stop()
print("unable to read")
time.sleep (5)
client_connect()
print ("count",count)
count=count+1
time.sleep(2)
main_fun()
Hello. thank you for python-opcua
MatrikonOPC Server for Simulation is Run in windows2003
python-opc is client that Run in linux
the windows2003 ip is 192.168.1.110. MatrikonOPC Server for Simulation Server Name is Matrikon.OPC.Simulation.1 and the windows2003 user is OPCTest password OPC
I'm using Code in example-client.py
if name == "main":
logging.basicConfig(level=logging.WARN)
#logger = logging.getLogger("KeepAlive")
#logger.setLevel(logging.DEBUG)
client = Client("opc.tcp://[email protected]:135/Matrikon.OPC.Simulation.1")
#client = Client("opc.tcp://localhost:4841/freeopcua/server/")
# client = Client("opc.tcp://admin@localhost:4841/freeopcua/server/") #connect using a user
try:
client.connect()
but connect fail ,how can I to do
Hi,
I'm using this "http://open62541.org/" opcua server running on my pc.
Right after i connect to the server, i'm getting this exception:
Exception in thread Thread-2:
Traceback (most recent call last):
File "/usr/lib/python2.7/threading.py", line 810, in bootstrap_inner
self.run()
File "/usr/lib/python2.7/site-packages/opcua/client.py", line 41, in run
val = server_state.get_value()
File "/usr/lib/python2.7/site-packages/opcua/node.py", line 168, in get_value
result = self.get_data_value()
File "/usr/lib/python2.7/site-packages/opcua/node.py", line 177, in get_data_value
return self.get_attribute(ua.AttributeIds.Value)
File "/usr/lib/python2.7/site-packages/opcua/node.py", line 234, in get_attribute
result = self.server.read(params)
File "/usr/lib/python2.7/site-packages/opcua/binary_client.py", line 317, in read
response = ua.ReadResponse.from_binary(data)
File "/usr/lib/python2.7/site-packages/opcua/uaprotocol_auto.py", line 6689, in from_binary
obj.Results.append(DataValue.from_binary(data))
File "/usr/lib/python2.7/site-packages/opcua/uatypes.py", line 858, in from_binary
obj.Value = Variant.from_binary(data)
File "/usr/lib/python2.7/site-packages/opcua/uatypes.py", line 782, in from_binary
obj.VariantType = VariantType(val)
File "/usr/lib/python2.7/site-packages/enum-0.4.4-py2.7.egg/enum.py", line 197, in __init
raise EnumBadKeyError(key)
EnumBadKeyError: Enumeration keys must be strings: 6
This is probably usefull in many situations.
Maybe the best solution is to make get_attribute method return DataValue instead of python object.
And convert to python object in all the helper methods: get_value, get_browse_name, etc...
Hi,
So I'm trying to to subscribe to a node against an OPC UA server hosted by Ignition (https://inductiveautomation.com/products/ignitionopc/overview) and I'm getting a problem. I can get nodes, get names, values, and children from nodes without any problem. But as soon as I try to subscribe to a node, I get this problem:
exception calling callback for <Future at 0x178e250 state=finished returned Buffer>
Traceback (most recent call last):
File "/opt/osprey/VENV/local/lib/python2.7/site-packages/concurrent/futures/_base.py", line 298, in _invoke_callbacks
callback(self)
File "/opt/python-opcua/opcua/binary_client.py", line 332, in _call_publish_callback
response = ua.PublishResponse.from_binary(future.result())
File "/opt/python-opcua/opcua/uaprotocol_auto.py", line 10443, in from_binary
obj.Parameters = PublishResult.from_binary(data)
File "/opt/python-opcua/opcua/uaprotocol_auto.py", line 10383, in from_binary
obj.SubscriptionId = unpack_uatype('UInt32', data)
File "/opt/python-opcua/opcua/uatypes.py", line 134, in unpack_uatype
return struct.unpack(fmt, data.read(size))[0]
File "/opt/python-opcua/opcua/utils.py", line 39, in read
raise Exception("No enough data left in buffer, request for {}, we have {}".format(size, self))
Exception: No enough data left in buffer, request for 4, we have Buffer(size:0, data:)
After doing some digging, I found:
PublishResponse.from_binary() start:
len(data) at start: 65
len(data) after NodeId: 61
NodeId: NodeId(i=829)
len(data) after ResponseHeader: 37
ResponseHeader: ResponseHeader(Timestamp:2015-09-16 16:03:49.359000, RequestHandle:5, ServiceResult:StatusCode(Good), ServiceDiagnostics:DiagnosticInfo(Encoding:0, SymbolicId:0, NamespaceURI:0, LocalizedText:0, AdditionalInfo:, InnerStatusCode:StatusCode(Good), InnerDiagnosticInfo:None), StringTable:None, AdditionalHeader:ExtensionObject(TypeId:NodeId(i=0), Encoding:0, Body:))
len(data) after PublishResult: 0
Parameters: PublishResult(SubscriptionId:24, AvailableSequenceNumbers:[1], MoreNotifications:True, NotificationMessage:NotificationMessage(SequenceNumber:1, PublishTime:2015-09-16 16:03:49.359000, NotificationData:[]), Results:[], DiagnosticInfos:[])
PublishResponse.from_binary() start:
len(data) at start: 28
len(data) after NodeId: 24
NodeId: NodeId(i=397)
len(data) after ResponseHeader: 0
ResponseHeader: ResponseHeader(Timestamp:2015-09-16 16:03:49.360000, RequestHandle:8, ServiceResult:StatusCode(BadInternalError), ServiceDiagnostics:DiagnosticInfo(Encoding:0, SymbolicId:0, NamespaceURI:0, LocalizedText:0, AdditionalInfo:, InnerStatusCode:StatusCode(Good), InnerDiagnosticInfo:None), StringTable:None, AdditionalHeader:ExtensionObject(TypeId:NodeId(i=0), Encoding:0, Body:))
it's at this point that the error is thrown, as it tries to pull the PublishResult when the size of data is already at 0. When I get the time, I want to make a pull request that logs out some of this information and handles errors a little bit differently.
The error I get from the Ignition console is this:
OPC-UA Server.PublishService Returning ServiceFault for request: [PublishRequest requestHandle=8]. StatusCode=StatusCode[Severity=Bad, Subcode=Bad_InternalError]
java.lang.IllegalArgumentException: fromIndex(0) > toIndex(-1)
at java.util.ArrayList.subListRangeCheck(Unknown Source)
at java.util.ArrayList.subList(Unknown Source)
at com.inductiveautomation.xopc.server.subscriptions.NotificationMessageFactory.createMessageForItems(NotificationMessageFactory.java:118)
at com.inductiveautomation.xopc.server.subscriptions.BaseSubscription.returnNotifications(BaseSubscription.java:583)
at com.inductiveautomation.xopc.server.subscriptions.BaseSubscription.requestReceivedNormal(BaseSubscription.java:453)
at com.inductiveautomation.xopc.server.subscriptions.BaseSubscription.consume(BaseSubscription.java:409)
at com.inductiveautomation.xopc.server.sessions.UaSession.publishRequestReceived(UaSession.java:313)
at com.inductiveautomation.xopc.server.core.services.subscription.PublishService.executeInternal(PublishService.java:38)
at com.inductiveautomation.xopc.server.core.services.subscription.PublishService.executeInternal(PublishService.java:18)
at com.inductiveautomation.xopc.server.core.services.AbstractService.execute(AbstractService.java:53)
at com.inductiveautomation.xopc.server.stack.AbstractUAServer$RequestServer.serveRequest(AbstractUAServer.java:77)
at com.inductiveautomation.xopc.server.stack.AbstractUAServer$RequestServer.run(AbstractUAServer.java:66)
at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
at java.lang.Thread.run(Unknown Source)
This happens very consistently, every time I try to make a subscription. The code I'm using to make a subscription is based on the example client. It looks something like this:
import time
from opcua import Client
class SubHandler(object):
"""
Subscription Handler. To receive events from server for a subscription
"""
def data_change(self, handle, node, val, attr):
print("Python: New data change event", handle, node, val, attr)
def event(self, handle, event):
print("Python: New event", handle, event)
if __name__ == "__main__":
client = Client("opc.tcp://user:[email protected]:4096/")
try:
client.connect()
var = client.get_node("ns=1;s=[Test_Device]_Meta:Ramp/Ramp4")
print(var)
handler = SubHandler()
sub = client.create_subscription(2000, handler)
handle = sub.subscribe_data_change(var)
time.sleep(0.1)
i = 0
timing = 0
while i < 500:
print "i:", i
time.sleep(1)
i += 1
except Exception as e:
import traceback
print traceback.format_exc()
finally:
client.disconnect()
It gets the node just fine, and I can even get_value() from it, but it just can't subscribe, so I'm a bit at a loss on how to proceed. Is this something you have seen? Any suggestions or ideas on how to fix the problem?
When another OPC UA server is the client to python opcua "Strong Typed" variables don't pass validation.
I am using TOP Server OPC UA client to my python OPC UA server and it only adds variables with no ua type.
From the example-server, this will be thrown by TOP Server:
Date Time Level Source Event
10/4/2015 5:09:47 PM Warning OPC UA Client Tag 'myStronglytTypedVariable' on device 'Channel1.Device1' was not imported. The item failed validation.
I don't know what validation is taking place. Is there any way to troubleshoot this?
Edit: I did more research. Oddly enough other clients (such as UaExpert) doesn't have any problems. If I manually add this tag to TOP Server and manually set the data type it also seems to work. It could be a problem with TOP Server object import. If there isn't anything we can do this issue could be closed.
Hello!
Is it possible to detect if the server has been turned off or the connection between the server and client was lost? The only way I found is to subscribe to the server time and use the subscription as "watchdog signal". Is there any way to detect if the session has ended?
I have been testing against two different OPC servers, Kepware and Ignition
from Inductive Automation. I am having issues with both. Sometimes I get a
BadNoMatch error when issuing a get_child command and sometimes it works just
fine. My code is as follows for the ignition server.
""" Testing OPCUA read/write tags """
import opcua
def ignition_test():
""" Run a test against the Ignition server. """
print("Testing Ignition OPC")
client = opcua.Client("opc.tcp://10.9.10.209:4096")
client.connect()
objects = client.get_objects_node()
myval = objects.get_child([
"1:Devices",
"1:[Simulator]",
"1:_Meta:Writeable",
"1:WriteableFloat2"])
before = myval.get_value()
myval.set_value(opcua.ua.Variant([1], opcua.ua.VariantType.Float))
after = myval.get_value()
print(before, after)
client.disconnect()
if __name__ == "__main__":
ignition_test()
Running this gives the following error periodically:
C:\Windows\system32\cmd.exe /c (python opc_test2.py)
Testing Ignition OPC
Traceback (most recent call last):
File "opc_test2.py", line 28, in <module>
ignition_test()
File "opc_test2.py", line 16, in ignition_test
"1:WriteableFloat2"])
File "C:\Python34\lib\site-packages\opcua\node.py", line 285, in get_child
result.StatusCode.check()
File "C:\Python34\lib\site-packages\opcua\uatypes.py", line 249, in check
raise Exception("{}({})".format(self.doc, self.name))
Exception: The requested operation has no match to return.(BadNoMatch)
Any thoughts on what I should be looking into? I am hoping to resolve this
and contribute back.
Thanks
I pushed by mistake a big restructuring to master. hope it does not brake too many things. Let me know if someone has issues or other propositions
Hello and thank you for a create OPC UA Pythono library!
I'm using it on my thesis and I need timestamp data. I have downloaded now the latest version (just minutes ago) but still I can't find proper timestamp records.
I'm using Beckhoff TwinCAT OPC UA Server and so far there have been no issues. I can also get the timestamps as I like to (JSON format):
{
'MAIN.o_bAlarm[0]': {
'timestamp': '2015-07-26 12:35:11.852617',
'value': '0'
},
and so on...
}
Timestamp is current timestamp (when the data has been checked by client), not when the value has been changed.
If I use UaExpert-tool, I can see MAIN.o_bAlarm[0].timestamp is few hours earlier as it should (as I haven't changed the value since that).
Am I doing something wrong or does the code support such a feature at all?
My application has no OPC UA connection all the time, and that's the reason I want to know how long ago these values has been changed.
Best regards,
TeemuV aka dewabe
The website http://freeopcua.github.io/ states LGPL http://freeopcua.github.io/. The python setup.py states GPLv3 https://github.com/FreeOpcUa/python-opcua/search?utf8=%E2%9C%93&q=license.
I would like to use it and happy to contribute back any fixes we find, however, I can't use GPL but can use LGPL.
Are you willing to clarify this?
Best
Hello everyone,
I am currently experiencing weird behaviour concerning the disconnection of a client from a server.
Here is a short description :
OPC-UA server
Running on Ubuntu 14.04 (LTS) (unity DE), 64 bits
Implemented in python using pythin-opcua (https://github.com/FreeOpcUa/python-opcua)
IP address : 144.3.82.70:4841
Server URL : opc.tcp://141.3.82.70:4841/freeopcua/server/
OPC-UA client
Running on Microsoft windows 7 64bits
Implemented in C# using the Unified Automation SDK .net (https://www.unified-automation.com/downloads/opc-ua-development.html)
Ip address : 144.3.82.76
I am unable to disconnect. BUT with Unified Automation's UAexpert, I can connect and disconnect. So I spied with wireshark, and there is actually a difference.
Can you help me?
More data (including the wireshark capture files) can be downloaded here :
https://www.dropbox.com/s/abw8wi7aq8rvz2h/TroublesDisconnectionOpcUa.zip?dl=0
Thanks in advance
Cheers
Boris Bocquet
Application Engineer –Vision & Robotics
AKEO PLUS SAS
Handler is simple but misses some information like timestamp. I am not sure what the api should be.
Currently it is:
class SubHandler(object):
def data_change(self, handle, node, val, attr):
pass
def event(self, handle, event):
print("Python: New event", handle, event)
event interface is good. we can add whatever we want to Event object. but data_change is not extensible...
maybe
def data_change(self, node, val, data):
pass
Hi
I registered almost 300 tags with Kepserver and receiving the continuous value and making separate thread for each received value.
But my system crashed due to below error:
Traceback (most recent call last):
File "/usr/lib/python3.4/threading.py", line 920, in _bootstrap_inner
self.run()
File "./opcua/client.py", line 40, in run
self.client.open_secure_channel(renew=True)
File "./opcua/client.py", line 145, in open_secure_channel
result = self.bclient.open_secure_channel(params)
File "./opcua/binary_client.py", line 203, in open_secure_channel
self._write_socket(hdr, asymhdr, seqhdr, request)
File "./opcua/binary_client.py", line 142, in _write_socket
self._socket.write(alle)
File "./opcua/utils.py", line 88, in write
self.socket.sendall(data)
BrokenPipeError: [Errno 32] Broken pipe
Please help me to handle such cases.
Hi,
I just wanted to set some variables from external application but was getting error regarding access rights. Currently, on creation of variables and properties they are defined to be only read, but what if one would like to write this variables/properties from outside? Should current implementations be extended or there is some other way to set user-rights for every node?
Hello,
I'm working on an analytics program with a "built in" OPC UA server to share the data. The built in server also allows me to adjust variables in the software (via a web based SCADA type GUI).
When I start the server and import all my nodes from XML, everything works good and I can manipulate the variables from the SCADA. However if I close the OPC UA server and start it again, I have to adjust all my variables again, because the XML gets imported again with default values.
What is a good way to store the OPC UA server configuration? I was thinking of "exporting" all the nodes and their values back to XML when the server shuts down. Is this a valid method? Is there some easier way to store my nodes and values?
I'm trying to install python opcua on an Arduino Yun (python 2.7).
When I do this:
pip install -v freeopcua
All dependencies install ok, but when the installation reaches this point:
byte-compiling /usr/lib/python2.7/site-packages/opcua/standard_address_space_part5.py to standard_address_space_part5.pyc
It locks up. When I look at all the other "Standard_Address_Space" files they are very small, but part 5 is large at 1.3mb.
Is part 5 required for the OPCUA server to run? I really want to figure out how to get this installed on my Yun.
http://ulozto.net/xiWcarrj/20151028-servicefault-instead-of-publishresponse-pcapng
password: ua1234
After I delete subscription (I'm doing this before disconnecting client) I can find following exception in log:
2015-10-28 10:11:39,013 - concurrent.futures - ERROR - exception calling callback for <Future at 0x546c870 state=finished returned Buffer>
Traceback (most recent call last):
File "C:\Python27\lib\site-packages\concurrent\futures_base.py", line 298, in _invoke_callbacks
callback(self)
File "C:\Python27\lib\site-packages\opcua\binary_client.py", line 330, in _call_publish_callback
response = ua.PublishResponse.from_binary(future.result())
File "C:\Python27\lib\site-packages\opcua\uaprotocol_auto.py", line 10434, in from_binary
obj.Parameters = PublishResult.from_binary(data)
File "C:\Python27\lib\site-packages\opcua\uaprotocol_auto.py", line 10383, in from_binary
obj.SubscriptionId = unpack_uatype('UInt32', data)
File "C:\Python27\lib\site-packages\opcua\uatypes.py", line 134, in unpack_uatype
return struct.unpack(fmt, data.read(size))[0]
File "C:\Python27\lib\site-packages\opcua\utils.py", line 39, in read
raise Exception("No enough data left in buffer, request for {}, we have {}".format(size, self))
Exception: No enough data left in buffer, request for 4, we have Buffer(size:0, data:)
I doesn't bother me much because it is handled somewhere inside so my app doesn't know about this. That's why I didn't investigate it very much.
I only think that this happens when BinaryClient is expecting PublishResponse but he gets ServiceFault packet.
Here is another capture when I didn't call subscription.delete before client.disconnect:
http://ulozto.net/xDundii7/20151028-servicefault-instead-of-publishresponse-v2-pcapng
I humbly suggest that the message in log could be more accurate. It's not the problem "No enough data left...".
Maybe it is similar to issue #29. (?)
I'm not sure if this is a bug, or I don't understand how the atexit module works.
If you register atexit functions in a program that uses the opc ua server, the atexit functions never get called. Perhaps it's actually an issue with asycnio?
I noticed in log from Kepware OPC Server that when my client app disconnects then session is deleted but SecureChannel isn't closed. I compared it with UaExpert which disconnects from Kepware correctly. I watched into Wireshark that my app is sending CloseSecureChannelRequest with SecurityTokenId = 0 (while eg. in CloseSessionRequest there is SecurityTokenId = 1) and Kepware returns ErrorMessage with BadInvalidArgument.
The following modification of BinaryClient.close_secure_channel()
fixes the problem (inspired from _send_request()
):
#symhdr = ua.SymmetricAlgorithmHeader()
symhdr = self._create_sym_algo_header()
Hey guys,
we got a user who tested our open62541 client with pyhton server (and it did not work).
As far as I see in wireshark, the OpenSecureChannel response is malformed (and our client returns a decode error). However UaExpert seems to ignore this problem and just carries on, however a malformed packet is there.
The wireshark capture can be found here: http://s000.tinyupload.com/index.php?file_id=50188691273227621360 (minimal-server.py server runs on port 16664).
A screenshot is shown below:
Any idea what's the reason?
To be able to debug/test my application base on this stack I would like to call Methods from UaExpert. Usually, UaExpert generates from based on input and output parameters where the values can be entered. With the python-opcua stack this is not the case. In the figure below you can see on the left side multiply method from example server and on the right call of (completely different) method on UA sdk server.
Last two days I am search for solution, I tried add names and descriptions (also play with references) but nothing helped. Somebody has idea?
I finally caught it (I noticed it in issue #47 yesterday):
http://ulozto.net/xWGF411f/test-ua2-zip
password: ua1234
There is a log and pcapng. In log there is interesting time 2015-10-26 08:57:19.983. In pcapng there is interesting time 2063 with filter tcp.stream eq 2
.
I have another things to do today but it seems to me that RequestResponse and OpenSecureChannel have switched SequenceNumber. And Kepware OPC server seems not to like it. I haven't investigate it much yet, but lock is bit different in BinaryClient.open_secure_channel()
than in BinaryClient._send_request()
.
Hi
When Opc server restarted i got the following issue
File "/usr/local/lib/python3.4/concurrent/futures/_base.py", line 297, in _invoke_callbacks
callback(self)
File "/home/kashp/PycharmProjects/gor_flip/opcua/binary_client.py", line 328, in _call_publish_callback
response = ua.PublishResponse.from_binary(future.result())
File "/home/kashp/PycharmProjects/gor_flip/opcua/uaprotocol_auto.py", line 10434, in from_binary
obj.Parameters = PublishResult.from_binary(data)
File "/home/kashp/PycharmProjects/gor_flip/opcua/uaprotocol_auto.py", line 10383, in from_binary
obj.SubscriptionId = unpack_uatype('UInt32', data)
File "/home/kashp/PycharmProjects/gor_flip/opcua/uatypes.py", line 135, in unpack_uatype
return struct.unpack(fmt, data.read(size))[0]
File "/home/kashp/PycharmProjects/gor_flip/opcua/utils.py", line 39, in read
raise Exception("No enough data left in buffer, request for {}, we have {}".format(size, self))
Exception: No enough data left in buffer, request for 4, we have Buffer(size:0, data:b'')
Hi oroulet
I am connecting kepserver with python using python-opcua
I am polling the server for tag value change, Is there any event registration mechanism so that my python function triggered automatically as the tag value will change
Thanks
Hi
Please help me to understand the below issue:
File "/home/kashp/PycharmProjects/gor_flip/opcua/binary_client.py", line 330, in _call_publish_callback
self._publishcallbacksresponse.Parameters.SubscriptionId
File "/home/kashp/PycharmProjects/gor_flip/opcua/subscription.py", line 61, in publish_callback
self._call_datachange(datachange)
File "/home/kashp/PycharmProjects/gor_flip/opcua/subscription.py", line 79, in _call_datachange
data = self._monitoreditems_map[item.ClientHandle]
KeyError: 201
Thanks
Kashp
everything is done apart from default values
Because of the major refactoring, I have not merged the head of master.
TODO:
1, remove KeepAlive thread
2, review security_policy carefully, it may contains race condition
3, attack subscription race condition
Suggestion is welcome.
Not sure what happened but read the docs for python opcua is broken at the moment.
i am trying to communicate with kepserverex and i am trying to set value of tag but getting error
code:
client.connect()
root = client.get_root_node()
state = root.get_child(["0:Objects", "2:Channel1.Device1.Tag1"])
print(state.get_value())
state.set_value(ua.Variant([23], ua.VariantType.Int64))
error:
File "example-client.py", line 51, in
WARNING:opcua.binary_client:Received an error message type
state.set_value(ua.Variant([23], ua.VariantType.Int64))
File "/home/kashp/Desktop/pythonopc/python-opcua-master/opcua/node.py", line 195, in set_value
WARNING:opcua.binary_client:MessageAbort(error:StatusCode(BadInvalidArgument), reason:)
self.set_attribute(ua.AttributeIds.Value, datavalue)
File "/home/kashp/Desktop/pythonopc/python-opcua-master/opcua/node.py", line 214, in set_attribute
result[0].check()
File "/home/kashp/Desktop/pythonopc/python-opcua-master/opcua/uatypes.py", line 249, in check
raise Exception("{}({})".format(self.doc, self.name))
Exception: The server not does support writing the combination of value, status and timestamps provided.(BadWriteNotSupported)
Please help
Looking for help understanding a connection issue.
I am trying to connect to a machine hosted opc ua server using
client = Client("opc.tcp://user:[email protected]:4880/Arburg")
I am getting the following error and am not sure if this is something I am doing or if this is not supported yet.
Traceback (most recent call last):
File "example-client.py", line 41, in
client.connect()
File "C:\opcua\opcua\client.py", line 111, in connect
self.activate_session()
File "C:\opcua\opcua\client.py", line 199, in activate_session
params.UserIdentityToken.Password = bytes(self.server_url.password)
TypeError: string argument without an encoding
WARNING:opcua.binary_client:Received an error message type
WARNING:opcua.binary_client:MessageAbort(error:StatusCode(BadInvalidArgument), reason:)
I went from 0.9.3 to the latest, 0.9.6 (your commit from today). and when my client code hits the opcua import i get an error that the module opcua.user doesn't exist.
I'm very new to python so it could be that I've done something wrong, but when I go back and install 0.9.3 my code runs again.
Edit: Your July 5th commit is also working.
Thanks to @alkor we now have support for encryption in both server and client. The OPC-UA implementation is now quasi complete. There are some shortcuts around, but even the proprietary stacks are not 100% perfect. I am waiting a bit to be sure we catch the most obvious bugs, then I propose to release a 1.0 version.
If someone knowns of are missing big part of the protocol let me know
2.0 will then be released when we support xml protocol, but I currently have no use for it so it will wait for someone motivated. It should not be very hard though...
Hi,
I have problem by writing value in custom server based on UA SDK. I get following error message: The server not does support writing the combination of value, status and timestamps provided.(BadWriteNotSupported). The variable is writeable for sure.
I found a problem and it is in Timestamps, if the booth timestamp (DataValue structure) are set to 0 than works.
Should the user be enable to set custom Timestamp from client API?
I have been trying to trouble shoot this for the last hour or so but I can't figure it out.
If I try to use this XML code with the server import funciton:
<UAVariable NodeId="i=30004" BrowseName="MyXMLVariable" DataType="Float">
<References>
<Reference ReferenceType="HasTypeDefinition">i=69</Reference>
<Reference ReferenceType="Organizes" IsForward="false">i=30001</Reference>
</References>
<Value>
<Float>1.23</Float>
</Value>
</UAVariable>
The node is created, but the value is Null, even though a value is specified. When I step through the code the obj.value is never assigned. If the type is UInt32 it works correctly.
I'm trying to figure out what timezone is being used a server's variables. There appears to be an hour offset but I'm not sure how to change it.
Hello,
As in python isinstance(True,int) == True
, all boolean values passed to a Variant will be converted to Int64 when going through Variant._guess_type at line 741 of python-opcua/opcua/uatypes.py.
Is this wanted to avoid the use of booleans ?
Best,
Maxime
Hi.
I have a .Net Opc Ua server which generates events of SystemEventType.
I have managed to subscribe to the events using a .Net client.
However I cannot do the same using the python client (only the data subscription works).
On the other hand the python client works fine with the example python server.
I have used the subscribe_events function with no arguments and subscribe_events(2253,2130)
Am I doing something wrong?
Thanks
Hi
How to handle OPC server Connection timeout while reading tags ore creating connections.
What are the different exceptions raised for different error.
I'm trying program a subscription handler to read the attribute on a separate node (separate from node the subscription is set on), but it hangs when the get_value function is called.
For example, I can successfully create a subscription handler for node (say Node A), and I can run a print command on data_change just like in the sample program. But when I add a line to the handler to read of the attribute of a separate node (Node B), and rerun it, the program hangs.
It looks like it is hanging when BinaryClient._send_request is calling future.result because the state is "PENDING". When I ran it through PyCharm's debugger, the last line of opcua code that runs (before it hangs) is line 62 in binary_client.py.
If I remove the two node_b lines, it works, but with them in it just hangs:
from opcua import ua, Client
class SubHandler(object):
def data_change(self, handle, node, val, attr):
print("Python: New data change event", handle, node, val, attr)
node_b_path = ['Objects', '164 Zone 2', '164-24', 'Global', 'Part_1_Print_Label']
node_b_value = root.get_child(node_b_path).get_value()
client = Client("opc.tcp://internal-kepserver:49320")
client.connect()
root = client.get_root_node()
handler = SubHandler()
sub = client.create_subscription(500, handler)
node_a_path = ['Objects', '164 Zone 2', '164-24', 'Global', 'Part_1_Rack_Count_Temp']
node_a = root.get_child(node_a_path)
sub_handle = sub.subscribe_data_change(node_a)
variables should be read-only by default
add a method set_read_only to Node
All calls go through a session object. this is done to be able to add user
management later. I propose to add a constructor parameter to Session
called for example access_rigths.
in InternalServer an internal session is created, create the session using
for example access_right="admin" (or better use an enum)
then then pass access_rigths to set_attribute_value and in method do a test:
def set_attribute_value(self, nodeid, attr, value, access_right = "user")
...
if access_right != "admin":
check_access
...
There appears to be alarms with and without nodes, I only see examples of how to deal with node alarms in PyUAF's "easiest client tutorial". Is there a method to dealing with alarms without nodes?
Thanks!
In my client app I connect to Kepware OPC server, then I create one subscription and dozens of "monitored items". I don't know why, but some calls of subscribe_data_change()
end with TimeoutError exception (in Wireshark seems everything good), but never mind. Worse is, that shortly after this error I get following exception:
Traceback (most recent call last):
File "C:\Python27\lib\site-packages\opcua\binary_client.py", line 331, in _call_publish_callback
self._publishcallbacks[response.Parameters.SubscriptionId](response.Parameters)
File "C:\Python27\lib\site-packages\opcua\subscription.py", line 61, in publish_callback
self._call_datachange(datachange)
File "C:\Python27\lib\site-packages\opcua\subscription.py", line 82, in _call_datachange
data = self._monitoreditems_map[item.ClientHandle]
KeyError: 205
And after second occurence of this exception I stop getting new data change callbacks.
My amateur explanation is following:
In Subscription.__init__()
is twice called BinaryClient.publish()
which after receiving callback calls _call_publish_callback()
and this calls Subscription.publish_callback()
.
Exception in Subscription._call_datachange()
stops correct finnishing of Subscription.publish_callback()
, which means that next BinaryClient.publish()
isn't called.
And when this happens twice, then there is nobody sending PublishRequests.
And my amateur fix of this issue is to wrap part of code in try/except:
def publish_callback(self, publishresult):
self.logger.info("Publish callback called with result: %s", publishresult)
while self.subscription_id is None:
time.sleep(0.01)
try:
for notif in publishresult.NotificationMessage.NotificationData:
if notif.TypeId == ua.FourByteNodeId(ua.ObjectIds.DataChangeNotification_Encoding_DefaultBinary):
datachange = ua.DataChangeNotification.from_binary(io.BytesIO(notif.to_binary()))
self._call_datachange(datachange)
elif notif.TypeId == ua.FourByteNodeId(ua.ObjectIds.EventNotificationList_Encoding_DefaultBinary):
eventlist = ua.EventNotificationList.from_binary(io.BytesIO(notif.to_binary()))
self._call_event(eventlist)
elif notif.TypeId == ua.FourByteNodeId(ua.ObjectIds.StatusChangeNotification_Encoding_DefaultBinary):
statuschange = ua.StatusChangeNotification.from_binary(io.BytesIO(notif.to_binary()))
self._call_status(statuschange)
else:
self.logger.warning("Notification type not supported yet for notification %s", notif)
ack = ua.SubscriptionAcknowledgement()
ack.SubscriptionId = self.subscription_id
ack.SequenceNumber = publishresult.NotificationMessage.SequenceNumber
self.server.publish([ack])
except:
self.logger.exception("Exception while processing publishresult.")
self.server.publish()
But I'm sure you will find out better fix because I'm just a programming pig.
BTW, why is publish()
called twice in Subscription.__init__()
?
Just grabbed the latest code and noticed dcbc5dd adds the dependency of pycrypto.
Unfortunately it looks like pycrpto is not supported by Python 3.4+.
Can we make the import of pycrypto only happen if we actually want to use certificates? Otherwise the server can't start with python 3.4 and newer.
The other option is to use a module that is being maintained like https://github.com/Legrandin/pycryptodome
I don't think anyone has updated pycrypto in 2 years?
A declarative, efficient, and flexible JavaScript library for building user interfaces.
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google ❤️ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.