Example usage for io.netty.buffer ByteBuf readSlice

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

Introduction

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

Prototype

public abstract ByteBuf readSlice(int length);

Source Link

Document

Returns a new slice of this buffer's sub-region starting at the current readerIndex and increases the readerIndex by the size of the new slice (= length ).

Usage

From source file:org.traccar.protocol.MeiligaoProtocolDecoder.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.readShort(); // length
    ByteBuf id = buf.readSlice(7);
    int command = buf.readUnsignedShort();

    if (command == MSG_LOGIN) {
        ByteBuf response = Unpooled.wrappedBuffer(new byte[] { 0x01 });
        sendResponse(channel, remoteAddress, id, MSG_LOGIN_RESPONSE, response);
        return null;
    } else if (command == MSG_HEARTBEAT) {
        ByteBuf response = Unpooled.wrappedBuffer(new byte[] { 0x01 });
        sendResponse(channel, remoteAddress, id, MSG_HEARTBEAT, response);
        return null;
    } else if (command == MSG_SERVER) {
        ByteBuf response = Unpooled.copiedBuffer(getServer(channel, ':'), StandardCharsets.US_ASCII);
        sendResponse(channel, remoteAddress, id, MSG_SERVER, response);
        return null;
    } else if (command == MSG_UPLOAD_PHOTO) {
        byte imageIndex = buf.readByte();
        photos.put(imageIndex, Unpooled.buffer());
        ByteBuf response = Unpooled.copiedBuffer(new byte[] { imageIndex });
        sendResponse(channel, remoteAddress, id, MSG_UPLOAD_PHOTO_RESPONSE, response);
        return null;
    } else if (command == MSG_UPLOAD_COMPLETE) {
        byte imageIndex = buf.readByte();
        ByteBuf response = Unpooled.copiedBuffer(new byte[] { imageIndex, 0, 0 });
        sendResponse(channel, remoteAddress, id, MSG_RETRANSMISSION, response);
        return null;
    }//from  www .  j av  a 2 s .com

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

    if (command == MSG_DATA_PHOTO) {

        byte imageIndex = buf.readByte();
        buf.readUnsignedShort(); // image footage
        buf.readUnsignedByte(); // total packets
        buf.readUnsignedByte(); // packet index

        photos.get(imageIndex).writeBytes(buf, buf.readableBytes() - 2 - 2);

        return null;

    } else if (command == MSG_RETRANSMISSION) {

        return decodeRetransmission(buf, deviceSession);

    } else {

        Position position = new Position(getProtocolName());

        position.setDeviceId(deviceSession.getDeviceId());

        if (command == MSG_ALARM) {
            short alarmCode = buf.readUnsignedByte();
            position.set(Position.KEY_ALARM, decodeAlarm(alarmCode));
            if (alarmCode >= 0x02 && alarmCode <= 0x05) {
                position.set(Position.PREFIX_IN + alarmCode, 1);
            } else if (alarmCode >= 0x32 && alarmCode <= 0x35) {
                position.set(Position.PREFIX_IN + (alarmCode - 0x30), 0);
            }
        } else if (command == MSG_POSITION_LOGGED) {
            buf.skipBytes(6);
        } else if (command == MSG_RFID) {
            for (int i = 0; i < 15; i++) {
                long rfid = buf.readUnsignedInt();
                if (rfid != 0) {
                    String card = String.format("%010d", rfid);
                    position.set("card" + (i + 1), card);
                    position.set(Position.KEY_DRIVER_UNIQUE_ID, card);
                }
            }
        } else if (command == MSG_POSITION_IMAGE) {
            byte imageIndex = buf.readByte();
            buf.readUnsignedByte(); // image upload type
            String uniqueId = Context.getIdentityManager().getById(deviceSession.getDeviceId()).getUniqueId();
            ByteBuf photo = photos.remove(imageIndex);
            try {
                position.set(Position.KEY_IMAGE, Context.getMediaManager().writeFile(uniqueId, photo, "jpg"));
            } finally {
                photo.release();
            }
        }

        String sentence = buf.toString(buf.readerIndex(), buf.readableBytes() - 4, StandardCharsets.US_ASCII);

        switch (command) {
        case MSG_POSITION:
        case MSG_POSITION_LOGGED:
        case MSG_ALARM:
        case MSG_POSITION_IMAGE:
            return decodeRegular(position, sentence);
        case MSG_RFID:
            return decodeRfid(position, sentence);
        case MSG_OBD_RT:
            return decodeObd(position, sentence);
        case MSG_OBD_RTA:
            return decodeObdA(position, sentence);
        default:
            return null;
        }

    }
}

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

