FreeOpcUa / opcua-asyncio

OPC UA library for python >= 3.7
GNU Lesser General Public License v3.0
1.04k stars 346 forks source link

Cannot set attribute bits for float or double values #1543

Closed DavideFigundio closed 6 months ago

DavideFigundio commented 6 months ago

Currently it is not possible to change the attribute bits for float and double values.

I am running the following code:

def set_bit(node: SyncNode, bit: int, value: bool):
    '''Sets the value of the indicated bit for the given node.'''

    if value:
        node.set_attr_bit(asyncua.ua.AttributeIds.Value, bit)
    else:
        node.unset_attr_bit(asyncua.ua.AttributeIds.Value, bit)

Whenever the value attribute of node is a float or double, calling this function raises an exception:

    ...
    File "C:\automatedTestingEnv\Lib\site-packages\asyncua\ua\ua_binary.py", line 30, in set_bit
    return data | mask
           ~~~~~^~~~~~
TypeError: unsupported operand type(s) for |: 'float' and 'int'

Python version: 3.12 opcua-asyncio version: 1.0.6

schroeder- commented 6 months ago

You can not bitmask a float. If you still want to do this, write your own function like this:

def set_bit(node: SyncNode, bit: int, value: bool):
     v = node.get_value()
     t = None
     if isinstance(v, float):
         v = int(v)
         t = type(v)
     val = int()
     if bit:
        val = val | (1<<bit)
     else:
        val = val & ~(1<<bit)
     if t is not None:
        val = t(val)
     node.set_value(val)