Example usage for io.netty.buffer ByteBuf readUnsignedIntLE

List of usage examples for io.netty.buffer ByteBuf readUnsignedIntLE

Introduction

In this page you can find the example usage for io.netty.buffer ByteBuf readUnsignedIntLE.

Prototype

public abstract long readUnsignedIntLE();

Source Link

Document

Gets an unsigned 32-bit integer at the current readerIndex in the Little Endian Byte Order and increases the readerIndex by 4 in this buffer.

Usage

From source file:nearenough.protocol.RtMessage.java

License:Open Source License

private int extractNumTags(ByteBuf msg) {
    long readNumTags = msg.readUnsignedIntLE();

    // Spec says max # tags can be 2^32-1, but capping at 64k tags in this implementation
    if (readNumTags > 0xffffL) {
        throw new InvalidNumTagsException("invalid num_tags value " + readNumTags);
    }//from   w  ww. j a  v  a 2 s  .  com

    return (int) readNumTags;
}

From source file:nearenough.protocol.RtMessage.java

License:Open Source License

private int[] extractOffsets(ByteBuf msg) {
    int numOffsets = numTags - 1;
    int endOfPayload = msg.readableBytes() - (4 * numOffsets);

    // Offset for every tag, including the value of tag 0 which starts immediately after header.
    int[] offsets = new int[numTags];
    offsets[0] = 0;/*w w  w  .  j  a  v  a  2s . c  om*/

    for (int i = 0; i < numOffsets; i++) {
        long offset = msg.readUnsignedIntLE();

        if ((offset % 4) != 0) {
            throw new TagOffsetUnalignedException("offset " + i + " not multiple of 4: " + offset);
        }
        if (offset > endOfPayload) {
            throw new TagOffsetOverflowException("offset " + i + " overflow: " + offset);
        }

        checkState((int) offset >= 0, "impossible, negative offset");
        offsets[i + 1] = (int) offset;
    }

    return offsets;
}

From source file:org.eclipse.milo.opcua.stack.client.transport.uasc.UascClientMessageHandler.java

License:Open Source License

private void onSecureMessage(ChannelHandlerContext ctx, ByteBuf buffer) throws UaException {
    buffer.skipBytes(3 + 1 + 4); // skip messageType, chunkType, messageSize

    long secureChannelId = buffer.readUnsignedIntLE();
    if (secureChannelId != secureChannel.getChannelId()) {
        throw new UaException(StatusCodes.Bad_SecureChannelIdInvalid,
                "invalid secure channel id: " + secureChannelId);
    }//w  w w.jav a  2  s .  c om

    if (accumulateChunk(buffer)) {
        final List<ByteBuf> buffersToDecode = chunkBuffers;
        chunkBuffers = new ArrayList<>(maxChunkCount);

        serializationQueue.decode((binaryDecoder, chunkDecoder) -> {
            try {
                validateChunkHeaders(buffersToDecode);
            } catch (UaException e) {
                logger.error("Error validating chunk headers: {}", e.getMessage(), e);
                buffersToDecode.forEach(ReferenceCountUtil::safeRelease);
                ctx.close();
                return;
            }

            chunkDecoder.decodeSymmetric(secureChannel, buffersToDecode, new ChunkDecoder.Callback() {
                @Override
                public void onDecodingError(UaException ex) {
                    logger.error("Error decoding symmetric message: {}", ex.getMessage(), ex);

                    ctx.close();
                }

                @Override
                public void onMessageAborted(MessageAbortedException ex) {
                    logger.warn("Received message abort chunk; error={}, reason={}", ex.getStatusCode(),
                            ex.getMessage());

                    long requestId = ex.getRequestId();
                    UaTransportRequest request = pending.remove(requestId);

                    if (request != null) {
                        request.getFuture().completeExceptionally(ex);
                    } else {
                        logger.warn("No pending request for requestId={}", requestId);
                    }
                }

                @Override
                public void onMessageDecoded(ByteBuf message, long requestId) {
                    UaTransportRequest request = pending.remove(requestId);

                    try {
                        if (request != null) {
                            UaResponseMessage response = (UaResponseMessage) binaryDecoder.setBuffer(message)
                                    .readMessage(null);

                            request.getFuture().complete(response);
                        } else {
                            logger.warn("No pending request for requestId={}", requestId);
                        }
                    } catch (Throwable t) {
                        logger.error("Error decoding UaResponseMessage", t);

                        if (request != null) {
                            request.getFuture().completeExceptionally(t);
                        }
                    } finally {
                        message.release();
                    }
                }
            });
        });
    }
}

