Refactoring in core. Added delegates for values and states

This commit is contained in:
Alexander Nozik 2017-11-21 19:11:12 +03:00
parent b070156c51
commit b4c738adc2
40 changed files with 173 additions and 108 deletions

View File

@ -92,18 +92,18 @@ public class NumassClient implements AutoCloseable, Responder {
} }
public Meta getCurrentRun() { public Meta getCurrentRun() {
return respond(requestActionBase("numass.run", "get").build()).meta(); return respond(requestActionBase("numass.run", "get").build()).getMeta();
} }
public Meta startRun(String name) { public Meta startRun(String name) {
return respond(requestActionBase("numass.run", "start") return respond(requestActionBase("numass.run", "start")
.putMetaValue("path", name) .putMetaValue("path", name)
.build()).meta(); .build()).getMeta();
} }
public Meta resetRun() { public Meta resetRun() {
return respond(requestActionBase("numass.run", "reset") return respond(requestActionBase("numass.run", "reset")
.build()).meta(); .build()).getMeta();
} }
public Meta sendNumassData(String path, String fileName) { public Meta sendNumassData(String path, String fileName) {
@ -137,7 +137,7 @@ public class NumassClient implements AutoCloseable, Responder {
.setData(buffer) .setData(buffer)
.build(); .build();
return respond(bin).meta(); return respond(bin).getMeta();
} catch (IOException ex) { } catch (IOException ex) {
return StorageUtils.getErrorMeta(ex); return StorageUtils.getErrorMeta(ex);
} }
@ -157,7 +157,7 @@ public class NumassClient implements AutoCloseable, Responder {
env.putMetaValue("name", Arrays.asList(stateNames)); env.putMetaValue("name", Arrays.asList(stateNames));
} }
Meta response = respond(env.build()).meta(); Meta response = respond(env.build()).getMeta();
if (response.getBoolean("success", true)) { if (response.getBoolean("success", true)) {
Map<String, Value> res = new HashMap<>(); Map<String, Value> res = new HashMap<>();
response.getMetaList("state").stream().forEach((stateMeta) -> { response.getMetaList("state").stream().forEach((stateMeta) -> {
@ -183,7 +183,7 @@ public class NumassClient implements AutoCloseable, Responder {
.setValue("value", value) .setValue("value", value)
.build()); .build());
return respond(env.build()).meta(); return respond(env.build()).getMeta();
} }
/** /**
@ -200,7 +200,7 @@ public class NumassClient implements AutoCloseable, Responder {
.setValue("value", state.getValue()) .setValue("value", state.getValue())
.build()); .build());
}); });
return respond(env.build()).meta(); return respond(env.build()).getMeta();
} }
public Meta addNote(String text, Instant time) { public Meta addNote(String text, Instant time) {
@ -209,7 +209,7 @@ public class NumassClient implements AutoCloseable, Responder {
if (time != null) { if (time != null) {
env.putMetaValue("note.time", time); env.putMetaValue("note.time", time);
} }
return respond(env.build()).meta(); return respond(env.build()).getMeta();
} }
public Meta getNotes(int limit) { public Meta getNotes(int limit) {
@ -217,7 +217,7 @@ public class NumassClient implements AutoCloseable, Responder {
if (limit > 0) { if (limit > 0) {
env.putMetaValue("limit", limit); env.putMetaValue("limit", limit);
} }
return respond(env.build()).meta(); return respond(env.build()).getMeta();
} }
/** /**

View File

@ -55,15 +55,15 @@ internal fun createChannel(meta: Meta): PKT8Channel {
class PKT8Channel(private val _meta: Meta, val func: (Double) -> Double) : Named, Metoid { class PKT8Channel(private val _meta: Meta, val func: (Double) -> Double) : Named, Metoid {
override fun getName(): String { override fun getName(): String {
return meta().getString("name") return getMeta().getString("name")
} }
override fun meta(): Meta { override fun getMeta(): Meta {
return _meta return _meta
} }
fun description(): String { fun description(): String {
return meta().getString("description", "") return getMeta().getString("description", "")
} }
/** /**

View File

@ -92,7 +92,7 @@ class PKT8Device(context: Context, meta: Meta) : PortSensor<PKT8Result>(context,
val abuf: String val abuf: String
get() = getState(ABUF).stringValue() get() = getState(ABUF).stringValue()
private val duration = Duration.parse(meta().getString("averagingDuration", "PT30S")) private val duration = Duration.parse(getMeta().getString("averagingDuration", "PT30S"))
private fun buildLoader(connection: StorageConnection): TableLoader { private fun buildLoader(connection: StorageConnection): TableLoader {
val storage = connection.storage val storage = connection.storage
@ -110,8 +110,8 @@ class PKT8Device(context: Context, meta: Meta) : PortSensor<PKT8Result>(context,
override fun init() { override fun init() {
//read channel configuration //read channel configuration
if (meta().hasMeta("channel")) { if (getMeta().hasMeta("channel")) {
for (node in meta().getMetaList("channel")) { for (node in getMeta().getMetaList("channel")) {
val designation = node.getString("designation", "default") val designation = node.getString("designation", "default")
this.channels.put(designation, createChannel(node)) this.channels.put(designation, createChannel(node))
} }
@ -137,8 +137,8 @@ class PKT8Device(context: Context, meta: Meta) : PortSensor<PKT8Result>(context,
} }
setSPS(meta().getInt("sps", 0)) setSPS(getMeta().getInt("sps", 0))
setBUF(meta().getInt("abuf", 100)) setBUF(getMeta().getInt("abuf", 100))
// setting up the collector // setting up the collector
storageHelper = StorageHelper(this) { connection: StorageConnection -> this.buildLoader(connection) } storageHelper = StorageHelper(this) { connection: StorageConnection -> this.buildLoader(connection) }
@ -156,7 +156,7 @@ class PKT8Device(context: Context, meta: Meta) : PortSensor<PKT8Result>(context,
//setup connection //setup connection
val handler: Port = if ("virtual" == portName) { val handler: Port = if ("virtual" == portName) {
logger.info("Starting {} using virtual debug port", name) logger.info("Starting {} using virtual debug port", name)
PKT8VirtualPort("PKT8", meta().getMetaOrEmpty("debug")) PKT8VirtualPort("PKT8", getMeta().getMetaOrEmpty("debug"))
} else { } else {
super.buildPort(portName) super.buildPort(portName)
} }

View File

@ -171,7 +171,7 @@ class PKT8Display : DeviceDisplay<PKT8Device>(), MeasurementListener {
} }
init { init {
if (device.meta().hasMeta("plotConfig")) { if (device.getMeta().hasMeta("plotConfig")) {
with(plotFrame.plots) { with(plotFrame.plots) {
//configure(device.meta().getMeta("plotConfig")) //configure(device.meta().getMeta("plotConfig"))
TimePlot.setMaxItems(this, 1000) TimePlot.setMaxItems(this, 1000)
@ -199,7 +199,7 @@ class PKT8Display : DeviceDisplay<PKT8Device>(), MeasurementListener {
} else { } else {
device.channels.values.find { it.name == channelName }?.let { device.channels.values.find { it.name == channelName }?.let {
TimePlot(it.name).apply { TimePlot(it.name).apply {
configure(it.meta()) configure(it.getMeta())
plotFrame.add(this) plotFrame.add(this)
} }
} }

View File

@ -31,7 +31,7 @@ class PKT8VirtualPort(portName: String, meta: Meta) : VirtualPort(meta), Metoid
"s" -> { "s" -> {
val letters = arrayOf("a", "b", "c", "d", "e", "f", "g", "h") val letters = arrayOf("a", "b", "c", "d", "e", "f", "g", "h")
for (letter in letters) { for (letter in letters) {
val channelMeta = MetaUtils.findNodeByValue(meta(), "channel", "letter", Value.of(letter)).orElse(Meta.empty()) val channelMeta = MetaUtils.findNodeByValue(getMeta(), "channel", "letter", Value.of(letter)).orElse(Meta.empty())
val average: Double val average: Double
val sigma: Double val sigma: Double

View File

@ -153,7 +153,7 @@ public class VirtualLambdaPort extends VirtualPort {
} }
@Override @Override
public Meta meta() { public Meta getMeta() {
return Meta.buildEmpty("virtualPort"); return Meta.buildEmpty("virtualPort");
} }

View File

@ -1,8 +1,11 @@
package inr.numass.control.magnet package inr.numass.control.magnet
import hep.dataforge.context.Context
import hep.dataforge.context.ContextAware
import hep.dataforge.control.ports.Port import hep.dataforge.control.ports.Port
class LambdaPortController(private val port: Port) : Port.PortController { class LambdaPortController(private val _context: Context, private val port: Port) : Port.PortController, ContextAware {
override fun getContext(): Context = _context
private var address: Int = -1; private var address: Int = -1;

View File

@ -74,7 +74,7 @@ class MspDevice(context: Context, meta: Meta) : PortSensor<Values>(context, meta
val isFilamentOn: Boolean val isFilamentOn: Boolean
get() = getState("filamentOn").booleanValue() get() = getState("filamentOn").booleanValue()
private val averagingDuration: Duration = Duration.parse(meta().getString("averagingDuration", "PT30S")) private val averagingDuration: Duration = Duration.parse(getMeta().getString("averagingDuration", "PT30S"))
@Throws(ControlException::class) @Throws(ControlException::class)
override fun init() { override fun init() {
@ -140,7 +140,7 @@ class MspDevice(context: Context, meta: Meta) : PortSensor<Values>(context, meta
@Throws(MeasurementException::class) @Throws(MeasurementException::class)
override fun createMeasurement(): PeakJumpMeasurement { override fun createMeasurement(): PeakJumpMeasurement {
val measurementMeta = meta().getMeta("peakJump") val measurementMeta = getMeta().getMeta("peakJump")
val s = measurementMeta.getString("type", "peakJump") val s = measurementMeta.getString("type", "peakJump")
if (s == "peakJump") { if (s == "peakJump") {
val measurement = PeakJumpMeasurement(measurementMeta) val measurement = PeakJumpMeasurement(measurementMeta)

View File

@ -71,7 +71,7 @@ class MspDisplay() : DeviceDisplay<MspDevice>(), DeviceListener, NamedValueListe
inner class MspView : View("Numass mass-spectrometer measurement") { inner class MspView : View("Numass mass-spectrometer measurement") {
private val plotFrameMeta: Meta = device.meta().getMeta("plotConfig", device.meta) private val plotFrameMeta: Meta = device.getMeta().getMeta("plotConfig", device.meta)
private val plotFrame: PlotFrame by lazy { private val plotFrame: PlotFrame by lazy {
val basePlotConfig = MetaBuilder("plotFrame") val basePlotConfig = MetaBuilder("plotFrame")

View File

@ -0,0 +1,62 @@
package inr.numass.control
import hep.dataforge.control.devices.Stateful
import hep.dataforge.values.Value
import java.time.Instant
import kotlin.reflect.KProperty
class StateDelegate(private val stateName: String?) {
operator fun getValue(thisRef: Stateful, property: KProperty<*>): Value? =
thisRef.getState(stateName ?: property.name)
operator fun setValue(thisRef: Stateful, property: KProperty<*>, value: Value?) {
thisRef.setState(stateName ?: property.name, value);
}
}
class StringStateDelegate(private val valueName: String?) {
operator fun getValue(thisRef: Stateful, property: KProperty<*>): String? =
thisRef.getState(valueName ?: property.name).stringValue()
operator fun setValue(thisRef: Stateful, property: KProperty<*>, value: String?) {
thisRef.setState(valueName ?: property.name, value);
}
}
class BooleanStateDelegate(private val valueName: String?) {
operator fun getValue(thisRef: Stateful, property: KProperty<*>): Boolean? =
thisRef.getState(valueName ?: property.name).booleanValue()
operator fun setValue(thisRef: Stateful, property: KProperty<*>, value: Boolean?) {
thisRef.setState(valueName ?: property.name, value);
}
}
class TimeStateDelegate(private val valueName: String?) {
operator fun getValue(thisRef: Stateful, property: KProperty<*>): Instant? =
thisRef.getState(valueName ?: property.name).timeValue()
operator fun setValue(thisRef: Stateful, property: KProperty<*>, value: Instant?) {
thisRef.setState(valueName ?: property.name, value);
}
}
class NumberStateDelegate(private val valueName: String?) {
operator fun getValue(thisRef: Stateful, property: KProperty<*>): Number? =
thisRef.getState(valueName ?: property.name).numberValue()
operator fun setValue(thisRef: Stateful, property: KProperty<*>, value: Number?) {
thisRef.setState(valueName ?: property.name, value);
}
}
/**
* Delegate states to read/write property
*/
fun Stateful.state(valueName: String? = null) = StateDelegate(valueName)
fun Stateful.stringState(valueName: String? = null) = StringStateDelegate(valueName)
fun Stateful.booleanState(valueName: String? = null) = BooleanStateDelegate(valueName)
fun Stateful.timeState(valueName: String? = null) = TimeStateDelegate(valueName)
fun Stateful.numberState(valueName: String? = null) = NumberStateDelegate(valueName)

View File

@ -42,7 +42,7 @@ fun connectStorage(device: Device, config: Meta) {
if (config.hasMeta("storage") && device.acceptsRole(Roles.STORAGE_ROLE)) { if (config.hasMeta("storage") && device.acceptsRole(Roles.STORAGE_ROLE)) {
val numassRun = ClientUtils.getRunName(config) val numassRun = ClientUtils.getRunName(config)
config.getMetaList("storage").forEach { node -> config.getMetaList("storage").forEach { node ->
device.context.logger.info("Creating storage for device with meta: {}", node) device.context.logger.info("Creating storage for device with getMeta: {}", node)
//building storage in a separate thread //building storage in a separate thread
Thread { Thread {
var storage = StorageFactory.buildStorage(device.context, node) var storage = StorageFactory.buildStorage(device.context, node)

View File

@ -41,7 +41,7 @@ class CM32Device(context: Context, meta: Meta) : PortSensor<Double>(context, met
} }
override fun getType(): String { override fun getType(): String {
return meta().getString("type", "Leibold CM32") return getMeta().getString("type", "Leibold CM32")
} }
private inner class CMVacMeasurement : SimpleMeasurement<Double>() { private inner class CMVacMeasurement : SimpleMeasurement<Double>() {

View File

@ -23,7 +23,7 @@ import inr.numass.control.DeviceView
@DeviceView(VacDisplay::class) @DeviceView(VacDisplay::class)
class MKSBaratronDevice(context: Context, meta: Meta) : PortSensor<Double>(context, meta) { class MKSBaratronDevice(context: Context, meta: Meta) : PortSensor<Double>(context, meta) {
private val channel: Int = meta().getInt("channel", 2) private val channel: Int = getMeta().getInt("channel", 2)
override fun createMeasurement(): Measurement<Double> { override fun createMeasurement(): Measurement<Double> {
@ -31,7 +31,7 @@ class MKSBaratronDevice(context: Context, meta: Meta) : PortSensor<Double>(conte
} }
override fun getType(): String { override fun getType(): String {
return meta().getString("type", "MKS baratron") return getMeta().getString("type", "MKS baratron")
} }
@Throws(ControlException::class) @Throws(ControlException::class)

View File

@ -36,7 +36,7 @@ import java.util.regex.Pattern
class MKSVacDevice(context: Context, meta: Meta) : PortSensor<Double>(context, meta) { class MKSVacDevice(context: Context, meta: Meta) : PortSensor<Double>(context, meta) {
private val deviceAddress: String private val deviceAddress: String
get() = meta().getString("address", "253") get() = getMeta().getString("address", "253")
private var isPowerOn: Boolean private var isPowerOn: Boolean
@ -62,7 +62,7 @@ class MKSVacDevice(context: Context, meta: Meta) : PortSensor<Double>(context, m
} }
} }
private val channel: Int = meta().getInt("channel", 5)!! private val channel: Int = getMeta().getInt("channel", 5)!!
@Throws(ControlException::class) @Throws(ControlException::class)
private fun talk(requestContent: String): String? { private fun talk(requestContent: String): String? {
@ -123,7 +123,7 @@ class MKSVacDevice(context: Context, meta: Meta) : PortSensor<Double>(context, m
} }
override fun getType(): String { override fun getType(): String {
return meta().getString("type", "MKS vacuumeter") return getMeta().getString("type", "MKS vacuumeter")
} }
private inner class MKSVacMeasurement : SimpleMeasurement<Double>() { private inner class MKSVacMeasurement : SimpleMeasurement<Double>() {

View File

@ -38,7 +38,7 @@ class MeradatVacDevice(context: Context, meta: Meta) : PortSensor<Double>(contex
} }
override fun getType(): String { override fun getType(): String {
return meta().getString("type", "Vit vacuumeter") return getMeta().getString("type", "Vit vacuumeter")
} }
@ -49,7 +49,7 @@ class MeradatVacDevice(context: Context, meta: Meta) : PortSensor<Double>(contex
private val base: String private val base: String
init { init {
base = String.format(":%02d", meta().getInt("address", 1)) base = String.format(":%02d", getMeta().getInt("address", 1))
val dataStr = base.substring(1) + REQUEST val dataStr = base.substring(1) + REQUEST
query = base + REQUEST + calculateLRC(dataStr) + "\r\n" query = base + REQUEST + calculateLRC(dataStr) + "\r\n"
response = Pattern.compile(base + "0304(\\w{4})(\\w{4})..\r\n") response = Pattern.compile(base + "0304(\\w{4})(\\w{4})..\r\n")

View File

@ -52,7 +52,7 @@ class VacCollectorDevice(context: Context, meta: Meta, val sensors: Collection<S
private val helper = StorageHelper(this, this::buildLoader) private val helper = StorageHelper(this, this::buildLoader)
private val averagingDuration: Duration private val averagingDuration: Duration
get() = Duration.parse(meta().getString("averagingDuration", "PT30S")) get() = Duration.parse(getMeta().getString("averagingDuration", "PT30S"))
override fun optDevice(name: Name): Optional<Device> { override fun optDevice(name: Name): Optional<Device> {
@ -122,7 +122,7 @@ class VacCollectorDevice(context: Context, meta: Meta, val sensors: Collection<S
override fun start() { override fun start() {
executor = Executors.newSingleThreadScheduledExecutor { r: Runnable -> Thread(r, "VacuumMeasurement thread") } executor = Executors.newSingleThreadScheduledExecutor { r: Runnable -> Thread(r, "VacuumMeasurement thread") }
val delay = meta().getInt("delay", 5)!! * 1000 val delay = getMeta().getInt("delay", 5)!! * 1000
currentTask = executor!!.scheduleWithFixedDelay({ currentTask = executor!!.scheduleWithFixedDelay({
sensors.forEach { sensor -> sensors.forEach { sensor ->
try { try {

View File

@ -68,7 +68,7 @@ class VacCollectorDisplay : DeviceDisplay<VacCollectorDevice>() {
private val plottables = TimePlottableGroup().apply { private val plottables = TimePlottableGroup().apply {
viewList.forEach { viewList.forEach {
val plot = TimePlot(it.getTitle(), it.device.name) val plot = TimePlot(it.getTitle(), it.device.name)
plot.configure(it.device.meta()) plot.configure(it.device.getMeta())
add(plot) add(plot)
} }
setValue("thickness", 3) setValue("thickness", 3)

View File

@ -78,7 +78,7 @@ open class VacDisplay : DeviceDisplay<Sensor<Double>>(), MeasurementListener {
} }
fun getTitle(): String{ fun getTitle(): String{
return device.meta().getString("title", device.name); return device.getMeta().getString("title", device.name);
} }
inner class VacView : View("Numass vacuumeter ${getTitle()}") { inner class VacView : View("Numass vacuumeter ${getTitle()}") {
@ -123,7 +123,7 @@ open class VacDisplay : DeviceDisplay<Sensor<Double>>(), MeasurementListener {
prefHeight = 60.0 prefHeight = 60.0
alignment = Pos.CENTER_RIGHT alignment = Pos.CENTER_RIGHT
textProperty().bind(valueProperty) textProperty().bind(valueProperty)
device.meta().optValue("color").ifPresent { colorValue -> textFill = Color.valueOf(colorValue.stringValue()) } device.getMeta().optValue("color").ifPresent { colorValue -> textFill = Color.valueOf(colorValue.stringValue()) }
style { style {
fontSize = 24.pt fontSize = 24.pt
fontWeight = FontWeight.BOLD fontWeight = FontWeight.BOLD
@ -136,7 +136,7 @@ open class VacDisplay : DeviceDisplay<Sensor<Double>>(), MeasurementListener {
prefHeight = 60.0 prefHeight = 60.0
prefWidth = 75.0 prefWidth = 75.0
alignment = Pos.CENTER_LEFT alignment = Pos.CENTER_LEFT
text = device.meta().getString("units", "mbar") text = device.getMeta().getString("units", "mbar")
style { style {
fontSize = 24.pt fontSize = 24.pt
} }

View File

@ -35,9 +35,9 @@ public class NumassDataUtils {
} }
@Override @Override
public Meta meta() { public Meta getMeta() {
MetaBuilder metaBuilder = new MetaBuilder(); MetaBuilder metaBuilder = new MetaBuilder();
sets.forEach(set -> metaBuilder.putNode(set.getName(), set.meta())); sets.forEach(set -> metaBuilder.putNode(set.getName(), set.getMeta()));
return metaBuilder; return metaBuilder;
} }

View File

@ -24,7 +24,7 @@ public interface NumassPoint extends Metoid, NumassBlock {
* @return * @return
*/ */
default double getVoltage() { default double getVoltage() {
return meta().getDouble(HV_KEY, 0); return getMeta().getDouble(HV_KEY, 0);
} }
/** /**
@ -41,7 +41,7 @@ public interface NumassPoint extends Metoid, NumassBlock {
*/ */
@Override @Override
default Instant getStartTime() { default Instant getStartTime() {
return meta().optValue(START_TIME_KEY).map(Value::timeValue).orElseGet(() -> getFirstBlock().getStartTime()); return getMeta().optValue(START_TIME_KEY).map(Value::timeValue).orElseGet(() -> getFirstBlock().getStartTime());
} }
/** /**
@ -52,7 +52,7 @@ public interface NumassPoint extends Metoid, NumassBlock {
@Override @Override
default Duration getLength() { default Duration getLength() {
return Duration.ofNanos( return Duration.ofNanos(
meta().optValue(LENGTH_KEY).map(Value::longValue) getMeta().optValue(LENGTH_KEY).map(Value::longValue)
.orElseGet(() -> getBlocks().mapToLong(it -> it.getLength().toNanos()).sum()) .orElseGet(() -> getBlocks().mapToLong(it -> it.getLength().toNanos()).sum())
); );
} }

View File

@ -33,7 +33,7 @@ public interface NumassSet extends Named, Metoid, Iterable<NumassPoint>, Provide
Stream<NumassPoint> getPoints(); Stream<NumassPoint> getPoints();
default String getDescription() { default String getDescription() {
return meta().getString(DESCRIPTION_KEY, ""); return getMeta().getString(DESCRIPTION_KEY, "");
} }
@NotNull @NotNull
@ -57,7 +57,7 @@ public interface NumassSet extends Named, Metoid, Iterable<NumassPoint>, Provide
* @return * @return
*/ */
default Instant getStartTime() { default Instant getStartTime() {
return meta().optValue(NumassPoint.START_TIME_KEY).map(Value::timeValue).orElseGet(() -> getFirstPoint().getStartTime()); return getMeta().optValue(NumassPoint.START_TIME_KEY).map(Value::timeValue).orElseGet(() -> getFirstPoint().getStartTime());
} }
/** /**

View File

@ -47,7 +47,7 @@ public class NumassDatFile implements NumassSet {
} }
@Override @Override
public Meta meta() { public Meta getMeta() {
return meta; return meta;
} }
@ -57,11 +57,11 @@ public class NumassDatFile implements NumassSet {
} }
private double getHVdev() { private double getHVdev() {
return meta().getDouble("dat.hvDev", 2.468555393226049); return getMeta().getDouble("dat.hvDev", 2.468555393226049);
} }
private boolean hasUset() { private boolean hasUset() {
return meta().getBoolean("dat.uSet", true); return getMeta().getBoolean("dat.uSet", true);
} }
private static String readHead(Path path) throws IOException { private static String readHead(Path path) throws IOException {

View File

@ -33,18 +33,18 @@ public class ClassicNumassPoint implements NumassPoint {
public Stream<NumassBlock> getBlocks() { public Stream<NumassBlock> getBlocks() {
// double u = envelope.meta().getDouble("external_meta.HV1_value", 0); // double u = envelope.meta().getDouble("external_meta.HV1_value", 0);
long length; long length;
if (envelope.meta().hasValue("external_meta.acquisition_time")) { if (envelope.getMeta().hasValue("external_meta.acquisition_time")) {
length = envelope.meta().getValue("external_meta.acquisition_time").longValue(); length = envelope.getMeta().getValue("external_meta.acquisition_time").longValue();
} else { } else {
length = envelope.meta().getValue("acquisition_time").longValue(); length = envelope.getMeta().getValue("acquisition_time").longValue();
} }
return Stream.of(new ClassicBlock(getStartTime(), Duration.ofSeconds(length))); return Stream.of(new ClassicBlock(getStartTime(), Duration.ofSeconds(length)));
} }
@Override @Override
public Instant getStartTime() { public Instant getStartTime() {
if (meta().hasValue("start_time")) { if (getMeta().hasValue("start_time")) {
return meta().getValue("start_time").timeValue(); return getMeta().getValue("start_time").timeValue();
} else { } else {
return Instant.EPOCH; return Instant.EPOCH;
} }
@ -52,12 +52,12 @@ public class ClassicNumassPoint implements NumassPoint {
@Override @Override
public double getVoltage() { public double getVoltage() {
return meta().getDouble("external_meta.HV1_value", 0); return getMeta().getDouble("external_meta.HV1_value", 0);
} }
@Override @Override
public Meta meta() { public Meta getMeta() {
return envelope.meta(); return envelope.getMeta();
} }
//TODO split blocks using meta //TODO split blocks using meta
@ -90,7 +90,7 @@ public class ClassicNumassPoint implements NumassPoint {
@NotNull @NotNull
@Override @Override
public Iterator<NumassEvent> iterator() { public Iterator<NumassEvent> iterator() {
double timeCoef = envelope.meta().getDouble("time_coeff", 50); double timeCoef = envelope.getMeta().getDouble("time_coeff", 50);
try { try {
ByteBuffer buffer = ByteBuffer.allocate(7000); ByteBuffer buffer = ByteBuffer.allocate(7000);
buffer.order(ByteOrder.LITTLE_ENDIAN); buffer.order(ByteOrder.LITTLE_ENDIAN);

View File

@ -148,11 +148,11 @@ public class NumassDataLoader extends AbstractLoader implements ObjectLoader<Env
} }
@Override @Override
public Meta meta() { public Meta getMeta() {
return getItems() return getItems()
.get(META_FRAGMENT_NAME) .get(META_FRAGMENT_NAME)
.get() .get()
.meta(); .getMeta();
} }
@ -178,7 +178,7 @@ public class NumassDataLoader extends AbstractLoader implements ObjectLoader<Env
return getItems().entrySet().stream() return getItems().entrySet().stream()
.filter(entry -> entry.getKey().startsWith(POINT_FRAGMENT_NAME) && entry.getValue() != null) .filter(entry -> entry.getKey().startsWith(POINT_FRAGMENT_NAME) && entry.getValue() != null)
.map(entry -> entry.getValue().get()) .map(entry -> entry.getValue().get())
.sorted(Comparator.comparing(t -> t.meta().getInt("external_meta.point_index", -1))); .sorted(Comparator.comparing(t -> t.getMeta().getInt("external_meta.point_index", -1)));
} }
@ -188,7 +188,7 @@ public class NumassDataLoader extends AbstractLoader implements ObjectLoader<Env
} }
public boolean isReversed() { public boolean isReversed() {
return meta().getBoolean("iteration_info.reverse", false); return this.getMeta().getBoolean("iteration_info.reverse", false);
} }
@Override @Override
@ -219,7 +219,7 @@ public class NumassDataLoader extends AbstractLoader implements ObjectLoader<Env
@Override @Override
public String getDescription() { public String getDescription() {
return meta().getString("description", "").replace("\\n", "\n"); return this.getMeta().getString("description", "").replace("\\n", "\n");
} }
@Override @Override

View File

@ -75,7 +75,7 @@ public class NumassStorage extends FileStorage {
NumassDataLoader.fromDir(this, file, null)); NumassDataLoader.fromDir(this, file, null));
} else { } else {
this.shelves.put(entryName(file), this.shelves.put(entryName(file),
new NumassStorage(this, entryName(file), meta())); new NumassStorage(this, entryName(file), getMeta()));
} }
} else if (file.getFileName().endsWith(NUMASS_ZIP_EXTENSION)) { } else if (file.getFileName().endsWith(NUMASS_ZIP_EXTENSION)) {
this.loaders.put(entryName(file), NumassDataLoader.fromFile(this, file)); this.loaders.put(entryName(file), NumassDataLoader.fromFile(this, file));
@ -163,7 +163,7 @@ public class NumassStorage extends FileStorage {
} }
public String getDescription() { public String getDescription() {
return meta().getString("description", ""); return getMeta().getString("description", "");
} }
public static class NumassDataPointEvent extends Event { public static class NumassDataPointEvent extends Event {
@ -187,11 +187,11 @@ public class NumassStorage extends FileStorage {
} }
public int getFileSize() { public int getFileSize() {
return meta().getInt(FILE_SIZE_KEY, 0); return getMeta().getInt(FILE_SIZE_KEY, 0);
} }
public String getFileName() { public String getFileName() {
return meta().getString(FILE_NAME_KEY); return getMeta().getString(FILE_NAME_KEY);
} }
@Override @Override

View File

@ -54,8 +54,8 @@ public class ProtoNumassPoint implements NumassPoint {
} }
@Override @Override
public Meta meta() { public Meta getMeta() {
return envelope.meta(); return envelope.getMeta();
} }
public static Instant ofEpochNanos(long nanos) { public static Instant ofEpochNanos(long nanos) {
@ -81,7 +81,7 @@ public class ProtoNumassPoint implements NumassPoint {
@Override @Override
public Duration getLength() { public Duration getLength() {
return Duration.ofNanos((long) (meta().getInt("b_size") / meta().getInt("sample_freq") * 1e9)); return Duration.ofNanos((long) (getMeta().getInt("b_size") / getMeta().getInt("sample_freq") * 1e9));
} }
@Override @Override
@ -99,7 +99,7 @@ public class ProtoNumassPoint implements NumassPoint {
@Override @Override
public Stream<NumassFrame> getFrames() { public Stream<NumassFrame> getFrames() {
Duration tickSize = Duration.ofNanos((long) (1e9 / meta().getInt("params.sample_freq"))); Duration tickSize = Duration.ofNanos((long) (1e9 / getMeta().getInt("params.sample_freq")));
return block.getFramesList().stream().map(frame -> { return block.getFramesList().stream().map(frame -> {
Instant time = getStartTime().plusNanos(frame.getTime()); Instant time = getStartTime().plusNanos(frame.getTime());
ByteBuffer data = frame.getData().asReadOnlyByteBuffer(); ByteBuffer data = frame.getData().asReadOnlyByteBuffer();

View File

@ -61,7 +61,7 @@ public class NumassIO extends BasicIOManager {
ple.setContext(lc); ple.setContext(lc);
ple.start(); ple.start();
FileAppender<ILoggingEvent> appender = new FileAppender<>(); FileAppender<ILoggingEvent> appender = new FileAppender<>();
appender.setFile(new File(getWorkDirectory().toFile(), meta().getString("logFileName", "numass.log")).toString()); appender.setFile(new File(getWorkDirectory().toFile(), getMeta().getString("logFileName", "numass.log")).toString());
appender.setEncoder(ple); appender.setEncoder(ple);
return appender; return appender;
} }

View File

@ -138,10 +138,10 @@ object NumassUtils {
set.points.forEach { point -> set.points.forEach { point ->
val pointMeta = MetaBuilder("point") val pointMeta = MetaBuilder("point")
.putValue("voltage", point.voltage) .putValue("voltage", point.voltage)
.putValue("index", point.meta().getInt("external_meta.point_index", -1)) .putValue("index", point.getMeta().getInt("external_meta.point_index", -1))
.putValue("run", point.meta().getString("external_meta.session", "")) .putValue("run", point.getMeta().getString("external_meta.session", ""))
.putValue("group", point.meta().getString("external_meta.group", "")) .putValue("group", point.getMeta().getString("external_meta.group", ""))
val pointName = "point_" + point.meta().getInt("external_meta.point_index", point.hashCode())!! val pointName = "point_" + point.getMeta().getInt("external_meta.point_index", point.hashCode())!!
builder.putData(pointName, point, pointMeta) builder.putData(pointName, point, pointMeta)
} }
set.hvData.ifPresent { hv -> builder.putData("hv", hv, Meta.empty()) } set.hvData.ifPresent { hv -> builder.putData("hv", hv, Meta.empty()) }

View File

@ -41,7 +41,7 @@ class MergeDataAction : ManyToOneAction<Table, Table>() {
val parnames = arrayOf(NumassPoint.HV_KEY, NumassPoint.LENGTH_KEY, NumassAnalyzer.COUNT_KEY, NumassAnalyzer.COUNT_RATE_KEY, NumassAnalyzer.COUNT_RATE_ERROR_KEY) val parnames = arrayOf(NumassPoint.HV_KEY, NumassPoint.LENGTH_KEY, NumassAnalyzer.COUNT_KEY, NumassAnalyzer.COUNT_RATE_KEY, NumassAnalyzer.COUNT_RATE_ERROR_KEY)
override fun buildGroups(context: Context, input: DataNode<Table>, actionMeta: Meta): List<DataNode<Table>> { override fun buildGroups(context: Context, input: DataNode<Table>, actionMeta: Meta): List<DataNode<Table>> {
val meta = inputMeta(context, input.meta(), actionMeta) val meta = inputMeta(context, input.getMeta(), actionMeta)
val groups: List<DataNode<Table>> val groups: List<DataNode<Table>>
if (meta.hasValue("grouping.byValue")) { if (meta.hasValue("grouping.byValue")) {
groups = super.buildGroups(context, input, actionMeta) groups = super.buildGroups(context, input, actionMeta)

View File

@ -40,7 +40,7 @@ import java.util.*
class SummaryAction : ManyToOneAction<FitState, Table>() { class SummaryAction : ManyToOneAction<FitState, Table>() {
protected override fun buildGroups(context: Context, input: DataNode<FitState>, actionMeta: Meta): List<DataNode<FitState>> { protected override fun buildGroups(context: Context, input: DataNode<FitState>, actionMeta: Meta): List<DataNode<FitState>> {
val meta = inputMeta(context, input.meta(), actionMeta) val meta = inputMeta(context, input.getMeta(), actionMeta)
val groups: List<DataNode<FitState>> val groups: List<DataNode<FitState>>
if (meta.hasValue("grouping.byValue")) { if (meta.hasValue("grouping.byValue")) {
groups = super.buildGroups(context, input, actionMeta) groups = super.buildGroups(context, input, actionMeta)

View File

@ -30,7 +30,7 @@ class NumassFitScanSummaryTask : AbstractTask<Table>() {
val builder = DataSet.builder(Table::class.java) val builder = DataSet.builder(Table::class.java)
val action = FitSummaryAction() val action = FitSummaryAction()
val input = data.checked(FitResult::class.java) val input = data.checked(FitResult::class.java)
input.nodeStream().filter { it -> it.dataSize(false) > 0 }.forEach { node -> builder.putData(node.name, action.run(model.context, node, model.meta()).data) } input.nodeStream().filter { it -> it.dataSize(false) > 0 }.forEach { node -> builder.putData(node.name, action.run(model.context, node, model.getMeta()).data) }
return builder.build() return builder.build()
} }

View File

@ -25,7 +25,7 @@ class NumassFitScanTask : AbstractTask<FitResult>() {
override fun run(model: TaskModel, data: DataNode<*>): DataNode<FitResult> { override fun run(model: TaskModel, data: DataNode<*>): DataNode<FitResult> {
val config = model.meta() val config = model.getMeta()
val scanParameter = config.getString("parameter", "msterile2") val scanParameter = config.getString("parameter", "msterile2")
val scanValues: Value = if (config.hasValue("masses")) { val scanValues: Value = if (config.hasValue("masses")) {

View File

@ -42,7 +42,7 @@ class NumassFitSummaryTask : SingleActionTask<FitState, Table>() {
} }
override fun transformMeta(model: TaskModel): Meta { override fun transformMeta(model: TaskModel): Meta {
return model.meta().getMeta("summary") return model.getMeta().getMeta("summary")
} }
override fun buildModel(model: TaskModel.Builder, meta: Meta) { override fun buildModel(model: TaskModel.Builder, meta: Meta) {

View File

@ -44,8 +44,8 @@ public class NumassRootHandler implements Handler {
Template template = ServletUtils.freemarkerConfig().getTemplate("NumassRoot.ftl"); Template template = ServletUtils.freemarkerConfig().getTemplate("NumassRoot.ftl");
Map data = new HashMap(6); Map data = new HashMap(6);
if (!server.meta().isEmpty()) { if (!server.getMeta().isEmpty()) {
data.put("serverMeta", writer.writeString(server.meta())); data.put("serverMeta", writer.writeString(server.getMeta()));
} }
if (server.getRootState() != null) { if (server.getRootState() != null) {
@ -54,8 +54,8 @@ public class NumassRootHandler implements Handler {
if (server.getRun() != null) { if (server.getRun() != null) {
data.put("runPresent", true); data.put("runPresent", true);
if (!server.getRun().meta().isEmpty()) { if (!server.getRun().getMeta().isEmpty()) {
data.put("runMeta", writer.writeString(server.getRun().meta())); data.put("runMeta", writer.writeString(server.getRun().getMeta()));
} }
StateLoader runState = server.getRun().getStates(); StateLoader runState = server.getRun().getStates();

View File

@ -95,7 +95,7 @@ public class NumassRun implements Metoid, Responder {
@Override @Override
public Envelope respond(Envelope message) { public Envelope respond(Envelope message) {
Meta meta = message.meta(); Meta meta = message.getMeta();
String type = meta.getString("type", "numass.run.state"); String type = meta.getString("type", "numass.run.state");
String action = meta.getString("action"); String action = meta.getString("action");
switch (type) { switch (type) {
@ -135,12 +135,12 @@ public class NumassRun implements Metoid, Responder {
private synchronized Envelope pushNote(Envelope message) { private synchronized Envelope pushNote(Envelope message) {
try { try {
if (message.meta().hasMeta("note")) { if (message.getMeta().hasMeta("note")) {
for (Meta node : message.meta().getMetaList("note")) { for (Meta node : message.getMeta().getMetaList("note")) {
addNote(NumassNote.buildFrom(node)); addNote(NumassNote.buildFrom(node));
} }
} else { } else {
addNote(NumassNote.buildFrom(message.meta())); addNote(NumassNote.buildFrom(message.getMeta()));
} }
return factory.okResponseBase(message, false, false).build(); return factory.okResponseBase(message, false, false).build();
} catch (Exception ex) { } catch (Exception ex) {
@ -151,7 +151,7 @@ public class NumassRun implements Metoid, Responder {
private Envelope pullNotes(Envelope message) { private Envelope pullNotes(Envelope message) {
EnvelopeBuilder envelope = factory.okResponseBase(message, true, false); EnvelopeBuilder envelope = factory.okResponseBase(message, true, false);
int limit = message.meta().getInt("limit", -1); int limit = message.getMeta().getInt("limit", -1);
//TODO add time window and search conditions here //TODO add time window and search conditions here
Stream<NumassNote> stream = getNotes(noteLoader); Stream<NumassNote> stream = getNotes(noteLoader);
if (limit > 0) { if (limit > 0) {
@ -164,8 +164,8 @@ public class NumassRun implements Metoid, Responder {
private Envelope pushNumassPoint(Envelope message) { private Envelope pushNumassPoint(Envelope message) {
try { try {
String filePath = message.meta().getString("path", ""); String filePath = message.getMeta().getString("path", "");
String fileName = message.meta().getString("name") String fileName = message.getMeta().getString("name")
.replace(NumassStorage.NUMASS_ZIP_EXTENSION, "");// removing .nm.zip if it is present .replace(NumassStorage.NUMASS_ZIP_EXTENSION, "");// removing .nm.zip if it is present
if (storage instanceof NumassStorage) { if (storage instanceof NumassStorage) {
((NumassStorage) storage).pushNumassData(filePath, fileName, message.getData().getBuffer()); ((NumassStorage) storage).pushNumassData(filePath, fileName, message.getData().getBuffer());
@ -181,8 +181,8 @@ public class NumassRun implements Metoid, Responder {
} }
@Override @Override
public Meta meta() { public Meta getMeta() {
return storage.meta(); return storage.getMeta();
} }
public Storage getStorage() { public Storage getStorage() {

View File

@ -77,7 +77,7 @@ public class NumassServer extends AbstractNetworkListener implements ContextAwar
@Override @Override
public void open() throws Exception { public void open() throws Exception {
super.open(); super.open();
int port = meta().getInt("ratpack.port", 8336); int port = getMeta().getInt("ratpack.port", 8336);
// ratpack = RatpackServer.start((RatpackServerSpec server) -> server // ratpack = RatpackServer.start((RatpackServerSpec server) -> server
// .serverConfig((ServerConfigBuilder config) -> config // .serverConfig((ServerConfigBuilder config) -> config
//// .baseDir(Paths.get(getClass().getResource("/ratpack/.ratpack").toURI())) //// .baseDir(Paths.get(getClass().getResource("/ratpack/.ratpack").toURI()))
@ -110,7 +110,7 @@ public class NumassServer extends AbstractNetworkListener implements ContextAwar
*/ */
@Override @Override
public Envelope respond(Envelope message) { public Envelope respond(Envelope message) {
Meta meta = message.meta(); Meta meta = message.getMeta();
// ByteBuffer data = message.getData(); // ByteBuffer data = message.getData();
//switch message type //switch message type
@ -155,8 +155,8 @@ public class NumassServer extends AbstractNetworkListener implements ContextAwar
public Envelope getCurrentRun() { public Envelope getCurrentRun() {
MetaBuilder runAn = new MetaBuilder("run") MetaBuilder runAn = new MetaBuilder("run")
.putValue("path", getRun().getRunPath()); .putValue("path", getRun().getRunPath());
if (!run.meta().isEmpty()) { if (!run.getMeta().isEmpty()) {
runAn.putNode(getRun().meta()); runAn.putNode(getRun().getMeta());
} }
return getResponseFactory().responseBase("numass.run.response") return getResponseFactory().responseBase("numass.run.response")

View File

@ -55,7 +55,7 @@ public class ServerRunner extends SimpleConfigurable implements AutoCloseable {
public ServerRunner start() throws Exception { public ServerRunner start() throws Exception {
// String repoPath = meta().getString(NUMASS_REPO_PATH_PROPERTY, "."); // String repoPath = meta().getString(NUMASS_REPO_PATH_PROPERTY, ".");
Meta storageMeta = meta().getMetaOrEmpty(NUMASS_REPO_ELEMENT); Meta storageMeta = getMeta().getMetaOrEmpty(NUMASS_REPO_ELEMENT);
context.getLogger().info("Initializing file storage with meta: {}",storageMeta); context.getLogger().info("Initializing file storage with meta: {}",storageMeta);
root = new NumassStorage(context,storageMeta); root = new NumassStorage(context,storageMeta);
@ -63,8 +63,8 @@ public class ServerRunner extends SimpleConfigurable implements AutoCloseable {
if (root != null) { if (root != null) {
root.open(); root.open();
Meta listenerConfig = null; Meta listenerConfig = null;
if (meta().hasMeta(LISTENER_ELEMENT)) { if (getMeta().hasMeta(LISTENER_ELEMENT)) {
listenerConfig = meta().getMeta(LISTENER_ELEMENT); listenerConfig = getMeta().getMeta(LISTENER_ELEMENT);
} }
listener = new NumassServer(root, listenerConfig); listener = new NumassServer(root, listenerConfig);

View File

@ -51,6 +51,6 @@ new NumassClient("127.0.0.1",8335).withCloseable{
def response = it.respond(bin); def response = it.respond(bin);
println parser.writeString(response.meta()); println parser.writeString(response.getMeta());
} }

View File

@ -27,7 +27,7 @@ class NumassDataCache(val data: NumassSet) : NumassSet {
return cachedDescription return cachedDescription
} }
override fun meta(): Meta { override fun getMeta(): Meta {
return cachedMeta return cachedMeta
} }

View File

@ -46,7 +46,7 @@ val storageInterceptor = InterceptorFactory { context, meta ->
add("name", loader.name) add("name", loader.name)
add("path", loader.path.toString()) add("path", loader.path.toString())
add("type", loader.type) add("type", loader.type)
add("meta", loader.laminate.asJson()) add("getMeta", loader.laminate.asJson())
}) })
} }
add("loaders", loaders) add("loaders", loaders)
@ -96,7 +96,7 @@ val deviceInterceptor = InterceptorFactory { context, meta ->
devices.add(jsonObject { devices.add(jsonObject {
add("name", name.toUnescaped()) add("name", name.toUnescaped())
add("type", device.getType()) add("type", device.getType())
add("meta", device.meta.asJson()) add("getMeta", device.meta.asJson())
}) })
} }
} }
@ -112,7 +112,7 @@ val deviceInterceptor = InterceptorFactory { context, meta ->
call.json { call.json {
add("name", deviceName) add("name", deviceName)
add("type", device.type) add("type", device.type)
add("meta", device.meta.asJson()) add("getMeta", device.meta.asJson())
add("state", jsonObject { add("state", jsonObject {
for (state in device.listStates()) { for (state in device.listStates()) {
add(state, device.getState(state).toString()) add(state, device.getState(state).toString())