示例#1
0
  /** Initialize logger */
  private void initLogger(Properties properties) throws IOException {

    loggerEnabled = Boolean.valueOf(properties.getProperty("logger.enable"));

    if (loggerEnabled) {

      String fileName = properties.getProperty("logger.file");
      if (fileName != null) {

        FileHandler file = new FileHandler(fileName, true);

        // Simple formatter
        file.setFormatter(
            new Formatter() {
              private final String LINE_SEPARATOR = System.getProperty("line.separator", "\n");

              private final DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");

              public String format(LogRecord record) {
                String line = dateFormat.format(new Date(record.getMillis()));
                line += " " + record.getLevel().getName() + ": ";
                line += formatMessage(record);
                line += LINE_SEPARATOR;
                return line;
              }
            });

        // NOTE: Console logger level will remain INFO
        Log.getLogger().setLevel(Level.ALL);
        Log.getLogger().addHandler(file);
      }
    }
  }
  @Override
  protected Object decode(Channel channel, SocketAddress remoteAddress, Object msg)
      throws Exception {

    ChannelBuffer buf = (ChannelBuffer) msg;

    prefix = buf.toString(buf.readerIndex(), 4, CHARSET);
    buf.skipBytes(prefix.length()); // prefix @NTC by default
    serverId = buf.readUnsignedInt();
    deviceUniqueId = buf.readUnsignedInt();
    int length = buf.readUnsignedShort();
    buf.skipBytes(2); // header and data XOR checksum

    if (length == 0) {
      return null; // keep alive message
    }

    String type = buf.toString(buf.readerIndex(), 3, CHARSET);
    buf.skipBytes(type.length());

    switch (type) {
      case "*>T":
        return processSingle(channel, buf);
      case "*>A":
        return processArray(channel, buf);
      case "*>S":
        return processHandshake(channel, buf);
      default:
        Log.warning(new UnsupportedOperationException(type));
        break;
    }

    return null;
  }