From source file:org.eclipse.milo.opcua.stack.server.transport.uasc.UascServerAsymmetricHandler.java

License:Open Source License

private void onOpenSecureChannel(ChannelHandlerContext ctx, ByteBuf buffer) throws UaException {
    buffer.skipBytes(3); // Skip messageType

    char chunkType = (char) buffer.readByte();

    if (chunkType == 'A') {
        chunkBuffers.forEach(ByteBuf::release);
        chunkBuffers.clear();//from   w w  w . jav  a2  s. c o  m
        headerRef.set(null);
    } else {
        buffer.skipBytes(4); // Skip messageSize

        final long secureChannelId = buffer.readUnsignedIntLE();

        final AsymmetricSecurityHeader header = AsymmetricSecurityHeader.decode(buffer, maxArrayLength,
                maxStringLength);

        if (!headerRef.compareAndSet(null, header)) {
            if (!header.equals(headerRef.get())) {
                throw new UaException(StatusCodes.Bad_SecurityChecksFailed,
                        "subsequent AsymmetricSecurityHeader did not match");
            }
        }

        if (secureChannelId != 0) {
            if (secureChannel == null) {
                throw new UaException(StatusCodes.Bad_TcpSecureChannelUnknown,
                        "unknown secure channel id: " + secureChannelId);
            }

            if (secureChannelId != secureChannel.getChannelId()) {
                throw new UaException(StatusCodes.Bad_TcpSecureChannelUnknown,
                        "unknown secure channel id: " + secureChannelId);
            }
        }

        if (secureChannel == null) {
            secureChannel = new ServerSecureChannel();
            secureChannel.setChannelId(stackServer.getNextChannelId());

            String securityPolicyUri = header.getSecurityPolicyUri();
            SecurityPolicy securityPolicy = SecurityPolicy.fromUri(securityPolicyUri);

            secureChannel.setSecurityPolicy(securityPolicy);

            if (securityPolicy != SecurityPolicy.None) {
                secureChannel.setRemoteCertificate(header.getSenderCertificate().bytesOrEmpty());

                CertificateValidator certificateValidator = stackServer.getConfig().getCertificateValidator();

                certificateValidator.validate(secureChannel.getRemoteCertificate());
                certificateValidator.verifyTrustChain(secureChannel.getRemoteCertificateChain());

                CertificateManager certificateManager = stackServer.getConfig().getCertificateManager();

                Optional<X509Certificate[]> localCertificateChain = certificateManager
                        .getCertificateChain(header.getReceiverThumbprint());

                Optional<KeyPair> keyPair = certificateManager.getKeyPair(header.getReceiverThumbprint());

                if (localCertificateChain.isPresent() && keyPair.isPresent()) {
                    X509Certificate[] chain = localCertificateChain.get();

                    secureChannel.setLocalCertificate(chain[0]);
                    secureChannel.setLocalCertificateChain(chain);
                    secureChannel.setKeyPair(keyPair.get());
                } else {
                    throw new UaException(StatusCodes.Bad_SecurityChecksFailed,
                            "no certificate for provided thumbprint");
                }
            }
        }

        int chunkSize = buffer.readerIndex(0).readableBytes();

        if (chunkSize > maxChunkSize) {
            throw new UaException(StatusCodes.Bad_TcpMessageTooLarge,
                    String.format("max chunk size exceeded (%s)", maxChunkSize));
        }

        chunkBuffers.add(buffer.retain());

        if (maxChunkCount > 0 && chunkBuffers.size() > maxChunkCount) {
            throw new UaException(StatusCodes.Bad_TcpMessageTooLarge,
                    String.format("max chunk count exceeded (%s)", maxChunkCount));
        }

        if (chunkType == 'F') {
            final List<ByteBuf> buffersToDecode = chunkBuffers;

            chunkBuffers = new ArrayList<>();
            headerRef.set(null);

            serializationQueue.decode((binaryDecoder, chunkDecoder) -> chunkDecoder
                    .decodeAsymmetric(secureChannel, buffersToDecode, new ChunkDecoder.Callback() {
                        @Override
                        public void onDecodingError(UaException ex) {
                            logger.error("Error decoding asymmetric message: {}", ex.getMessage(), ex);

                            ctx.close();
                        }

                        @Override
                        public void onMessageAborted(MessageAbortedException ex) {
                            logger.warn("Asymmetric message aborted. error={} reason={}", ex.getStatusCode(),
                                    ex.getMessage());
                        }

                        @Override
                        public void onMessageDecoded(ByteBuf message, long requestId) {
                            try {
                                OpenSecureChannelRequest request = (OpenSecureChannelRequest) binaryDecoder
                                        .setBuffer(message).readMessage(null);

                                logger.debug("Received OpenSecureChannelRequest ({}, id={}).",
                                        request.getRequestType(), secureChannelId);

                                sendOpenSecureChannelResponse(ctx, requestId, request);
                            } catch (Throwable t) {
                                logger.error("Error decoding OpenSecureChannelRequest", t);
                                ctx.close();
                            } finally {
                                message.release();
                                buffersToDecode.clear();
                            }
                        }
                    }));
        }
    }
}

