Search in sources :

Example 1 with OslpEnvelope

use of com.alliander.osgp.oslp.OslpEnvelope in project Protocol-Adapter-OSLP by OSGP.

the class OslpDeviceService method doGetPowerUsageHistory.

@Override
public void doGetPowerUsageHistory(final OslpEnvelope oslpRequest, final PowerUsageHistoryResponseMessageDataContainerDto powerUsageHistoryResponseMessageDataContainer, final GetPowerUsageHistoryDeviceRequest deviceRequest, final DeviceResponseHandler deviceResponseHandler, final String ipAddress, final String domain, final String domainVersion, final String messageType, final int retryCount, final boolean isScheduled) throws IOException {
    LOGGER.info("doGetPowerUsageHistory() for device: {}.", deviceRequest.getDeviceIdentification());
    this.saveOslpRequestLogEntry(deviceRequest, oslpRequest);
    final List<PowerUsageDataDto> powerUsageHistoryData = powerUsageHistoryResponseMessageDataContainer.getPowerUsageData();
    final PageInfoDto pageInfo = powerUsageHistoryResponseMessageDataContainer.getPageInfo();
    final Pager pager = new Pager(pageInfo.getTotalPages(), pageInfo.getPageSize(), pageInfo.getCurrentPage());
    final OslpResponseHandler oslpResponseHandler = new OslpResponseHandler() {

        @Override
        public void handleResponse(final OslpEnvelope oslpResponse) {
            OslpDeviceService.this.handleOslpResponseGetPowerUsageHistory(deviceRequest, oslpResponse, pager, powerUsageHistoryData, deviceResponseHandler, ipAddress, domain, domainVersion, messageType, retryCount, isScheduled);
        }

        @Override
        public void handleException(final Throwable t) {
            OslpDeviceService.this.handleException(t, deviceRequest, deviceResponseHandler);
        }
    };
    this.sendMessage(ipAddress, oslpRequest, oslpResponseHandler, deviceRequest);
}
Also used : PageInfoDto(com.alliander.osgp.dto.valueobjects.PageInfoDto) PowerUsageDataDto(com.alliander.osgp.dto.valueobjects.PowerUsageDataDto) OslpEnvelope(com.alliander.osgp.oslp.OslpEnvelope)

Example 2 with OslpEnvelope

use of com.alliander.osgp.oslp.OslpEnvelope in project Protocol-Adapter-OSLP by OSGP.

the class OslpEnvelopeRsaTest method buildOslpMessageSuccess.

/**
 * @param signature
 * @throws IOException
 * @throws NoSuchAlgorithmException
 * @throws InvalidKeySpecException
 * @throws NoSuchProviderException
 * @throws Exception
 */
private void buildOslpMessageSuccess(final String signature) throws IOException, NoSuchAlgorithmException, InvalidKeySpecException, NoSuchProviderException, Exception {
    final OslpEnvelope request = this.buildMessage(signature);
    // Validate security key is set in request
    final byte[] securityKey = request.getSecurityKey();
    assertTrue(securityKey.length == OslpEnvelope.SECURITY_KEY_LENGTH);
    assertFalse(ArrayUtils.isEmpty(securityKey));
    // Verify the message using public certificate
    final OslpEnvelope response = new OslpEnvelope.Builder().withSignature(signature).withProvider(PROVIDER).withSecurityKey(request.getSecurityKey()).withDeviceId(request.getDeviceId()).withSequenceNumber(request.getSequenceNumber()).withPayloadMessage(request.getPayloadMessage()).build();
    assertTrue(response.validate(CertificateHelper.createPublicKeyFromBase64(PUBLIC_KEY_BASE_64, KEY_TYPE, PROVIDER)));
}
Also used : OslpEnvelope(com.alliander.osgp.oslp.OslpEnvelope)

Example 3 with OslpEnvelope

use of com.alliander.osgp.oslp.OslpEnvelope in project Protocol-Adapter-OSLP by OSGP.

the class OslpChannelHandler method messageReceived.

