Java Code Examples for org.jboss.netty.channel.Channel.write()

The following are Jave code examples for showing how to use write() of the org.jboss.netty.channel.Channel class. You can vote up the examples you like. Your votes will be used in our system to get more good examples.
+ Save this method
Example 1
Project: traccar-service   File: SmokeyProtocolDecoder.java   View Source Code Vote up 6 votes
private static void sendResponse(
        Channel channel, SocketAddress remoteAddress, ChannelBuffer id, int index, int report) {

    if (channel != null) {
        ChannelBuffer response = ChannelBuffers.dynamicBuffer();
        response.writeBytes("SM".getBytes(StandardCharsets.US_ASCII));
        response.writeByte(3); // protocol version
        response.writeByte(MSG_DATE_RECORD_ACK);
        response.writeBytes(id);
        response.writeInt(Seconds.secondsBetween(
                new DateTime(2000, 1, 1, 0, 0, DateTimeZone.UTC), new DateTime(DateTimeZone.UTC)).getSeconds());
        response.writeByte(index);
        response.writeByte(report - 0x200);

        short checksum = (short) 0xF5A0;
        for (int i = 0; i < response.readableBytes(); i += 2) {
            checksum ^= ChannelBuffers.swapShort(response.getShort(i));
        }
        response.writeShort(checksum);

        channel.write(response, remoteAddress);
    }
}
 
Example 2
Project: traccar-service   File: MeiligaoProtocolDecoder.java   View Source Code Vote up 6 votes
private static void sendResponse(
        Channel channel, SocketAddress remoteAddress, ChannelBuffer id, int type, ChannelBuffer msg) {

    if (channel != null) {
        ChannelBuffer buf = ChannelBuffers.buffer(
                2 + 2 + id.readableBytes() + 2 + msg.readableBytes() + 2 + 2);

        buf.writeByte('@');
        buf.writeByte('@');
        buf.writeShort(buf.capacity());
        buf.writeBytes(id);
        buf.writeShort(type);
        buf.writeBytes(msg);
        buf.writeShort(Checksum.crc16(Checksum.CRC16_CCITT_FALSE, buf.toByteBuffer()));
        buf.writeByte('\r');
        buf.writeByte('\n');

        channel.write(buf, remoteAddress);
    }
}
 
Example 3
Project: athena   File: OspfNbrImpl.java   View Source Code Vote up 6 votes
/**
 * Sends a direct Acknowledgment for a particular LSA to the Neighbor.
 *
 * @param ackLsa   LSA instance
 * @param ch       netty channel instance
 * @param sourceIp source IP address
 */
public void directAcknowledge(LsaHeader ackLsa, Channel ch, Ip4Address sourceIp) {
    log.debug("OSPFNbr::directAcknowledge...!!!");

    LsAcknowledge ackContent = new LsAcknowledge();
    // seting OSPF Header
    ackContent.setOspfVer(OspfUtil.OSPF_VERSION);
    ackContent.setOspftype(OspfPacketType.LSAACK.value());
    ackContent.setRouterId(ospfArea.routerId());
    ackContent.setAreaId(ospfArea.areaId());
    ackContent.setAuthType(OspfUtil.NOT_ASSIGNED);
    ackContent.setAuthentication(OspfUtil.NOT_ASSIGNED);
    ackContent.setOspfPacLength(OspfUtil.NOT_ASSIGNED); // to calculate packet length
    ackContent.setChecksum(OspfUtil.NOT_ASSIGNED);
    ackContent.addLinkStateHeader(ackLsa);
    //setting the destination IP
    ackContent.setDestinationIp(sourceIp);
    byte[] messageToWrite = getMessage(ackContent);
    ch.write(messageToWrite);
}
 
Example 4
Project: traccar-service   File: GatorProtocolDecoder.java   View Source Code Vote up 5 votes
private void sendResponse(Channel channel, byte calibration) {
    if (channel != null) {
        ChannelBuffer response = ChannelBuffers.dynamicBuffer();
        response.writeByte(0x24); response.writeByte(0x24); // header
        response.writeByte(MSG_HEARTBEAT); // size
        response.writeShort(5);
        response.writeByte(calibration);
        response.writeByte(0); // main order
        response.writeByte(0); // slave order
        response.writeByte(1); // calibration
        response.writeByte(0x0D);
        channel.write(response);
    }
}
 
