Search in sources :

Example 1 with ChannelRecordContainer

use of org.openmuc.framework.driver.spi.ChannelRecordContainer in project OpenMUC by isc-konstanz.

the class DataManager method handleInterruptEvent.

private void handleInterruptEvent() {
    if (stopFlag) {
        prepareStop();
        return;
    }
    long currentTime = 0;
    if (newRootConfigWithoutDefaults != null) {
        currentTime = System.currentTimeMillis();
        applyConfiguration(newRootConfigWithoutDefaults, currentTime);
        newRootConfigWithoutDefaults = null;
        newConfigSignal.countDown();
    }
    synchronized (receivedRecordContainers) {
        List<ChannelRecordContainer> recordContainers;
        LoggingController loggingController = new LoggingController(activeDataLoggers);
        List<ChannelRecordContainerImpl> channelRecordContainerList = new ArrayList<>();
        while ((recordContainers = receivedRecordContainers.poll()) != null) {
            recordContainers.stream().map(recContainer -> (ChannelRecordContainerImpl) recContainer).filter(containerImpl -> containerImpl.getChannel().getChannelState() == ChannelState.LISTENING || containerImpl.getChannel().getDriverId().equals(DriverOptionsFactory.VIRTUAL)).forEach(containerImpl -> {
                containerImpl.getChannel().setNewRecord(containerImpl.getRecord());
                if (containerImpl.getChannel().isLoggingEvent())
                    channelRecordContainerList.add(containerImpl);
            });
        }
        loggingController.deliverLogsToEventBasedLogServices(channelRecordContainerList);
    }
    synchronized (samplingTaskFinished) {
        SamplingTask samplingTask;
        while ((samplingTask = samplingTaskFinished.poll()) != null) {
            samplingTask.storeValues();
            samplingTask.device.taskFinished();
        }
    }
    synchronized (tasksFinished) {
        DeviceTask deviceTask;
        while ((deviceTask = tasksFinished.poll()) != null) {
            deviceTask.device.taskFinished();
        }
    }
    synchronized (newDrivers) {
        // Needed to synchronize with getRunningDrivers
        synchronized (activeDrivers) {
            activeDrivers.putAll(newDrivers);
        }
        for (Entry<String, DriverService> newDriverEntry : newDrivers.entrySet()) {
            String driverId = newDriverEntry.getKey();
            logger.info("Registered driver: " + driverId);
            DriverConfigImpl driverConfig = rootConfig.driverConfigsById.get(driverId);
            if (driverConfig == null) {
                continue;
            }
            driverConfig.activeDriver = newDriverEntry.getValue();
            for (DeviceConfigImpl deviceConfig : driverConfig.deviceConfigsById.values()) {
                deviceConfig.device.driverRegisteredSignal();
            }
        }
        newDrivers.clear();
    }
    synchronized (newServers) {
        if (!newServers.isEmpty()) {
            activeServers.addAll(newServers);
            for (ServerService server : newServers) {
                logger.info("Registered server: {}", server.getId());
                notifyServer(server);
            }
            newServers.clear();
        }
    }
    synchronized (newDataLoggers) {
        if (!newDataLoggers.isEmpty()) {
            activeDataLoggers.addAll(newDataLoggers);
            for (DataLoggerService dataLogger : newDataLoggers) {
                logger.info("Registered data logger: {}", dataLogger.getId());
                dataLogger.setChannelsToLog(rootConfig.logChannels);
            }
            newDataLoggers.clear();
        }
    }
    if (driverToBeRemovedId != null) {
        DriverService removedDriver;
        synchronized (activeDrivers) {
            removedDriver = activeDrivers.remove(driverToBeRemovedId);
        }
        if (removedDriver == null) {
            // drivers was removed before it was added to activeDrivers
            newDrivers.remove(driverToBeRemovedId);
            driverRemovedSignal.countDown();
        } else {
            DriverConfigImpl driverConfig = rootConfig.driverConfigsById.get(driverToBeRemovedId);
            if (driverConfig != null) {
                activeDeviceCountDown = driverConfig.deviceConfigsById.size();
                if (activeDeviceCountDown > 0) {
                    // all devices have to be given a chance to finish their current task and disconnect:
                    for (DeviceConfigImpl deviceConfig : driverConfig.deviceConfigsById.values()) {
                        deviceConfig.device.driverDeregisteredSignal();
                    }
                    synchronized (driverRemovedSignal) {
                        if (activeDeviceCountDown == 0) {
                            driverRemovedSignal.countDown();
                        }
                    }
                } else {
                    driverRemovedSignal.countDown();
                }
            } else {
                driverRemovedSignal.countDown();
            }
        }
        driverToBeRemovedId = null;
    }
    if (serverToBeRemoved != null) {
        if (!activeServers.remove(serverToBeRemoved)) {
            newServers.remove(serverToBeRemoved);
        }
        serverToBeRemoved = null;
        serverRemovedSignal.countDown();
    }
    if (dataLoggerToBeRemoved != null) {
        if (!activeDataLoggers.remove(dataLoggerToBeRemoved)) {
            newDataLoggers.remove(dataLoggerToBeRemoved);
        }
        dataLoggerToBeRemoved = null;
        dataLoggerRemovedSignal.countDown();
    }
    synchronized (connectionFailures) {
        if (currentTime == 0) {
            currentTime = System.currentTimeMillis();
        }
        Device connectionFailureDevice;
        while ((connectionFailureDevice = connectionFailures.poll()) != null) {
            connectionFailureDevice.connectFailureSignal(currentTime);
        }
    }
    synchronized (connectedDevices) {
        if (currentTime == 0) {
            currentTime = System.currentTimeMillis();
        }
        Device connectedDevice;
        while ((connectedDevice = connectedDevices.poll()) != null) {
            connectedDevice.connectedSignal(currentTime);
        }
    }
    synchronized (newWriteTasks) {
        addTasksAndClear(newWriteTasks);
    }
    synchronized (newReadTasks) {
        addTasksAndClear(newReadTasks);
    }
    synchronized (disconnectedDevices) {
        Device connectedDevice;
        while ((connectedDevice = disconnectedDevices.poll()) != null) {
            connectedDevice.disconnectedSignal();
        }
    }
}
Also used : Arrays(java.util.Arrays) ListIterator(java.util.ListIterator) DeviceScanInfo(org.openmuc.framework.config.DeviceScanInfo) LoggerFactory(org.slf4j.LoggerFactory) DriverInfo(org.openmuc.framework.config.DriverInfo) Connection(org.openmuc.framework.driver.spi.Connection) Channel(org.openmuc.framework.dataaccess.Channel) DriverConfig(org.openmuc.framework.config.DriverConfig) DeviceScanListener(org.openmuc.framework.config.DeviceScanListener) Map(java.util.Map) ParseException(org.openmuc.framework.config.ParseException) ServerMapping(org.openmuc.framework.config.ServerMapping) ServerService(org.openmuc.framework.server.spi.ServerService) ConnectionException(org.openmuc.framework.driver.spi.ConnectionException) ScanException(org.openmuc.framework.config.ScanException) Deactivate(org.osgi.service.component.annotations.Deactivate) DriverDeviceScanListener(org.openmuc.framework.driver.spi.DriverDeviceScanListener) ReferencePolicy(org.osgi.service.component.annotations.ReferencePolicy) ConfigWriteException(org.openmuc.framework.config.ConfigWriteException) Collectors(java.util.stream.Collectors) Flag(org.openmuc.framework.data.Flag) FileNotFoundException(java.io.FileNotFoundException) Executors(java.util.concurrent.Executors) ChannelState(org.openmuc.framework.dataaccess.ChannelState) CountDownLatch(java.util.concurrent.CountDownLatch) List(java.util.List) ChannelScanInfo(org.openmuc.framework.config.ChannelScanInfo) ChannelConfig(org.openmuc.framework.config.ChannelConfig) ChannelChangeListener(org.openmuc.framework.dataaccess.ChannelChangeListener) Entry(java.util.Map.Entry) Optional(java.util.Optional) Queue(java.util.Queue) ReadRecordContainer(org.openmuc.framework.dataaccess.ReadRecordContainer) DataLoggerNotAvailableException(org.openmuc.framework.dataaccess.DataLoggerNotAvailableException) TransformerException(javax.xml.transform.TransformerException) ThreadPoolExecutor(java.util.concurrent.ThreadPoolExecutor) DriverOptionsFactory(org.openmuc.framework.config.option.DriverOptionsFactory) HashMap(java.util.HashMap) Deque(java.util.Deque) RootConfig(org.openmuc.framework.config.RootConfig) ConfigService(org.openmuc.framework.config.ConfigService) ArrayList(java.util.ArrayList) LinkedHashMap(java.util.LinkedHashMap) LogicalDeviceChangeListener(org.openmuc.framework.dataaccess.LogicalDeviceChangeListener) ChannelRecordContainer(org.openmuc.framework.driver.spi.ChannelRecordContainer) Component(org.osgi.service.component.annotations.Component) WriteValueContainer(org.openmuc.framework.dataaccess.WriteValueContainer) TransformerFactoryConfigurationError(javax.xml.transform.TransformerFactoryConfigurationError) DataLoggerService(org.openmuc.framework.datalogger.spi.DataLoggerService) Activate(org.osgi.service.component.annotations.Activate) DriverNotAvailableException(org.openmuc.framework.config.DriverNotAvailableException) LinkedList(java.util.LinkedList) ArgumentSyntaxException(org.openmuc.framework.config.ArgumentSyntaxException) ServerMappingContainer(org.openmuc.framework.server.spi.ServerMappingContainer) CommandProcessor(org.apache.felix.service.command.CommandProcessor) ConfigChangeListener(org.openmuc.framework.config.ConfigChangeListener) Logger(org.slf4j.Logger) ReentrantLock(java.util.concurrent.locks.ReentrantLock) IOException(java.io.IOException) File(java.io.File) LogicalDevice(org.openmuc.framework.dataaccess.LogicalDevice) ScanInterruptedException(org.openmuc.framework.config.ScanInterruptedException) DeviceConfig(org.openmuc.framework.config.DeviceConfig) ReferenceCardinality(org.osgi.service.component.annotations.ReferenceCardinality) ParserConfigurationException(javax.xml.parsers.ParserConfigurationException) DriverService(org.openmuc.framework.driver.spi.DriverService) LinkedBlockingDeque(java.util.concurrent.LinkedBlockingDeque) DataAccessService(org.openmuc.framework.dataaccess.DataAccessService) DeviceState(org.openmuc.framework.dataaccess.DeviceState) Reference(org.osgi.service.component.annotations.Reference) LogChannel(org.openmuc.framework.datalogger.spi.LogChannel) RecordsReceivedListener(org.openmuc.framework.driver.spi.RecordsReceivedListener) DataLoggerService(org.openmuc.framework.datalogger.spi.DataLoggerService) LogicalDevice(org.openmuc.framework.dataaccess.LogicalDevice) ArrayList(java.util.ArrayList) ChannelRecordContainer(org.openmuc.framework.driver.spi.ChannelRecordContainer) ServerService(org.openmuc.framework.server.spi.ServerService) DriverService(org.openmuc.framework.driver.spi.DriverService)

