rework SECoP: redesign message class, fix command reply

This commit is contained in:
l_samenv
2024-09-27 14:25:11 +02:00
parent cd306c45ac
commit 415d4c86f6

View File

@@ -168,7 +168,7 @@ def reply():
logging.error('%s', traceback.format_exc())
circularlog.log()
msg = dict(type='error', request=path[1:], error=repr(e))
resp = flask.Response(json.dumps(msg, cls=MyEncoder), mimetype='application/json')
resp = flask.Response(json.dumps(msg), mimetype='application/json')
resp.headers['Access-Control-Allow-Origin'] = '*'
return resp
@@ -860,22 +860,33 @@ class DummyInstrument(Instrument):
return self.register(DummyClient(self.host_port))
class SecopMsg:
par = None
value = None
class SecopMsg(tuple):
asynch = False
def __init__(self, line):
sl = line.split(' ', 2)
def __new__(cls, line):
sl = (line+' ').split(' ', 2)
if len(sl[0].split(',')) > 1:
self.type = 'idn'
self.value = line
return tuple.__new__(cls, ('idn', None, line))
else:
self.type = sl[0]
if len(sl) > 1:
self.par = sl[1]
if len(sl) > 2:
self.value = json.loads(sl[2])
self.asynch = self.type in ('update', 'error_update')
typ, par, val = sl
val = val.strip() or None
if val:
val = json.loads(val)
if typ in ('update', 'error_update'):
cls = SecopAsyncMsg
return tuple.__new__(cls, (typ, par, val))
@property
def type(self):
return self[0]
@property
def par(self):
return self[1]
@property
def value(self):
return self[2]
def __repr__(self):
value = repr(self.value)
@@ -883,14 +894,9 @@ class SecopMsg:
value = value[:50] + '...'
return "SecopMsg('%s %s %s')" % (self.type, self.par, value)
def toJSON(self):
return json.dumps([self.type, self.par, self.value])
class MyEncoder(json.JSONEncoder):
def default(self, obj):
toJSON = getattr(obj, 'toJSON')
return toJSON() if toJSON else super().default(obj)
class SecopAsyncMsg(SecopMsg):
asynch = True
def SecopEncode(cmd, par=None, value=None):
@@ -924,7 +930,7 @@ def convert_event(messages):
if msg.type == 'update':
updates.append(dict(name=msg.par, value=msg.value[0]))
elif msg.type == 'error_update':
updates.append(dict(name=msg.par, value=f'{msg.value[0]} - {msg.value[1]}'))
updates.append(dict(name=msg.par, error=f'{msg.value[0]} - {msg.value[1]}'))
# updates.append(dict(name=msg.par, value=str(msg.value[0])))
return [dict(type='update', updates=updates)]
@@ -1074,8 +1080,8 @@ class SecopClient:
else:
replytype = None
# cmd = "change " + command
print(command, replytype)
return node.cmd_reply(command, replytype)
reply = node.cmd_reply(command, replytype)
return dict(type='accept-command', result=reply)
def poll(self):
messages = []