License:Apache License

private List<Position> decodeBinaryE(Channel channel, SocketAddress remoteAddress, ByteBuf buf) {
    List<Position> positions = new LinkedList<>();

    buf.readerIndex(buf.indexOf(buf.readerIndex(), buf.writerIndex(), (byte) ',') + 1);
    String imei = buf.readSlice(15).toString(StandardCharsets.US_ASCII);
    buf.skipBytes(1 + 3 + 1);/*from w w w. j a  va  2 s. c o  m*/

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

    buf.readUnsignedIntLE(); // remaining cache
    int count = buf.readUnsignedShortLE();

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

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

        int paramCount = buf.readUnsignedByte();
        for (int j = 0; j < paramCount; j++) {
            int id = buf.readUnsignedByte();
            switch (id) {
            case 0x01:
                position.set(Position.KEY_EVENT, buf.readUnsignedByte());
                break;
            case 0x05:
                position.setValid(buf.readUnsignedByte() > 0);
                break;
            case 0x06:
                position.set(Position.KEY_SATELLITES, buf.readUnsignedByte());
                break;
            case 0x07:
                position.set(Position.KEY_RSSI, buf.readUnsignedByte());
                break;
            default:
                buf.readUnsignedByte();
                break;
            }
        }

        paramCount = buf.readUnsignedByte();
        for (int j = 0; j < paramCount; j++) {
            int id = buf.readUnsignedByte();
            switch (id) {
            case 0x08:
                position.setSpeed(UnitsConverter.knotsFromKph(buf.readUnsignedShortLE()));
                break;
            case 0x09:
                position.setCourse(buf.readUnsignedShortLE());
                break;
            case 0x0B:
                position.setAltitude(buf.readShortLE());
                break;
            case 0x19:
                position.set(Position.KEY_BATTERY, buf.readUnsignedShortLE() * 0.01);
                break;
            case 0x1A:
                position.set(Position.KEY_POWER, buf.readUnsignedShortLE() * 0.01);
                break;
            default:
                buf.readUnsignedShortLE();
                break;
            }
        }

        paramCount = buf.readUnsignedByte();
        for (int j = 0; j < paramCount; j++) {
            int id = buf.readUnsignedByte();
            switch (id) {
            case 0x02:
                position.setLatitude(buf.readIntLE() * 0.000001);
                break;
            case 0x03:
                position.setLongitude(buf.readIntLE() * 0.000001);
                break;
            case 0x04:
                position.setTime(new Date((946684800 + buf.readUnsignedIntLE()) * 1000)); // 2000-01-01
                break;
            case 0x0D:
                position.set("runtime", buf.readUnsignedIntLE());
                break;
            default:
                buf.readUnsignedIntLE();
                break;
            }
        }

        paramCount = buf.readUnsignedByte();
        for (int j = 0; j < paramCount; j++) {
            buf.readUnsignedByte(); // id
            buf.skipBytes(buf.readUnsignedByte()); // value
        }

        positions.add(position);
    }

    return positions;
}

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

License:Apache License

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

    ByteBuf buf = (ByteBuf) msg;

    int index = buf.indexOf(buf.readerIndex(), buf.writerIndex(), (byte) ',');
    String imei = buf.toString(index + 1, 15, StandardCharsets.US_ASCII);
    index = buf.indexOf(index + 1, buf.writerIndex(), (byte) ',');
    String type = buf.toString(index + 1, 3, StandardCharsets.US_ASCII);

    switch (type) {
    case "D00":
        if (photo == null) {
            photo = Unpooled.buffer();//from  w  ww.  j ava  2s . co  m
        }

        index = index + 1 + type.length() + 1;
        int endIndex = buf.indexOf(index, buf.writerIndex(), (byte) ',');
        String file = buf.toString(index, endIndex - index, StandardCharsets.US_ASCII);
        index = endIndex + 1;
        endIndex = buf.indexOf(index, buf.writerIndex(), (byte) ',');
        int total = Integer.parseInt(buf.toString(index, endIndex - index, StandardCharsets.US_ASCII));
        index = endIndex + 1;
        endIndex = buf.indexOf(index, buf.writerIndex(), (byte) ',');
        int current = Integer.parseInt(buf.toString(index, endIndex - index, StandardCharsets.US_ASCII));

        buf.readerIndex(endIndex + 1);
        photo.writeBytes(buf.readSlice(buf.readableBytes() - 1 - 2 - 2));

        if (current == total - 1) {
            Position position = new Position(getProtocolName());
            position.setDeviceId(getDeviceSession(channel, remoteAddress, imei).getDeviceId());

            getLastLocation(position, null);

            position.set(Position.KEY_IMAGE, Context.getMediaManager().writeFile(imei, photo, "jpg"));
            photo.release();
            photo = null;

            return position;
        } else {
            if ((current + 1) % 8 == 0) {
                requestPhotoPacket(channel, remoteAddress, imei, file, current + 1);
            }
            return null;
        }
    case "D03":
        photo = Unpooled.buffer();
        requestPhotoPacket(channel, remoteAddress, imei, "camera_picture.jpg", 0);
        return null;
    case "CCC":
        return decodeBinaryC(channel, remoteAddress, buf);
    case "CCE":
        return decodeBinaryE(channel, remoteAddress, buf);
    default:
        return decodeRegular(channel, remoteAddress, buf);
    }
}

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

License:Apache License

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

    ByteBuf buf = (ByteBuf) msg;

    buf.readUnsignedShortLE(); // length
    int type = buf.readUnsignedShortLE();

    if (type == MSG_SHAKE_HAND && channel != null) {

        ByteBuf response = Unpooled.buffer(13);
        response.writeCharSequence("\r\n*KW", StandardCharsets.US_ASCII);
        response.writeByte(0);/*from ww  w  .  j  a v a  2s .  com*/
        response.writeShortLE(response.capacity());
        response.writeShortLE(MSG_SHAKE_HAND_RESPONSE);
        response.writeByte(1); // status
        response.writeCharSequence("\r\n", StandardCharsets.US_ASCII);

        channel.writeAndFlush(new NetworkMessage(response, remoteAddress));

    } else if (type == MSG_UPLOAD_POSITION || type == MSG_UPLOAD_POSITION_NEW || type == MSG_CONTROL_RESPONSE
            || type == MSG_ALARM) {

        boolean newFormat = false;
        if (type == MSG_UPLOAD_POSITION && buf.readableBytes() == 48
                || type == MSG_ALARM && buf.readableBytes() == 48
                || type == MSG_CONTROL_RESPONSE && buf.readableBytes() == 57) {
            newFormat = true;
        }

        Position position = new Position(getProtocolName());

        if (type == MSG_CONTROL_RESPONSE) {
            buf.readUnsignedIntLE(); // GIS ip
            buf.readUnsignedIntLE(); // GIS port
        }

        position.setValid(BitUtil.check(buf.readUnsignedByte(), 0));

        short alarm = buf.readUnsignedByte();
        switch (alarm) {
        case 1:
            position.set(Position.KEY_ALARM, Position.ALARM_SOS);
            break;
        case 2:
            position.set(Position.KEY_ALARM, Position.ALARM_OVERSPEED);
            break;
        case 3:
            position.set(Position.KEY_ALARM, Position.ALARM_GEOFENCE_EXIT);
            break;
        case 9:
            position.set(Position.KEY_ALARM, Position.ALARM_POWER_OFF);
            break;
        default:
            break;
        }

        if (newFormat) {
            position.setSpeed(UnitsConverter.knotsFromKph(buf.readUnsignedIntLE()));
            position.setCourse(buf.readFloatLE());
        } else {
            position.setSpeed(UnitsConverter.knotsFromKph(buf.readUnsignedByte()));
            position.setCourse(buf.readUnsignedShortLE());
        }
        position.setLongitude(buf.readFloatLE());
        position.setLatitude(buf.readFloatLE());

        if (!newFormat) {
            long timeValue = buf.readUnsignedIntLE();
            DateBuilder dateBuilder = new DateBuilder().setYear((int) BitUtil.from(timeValue, 26))
                    .setMonth((int) BitUtil.between(timeValue, 22, 26))
                    .setDay((int) BitUtil.between(timeValue, 17, 22))
                    .setHour((int) BitUtil.between(timeValue, 12, 17))
                    .setMinute((int) BitUtil.between(timeValue, 6, 12))
                    .setSecond((int) BitUtil.to(timeValue, 6));
            position.setTime(dateBuilder.getDate());
        }

        ByteBuf rawId;
        if (newFormat) {
            rawId = buf.readSlice(12);
        } else {
            rawId = buf.readSlice(11);
        }
        String id = rawId.toString(StandardCharsets.US_ASCII).replaceAll("[^\\p{Print}]", "");
        DeviceSession deviceSession = getDeviceSession(channel, remoteAddress, id);
        if (deviceSession == null) {
            return null;
        }
        position.setDeviceId(deviceSession.getDeviceId());

        if (newFormat) {
            DateFormat dateFormat = new SimpleDateFormat("yy-MM-dd HH:mm:ss");
            position.setTime(dateFormat.parse(buf.readSlice(17).toString(StandardCharsets.US_ASCII)));
            buf.readByte();
        }

        if (!newFormat) {
            position.set(Position.PREFIX_IO + 1, buf.readUnsignedByte());
            position.set(Position.KEY_FUEL_LEVEL, buf.readUnsignedByte());
        } else if (type == MSG_UPLOAD_POSITION_NEW) {
            position.set(Position.PREFIX_TEMP + 1, buf.readShortLE());
            position.set(Position.KEY_ODOMETER, buf.readFloatLE());
        }

        return position;
    }

    return null;
}

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

