Search in sources :

Example 6 with OslpEnvelope

use of org.opensmartgridplatform.oslp.OslpEnvelope in project open-smart-grid-platform by OSGP.

the class MetricsCounterTest method oslpEnvelope.

private OslpEnvelope oslpEnvelope() throws Exception {
    final ECGenParameterSpec parameterSpec = new ECGenParameterSpec("secp256r1");
    final KeyPairGenerator generator = KeyPairGenerator.getInstance("EC");
    generator.initialize(parameterSpec, new SecureRandom());
    final KeyPair keyPair = generator.generateKeyPair();
    final OslpEnvelope oslpEnvelope = this.envelopeBuilder(keyPair.getPrivate()).build();
    oslpEnvelope.validate(keyPair.getPublic());
    return oslpEnvelope;
}
Also used : KeyPair(java.security.KeyPair) ECGenParameterSpec(java.security.spec.ECGenParameterSpec) SecureRandom(java.security.SecureRandom) KeyPairGenerator(java.security.KeyPairGenerator) OslpEnvelope(org.opensmartgridplatform.oslp.OslpEnvelope)

Example 7 with OslpEnvelope

use of org.opensmartgridplatform.oslp.OslpEnvelope in project open-smart-grid-platform by OSGP.

the class OslpChannelHandler method send.

public OslpEnvelope send(final InetSocketAddress address, final OslpEnvelope request, final String deviceIdentification) throws IOException, DeviceSimulatorException {
    LOGGER.info("Sending OSLP request: {}", request.getPayloadMessage());
    final Callback callback = new Callback(this.connectionTimeout);
    this.lock.lock();
    // Open connection and send message
    ChannelFuture channelFuture;
    try {
        channelFuture = this.bootstrap.connect(address);
        channelFuture.awaitUninterruptibly(this.connectionTimeout, TimeUnit.MILLISECONDS);
        if (channelFuture.channel() != null && channelFuture.channel().isActive()) {
            LOGGER.info("Connection established to: {}", address);
        } else {
            LOGGER.info("The connnection to OSGP from device {} is not successful", deviceIdentification);
            LOGGER.warn("Unable to connect to: {}", address);
            throw new IOException("Unable to connect");
        }
        this.callbacks.put(channelFuture.channel().id().asLongText(), callback);
        channelFuture.channel().writeAndFlush(request);
    } finally {
        this.lock.unlock();
    }
    // wait for response and close connection
    try {
        final OslpEnvelope response = callback.get(deviceIdentification);
        LOGGER.info("Received OSLP response (after callback): {}", response.getPayloadMessage());
        /*
       * Devices expect the channel to be closed if - and only if - the
       * platform initiated the conversation. If the device initiated the
       * conversation it needs to close the channel itself.
       */
        channelFuture.channel().close();
        return response;
    } catch (final IOException | DeviceSimulatorException e) {
        // Remove callback when exception has occurred
        this.callbacks.remove(channelFuture.channel().id().asLongText());
        throw e;
    }
}
Also used : ChannelFuture(io.netty.channel.ChannelFuture) DeviceSimulatorException(org.opensmartgridplatform.webdevicesimulator.exceptions.DeviceSimulatorException) IOException(java.io.IOException) OslpEnvelope(org.opensmartgridplatform.oslp.OslpEnvelope)

Example 8 with OslpEnvelope

use of org.opensmartgridplatform.oslp.OslpEnvelope in project open-smart-grid-platform by OSGP.

the class RegisterDevice method sendRegisterDeviceCommand.