示例#3
0
  public QueryBuilder setObject(Object object) throws SQLException {

    Method[] methods = object.getClass().getMethods();

    for (Method method : methods) {
      if (method.getName().startsWith("get") && method.getParameterTypes().length == 0) {
        String name = method.getName().substring(3);
        try {
          if (method.getReturnType().equals(boolean.class)) {
            setBoolean(name, (Boolean) method.invoke(object));
          } else if (method.getReturnType().equals(int.class)) {
            setInteger(name, (Integer) method.invoke(object));
          } else if (method.getReturnType().equals(long.class)) {
            setLong(name, (Long) method.invoke(object));
          } else if (method.getReturnType().equals(double.class)) {
            setDouble(name, (Double) method.invoke(object));
          } else if (method.getReturnType().equals(String.class)) {
            setString(name, (String) method.invoke(object));
          } else if (method.getReturnType().equals(Date.class)) {
            setDate(name, (Date) method.invoke(object));
          } else if (method.getReturnType().equals(Map.class)) {
            if (Context.getConfig().getBoolean("database.xml")) {
              setString(name, MiscFormatter.toXmlString((Map) method.invoke(object)));
            } else {
              setString(name, MiscFormatter.toJsonString((Map) method.invoke(object)));
            }
          }
        } catch (IllegalAccessException | InvocationTargetException error) {
          Log.warning(error);
        }
      }
    }

    return this;
  }
 public final void updateGeofence(Geofence geofence) {
   geofencesLock.writeLock().lock();
   try {
     geofences.put(geofence.getId(), geofence);
   } finally {
     geofencesLock.writeLock().unlock();
   }
   try {
     dataManager.updateGeofence(geofence);
   } catch (SQLException error) {
     Log.warning(error);
   }
 }
 public final void refreshUserGeofences() {
   if (dataManager != null) {
     try {
       userGeofencesLock.writeLock().lock();
       try {
         userGeofences.clear();
         for (GeofencePermission geofencePermission : dataManager.getGeofencePermissions()) {
           getUserGeofences(geofencePermission.getUserId())
               .add(geofencePermission.getGeofenceId());
         }
       } finally {
         userGeofencesLock.writeLock().unlock();
       }
     } catch (SQLException error) {
       Log.warning(error);
     }
   }
 }
 public final void refreshGeofences() {
   if (dataManager != null) {
     try {
       geofencesLock.writeLock().lock();
       try {
         geofences.clear();
         for (Geofence geofence : dataManager.getGeofences()) {
           geofences.put(geofence.getId(), geofence);
         }
       } finally {
         geofencesLock.writeLock().unlock();
       }
     } catch (SQLException error) {
       Log.warning(error);
     }
   }
   refreshUserGeofences();
   refresh();
 }
  @Override
  public void messageReceived(ChannelHandlerContext ctx, MessageEvent e) {

    if (e.getMessage() instanceof ChannelBuffer) {
      ChannelBuffer buf = (ChannelBuffer) e.getMessage();

      for (TrackerServer server : serverList) {
        try {
          if (!server.getProtocol().equals("detector")) {
            checkPipeline(server.getProtocol(), server.getPipelineFactory().getPipeline(), buf);
          }
        } catch (Exception error) {
          if (showFailed) {
            Log.info("Protocol " + server.getProtocol() + " error");
          }
        }
      }
    }
  }
  @Override
  protected Collection<Event> analyzePosition(Position position) {

    Device device = Context.getIdentityManager().getDeviceById(position.getDeviceId());
    if (device == null) {
      return null;
    }
    if (!Context.getDeviceManager().isLatestPosition(position) || !position.getValid()) {
      return null;
    }

    Collection<Event> result = null;
    double speed = position.getSpeed();
    double oldSpeed = 0;
    Position lastPosition = Context.getDeviceManager().getLastPosition(position.getDeviceId());
    if (lastPosition != null) {
      oldSpeed = lastPosition.getSpeed();
    }
    try {
      if (speed > SPEED_THRESHOLD && oldSpeed <= SPEED_THRESHOLD) {
        result = new ArrayList<>();
        result.add(new Event(Event.TYPE_DEVICE_MOVING, position.getDeviceId(), position.getId()));
      } else if (speed <= SPEED_THRESHOLD && oldSpeed > SPEED_THRESHOLD) {
        result = new ArrayList<>();
        result.add(new Event(Event.TYPE_DEVICE_STOPPED, position.getDeviceId(), position.getId()));
      }

      if (result != null && !result.isEmpty()) {
        for (Event event : result) {
          if (!Context.getDataManager()
              .getLastEvents(position.getDeviceId(), event.getType(), suppressRepeated)
              .isEmpty()) {
            event = null;
          }
        }
      }
    } catch (SQLException error) {
      Log.warning(error);
    }
    return result;
  }
示例#9
0
  public static void main(String[] args) throws Exception {

    // TODO: Temporary formatting workaround
    Locale.setDefault(Locale.ENGLISH);

    final Server service = new Server();
    service.init(args);

    Log.info("starting server...");
    service.start();

    // Shutdown server properly
    Runtime.getRuntime()
        .addShutdownHook(
            new Thread() {
              @Override
              public void run() {
                Log.info("shutting down server...");
                service.stop();
              }
            });
  }
示例#10
0
  /** Initialize logger */
  private void initLogger(Properties properties) throws IOException {

    loggerEnabled = Boolean.valueOf(properties.getProperty("logger.enable"));

    if (loggerEnabled) {

      String fileName = properties.getProperty("logger.file");
      if (fileName != null) {

        FileHandler file = new FileHandler(fileName, true);

        // Simple formatter
        file.setFormatter(
            new Formatter() {
              private final String LINE_SEPARATOR = System.getProperty("line.separator", "\n");

              private final DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

              @Override
              public String format(LogRecord record) {
                StringBuffer line = new StringBuffer();
                dateFormat.format(new Date(record.getMillis()), line, new FieldPosition(0));
                line.append(" ");
                line.append(record.getSourceClassName());
                line.append(".");
                line.append(record.getSourceMethodName());
                line.append(" ");
                line.append(record.getLevel().getName());
                line.append(": ");
                line.append(formatMessage(record));
                line.append(LINE_SEPARATOR);
                return line.toString();
              }
            });

        Log.getLogger().addHandler(file);
      }
    }
  }
示例#11
0
  @Override
  protected Object decode(ChannelHandlerContext ctx, Channel channel, Object msg) throws Exception {

    String sentence = (String) msg;

    // Heartbeat
    if (sentence.startsWith("$ECHK") && channel != null) {
      channel.write(sentence + "\r\n");
      return null;
    }

    // Parse message
    Matcher parser = pattern.matcher(sentence);
    if (!parser.matches()) {
      return null;
    }

    // Create new position
    Position position = new Position();
    ExtendedInfoFormatter extendedInfo = new ExtendedInfoFormatter("laipac");
    Integer index = 1;

    // Identification
    String id = parser.group(index++);
    try {
      position.setDeviceId(getDataManager().getDeviceByImei(id).getId());
    } catch (Exception error) {
      Log.warning("Unknown device - " + id);
    }

    // Time
    Calendar time = Calendar.getInstance(TimeZone.getTimeZone("UTC"));
    time.clear();
    time.set(Calendar.HOUR_OF_DAY, Integer.valueOf(parser.group(index++)));
    time.set(Calendar.MINUTE, Integer.valueOf(parser.group(index++)));
    time.set(Calendar.SECOND, Integer.valueOf(parser.group(index++)));

    // Validity
    String status = parser.group(index++);
    position.setValid(status.compareToIgnoreCase("A") == 0);

    // Latitude
    Double latitude = Double.valueOf(parser.group(index++));
    latitude += Double.valueOf(parser.group(index++)) / 60;
    if (parser.group(index++).compareTo("S") == 0) latitude = -latitude;
    position.setLatitude(latitude);

    // Longitude
    Double longitude = Double.valueOf(parser.group(index++));
    longitude += Double.valueOf(parser.group(index++)) / 60;
    if (parser.group(index++).compareTo("W") == 0) longitude = -longitude;
    position.setLongitude(longitude);

    // Speed
    position.setSpeed(Double.valueOf(parser.group(index++)));

    // Course
    position.setCourse(Double.valueOf(parser.group(index++)));

    // Date
    time.set(Calendar.DAY_OF_MONTH, Integer.valueOf(parser.group(index++)));
    time.set(Calendar.MONTH, Integer.valueOf(parser.group(index++)) - 1);
    time.set(Calendar.YEAR, 2000 + Integer.valueOf(parser.group(index++)));
    position.setTime(time.getTime());

    // Altitude
    position.setAltitude(0.0);

    // Response
    String type = parser.group(index++);
    String checksum = parser.group(index++);
    String response = null;

    if (type.equals("0") && Character.isLowerCase(status.charAt(0))) {
      response = "$EAVACK,0," + checksum;
      response += Crc.nmeaChecksum(response);
    } else if (type.equals("S") || type.equals("T")) {
      response = "$AVCFG,00000000,t*21";
    } else if (type.equals("3")) {
      response = "$AVCFG,00000000,d*31";
    } else if (type.equals("X") || type.equals("4")) {
      response = "$AVCFG,00000000,x*2D";
    }

    if (response != null && channel != null) {
      channel.write(response + "\r\n");
    }

    position.setExtendedInfo(extendedInfo.toString());
    return position;
  }
  @Override
  protected Object decode(ChannelHandlerContext ctx, Channel channel, Object msg) throws Exception {

    String sentence = (String) msg;

    // Parse message
    Matcher parser = pattern.matcher(sentence);
    if (!parser.matches()) {
      return null;
    }

    // Create new position
    Position position = new Position();
    StringBuilder extendedInfo = new StringBuilder("<protocol>intellitrac</protocol>");
    Integer index = 1;

    // Detect device
    String id = parser.group(index++);
    try {
      position.setDeviceId(getDataManager().getDeviceByImei(id).getId());
    } catch (Exception error) {
      Log.warning("Unknown device - " + id);
      return null;
    }

    // Date and time
    Calendar time = Calendar.getInstance(TimeZone.getTimeZone("UTC"));
    time.clear();
    time.set(Calendar.YEAR, Integer.valueOf(parser.group(index++)));
    time.set(Calendar.MONTH, Integer.valueOf(parser.group(index++)) - 1);
    time.set(Calendar.DAY_OF_MONTH, Integer.valueOf(parser.group(index++)));
    time.set(Calendar.HOUR, Integer.valueOf(parser.group(index++)));
    time.set(Calendar.MINUTE, Integer.valueOf(parser.group(index++)));
    time.set(Calendar.SECOND, Integer.valueOf(parser.group(index++)));
    position.setTime(time.getTime());

    // Location data
    position.setLongitude(Double.valueOf(parser.group(index++)));
    position.setLatitude(Double.valueOf(parser.group(index++)));
    position.setSpeed(Double.valueOf(parser.group(index++)));
    position.setCourse(Double.valueOf(parser.group(index++)));
    position.setAltitude(Double.valueOf(parser.group(index++)));

    // Satellites
    int satellites = Integer.valueOf(parser.group(index++));
    position.setValid(satellites >= 3);
    extendedInfo.append("<satellites>");
    extendedInfo.append(satellites);
    extendedInfo.append("</satellites>");

    // Report identifier
    position.setId(Long.valueOf(parser.group(index++)));

    // Input
    extendedInfo.append("<input>");
    extendedInfo.append(parser.group(index++));
    extendedInfo.append("</input>");

    // Output
    extendedInfo.append("<output>");
    extendedInfo.append(parser.group(index++));
    extendedInfo.append("</output>");

    // ADC1
    String adc1 = parser.group(index++);
    if (adc1 != null) {
      extendedInfo.append("<adc1>").append(adc1).append("</adc1>");
    }

    // ADC2
    String adc2 = parser.group(index++);
    if (adc2 != null) {
      extendedInfo.append("<adc2>").append(adc2).append("</adc2>");
    }

    position.setExtendedInfo(extendedInfo.toString());
    return position;
  }
  @Override
  protected Object decode(ChannelHandlerContext ctx, Channel channel, Object msg) throws Exception {

    String sentence = (String) msg;

    // Process login
    if (sentence.startsWith("$FRLIN,")) {
      int beginIndex = sentence.indexOf(',', 7);
      if (beginIndex != -1) {
        beginIndex += 1;
        int endIndex = sentence.indexOf(',', beginIndex);
        if (endIndex != -1) {
          String imei = sentence.substring(beginIndex, endIndex);
          try {
            deviceId = getDataManager().getDeviceByImei(imei).getId();
            send(channel, "$FRSES," + channel.getId());
          } catch (Exception error) {
            Log.warning("Unknown device - " + imei);
            send(channel, "$FRERR,AuthError,Unknown device");
          }
        } else {
          send(channel, "$FRERR,AuthError,Parse error");
        }
      } else {
        send(channel, "$FRERR,AuthError,Parse error");
      }
    }

    // Process data
    else if (sentence.contains("$GPRMC") && deviceId != null) {

      // Parse message
      Matcher parser = pattern.matcher(sentence);
      if (!parser.matches()) {
        return null;
      }

      // Create new position
      Position position = new Position();
      position.setDeviceId(deviceId);

      Integer index = 1;

      // Time
      Calendar time = Calendar.getInstance(TimeZone.getTimeZone("UTC"));
      time.clear();
      time.set(Calendar.HOUR, Integer.valueOf(parser.group(index++)));
      time.set(Calendar.MINUTE, Integer.valueOf(parser.group(index++)));
      time.set(Calendar.SECOND, Integer.valueOf(parser.group(index++)));
      index += 1; // Skip milliseconds

      // Validity
      position.setValid(parser.group(index++).compareTo("A") == 0 ? true : false);

      // Latitude
      Double latitude = Double.valueOf(parser.group(index++));
      latitude += Double.valueOf(parser.group(index++)) / 60;
      if (parser.group(index++).compareTo("S") == 0) latitude = -latitude;
      position.setLatitude(latitude);

      // Longitude
      Double lonlitude = Double.valueOf(parser.group(index++));
      lonlitude += Double.valueOf(parser.group(index++)) / 60;
      if (parser.group(index++).compareTo("W") == 0) lonlitude = -lonlitude;
      position.setLongitude(lonlitude);

      // Speed
      String speed = parser.group(index++);
      if (speed != null) {
        position.setSpeed(Double.valueOf(speed));
      } else {
        position.setSpeed(0.0);
      }

      // Course
      String course = parser.group(index++);
      if (course != null) {
        position.setCourse(Double.valueOf(course));
      } else {
        position.setCourse(0.0);
      }

      // Date
      time.set(Calendar.DAY_OF_MONTH, Integer.valueOf(parser.group(index++)));
      time.set(Calendar.MONTH, Integer.valueOf(parser.group(index++)) - 1);
      time.set(Calendar.YEAR, 2000 + Integer.valueOf(parser.group(index++)));
      position.setTime(time.getTime());

      // Altitude
      position.setAltitude(0.0);

      return position;
    }

    return null;
  }
示例#14
0
  public void checkPipeline(String protocol, ChannelPipeline pipeline, ChannelBuffer buf)
      throws Exception {
    Object tmp = buf.duplicate();

    // Frame decoder
    FrameDecoder frameDecoder = (FrameDecoder) pipeline.get("frameDecoder");
    if (frameDecoder != null) {
      try {
        Method method =
            frameDecoder
                .getClass()
                .getDeclaredMethod(
                    "decode", ChannelHandlerContext.class, Channel.class, ChannelBuffer.class);
        method.setAccessible(true);
        tmp = method.invoke(frameDecoder, null, null, tmp);
      } catch (NoSuchMethodException error) {
        Method method =
            frameDecoder
                .getClass()
                .getSuperclass()
                .getDeclaredMethod(
                    "decode", ChannelHandlerContext.class, Channel.class, ChannelBuffer.class);
        method.setAccessible(true);
        tmp = method.invoke(frameDecoder, null, null, tmp);
      }
    }

    // String decoder
    if (pipeline.get("stringDecoder") != null) {
      StringDecoder stringDecoder = new StringDecoder();
      if (tmp != null) {
        try {
          Method method =
              stringDecoder
                  .getClass()
                  .getDeclaredMethod(
                      "decode", ChannelHandlerContext.class, Channel.class, Object.class);
          method.setAccessible(true);
          tmp = method.invoke(stringDecoder, null, null, tmp);
        } catch (NoSuchMethodException error) {
          Method method =
              stringDecoder
                  .getClass()
                  .getSuperclass()
                  .getDeclaredMethod(
                      "decode", ChannelHandlerContext.class, Channel.class, Object.class);
          method.setAccessible(true);
          tmp = method.invoke(stringDecoder, null, null, tmp);
        }
      }
    }

    // Protocol decoder
    BaseProtocolDecoder protocolDecoder = (BaseProtocolDecoder) pipeline.get("objectDecoder");
    if (tmp != null) {
      try {
        Method method =
            protocolDecoder
                .getClass()
                .getDeclaredMethod(
                    "decode",
                    ChannelHandlerContext.class,
                    Channel.class,
                    SocketAddress.class,
                    Object.class);
        method.setAccessible(true);
        tmp = method.invoke(protocolDecoder, null, null, null, tmp);
      } catch (NoSuchMethodException error) {
        Method method =
            protocolDecoder
                .getClass()
                .getSuperclass()
                .getDeclaredMethod(
                    "decode",
                    ChannelHandlerContext.class,
                    Channel.class,
                    SocketAddress.class,
                    Object.class);
        method.setAccessible(true);
        tmp = method.invoke(protocolDecoder, null, null, null, tmp);
      }
    }

    if (tmp != null) {
      Log.info("Protocol " + protocol + " possible match");
    } else if (showFailed) {
      Log.info("Protocol " + protocol + " no match");
    }
  }
  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;
      }
    }
  }
