MiloSourceProvider.java

package de.dlr.bt.stc.source.opcua;

import java.util.HashMap;
import java.util.Map;

import org.greenrobot.eventbus.EventBus;

import de.dlr.bt.stc.config.ConfigurationManager;
import de.dlr.bt.stc.entities.TaskLifecycle;
import de.dlr.bt.stc.exceptions.SourceConfigurationException;
import de.dlr.bt.stc.init.Register;
import de.dlr.bt.stc.source.ASourceProvider;
import de.dlr.bt.stc.task.TaskProviderFactory;
import lombok.extern.slf4j.Slf4j;

@Slf4j
public class MiloSourceProvider extends ASourceProvider<MiloSource> {

	private final EventBus instanceEventBus;

	private final Map<MiloClientCfg, MiloClient> miloClients = new HashMap<>();

	@Register
	public static void register() {
		TaskProviderFactory.getInstance().registerCreator(SourceOPCUACfg.class, MiloSourceProvider::new);
	}

	private MiloSourceProvider(ConfigurationManager config) {
		super(config.getManagementEventBus());
		this.instanceEventBus = config.getInstanceEventBus();

		for (var entry : config.getConfigurations().entrySet()) {
			if (entry.getValue() instanceof SourceOPCUACfg soc) {
				this.taskLifecycles.put(soc.getId(), new TaskLifecycle<>(new MiloSource(soc, this.instanceEventBus)));
				this.miloClients.putIfAbsent(new MiloClientCfg(soc), null);
			}
		}
	}

	@Override
	public boolean initializeTasks() {
		boolean ok = createMiloClients();
		ok &= super.initializeTasks();

		return ok;
	}

	@Override
	protected boolean initializeTask(TaskLifecycle<MiloSource> task) {
		if (task.getTask().getClient() == null) {
			MiloClientCfg mcfg = new MiloClientCfg(task.getTask().getConfig());
			var mc = miloClients.get(mcfg);
			if (mc != null)
				task.getTask().setClient(mc);

		}

		if (task.getTask().getClient() != null)
			return super.initializeTask(task);
		else
			return false;

	}

	private boolean createMiloClients() {
		boolean ok = true;
		for (var entry : miloClients.entrySet()) {
			if (entry.getValue() == null) {
				try {
					var client = new MiloClient(entry.getKey());
					entry.setValue(client);
				} catch (SourceConfigurationException sce) {
					ok = false;
					log.error("Could not initialize MiloClient {}, Exception {}", entry, sce.getMessage());
				}
			}
		}
		return ok;
	}

	@Override
	public boolean startTasks() {
		boolean ok = super.startTasks();

		for (var client : miloClients.values()) {
			if (client != null)
				client.updateSubscriptions();
		}
		return ok;
	}

	@Override
	public void stopTasks() {
		for (var client : miloClients.values()) {
			if (client != null)
				client.removeSubscriptions();
		}

		super.stopTasks();
	}

	@Override
	public void cleanupTasks() {
		stopTasks();

		super.cleanupTasks();

		for (var entry : miloClients.entrySet()) {
			if (entry.getValue() != null) {
				entry.getValue().cleanup();
				entry.setValue(null);
			}
		}
	}

}