public DeviceMessageStatus sendRegisterDeviceCommand(final long deviceId, final Boolean hasSchedule) {
    // Find device.
    final Device device = this.deviceManagementService.findDevice(deviceId);
    if (device == null) {
        // Set the DeviceMessageStatus NOT_FOUND as the Device is not found.
        return DeviceMessageStatus.NOT_FOUND;
    }
    this.errorMessage = "";
    try {
        // Generate random sequence number and random device number.
        final Integer sequenceNumber = device.doGenerateRandomNumber();
        final Integer randomDevice = device.doGenerateRandomNumber();
        // Create registration message.
        final OslpEnvelope oslpRequest = this.createEnvelopeBuilder(device.getDeviceUid(), sequenceNumber).withPayloadMessage(Message.newBuilder().setRegisterDeviceRequest(Oslp.RegisterDeviceRequest.newBuilder().setDeviceIdentification(device.getDeviceIdentification()).setIpAddress(ByteString.copyFrom(InetAddress.getByName(device.getIpAddress()).getAddress())).setDeviceType(device.getDeviceType().isEmpty() ? DeviceType.PSLD : DeviceType.valueOf(device.getDeviceType())).setHasSchedule(hasSchedule).setRandomDevice(randomDevice)).build()).build();
        // Write outgoing request to log.
        this.writeOslpLogItem(oslpRequest, device, false);
        final OslpEnvelope response = this.sendRequest(device, oslpRequest);
        // Write incoming response to log.
        this.writeOslpLogItem(response, device, true);
        this.currentTime = response.getPayloadMessage().getRegisterDeviceResponse().getCurrentTime();
        // Get the sequence number from the response envelope and check it.
        this.checkSequenceNumber(response.getSequenceNumber(), sequenceNumber);
        // Get the two random numbers and check them both.
        this.checkRandomDeviceAndRandomPlatform(randomDevice, response.getPayloadMessage().getRegisterDeviceResponse().getRandomDevice(), response.getPayloadMessage().getRegisterDeviceResponse().getRandomPlatform());
        // Set the sequence number and persist it.
        device.setSequenceNumber(sequenceNumber);
        // Get the two random numbers and persist them both.
        device.setRandomDevice(response.getPayloadMessage().getRegisterDeviceResponse().getRandomDevice());
        device.setRandomPlatform(response.getPayloadMessage().getRegisterDeviceResponse().getRandomPlatform());
        // Save the entity.
        this.deviceManagementService.updateDevice(device);
        // Set the DeviceMessageStatus OK as the registration is successful.
        return DeviceMessageStatus.OK;
    } catch (final UnknownHostException ex) {
        LOGGER.error("incorrect IP address format", ex);
    } catch (final Exception e) {
        LOGGER.error("register device exception", e);
        this.errorMessage = e.getMessage();
        // successful.
        return DeviceMessageStatus.FAILURE;
    }
    return DeviceMessageStatus.NOT_FOUND;
}
Also used : UnknownHostException(java.net.UnknownHostException) Device(org.opensmartgridplatform.webdevicesimulator.domain.entities.Device) DeviceSimulatorException(org.opensmartgridplatform.webdevicesimulator.exceptions.DeviceSimulatorException) IOException(java.io.IOException) UnknownHostException(java.net.UnknownHostException) OslpEnvelope(org.opensmartgridplatform.oslp.OslpEnvelope)

Example 9 with OslpEnvelope

use of org.opensmartgridplatform.oslp.OslpEnvelope in project open-smart-grid-platform by OSGP.

the class DeviceSimulatorIT method returnsASetRebootResponseOnRebootRequest.

@Test
void returnsASetRebootResponseOnRebootRequest() throws Exception {
    final long id = DEVICE_ID.incrementAndGet();
    final int sequenceNumber = this.aSequenceNumber();
    final byte[] deviceUid = this.aDeviceUid();
    final Device device = this.aDevice(id, String.format("TST-%03d", id), deviceUid, sequenceNumber);
    when(this.deviceManagementService.findDevice(device.getDeviceUid())).thenReturn(device);
    when(this.registerDevice.sendRegisterDeviceCommand(id, true)).thenReturn(DeviceMessageStatus.FAILURE);
    final Channel channel = this.activeChannelToSimulator();
    channel.writeAndFlush(this.setRebootEnvelope(deviceUid, sequenceNumber));
    channel.closeFuture().awaitUninterruptibly(1000 * (REBOOT_DELAY_IN_SECONDS + 1));
    verify(this.oslpEnvelopeConsumer).accept(this.oslpEnvelopeCaptor.capture());
    final OslpEnvelope responseEnvelope = this.oslpEnvelopeCaptor.getValue();
    assertThat(responseEnvelope).hasDeviceId(deviceUid).hasMessageWithName("setRebootResponse");
}
Also used : RegisterDevice(org.opensmartgridplatform.webdevicesimulator.service.RegisterDevice) Device(org.opensmartgridplatform.webdevicesimulator.domain.entities.Device) SocketChannel(io.netty.channel.socket.SocketChannel) NioSocketChannel(io.netty.channel.socket.nio.NioSocketChannel) Channel(io.netty.channel.Channel) OslpEnvelope(org.opensmartgridplatform.oslp.OslpEnvelope) Test(org.junit.jupiter.api.Test)

Example 10 with OslpEnvelope

use of org.opensmartgridplatform.oslp.OslpEnvelope in project open-smart-grid-platform by OSGP.

the class DeviceSimulatorIT method allowsRequestForOtherDeviceDuringRebootDelay.