Example 5
Project: iTAP-controller   File: AbstractRPCChannelHandler.java   View Source Code Vote up 5 votes
protected void handshakeChallengeResponse(HelloMessage request,
                                          Channel channel) 
                                                  throws AuthException {
    AuthChallengeResponse cr = request.getAuthChallengeResponse();
    if (cr == null) {
        throw new AuthException("No authentication data in " + 
                "handshake message");
    }
    if (cr.isSetResponse()) {
        authenticateResponse(currentChallenge, cr.getResponse());
        currentChallenge = null;
        channelState = ChannelState.AUTHENTICATED;
        handleHello(request, channel);
    } else if (cr.isSetChallenge()) {
        HelloMessage m = new HelloMessage();
        if (getLocalNodeId() != null)
            m.setNodeId(getLocalNodeId());
        AsyncMessageHeader header = new AsyncMessageHeader();
        header.setTransactionId(getTransactionId());
        m.setHeader(header);
        SyncMessage bsm = new SyncMessage(MessageType.HELLO);
        bsm.setHello(m);

        AuthChallengeResponse reply = new AuthChallengeResponse();
        reply.setResponse(generateResponse(cr.getChallenge()));
        m.setAuthChallengeResponse(reply);
        channel.write(bsm);
    } else {
        throw new AuthException("No authentication data in " + 
                "handshake message");
    }
}
 
Example 6
Project: traccar-service   File: Gl200TextProtocolDecoder.java   View Source Code Vote up 5 votes
private Object decodeOther(Channel channel, SocketAddress remoteAddress, String sentence, String type) {
    Parser parser = new Parser(PATTERN, sentence);
    Position position = initPosition(parser, channel, remoteAddress);
    if (position == null) {
        return null;
    }

    int reportType = parser.nextInt(0);
    if (type.equals("NMR")) {
        position.set(Position.KEY_MOTION, reportType == 1);
    } else if (type.equals("SOS")) {
        position.set(Position.KEY_ALARM, Position.ALARM_SOS);
    }

    decodeLocation(position, parser);

    position.set(Position.KEY_ODOMETER, parser.nextDouble(0) * 1000);
    position.set(Position.KEY_BATTERY_LEVEL, parser.nextInt(0));

    position.set(Position.KEY_ODOMETER, parser.nextDouble(0) * 1000);

    decodeDeviceTime(position, parser);

    if (Context.getConfig().getBoolean(getProtocolName() + ".ack") && channel != null) {
        channel.write("+SACK:" + parser.next() + "$", remoteAddress);
    }

    return position;
}
 
Example 7
Project: traccar-service   File: Gl100ProtocolDecoder.java   View Source Code Vote up 5 votes
@Override
protected Object decode(
        Channel channel, SocketAddress remoteAddress, Object msg) throws Exception {

    String sentence = (String) msg;

    if (sentence.contains("AT+GTHBD=") && channel != null) {
        String response = "+RESP:GTHBD,GPRS ACTIVE,";
        response += sentence.substring(9, sentence.lastIndexOf(','));
        response += '\0';
        channel.write(response); // heartbeat response
    }

    Parser parser = new Parser(PATTERN, sentence);
    if (!parser.matches()) {
        return null;
    }

    Position position = new Position();
    position.setProtocol(getProtocolName());

    DeviceSession deviceSession = getDeviceSession(channel, remoteAddress, parser.next());
    if (deviceSession == null) {
        return null;
    }
    position.setDeviceId(deviceSession.getDeviceId());

    position.setValid(parser.nextInt(0) == 0);
    position.setSpeed(parser.nextDouble(0));
    position.setCourse(parser.nextDouble(0));
    position.setAltitude(parser.nextDouble(0));
    position.setLongitude(parser.nextDouble(0));
    position.setLatitude(parser.nextDouble(0));

    position.setTime(parser.nextDateTime());

    return position;
}
 
Example 8
Project: traccar-service   File: EelinkProtocolDecoder.java   View Source Code Vote up 5 votes
private void sendResponse(Channel channel, int type, int index) {
    if (channel != null) {
        ChannelBuffer response = ChannelBuffers.buffer(7);
        response.writeByte(0x67); response.writeByte(0x67); // header
        response.writeByte(type);
        response.writeShort(2); // length
        response.writeShort(index);
        channel.write(response);
    }
}
 
