All Downloads are FREE. Search and download functionalities are using the official Maven repository.

io.mapsmessaging.devices.spi.SpiBusManager Maven / Gradle / Ivy

The newest version!
package io.mapsmessaging.devices.spi;

import com.pi4j.context.Context;
import io.mapsmessaging.devices.DeviceController;
import io.mapsmessaging.devices.logging.DeviceLogMessage;
import io.mapsmessaging.logging.Logger;
import io.mapsmessaging.logging.LoggerFactory;

import java.util.*;
import java.util.concurrent.ConcurrentHashMap;

public class SpiBusManager {

  private final Logger logger = LoggerFactory.getLogger(SpiBusManager.class);

  private final Map knownDevices;
  private final Map activeDevices;

  private final Context pi4j;

  public SpiBusManager(Context pi4j) {
    logger.log(DeviceLogMessage.SPI_BUS_MANAGER_STARTUP);

    this.pi4j = pi4j;
    knownDevices = new LinkedHashMap<>();
    activeDevices = new ConcurrentHashMap<>();
    ServiceLoader deviceEntries = ServiceLoader.load(SpiDeviceController.class);
    for (SpiDeviceController controller : deviceEntries) {
      knownDevices.putIfAbsent(controller.getName(), controller);
    }
  }

  public SpiDeviceController configureDevice(String spiName, Map configuration) {
    return mount(spiName, configuration);
  }

  public List configureDevices(Map configuration) {
    List devices = new ArrayList<>();
    for (Map.Entry entry : configuration.entrySet()) {
      String spiName = entry.getKey();
      Map deviceConfig = (Map) entry.getValue();
      devices.add(configureDevice(spiName, deviceConfig));
    }
    return devices;
  }

  public SpiDeviceController mount(String name, Map config) {
    SpiDeviceController controller = knownDevices.get(name);
    if (controller != null) {
      SpiDeviceController mounted = controller.mount(pi4j, config);
      activeDevices.put(mounted.getName(), new SpiDeviceScheduler(mounted));
      return mounted;
    }
    return null;
  }

  public Map getActive() {
    return activeDevices;
  }

  public SpiDeviceController get(String id) {
    return (SpiDeviceController) activeDevices.get(id);
  }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy