private void decodeEventData(int event, ChannelBuffer buf) {
   switch (event) {
     case 2:
     case 40:
       buf.readUnsignedByte();
       break;
     case 9:
       buf.readUnsignedMedium();
       break;
     case 31:
     case 32:
       buf.readUnsignedShort();
       break;
     case 38:
       buf.skipBytes(4 * 9);
       break;
     case 113:
       buf.readUnsignedInt();
       buf.readUnsignedByte();
       break;
     case 121:
     case 142:
       buf.readLong();
       break;
     case 130:
       buf.readUnsignedInt(); // incorrect
       break;
     default:
       break;
   }
 }
  @Override
  protected Object decode(Channel channel, SocketAddress remoteAddress, Object msg)
      throws Exception {

    ChannelBuffer buf = (ChannelBuffer) msg;

    buf.skipBytes(4); // system code
    int type = buf.readUnsignedByte();
    long deviceUniqueId = buf.readUnsignedInt();

    if (type != MSG_CLIENT_SERIAL) {
      buf.readUnsignedShort(); // communication control
    }
    byte packetNumber = buf.readByte();

    // Send reply
    sendReply(channel, deviceUniqueId, packetNumber);

    // Parse location
    if (type == MSG_CLIENT_STATUS) {
      Position position = new Position();
      position.setProtocol(getProtocolName());

      // Device identifier
      if (!identify(String.valueOf(deviceUniqueId), channel)) {
        return null;
      }
      position.setDeviceId(getDeviceId());

      buf.readUnsignedByte(); // hardware version
      buf.readUnsignedByte(); // software version
      buf.readUnsignedByte(); // protocol version

      // Status
      position.set(Event.KEY_STATUS, buf.getUnsignedByte(buf.readerIndex()) & 0x0f);

      int operator = (buf.readUnsignedByte() & 0xf0) << 4;
      operator += buf.readUnsignedByte();

      buf.readUnsignedByte(); // reason data
      buf.readUnsignedByte(); // reason
      buf.readUnsignedByte(); // mode
      buf.readUnsignedInt(); // IO

      operator <<= 8;
      operator += buf.readUnsignedByte();
      position.set("operator", operator);

      buf.readUnsignedInt(); // ADC
      buf.readUnsignedMedium(); // Odometer
      buf.skipBytes(6); // multi-purpose data

      buf.readUnsignedShort(); // gps fix
      buf.readUnsignedByte(); // location status
      buf.readUnsignedByte(); // mode 1
      buf.readUnsignedByte(); // mode 2

      position.setValid(buf.readUnsignedByte() >= 3); // satellites

      // Location data
      position.setLongitude(buf.readInt() / Math.PI * 180 / 100000000);
      position.setLatitude(buf.readInt() / Math.PI * 180 / 100000000.0);
      position.setAltitude(buf.readInt() * 0.01);
      position.setSpeed(UnitsConverter.knotsFromMps(buf.readInt() * 0.01));
      position.setCourse(buf.readUnsignedShort() / Math.PI * 180.0 / 1000.0);

      // Time
      Calendar time = Calendar.getInstance(TimeZone.getTimeZone("UTC"));
      time.clear();
      time.set(Calendar.SECOND, buf.readUnsignedByte());
      time.set(Calendar.MINUTE, buf.readUnsignedByte());
      time.set(Calendar.HOUR_OF_DAY, buf.readUnsignedByte());
      time.set(Calendar.DAY_OF_MONTH, buf.readUnsignedByte());
      time.set(Calendar.MONTH, buf.readUnsignedByte() - 1);
      time.set(Calendar.YEAR, buf.readUnsignedShort());
      position.setTime(time.getTime());
      return position;
    }

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

    ChannelBuffer buf = (ChannelBuffer) msg;

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

    if (type == MSG_ON_DEMAND
        || type == MSG_POSITION_UPLOAD
        || type == MSG_POSITION_REUPLOAD
        || type == MSG_ALARM
        || type == MSG_REPLY
        || type == MSG_PERIPHERAL) {

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

      // Device identification
      if (!identify(readSerialNumber(buf), channel)) {
        return null;
      }
      position.setDeviceId(getDeviceId());

      // Date and time
      Calendar time = Calendar.getInstance(TimeZone.getTimeZone("UTC"));
      time.clear();
      time.set(Calendar.YEAR, 2000 + ChannelBufferTools.readHexInteger(buf, 2));
      time.set(Calendar.MONTH, ChannelBufferTools.readHexInteger(buf, 2) - 1);
      time.set(Calendar.DAY_OF_MONTH, ChannelBufferTools.readHexInteger(buf, 2));
      time.set(Calendar.HOUR_OF_DAY, ChannelBufferTools.readHexInteger(buf, 2));
      time.set(Calendar.MINUTE, ChannelBufferTools.readHexInteger(buf, 2));
      time.set(Calendar.SECOND, ChannelBufferTools.readHexInteger(buf, 2));
      position.setTime(time.getTime());

      // Location
      position.setLatitude(ChannelBufferTools.readCoordinate(buf));
      position.setLongitude(ChannelBufferTools.readCoordinate(buf));
      position.setSpeed(UnitsConverter.knotsFromKph(ChannelBufferTools.readHexInteger(buf, 4)));
      position.setCourse(ChannelBufferTools.readHexInteger(buf, 4));

      // Flags
      int flags = buf.readUnsignedByte();
      position.setValid((flags & 0x80) != 0);

      if (type == MSG_ALARM) {

        buf.skipBytes(2);

      } else {

        // Odometer
        position.set(Event.KEY_ODOMETER, buf.readUnsignedMedium());

        // Status
        buf.skipBytes(4);

        // Other
        buf.skipBytes(8);
      }

      // TODO: parse extra data
      return position;
    } else if (type == MSG_LOGIN && channel != null) {

      buf.skipBytes(4); // serial number
      buf.readByte(); // reserved

      ChannelBuffer response = ChannelBuffers.dynamicBuffer();
      response.writeByte(0x29);
      response.writeByte(0x29); // header
      response.writeByte(MSG_CONFIRMATION);
      response.writeShort(5); // size
      response.writeByte(buf.readUnsignedByte());
      response.writeByte(type);
      response.writeByte(0); // reserved
      response.writeByte(Crc.xorChecksum(response.toByteBuffer()));
      response.writeByte(0x0D); // ending
      channel.write(response);
    }

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

    ChannelBuffer buf = (ChannelBuffer) msg;

    buf.readUnsignedByte(); // marker
    int version = buf.readUnsignedByte();

    String imei;
    if ((version & 0x80) != 0) {
      imei = String.valueOf((buf.readUnsignedInt() << (3 * 8)) | buf.readUnsignedMedium());
    } else {
      imei = String.valueOf(imeiFromUnitId(buf.readUnsignedMedium()));
    }

    buf.readUnsignedShort(); // length

    int selector = DEFAULT_SELECTOR;
    if ((version & 0x40) != 0) {
      selector = buf.readUnsignedMedium();
    }

    Position position = new Position();
    position.setProtocol(getProtocolName());
    if (!identify(imei, channel, remoteAddress)) {
      return null;
    }

    position.setDeviceId(getDeviceId());

    int event = buf.readUnsignedByte();
    position.set(Event.KEY_EVENT, event);
    position.set("event-info", buf.readUnsignedByte());

    if ((selector & 0x0008) != 0) {
      position.setValid((buf.readUnsignedByte() & 0x40) != 0);
    } else {
      return null; // no location data
    }

    if ((selector & 0x0004) != 0) {
      buf.skipBytes(4); // snapshot time
    }

    if ((selector & 0x0008) != 0) {
      position.setTime(new Date(buf.readUnsignedInt() * 1000));
      position.setLatitude(buf.readInt() / 1000000.0);
      position.setLongitude(buf.readInt() / 1000000.0);
      position.set(Event.KEY_SATELLITES, buf.readUnsignedByte());
    }

    if ((selector & 0x0010) != 0) {
      position.setSpeed(UnitsConverter.knotsFromKph(buf.readUnsignedByte()));
      buf.readUnsignedByte(); // maximum speed
      position.setCourse(buf.readUnsignedByte() * 2.0);
    }

    if ((selector & 0x0040) != 0) {
      position.set(Event.KEY_INPUT, buf.readUnsignedByte());
    }

    if ((selector & 0x0020) != 0) {
      position.set(Event.PREFIX_ADC + 1, buf.readUnsignedShort());
      position.set(Event.PREFIX_ADC + 2, buf.readUnsignedShort());
      position.set(Event.PREFIX_ADC + 3, buf.readUnsignedShort());
      position.set(Event.PREFIX_ADC + 4, buf.readUnsignedShort());
    }

    if ((selector & 0x8000) != 0) {
      position.set(Event.KEY_POWER, buf.readUnsignedShort() / 1000.0);
      position.set(Event.KEY_BATTERY, buf.readUnsignedShort());
    }

    // Pulse rate 1
    if ((selector & 0x10000) != 0) {
      buf.readUnsignedShort();
      buf.readUnsignedInt();
    }

    // Pulse rate 2
    if ((selector & 0x20000) != 0) {
      buf.readUnsignedShort();
      buf.readUnsignedInt();
    }

    if ((selector & 0x0080) != 0) {
      position.set("trip1", buf.readUnsignedInt());
    }

    if ((selector & 0x0100) != 0) {
      position.set("trip2", buf.readUnsignedInt());
    }

    if ((selector & 0x0040) != 0) {
      position.set(Event.KEY_OUTPUT, buf.readUnsignedByte());
    }

    if ((selector & 0x0200) != 0) {
      position.set(
          Event.KEY_RFID, (((long) buf.readUnsignedShort()) << 32) + buf.readUnsignedInt());
    }

    if ((selector & 0x0400) != 0) {
      buf.readUnsignedByte(); // Keypad
    }

    if ((selector & 0x0800) != 0) {
      position.setAltitude(buf.readShort());
    }

    if ((selector & 0x2000) != 0) {
      buf.readUnsignedShort(); // snapshot counter
    }

    if ((selector & 0x4000) != 0) {
      buf.skipBytes(8); // state flags
    }

    if ((selector & 0x80000) != 0) {
      buf.skipBytes(11); // cell info
    }

    if ((selector & 0x1000) != 0) {
      decodeEventData(event, buf);
    }

    if (Context.getConfig().getBoolean(getProtocolName() + ".can")
        && buf.readable()
        && (selector & 0x1000) != 0
        && event == EVENT_DATA) {

      decodeCanData(buf, position);
    }

    return position;
  }
  private void decodeCanData(ChannelBuffer buf, Position position) {

    buf.readUnsignedMedium(); // packet identifier
    buf.readUnsignedByte(); // version
    int count = buf.readUnsignedByte();
    buf.readUnsignedByte(); // batch count
    buf.readUnsignedShort(); // selector bit
    buf.readUnsignedInt(); // timestamp

    buf.skipBytes(8);

    ArrayList<ChannelBuffer> values = new ArrayList<>(count);

    for (int i = 0; i < count; i++) {
      values.add(buf.readBytes(8));
    }

    for (int i = 0; i < count; i++) {
      ChannelBuffer value = values.get(i);
      switch (buf.readInt()) {
        case 0x20D:
          position.set(Event.KEY_RPM, ChannelBuffers.swapShort(value.readShort()));
          position.set("diesel-temperature", ChannelBuffers.swapShort(value.readShort()) * 0.1);
          position.set("battery-voltage", ChannelBuffers.swapShort(value.readShort()) * 0.01);
          position.set("supply-air-temp-dep1", ChannelBuffers.swapShort(value.readShort()) * 0.1);
          break;
        case 0x30D:
          position.set("active-alarm", ChannelBuffers.hexDump(value));
          break;
        case 0x40C:
          position.set("air-temp-dep1", ChannelBuffers.swapShort(value.readShort()) * 0.1);
          position.set("air-temp-dep2", ChannelBuffers.swapShort(value.readShort()) * 0.1);
          break;
        case 0x40D:
          position.set("cold-unit-state", ChannelBuffers.hexDump(value));
          break;
        case 0x50C:
          position.set("defrost-temp-dep1", ChannelBuffers.swapShort(value.readShort()) * 0.1);
          position.set("defrost-temp-dep2", ChannelBuffers.swapShort(value.readShort()) * 0.1);
          break;
        case 0x50D:
          position.set("condenser-pressure", ChannelBuffers.swapShort(value.readShort()) * 0.1);
          position.set("suction-pressure", ChannelBuffers.swapShort(value.readShort()) * 0.1);
          break;
        case 0x58C:
          value.readByte();
          value.readShort(); // index
          switch (value.readByte()) {
            case 0x01:
              position.set("setpoint-zone1", ChannelBuffers.swapInt(value.readInt()) * 0.1);
              break;
            case 0x02:
              position.set("setpoint-zone2", ChannelBuffers.swapInt(value.readInt()) * 0.1);
              break;
            case 0x05:
              position.set("unit-type", ChannelBuffers.swapInt(value.readInt()));
              break;
            case 0x13:
              position.set("diesel-hours", ChannelBuffers.swapInt(value.readInt()) / 60 / 60);
              break;
            case 0x14:
              position.set("electric-hours", ChannelBuffers.swapInt(value.readInt()) / 60 / 60);
              break;
            case 0x17:
              position.set("service-indicator", ChannelBuffers.swapInt(value.readInt()));
              break;
            case 0x18:
              position.set("software-version", ChannelBuffers.swapInt(value.readInt()) * 0.01);
              break;
            default:
              break;
          }
          break;
        default:
          Log.warning(new UnsupportedOperationException());
          break;
      }
    }
  }
  @Override
  protected Object decode(Channel channel, SocketAddress remoteAddress, Object msg)
      throws Exception {

    ChannelBuffer buf = (ChannelBuffer) msg;

    buf.readUnsignedByte(); // protocol
    buf.readUnsignedShort(); // length
    int index = buf.readUnsignedByte() >> 3;

    if (channel != null) {
      ChannelBuffer response = ChannelBuffers.copiedBuffer("^" + index, Charset.defaultCharset());
      channel.write(response, remoteAddress);
    }

    String id = String.valueOf(buf.readUnsignedInt());
    if (!identify(id, channel, remoteAddress)) {
      return null;
    }

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

    while (buf.readableBytes() > 2) {

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

      int end = buf.readerIndex() + buf.readUnsignedByte();

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

      int flags = buf.readUnsignedByte();
      position.set(Event.KEY_SATELLITES, BitUtil.range(flags, 2));
      position.setValid(BitUtil.range(flags, 0, 2) > 0);

      // Latitude
      double lat = buf.readUnsignedMedium();
      lat = lat * -180 / 16777216 + 90;
      position.setLatitude(lat);

      // Longitude
      double lon = buf.readUnsignedMedium();
      lon = lon * 360 / 16777216 - 180;
      position.setLongitude(lon);

      // Status
      flags = buf.readUnsignedByte();
      position.set(Event.KEY_IGNITION, BitUtil.check(flags, 0));
      position.set(Event.KEY_GSM, BitUtil.range(flags, 2, 3));
      position.setCourse((BitUtil.range(flags, 5) * 45 + 180) % 360);

      // Speed
      int speed = buf.readUnsignedByte();
      if (speed < 250) {
        position.setSpeed(UnitsConverter.knotsFromKph(speed));
      }

      while (buf.readerIndex() < end) {

        int type = buf.readUnsignedByte();
        int length = buf.readUnsignedByte();
        if (length == 255) {
          length += buf.readUnsignedByte();
        }

        switch (type) {
          case 2:
            position.set(Event.KEY_ODOMETER, buf.readUnsignedMedium());
            break;
          case 5:
            position.set(Event.KEY_INPUT, buf.readUnsignedByte());
            break;
          case 6:
            {
              int n = buf.readUnsignedByte() >> 4;
              if (n < 2) {
                position.set(Event.PREFIX_ADC + n, readSwappedFloat(buf));
              } else {
                position.set("di" + (n - 2), readSwappedFloat(buf));
              }
            }
            break;
          case 7:
            {
              int alarm = buf.readUnsignedByte();
              buf.readUnsignedByte();
              if (BitUtil.check(alarm, 5)) {
                position.set(Event.KEY_ALARM, BitUtil.range(alarm, 0, 4));
              }
            }
            break;
          case 8:
            position.set("antihijack", buf.readUnsignedByte());
            break;
          case 9:
            position.set("authorized", ChannelBufferTools.readHexString(buf, 16));
            break;
          case 10:
            position.set("unauthorized", ChannelBufferTools.readHexString(buf, 16));
            break;
          case 24:
            {
              Set<Integer> temps = new LinkedHashSet<>();
              int temp = buf.readUnsignedByte();
              for (int i = 3; i >= 0; i--) {
                int n = (temp >> (2 * i)) & 0x03;
                if (!temps.contains(n)) {
                  temps.add(n);
                }
              }
              for (int n : temps) {
                position.set(Event.PREFIX_TEMP + n, buf.readUnsignedByte());
              }
            }
            break;
          case 28:
            position.set("weight", buf.readUnsignedShort());
            buf.readUnsignedByte();
            break;
          case 90:
            position.set(Event.KEY_POWER, readSwappedFloat(buf));
            break;
          case 101:
            position.set(Event.KEY_OBD_SPEED, buf.readUnsignedByte());
            break;
          case 102:
            position.set(Event.KEY_RPM, buf.readUnsignedByte() * 50);
            break;
          case 107:
            {
              int fuel = buf.readUnsignedShort();
              switch (fuel >> 14) {
                case 1:
                  position.set(Event.KEY_FUEL, (fuel & 0x3fff) * 0.4 + "%");
                  break;
                case 2:
                  position.set(Event.KEY_FUEL, (fuel & 0x3fff) * 0.5 + " l");
                  break;
                case 3:
                  position.set(Event.KEY_FUEL, (fuel & 0x3fff) * -0.5 + " l");
                  break;
              }
            }
            break;
          case 108:
            position.set(Event.KEY_OBD_ODOMETER, buf.readUnsignedInt() * 5);
            break;
          case 150:
            position.set("door", buf.readUnsignedByte());
            break;
          default:
            buf.skipBytes(length);
            break;
        }
      }

      positions.add(position);
    }

    return positions;
  }