Search code examples
pythonpython-3.xplcopc-uasiemens

Writing variables with OPC UA


Recently I was trying to communicate with a Siemens S7-1200 plc, I am using the OPC UA protocol, I am able to connect and read all the variables but I have problems when I try to write a value in the variable, this is the error message:

File "c:\Users\User\Documents\Python\OpcUa\Client_PLC.py", line 18, in <module>
Plc.set_values(var_2,val)
File "C:\Python310\lib\site-packages\opcua\client\client.py", line 670, in set_values
nodeids = [node.nodeid for node in nodes]
TypeError: 'Node' object is not iterable

And this is the code I am trying.

from opcua import Client
import time
   
url = "tcp.upc://192.168.0.1:4840"

val = 2

Plc = Client(url)

Plc.connect()


while True  :
    var = Plc.get_node("ns=4;i=2")
    print ("The value is : {}".format(var.get_value()))
    var_2 = Plc.get_node("ns=4;i=3")
    print(var_2)
    Plc.set_values(var_2,val)
    time.sleep(2)

Update:

I've tried to use set_value command but I get this error code:

opcua.ua.uaerrors._auto.BadWriteNotSupported: "The server does not support writing the combination of value, status and timestamps provided."(BadWriteNotSupported)


Solution

  • You use the function set_values which expects a list of nodes. Try this instead:

    val.set_value(var_2)
    

    If the plc returns an error set only the value:

    val.set_value(DataValue(var_2))