@Override
public void messageReceived(final ChannelHandlerContext ctx, final MessageEvent e) throws Exception {
    final OslpEnvelope message = (OslpEnvelope) e.getMessage();
    this.oslpLogItemRepository.save(new OslpLogItem(message.getDeviceId(), this.getDeviceIdentificationFromMessage(message.getPayloadMessage()), true, message.getPayloadMessage()));
    if (message.isValid()) {
        if (this.isOslpResponse(message)) {
            LOGGER.info("Received OSLP Response (before callback): {}", message.getPayloadMessage());
            // Lookup correct callback and call handle method
            final Integer channelId = e.getChannel().getId();
            final Callback callback = this.callbacks.remove(channelId);
            if (callback == null) {
                LOGGER.warn("Callback for channel {} does not longer exist, dropping response.", channelId);
                return;
            }
            callback.handle(message);
        } else {
            LOGGER.info("Received OSLP Request: {}", message.getPayloadMessage().toString().split(" ")[0]);
            // Sequence number logic
            byte[] sequenceNumber = message.getSequenceNumber();
            Integer number = -1;
            if (!(message.getPayloadMessage().hasRegisterDeviceRequest() || message.getPayloadMessage().hasConfirmRegisterDeviceRequest())) {
                // Convert byte array to integer
                number = this.convertByteArrayToInteger(sequenceNumber);
                // increment
                if (number >= this.sequenceNumberMaximum) {
                    LOGGER.info("wrapping sequence number back to 0, current sequence number: {} next sequence number: 0", number);
                    number = 0;
                } else {
                    LOGGER.info("incrementing sequence number, current sequence number: {} next sequence number: {}", number, number + 1);
                    number += 1;
                }
                // Convert integer back to byte array
                sequenceNumber = this.convertIntegerToByteArray(number);
            }
            final byte[] deviceId = message.getDeviceId();
            // Build the OslpEnvelope with the incremented sequence number.
            final OslpEnvelope.Builder responseBuilder = new OslpEnvelope.Builder().withSignature(this.oslpSignature).withProvider(this.oslpSignatureProvider).withPrimaryKey(this.privateKey).withDeviceId(deviceId).withSequenceNumber(sequenceNumber);
            // Pass the incremented sequence number to the handleRequest()
            // function for checking.
            responseBuilder.withPayloadMessage(this.handleRequest(message, number));
            final OslpEnvelope response = responseBuilder.build();
            this.oslpLogItemRepository.save(new OslpLogItem(response.getDeviceId(), this.getDeviceIdentificationFromMessage(response.getPayloadMessage()), false, response.getPayloadMessage()));
            LOGGER.info("sending OSLP response with sequence number: {}", this.convertByteArrayToInteger(response.getSequenceNumber()));
            e.getChannel().write(response);
            LOGGER.info("Send OSLP Response: {}", response.getPayloadMessage().toString().split(" ")[0]);
        }
    } else {
        LOGGER.warn("Received message wasn't properly secured.");
    }
}
Also used : OslpLogItem(com.alliander.osgp.webdevicesimulator.domain.entities.OslpLogItem) OslpEnvelope(com.alliander.osgp.oslp.OslpEnvelope)

Example 4 with OslpEnvelope

use of com.alliander.osgp.oslp.OslpEnvelope in project Protocol-Adapter-OSLP 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 = null;
    try {
        channelFuture = this.bootstrap.connect(address);
        channelFuture.awaitUninterruptibly(this.connectionTimeout, TimeUnit.MILLISECONDS);
        if (channelFuture.getChannel() != null && channelFuture.getChannel().isConnected()) {
            LOGGER.info("Connection established to: {}", address);
        } else {
            LOGGER.info("The connnection to the device {} is not successfull", deviceIdentification);
            LOGGER.warn("Unable to connect to: {}", address);
            throw new IOException("Unable to connect");
        }
        this.callbacks.put(channelFuture.getChannel().getId(), callback);
        channelFuture.getChannel().write(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.getChannel().close();
        return response;
    } catch (final IOException | DeviceSimulatorException e) {
        LOGGER.error("send exception", e);
        // Remove callback when exception has occurred
        this.callbacks.remove(channelFuture.getChannel().getId());
        throw e;
    }
}
Also used : ChannelFuture(org.jboss.netty.channel.ChannelFuture) DeviceSimulatorException(com.alliander.osgp.webdevicesimulator.exceptions.DeviceSimulatorException) IOException(java.io.IOException) OslpEnvelope(com.alliander.osgp.oslp.OslpEnvelope)

