Commit 55ba0ba6 authored by ORD's avatar ORD Committed by GitHub

Explicitely numbered replacement fields (#371)

parent 90bcd3a1
......@@ -36,9 +36,9 @@ if __name__ == "__main__":
tag1 = client.get_node("ns=2;s=Channel1.Device1.Tag1")
print("tag1 is: {} with value {} ".format(tag1, tag1.get_value()))
print("tag1 is: {0} with value {1} ".format(tag1, tag1.get_value()))
tag2 = client.get_node("ns=2;s=Channel1.Device1.Tag2")
print("tag2 is: {} with value {} ".format(tag2, tag2.get_value()))
print("tag2 is: {0} with value {1} ".format(tag2, tag2.get_value()))
handler = SubHandler()
sub = client.create_subscription(500, handler)
......
......@@ -26,7 +26,7 @@ def create_monitored_items(event, dispatcher):
for idx in range(len(event.response_params)) :
if (event.response_params[idx].StatusCode.is_good()) :
nodeId = event.request_params.ItemsToCreate[idx].ItemToMonitor.NodeId
print("Node {} was created".format(nodeId))
print("Node {0} was created".format(nodeId))
def modify_monitored_items(event, dispatcher):
......
......@@ -125,7 +125,7 @@ class Client(object):
ep.SecurityMode == security_mode and
ep.SecurityPolicyUri == policy_uri):
return ep
raise ua.UaError("No matching endpoints: {}, {}".format(
raise ua.UaError("No matching endpoints: {0}, {1}".format(
security_mode, policy_uri))
def set_security_string(self, string):
......@@ -142,7 +142,7 @@ class Client(object):
return
parts = string.split(',')
if len(parts) < 4:
raise ua.UaError('Wrong format: `{}`, expected at least 4 comma-separated values'.format(string))
raise ua.UaError('Wrong format: `{0}`, expected at least 4 comma-separated values'.format(string))
policy_class = getattr(security_policies, 'SecurityPolicy' + parts[0])
mode = getattr(ua.MessageSecurityMode, parts[1])
return self.set_security(policy_class, parts[2], parts[3],
......
......@@ -116,7 +116,7 @@ class UASocketClient(object):
with self._lock:
future = self._callbackmap.pop(request_id, None)
if future is None:
raise ua.UaError("No future object found for request: {}, callbacks in list are {}".format(request_id, self._callbackmap.keys()))
raise ua.UaError("No future object found for request: {0}, callbacks in list are {1}".format(request_id, self._callbackmap.keys()))
future.set_result(body)
def _create_request_header(self, timeout=1000):
......
......@@ -28,7 +28,7 @@ class Event(object):
self.internal_properties = list(self.__dict__.keys())[:] + ["internal_properties"]
def __str__(self):
return "{}({})".format(
return "{0}({1})".format(
self.__class__.__name__,
[str(k) + ":" + str(v) for k, v in self.__dict__.items() if k not in self.internal_properties])
__repr__ = __str__
......
......@@ -28,7 +28,7 @@ def _parse_nodeid_qname(*args):
except ua.UaError:
raise
except Exception as ex:
raise TypeError("This method takes either a namespace index and a string as argument or a nodeid and a qualifiedname. Received arguments {} and got exception {}".format(args, ex))
raise TypeError("This method takes either a namespace index and a string as argument or a nodeid and a qualifiedname. Received arguments {0} and got exception {1}".format(args, ex))
def create_folder(parent, nodeid, bname):
......@@ -96,7 +96,7 @@ def create_variable_type(parent, nodeid, bname, datatype):
"""
nodeid, qname = _parse_nodeid_qname(nodeid, bname)
if datatype and not isinstance(datatype, ua.NodeId):
raise RuntimeError("Data type should be nodeid, got {}".format(datatype))
raise RuntimeError("Data type should be nodeid, got {0}".format(datatype))
addnode = ua.AddNodesItem()
addnode.RequestedNewNodeId = nodeid
addnode.BrowseName = qname
......
......@@ -29,7 +29,7 @@ class Node(object):
elif isinstance(nodeid, int):
self.nodeid = ua.NodeId(nodeid, 0)
else:
raise ua.UaError("argument to node must be a NodeId object or a string defining a nodeid found {} of type {}".format(nodeid, type(nodeid)))
raise ua.UaError("argument to node must be a NodeId object or a string defining a nodeid found {0} of type {1}".format(nodeid, type(nodeid)))
def __eq__(self, other):
if isinstance(other, Node) and self.nodeid == other.nodeid:
......@@ -40,7 +40,7 @@ class Node(object):
return not self.__eq__(other)
def __str__(self):
return "Node({})".format(self.nodeid)
return "Node({0})".format(self.nodeid)
__repr__ = __str__
def __hash__(self):
......
......@@ -63,7 +63,7 @@ class DataChangeNotif(object):
self.subscription_data = subscription_data
def __str__(self):
return "DataChangeNotification({}, {})".format(self.subscription_data, self.monitored_item)
return "DataChangeNotification({0}, {1})".format(self.subscription_data, self.monitored_item)
__repr__ = __str__
......
......@@ -45,7 +45,7 @@ class Buffer(object):
self._size = size
def __str__(self):
return "Buffer(size:{}, data:{})".format(
return "Buffer(size:{0}, data:{1})".format(
self._size,
self._data[self._cur_pos:self._cur_pos + self._size])
__repr__ = __str__
......@@ -58,7 +58,7 @@ class Buffer(object):
read and pop number of bytes for buffer
"""
if size > self._size:
raise NotEnoughData("Not enough data left in buffer, request for {}, we have {}".format(size, self))
raise NotEnoughData("Not enough data left in buffer, request for {0}, we have {1}".format(size, self))
# self.logger.debug("Request for %s bytes, from %s", size, self)
self._size -= size
pos = self._cur_pos
......@@ -80,7 +80,7 @@ class Buffer(object):
skip size bytes in buffer
"""
if size > self._size:
raise NotEnoughData("Not enough data left in buffer, request for {}, we have {}".format(size, self))
raise NotEnoughData("Not enough data left in buffer, request for {0}, we have {1}".format(size, self))
self._size -= size
self._cur_pos += size
......
......@@ -65,7 +65,7 @@ class NodeData(object):
self.definition = []
def __str__(self):
return "NodeData(nodeid:{})".format(self.nodeid)
return "NodeData(nodeid:{0})".format(self.nodeid)
__repr__ = __str__
......@@ -86,7 +86,7 @@ class ExtObj(object):
self.body = {}
def __str__(self):
return "ExtObj({}, {})".format(self.objname, self.body)
return "ExtObj({0}, {1})".format(self.objname, self.body)
__repr__ = __str__
......
......@@ -18,7 +18,7 @@ def require_cryptography(obj):
Call this function in constructors.
"""
if not CRYPTOGRAPHY_AVAILABLE:
raise UaError("Can't use {}, cryptography module is not installed".format(obj.__class__.__name__))
raise UaError("Can't use {0}, cryptography module is not installed".format(obj.__class__.__name__))
class Signer(object):
......@@ -453,4 +453,4 @@ def encrypt_asymmetric(pubkey, data, policy_uri):
cls.AsymmetricEncryptionURI)
if not policy_uri or policy_uri == POLICY_NONE_URI:
return (data, '')
raise UaError("Unsupported security policy `{}`".format(policy_uri))
raise UaError("Unsupported security policy `{0}`".format(policy_uri))
......@@ -157,7 +157,7 @@ def p_sha1(secret, seed, sizes=()):
def x509_name_to_string(name):
parts = ["{}={}".format(attr.oid._name, attr.value) for attr in name]
parts = ["{0}={1}".format(attr.oid._name, attr.value) for attr in name]
return ', '.join(parts)
......@@ -168,9 +168,9 @@ def x509_to_string(cert):
if cert.subject == cert.issuer:
issuer = ' (self-signed)'
else:
issuer = ', issuer: {}'.format(x509_name_to_string(cert.issuer))
issuer = ', issuer: {0}'.format(x509_name_to_string(cert.issuer))
# TODO: show more information
return "{}{}, {} - {}".format(x509_name_to_string(cert.subject), issuer, cert.not_valid_before, cert.not_valid_after)
return "{0}{1}, {2} - {3}".format(x509_name_to_string(cert.subject), issuer, cert.not_valid_before, cert.not_valid_after)
if __name__ == "__main__":
......
......@@ -20,7 +20,7 @@ class AttributeValue(object):
self.datachange_callbacks = {}
def __str__(self):
return "AttributeValue({})".format(self.value)
return "AttributeValue({0})".format(self.value)
__repr__ = __str__
......@@ -33,7 +33,7 @@ class NodeData(object):
self.call = None
def __str__(self):
return "NodeData(id:{}, attrs:{}, refs:{})".format(self.nodeid, self.attributes, self.references)
return "NodeData(id:{0}, attrs:{1}, refs:{2})".format(self.nodeid, self.attributes, self.references)
__repr__ = __str__
......
......@@ -103,7 +103,7 @@ class BinaryServer(object):
sockname = self._server.sockets[0].getsockname()
self.hostname = sockname[0]
self.port = sockname[1]
print('Listening on {}:{}'.format(self.hostname, self.port))
print('Listening on {0}:{1}'.format(self.hostname, self.port))
def stop(self):
self.logger.info("Closing asyncio socket server")
......
......@@ -75,7 +75,7 @@ class EventGenerator(object):
# result.StatusCode.check()
def __str__(self):
return "EventGenerator(Type:{}, Source:{}, Time:{}, Message: {})".format(self.event.EventType,
return "EventGenerator(Type:{0}, Source:{1}, Time:{2}, Message: {3})".format(self.event.EventType,
self.event.SourceNode,
self.event.Time,
self.event.Message)
......
......@@ -213,7 +213,7 @@ class HistoryManager(object):
if not self._sub:
self._sub = self._create_subscription(SubHandler(self.storage))
if node in self._handlers:
raise ua.UaError("Node {} is already historized".format(node))
raise ua.UaError("Node {0} is already historized".format(node))
self.storage.new_historized_node(node.nodeid, period, count)
handler = self._sub.subscribe_data_change(node)
self._handlers[node] = handler
......@@ -234,7 +234,7 @@ class HistoryManager(object):
if not self._sub:
self._sub = self._create_subscription(SubHandler(self.storage))
if source in self._handlers:
raise ua.UaError("Events from {} are already historized".format(source))
raise ua.UaError("Events from {0} are already historized".format(source))
# get list of all event types that the source node generates; change this to only historize specific events
event_types = source.get_referenced_nodes(ua.ObjectIds.GeneratesEvent)
......
......@@ -265,7 +265,7 @@ class InternalSession(object):
self._lock = Lock()
def __str__(self):
return "InternalSession(name:{}, user:{}, id:{}, auth_token:{})".format(
return "InternalSession(name:{0}, user:{1}, id:{2}, auth_token:{3})".format(
self.name, self.user, self.session_id, self.authentication_token)
def get_endpoints(self, params=None, sockname=None):
......
......@@ -263,7 +263,7 @@ class InternalSubscription(object):
self._stopev = False
def __str__(self):
return "Subscription(id:{})".format(self.data.SubscriptionId)
return "Subscription(id:{0})".format(self.data.SubscriptionId)
def start(self):
self.logger.debug("starting subscription %s", self.data.SubscriptionId)
......
......@@ -66,7 +66,7 @@ def _require_nodeid(parser, args):
# check that a nodeid has been given explicitly, a bit hackish...
if args.nodeid == "i=84" and args.path == "":
parser.print_usage()
print("{}: error: A NodeId or BrowsePath is required".format(parser.prog))
print("{0}: error: A NodeId or BrowsePath is required".format(parser.prog))
sys.exit(1)
......@@ -280,7 +280,7 @@ def uals():
client.connect()
try:
node = get_node(client, args)
print("Browsing node {} at {}\n".format(node, args.url))
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:
......@@ -295,32 +295,32 @@ def uals():
def _lsprint_0(node, depth, indent=""):
if not indent:
print("{:30} {:25}".format("DisplayName", "NodeId"))
print("{0:30} {1:25}".format("DisplayName", "NodeId"))
print("")
for desc in node.get_children_descriptions():
print("{}{:30} {:25}".format(indent, desc.DisplayName.to_string(), desc.NodeId.to_string()))
print("{0}{1:30} {2:25}".format(indent, desc.DisplayName.to_string(), desc.NodeId.to_string()))
if depth:
_lsprint_0(Node(node.server, desc.NodeId), depth - 1, indent + " ")
def _lsprint_1(node, depth, indent=""):
if not indent:
print("{:30} {:25} {:25} {:25}".format("DisplayName", "NodeId", "BrowseName", "Value"))
print("{0:30} {1:25} {2:25} {3:25}".format("DisplayName", "NodeId", "BrowseName", "Value"))
print("")
for desc in node.get_children_descriptions():
if desc.NodeClass == ua.NodeClass.Variable:
val = Node(node.server, desc.NodeId).get_value()
print("{}{:30} {!s:25} {!s:25}, {!s:3}".format(indent, desc.DisplayName.to_string(), desc.NodeId.to_string(), desc.BrowseName.to_string(), val))
print("{0}{1:30} {2!s:25} {3!s:25}, {4!s:3}".format(indent, desc.DisplayName.to_string(), desc.NodeId.to_string(), desc.BrowseName.to_string(), val))
else:
print("{}{:30} {!s:25} {!s:25}".format(indent, desc.DisplayName.to_string(), desc.NodeId.to_string(), desc.BrowseName.to_string()))
print("{0}{1:30} {2!s:25} {3!s:25}".format(indent, desc.DisplayName.to_string(), desc.NodeId.to_string(), desc.BrowseName.to_string()))
if depth:
_lsprint_1(Node(node.server, desc.NodeId), depth - 1, indent + " ")
def _lsprint_long(pnode, depth, indent=""):
if not indent:
print("{:30} {:25} {:25} {:10} {:30} {:25}".format("DisplayName", "NodeId", "BrowseName", "DataType", "Timestamp", "Value"))
print("{0:30} {1:25} {2:25} {3:10} {4:30} {5:25}".format("DisplayName", "NodeId", "BrowseName", "DataType", "Timestamp", "Value"))
print("")
for node in pnode.get_children():
attrs = node.get_attributes([ua.AttributeIds.DisplayName,
......@@ -333,9 +333,9 @@ def _lsprint_long(pnode, depth, indent=""):
name, bname, nclass, mask, umask, dtype, val = [attr.Value.Value for attr in attrs]
update = attrs[-1].ServerTimestamp
if nclass == ua.NodeClass.Variable:
print("{}{:30} {:25} {:25} {:10} {!s:30} {!s:25}".format(indent, name.to_string(), node.nodeid.to_string(), bname.to_string(), dtype.to_string(), update, val))
print("{0}{1:30} {2:25} {3:25} {4:10} {5!s:30} {6!s:25}".format(indent, name.to_string(), node.nodeid.to_string(), bname.to_string(), dtype.to_string(), update, val))
else:
print("{}{:30} {:25} {:25}".format(indent, name.to_string(), bname.to_string(), node.nodeid.to_string()))
print("{0}{1:30} {2:25} {3:25}".format(indent, name.to_string(), bname.to_string(), node.nodeid.to_string()))
if depth:
_lsprint_long(node, depth - 1, indent + " ")
......@@ -411,7 +411,7 @@ def cert_to_string(der):
try:
from opcua.crypto import uacrypto
except ImportError:
return "{} bytes".format(len(der))
return "{0} bytes".format(len(der))
cert = uacrypto.x509_from_der(der)
return uacrypto.x509_to_string(cert)
......@@ -570,24 +570,24 @@ def uadiscover():
client = Client(args.url, timeout=args.timeout)
if args.network:
print("Performing discovery at {}\n".format(args.url))
print("Performing discovery at {0}\n".format(args.url))
for i, server in enumerate(client.connect_and_find_servers_on_network(), start=1):
print('Server {}:'.format(i))
print('Server {0}:'.format(i))
#for (n, v) in application_to_strings(server):
#print(' {}: {}'.format(n, v))
print('')
print("Performing discovery at {}\n".format(args.url))
print("Performing discovery at {0}\n".format(args.url))
for i, server in enumerate(client.connect_and_find_servers(), start=1):
print('Server {}:'.format(i))
print('Server {0}:'.format(i))
for (n, v) in application_to_strings(server):
print(' {}: {}'.format(n, v))
print(' {0}: {1}'.format(n, v))
print('')
for i, ep in enumerate(client.connect_and_get_server_endpoints(), start=1):
print('Endpoint {}:'.format(i))
print('Endpoint {0}:'.format(i))
for (n, v) in endpoint_to_strings(ep):
print(' {}: {}'.format(n, v))
print(' {0}: {1}'.format(n, v))
print('')
sys.exit(0)
......@@ -595,9 +595,9 @@ def uadiscover():
def print_history(o):
if isinstance(o, ua.HistoryData):
print("{:30} {:10} {}".format('Source timestamp', 'Status', 'Value'))
print("{0:30} {1:10} {2}".format('Source timestamp', 'Status', 'Value'))
for d in o.DataValues:
print("{:30} {:10} {}".format(str(d.SourceTimestamp), d.StatusCode.name, d.Value))
print("{0:30} {1:10} {2}".format(str(d.SourceTimestamp), d.StatusCode.name, d.Value))
def str_to_datetime(s, default=None):
......@@ -641,7 +641,7 @@ def uahistoryread():
node = get_node(client, args)
starttime = str_to_datetime(args.starttime, datetime.utcnow() - timedelta(days=1))
endtime = str_to_datetime(args.endtime, datetime.utcnow())
print("Reading raw history of node {} at {}; start at {}, end at {}\n".format(node, args.url, starttime, endtime))
print("Reading raw history of node {0} at {1}; start at {2}, end at {3}\n".format(node, args.url, starttime, endtime))
if args.events:
evs = node.read_event_history(starttime, endtime, numvalues=args.limit)
for ev in evs:
......
......@@ -475,8 +475,8 @@ def get_name_and_doc(val):
return code_to_name_doc[val]
else:
if uabin.test_bit(val, 31):
return 'Bad', 'Unknown StatusCode value: {}'.format(val)
return 'Bad', 'Unknown StatusCode value: {0}'.format(val)
elif uabin.test_bit(val, 30):
return 'UncertainIn', 'Unknown StatusCode value: {}'.format(val)
return 'UncertainIn', 'Unknown StatusCode value: {0}'.format(val)
else:
return 'Good', 'Unknown StatusCode value: {}'.format(val)
return 'Good', 'Unknown StatusCode value: {0}'.format(val)
......@@ -269,7 +269,7 @@ def pack_uatype(vtype, value):
try:
return value.to_binary()
except AttributeError:
raise UaError("{} could not be packed with value {}".format(vtype, value))
raise UaError("{0} could not be packed with value {1}".format(vtype, value))
def unpack_uatype(vtype, data):
......
......@@ -16318,7 +16318,7 @@ def extensionobject_from_binary(data):
return e
klass = ExtensionClasses[TypeId.Identifier]
if body is None:
raise UaError("parsing ExtensionObject {} without data".format(klass.__name__))
raise UaError("parsing ExtensionObject {0} without data".format(klass.__name__))
return klass.from_binary(body)
......@@ -16334,7 +16334,7 @@ def extensionobject_to_binary(obj):
Encoding = 0
Body = None
if obj is not None:
TypeId = FourByteNodeId(getattr(ObjectIds, "{}_Encoding_DefaultBinary".format(obj.__class__.__name__)))
TypeId = FourByteNodeId(getattr(ObjectIds, "{0}_Encoding_DefaultBinary".format(obj.__class__.__name__)))
Encoding |= (1 << 0)
Body = obj.to_binary()
packet = []
......
......@@ -103,7 +103,7 @@ class Header(uatypes.FrozenClass):
return struct.calcsize("<3scII")
def __str__(self):
return "Header(type:{}, chunk_type:{}, body_size:{}, channel:{})".format(
return "Header(type:{0}, chunk_type:{1}, body_size:{2}, channel:{3})".format(
self.MessageType, self.ChunkType, self.body_size, self.ChannelId)
__repr__ = __str__
......@@ -129,7 +129,7 @@ class ErrorMessage(uatypes.FrozenClass):
return ack
def __str__(self):
return "MessageAbort(error:{}, reason:{})".format(self.Error, self.Reason)
return "MessageAbort(error:{0}, reason:{1})".format(self.Error, self.Reason)
__repr__ = __str__
......@@ -184,7 +184,7 @@ class AsymmetricAlgorithmHeader(uatypes.FrozenClass):
return hdr
def __str__(self):
return "{}(SecurityPolicy:{}, certificatesize:{}, receiverCertificatesize:{} )".format(
return "{0}(SecurityPolicy:{1}, certificatesize:{2}, receiverCertificatesize:{3} )".format(
self.__class__.__name__, self.SecurityPolicyURI, len(self.SenderCertificate),
len(self.ReceiverCertificateThumbPrint))
__repr__ = __str__
......@@ -210,7 +210,7 @@ class SymmetricAlgorithmHeader(uatypes.FrozenClass):
return struct.calcsize("<I")
def __str__(self):
return "{}(TokenId:{} )".format(self.__class__.__name__, self.TokenId)
return "{0}(TokenId:{1} )".format(self.__class__.__name__, self.TokenId)
__repr__ = __str__
......@@ -239,7 +239,7 @@ class SequenceHeader(uatypes.FrozenClass):
return struct.calcsize("<II")
def __str__(self):
return "{}(SequenceNumber:{}, RequestId:{} )".format(
return "{0}(SequenceNumber:{1}, RequestId:{2} )".format(
self.__class__.__name__, self.SequenceNumber, self.RequestId)
__repr__ = __str__
......@@ -357,7 +357,7 @@ class MessageChunk(uatypes.FrozenClass):
elif msg_type == MessageType.SecureOpen:
self.SecurityHeader = AsymmetricAlgorithmHeader()
else:
raise UaError("Unsupported message type: {}".format(msg_type))
raise UaError("Unsupported message type: {0}".format(msg_type))
self.SequenceHeader = SequenceHeader()
self.Body = body
self._security_policy = security_policy
......@@ -379,7 +379,7 @@ class MessageChunk(uatypes.FrozenClass):
security_header = AsymmetricAlgorithmHeader.from_binary(data)
crypto = security_policy.asymmetric_cryptography
else:
raise UaError("Unsupported message type: {}".format(header.MessageType))
raise UaError("Unsupported message type: {0}".format(header.MessageType))
obj = MessageChunk(crypto)
obj.MessageHeader = header
obj.SecurityHeader = security_header
......@@ -455,7 +455,7 @@ class MessageChunk(uatypes.FrozenClass):
return chunks
def __str__(self):
return "{}({}, {}, {}, {} bytes)".format(self.__class__.__name__,
return "{0}({1}, {2}, {3}, {4} bytes)".format(self.__class__.__name__,
self.MessageHeader, self.SequenceHeader,
self.SecurityHeader, len(self.Body))
__repr__ = __str__
......@@ -545,7 +545,7 @@ class SecureConnection(object):
return
if self._security_policy.URI != uri or (mode is not None and
self._security_policy.Mode != mode):
raise UaError("No matching policy: {}, {}".format(uri, mode))
raise UaError("No matching policy: {0}, {1}".format(uri, mode))
def tcp_to_binary(self, message_type, message):
"""
......@@ -582,10 +582,10 @@ class SecureConnection(object):
return b"".join([chunk.to_binary() for chunk in chunks])
def _check_incoming_chunk(self, chunk):
assert isinstance(chunk, MessageChunk), "Expected chunk, got: {}".format(chunk)
assert isinstance(chunk, MessageChunk), "Expected chunk, got: {0}".format(chunk)
if chunk.MessageHeader.MessageType != MessageType.SecureOpen:
if chunk.MessageHeader.ChannelId != self.channel.SecurityToken.ChannelId:
raise UaError("Wrong channel id {}, expected {}".format(
raise UaError("Wrong channel id {0}, expected {1}".format(
chunk.MessageHeader.ChannelId,
self.channel.SecurityToken.ChannelId))
if chunk.SecurityHeader.TokenId != self.channel.SecurityToken.TokenId:
......@@ -604,7 +604,7 @@ class SecureConnection(object):
self._old_tokens = self._old_tokens[idx:]
if self._incoming_parts:
if self._incoming_parts[0].SequenceHeader.RequestId != chunk.SequenceHeader.RequestId:
raise UaError("Wrong request id {}, expected {}".format(
raise UaError("Wrong request id {0}, expected {1}".format(
chunk.SequenceHeader.RequestId,
self._incoming_parts[0].SequenceHeader.RequestId))
......@@ -619,7 +619,7 @@ class SecureConnection(object):
self._peer_sequence_number, num)
else:
raise UaError(
"Wrong sequence {} -> {} (server bug or replay attack)"
"Wrong sequence {0} -> {1} (server bug or replay attack)"
.format(self._peer_sequence_number, num))
self._peer_sequence_number = num
......@@ -653,7 +653,7 @@ class SecureConnection(object):
logger.warning("Received an error: %s", msg)
return msg
else:
raise UaError("Unsupported message type {}".format(header.MessageType))
raise UaError("Unsupported message type {0}".format(header.MessageType))
def receive_from_socket(self, socket):
"""
......@@ -666,7 +666,7 @@ class SecureConnection(object):
logger.info("received header: %s", header)
body = socket.read(header.body_size)
if len(body) != header.body_size:
raise UaError("{} bytes expected, {} available".format(header.body_size, len(body)))
raise UaError("{0} bytes expected, {1} available".format(header.body_size, len(body)))
return self.receive_from_header_and_body(header, utils.Buffer(body))
def _receive(self, msg):
......@@ -686,7 +686,7 @@ class SecureConnection(object):
self._incoming_parts = []
return message
else:
raise UaError("Unsupported chunk type: {}".format(msg))
raise UaError("Unsupported chunk type: {0}".format(msg))
# FIXES for missing switchfield in NodeAttributes classes
......
......@@ -35,7 +35,7 @@ class _FrozenClass(object):
def __setattr__(self, key, value):
if self._freeze and not hasattr(self, key):
raise TypeError("Error adding member '{}' to class '{}', class is frozen, members are {}".format(
raise TypeError("Error adding member '{0}' to class '{1}', class is frozen, members are {2}".format(
key, self.__class__.__name__, self.__dict__.keys()))
object.__setattr__(self, key, value)
......@@ -211,7 +211,7 @@ class StatusCode(FrozenClass):
return True
def __str__(self):
return 'StatusCode({})'.format(self.name)
return 'StatusCode({0})'.format(self.name)
__repr__ = __str__
def __eq__(self, other):
......@@ -313,7 +313,7 @@ class NodeId(FrozenClass):
try:
return NodeId._from_string(string)
except ValueError as ex:
raise UaStringParsingError("Error parsing string {}".format(string), ex)
raise UaStringParsingError("Error parsing string {0}".format(string), ex)
@staticmethod
def _from_string(string):
......@@ -357,7 +357,7 @@ class NodeId(FrozenClass):
def to_string(self):
string = ""
if self.NamespaceIndex != 0:
string += "ns={};".format(self.NamespaceIndex)
string += "ns={0};".format(self.NamespaceIndex)
ntype = None
if self.NodeIdType == NodeIdType.Numeric:
ntype = "i"
......@@ -371,15 +371,15 @@ class NodeId(FrozenClass):
ntype = "g"
elif self.NodeIdType == NodeIdType.ByteString:
ntype = "b"
string += "{}={}".format(ntype, self.Identifier)
string += "{0}={1}".format(ntype, self.Identifier)
if self.ServerIndex:
string = "srv=" + str(self.ServerIndex) + string
if self.NamespaceUri:
string += "nsu={}".format(self.NamespaceUri)
string += "nsu={0}".format(self.NamespaceUri)
return string
def __str__(self):
return "{}NodeId({})".format(self.NodeIdType.name, self.to_string())
return "{0}NodeId({1})".format(self.NodeIdType.name, self.to_string())
__repr__ = __str__
def to_binary(self):
......@@ -487,7 +487,7 @@ class QualifiedName(FrozenClass):
self._freeze = True
def to_string(self):
return "{}:{}".format(self.NamespaceIndex, self.Name)
return "{0}:{1}".format(self.NamespaceIndex, self.Name)
@staticmethod
def from_string(string):
......@@ -496,7 +496,7 @@ class QualifiedName(FrozenClass):
idx, name = string.split(":", 1)
idx = int(idx)
except (TypeError, ValueError) as ex:
raise UaStringParsingError("Error parsing string {}".format(string), ex)
raise UaStringParsingError("Error parsing string {0}".format(string), ex)
else:
idx = 0
name = string
......@@ -523,14 +523,14 @@ class QualifiedName(FrozenClass):
def __lt__(self, other):
if not isinstance(other, QualifiedName):
raise TypeError("Cannot compare QualifiedName and {}".format(other))
raise TypeError("Cannot compare QualifiedName and {0}".format(other))
if self.NamespaceIndex == other.NamespaceIndex:
return self.Name < other.Name
else:
return self.NamespaceIndex < other.NamespaceIndex
def __str__(self):
return 'QualifiedName({}:{})'.format(self.NamespaceIndex, self.Name)
return 'QualifiedName({0}:{1})'.format(self.NamespaceIndex, self.Name)
__repr__ = __str__
......@@ -637,7 +637,7 @@ class ExtensionObject(FrozenClass):
@staticmethod
def from_object(obj):
ext = ExtensionObject()
oid = getattr(ObjectIds, "{}_Encoding_DefaultBinary".format(obj.__class__.__name__))
oid = getattr(ObjectIds, "{0}_Encoding_DefaultBinary".format(obj.__class__.__name__))
ext.TypeId = FourByteNodeId(oid)
ext.Body = obj.to_binary()
return ext
......@@ -721,10 +721,10 @@ class VariantTypeCustom(object):
self.name = "Custom"
self.value = val
if self.value > 0b00111111:
raise UaError("Cannot create VariantType. VariantType must be {} > x > {}, received {}".format(0b111111, 25, val))
raise UaError("Cannot create VariantType. VariantType must be {0} > x > {1}, received {2}".format(0b111111, 25, val))
def __str__(self):
return "VariantType.Custom:{}".format(self.value)
return "VariantType.Custom:{0}".format(self.value)
__repr__ = __str__
def __eq__(self, other):
......@@ -758,7 +758,7 @@ class Variant(FrozenClass):
VariantType.Null,
VariantType.String,
VariantType.DateTime):
raise UaError("Variant of type {} cannot have value None".format(self.VariantType))
raise UaError("Variant of type {0} cannot have value None".format(self.VariantType))
if self.Dimensions is None and type(self.Value) in (list, tuple):
dims = get_shape(self.Value)
if len(dims) > 1:
......@@ -777,7 +777,7 @@ class Variant(FrozenClass):
error_val = val
while isinstance(val, (list, tuple)):
if len(val) == 0:
raise UaError("could not guess UA type of variable {}".format(error_val))
raise UaError("could not guess UA type of variable {0}".format(error_val))
val = val[0]
if val is None:
return VariantType.Null
......@@ -802,10 +802,10 @@ class Variant(FrozenClass):
except AttributeError:
return VariantType.ExtensionObject
else:
raise UaError("Could not guess UA type of {} with type {}, specify UA type".format(val, type(val)))
raise UaError("Could not guess UA type of {0} with type {1}, specify UA type".format(val, type(val)))
def __str__(self):
return "Variant(val:{!s},type:{})".format(self.Value, self.VariantType)
return "Variant(val:{0!s},type:{1})".format(self.Value, self.VariantType)
__repr__ = __str__
def to_binary(self):
......@@ -1010,17 +1010,17 @@ class DataValue(FrozenClass):
return obj
def __str__(self):
s = 'DataValue(Value:{}'.format(self.Value)
s = 'DataValue(Value:{0}'.format(self.Value)
if self.StatusCode is not None:
s += ', StatusCode:{}'.format(self.StatusCode)
s += ', StatusCode:{0}'.format(self.StatusCode)
if self.SourceTimestamp is not None:
s += ', SourceTimestamp:{}'.format(self.SourceTimestamp)
s += ', SourceTimestamp:{0}'.format(self.SourceTimestamp)
if self.ServerTimestamp is not None:
s += ', ServerTimestamp:{}'.format(self.ServerTimestamp)
s += ', ServerTimestamp:{0}'.format(self.ServerTimestamp)
if self.SourcePicoseconds is not None:
s += ', SourcePicoseconds:{}'.format(self.SourcePicoseconds)
s += ', SourcePicoseconds:{0}'.format(self.SourcePicoseconds)
if self.ServerPicoseconds is not None:
s += ', ServerPicoseconds:{}'.format(self.ServerPicoseconds)
s += ', ServerPicoseconds:{0}'.format(self.ServerPicoseconds)
s += ')'
return s
......
......@@ -7,9 +7,9 @@ def bump_version():
s = f.read()
m = re.search(r'version="(.*)\.(.*)\.(.*)",', s)
v1, v2, v3 = m.groups()
oldv = "{}.{}.{}".format(v1, v2, v3)
newv = "{}.{}.{}".format(v1, v2, str(int(v3) + 1))
print("Current version is: {}, write new version, ctrl-c to exit".format(oldv))
oldv = "{0}.{1}.{2}".format(v1, v2, v3)
newv = "{0}.{1}.{2}".format(v1, v2, str(int(v3) + 1))
print("Current version is: {0}, write new version, ctrl-c to exit".format(oldv))
ans = input(newv)
if ans:
newv = ans
......@@ -25,7 +25,7 @@ def release():
if ans in ("", "y", "yes"):
os.system("git add setup.py")
os.system("git commit -m 'new release'")
os.system("git tag {}".format(v))
os.system("git tag {0}".format(v))
ans = input("change committed, push to server?(Y/n)")
if ans in ("", "y", "yes"):
os.system("git push")
......
This diff is collapsed.
......@@ -11,14 +11,14 @@ if __name__ == "__main__":
outputfile.write(" Null = 0\n")
for line in inputfile:
name, nb, datatype = line.split(",")
outputfile.write(" {} = {}\n".format(name, nb))
outputfile.write(" {0} = {1}\n".format(name, nb))
inputfile.close()
inputfile = open("NodeIds.csv")
outputfile.write("\n\nObjectIdNames = {}\n")
outputfile.write("ObjectIdNames[0] = 'Null'\n".format(nb, name))
for line in inputfile:
name, nb, datatype = line.split(",")
outputfile.write("ObjectIdNames[{}] = '{}'\n".format(nb, name))
outputfile.write("ObjectIdNames[{0}] = '{1}'\n".format(nb, name))
inputfile = open("AttributeIds.csv")
outputfile = open("../opcua/ua/attribute_ids.py", "w")
......@@ -29,5 +29,5 @@ if __name__ == "__main__":
outputfile.write("class AttributeIds(IntEnum):\n")
for line in inputfile:
name, nb = line.split(",")
outputfile.write(" {} = {}\n".format(name.strip(), nb.strip()))
outputfile.write(" {0} = {1}\n".format(name.strip(), nb.strip()))
......@@ -33,7 +33,7 @@ class Bit(object):
self.length = 1
def __str__(self):
return "(Bit: {}, container:{}, idx:{})".format(self.name, self.container, self.idx)
return "(Bit: {0}, container:{1}, idx:{2})".format(self.name, self.container, self.idx)
__repr__ = __str__
class Struct(object):
......@@ -56,7 +56,7 @@ class Struct(object):
raise Exception("field not found: " + name)
def __str__(self):
return "Struct {}:{}".format(self.name, self.basetype)
return "Struct {0}:{1}".format(self.name, self.basetype)
__repr__ = __str__
......@@ -72,7 +72,7 @@ class Field(object):
self.bitlength = 1
def __str__(self):
return "Field {}({})".format(self.name, self.uatype)
return "Field {0}({1})".format(self.name, self.uatype)
__repr__ = __str__
......@@ -121,7 +121,7 @@ class Field(object):
else:
ty = "OpcUa::" + self.uatype
if self.length:
ty = "std::vector<{}>".format(ty)
ty = "std::vector<{0}>".format(ty)
return ty
class Enum(object):
......@@ -132,7 +132,7 @@ class Enum(object):
self.doc = ""
def get_ctype(self):
return "uint{}_t".format(self.uatype)
return "uint{0}_t".format(self.uatype)
class EnumValue(object):
def __init__(self):
......@@ -187,13 +187,13 @@ def reorder_structs(model):
if not s2.waitingfor:
newstructs.append(s2)
if len(model.structs) != len(newstructs):
print("Error while reordering structs, some structs could not be reinserted, had {} structs, we now have {} structs".format(len(model.structs), len(newstructs)))
print("Error while reordering structs, some structs could not be reinserted, had {0} structs, we now have {1} structs".format(len(model.structs), len(newstructs)))
s1 = set(model.structs)
s2 = set(newstructs)
rest = s1 -s2
print("Variant" in types)
for s in s1-s2:
print("{} is waiting for: {}".format(s, s.waitingfor))
print("{0} is waiting for: {1}".format(s, s.waitingfor))
#print(s1 -s2)
#print(waiting)
model.structs = newstructs
......
......@@ -30,7 +30,7 @@ if __name__ == "__main__":
outputfile.write("class StatusCodes(object):\n")
for name, val, doc in codes:
doc = doc.strip()
outputfile.write(" {} = {}\n".format(name, val))
outputfile.write(" {0} = {1}\n".format(name, val))
outputfile.write("\n")
outputfile.write("\n")
......@@ -38,7 +38,7 @@ if __name__ == "__main__":
for name, val, doc in codes:
doc = doc.strip()
doc = doc.replace("'", '"')
outputfile.write(" {}: ('{}', '{}'),\n".format(val, name, doc))
outputfile.write(" {0}: ('{1}', '{2}'),\n".format(val, name, doc))
outputfile.write("}\n")
outputfile.write("\n")
outputfile.write("\n")
......
......@@ -25,7 +25,7 @@ def extensionobject_from_binary(data):
return e
klass = ExtensionClasses[TypeId.Identifier]
if body is None:
raise UaError("parsing ExtensionObject {} without data".format(klass.__name__))
raise UaError("parsing ExtensionObject {0} without data".format(klass.__name__))
return klass.from_binary(body)
......@@ -41,7 +41,7 @@ def extensionobject_to_binary(obj):
Encoding = 0
Body = None
if obj is not None:
TypeId = FourByteNodeId(getattr(ObjectIds, "{}_Encoding_DefaultBinary".format(obj.__class__.__name__)))
TypeId = FourByteNodeId(getattr(ObjectIds, "{0}_Encoding_DefaultBinary".format(obj.__class__.__name__)))
Encoding |= (1 << 0)
Body = obj.to_binary()
packet = []
......
......@@ -274,7 +274,7 @@ class SubscriptionTests(object):
elif node == v2:
self.assertEqual(startv2, val)
else:
self.fail("Error node {} is neither {} nor {}".format(node, v1, v2))
self.fail("Error node {0} is neither {1} nor {2}".format(node, v1, v2))
sub.delete()
......
......@@ -147,7 +147,7 @@ class XmlTests(object):
vnew = onew.add_variable(new_ns, "xmlns_new_var", 9.99)
o_no_export = self.opc.nodes.objects.add_object(ref_ns, "xmlns_parent")
v_no_parent = o_no_export.add_variable(new_ns, "xmlns_new_var_no_parent", 9.99)
o_bname = onew.add_object("ns={};i=4000".format(new_ns), "{}:BNAME".format(bname_ns))
o_bname = onew.add_object("ns={0};i=4000".format(new_ns), "{0}:BNAME".format(bname_ns))
nodes = [o, o50, o200, onew, vnew, v_no_parent, o_bname]
print("CREATED", nodes, o_no_export)
......@@ -266,7 +266,7 @@ class XmlTests(object):
dim = node.get_array_dimensions()
nclass = node.get_node_class()
path = "export-{}.xml".format(typename)
path = "export-{0}.xml".format(typename)
self.opc.export_xml([node], path)
self.opc.delete_nodes([node])
new_nodes = self.opc.import_xml(path)
......
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment