@Override
  protected Object decode(
      final ChannelHandlerContext ctx, final Channel channel, final ChannelBuffer buffer)
      throws Exception {

    while (buffer.readable()) {

      byte c = buffer.readByte();

      // check if last character read was DLE
      if (foundDLE) {
        foundDLE = false;

        if (c == DleStxEtxConstants.STX && !foundPacket) {

          foundPacket = true;

        } else if (c == DleStxEtxConstants.ETX && foundPacket) {

          ChannelBuffer packetRead = packet;
          resetDecodingState();
          return packetRead;

        } else if (c == DleStxEtxConstants.DLE && foundPacket) {

          // Stuffed DLE found
          packet.writeByte(DleStxEtxConstants.DLE);

        } else {

          if (log.isWarnEnabled()) {
            log.warn(
                "Incomplete packet received: {}",
                StringUtils.toHexString(
                    packet.array(), packet.readerIndex(), packet.readableBytes()));
          }
          resetDecodingState();
        }

      } else {

        if (c == DleStxEtxConstants.DLE) {
          // log.trace("Plain DLE received");
          foundDLE = true;
        } else if (foundPacket) {
          packet.writeByte(c);
        }
      }
    }

    // decoding is not yet complete, we'll need more bytes until we find DLE
    // ETX
    return null;
  }
  public static void main(String[] args) throws IOException {

    Logging.setLoggingDefaults();

    if (args.length > 1) {
      log.info("Searching for {} device with MAC address: {}", args[0], args[1]);
      MoteType type = MoteType.fromString(args[0]);
      if (type == null) {
        log.error("Unknown node type \"{}\" given.", args[0]);
        System.exit(1);
      }

      Map<String, String> telosBReferenceToMACMap = null;
      if (args.length == 3) {
        telosBReferenceToMACMap = readTelosBReferenceToMACMap(args[2]);
        log.info("Using Telos B USB chip ID to MAC mapping: {}", telosBReferenceToMACMap);
      }

      MoteList moteList = MoteListFactory.create(telosBReferenceToMACMap);
      log.info("Found: {}", moteList.getMotePort(type, StringUtils.parseHexOrDecLong(args[1])));

    } else if (args.length == 1) {

      Map<String, String> telosBReferenceToMACMap = null;
      if (args.length == 3) {
        telosBReferenceToMACMap = readTelosBReferenceToMACMap(args[2]);
        log.info("Using Telos B USB chip ID to MAC mapping: {}", telosBReferenceToMACMap);
      }

      log.info(
          "Displaying all connected devices: \n{}",
          MoteListFactory.create(telosBReferenceToMACMap).getMoteList());

    } else {
      log.info(
          "Displaying all connected devices: \n{}", MoteListFactory.create(null).getMoteList());
    }
  }