Python OPC UA Client - Write variable using BrowseName - python

I can't find the correct syntax for assigning a value to a variable using its BrowseName.
I am testing with the 'flag1' boolean variable because it is easier to debug. But my goal is be able to write in all variables, including the arrays.
If I try to use the index number it works fine.
import pyOPCClient as opc
client = opc.opcConnect('192.168.5.10')
opc.write_value_bool(client, 'ns=4;s="opcData"."flag1"', True)
client.disconnect()
Here is my function to write boolean
##### Function to WRITE a Boolean into Bool Object Variable - Requires Object Name #####
def write_value_bool(client, node_id, value):
client_node = client.get_node(node_id) # get node
client_node_value = value
client_node_dv = ua.DataValue(ua.Variant(client_node_value, ua.VariantType.Boolean))
client_node.set_value(client_node_dv)
print("Value of : " + str(client_node) + ' : ' + str(client_node_value))
I am getting this error:
PS C:\Users\ALEMAC\Documents\Python Scripts> & C:/ProgramData/Anaconda3/python.exe "c:/Users/ALEMAC/Documents/Python Scripts/opctest.py"
Requested session timeout to be 3600000ms, got 30000ms instead
Traceback (most recent call last):
File "c:\Users\ALEMAC\Documents\Python Scripts\opctest.py", line 5, in <module>
opc.write_value_bool(client, 'ns=4;s="opcData"."flag1"', True)
File "c:\Users\ALEMAC\Documents\Python Scripts\pyOPCClient.py", line 49, in write_value_bool
client_node.set_value(client_node_dv)
File "c:\Users\ALEMAC\Documents\Python Scripts\opcua\common\node.py", line 217, in set_value
self.set_attribute(ua.AttributeIds.Value, datavalue)
File "c:\Users\ALEMAC\Documents\Python Scripts\opcua\common\node.py", line 263, in set_attribute
result[0].check()
File "c:\Users\ALEMAC\Documents\Python Scripts\opcua\ua\uatypes.py", line 218, in check
raise UaStatusCodeError(self.value)
opcua.ua.uaerrors._auto.BadNodeIdUnknown: "The node id refers to a node that does not exist in the server address space."(BadNodeIdUnknown)

I see you use the pyOPCClient package. I´m not sure if this is maintaned anymore (Last Update: 2014-01-09 see here).
You can switch to opcua-asyncio which can address nodes with the browse services like this:
myvar = await client.nodes.root.get_child(["0:Objects",..., "4:flag1"])
And here is the complete example

You are using a mix of NodeId and BrowseName. Just Keep the node NodeId
opc.write_value_bool(client, 'ns=4;i=20', True)
To write other datapoint "args" you will also have to find their NodeId.
You can use the OPC UA Service Browse for that.

Apparently the S7-1200 by default, when you create a tag in S7-1200 the NodeID is set to NUMERIC. Looks lik you can change it though, using another software called SiOME.
https://support.industry.siemens.com/cs/document/109793221/how-do-you-change-the-node-id-identifier-type-of-the-nodes-in-the-s7-1200-opc-ua-server-from-numeric-to-string-?dti=0&dl=en&lc=nl-NL

Related

VI_ERROR_TMO when a computer does a query to a function generator