Example 2 with ChannelRecordContainer

use of org.openmuc.framework.driver.spi.ChannelRecordContainer in project OpenMUC by isc-konstanz.

the class DriverConnection method setRecords.

private boolean setRecords(List<ChannelRecordContainer> containers, MBusConnection mBusConnection, long timestamp, List<DataRecord> dataRecords, String[] dibvibs) throws ConnectionException {
    boolean selectForReadoutSet = false;
    for (ChannelRecordContainer container : containers) {
        String channelAddress = container.getChannelAddress();
        if (channelAddress.startsWith("X")) {
            String[] dibAndVib = channelAddress.split(":");
            if (dibAndVib.length != 2) {
                container.setRecord(new Record(Flag.DRIVER_ERROR_CHANNEL_ADDRESS_SYNTAX_INVALID));
            }
            List<DataRecord> dataRecordsToSelectForReadout = new ArrayList<>(1);
            selectForReadoutSet = true;
            try {
                mBusConnection.selectForReadout(mBusAddress, dataRecordsToSelectForReadout);
                sleep(delay);
            } catch (SerialPortTimeoutException e) {
                container.setRecord(new Record(Flag.DRIVER_ERROR_TIMEOUT));
                continue;
            } catch (IOException e) {
                connectionInterface.close();
                throw new ConnectionException(e);
            }
            VariableDataStructure variableDataStructure2 = null;
            try {
                variableDataStructure2 = mBusConnection.read(mBusAddress);
            } catch (SerialPortTimeoutException e1) {
                container.setRecord(new Record(Flag.DRIVER_ERROR_TIMEOUT));
                continue;
            } catch (IOException e1) {
                connectionInterface.close();
                throw new ConnectionException(e1);
            }
            DataRecord dataRecord = variableDataStructure2.getDataRecords().get(0);
            setContainersRecord(timestamp, container, dataRecord);
            continue;
        }
        int j = 0;
        for (DataRecord dataRecord : dataRecords) {
            if (dibvibs[j++].equalsIgnoreCase(channelAddress)) {
                setContainersRecord(timestamp, container, dataRecord);
                break;
            }
        }
        if (container.getRecord() == null) {
            container.setRecord(new Record(Flag.DRIVER_ERROR_CHANNEL_WITH_THIS_ADDRESS_NOT_FOUND));
        }
    }
    return selectForReadoutSet;
}
Also used : ArrayList(java.util.ArrayList) IOException(java.io.IOException) ChannelRecordContainer(org.openmuc.framework.driver.spi.ChannelRecordContainer) SerialPortTimeoutException(org.openmuc.jrxtx.SerialPortTimeoutException) DataRecord(org.openmuc.jmbus.DataRecord) Record(org.openmuc.framework.data.Record) DataRecord(org.openmuc.jmbus.DataRecord) VariableDataStructure(org.openmuc.jmbus.VariableDataStructure) ConnectionException(org.openmuc.framework.driver.spi.ConnectionException)