From source file:org.eclipse.milo.opcua.stack.server.transport.uasc.UascServerSymmetricHandler.java

License:Open Source License

private void onSecureMessage(ChannelHandlerContext ctx, ByteBuf buffer) throws UaException {
    buffer.skipBytes(3); // Skip messageType

    char chunkType = (char) buffer.readByte();

    if (chunkType == 'A') {
        chunkBuffers.forEach(ByteBuf::release);
        chunkBuffers.clear();/*www .  j  av  a  2 s.  c o  m*/
    } else {
        buffer.skipBytes(4); // Skip messageSize

        long secureChannelId = buffer.readUnsignedIntLE();
        if (secureChannelId != secureChannel.getChannelId()) {
            throw new UaException(StatusCodes.Bad_SecureChannelIdInvalid,
                    "invalid secure channel id: " + secureChannelId);
        }

        int chunkSize = buffer.readerIndex(0).readableBytes();
        if (chunkSize > maxChunkSize) {
            throw new UaException(StatusCodes.Bad_TcpMessageTooLarge,
                    String.format("max chunk size exceeded (%s)", maxChunkSize));
        }

        chunkBuffers.add(buffer.retain());

        if (maxChunkCount > 0 && chunkBuffers.size() > maxChunkCount) {
            throw new UaException(StatusCodes.Bad_TcpMessageTooLarge,
                    String.format("max chunk count exceeded (%s)", maxChunkCount));
        }

        if (chunkType == 'F') {
            final List<ByteBuf> buffersToDecode = chunkBuffers;
            chunkBuffers = new ArrayList<>();

            serializationQueue.decode((binaryDecoder, chunkDecoder) -> {
                try {
                    validateChunkHeaders(buffersToDecode);
                } catch (UaException e) {
                    logger.error("Error validating chunk headers: {}", e.getMessage(), e);
                    buffersToDecode.forEach(ReferenceCountUtil::safeRelease);
                    ctx.fireExceptionCaught(e);
                    return;
                }

                chunkDecoder.decodeSymmetric(secureChannel, buffersToDecode, new ChunkDecoder.Callback() {
                    @Override
                    public void onDecodingError(UaException ex) {
                        logger.error("Error decoding symmetric message: {}", ex.getMessage(), ex);

                        ctx.close();
                    }

                    @Override
                    public void onMessageAborted(MessageAbortedException ex) {
                        logger.warn("Received message abort chunk; error={}, reason={}", ex.getStatusCode(),
                                ex.getMessage());
                    }

                    @Override
                    public void onMessageDecoded(ByteBuf message, long requestId) {
                        UaRequestMessage request = (UaRequestMessage) binaryDecoder.setBuffer(message)
                                .readMessage(null);

                        stackServer.getConfig().getExecutor().execute(() -> {
                            try {
                                String endpointUrl = ctx.channel().attr(UascServerHelloHandler.ENDPOINT_URL_KEY)
                                        .get();

                                EndpointDescription endpoint = ctx.channel()
                                        .attr(UascServerAsymmetricHandler.ENDPOINT_KEY).get();

                                String path = EndpointUtil.getPath(endpointUrl);

                                InetSocketAddress remoteSocketAddress = (InetSocketAddress) ctx.channel()
                                        .remoteAddress();

                                ServiceRequest serviceRequest = new ServiceRequest(stackServer, request,
                                        endpoint, secureChannel.getChannelId(),
                                        remoteSocketAddress.getAddress(),
                                        secureChannel.getRemoteCertificateBytes());

                                serviceRequest.getFuture().whenComplete((response, fault) -> {
                                    if (response != null) {
                                        sendServiceResponse(ctx, requestId, request, response);
                                    } else {
                                        UInteger requestHandle = request.getRequestHeader().getRequestHandle();

                                        sendServiceFault(ctx, requestId, requestHandle, fault);
                                    }
                                });

                                stackServer.onServiceRequest(path, serviceRequest);
                            } catch (Throwable t) {
                                logger.error("Error decoding UaRequestMessage", t);

                                sendServiceFault(ctx, requestId, uint(0), t);
                            } finally {
                                message.release();
                                buffersToDecode.clear();
                            }
                        });
                    }
                });
            });
        }
    }
}

