diff options
Diffstat (limited to 'src/org')
26 files changed, 412 insertions, 276 deletions
diff --git a/src/org/traccar/BaseProtocolDecoder.java b/src/org/traccar/BaseProtocolDecoder.java index d8130c79e..ea0905bf2 100644 --- a/src/org/traccar/BaseProtocolDecoder.java +++ b/src/org/traccar/BaseProtocolDecoder.java @@ -36,6 +36,12 @@ public abstract class BaseProtocolDecoder extends ExtendedObjectDecoder { Device device = new Device(); device.setName(uniqueId); device.setUniqueId(uniqueId); + device.setCategory(Context.getConfig().getString("database.registerUnknown.defaultCategory")); + + long defaultGroupId = Context.getConfig().getLong("database.registerUnknown.defaultGroupId"); + if (defaultGroupId != 0) { + device.setGroupId(defaultGroupId); + } try { Context.getDeviceManager().addDevice(device); diff --git a/src/org/traccar/Context.java b/src/org/traccar/Context.java index 581f00082..2b8860187 100644 --- a/src/org/traccar/Context.java +++ b/src/org/traccar/Context.java @@ -17,6 +17,11 @@ package org.traccar; import com.ning.http.client.AsyncHttpClient; +import java.net.InetAddress; +import java.util.Properties; + +import org.apache.velocity.app.VelocityEngine; +import org.eclipse.jetty.util.URIUtil; import org.traccar.database.AliasesManager; import org.traccar.database.ConnectionManager; import org.traccar.database.DataManager; @@ -125,6 +130,12 @@ public final class Context { return notificationManager; } + private static VelocityEngine velocityEngine; + + public static VelocityEngine getVelocityEngine() { + return velocityEngine; + } + private static final AsyncHttpClient ASYNC_HTTP_CLIENT = new AsyncHttpClient(); public static AsyncHttpClient getAsyncHttpClient() { @@ -181,7 +192,11 @@ public final class Context { int cacheSize = config.getInteger("geocoder.cacheSize"); switch (type) { case "nominatim": - reverseGeocoder = new NominatimReverseGeocoder(url, cacheSize); + if (key != null) { + reverseGeocoder = new NominatimReverseGeocoder(url, key, cacheSize); + } else { + reverseGeocoder = new NominatimReverseGeocoder(url, cacheSize); + } break; case "gisgraphy": reverseGeocoder = new GisgraphyReverseGeocoder(url, cacheSize); @@ -242,6 +257,20 @@ public final class Context { if (config.getBoolean("event.enable")) { notificationManager = new NotificationManager(dataManager); + Properties velocityProperties = new Properties(); + velocityProperties.setProperty("file.resource.loader.path", + Context.getConfig().getString("mail.templatesPath", "templates/mail") + "/"); + velocityProperties.setProperty("runtime.log.logsystem.class", + "org.apache.velocity.runtime.log.NullLogChute"); + + String address = config.getString("web.address", InetAddress.getLocalHost().getHostAddress()); + int port = config.getInteger("web.port", 8082); + String webUrl = URIUtil.newURI("http", address, port, "", ""); + webUrl = Context.getConfig().getString("web.url", webUrl); + velocityProperties.setProperty("web.url", webUrl); + + velocityEngine = new VelocityEngine(); + velocityEngine.init(velocityProperties); } serverManager = new ServerManager(); diff --git a/src/org/traccar/api/resource/EventResource.java b/src/org/traccar/api/resource/EventResource.java index c0a8f968d..0ef5456af 100644 --- a/src/org/traccar/api/resource/EventResource.java +++ b/src/org/traccar/api/resource/EventResource.java @@ -29,4 +29,5 @@ public class EventResource extends BaseResource { } return event; } + } diff --git a/src/org/traccar/api/resource/NotificationResource.java b/src/org/traccar/api/resource/NotificationResource.java index 6c9725f37..03f7e4ba0 100644 --- a/src/org/traccar/api/resource/NotificationResource.java +++ b/src/org/traccar/api/resource/NotificationResource.java @@ -49,7 +49,7 @@ public class NotificationResource extends BaseResource { userId = getUserId(); } Context.getPermissionsManager().checkUser(getUserId(), userId); - return Context.getNotificationManager().getUserNotifications(userId); + return Context.getNotificationManager().getAllUserNotifications(userId); } @POST diff --git a/src/org/traccar/api/resource/PositionResource.java b/src/org/traccar/api/resource/PositionResource.java index 84f406bee..9d3cd9ae6 100644 --- a/src/org/traccar/api/resource/PositionResource.java +++ b/src/org/traccar/api/resource/PositionResource.java @@ -37,6 +37,7 @@ import java.util.Collection; import java.util.List; @Path("positions") +@Produces(MediaType.APPLICATION_JSON) @Consumes(MediaType.APPLICATION_JSON) public class PositionResource extends BaseResource { @@ -46,7 +47,6 @@ public class PositionResource extends BaseResource { public static final String CONTENT_DISPOSITION_VALUE_GPX = "attachment; filename=positions.gpx"; @GET - @Produces(MediaType.APPLICATION_JSON) public Collection<Position> getJson( @QueryParam("deviceId") long deviceId, @QueryParam("id") List<Long> positionIds, @QueryParam("from") String from, @QueryParam("to") String to) @@ -92,4 +92,5 @@ public class PositionResource extends BaseResource { deviceId, DateUtil.parseDate(from), DateUtil.parseDate(to))); return Response.ok(gpx.build()).header(HttpHeaders.CONTENT_DISPOSITION, CONTENT_DISPOSITION_VALUE_GPX).build(); } + } diff --git a/src/org/traccar/api/resource/ReportResource.java b/src/org/traccar/api/resource/ReportResource.java index e37d6f01d..a1b35d64e 100644 --- a/src/org/traccar/api/resource/ReportResource.java +++ b/src/org/traccar/api/resource/ReportResource.java @@ -27,6 +27,7 @@ import org.traccar.reports.model.TripReport; import org.traccar.reports.Route; @Path("reports") +@Produces(MediaType.APPLICATION_JSON) @Consumes(MediaType.APPLICATION_JSON) public class ReportResource extends BaseResource { @@ -35,7 +36,6 @@ public class ReportResource extends BaseResource { @Path("route") @GET - @Produces(MediaType.APPLICATION_JSON) public Collection<Position> getRoute( @QueryParam("deviceId") final List<Long> deviceIds, @QueryParam("groupId") final List<Long> groupIds, @QueryParam("from") String from, @QueryParam("to") String to) throws SQLException { @@ -59,7 +59,6 @@ public class ReportResource extends BaseResource { @Path("events") @GET - @Produces(MediaType.APPLICATION_JSON) public Collection<Event> getEvents( @QueryParam("deviceId") final List<Long> deviceIds, @QueryParam("groupId") final List<Long> groupIds, @QueryParam("type") final List<String> types, @@ -85,7 +84,6 @@ public class ReportResource extends BaseResource { @Path("summary") @GET - @Produces(MediaType.APPLICATION_JSON) public Collection<SummaryReport> getSummary( @QueryParam("deviceId") final List<Long> deviceIds, @QueryParam("groupId") final List<Long> groupIds, @QueryParam("from") String from, @QueryParam("to") String to) throws SQLException { diff --git a/src/org/traccar/database/NotificationManager.java b/src/org/traccar/database/NotificationManager.java index 7e79e289f..ee804f5cd 100644 --- a/src/org/traccar/database/NotificationManager.java +++ b/src/org/traccar/database/NotificationManager.java @@ -59,10 +59,10 @@ public class NotificationManager { && Context.getGeofenceManager().checkGeofence(userId, event.getGeofenceId())) { Notification notification = getUserNotificationByType(userId, event.getType()); if (notification != null) { - if (notification.getAttributes().containsKey("web")) { + if (notification.getWeb()) { Context.getConnectionManager().updateEvent(userId, event, position); } - if (notification.getAttributes().containsKey("mail")) { + if (notification.getMail()) { NotificationMail.sendMailAsync(userId, event, position); } } @@ -130,8 +130,9 @@ public class NotificationManager { public void updateNotification(Notification notification) { Notification cachedNotification = getUserNotificationByType(notification.getUserId(), notification.getType()); if (cachedNotification != null) { - if (!cachedNotification.getAttributes().equals(notification.getAttributes())) { - if (notification.getAttributes().isEmpty()) { + if (cachedNotification.getWeb() != notification.getWeb() + || cachedNotification.getMail() != notification.getMail()) { + if (!notification.getWeb() && !notification.getMail()) { try { dataManager.removeNotification(cachedNotification); } catch (SQLException error) { @@ -146,6 +147,8 @@ public class NotificationManager { } else { notificationsLock.writeLock().lock(); try { + cachedNotification.setWeb(notification.getWeb()); + cachedNotification.setMail(notification.getMail()); cachedNotification.setAttributes(notification.getAttributes()); } finally { notificationsLock.writeLock().unlock(); @@ -159,7 +162,7 @@ public class NotificationManager { } else { notification.setId(cachedNotification.getId()); } - } else if (!notification.getAttributes().isEmpty()) { + } else if (notification.getWeb() || notification.getMail()) { try { dataManager.addNotification(notification); } catch (SQLException error) { @@ -193,4 +196,16 @@ public class NotificationManager { return notifications; } + public Collection<Notification> getAllUserNotifications(long userId) { + Map<String, Notification> notifications = new HashMap<>(); + for (Notification notification : getAllNotifications()) { + notification.setUserId(userId); + notifications.put(notification.getType(), notification); + } + for (Notification notification : getUserNotifications(userId)) { + notifications.put(notification.getType(), notification); + } + return notifications.values(); + } + } diff --git a/src/org/traccar/geocode/NominatimReverseGeocoder.java b/src/org/traccar/geocode/NominatimReverseGeocoder.java index 0fbeaef83..b393f6490 100644 --- a/src/org/traccar/geocode/NominatimReverseGeocoder.java +++ b/src/org/traccar/geocode/NominatimReverseGeocoder.java @@ -27,6 +27,10 @@ public class NominatimReverseGeocoder extends JsonReverseGeocoder { super(url + "?format=json&lat=%f&lon=%f&zoom=18&addressdetails=1", cacheSize); } + public NominatimReverseGeocoder(String url, String key, int cacheSize) { + super(url + "?format=json&lat=%f&lon=%f&zoom=18&addressdetails=1&key=" + key, cacheSize); + } + @Override public Address parseAddress(JsonObject json) { JsonObject result = json.getJsonObject("address"); diff --git a/src/org/traccar/helper/UnitsConverter.java b/src/org/traccar/helper/UnitsConverter.java index 00b00861e..e0d94c6dc 100644 --- a/src/org/traccar/helper/UnitsConverter.java +++ b/src/org/traccar/helper/UnitsConverter.java @@ -21,6 +21,7 @@ public final class UnitsConverter { private static final double KNOTS_TO_MPH_RATIO = 0.868976; private static final double KNOTS_TO_MPS_RATIO = 1.94384; private static final double KNOTS_TO_CPS_RATIO = 0.0194384449; + private static final double METERS_TO_FEET_RATIO = 0.3048; private UnitsConverter() { } @@ -53,4 +54,12 @@ public final class UnitsConverter { return value * KNOTS_TO_CPS_RATIO; } + public static double feetFromMeters(double value) { + return value / METERS_TO_FEET_RATIO; + } + + public static double metersFromFeet(double value) { + return value * METERS_TO_FEET_RATIO; + } + } diff --git a/src/org/traccar/model/Notification.java b/src/org/traccar/model/Notification.java index 64e1ac60c..dd5f66f15 100644 --- a/src/org/traccar/model/Notification.java +++ b/src/org/traccar/model/Notification.java @@ -37,4 +37,23 @@ public class Notification extends Extensible { this.type = type; } + private boolean web; + + public boolean getWeb() { + return web; + } + + public void setWeb(boolean web) { + this.web = web; + } + + private boolean mail; + + public boolean getMail() { + return mail; + } + + public void setMail(boolean mail) { + this.mail = mail; + } } diff --git a/src/org/traccar/model/Position.java b/src/org/traccar/model/Position.java index b2965c89c..8ca2588e2 100644 --- a/src/org/traccar/model/Position.java +++ b/src/org/traccar/model/Position.java @@ -59,6 +59,7 @@ public class Position extends Message { public static final String KEY_MOTION = "motion"; public static final String KEY_ARMED = "armed"; public static final String KEY_ACCURACY = "accuracy"; + public static final String KEY_GEOFENCE = "geofence"; public static final String KEY_DTCS = "dtcs"; public static final String KEY_OBD_SPEED = "obdSpeed"; diff --git a/src/org/traccar/notification/MailMessage.java b/src/org/traccar/notification/MailMessage.java new file mode 100644 index 000000000..0fce43740 --- /dev/null +++ b/src/org/traccar/notification/MailMessage.java @@ -0,0 +1,36 @@ +/* + * Copyright 2016 Anton Tananaev (anton@traccar.org) + * Copyright 2016 Andrey Kunitsyn (andrey@traccar.org) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.traccar.notification; + +public class MailMessage { + + private String subject; + private String body; + + public MailMessage(String subject, String body) { + this.subject = subject; + this.body = body; + } + + public String getSubject() { + return subject; + } + + public String getBody() { + return body; + } +} diff --git a/src/org/traccar/notification/NotificationFormatter.java b/src/org/traccar/notification/NotificationFormatter.java index 6753873ed..819c387d1 100644 --- a/src/org/traccar/notification/NotificationFormatter.java +++ b/src/org/traccar/notification/NotificationFormatter.java @@ -15,223 +15,49 @@ */ package org.traccar.notification; -import java.text.DecimalFormat; -import java.util.Formatter; -import java.util.Locale; +import java.io.StringWriter; +import org.apache.velocity.Template; +import org.apache.velocity.VelocityContext; +import org.apache.velocity.exception.ResourceNotFoundException; import org.traccar.Context; -import org.traccar.helper.UnitsConverter; +import org.traccar.helper.Log; import org.traccar.model.Device; import org.traccar.model.Event; import org.traccar.model.Position; +import org.traccar.reports.ReportUtils; public final class NotificationFormatter { private NotificationFormatter() { } - public static final String TITLE_TEMPLATE_TYPE_COMMAND_RESULT = "%1$s: command result received"; - public static final String MESSAGE_TEMPLATE_TYPE_COMMAND_RESULT = "Device: %1$s%n" - + "Result: %3$s%n" - + "Time: %2$tc%n"; - - public static final String TITLE_TEMPLATE_TYPE_DEVICE_ONLINE = "%1$s: online"; - public static final String MESSAGE_TEMPLATE_TYPE_DEVICE_ONLINE = "Device: %1$s%n" - + "Online%n" - + "Time: %2$tc%n"; - public static final String TITLE_TEMPLATE_TYPE_DEVICE_UNKNOWN = "%1$s: status is unknown"; - public static final String MESSAGE_TEMPLATE_TYPE_DEVICE_UNKNOWN = "Device: %1$s%n" - + "Status is unknown%n" - + "Time: %2$tc%n"; - public static final String TITLE_TEMPLATE_TYPE_DEVICE_OFFLINE = "%1$s: offline"; - public static final String MESSAGE_TEMPLATE_TYPE_DEVICE_OFFLINE = "Device: %1$s%n" - + "Offline%n" - + "Time: %2$tc%n"; - - public static final String TITLE_TEMPLATE_TYPE_DEVICE_MOVING = "%1$s: moving"; - public static final String MESSAGE_TEMPLATE_TYPE_DEVICE_MOVING = "Device: %1$s%n" - + "Moving%n" - + "Point: https://www.openstreetmap.org/?mlat=%3$f&mlon=%4$f#map=16/%3$f/%4$f%n" - + "Time: %2$tc%n"; - public static final String TITLE_TEMPLATE_TYPE_DEVICE_STOPPED = "%1$s: stopped"; - public static final String MESSAGE_TEMPLATE_TYPE_DEVICE_STOPPED = "Device: %1$s%n" - + "Stopped%n" - + "Point: https://www.openstreetmap.org/?mlat=%3$f&mlon=%4$f#map=16/%3$f/%4$f%n" - + "Time: %2$tc%n"; - - public static final String TITLE_TEMPLATE_TYPE_DEVICE_OVERSPEED = "%1$s: exceeds the speed"; - public static final String MESSAGE_TEMPLATE_TYPE_DEVICE_OVERSPEED = "Device: %1$s%n" - + "Exceeds the speed: %5$s%n" - + "Point: https://www.openstreetmap.org/?mlat=%3$f&mlon=%4$f#map=16/%3$f/%4$f%n" - + "Time: %2$tc%n"; - - public static final String TITLE_TEMPLATE_TYPE_GEOFENCE_ENTER = "%1$s: has entered geofence"; - public static final String MESSAGE_TEMPLATE_TYPE_GEOFENCE_ENTER = "Device: %1$s%n" - + "Has entered geofence: %5$s%n" - + "Point: https://www.openstreetmap.org/?mlat=%3$f&mlon=%4$f#map=16/%3$f/%4$f%n" - + "Time: %2$tc%n"; - public static final String TITLE_TEMPLATE_TYPE_GEOFENCE_EXIT = "%1$s: has exited geofence"; - public static final String MESSAGE_TEMPLATE_TYPE_GEOFENCE_EXIT = "Device: %1$s%n" - + "Has exited geofence: %5$s%n" - + "Point: https://www.openstreetmap.org/?mlat=%3$f&mlon=%4$f#map=16/%3$f/%4$f%n" - + "Time: %2$tc%n"; - - public static final String TITLE_TEMPLATE_TYPE_ALARM = "%1$s: alarm!"; - public static final String MESSAGE_TEMPLATE_TYPE_ALARM = "Device: %1$s%n" - + "Alarm: %5$s%n" - + "Point: https://www.openstreetmap.org/?mlat=%3$f&mlon=%4$f#map=16/%3$f/%4$f%n" - + "Time: %2$tc%n"; - - public static final String TITLE_TEMPLATE_TYPE_IGNITION_ON = "%1$s: ignition ON"; - public static final String MESSAGE_TEMPLATE_TYPE_IGNITION_ON = "Device: %1$s%n" - + "Ignition ON%n" - + "Point: https://www.openstreetmap.org/?mlat=%3$f&mlon=%4$f#map=16/%3$f/%4$f%n" - + "Time: %2$tc%n"; - public static final String TITLE_TEMPLATE_TYPE_IGNITION_OFF = "%1$s: ignition OFF"; - public static final String MESSAGE_TEMPLATE_TYPE_IGNITION_OFF = "Device: %1$s%n" - + "Ignition OFF%n" - + "Point: https://www.openstreetmap.org/?mlat=%3$f&mlon=%4$f#map=16/%3$f/%4$f%n" - + "Time: %2$tc%n"; - public static final String TITLE_TEMPLATE_TYPE_MAINTENANCE = "%1$s: maintenance is required"; - public static final String MESSAGE_TEMPLATE_TYPE_MAINTENANCE = "Device: %1$s%n" - + "Maintenance is required%n" - + "Point: https://www.openstreetmap.org/?mlat=%3$f&mlon=%4$f#map=16/%3$f/%4$f%n" - + "Time: %2$tc%n"; - - public static String formatTitle(long userId, Event event, Position position) { + public static MailMessage formatMessage(long userId, Event event, Position position) { Device device = Context.getIdentityManager().getDeviceById(event.getDeviceId()); - StringBuilder stringBuilder = new StringBuilder(); - Formatter formatter = new Formatter(stringBuilder, Locale.getDefault()); - switch (event.getType()) { - case Event.TYPE_COMMAND_RESULT: - formatter.format(TITLE_TEMPLATE_TYPE_COMMAND_RESULT, device.getName()); - break; - case Event.TYPE_DEVICE_ONLINE: - formatter.format(TITLE_TEMPLATE_TYPE_DEVICE_ONLINE, device.getName()); - break; - case Event.TYPE_DEVICE_UNKNOWN: - formatter.format(TITLE_TEMPLATE_TYPE_DEVICE_UNKNOWN, device.getName()); - break; - case Event.TYPE_DEVICE_OFFLINE: - formatter.format(TITLE_TEMPLATE_TYPE_DEVICE_OFFLINE, device.getName()); - break; - case Event.TYPE_DEVICE_MOVING: - formatter.format(TITLE_TEMPLATE_TYPE_DEVICE_MOVING, device.getName()); - break; - case Event.TYPE_DEVICE_STOPPED: - formatter.format(TITLE_TEMPLATE_TYPE_DEVICE_STOPPED, device.getName()); - break; - case Event.TYPE_DEVICE_OVERSPEED: - formatter.format(TITLE_TEMPLATE_TYPE_DEVICE_OVERSPEED, device.getName()); - break; - case Event.TYPE_GEOFENCE_ENTER: - formatter.format(TITLE_TEMPLATE_TYPE_GEOFENCE_ENTER, device.getName()); - break; - case Event.TYPE_GEOFENCE_EXIT: - formatter.format(TITLE_TEMPLATE_TYPE_GEOFENCE_EXIT, device.getName()); - break; - case Event.TYPE_ALARM: - formatter.format(TITLE_TEMPLATE_TYPE_ALARM, device.getName()); - break; - case Event.TYPE_IGNITION_ON: - formatter.format(TITLE_TEMPLATE_TYPE_IGNITION_ON, device.getName()); - break; - case Event.TYPE_IGNITION_OFF: - formatter.format(TITLE_TEMPLATE_TYPE_IGNITION_OFF, device.getName()); - break; - case Event.TYPE_MAINTENANCE: - formatter.format(TITLE_TEMPLATE_TYPE_MAINTENANCE, device.getName()); - break; - default: - formatter.format("Unknown type"); - break; + VelocityContext velocityContext = new VelocityContext(); + velocityContext.put("device", device); + velocityContext.put("event", event); + if (position != null) { + velocityContext.put("position", position); + velocityContext.put("speedUnits", ReportUtils.getSpeedUnit(userId)); } - String result = formatter.toString(); - formatter.close(); - return result; - } - - public static String formatMessage(long userId, Event event, Position position) { - Device device = Context.getIdentityManager().getDeviceById(event.getDeviceId()); - StringBuilder stringBuilder = new StringBuilder(); - Formatter formatter = new Formatter(stringBuilder, Locale.getDefault()); - - switch (event.getType()) { - case Event.TYPE_COMMAND_RESULT: - formatter.format(MESSAGE_TEMPLATE_TYPE_COMMAND_RESULT, device.getName(), event.getServerTime(), - position.getAttributes().get(Position.KEY_RESULT)); - break; - case Event.TYPE_DEVICE_ONLINE: - formatter.format(MESSAGE_TEMPLATE_TYPE_DEVICE_ONLINE, device.getName(), event.getServerTime()); - break; - case Event.TYPE_DEVICE_UNKNOWN: - formatter.format(MESSAGE_TEMPLATE_TYPE_DEVICE_UNKNOWN, device.getName(), event.getServerTime()); - break; - case Event.TYPE_DEVICE_OFFLINE: - formatter.format(MESSAGE_TEMPLATE_TYPE_DEVICE_OFFLINE, device.getName(), event.getServerTime()); - break; - case Event.TYPE_DEVICE_MOVING: - formatter.format(MESSAGE_TEMPLATE_TYPE_DEVICE_MOVING, device.getName(), position.getFixTime(), - position.getLatitude(), position.getLongitude()); - break; - case Event.TYPE_DEVICE_STOPPED: - formatter.format(MESSAGE_TEMPLATE_TYPE_DEVICE_STOPPED, device.getName(), position.getFixTime(), - position.getLatitude(), position.getLongitude()); - break; - case Event.TYPE_DEVICE_OVERSPEED: - formatter.format(MESSAGE_TEMPLATE_TYPE_DEVICE_OVERSPEED, device.getName(), position.getFixTime(), - position.getLatitude(), position.getLongitude(), formatSpeed(userId, position.getSpeed())); - break; - case Event.TYPE_GEOFENCE_ENTER: - formatter.format(MESSAGE_TEMPLATE_TYPE_GEOFENCE_ENTER, device.getName(), position.getFixTime(), - position.getLatitude(), position.getLongitude(), - Context.getGeofenceManager().getGeofence(event.getGeofenceId()).getName()); - break; - case Event.TYPE_GEOFENCE_EXIT: - formatter.format(MESSAGE_TEMPLATE_TYPE_GEOFENCE_EXIT, device.getName(), position.getFixTime(), - position.getLatitude(), position.getLongitude(), - Context.getGeofenceManager().getGeofence(event.getGeofenceId()).getName()); - break; - case Event.TYPE_ALARM: - formatter.format(MESSAGE_TEMPLATE_TYPE_ALARM, device.getName(), event.getServerTime(), - position.getLatitude(), position.getLongitude(), - position.getAttributes().get(Position.KEY_ALARM)); - break; - case Event.TYPE_IGNITION_ON: - formatter.format(MESSAGE_TEMPLATE_TYPE_IGNITION_ON, device.getName(), position.getFixTime(), - position.getLatitude(), position.getLongitude()); - break; - case Event.TYPE_IGNITION_OFF: - formatter.format(MESSAGE_TEMPLATE_TYPE_IGNITION_OFF, device.getName(), position.getFixTime(), - position.getLatitude(), position.getLongitude()); - break; - case Event.TYPE_MAINTENANCE: - formatter.format(MESSAGE_TEMPLATE_TYPE_MAINTENANCE, device.getName(), position.getFixTime(), - position.getLatitude(), position.getLongitude()); - break; - default: - formatter.format("Unknown type"); - break; + if (event.getGeofenceId() != 0) { + velocityContext.put("geofence", Context.getGeofenceManager().getGeofence(event.getGeofenceId())); } - String result = formatter.toString(); - formatter.close(); - return result; - } - - private static String formatSpeed(long userId, double speed) { - DecimalFormat df = new DecimalFormat("#.##"); - String result = df.format(speed) + " kn"; - switch (Context.getPermissionsManager().getUser(userId).getSpeedUnit()) { - case "kmh": - result = df.format(UnitsConverter.kphFromKnots(speed)) + " km/h"; - break; - case "mph": - result = df.format(UnitsConverter.mphFromKnots(speed)) + " mph"; - break; - default: - break; + velocityContext.put("webUrl", Context.getVelocityEngine().getProperty("web.url")); + + Template template = null; + try { + template = Context.getVelocityEngine().getTemplate(event.getType() + ".vm"); + } catch (ResourceNotFoundException error) { + Log.warning(error); + template = Context.getVelocityEngine().getTemplate("unknown.vm"); } - return result; + + StringWriter writer = new StringWriter(); + template.merge(velocityContext, writer); + String subject = (String) velocityContext.get("subject"); + return new MailMessage(subject, writer.toString()); } } diff --git a/src/org/traccar/notification/NotificationMail.java b/src/org/traccar/notification/NotificationMail.java index 17e4d6be4..7b7ef6e74 100644 --- a/src/org/traccar/notification/NotificationMail.java +++ b/src/org/traccar/notification/NotificationMail.java @@ -61,6 +61,11 @@ public final class NotificationMail { properties.put("mail.smtp.ssl.trust", sslTrust); } + String sslProtocols = provider.getString("mail.smtp.ssl.protocols"); + if (sslProtocols != null) { + properties.put("mail.smtp.ssl.protocols", sslProtocols); + } + properties.put("mail.smtp.auth", provider.getString("mail.smtp.auth")); String username = provider.getString("mail.smtp.username"); @@ -101,8 +106,9 @@ public final class NotificationMail { } message.addRecipient(Message.RecipientType.TO, new InternetAddress(user.getEmail())); - message.setSubject(NotificationFormatter.formatTitle(userId, event, position)); - message.setText(NotificationFormatter.formatMessage(userId, event, position)); + MailMessage mailMessage = NotificationFormatter.formatMessage(userId, event, position); + message.setSubject(mailMessage.getSubject()); + message.setContent(mailMessage.getBody(), "text/html; charset=utf-8"); Transport transport = session.getTransport(); try { diff --git a/src/org/traccar/protocol/At2000Protocol.java b/src/org/traccar/protocol/At2000Protocol.java index 418619cb4..35aa0b469 100644 --- a/src/org/traccar/protocol/At2000Protocol.java +++ b/src/org/traccar/protocol/At2000Protocol.java @@ -20,6 +20,7 @@ import org.jboss.netty.channel.ChannelPipeline; import org.traccar.BaseProtocol; import org.traccar.TrackerServer; +import java.nio.ByteOrder; import java.util.List; public class At2000Protocol extends BaseProtocol { @@ -30,13 +31,15 @@ public class At2000Protocol extends BaseProtocol { @Override public void initTrackerServers(List<TrackerServer> serverList) { - serverList.add(new TrackerServer(new ServerBootstrap(), getName()) { + TrackerServer server = new TrackerServer(new ServerBootstrap(), getName()) { @Override protected void addSpecificHandlers(ChannelPipeline pipeline) { pipeline.addLast("frameDecoder", new At2000FrameDecoder()); pipeline.addLast("objectDecoder", new At2000ProtocolDecoder(At2000Protocol.this)); } - }); + }; + server.setEndianness(ByteOrder.LITTLE_ENDIAN); + serverList.add(server); } } diff --git a/src/org/traccar/protocol/At2000ProtocolDecoder.java b/src/org/traccar/protocol/At2000ProtocolDecoder.java index 17da0eef7..e9c26d406 100644 --- a/src/org/traccar/protocol/At2000ProtocolDecoder.java +++ b/src/org/traccar/protocol/At2000ProtocolDecoder.java @@ -50,11 +50,11 @@ public class At2000ProtocolDecoder extends BaseProtocolDecoder { private static void sendResponse(Channel channel) { if (channel != null) { - ChannelBuffer response = ChannelBuffers.directBuffer(BLOCK_LENGTH); + ChannelBuffer response = ChannelBuffers.directBuffer(ByteOrder.LITTLE_ENDIAN, 2 * BLOCK_LENGTH); response.writeByte(MSG_ACKNOWLEDGEMENT); - response.writeMedium(1); + response.writeMedium(ChannelBuffers.swapMedium(1)); response.writeByte(0x00); // success - response.writerIndex(BLOCK_LENGTH); + response.writerIndex(2 * BLOCK_LENGTH); channel.write(response); } } diff --git a/src/org/traccar/protocol/CalAmpProtocolDecoder.java b/src/org/traccar/protocol/CalAmpProtocolDecoder.java index 510684411..ee4cc65b4 100644 --- a/src/org/traccar/protocol/CalAmpProtocolDecoder.java +++ b/src/org/traccar/protocol/CalAmpProtocolDecoder.java @@ -149,19 +149,8 @@ public class CalAmpProtocolDecoder extends BaseProtocolDecoder { int content = buf.readUnsignedByte(); if (BitUtil.check(content, 0)) { - - int length = buf.readUnsignedByte(); - long id = 0; - for (int i = 0; i < length; i++) { - int b = buf.readUnsignedByte(); - id = id * 10 + (b >> 4); - if ((b & 0xf) != 0xf) { - id = id * 10 + (b & 0xf); - } - } - - getDeviceSession(channel, remoteAddress, String.valueOf(id)); - + String id = ChannelBuffers.hexDump(buf.readBytes(buf.readUnsignedByte())); + getDeviceSession(channel, remoteAddress, id); } if (BitUtil.check(content, 1)) { diff --git a/src/org/traccar/protocol/GoSafeProtocolDecoder.java b/src/org/traccar/protocol/GoSafeProtocolDecoder.java index a258e922c..a7f1024c6 100644 --- a/src/org/traccar/protocol/GoSafeProtocolDecoder.java +++ b/src/org/traccar/protocol/GoSafeProtocolDecoder.java @@ -90,13 +90,14 @@ public class GoSafeProtocolDecoder extends BaseProtocolDecoder { .groupBegin() .text("DTT:") .number("(x+);") // status - .expression("[^;]*;") - .number("x+;") // geo-fence 0-119 - .number("x+;") // geo-fence 120-155 - .number("x+,?") // event status + .number("(x+)?;") // io + .number("(x+);") // geo-fence 0-119 + .number("(x+);") // geo-fence 120-155 + .number("(x+)") // event status + .number("(?:;(x+))?,?") // packet type .groupEnd("?") .groupBegin() - .text("ETD:").expression("[^,]*,?") + .text("ETD:").expression("([^,]+),?") .groupEnd("?") .groupBegin() .text("OBD:") @@ -108,6 +109,9 @@ public class GoSafeProtocolDecoder extends BaseProtocolDecoder { .groupBegin() .text("TRU:").expression("[^,]*,?") .groupEnd("?") + .groupBegin() + .text("TAG:").expression("([^,]+),?") + .groupEnd("?") .compile(); private static final Pattern PATTERN_OLD = new PatternBuilder() @@ -122,7 +126,7 @@ public class GoSafeProtocolDecoder extends BaseProtocolDecoder { .number("([EW])(d+.d+);") // longitude .number("(d+)?;") // speed .number("(d+);") // course - .number("(d+.?d*)").optional() // hdop + .number("(d+.?d*)").optional() // hdop .number("(dd)(dd)(dd)") // date .any() .compile(); @@ -162,16 +166,28 @@ public class GoSafeProtocolDecoder extends BaseProtocolDecoder { position.set(Position.KEY_POWER, parser.next()); position.set(Position.KEY_BATTERY, parser.next()); - String status = parser.next(); - if (status != null) { - position.set(Position.KEY_IGNITION, BitUtil.check(Integer.parseInt(status, 16), 13)); + if (parser.hasNext(6)) { + long status = parser.nextLong(16); + position.set(Position.KEY_IGNITION, BitUtil.check(status, 13)); position.set(Position.KEY_STATUS, status); + position.set("ioStatus", parser.next()); + position.set(Position.KEY_GEOFENCE, parser.next() + parser.next()); + position.set("eventStatus", parser.next()); + position.set("packetType", parser.next()); + } + + if (parser.hasNext()) { + position.set("eventData", parser.next()); } if (parser.hasNext()) { position.set("obd", parser.next()); } + if (parser.hasNext()) { + position.set("tagData", parser.next()); + } + return position; } @@ -211,7 +227,7 @@ public class GoSafeProtocolDecoder extends BaseProtocolDecoder { position.setValid(parser.next().equals("A")); position.setLatitude(parser.nextCoordinate(Parser.CoordinateFormat.HEM_DEG)); position.setLongitude(parser.nextCoordinate(Parser.CoordinateFormat.HEM_DEG)); - position.setSpeed(parser.nextDouble()); + position.setSpeed(UnitsConverter.knotsFromKph(parser.nextDouble())); position.setCourse(parser.nextDouble()); position.set(Position.KEY_HDOP, parser.next()); diff --git a/src/org/traccar/protocol/Gps103ProtocolDecoder.java b/src/org/traccar/protocol/Gps103ProtocolDecoder.java index 57dc784d3..d929ae917 100644 --- a/src/org/traccar/protocol/Gps103ProtocolDecoder.java +++ b/src/org/traccar/protocol/Gps103ProtocolDecoder.java @@ -119,6 +119,8 @@ public class Gps103ProtocolDecoder extends BaseProtocolDecoder { return Position.ALARM_POWER_OFF; case "door alarm": return Position.ALARM_DOOR; + case "ac alarm": + return Position.ALARM_POWER_CUT; default: return null; } diff --git a/src/org/traccar/protocol/GranitProtocolDecoder.java b/src/org/traccar/protocol/GranitProtocolDecoder.java index 5fa786e4d..6e8bc24bf 100644 --- a/src/org/traccar/protocol/GranitProtocolDecoder.java +++ b/src/org/traccar/protocol/GranitProtocolDecoder.java @@ -61,7 +61,7 @@ public class GranitProtocolDecoder extends BaseProtocolDecoder { private static void sendResponseCurrent(Channel channel, int deviceId, long time) { ChannelBuffer response = ChannelBuffers.dynamicBuffer(ByteOrder.LITTLE_ENDIAN, 0); response.writeBytes("BB+UGRC~".getBytes(StandardCharsets.US_ASCII)); - response.writeShort(6); //binary length + response.writeShort(6); // length response.writeInt((int) time); response.writeShort(deviceId); appendChecksum(response, 16); @@ -71,7 +71,7 @@ public class GranitProtocolDecoder extends BaseProtocolDecoder { private static void sendResponseArchive(Channel channel, int deviceId, int packNum) { ChannelBuffer response = ChannelBuffers.dynamicBuffer(ByteOrder.LITTLE_ENDIAN, 0); response.writeBytes("BB+ARCF~".getBytes(StandardCharsets.US_ASCII)); - response.writeShort(4); //binary length + response.writeShort(4); // length response.writeShort(packNum); response.writeShort(deviceId); appendChecksum(response, 14); @@ -95,14 +95,19 @@ public class GranitProtocolDecoder extends BaseProtocolDecoder { int latDegrees = buf.readUnsignedByte(); int lonMinutes = buf.readUnsignedShort(); int latMinutes = buf.readUnsignedShort(); + double latitude = latDegrees + latMinutes / 60000.0; double longitude = lonDegrees + lonMinutes / 60000.0; - if (!BitUtil.check(flags, 4)) { - latitude = -latitude; - } - if (!BitUtil.check(flags, 5)) { - longitude = -longitude; + + if (position.getValid()) { + if (!BitUtil.check(flags, 4)) { + latitude = -latitude; + } + if (!BitUtil.check(flags, 5)) { + longitude = -longitude; + } } + position.setLongitude(longitude); position.setLatitude(latitude); @@ -135,11 +140,11 @@ public class GranitProtocolDecoder extends BaseProtocolDecoder { position.setAltitude(buf.readUnsignedByte() * 10); - short diOut = buf.readUnsignedByte(); + int output = buf.readUnsignedByte(); for (int i = 0; i < 8; i++) { - position.set(Position.PREFIX_IO + (i + 1), BitUtil.check(diOut, i)); + position.set(Position.PREFIX_IO + (i + 1), BitUtil.check(output, i)); } - buf.skipBytes(1); //StatMess + buf.readUnsignedByte(); // status message buffer } @Override diff --git a/src/org/traccar/protocol/H02ProtocolDecoder.java b/src/org/traccar/protocol/H02ProtocolDecoder.java index 45a978571..2c7852d16 100644 --- a/src/org/traccar/protocol/H02ProtocolDecoder.java +++ b/src/org/traccar/protocol/H02ProtocolDecoder.java @@ -75,7 +75,7 @@ public class H02ProtocolDecoder extends BaseProtocolDecoder { position.set(Position.KEY_ALARM, Position.ALARM_OVERSPEED); } } - position.set(Position.KEY_IGNITION, BitUtil.check(status, 10)); + position.set(Position.KEY_IGNITION, !BitUtil.check(status, 10)); position.set(Position.KEY_STATUS, status); } @@ -167,6 +167,12 @@ public class H02ProtocolDecoder extends BaseProtocolDecoder { .number("(?:(dd)(dd)(dd))?,") // date (ddmmyy) .any() .number("(x{8})") // status + .groupBegin() + .number(", *(x+),") // mcc + .number(" *(x+),") // mnc + .number(" *(x+),") // lac + .number(" *(x+)") // cid + .groupEnd("?") .any() .compile(); @@ -237,6 +243,19 @@ public class H02ProtocolDecoder extends BaseProtocolDecoder { processStatus(position, parser.nextLong(16)); + if (parser.hasNext(4)) { + int mcc = parser.nextInt(16); + int mnc = parser.nextInt(16); + int lac = parser.nextInt(16); + int cid = parser.nextInt(16); + if (mcc != 0 && mnc != 0 && lac != 0 && cid != 0) { + position.set(Position.KEY_MCC, mcc); + position.set(Position.KEY_MNC, mnc); + position.set(Position.KEY_LAC, lac); + position.set(Position.KEY_CID, cid); + } + } + return position; } diff --git a/src/org/traccar/protocol/OigoProtocolDecoder.java b/src/org/traccar/protocol/OigoProtocolDecoder.java index 15a215c4f..9e6a9a82e 100644 --- a/src/org/traccar/protocol/OigoProtocolDecoder.java +++ b/src/org/traccar/protocol/OigoProtocolDecoder.java @@ -34,15 +34,12 @@ public class OigoProtocolDecoder extends BaseProtocolDecoder { super(protocol); } - public static final int MSG_LOCATION = 0x00; - public static final int MSG_REMOTE_START = 0x10; - public static final int MSG_ACKNOWLEDGEMENT = 0xE0; + public static final int MSG_AR_LOCATION = 0x00; + public static final int MSG_AR_REMOTE_START = 0x10; - @Override - protected Object decode( - Channel channel, SocketAddress remoteAddress, Object msg) throws Exception { + public static final int MSG_ACKNOWLEDGEMENT = 0xE0; - ChannelBuffer buf = (ChannelBuffer) msg; + private Position decodeArMessage(Channel channel, SocketAddress remoteAddress, ChannelBuffer buf) { buf.skipBytes(1); // header buf.readUnsignedShort(); // length @@ -67,7 +64,7 @@ public class OigoProtocolDecoder extends BaseProtocolDecoder { break; } - if (deviceSession == null || type != MSG_LOCATION) { + if (deviceSession == null || type != MSG_AR_LOCATION) { return null; } @@ -154,4 +151,89 @@ public class OigoProtocolDecoder extends BaseProtocolDecoder { return position; } + private double convertCoordinate(long value) { + boolean negative = value < 0; + value = Math.abs(value); + double minutes = (value % 100000) * 0.001; + value /= 100000; + double degrees = value + minutes / 60; + return negative ? -degrees : degrees; + } + + 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() * 100 + "mV"); + position.set(Position.PREFIX_IO + 1, buf.readUnsignedByte()); + + dateBuilder.setSecond(buf.readUnsignedByte()); + position.setTime(dateBuilder.getDate()); + + position.set(Position.KEY_GSM, buf.readUnsignedByte()); + + int index = buf.readUnsignedByte(); + + position.set(Position.KEY_VERSION, 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; + } + + @Override + protected Object decode( + Channel channel, SocketAddress remoteAddress, Object msg) throws Exception { + + ChannelBuffer buf = (ChannelBuffer) msg; + + if (buf.getUnsignedByte(buf.readerIndex()) == 0x7e) { + return decodeArMessage(channel, remoteAddress, buf); + } else { + return decodeMgMessage(channel, remoteAddress, buf); + } + } + } diff --git a/src/org/traccar/protocol/Pt502ProtocolDecoder.java b/src/org/traccar/protocol/Pt502ProtocolDecoder.java index 2d3cb9101..f3d9e8380 100644 --- a/src/org/traccar/protocol/Pt502ProtocolDecoder.java +++ b/src/org/traccar/protocol/Pt502ProtocolDecoder.java @@ -29,6 +29,10 @@ import java.util.regex.Pattern; public class Pt502ProtocolDecoder extends BaseProtocolDecoder {
+ private static final int MAX_CHUNK_SIZE = 960;
+
+ private byte[] photo;
+
public Pt502ProtocolDecoder(Pt502Protocol protocol) {
super(protocol);
}
@@ -92,7 +96,8 @@ public class Pt502ProtocolDecoder extends BaseProtocolDecoder { String type = parser.next();
if (type.startsWith("PHO") && channel != null) {
- channel.write("#PHD0," + type.substring(3) + "\r\n");
+ photo = new byte[Integer.parseInt(type.substring(3))];
+ channel.write("#PHD0," + Math.min(photo.length, MAX_CHUNK_SIZE) + "\r\n");
}
position.set(Position.KEY_ALARM, decodeAlarm(type));
diff --git a/src/org/traccar/protocol/XexunProtocol.java b/src/org/traccar/protocol/XexunProtocol.java index 2aea2f246..a52d9ff45 100644 --- a/src/org/traccar/protocol/XexunProtocol.java +++ b/src/org/traccar/protocol/XexunProtocol.java @@ -1,5 +1,5 @@ /* - * Copyright 2015 Anton Tananaev (anton@traccar.org) + * Copyright 2015 - 2016 Anton Tananaev (anton@traccar.org) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -23,6 +23,7 @@ import org.jboss.netty.handler.codec.string.StringEncoder; import org.traccar.BaseProtocol; import org.traccar.Context; import org.traccar.TrackerServer; +import org.traccar.model.Command; import java.util.List; @@ -30,6 +31,9 @@ public class XexunProtocol extends BaseProtocol { public XexunProtocol() { super("xexun"); + setSupportedCommands( + Command.TYPE_ENGINE_STOP, + Command.TYPE_ENGINE_RESUME); } @Override @@ -43,8 +47,9 @@ public class XexunProtocol extends BaseProtocol { } else { pipeline.addLast("frameDecoder", new XexunFrameDecoder()); } - pipeline.addLast("stringDecoder", new StringDecoder()); pipeline.addLast("stringEncoder", new StringEncoder()); + pipeline.addLast("stringDecoder", new StringDecoder()); + pipeline.addLast("objectEncoder", new XexunProtocolEncoder()); pipeline.addLast("objectDecoder", new XexunProtocolDecoder(XexunProtocol.this, full)); } }); diff --git a/src/org/traccar/protocol/XexunProtocolEncoder.java b/src/org/traccar/protocol/XexunProtocolEncoder.java new file mode 100644 index 000000000..cdf3ac6f7 --- /dev/null +++ b/src/org/traccar/protocol/XexunProtocolEncoder.java @@ -0,0 +1,42 @@ +/* + * Copyright 2016 Anton Tananaev (anton@traccar.org) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.traccar.protocol; + +import org.traccar.StringProtocolEncoder; +import org.traccar.helper.Log; +import org.traccar.model.Command; + +public class XexunProtocolEncoder extends StringProtocolEncoder { + + @Override + protected Object encodeCommand(Command command) { + + initDevicePassword(command, "123456"); + + switch (command.getType()) { + case Command.TYPE_ENGINE_STOP: + return formatCommand(command, "powercar{%s} 11", Command.KEY_DEVICE_PASSWORD); + case Command.TYPE_ENGINE_RESUME: + return formatCommand(command, "powercar{%s} 00", Command.KEY_DEVICE_PASSWORD); + default: + Log.warning(new UnsupportedOperationException(command.getType())); + break; + } + + return null; + } + +} diff --git a/src/org/traccar/reports/Trips.java b/src/org/traccar/reports/Trips.java index d4e25f5e5..a52d48f16 100644 --- a/src/org/traccar/reports/Trips.java +++ b/src/org/traccar/reports/Trips.java @@ -46,7 +46,8 @@ public final class Trips { private Trips() { } - private static TripReport calculateTrip(ArrayList<Position> positions, int startIndex, int endIndex) { + private static TripReport calculateTrip( + ArrayList<Position> positions, int startIndex, int endIndex, boolean ignoreOdometer) { Position startTrip = positions.get(startIndex); Position endTrip = positions.get(endIndex); @@ -79,8 +80,6 @@ public final class Trips { trip.setEndTime(endTrip.getFixTime()); trip.setEndAddress(endTrip.getAddress()); - boolean ignoreOdometer = Context.getDeviceManager() - .lookupAttributeBoolean(deviceId, "report.ignoreOdometer", false, true); trip.setDistance(ReportUtils.calculateDistance(startTrip, endTrip, !ignoreOdometer)); trip.setDuration(tripDuration); trip.setAverageSpeed(speedSum / (endIndex - startIndex)); @@ -90,15 +89,14 @@ public final class Trips { return trip; } - private static Collection<TripReport> detectTrips(long deviceId, Date from, Date to) throws SQLException { - double speedThreshold = Context.getConfig().getDouble("event.motion.speedThreshold", 0.01); - long minimalTripDuration = Context.getConfig().getLong("report.trip.minimalTripDuration", 300) * 1000; - double minimalTripDistance = Context.getConfig().getLong("report.trip.minimalTripDistance", 500); - long minimalParkingDuration = Context.getConfig().getLong("report.trip.minimalParkingDuration", 300) * 1000; - boolean greedyParking = Context.getConfig().getBoolean("report.trip.greedyParking"); + protected static Collection<TripReport> detectTrips( + double speedThreshold, double minimalTripDistance, + long minimalTripDuration, long minimalParkingDuration, boolean greedyParking, boolean ignoreOdometer, + Collection<Position> positionCollection) { + Collection<TripReport> result = new ArrayList<>(); - ArrayList<Position> positions = new ArrayList<>(Context.getDataManager().getPositions(deviceId, from, to)); + ArrayList<Position> positions = new ArrayList<>(positionCollection); if (positions != null && !positions.isEmpty()) { int previousStartParkingIndex = 0; int startParkingIndex = -1; @@ -150,7 +148,8 @@ public final class Trips { if ((parkingDuration >= minimalParkingDuration || isLast) && previousEndParkingIndex < startParkingIndex) { if (!tripFiltered) { - result.add(calculateTrip(positions, previousEndParkingIndex, startParkingIndex)); + result.add(calculateTrip( + positions, previousEndParkingIndex, startParkingIndex, ignoreOdometer)); } previousEndParkingIndex = endParkingIndex; skipped = false; @@ -161,9 +160,26 @@ public final class Trips { } } } + return result; } + private static Collection<TripReport> detectTrips(long deviceId, Date from, Date to) throws SQLException { + double speedThreshold = Context.getConfig().getDouble("event.motion.speedThreshold", 0.01); + long minimalTripDuration = Context.getConfig().getLong("report.trip.minimalTripDuration", 300) * 1000; + double minimalTripDistance = Context.getConfig().getLong("report.trip.minimalTripDistance", 500); + long minimalParkingDuration = Context.getConfig().getLong("report.trip.minimalParkingDuration", 300) * 1000; + boolean greedyParking = Context.getConfig().getBoolean("report.trip.greedyParking"); + + boolean ignoreOdometer = Context.getDeviceManager() + .lookupAttributeBoolean(deviceId, "report.ignoreOdometer", false, true); + + return detectTrips( + speedThreshold, minimalTripDistance, minimalTripDuration, + minimalParkingDuration, greedyParking, ignoreOdometer, + Context.getDataManager().getPositions(deviceId, from, to)); + } + public static Collection<TripReport> getObjects(long userId, Collection<Long> deviceIds, Collection<Long> groupIds, Date from, Date to) throws SQLException { ArrayList<TripReport> result = new ArrayList<>(); @@ -217,4 +233,5 @@ public final class Trips { transformer.write(); } } + } |