Example 3 with ChannelRecordContainer

use of org.openmuc.framework.driver.spi.ChannelRecordContainer in project OpenMUC by isc-konstanz.

the class DriverConnectionTest method testReadThrowsIOException.

@Test
public void testReadThrowsIOException() throws Exception {
    MBusConnection con = mock(MBusConnection.class);
    VariableDataStructure vds = new VariableDataStructure(NZR_ANSWER, 6, NZR_ANSWER.length - 6, null, null);
    vds.decode();
    when(con.read(anyInt())).thenThrow(new IOException());
    ConnectionInterface serialIntervace = new ConnectionInterface(con, "/dev/ttyS100:5", delay, interfaces);
    serialIntervace.increaseConnectionCounter();
    String[] deviceAddressTokens = { "/dev/ttyS100", "5" };
    int address = Integer.parseInt(deviceAddressTokens[1]);
    DriverConnection driverCon = new DriverConnection(serialIntervace, address, null, delay);
    List<ChannelRecordContainer> records = Arrays.asList(newChannelRecordContainer("04:03"));
    driverCon.read(records, null, null);
    Flag actualFlag = records.get(0).getRecord().getFlag();
    assertEquals(Flag.DRIVER_ERROR_TIMEOUT, actualFlag);
}
Also used : MBusConnection(org.openmuc.jmbus.MBusConnection) ChannelRecordContainer(org.openmuc.framework.driver.spi.ChannelRecordContainer) IOException(java.io.IOException) VariableDataStructure(org.openmuc.jmbus.VariableDataStructure) Flag(org.openmuc.framework.data.Flag) PrepareForTest(org.powermock.core.classloader.annotations.PrepareForTest) Test(org.junit.Test)