From source file:org.traccar.protocol.AdmProtocolDecoder.java

License:Apache License

private Position decodeData(Channel channel, SocketAddress remoteAddress, ByteBuf buf, int type) {

    DeviceSession deviceSession = getDeviceSession(channel, remoteAddress);
    if (deviceSession == null) {
        return null;
    }/*from  ww w .jav a 2s . c om*/

    if (BitUtil.to(type, 2) == 0) {
        Position position = new Position(getProtocolName());
        position.setDeviceId(deviceSession.getDeviceId());

        position.set(Position.KEY_VERSION_FW, buf.readUnsignedByte());
        position.set(Position.KEY_INDEX, buf.readUnsignedShortLE());

        int status = buf.readUnsignedShortLE();
        position.set(Position.KEY_STATUS, status);
        position.setValid(!BitUtil.check(status, 5));
        position.setLatitude(buf.readFloatLE());
        position.setLongitude(buf.readFloatLE());
        position.setCourse(buf.readUnsignedShortLE() * 0.1);
        position.setSpeed(UnitsConverter.knotsFromKph(buf.readUnsignedShortLE() * 0.1));

        position.set(Position.KEY_ACCELERATION, buf.readUnsignedByte() * 0.1);
        position.setAltitude(buf.readShortLE());
        position.set(Position.KEY_HDOP, buf.readUnsignedByte() * 0.1);
        position.set(Position.KEY_SATELLITES, buf.readUnsignedByte() & 0x0f);

        position.setTime(new Date(buf.readUnsignedIntLE() * 1000));

        position.set(Position.KEY_POWER, buf.readUnsignedShortLE() * 0.001);
        position.set(Position.KEY_BATTERY, buf.readUnsignedShortLE() * 0.001);

        if (BitUtil.check(type, 2)) {
            buf.readUnsignedByte(); // vib
            buf.readUnsignedByte(); // vib_count

            int out = buf.readUnsignedByte();
            for (int i = 0; i <= 3; i++) {
                position.set(Position.PREFIX_OUT + (i + 1), BitUtil.check(out, i) ? 1 : 0);
            }

            buf.readUnsignedByte(); // in_alarm
        }

        if (BitUtil.check(type, 3)) {
            for (int i = 1; i <= 6; i++) {
                position.set(Position.PREFIX_ADC + i, buf.readUnsignedShortLE() * 0.001);
            }
        }

        if (BitUtil.check(type, 4)) {
            for (int i = 1; i <= 2; i++) {
                position.set(Position.PREFIX_COUNT + i, buf.readUnsignedIntLE());
            }
        }

        if (BitUtil.check(type, 5)) {
            for (int i = 1; i <= 3; i++) {
                buf.readUnsignedShortLE(); // fuel level
            }
            for (int i = 1; i <= 3; i++) {
                position.set(Position.PREFIX_TEMP + i, buf.readUnsignedByte());
            }
        }

        if (BitUtil.check(type, 6)) {
            int endIndex = buf.readerIndex() + buf.readUnsignedByte();
            while (buf.readerIndex() < endIndex) {
                int mask = buf.readUnsignedByte();
                long value;
                switch (BitUtil.from(mask, 6)) {
                case 3:
                    value = buf.readLongLE();
                    break;
                case 2:
                    value = buf.readUnsignedIntLE();
                    break;
                case 1:
                    value = buf.readUnsignedShortLE();
                    break;
                default:
                    value = buf.readUnsignedByte();
                    break;
                }
                int index = BitUtil.to(mask, 6);
                switch (index) {
                case 1:
                    position.set(Position.PREFIX_TEMP + 1, value);
                    break;
                case 2:
                    position.set("humidity", value);
                    break;
                case 3:
                    position.set("illumination", value);
                    break;
                case 4:
                    position.set(Position.KEY_BATTERY, value);
                    break;
                default:
                    position.set("can" + index, value);
                    break;
                }
            }
        }

        if (BitUtil.check(type, 7)) {
            position.set(Position.KEY_ODOMETER, buf.readUnsignedIntLE());
        }

        return position;
    }

    return null;
}

