move classes using influx from secop to influxgraph

+ fix parameter change command in secop
This commit is contained in:
2024-10-23 16:32:49 +02:00
parent 7471a0c171
commit 7736e0f7e3
3 changed files with 56 additions and 71 deletions

View File

@ -1,10 +1,13 @@
import time import time
import logging import logging
from colors import assign_colors_to_curves
import json import json
import io import io
import uuid
from influxdb import InfluxDB, InfluxDataGetter
from colors import assign_colors_to_curves
from chart_config import ChartConfig from chart_config import ChartConfig
from base import Instrument from base import Instrument, get_abs_time
from secop import SecopClient, SecopInstrument
class InfluxGraph: class InfluxGraph:
@ -44,21 +47,6 @@ class InfluxGraph:
self.lastvalues = {} self.lastvalues = {}
self.variables = {} # name:label self.variables = {} # name:label
def get_abs_time(self, times):
"""
Gets the absolute times for the given potential relative times. If a given timestamp is less than
one year, then the value is relative and converted into an absolute timestamp
Parameters :
times([(float)]) : an array of unix timestamps or relative duration (< 1 year) as floats
Returns :
[(float)] : an array of absolute unix timestamps as floats
"""
now = int(time.time() + 0.999)
oneyear = 365 * 24 * 3600
return [t + now if t < oneyear else t for t in times]
def complete_to_end_and_feed_lastvalues(self, result, endtime): def complete_to_end_and_feed_lastvalues(self, result, endtime):
""" """
Completes the data until the last requested point in time by adding the last known y-value at the end point. Completes the data until the last requested point in time by adding the last known y-value at the end point.
@ -93,7 +81,7 @@ class InfluxGraph:
and an array of points as a tuple (timestamp, y-value as float) and an array of points as a tuple (timestamp, y-value as float)
""" """
time = [float(t) for t in time.split(',')] time = [float(t) for t in time.split(',')]
start, end, now = self.get_abs_time(time + [0]) start, end, now = get_abs_time(time + [0])
start, end, now = int(start), int(end), int(now) start, end, now = int(start), int(end), int(now)
queried_time_range = [start, end] queried_time_range = [start, end]
queried_variables = variables.split(',') queried_variables = variables.split(',')
@ -121,7 +109,7 @@ class InfluxGraph:
client) and the server unix timestamp in seconds corresponding to the time asked by the client client) and the server unix timestamp in seconds corresponding to the time asked by the client
""" """
time = [float(t) for t in time.split(',')] time = [float(t) for t in time.split(',')]
return dict(type='time', time= self.get_abs_time(time)) return dict(type='time', time=get_abs_time(time))
def w_getvars(self, time, userconfiguration = None): def w_getvars(self, time, userconfiguration = None):
""" """
@ -143,7 +131,7 @@ class InfluxGraph:
""" """
time = [float(t) for t in time.split(',')] time = [float(t) for t in time.split(',')]
end_time = int(self.get_abs_time(time)[-1]) end_time = int(get_abs_time(time)[-1])
if not userconfiguration == None : userconfiguration = json.loads(userconfiguration) if not userconfiguration == None : userconfiguration = json.loads(userconfiguration)
@ -189,7 +177,7 @@ class InfluxGraph:
""" """
time = [float(t) for t in time.split(',')] time = [float(t) for t in time.split(',')]
start, end = self.get_abs_time(time) start, end = get_abs_time(time)
start, end = int(start), int(end) start, end = int(start), int(end)
queried_variables = variables.split(',') queried_variables = variables.split(',')
@ -218,7 +206,7 @@ class InfluxGraph:
""" """
if self.livemode != self.LIVE: if self.livemode != self.LIVE:
return None return None
now, = self.get_abs_time([0]) now, = get_abs_time([0])
result = self.influx_data_getter.poll_last_values(list(self.variables.keys()), self.lastvalues, now) result = self.influx_data_getter.poll_last_values(list(self.variables.keys()), self.lastvalues, now)
for variable, values in list(result.items()): for variable, values in list(result.items()):
@ -245,14 +233,14 @@ class InfluxGraph:
class InfluxInstrument(Instrument): class InfluxInstrument(Instrument):
def __init__(self, instr_name, inst_config=None): def __init__(self, instr_name, inst_config=None):
super().__init__()
self.db = InfluxDB() self.db = InfluxDB()
self.influx_data_getter = InfluxDataGetter(self.db, inst_name) self.influx_data_getter = InfluxDataGetter(self.db, instr_name)
self.clients = {}
self.title = instr_name self.title = instr_name
self.device = self.influx_data_getter.get_device_name(int(datetime.now().timestamp())) self.device = self.influx_data_getter.get_device_name(int(time.time()))
def new_client(self): def new_client(self):
return self.register(InfluxClient()) return self.register(InfluxClient(self))
class InfluxParams: class InfluxParams:
@ -261,14 +249,6 @@ class InfluxParams:
self.id = uuid.uuid4().hex[0:15] self.id = uuid.uuid4().hex[0:15]
self.queue = [] self.queue = []
def poll(self):
messages = self.queue
self.queue = []
msg = self.graphpoll()
if msg:
messages.append(msg)
return messages
def info(self): def info(self):
return ["na"] return ["na"]
@ -286,8 +266,40 @@ class InfluxParams:
class InfluxClient(InfluxParams, InfluxGraph): class InfluxClient(InfluxParams, InfluxGraph):
def __init__(self): def __init__(self, instrument):
InfluxParams.__init__(self) InfluxParams.__init__(self)
InfluxGraph.__init__(self, instrument.influx_data_getter, instrument.title) InfluxGraph.__init__(self, instrument.influx_data_getter, instrument.title)
def poll(self):
messages = self.queue
self.queue = []
msg = self.graphpoll()
if msg:
messages.append(msg)
return messages
class SecopInfluxClient(SecopClient, InfluxGraph):
def __init__(self, instrument):
SecopClient.__init__(self, instrument)
InfluxGraph.__init__(self, instrument.influx_data_getter, instrument.title)
def poll(self):
messages = super().poll()
msg = self.graphpoll()
if msg:
messages.append(msg)
return messages
class SecopInfluxInstrument(SecopInstrument):
def __init__(self, inst_name, instrument_config):
super().__init__(inst_name, instrument_config)
self.db = InfluxDB()
self.influx_data_getter = InfluxDataGetter(self.db, inst_name)
self.device = self.influx_data_getter.get_device_name(int(time.time()))
def new_client(self):
return self.register(SecopInfluxClient(self))