示例#16
0
  @Override
  protected Object decode(ChannelHandlerContext ctx, Channel channel, Object msg) throws Exception {

    // Parse message
    Matcher parser = pattern.matcher((String) msg);
    if (!parser.matches()) {
      return null;
    }

    // Create new position
    Position position = new Position();
    ExtendedInfoFormatter extendedInfo = new ExtendedInfoFormatter("wondex");
    int index = 1;

    // Device identifier
    String id = parser.group(index++);
    try {
      position.setDeviceId(getDataManager().getDeviceByImei(id).getId());
    } catch (Exception error) {
      Log.warning("Unknown device - " + id);
      return null;
    }

    // Time
    Calendar time = Calendar.getInstance(TimeZone.getTimeZone("UTC"));
    time.clear();
    time.set(Calendar.YEAR, Integer.valueOf(parser.group(index++)));
    time.set(Calendar.MONTH, Integer.valueOf(parser.group(index++)) - 1);
    time.set(Calendar.DAY_OF_MONTH, Integer.valueOf(parser.group(index++)));
    time.set(Calendar.HOUR_OF_DAY, Integer.valueOf(parser.group(index++)));
    time.set(Calendar.MINUTE, Integer.valueOf(parser.group(index++)));
    time.set(Calendar.SECOND, Integer.valueOf(parser.group(index++)));
    position.setTime(time.getTime());

    // Position data
    position.setLongitude(Double.valueOf(parser.group(index++)));
    position.setLatitude(Double.valueOf(parser.group(index++)));
    position.setSpeed(Double.valueOf(parser.group(index++)) * 0.539957);
    position.setCourse(Double.valueOf(parser.group(index++)));
    position.setAltitude(Double.valueOf(parser.group(index++)));

    // Satellites
    int satellites = Integer.valueOf(parser.group(index++));
    position.setValid(satellites >= 3);
    extendedInfo.set("satellites", satellites);

    // Event
    extendedInfo.set("event", parser.group(index++));

    // Battery
    extendedInfo.set("battery", parser.group(index++));

    // Milage
    extendedInfo.set("milage", parser.group(index++));

    // Input
    extendedInfo.set("input", parser.group(index++));

    // ADC
    extendedInfo.set("adc1", parser.group(index++));
    extendedInfo.set("adc2", parser.group(index++));

    // Output
    extendedInfo.set("output", parser.group(index++));

    position.setExtendedInfo(extendedInfo.toString());
    return position;
  }