From source file:org.traccar.protocol.AnytrekProtocolDecoder.java

License:Apache License

@Override
protected Object decode(Channel channel, SocketAddress remoteAddress, Object msg) throws Exception {

    ByteBuf buf = (ByteBuf) msg;

    buf.skipBytes(2); // header
    buf.readUnsignedShortLE(); // size
    int type = buf.readUnsignedByte();

    String imei = ByteBufUtil.hexDump(buf.readSlice(8)).substring(2);
    DeviceSession deviceSession = getDeviceSession(channel, remoteAddress, imei);
    if (deviceSession == null) {
        return null;
    }//  w w w. j  a v  a2  s.co m

    Position position = new Position(getProtocolName());
    position.setDeviceId(deviceSession.getDeviceId());

    position.set(Position.KEY_VERSION_FW, buf.readUnsignedShortLE());
    position.set(Position.KEY_BATTERY, buf.readUnsignedShortLE() * 0.01);
    position.set(Position.KEY_RSSI, buf.readUnsignedByte());

    DateBuilder dateBuilder = new DateBuilder()
            .setDate(buf.readUnsignedByte(), buf.readUnsignedByte(), buf.readUnsignedByte())
            .setTime(buf.readUnsignedByte(), buf.readUnsignedByte(), buf.readUnsignedByte());
    position.setTime(dateBuilder.getDate());

    position.set(Position.KEY_SATELLITES, BitUtil.to(buf.readUnsignedByte(), 4));

    double latitude = buf.readUnsignedIntLE() / 1800000.0;
    double longitude = buf.readUnsignedIntLE() / 1800000.0;
    position.setSpeed(UnitsConverter.knotsFromKph(buf.readUnsignedByte()));

    int flags = buf.readUnsignedShortLE();
    position.setCourse(BitUtil.to(flags, 10));
    position.setValid(BitUtil.check(flags, 12));

    if (!BitUtil.check(flags, 10)) {
        latitude = -latitude;
    }
    if (BitUtil.check(flags, 11)) {
        longitude = -longitude;
    }

    position.setLatitude(latitude);
    position.setLongitude(longitude);

    buf.readUnsignedIntLE(); // info index
    buf.readUnsignedIntLE(); // setting index

    flags = buf.readUnsignedByte();
    position.set(Position.KEY_CHARGE, BitUtil.check(flags, 0));
    position.set(Position.KEY_IGNITION, BitUtil.check(flags, 1));
    position.set(Position.KEY_ALARM, BitUtil.check(flags, 4) ? Position.ALARM_GENERAL : null);

    buf.readUnsignedShortLE(); // charge current

    position.set(Position.KEY_ODOMETER, buf.readUnsignedIntLE());

    sendResponse(channel, remoteAddress, type);

    return position;
}