@Test
void allowsRequestForOtherDeviceDuringRebootDelay() throws Exception {
    this.whenUsingARebootDelayOf(60);
    final long id1 = DEVICE_ID.incrementAndGet();
    final int sequenceNumber1 = this.aSequenceNumber();
    final byte[] deviceUid1 = this.aDeviceUid();
    final Device device1 = this.aDevice(id1, String.format("TST-%03d", id1), deviceUid1, sequenceNumber1);
    when(this.deviceManagementService.findDevice(device1.getDeviceUid())).thenReturn(device1);
    when(this.registerDevice.sendRegisterDeviceCommand(id1, true)).thenReturn(DeviceMessageStatus.FAILURE);
    final long id2 = DEVICE_ID.incrementAndGet();
    final int sequenceNumber2 = this.aSequenceNumber();
    final byte[] deviceUid2 = this.aDeviceUid();
    final Device device2 = this.aDevice(id2, String.format("TST-%03d", id2), deviceUid2, sequenceNumber2);
    when(this.deviceManagementService.findDevice(device2.getDeviceUid())).thenReturn(device2);
    when(this.registerDevice.sendRegisterDeviceCommand(id2, true)).thenReturn(DeviceMessageStatus.FAILURE);
    Channel channel = this.activeChannelToSimulator();
    channel.writeAndFlush(this.setRebootEnvelope(deviceUid1, sequenceNumber1));
    channel.closeFuture().awaitUninterruptibly(1000);
    channel = this.activeChannelToSimulator();
    channel.writeAndFlush(this.setRebootEnvelope(deviceUid2, sequenceNumber2));
    channel.closeFuture().awaitUninterruptibly(1000);
    verify(this.oslpLogItemRepository, times(4)).save(any(OslpLogItem.class));
    verify(this.oslpEnvelopeConsumer, times(2)).accept(this.oslpEnvelopeCaptor.capture());
    final List<OslpEnvelope> responseEnvelopes = this.oslpEnvelopeCaptor.getAllValues();
    assertThat(responseEnvelopes.get(0)).hasDeviceId(deviceUid1).hasMessageWithName("setRebootResponse");
    assertThat(responseEnvelopes.get(1)).hasDeviceId(deviceUid2).hasMessageWithName("setRebootResponse");
}
Also used : RegisterDevice(org.opensmartgridplatform.webdevicesimulator.service.RegisterDevice) Device(org.opensmartgridplatform.webdevicesimulator.domain.entities.Device) SocketChannel(io.netty.channel.socket.SocketChannel) NioSocketChannel(io.netty.channel.socket.nio.NioSocketChannel) Channel(io.netty.channel.Channel) OslpLogItem(org.opensmartgridplatform.webdevicesimulator.domain.entities.OslpLogItem) OslpEnvelope(org.opensmartgridplatform.oslp.OslpEnvelope) Test(org.junit.jupiter.api.Test)

Aggregations

OslpEnvelope (org.opensmartgridplatform.oslp.OslpEnvelope)42 IOException (java.io.IOException)28 UnsignedOslpEnvelopeDto (org.opensmartgridplatform.oslp.UnsignedOslpEnvelopeDto)22 DeviceResponseHandler (org.opensmartgridplatform.adapter.protocol.oslp.elster.device.DeviceResponseHandler)20 DeviceResponse (org.opensmartgridplatform.adapter.protocol.oslp.elster.device.DeviceResponse)18 DeviceRequest (org.opensmartgridplatform.adapter.protocol.oslp.elster.device.DeviceRequest)17 ByteString (com.google.protobuf.ByteString)7 Device (org.opensmartgridplatform.webdevicesimulator.domain.entities.Device)5 DeviceSimulatorException (org.opensmartgridplatform.webdevicesimulator.exceptions.DeviceSimulatorException)4 Given (io.cucumber.java.en.Given)3 Channel (io.netty.channel.Channel)3 ChannelFuture (io.netty.channel.ChannelFuture)3 UnknownHostException (java.net.UnknownHostException)3 GetStatusDeviceRequest (org.opensmartgridplatform.adapter.protocol.oslp.elster.device.requests.GetStatusDeviceRequest)3 GetStatusDeviceResponse (org.opensmartgridplatform.adapter.protocol.oslp.elster.device.responses.GetStatusDeviceResponse)3 ReadSettingsHelper.getString (org.opensmartgridplatform.cucumber.core.ReadSettingsHelper.getString)3 Oslp (org.opensmartgridplatform.oslp.Oslp)3 Message (org.opensmartgridplatform.oslp.Oslp.Message)3 SocketChannel (io.netty.channel.socket.SocketChannel)2 NioSocketChannel (io.netty.channel.socket.nio.NioSocketChannel)2