Example 9
Project: traccar-service   File: GpsmtaProtocolDecoder.java   View Source Code Vote up 5 votes
@Override
protected Object decode(
        Channel channel, SocketAddress remoteAddress, Object msg) throws Exception {

    Parser parser = new Parser(PATTERN, (String) msg);
    if (!parser.matches()) {
        return null;
    }

    Position position = new Position();
    position.setProtocol(getProtocolName());

    DeviceSession deviceSession = getDeviceSession(channel, remoteAddress, parser.next());
    if (deviceSession == null) {
        return null;
    }
    position.setDeviceId(deviceSession.getDeviceId());

    String time = parser.next();
    position.setTime(new Date(Long.parseLong(time) * 1000));

    position.setLatitude(parser.nextDouble(0));
    position.setLongitude(parser.nextDouble(0));
    position.setSpeed(parser.nextInt(0));
    position.setCourse(parser.nextInt(0));
    position.setAccuracy(parser.nextInt(0));
    position.setAltitude(parser.nextInt(0));

    position.set(Position.KEY_STATUS, parser.nextInt(0));
    position.set(Position.KEY_BATTERY, parser.nextInt(0));
    position.set(Position.PREFIX_TEMP + 1, parser.nextInt(0));
    position.set(Position.KEY_CHARGE, parser.nextInt(0) == 1);

    if (channel != null) {
        channel.write(time, remoteAddress);
    }

    return position;
}
 
Example 10
Project: traccar-service   File: ProgressProtocolDecoder.java   View Source Code Vote up 5 votes
private void requestArchive(Channel channel) {
    if (lastIndex == 0) {
        lastIndex = newIndex;
    } else if (newIndex > lastIndex) {
        ChannelBuffer request = ChannelBuffers.directBuffer(ByteOrder.LITTLE_ENDIAN, 12);
        request.writeShort(MSG_LOG_SYNC);
        request.writeShort(4);
        request.writeInt((int) lastIndex);
        request.writeInt(0);
        channel.write(request);
    }
}
 
Example 11
Project: athena   File: DefaultIsisInterface.java   View Source Code Vote up 5 votes
/**
 * Sends the partial sequence number PDU.
 *
 * @param lspEntryRequestList list of lsp entry request
 * @param isisPduType         intermediate system PDU type
 * @param channel             netty channel instance
 */
private void sendPsnPduMessage(List<LspEntry> lspEntryRequestList, IsisPduType isisPduType, Channel channel) {
    IsisHeader isisHeader = new LspGenerator().getHeader(isisPduType);
    Psnp psnp = new Psnp(isisHeader);
    psnp.setSourceId(lspKeyP2P(this.systemId));
    TlvHeader tlvHeader = new TlvHeader();
    tlvHeader.setTlvType(TlvType.LSPENTRY.value());
    tlvHeader.setTlvLength(0);
    LspEntriesTlv lspEntriesTlv = new LspEntriesTlv(tlvHeader);
    for (LspEntry lspEntry : lspEntryRequestList) {
        lspEntry.setLspChecksum(0);
        lspEntry.setLspSequenceNumber(0);
        lspEntry.setRemainingTime(0);
        lspEntriesTlv.addLspEntry(lspEntry);
    }
    psnp.addTlv(lspEntriesTlv);
    //write it to channel buffer.
    byte[] psnpBytes = psnp.asBytes();
    psnpBytes = IsisUtil.addLengthAndMarkItInReserved(psnpBytes, IsisConstants.LENGTHPOSITION,
                                                      IsisConstants.LENGTHPOSITION + 1,
                                                      IsisConstants.RESERVEDPOSITION);
    flagValue = false;
    //write to the channel
    if (channel != null && channel.isConnected() && channel.isOpen()) {
        channel.write(IsisUtil.framePacket(psnpBytes, interfaceIndex));
    }
}
 
Example 12
Project: traccar-service   File: T800xProtocolDecoder.java   View Source Code Vote up 5 votes
private void sendResponse(Channel channel, int type, ChannelBuffer imei) {
    if (channel != null) {
        ChannelBuffer response = ChannelBuffers.directBuffer(15);
        response.writeByte(0x23);
        response.writeByte(0x23); // header
        response.writeByte(type);
        response.writeShort(response.capacity()); // length
        response.writeShort(0x0001); // index
        response.writeBytes(imei);
        channel.write(response);
    }
}
 