License:Apache License

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

    ByteBuf buf = (ByteBuf) msg;

    buf.skipBytes(2); // header
    int index = buf.readUnsignedShort();

    String imei = buf.readSlice(15).toString(StandardCharsets.US_ASCII);
    DeviceSession deviceSession = getDeviceSession(channel, remoteAddress, imei);
    if (deviceSession == null) {
        return null;
    }/*ww w.ja v a2s . c om*/

    int type = buf.readUnsignedByte();

    buf.readUnsignedShort(); // data length

    if (type == MSG_TYPE_CONNECT) {

        ByteBuf response = Unpooled.buffer();
        response.writeByte(1);
        response.writeShort(0);
        response.writeInt(0);
        sendResponse(channel, MSG_TYPE_CONNACK, index, imei, response);

    } else if (type == MSG_TYPE_PUBLISH) {

        int typeMajor = buf.readUnsignedByte();
        int typeMinor = buf.readUnsignedByte();

        buf.readUnsignedByte(); // event id

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

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

        int flags = buf.readUnsignedByte();

        position.setValid(!BitUtil.check(flags, 6));

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

        double longitude = ((BitUtil.to(buf.readUnsignedShort(), 1) << 24) + buf.readUnsignedMedium())
                * 0.00001;
        position.setLongitude(BitUtil.check(flags, 5) ? longitude : -longitude);

        double latitude = buf.readUnsignedMedium() * 0.00001;
        position.setLatitude(BitUtil.check(flags, 4) ? latitude : -latitude);

        int speedCourse = buf.readUnsignedMedium();
        position.setSpeed(UnitsConverter.knotsFromMph(BitUtil.from(speedCourse, 10) * 0.1));
        position.setCourse(BitUtil.to(speedCourse, 10));

        ByteBuf response = Unpooled.buffer();
        response.writeByte(typeMajor);
        response.writeByte(typeMinor);
        sendResponse(channel, MSG_TYPE_PUBACK, index, imei, response);

        return position;

    }

    return null;
}

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

License:Apache License