I am using a peaktech 4046 : 160MHz Function/arbitrary Waveform Generator. I developping on pyton and I am using the pyvisa librairy.
The connection is well established and the generator applies the query. But it generates the following error and stops the program (it doesn't do anything after the error).
Here is the code :
import pyvisa
rm = pyvisa.ResourceManager()
inst = rm.open_resource('TCPIP0::130.79.192.123::5025::SOCKET')
print(inst.session)
print(inst.io_protocol)
inst.query("source1:function squ")
And here is what I have in my terminal :
2
IOProtocol.normal
Traceback (most recent call last):
File "c:\Users\Labo préclinique\Desktop\ProjetPython\importation de librairies\Forum.py", line 7, in <module>
inst.query("source1:function squ ")
File "C:\Users\Labo préclinique\AppData\Local\Programs\Python\Python39\lib\site-packages\pyvisa\resources\messagebased.py", line 644, in query
return self.read()
File "C:\Users\Labo préclinique\AppData\Local\Programs\Python\Python39\lib\site-packages\pyvisa\resources\messagebased.py", line 486, in read
message = self._read_raw().decode(enco)
File "C:\Users\Labo préclinique\AppData\Local\Programs\Python\Python39\lib\site-packages\pyvisa\resources\messagebased.py", line 442, in _read_raw
chunk, status = self.visalib.read(self.session, size)
File "C:\Users\Labo préclinique\AppData\Local\Programs\Python\Python39\lib\site-packages\pyvisa\ctwrapper\functions.py", line 2337, in read
ret = library.viRead(session, buffer, count, byref(return_count))
File "C:\Users\Labo préclinique\AppData\Local\Programs\Python\Python39\lib\site-packages\pyvisa\ctwrapper\highlevel.py", line 222, in _return_handler
return self.handle_return_value(session, ret_value) # type: ignore
File "C:\Users\Labo préclinique\AppData\Local\Programs\Python\Python39\lib\site-packages\pyvisa\highlevel.py", line 251, in handle_return_value
raise errors.VisaIOError(rv)
pyvisa.errors.VisaIOError: VI_ERROR_TMO (-1073807339): Timeout expired before operation completed.
I have tried (to no avail) :
-changing SOCKET to INSTR
-using a timout much longeur ( inst.timeout = 10000)
-adding a end term (tried \n and \r) with : inst.read_termination = '\n'
So I don't know what to do anymore... I need to give more than one command, so the program must not stop so fast. I suspect that my function generator is not sending anything back, but I don't know how to make sure this is the case.
What I wish to know is : Why do I have a time out error if the connection is well established and the request is executed on the device ? How to do the request in a proper way ?
Thank you in advance !!
PS : I know how to catch the error (with try except) but I'd rather have an Ok answer thant a KO one.
Try to get a list of resources by
rm.list_resources()
and check that your resource TCPIP0::130.79.192.123::5025::SOCKET in it.
Then check the standard request to the resource from tutorial:
inst.query("*IDN?")
query is a short form for a write operation to send a message, followed by a read. So you could do this in two actions to specify the error(read or write error?):
inst.write('"source1:function squ"')
print(inst.read())
Please, check the name of query source1:function squ because I don't see it in the documentation. Maybe you should use "source1:am:interanal:function square(p. 57 of documentation) or change squ -> square?
Accordingly documentation, you could try to set infinite timeout to your request by
del inst.timeout
Also, you could add read_termination/write_termination option to specify when you'll finish your reading/writing by
inst = rm.open_resource('TCPIP0::130.79.192.123::5025::SOCKET', read_termination='\r')
And the last chance is changing the options query_delay and send_end.

how to use trigger.adddependencies in pyzabbix

i'm a newbie in python and coding,i'm trying to use pyzabbix to add trigger dependecies,but some error occusrs.
When i run
zapi.trigger.addDependencies(triggerid, dependsOnTriggerid)
an error occurs
pyzabbix.ZabbixAPIException: ('Error -32500: Application error., No permissions to referred object or it does not exist!', -32500)
i get the "triggerid" and "dependsOnTriggerid" by trigger.get:
triggerid_info = zapi.trigger.get(filter={'host': 'xx','description': 'xx'},output=['triggerid'], selectDependencies=['description'])
triggerid = triggerid_info[0]['triggerid']
dependsOnTriggerid = trigger_info[0]['dependencies'][0]['triggerid']
The results are as follws:
Traceback (most recent call last): File "E:/10.python/2019-03-07/1.py", line 14, in zapi.trigger.addDependencies(triggerid, dependsOnTriggerid) File "D:\Program Files\Python37\lib\site-packages\pyzabbix__init__.py", line 166, in fn args or kwargs File "D:\Program Files\Python37\lib\site-packages\pyzabbix__init__.py", line 143, in do_request raise ZabbixAPIException(msg, response_json['error']['code']) pyzabbix.ZabbixAPIException: ('Error -32500: Application error., No permissions to referred object or it does not exist!', -32500)
Did i get the wrong triggerid? or the i use the method in a wrong way? Thanks so much
To add a dependancy means that you need to link two different triggers (from the same host or from another one) with a master-dependent logic.
You are trying to add the dependancy triggerid -> dependsOnTriggerid, which is obtained from a supposed existing dependancy (trigger_info[0]['dependencies'][0]['triggerid']), and this makes little sense and I suppose it's the cause of the error.
You need to get both trigger's triggerid and then add the dependancy:
masterTriggerObj = zapi.trigger.get( /* filter to get your master trigger here */ )
dependentTriggerObj = zapi.trigger.get( /* filter to get your dependent trigger here */)
result = zapi.trigger.adddependencies(triggerid=dependentTriggerObj[0]['triggerid'], dependsOnTriggerid=masterTriggerObj[0]['triggerid'])
The method "trigger.addDependencies" need only one parameter,and it should be a dict or some other object/array.The following code solves the problem.
trigger_info = zapi.trigger.get(filter={xx},output=['triggerid'])
trigger_depends_info_193 = zapi.trigger.get(filter={xx},output=['triggerid'])
trigger_dependson_193 = {"triggerid": trigger_info[0]['triggerid'], "dependsOnTriggerid": trigger_depends_info_193[0]['triggerid']}
zapi.trigger.adddependencies(trigger_dependson_193)

Python in ArcGIS

I wrote the following code, which results in an error and I don't know how to fix it to work.
The code is:
# Name: ClipGDBtoNewGDB.py
# Description: Take an input GDB, create a list, iterate through each
feature class, clipping it and writing it to a new GDB.
# Author: tuilbox
# Import system modules
import arcpy, os
from arcpy import env
# Set workspace
env.workspace = arcpy.GetParameterAsText(0)
arcpy.env.overwriteOutput=True
# Set local variables
fclist = arcpy.ListFeatureClasses()
clip_features = arcpy.GetParameterAsText(1)
output_directory=arcpy.GetParameterAsText(2)
xy_tolerance = ""
outgdb=os.path.join(output_directory, arcpy.GetParameterAsText(3))
if not arcpy.Exists(outgdb):
arcpy.CreateFileGDB_management(output_directory,
arcpy.GetParameterAsText(3))
# Execute Clip within for loop
for fc in fclist:
arcpy.Clip_analysis(fc, clip_features, os.path.join(outgdb, fc))
The error is: Traceback (most recent call last):
File "F:/GIS_Joseph/Lab10_Joseph/ClipGDBtoNewGDB.py", line 17, in <module>
arcpy.CreateFileGDB_management(output_directory, arcpy.GetParameterAsText(3))
File "C:\Program Files (x86)\ArcGIS\Desktop10.5\ArcPy\arcpy\management.py", line 18878, in CreateFileGDB
raise e
ExecuteError: Failed to execute. Parameters are not valid.
ERROR 000735: File GDB Location: Value is required
ERROR 000735: File GDB Name: Value is required
Failed to execute (CreateFileGDB).
Any help would be appreciated. Thank you.
With this type of question it would be helpful to let us know what parameters you are passing into your script. Have you passed a valid parameter in position 3? Use arcpy.AddMessage to double check what value you are attempting to pass to arcpy.CreateFileGDB_management.

struct.error: argument for 's' must be a string

i'm working on a authentication system with raspberry pi with the Fingerprint Scanner - TTL (GT-511C3) and i have a function that create a template and returns as result the following :
I want to extract only th data part so i did like this : response 1['Data']
but when i print it i get this :
i added this as header of my file :
reload(sys)
sys.setdefaultencoding('utf8')
and i tried a couple of solutions i found in the forum but i couldn't find one that works with me.
my problem is when i try to compare the created template with the ones already in the database of the scanner with a function called IdentifyTemplate and takes as a parameter a template it gives me the following error :
Traceback (most recent call last):
File "finger.py", line 169, in
indetifyResponse = f.IdentifyTemplate(makeTemplateResponse)
File "/home/pi/Desktop/fingerpi/fingerpi/fingerpi.py", line 213, in
IdentifyTemplate
if self.sendData(template, 498):
File "/home/pi/Desktop/fingerpi/fingerpi/fingerpi.py", line 53, in sendData
packet = encode_data_packet(data, data_len, device_id = self.device_id)
File "/home/pi/Desktop/fingerpi/fingerpi/base.py", line 72, in
encode_data_packet
data # Data to be sent
struct.error: argument for 's' must be a string
i suspect that the problem is comming from that Data that i'm trying to print.
Any help is much appreciated. My Python version is 2.7.13

Where does this pywinauto exception get its list from?

If I run:
from pywinauto.findwindows import find_windows
find_windows(best_match="affafa")
I get an exception that returns
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "c:\Python27\lib\site-packages\pywinauto\findwindows.py", line 204, in find_windows
best_match, wrapped_wins)
File "c:\Python27\lib\site-packages\pywinauto\findbestmatch.py", line 497, in find_best_control_matches
raise MatchError(items = name_control_map.keys(), tofind = search_text)
pywinauto.findbestmatch.MatchError: Could not find 'affafa' in '[u'CabinetWClass', u'Inbox (1,455) - ******#gmail.com - Gmail - Google Chrome', u'Chrome_WidgetWin_1', '', u'*new 2 - Notepad++Notepad++', u'python - Where does this pywinauto exception get its list from? - Stack Overflow - Google ChromeChrome_WidgetWin_1', u'C:\\Windows\\system32\\cmd.exe - pythonConsoleWindowClass1', u'C:\\Windows\\system32\\cmd.exe - pythonConsoleWindowClass0', u'C:\\Windows\\system32\\cmd.exe - pythonConsoleWindowClass2']' # this list has been shortened for security reasons
What I want to do is,Find out where the giant list of processes is coming from and directly call that.
So far ive been messing around with
find_windows(visible_only = False)
# and some of the other options listed in findwindows.py
but all the find_windows options only return a list of numbers which from documentation, i think are process IDs...., which for some reason do NOT match up with what i have ( for example, i create a "Calculator" and its process ID is 6566, and then i run find_windows() and i cannot find the process ID in it. So that's another issue I'm having.... but i can solve this problem if i can get my giant list.
This is my first question asked on stack overflow. I hope I made you guys proud
If you want to get a list of the names for all windows, you should use the next construction.
handles = pywinauto.findwindows.find_windows()
for w_handle in handles:
wind = app.window_(handle=w_handle)
print wind.Texts()
You may filter/extend the list by the next arguments of find_windows function:
top_level_only Top level windows only (default=True)
visible_only Visible windows only (default=True)
enabled_only Enabled windows only (default=True)
active_only Active windows only (default=False)

Categories

Resources