Example 13
Project: athena   File: DefaultIsisInterface.java   View Source Code Vote up 5 votes
/**
 * Sends LS PDU message to channel.
 *
 * @param lsp     LS PDU message instance
 * @param channel channel instance
 */
private void sendLsp(LsPdu lsp, Channel channel) {
    byte[] lspBytes = lsp.asBytes();
    lspBytes = IsisUtil.addLengthAndMarkItInReserved(lspBytes, IsisConstants.LENGTHPOSITION,
                                                     IsisConstants.LENGTHPOSITION + 1,
                                                     IsisConstants.RESERVEDPOSITION);
    lspBytes = IsisUtil.addChecksum(lspBytes, IsisConstants.CHECKSUMPOSITION,
                                    IsisConstants.CHECKSUMPOSITION + 1);
    //write to the channel
    if (channel != null && channel.isConnected() && channel.isOpen()) {
        channel.write(IsisUtil.framePacket(lspBytes, interfaceIndex));
    }
}
 
Example 14
Project: traccar-service   File: MeitrackProtocolDecoder.java   View Source Code Vote up 4 votes
private List<Position> decodeBinaryMessage(Channel channel, SocketAddress remoteAddress, ChannelBuffer buf) {
    List<Position> positions = new LinkedList<>();

    String flag = buf.toString(2, 1, StandardCharsets.US_ASCII);
    int index = buf.indexOf(buf.readerIndex(), buf.writerIndex(), (byte) ',');

    String imei = buf.toString(index + 1, 15, StandardCharsets.US_ASCII);
    DeviceSession deviceSession = getDeviceSession(channel, remoteAddress, imei);
    if (deviceSession == null) {
        return null;
    }

    buf.skipBytes(index + 1 + 15 + 1 + 3 + 1 + 2 + 2 + 4);

    while (buf.readableBytes() >= 0x34) {

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

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

        position.setLatitude(buf.readInt() * 0.000001);
        position.setLongitude(buf.readInt() * 0.000001);

        position.setTime(new Date((946684800 + buf.readUnsignedInt()) * 1000)); // 946684800 = 2000-01-01

        position.setValid(buf.readUnsignedByte() == 1);

        position.set(Position.KEY_SATELLITES, buf.readUnsignedByte());
        int rssi = buf.readUnsignedByte();

        position.setSpeed(UnitsConverter.knotsFromKph(buf.readUnsignedShort()));
        position.setCourse(buf.readUnsignedShort());

        position.set(Position.KEY_HDOP, buf.readUnsignedShort() * 0.1);

        position.setAltitude(buf.readUnsignedShort());

        position.set(Position.KEY_ODOMETER, buf.readUnsignedInt());
        position.set("runtime", buf.readUnsignedInt());

        position.setNetwork(new Network(CellTower.from(
                buf.readUnsignedShort(), buf.readUnsignedShort(),
                buf.readUnsignedShort(), buf.readUnsignedShort(),
                rssi)));

        position.set(Position.KEY_STATUS, buf.readUnsignedShort());

        position.set(Position.PREFIX_ADC + 1, buf.readUnsignedShort());
        position.set(Position.KEY_BATTERY, buf.readUnsignedShort() * 0.01);
        position.set(Position.KEY_POWER, buf.readUnsignedShort());

        buf.readUnsignedInt(); // geo-fence

        positions.add(position);
    }

    if (channel != null) {
        StringBuilder command = new StringBuilder("@@");
        command.append(flag).append(27 + positions.size() / 10).append(",");
        command.append(imei).append(",CCC,").append(positions.size()).append("*");
        int checksum = 0;
        for (int i = 0; i < command.length(); i += 1) {
            checksum += command.charAt(i);
        }
        command.append(String.format("%02x", checksum & 0xff).toUpperCase());
        command.append("\r\n");
        channel.write(command.toString()); // delete processed data
    }

    return positions;
}
 