示例#17
0
  @Override
  protected Object decode(ChannelHandlerContext ctx, Channel channel, Object msg) throws Exception {

    String sentence = (String) msg;

    // Send response #1
    if (sentence.contains("##")) {
      if (channel != null) {
        channel.write("LOAD");
      }
      return null;
    }

    // Send response #2
    if (sentence.length() == 15 && Character.isDigit(sentence.charAt(0))) {
      if (channel != null) {
        channel.write("ON");
      }
      return null;
    }

    // Parse message
    Matcher parser = pattern.matcher(sentence);
    if (!parser.matches()) {
      Log.info("Parsing error");
      return null;
    }

    // Create new position
    Position position = new Position();
    StringBuilder extendedInfo = new StringBuilder("<protocol>gps103</protocol>");

    Integer index = 1;

    // Get device by IMEI
    String imei = parser.group(index++);
    try {
      position.setDeviceId(getDataManager().getDeviceByImei(imei).getId());
    } catch (Exception error) {
      Log.warning("Unknown device - " + imei);
      return null;
    }

    // Alarm message
    extendedInfo.append("<alarm>");
    extendedInfo.append(parser.group(index++));
    extendedInfo.append("</alarm>");

    // Date
    Calendar time = Calendar.getInstance(TimeZone.getTimeZone("UTC"));
    time.clear();
    time.set(Calendar.YEAR, 2000 + Integer.valueOf(parser.group(index++)));
    time.set(Calendar.MONTH, Integer.valueOf(parser.group(index++)) - 1);
    time.set(Calendar.DAY_OF_MONTH, Integer.valueOf(parser.group(index++)));

    int localHours = Integer.valueOf(parser.group(index++));
    int localMinutes = Integer.valueOf(parser.group(index++));

    int utcHours = Integer.valueOf(parser.group(index++));
    int utcMinutes = Integer.valueOf(parser.group(index++));

    // Time
    time.set(Calendar.HOUR, localHours);
    time.set(Calendar.MINUTE, localMinutes);
    time.set(Calendar.SECOND, Integer.valueOf(parser.group(index++)));
    time.set(Calendar.MILLISECOND, Integer.valueOf(parser.group(index++)));

    // Timezone calculation
    int deltaMinutes = (localHours - utcHours) * 60 + localMinutes - utcMinutes;
    if (deltaMinutes <= -12 * 60) {
      deltaMinutes += 24 * 60;
    } else if (deltaMinutes > 12 * 60) {
      deltaMinutes -= 24 * 60;
    }
    time.add(Calendar.MINUTE, -deltaMinutes);
    position.setTime(time.getTime());

    // Validity
    position.setValid(parser.group(index++).compareTo("A") == 0 ? true : false);

    // Latitude
    Double latitude = Double.valueOf(parser.group(index++));
    latitude += Double.valueOf(parser.group(index++)) / 60;
    if (parser.group(index++).compareTo("S") == 0) latitude = -latitude;
    position.setLatitude(latitude);

    // Longitude
    Double lonlitude = Double.valueOf(parser.group(index++));
    lonlitude += Double.valueOf(parser.group(index++)) / 60;
    String hemisphere = parser.group(index++);
    if (hemisphere != null) {
      if (hemisphere.compareTo("W") == 0) lonlitude = -lonlitude;
    }
    position.setLongitude(lonlitude);

    // Altitude
    position.setAltitude(0.0);

    // Speed
    position.setSpeed(Double.valueOf(parser.group(index++)));

    // Course
    String course = parser.group(index++);
    if (course != null) {
      position.setCourse(Double.valueOf(course));
    } else {
      position.setCourse(0.0);
    }

    // Extended info
    position.setExtendedInfo(extendedInfo.toString());

    return position;
  }