Example 5 with OslpEnvelope

use of com.alliander.osgp.oslp.OslpEnvelope in project Protocol-Adapter-OSLP by OSGP.

the class RegisterDevice method sendRequest.

private OslpEnvelope sendRequest(final Device device, final OslpEnvelope request) throws IOException, DeviceSimulatorException {
    // Original protocol port.
    int port = this.oslpPortClient;
    // Newer protocol port.
    if (device.getProtocol().equals(ProtocolType.OSLP_ELSTER.toString())) {
        port = this.oslpElsterPortClient;
    }
    // Attempt to send the request and receive response.
    LOGGER.info("Trying to send request: {}", request.getPayloadMessage().toString());
    final OslpEnvelope response = this.oslpChannelHandler.send(new InetSocketAddress(this.oslpAddressServer, port), request, device.getDeviceIdentification());
    LOGGER.info("Received response: {}", response.getPayloadMessage().toString());
    return response;
}
Also used : InetSocketAddress(java.net.InetSocketAddress) OslpEnvelope(com.alliander.osgp.oslp.OslpEnvelope)

Aggregations

OslpEnvelope (com.alliander.osgp.oslp.OslpEnvelope)40 IOException (java.io.IOException)25 UnsignedOslpEnvelopeDto (com.alliander.osgp.oslp.UnsignedOslpEnvelopeDto)23 DeviceResponseHandler (com.alliander.osgp.adapter.protocol.oslp.elster.device.DeviceResponseHandler)21 DeviceResponse (com.alliander.osgp.adapter.protocol.oslp.elster.device.DeviceResponse)20 DeviceRequest (com.alliander.osgp.adapter.protocol.oslp.elster.device.DeviceRequest)15 GetStatusDeviceRequest (com.alliander.osgp.adapter.protocol.oslp.elster.device.requests.GetStatusDeviceRequest)4 DeviceSimulatorException (com.alliander.osgp.webdevicesimulator.exceptions.DeviceSimulatorException)4 GetStatusDeviceResponse (com.alliander.osgp.adapter.protocol.oslp.elster.device.responses.GetStatusDeviceResponse)3 Device (com.alliander.osgp.webdevicesimulator.domain.entities.Device)3 UnknownHostException (java.net.UnknownHostException)3 SetScheduleDeviceRequest (com.alliander.osgp.adapter.protocol.oslp.elster.device.requests.SetScheduleDeviceRequest)2 ScheduleMessageDataContainerDto (com.alliander.osgp.dto.valueobjects.ScheduleMessageDataContainerDto)2 Message (com.alliander.osgp.oslp.Oslp.Message)2 GetPowerUsageHistoryDeviceRequest (com.alliander.osgp.adapter.protocol.oslp.elster.device.requests.GetPowerUsageHistoryDeviceRequest)1 ResumeScheduleDeviceRequest (com.alliander.osgp.adapter.protocol.oslp.elster.device.requests.ResumeScheduleDeviceRequest)1 SetConfigurationDeviceRequest (com.alliander.osgp.adapter.protocol.oslp.elster.device.requests.SetConfigurationDeviceRequest)1 SetDeviceVerificationKeyDeviceRequest (com.alliander.osgp.adapter.protocol.oslp.elster.device.requests.SetDeviceVerificationKeyDeviceRequest)1 SetEventNotificationsDeviceRequest (com.alliander.osgp.adapter.protocol.oslp.elster.device.requests.SetEventNotificationsDeviceRequest)1 SetLightDeviceRequest (com.alliander.osgp.adapter.protocol.oslp.elster.device.requests.SetLightDeviceRequest)1