From source file:org.traccar.protocol.ApelProtocolDecoder.java

License:Apache License

@Override
protected Object decode(Channel channel, SocketAddress remoteAddress, Object msg) throws Exception {

    ByteBuf buf = (ByteBuf) msg;
    int type = buf.readUnsignedShortLE();
    boolean alarm = (type & 0x8000) != 0;
    type = type & 0x7FFF;/*from  w  w  w .j a v a  2s . c om*/
    buf.readUnsignedShortLE(); // length

    if (alarm) {
        sendSimpleMessage(channel, MSG_ACK_ALARM);
    }

    if (type == MSG_TRACKER_ID) {
        return null; // unsupported authentication type
    }

    if (type == MSG_TRACKER_ID_EXT) {

        buf.readUnsignedIntLE(); // id
        int length = buf.readUnsignedShortLE();
        buf.skipBytes(length);
        length = buf.readUnsignedShortLE();
        getDeviceSession(channel, remoteAddress, buf.readSlice(length).toString(StandardCharsets.US_ASCII));

    } else if (type == MSG_LAST_LOG_INDEX) {

        long index = buf.readUnsignedIntLE();
        if (index > 0) {
            newIndex = index;
            requestArchive(channel);
        }

    } else if (type == MSG_CURRENT_GPS_DATA || type == MSG_STATE_FULL_INFO_T104 || type == MSG_LOG_RECORDS) {

        DeviceSession deviceSession = getDeviceSession(channel, remoteAddress);
        if (deviceSession == null) {
            return null;
        }

        List<Position> positions = new LinkedList<>();

        int recordCount = 1;
        if (type == MSG_LOG_RECORDS) {
            recordCount = buf.readUnsignedShortLE();
        }

        for (int j = 0; j < recordCount; j++) {
            Position position = new Position(getProtocolName());
            position.setDeviceId(deviceSession.getDeviceId());

            int subtype = type;
            if (type == MSG_LOG_RECORDS) {
                position.set(Position.KEY_ARCHIVE, true);
                lastIndex = buf.readUnsignedIntLE() + 1;
                position.set(Position.KEY_INDEX, lastIndex);

                subtype = buf.readUnsignedShortLE();
                if (subtype != MSG_CURRENT_GPS_DATA && subtype != MSG_STATE_FULL_INFO_T104) {
                    buf.skipBytes(buf.readUnsignedShortLE());
                    continue;
                }
                buf.readUnsignedShortLE(); // length
            }

            position.setTime(new Date(buf.readUnsignedIntLE() * 1000));
            position.setLatitude(buf.readIntLE() * 180.0 / 0x7FFFFFFF);
            position.setLongitude(buf.readIntLE() * 180.0 / 0x7FFFFFFF);

            if (subtype == MSG_STATE_FULL_INFO_T104) {
                int speed = buf.readUnsignedByte();
                position.setValid(speed != 255);
                position.setSpeed(UnitsConverter.knotsFromKph(speed));
                position.set(Position.KEY_HDOP, buf.readByte());
            } else {
                int speed = buf.readShortLE();
                position.setValid(speed != -1);
                position.setSpeed(UnitsConverter.knotsFromKph(speed * 0.01));
            }

            position.setCourse(buf.readShortLE() * 0.01);
            position.setAltitude(buf.readShortLE());

            if (subtype == MSG_STATE_FULL_INFO_T104) {

                position.set(Position.KEY_SATELLITES, buf.readUnsignedByte());
                position.set(Position.KEY_RSSI, buf.readUnsignedByte());
                position.set(Position.KEY_EVENT, buf.readUnsignedShortLE());
                position.set(Position.KEY_ODOMETER, buf.readUnsignedIntLE());
                position.set(Position.KEY_INPUT, buf.readUnsignedByte());
                position.set(Position.KEY_OUTPUT, buf.readUnsignedByte());

                for (int i = 1; i <= 8; i++) {
                    position.set(Position.PREFIX_ADC + i, buf.readUnsignedShortLE());
                }

                position.set(Position.PREFIX_COUNT + 1, buf.readUnsignedIntLE());
                position.set(Position.PREFIX_COUNT + 2, buf.readUnsignedIntLE());
                position.set(Position.PREFIX_COUNT + 3, buf.readUnsignedIntLE());
            }

            positions.add(position);
        }

        buf.readUnsignedIntLE(); // crc

        if (type == MSG_LOG_RECORDS) {
            requestArchive(channel);
        } else {
            sendSimpleMessage(channel, MSG_REQUEST_LAST_LOG_INDEX);
        }

        return positions;
    }

    return null;
}