Example 4 with ChannelRecordContainer

use of org.openmuc.framework.driver.spi.ChannelRecordContainer in project OpenMUC by isc-konstanz.

the class DriverConnectionTest method testReadBcdDateLong.

@Test
public void testReadBcdDateLong() throws Exception {
    MBusConnection con = mock(MBusConnection.class);
    VariableDataStructure vds = new VariableDataStructure(SIEMENS_UH50_ANSWER, 6, SIEMENS_UH50_ANSWER.length - 6, null, null);
    vds.decode();
    when(con.read(anyInt())).thenReturn(vds);
    ConnectionInterface serialIntervace = new ConnectionInterface(con, "/dev/ttyS100:5", delay, interfaces);
    serialIntervace.increaseConnectionCounter();
    String[] deviceAddressTokens = { "/dev/ttyS100", "5" };
    DriverConnection mBusConnection = new DriverConnection(serialIntervace, Integer.parseInt(deviceAddressTokens[1]), null, delay);
    List<ChannelRecordContainer> records = new LinkedList<>();
    records.add(newChannelRecordContainer("09:74"));
    records.add(newChannelRecordContainer("42:6c"));
    records.add(newChannelRecordContainer("8c01:14"));
    mBusConnection.read(records, null, null);
}
Also used : MBusConnection(org.openmuc.jmbus.MBusConnection) ChannelRecordContainer(org.openmuc.framework.driver.spi.ChannelRecordContainer) VariableDataStructure(org.openmuc.jmbus.VariableDataStructure) LinkedList(java.util.LinkedList) PrepareForTest(org.powermock.core.classloader.annotations.PrepareForTest) Test(org.junit.Test)