private Position decodeArMessage(Channel channel, SocketAddress remoteAddress, ByteBuf buf) {

    buf.skipBytes(1); // header
    buf.readUnsignedShort(); // length

    int type = buf.readUnsignedByte();

    int tag = buf.readUnsignedByte();

    DeviceSession deviceSession;//  w  ww . j  a  v a  2  s.c  o m
    switch (BitUtil.to(tag, 3)) {
    case 0:
        String imei = ByteBufUtil.hexDump(buf.readSlice(8)).substring(1);
        deviceSession = getDeviceSession(channel, remoteAddress, imei);
        break;
    case 1:
        buf.skipBytes(1);
        String meid = buf.readSlice(14).toString(StandardCharsets.US_ASCII);
        deviceSession = getDeviceSession(channel, remoteAddress, meid);
        break;
    default:
        deviceSession = getDeviceSession(channel, remoteAddress);
        break;
    }

    if (deviceSession == null || type != MSG_AR_LOCATION) {
        return null;
    }

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

    position.set(Position.KEY_EVENT, buf.readUnsignedByte());

    int mask = buf.readInt();

    if (BitUtil.check(mask, 0)) {
        position.set(Position.KEY_INDEX, buf.readUnsignedShort());
    }

    if (BitUtil.check(mask, 1)) {
        int date = buf.readUnsignedByte();
        DateBuilder dateBuilder = new DateBuilder()
                .setDate(BitUtil.between(date, 4, 8) + 2010, BitUtil.to(date, 4), buf.readUnsignedByte())
                .setTime(buf.readUnsignedByte(), buf.readUnsignedByte(), buf.readUnsignedByte());
        position.setTime(dateBuilder.getDate());
    }

    if (BitUtil.check(mask, 2)) {
        buf.skipBytes(5); // device time
    }

    if (BitUtil.check(mask, 3)) {
        position.setLatitude(buf.readUnsignedInt() * 0.000001 - 90);
        position.setLongitude(buf.readUnsignedInt() * 0.000001 - 180.0);
    }

    if (BitUtil.check(mask, 4)) {
        int status = buf.readUnsignedByte();
        position.setValid(BitUtil.between(status, 4, 8) != 0);
        position.set(Position.KEY_SATELLITES, BitUtil.to(status, 4));
        position.set(Position.KEY_HDOP, buf.readUnsignedByte() * 0.1);
    }

    if (BitUtil.check(mask, 5)) {
        position.setSpeed(UnitsConverter.knotsFromKph(buf.readUnsignedByte()));
    }

    if (BitUtil.check(mask, 6)) {
        position.setCourse(buf.readUnsignedShort());
    }

    if (BitUtil.check(mask, 7)) {
        position.setAltitude(buf.readShort());
    }

    if (BitUtil.check(mask, 8)) {
        position.set(Position.KEY_RSSI, buf.readUnsignedByte());
    }

    if (BitUtil.check(mask, 9)) {
        position.set(Position.KEY_POWER, buf.readUnsignedShort() * 0.001);
    }

    if (BitUtil.check(mask, 10)) {
        position.set(Position.KEY_BATTERY, buf.readUnsignedShort() * 0.001);
    }

    if (BitUtil.check(mask, 11)) {
        buf.skipBytes(2); // gpio
    }

    if (BitUtil.check(mask, 12)) {
        position.set(Position.KEY_ODOMETER, buf.readUnsignedInt() * 1000);
    }

    if (BitUtil.check(mask, 13)) {
        buf.skipBytes(6); // software version
    }

    if (BitUtil.check(mask, 14)) {
        buf.skipBytes(5); // hardware version
    }

    if (BitUtil.check(mask, 15)) {
        buf.readUnsignedShort(); // device config
    }

    return position;
}

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

License:Apache License