示例#18
0
  public final void refresh() {
    if (dataManager != null) {
      try {
        groupGeofencesLock.writeLock().lock();
        deviceGeofencesLock.writeLock().lock();
        try {
          groupGeofences.clear();
          for (GroupGeofence groupGeofence : dataManager.getGroupGeofences()) {
            getGroupGeofences(groupGeofence.getGroupId()).add(groupGeofence.getGeofenceId());
          }

          deviceGeofences.clear();
          deviceGeofencesWithGroups.clear();

          for (DeviceGeofence deviceGeofence : dataManager.getDeviceGeofences()) {
            getDeviceGeofences(deviceGeofences, deviceGeofence.getDeviceId())
                .add(deviceGeofence.getGeofenceId());
            getDeviceGeofences(deviceGeofencesWithGroups, deviceGeofence.getDeviceId())
                .add(deviceGeofence.getGeofenceId());
          }

          for (Device device : dataManager.getAllDevicesCached()) {
            long groupId = device.getGroupId();
            while (groupId != 0) {
              getDeviceGeofences(deviceGeofencesWithGroups, device.getId())
                  .addAll(getGroupGeofences(groupId));
              if (dataManager.getGroupById(groupId) != null) {
                groupId = dataManager.getGroupById(groupId).getGroupId();
              } else {
                groupId = 0;
              }
            }
            List<Long> deviceGeofenceIds = device.getGeofenceIds();
            if (deviceGeofenceIds == null) {
              deviceGeofenceIds = new ArrayList<>();
            } else {
              deviceGeofenceIds.clear();
            }
            Position lastPosition = Context.getConnectionManager().getLastPosition(device.getId());
            if (lastPosition != null && deviceGeofencesWithGroups.containsKey(device.getId())) {
              for (long geofenceId : deviceGeofencesWithGroups.get(device.getId())) {
                Geofence geofence = getGeofence(geofenceId);
                if (geofence != null
                    && geofence
                        .getGeometry()
                        .containsPoint(lastPosition.getLatitude(), lastPosition.getLongitude())) {
                  deviceGeofenceIds.add(geofenceId);
                }
              }
            }
            device.setGeofenceIds(deviceGeofenceIds);
          }

        } finally {
          groupGeofencesLock.writeLock().unlock();
          deviceGeofencesLock.writeLock().unlock();
        }

      } catch (SQLException error) {
        Log.warning(error);
      }
    }
  }