Example 5 with ChannelRecordContainer

use of org.openmuc.framework.driver.spi.ChannelRecordContainer in project OpenMUC by isc-konstanz.

the class DriverConnectionTest method testReadThrowsTimeoutException.

@Test
public void testReadThrowsTimeoutException() throws Exception {
    MBusConnection con = mock(MBusConnection.class);
    VariableDataStructure vds = new VariableDataStructure(NZR_ANSWER, 6, NZR_ANSWER.length - 6, null, null);
    vds.decode();
    when(con.read(anyInt())).thenThrow(new SerialPortTimeoutException());
    ConnectionInterface serialIntervace = new ConnectionInterface(con, "/dev/ttyS100:5", delay, interfaces);
    serialIntervace.increaseConnectionCounter();
    String[] deviceAddressTokens = { "/dev/ttyS100", "5" };
    int address = Integer.parseInt(deviceAddressTokens[1]);
    DriverConnection driverCon = new DriverConnection(serialIntervace, address, null, delay);
    List<ChannelRecordContainer> records = Arrays.asList(newChannelRecordContainer("04:03"));
    driverCon.read(records, null, null);
    assertEquals(Flag.DRIVER_ERROR_TIMEOUT, records.get(0).getRecord().getFlag());
}
Also used : MBusConnection(org.openmuc.jmbus.MBusConnection) ChannelRecordContainer(org.openmuc.framework.driver.spi.ChannelRecordContainer) SerialPortTimeoutException(org.openmuc.jrxtx.SerialPortTimeoutException) VariableDataStructure(org.openmuc.jmbus.VariableDataStructure) PrepareForTest(org.powermock.core.classloader.annotations.PrepareForTest) Test(org.junit.Test)

Aggregations

ChannelRecordContainer (org.openmuc.framework.driver.spi.ChannelRecordContainer)39 Record (org.openmuc.framework.data.Record)24 ArrayList (java.util.ArrayList)14 ConnectionException (org.openmuc.framework.driver.spi.ConnectionException)11 ArgumentSyntaxException (org.openmuc.framework.config.ArgumentSyntaxException)10 Value (org.openmuc.framework.data.Value)7 IOException (java.io.IOException)6 VariableDataStructure (org.openmuc.jmbus.VariableDataStructure)5 ModbusException (com.ghgande.j2mod.modbus.ModbusException)4 ModbusIOException (com.ghgande.j2mod.modbus.ModbusIOException)4 ScanException (org.openmuc.framework.config.ScanException)4 BooleanValue (org.openmuc.framework.data.BooleanValue)4 MBusConnection (org.openmuc.jmbus.MBusConnection)4 LinkedList (java.util.LinkedList)3 Test (org.junit.Test)3 DoubleValue (org.openmuc.framework.data.DoubleValue)3 StringValue (org.openmuc.framework.data.StringValue)3 PrepareForTest (org.powermock.core.classloader.annotations.PrepareForTest)3 ServerModel (com.beanit.iec61850bean.ServerModel)2 Test (org.junit.jupiter.api.Test)2