private Position decodeMgMessage(Channel channel, SocketAddress remoteAddress, ByteBuf buf) {

    buf.readUnsignedByte(); // tag
    int flags = buf.getUnsignedByte(buf.readerIndex());

    DeviceSession deviceSession;//w w w  .  j a v  a2 s  . c  o m
    if (BitUtil.check(flags, 6)) {
        buf.readUnsignedByte(); // flags
        deviceSession = getDeviceSession(channel, remoteAddress);
    } else {
        String imei = ByteBufUtil.hexDump(buf.readSlice(8)).substring(1);
        deviceSession = getDeviceSession(channel, remoteAddress, imei);
    }

    if (deviceSession == null) {
        return null;
    }

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

    buf.skipBytes(8); // imsi

    int date = buf.readUnsignedShort();

    DateBuilder dateBuilder = new DateBuilder()
            .setDate(2010 + BitUtil.from(date, 12), BitUtil.between(date, 8, 12), BitUtil.to(date, 8))
            .setTime(buf.readUnsignedByte(), buf.readUnsignedByte(), 0);

    position.setValid(true);
    position.setLatitude(convertCoordinate(buf.readInt()));
    position.setLongitude(convertCoordinate(buf.readInt()));

    position.setAltitude(UnitsConverter.metersFromFeet(buf.readShort()));
    position.setCourse(buf.readUnsignedShort());
    position.setSpeed(UnitsConverter.knotsFromMph(buf.readUnsignedByte()));

    position.set(Position.KEY_POWER, buf.readUnsignedByte() * 0.1);
    position.set(Position.PREFIX_IO + 1, buf.readUnsignedByte());

    dateBuilder.setSecond(buf.readUnsignedByte());
    position.setTime(dateBuilder.getDate());

    position.set(Position.KEY_RSSI, buf.readUnsignedByte());

    int index = buf.readUnsignedByte();

    position.set(Position.KEY_VERSION_FW, buf.readUnsignedByte());
    position.set(Position.KEY_SATELLITES, buf.readUnsignedByte());
    position.set(Position.KEY_ODOMETER, (long) (buf.readUnsignedInt() * 1609.34));

    if (channel != null && BitUtil.check(flags, 7)) {
        ByteBuf response = Unpooled.buffer();
        response.writeByte(MSG_ACKNOWLEDGEMENT);
        response.writeByte(index);
        response.writeByte(0x00);
        channel.writeAndFlush(new NetworkMessage(response, remoteAddress));
    }

    return position;
}

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

License:Apache License

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

    ByteBuf buf = (ByteBuf) msg;

    buf.readUnsignedByte(); // header

    DeviceSession deviceSession = getDeviceSession(channel, remoteAddress,
            buf.readSlice(7).toString(StandardCharsets.US_ASCII));
    if (deviceSession == null) {
        return null;
    }//from w w  w .  j a  v  a2 s . co m

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

    position.set("eventType", buf.readUnsignedByte());
    position.set("packetVersion", buf.readUnsignedByte());
    position.set(Position.KEY_STATUS, buf.readUnsignedByte());
    position.set(Position.KEY_RSSI, buf.readUnsignedByte());
    position.set(Position.KEY_GPS, buf.readUnsignedByte());

    position.setTime(new DateBuilder()
            .setDateReverse(buf.readUnsignedByte(), buf.readUnsignedByte(), buf.readUnsignedByte())
            .setTime(buf.readUnsignedByte(), buf.readUnsignedByte(), buf.readUnsignedByte()).getDate());

    position.setValid(true);

    double lat = buf.getUnsignedShort(buf.readerIndex()) / 100;
    lat += (buf.readUnsignedShort() % 100 * 10000 + buf.readUnsignedShort()) / 600000.0;
    position.setLatitude(buf.readUnsignedByte() == 'S' ? -lat : lat);

    double lon = buf.getUnsignedMedium(buf.readerIndex()) / 100;
    lon += (buf.readUnsignedMedium() % 100 * 10000 + buf.readUnsignedShort()) / 600000.0;
    position.setLongitude(buf.readUnsignedByte() == 'W' ? -lon : lon);

    position.setSpeed(UnitsConverter.knotsFromKph(buf.readUnsignedByte()));

    position.set(Position.KEY_INPUT, buf.readUnsignedShort());
    position.set(Position.KEY_OUTPUT, buf.readUnsignedByte());

    position.set("analogAlerts", buf.readUnsignedByte());
    position.set("customAlertTypes", buf.readUnsignedShort());

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

    position.set(Position.KEY_ODOMETER, buf.readUnsignedMedium());
    position.set(Position.KEY_RPM, buf.readUnsignedShort());

    if (channel != null) {
        channel.writeAndFlush(
                new NetworkMessage(Unpooled.copiedBuffer("ACK", StandardCharsets.US_ASCII), remoteAddress));
    }

    return position;
}

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