Example 15
Project: iTAP-controller   File: RPCChannelHandler.java   View Source Code Vote up 4 votes
@Override
@LogMessageDoc(level="ERROR",
          message="[{id}->{id}] Attempted connection from unrecognized " +
                  "floodlight node {id}; disconnecting",
          explanation="A unknown node connected.  This can happen " +
                  "transiently if new nodes join the cluster.",
          recommendation="If the problem persists, verify your cluster" +
            "configuration and that you don't have unauthorized agents " +
            "in your network.")
protected void handleHello(HelloMessage hello, Channel channel) {
    if (!hello.isSetNodeId()) {
        // this is a client connection.  Don't set this up as a node
        // connection
        isClientConnection = true;
        return;
    }
    remoteNode = syncManager.getClusterConfig().getNode(hello.getNodeId());
    if (remoteNode == null) {
        logger.error("[{}->{}] Attempted connection from unrecognized " +
                     "floodlight node {}; disconnecting",
                     new Object[]{getLocalNodeIdString(),
                                  getRemoteNodeIdString(),
                                  hello.getNodeId()});
        channel.close();
        return;
    }
    rpcService.nodeConnected(remoteNode.getNodeId(), channel);

    FullSyncRequestMessage srm = new FullSyncRequestMessage();
    AsyncMessageHeader header = new AsyncMessageHeader();
    header.setTransactionId(getTransactionId());
    srm.setHeader(header);
    SyncMessage bsm = new SyncMessage(MessageType.FULL_SYNC_REQUEST);
    channel.write(bsm);

    // XXX - TODO - if last connection was longer ago than the tombstone
    // timeout, then we need to do a complete flush and reload of our
    // state.  This is complex though since this applies across entire
    // partitions and not just single nodes.  We'd need to identify the
    // partition and nuke the smaller half (or lower priority in the case
    // of an even split).  Downstream listeners would need to be able to
    // handle a state nuke as well. A simple way to nuke would be to ensure
    // floodlight is restarted in the smaller partition.
}
 
Example 16
Project: traccar-service   File: WatchProtocolDecoder.java   View Source Code Vote up 4 votes
private void sendResponse(Channel channel, String manufacturer, String id, String content) {
    if (channel != null) {
        channel.write(String.format(
                "[%s*%s*%04x*%s]", manufacturer, id, content.length(), content));
    }
}
 
Example 17
Project: iTAP-controller   File: RPCChannelHandler.java   View Source Code Vote up 4 votes
@Override
protected void handleSyncValue(SyncValueMessage request,
                               Channel channel) {
    if (request.isSetResponseTo())
        rpcService.messageAcked(MessageType.SYNC_REQUEST,
                                getRemoteNodeId());
    try {
        if (logger.isTraceEnabled()) {
            logger.trace("[{}->{}] Got syncvalue {}",
                         new Object[]{getLocalNodeIdString(),
                                      getRemoteNodeIdString(),
                                      request});
        }

        Scope scope = TProtocolUtil.getScope(request.getStore().getScope());
        for (KeyedValues kv : request.getValues()) {
            Iterable<VersionedValue> tvvi = kv.getValues();
            Iterable<Versioned<byte[]>> vs = new TVersionedValueIterable(tvvi);
            syncManager.writeSyncValue(request.getStore().getStoreName(),
                                       scope,
                                       request.getStore().isPersist(),
                                       kv.getKey(), vs);
        }

        SyncValueResponseMessage m = new SyncValueResponseMessage();
        m.setCount(request.getValuesSize());
        AsyncMessageHeader header = new AsyncMessageHeader();
        header.setTransactionId(request.getHeader().getTransactionId());
        m.setHeader(header);
        SyncMessage bsm =
                new SyncMessage(MessageType.SYNC_VALUE_RESPONSE);
        bsm.setSyncValueResponse(m);

        updateCounter(SyncManager.counterReceivedValues,
                      request.getValuesSize());
        channel.write(bsm);
    } catch (Exception e) {
        channel.write(getError(request.getHeader().getTransactionId(), e,
                               MessageType.SYNC_VALUE));
    }
}
 