From source file:org.traccar.protocol.At2000ProtocolDecoder.java

License:Apache License

@Override
protected Object decode(Channel channel, SocketAddress remoteAddress, Object msg) throws Exception {

    ByteBuf buf = (ByteBuf) msg;

    if (buf.getUnsignedByte(buf.readerIndex()) == 0x01) {
        buf.readUnsignedByte(); // codec id
    }/*  w  w w . java  2 s .c  om*/

    int type = buf.readUnsignedByte();
    buf.readUnsignedMediumLE(); // length
    buf.skipBytes(BLOCK_LENGTH - 1 - 3);

    if (type == MSG_DEVICE_ID) {

        String imei = buf.readSlice(15).toString(StandardCharsets.US_ASCII);
        if (getDeviceSession(channel, remoteAddress, imei) != null) {

            byte[] iv = new byte[BLOCK_LENGTH];
            buf.readBytes(iv);
            IvParameterSpec ivSpec = new IvParameterSpec(iv);

            SecretKeySpec keySpec = new SecretKeySpec(
                    DataConverter.parseHex("000102030405060708090a0b0c0d0e0f"), "AES");

            cipher = Cipher.getInstance("AES/CBC/NoPadding");
            cipher.init(Cipher.DECRYPT_MODE, keySpec, ivSpec);

            byte[] data = new byte[BLOCK_LENGTH];
            buf.readBytes(data);
            cipher.update(data);

        }

    } else if (type == MSG_TRACK_RESPONSE) {

        DeviceSession deviceSession = getDeviceSession(channel, remoteAddress);
        if (deviceSession == null) {
            return null;
        }

        if (buf.capacity() <= BLOCK_LENGTH) {
            return null; // empty message
        }

        List<Position> positions = new LinkedList<>();

        byte[] data = new byte[buf.capacity() - BLOCK_LENGTH];
        buf.readBytes(data);
        buf = Unpooled.wrappedBuffer(cipher.update(data));
        try {
            while (buf.readableBytes() >= 63) {

                Position position = new Position(getProtocolName());
                position.setDeviceId(deviceSession.getDeviceId());

                buf.readUnsignedShortLE(); // index
                buf.readUnsignedShortLE(); // reserved

                position.setValid(true);

                position.setTime(new Date(buf.readLongLE() * 1000));

                position.setLatitude(buf.readFloatLE());
                position.setLongitude(buf.readFloatLE());
                position.setAltitude(buf.readFloatLE());
                position.setSpeed(UnitsConverter.knotsFromKph(buf.readFloatLE()));
                position.setCourse(buf.readFloatLE());

                buf.readUnsignedIntLE(); // geozone event
                buf.readUnsignedIntLE(); // io events
                buf.readUnsignedIntLE(); // geozone value
                buf.readUnsignedIntLE(); // io values
                buf.readUnsignedShortLE(); // operator

                position.set(Position.PREFIX_ADC + 1, buf.readUnsignedShortLE());
                position.set(Position.PREFIX_ADC + 1, buf.readUnsignedShortLE());

                position.set(Position.KEY_POWER, buf.readUnsignedShortLE() * 0.001);

                buf.readUnsignedShortLE(); // cid
                position.set(Position.KEY_RSSI, buf.readUnsignedByte());
                buf.readUnsignedByte(); // current profile

                position.set(Position.KEY_BATTERY, buf.readUnsignedByte());
                position.set(Position.PREFIX_TEMP + 1, buf.readUnsignedByte());
                position.set(Position.KEY_SATELLITES, buf.readUnsignedByte());

                positions.add(position);

            }
        } finally {
            buf.release();
        }

        return positions;

    }

    if (type == MSG_DEVICE_ID) {
        sendRequest(channel);
    }

    return null;
}