License:Apache License

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

    ByteBuf buf = (ByteBuf) msg;
    int type = buf.readUnsignedShortLE();
    buf.readUnsignedShortLE(); // length

    if (type == MSG_IDENT || type == MSG_IDENT_FULL) {

        buf.readUnsignedIntLE(); // id
        int length = buf.readUnsignedShortLE();
        buf.skipBytes(length);//from  ww w  .  jav  a 2 s. c  om
        length = buf.readUnsignedShortLE();
        buf.skipBytes(length);
        length = buf.readUnsignedShortLE();
        String imei = buf.readSlice(length).toString(StandardCharsets.US_ASCII);
        getDeviceSession(channel, remoteAddress, imei);

    } else if (type == MSG_POINT || type == MSG_ALARM || type == MSG_LOGMSG) {

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

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

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

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

            if (type == MSG_LOGMSG) {
                position.set(Position.KEY_ARCHIVE, true);
                int subtype = buf.readUnsignedShortLE();
                if (subtype == MSG_ALARM) {
                    position.set(Position.KEY_ALARM, Position.ALARM_GENERAL);
                }
                if (buf.readUnsignedShortLE() > buf.readableBytes()) {
                    lastIndex += 1;
                    break; // workaround for device bug
                }
                lastIndex = buf.readUnsignedIntLE();
                position.set(Position.KEY_INDEX, lastIndex);
            } else {
                newIndex = buf.readUnsignedIntLE();
            }

            position.setTime(new Date(buf.readUnsignedIntLE() * 1000));
            position.setLatitude(buf.readIntLE() * 180.0 / 0x7FFFFFFF);
            position.setLongitude(buf.readIntLE() * 180.0 / 0x7FFFFFFF);
            position.setSpeed(buf.readUnsignedIntLE() * 0.01);
            position.setCourse(buf.readUnsignedShortLE() * 0.01);
            position.setAltitude(buf.readUnsignedShortLE() * 0.01);

            int satellites = buf.readUnsignedByte();
            position.setValid(satellites >= 3);
            position.set(Position.KEY_SATELLITES, satellites);

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

            long extraFlags = buf.readLongLE();

            if (BitUtil.check(extraFlags, 0)) {
                int count = buf.readUnsignedShortLE();
                for (int i = 1; i <= count; i++) {
                    position.set(Position.PREFIX_ADC + i, buf.readUnsignedShortLE());
                }
            }

            if (BitUtil.check(extraFlags, 1)) {
                int size = buf.readUnsignedShortLE();
                position.set("can", buf.toString(buf.readerIndex(), size, StandardCharsets.US_ASCII));
                buf.skipBytes(size);
            }

            if (BitUtil.check(extraFlags, 2)) {
                position.set("passenger", ByteBufUtil.hexDump(buf.readSlice(buf.readUnsignedShortLE())));
            }

            if (type == MSG_ALARM) {
                position.set(Position.KEY_ALARM, true);
                byte[] response = { (byte) 0xC9, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 };
                channel.writeAndFlush(new NetworkMessage(Unpooled.wrappedBuffer(response), remoteAddress));
            }

            buf.readUnsignedIntLE(); // crc

            positions.add(position);
        }

        requestArchive(channel);

        return positions;
    }

    return null;
}

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

License:Apache License

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

    ByteBuf buf = (ByteBuf) msg;

    int typeEndIndex = buf.indexOf(buf.readerIndex(), buf.writerIndex(), (byte) ',');
    String type = buf.toString(buf.readerIndex(), typeEndIndex - buf.readerIndex(), StandardCharsets.US_ASCII);

    if (type.startsWith("$PHD")) {

        int dataIndex = buf.indexOf(typeEndIndex + 1, buf.writerIndex(), (byte) ',') + 1;
        buf.readerIndex(dataIndex);/*from ww  w .  ja v  a  2  s  .c om*/

        if (photo != null) {

            photo.writeBytes(buf.readSlice(buf.readableBytes()));

            if (photo.writableBytes() > 0) {

                requestPhotoFragment(channel);

            } else {

                DeviceSession deviceSession = getDeviceSession(channel, remoteAddress);
                String uniqueId = Context.getIdentityManager().getById(deviceSession.getDeviceId())
                        .getUniqueId();

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

                getLastLocation(position, null);

                position.set(Position.KEY_IMAGE, Context.getMediaManager().writeFile(uniqueId, photo, "jpg"));
                photo.release();
                photo = null;

                return position;

            }

        }

    } else {

        if (type.startsWith("$PHO")) {
            int size = Integer.parseInt(type.split("-")[0].substring(4));
            if (size > 0) {
                photo = Unpooled.buffer(size);
                requestPhotoFragment(channel);
            }
        }

        return decodePosition(channel, remoteAddress, buf.toString(StandardCharsets.US_ASCII));

    }

    return null;
}