View File

@ -4,6 +4,6 @@ import sys
import pathlib import pathlib
sys.path.insert(0, str((pathlib.Path(__file__) / '..').resolve())) sys.path.insert(0, str((pathlib.Path(__file__) / '..').resolve()))
import webserver import webserver
from secop import SecopInfluxInstrument from influxgraph import SecopInfluxInstrument
webserver.instrument = webserver.main(SecopInfluxInstrument) webserver.instrument = webserver.main(SecopInfluxInstrument)

View File

@ -1,9 +1,6 @@
import time
import logging import logging
import uuid import uuid
from base import Instrument, get_abs_time from base import Instrument, get_abs_time
from influxdb import InfluxDB, InfluxDataGetter
from influxgraph import InfluxGraph
from frappy.client import SecopClient as SecNodeClient from frappy.client import SecopClient as SecNodeClient
from frappy.lib.enum import EnumMember from frappy.lib.enum import EnumMember
from frappy.datatypes import get_datatype from frappy.datatypes import get_datatype
@ -98,15 +95,17 @@ class SecopClient:
logging.info('SENDCOMMAND %r', command) logging.info('SENDCOMMAND %r', command)
if not command.strip(): if not command.strip():
return dict(type='accept-command') return dict(type='accept-command')
scmd = command.split(' ') if command.startswith('change '):
if scmd[0] != 'change': command = command[7:]
scmd.insert(0, 'change') modpar, _, strvalue = command.partition(' ')
# return dict(type='accept-command', error=f'do not know how to do {command!r}') module, _, parameter = modpar.partition(':')
module, _, parameter = scmd[1].partition(':')
if not parameter: if not parameter:
parameter = 'target' parameter = 'target'
node = self.instrument.node_map[module] node = self.instrument.node_map[module]
result = node.setParameterFromString(module, parameter, scmd[2]) try:
node.setParameterFromString(module, parameter, strvalue)
except Exception as e:
print(f"{e!r} converting {strvalue} to {node.modules[module]['parameters'][parameter]['datatype']}")
return dict(type='accept-command') return dict(type='accept-command')
def w_gettime(self, time): def w_gettime(self, time):
@ -138,7 +137,6 @@ class SecopInstrument(Instrument):
# self.test_day = [int(x) for x in test_day.split('-')] if test_day else None # self.test_day = [int(x) for x in test_day.split('-')] if test_day else None
self.title = inst_name self.title = inst_name
self.device = 'UNDEFINED' self.device = 'UNDEFINED'
self.clients = {}
self.nodes = [] self.nodes = []
self.node_map = {} self.node_map = {}
for host_port in host_ports.split(','): for host_port in host_ports.split(','):
@ -162,28 +160,3 @@ class SecopInstrument(Instrument):
def new_client(self): def new_client(self):
return self.register(SecopClient(self)) return self.register(SecopClient(self))
class SecopInfluxClient(SecopClient, InfluxGraph):
def __init__(self, instrument):
SecopClient.__init__(self, instrument)
InfluxGraph.__init__(self, instrument.influx_data_getter, instrument.title)
def poll(self):
messages = super().poll()
msg = self.graphpoll()
if msg:
messages.append(msg)
return messages
class SecopInfluxInstrument(SecopInstrument):
def __init__(self, inst_name, instrument_config):
super().__init__(inst_name, instrument_config)
self.db = InfluxDB()
self.influx_data_getter = InfluxDataGetter(self.db, inst_name)
self.device = self.influx_data_getter.get_device_name(int(time.time()))
def new_client(self):
return self.register(SecopInfluxClient(self))