示例#19
0
 @Test
 public void testLog() {
   Assert.assertEquals(
       "test - Exception (LogTest.java:10 < ...)", Log.exceptionStack(new Exception("test")));
 }
示例#20
0
  @Override
  protected Object decode(ChannelHandlerContext ctx, Channel channel, Object msg) throws Exception {

    // Parse message
    String sentence = (String) msg;
    Matcher parser = pattern.matcher(sentence);
    if (!parser.matches()) {
      return null;
    }

    // Create new position
    Position position = new Position();
    ExtendedInfoFormatter extendedInfo = new ExtendedInfoFormatter("xexun2");

    Integer index = 1;

    // Serial
    extendedInfo.set("serial", parser.group(index++));

    // Number
    extendedInfo.set("number", parser.group(index++));

    // Time
    Calendar time = Calendar.getInstance(TimeZone.getTimeZone("UTC"));
    time.clear();
    time.set(Calendar.HOUR, Integer.valueOf(parser.group(index++)));
    time.set(Calendar.MINUTE, Integer.valueOf(parser.group(index++)));
    time.set(Calendar.SECOND, Integer.valueOf(parser.group(index++)));
    time.set(Calendar.MILLISECOND, Integer.valueOf(parser.group(index++)));

    // Validity
    position.setValid(parser.group(index++).compareTo("A") == 0 ? true : false);

    // Latitude
    Double latitude = Double.valueOf(parser.group(index++));
    latitude += Double.valueOf(parser.group(index++)) / 60;
    if (parser.group(index++).compareTo("S") == 0) latitude = -latitude;
    position.setLatitude(latitude);

    // Longitude
    Double lonlitude = Double.valueOf(parser.group(index++));
    lonlitude += Double.valueOf(parser.group(index++)) / 60;
    if (parser.group(index++).compareTo("W") == 0) lonlitude = -lonlitude;
    position.setLongitude(lonlitude);

    // Speed
    position.setSpeed(Double.valueOf(parser.group(index++)));

    // Course
    String course = parser.group(index++);
    if (course != null) {
      position.setCourse(Double.valueOf(course));
    } else {
      position.setCourse(0.0);
    }

    // Date
    time.set(Calendar.DAY_OF_MONTH, Integer.valueOf(parser.group(index++)));
    time.set(Calendar.MONTH, Integer.valueOf(parser.group(index++)) - 1);
    time.set(Calendar.YEAR, 2000 + Integer.valueOf(parser.group(index++)));
    position.setTime(time.getTime());

    // Signal
    extendedInfo.set("signal", parser.group(index++));

    // Alarm
    extendedInfo.set("alarm", parser.group(index++));

    // Get device by IMEI
    String imei = parser.group(index++);
    try {
      position.setDeviceId(getDataManager().getDeviceByImei(imei).getId());
    } catch (Exception error) {
      Log.warning("Unknown device - " + imei);
      return null;
    }

    // Satellites
    extendedInfo.set("satellites", parser.group(index++).replaceFirst("^0*(?![\\.$])", ""));

    // Altitude
    String altitude = parser.group(index++);
    if (altitude != null) {
      position.setAltitude(Double.valueOf(altitude));
    } else {
      position.setAltitude(0.0);
    }

    // Power
    position.setPower(Double.valueOf(parser.group(index++)));

    // Extended info
    position.setExtendedInfo(extendedInfo.toString());

    return position;
  }