From source file:org.traccar.protocol.AutoTrackProtocolDecoder.java

License:Apache License

private Position decodeTelemetry(Channel channel, SocketAddress remoteAddress, DeviceSession deviceSession,
        ByteBuf buf) {

    Position position = new Position(getProtocolName());
    position.setDeviceId(deviceSession.getDeviceId());

    position.setTime(new Date(1009843200000L + buf.readUnsignedIntLE() * 1000)); // seconds since 2002
    position.setLatitude(buf.readIntLE() * 0.0000001);
    position.setLongitude(buf.readIntLE() * 0.0000001);

    position.set(Position.KEY_ODOMETER, buf.readUnsignedIntLE());
    position.set(Position.KEY_FUEL_USED, buf.readUnsignedIntLE());

    position.setSpeed(UnitsConverter.knotsFromKph(buf.readUnsignedShortLE()));
    buf.readUnsignedShortLE(); // max speed

    position.set(Position.KEY_INPUT, buf.readUnsignedShortLE());
    buf.readUnsignedIntLE(); // di 3 count
    buf.readUnsignedIntLE(); // di 4 count

    for (int i = 0; i < 5; i++) {
        position.set(Position.PREFIX_ADC + (i + 1), buf.readUnsignedShortLE());
    }/*w  w w.ja  va 2s.c  om*/

    position.setCourse(buf.readUnsignedShortLE());

    position.set(Position.KEY_STATUS, buf.readUnsignedShortLE());
    position.set(Position.KEY_EVENT, buf.readUnsignedShortLE());
    position.set(Position.KEY_DRIVER_UNIQUE_ID, buf.readLongLE());

    int index = buf.readUnsignedShortLE();

    buf.readUnsignedShortLE(); // checksum

    if (channel != null) {
        ByteBuf response = Unpooled.buffer();
        response.writeInt(0xF1F1F1F1); // sync
        response.writeByte(MSG_TELEMETRY_CONFIRM);
        response.writeShortLE(2); // length
        response.writeShortLE(index);
        response.writeShort(Checksum.crc16(Checksum.CRC16_XMODEM, response.nioBuffer()));
        channel.writeAndFlush(new NetworkMessage(response, remoteAddress));
    }

    return position;
}