Example 18
Project: traccar-service   File: BoxProtocolDecoder.java   View Source Code Vote up 4 votes
@Override
protected Object decode(
        Channel channel, SocketAddress remoteAddress, Object msg) throws Exception {

    String sentence = (String) msg;

    if (sentence.startsWith("H,")) {

        int index = sentence.indexOf(',', 2) + 1;
        String id = sentence.substring(index, sentence.indexOf(',', index));
        getDeviceSession(channel, remoteAddress, id);

    } else if (sentence.startsWith("E,")) {

        if (channel != null) {
            channel.write("A," + sentence.substring(2) + "\r");
        }

    } else if (sentence.startsWith("L,")) {

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

        Parser parser = new Parser(PATTERN, sentence);
        if (!parser.matches()) {
            return null;
        }

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

        position.setTime(parser.nextDateTime());

        position.setLatitude(parser.nextDouble(0));
        position.setLongitude(parser.nextDouble(0));
        position.setSpeed(UnitsConverter.knotsFromKph(parser.nextDouble(0)));
        position.setCourse(parser.nextDouble(0));

        position.set(Position.KEY_ODOMETER_TRIP, parser.nextDouble(0) * 1000);
        position.set(Position.KEY_EVENT, parser.next());

        int status = parser.nextInt(0);
        position.setValid((status & 0x04) == 0);
        position.set(Position.KEY_STATUS, status);

        return position;
    }

    return null;
}
 
Example 19
Project: hadoop   File: ShuffleHandler.java   View Source Code Vote up 4 votes
protected ChannelFuture sendMapOutput(ChannelHandlerContext ctx, Channel ch,
    String user, String mapId, int reduce, MapOutputInfo mapOutputInfo)
    throws IOException {
  final IndexRecord info = mapOutputInfo.indexRecord;
  final ShuffleHeader header =
    new ShuffleHeader(mapId, info.partLength, info.rawLength, reduce);
  final DataOutputBuffer dob = new DataOutputBuffer();
  header.write(dob);
  ch.write(wrappedBuffer(dob.getData(), 0, dob.getLength()));
  final File spillfile =
      new File(mapOutputInfo.mapOutputFileName.toString());
  RandomAccessFile spill;
  try {
    spill = SecureIOUtils.openForRandomRead(spillfile, "r", user, null);
  } catch (FileNotFoundException e) {
    LOG.info(spillfile + " not found");
    return null;
  }
  ChannelFuture writeFuture;
  if (ch.getPipeline().get(SslHandler.class) == null) {
    final FadvisedFileRegion partition = new FadvisedFileRegion(spill,
        info.startOffset, info.partLength, manageOsCache, readaheadLength,
        readaheadPool, spillfile.getAbsolutePath(), 
        shuffleBufferSize, shuffleTransferToAllowed);
    writeFuture = ch.write(partition);
    writeFuture.addListener(new ChannelFutureListener() {
        // TODO error handling; distinguish IO/connection failures,
        //      attribute to appropriate spill output
      @Override
      public void operationComplete(ChannelFuture future) {
        if (future.isSuccess()) {
          partition.transferSuccessful();
        }
        partition.releaseExternalResources();
      }
    });
  } else {
    // HTTPS cannot be done with zero copy.
    final FadvisedChunkedFile chunk = new FadvisedChunkedFile(spill,
        info.startOffset, info.partLength, sslFileBufferSize,
        manageOsCache, readaheadLength, readaheadPool,
        spillfile.getAbsolutePath());
    writeFuture = ch.write(chunk);
  }
  metrics.shuffleConnections.incr();
  metrics.shuffleOutputBytes.incr(info.partLength); // optimistic
  return writeFuture;
}
 
Example 20
Project: traccar-service   File: OigoProtocolDecoder.java   View Source Code Vote up 4 votes
private Position decodeMgMessage(Channel channel, SocketAddress remoteAddress, ChannelBuffer buf) {

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

        DeviceSession deviceSession;
        if (BitUtil.check(flags, 6)) {
            buf.readUnsignedByte(); // flags
            deviceSession = getDeviceSession(channel, remoteAddress);
        } else {
            String imei = ChannelBuffers.hexDump(buf.readBytes(8)).substring(1);
            deviceSession = getDeviceSession(channel, remoteAddress, imei);
        }

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

        Position position = new Position();
        position.setProtocol(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)) {
            ChannelBuffer response = ChannelBuffers.dynamicBuffer();
            response.writeByte(MSG_ACKNOWLEDGEMENT);
            response.writeByte(index);
            response.writeByte(0x00);
            channel.write(response, remoteAddress);
        }

        return position;
    }