aboutsummaryrefslogtreecommitdiff
path: root/src
diff options
context:
space:
mode:
authorAbyss777 <abyss@fox5.ru>2017-02-21 15:20:25 +0500
committerAbyss777 <abyss@fox5.ru>2017-02-21 15:20:25 +0500
commitbd2a8efaddacbd8d8386ae38f000b633845639ab (patch)
tree80d4454311d9656fe79850ebcdb4131e3cc32634 /src
parentb6af1e997c125336e2ce9f5056d9502743f22034 (diff)
downloadtrackermap-server-bd2a8efaddacbd8d8386ae38f000b633845639ab.tar.gz
trackermap-server-bd2a8efaddacbd8d8386ae38f000b633845639ab.tar.bz2
trackermap-server-bd2a8efaddacbd8d8386ae38f000b633845639ab.zip
Implement SMS notifications with help smpp protocol
Diffstat (limited to 'src')
-rw-r--r--src/org/traccar/Context.java15
-rw-r--r--src/org/traccar/api/resource/NotificationResource.java12
-rw-r--r--src/org/traccar/database/NotificationManager.java14
-rw-r--r--src/org/traccar/model/Notification.java10
-rw-r--r--src/org/traccar/model/User.java10
-rw-r--r--src/org/traccar/notification/NotificationFormatter.java33
-rw-r--r--src/org/traccar/notification/NotificationMail.java5
-rw-r--r--src/org/traccar/notification/NotificationSms.java50
-rw-r--r--src/org/traccar/smpp/ClientSmppSessionHandler.java67
-rw-r--r--src/org/traccar/smpp/EnquireLinkTask.java56
-rw-r--r--src/org/traccar/smpp/ReconnectionTask.java31
-rw-r--r--src/org/traccar/smpp/SmppClient.java218
12 files changed, 507 insertions, 14 deletions
diff --git a/src/org/traccar/Context.java b/src/org/traccar/Context.java
index c9c2e633e..6c271c3ed 100644
--- a/src/org/traccar/Context.java
+++ b/src/org/traccar/Context.java
@@ -1,5 +1,5 @@
/*
- * Copyright 2015 - 2016 Anton Tananaev (anton@traccar.org)
+ * Copyright 2015 - 2017 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.
@@ -49,6 +49,7 @@ import org.traccar.geolocation.GeolocationProvider;
import org.traccar.geolocation.MozillaGeolocationProvider;
import org.traccar.geolocation.OpenCellIdGeolocationProvider;
import org.traccar.notification.EventForwarder;
+import org.traccar.smpp.SmppClient;
import org.traccar.web.WebServer;
public final class Context {
@@ -176,6 +177,12 @@ public final class Context {
return statisticsManager;
}
+ private static SmppClient smppClient;
+
+ public static SmppClient getSmppManager() {
+ return smppClient;
+ }
+
public static void init(String[] arguments) throws Exception {
config = new Config();
@@ -277,7 +284,7 @@ public final class Context {
notificationManager = new NotificationManager(dataManager);
Properties velocityProperties = new Properties();
velocityProperties.setProperty("file.resource.loader.path",
- Context.getConfig().getString("mail.templatesPath", "templates/mail") + "/");
+ Context.getConfig().getString("templates.rootPath", "templates") + "/");
velocityProperties.setProperty("runtime.log.logsystem.class",
"org.apache.velocity.runtime.log.NullLogChute");
@@ -301,6 +308,10 @@ public final class Context {
statisticsManager = new StatisticsManager();
+ if (config.getBoolean("sms.smpp.enable")) {
+ smppClient = new SmppClient();
+ }
+
}
public static void init(IdentityManager testIdentityManager) {
diff --git a/src/org/traccar/api/resource/NotificationResource.java b/src/org/traccar/api/resource/NotificationResource.java
index 03f7e4ba0..dee972607 100644
--- a/src/org/traccar/api/resource/NotificationResource.java
+++ b/src/org/traccar/api/resource/NotificationResource.java
@@ -1,5 +1,5 @@
/*
- * Copyright 2016 Anton Tananaev (anton@traccar.org)
+ * Copyright 2016 - 2017 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.
@@ -33,6 +33,12 @@ import org.traccar.api.BaseResource;
import org.traccar.model.Event;
import org.traccar.model.Notification;
import org.traccar.notification.NotificationMail;
+import org.traccar.notification.NotificationSms;
+
+import com.cloudhopper.smpp.type.RecoverablePduException;
+import com.cloudhopper.smpp.type.SmppChannelException;
+import com.cloudhopper.smpp.type.SmppTimeoutException;
+import com.cloudhopper.smpp.type.UnrecoverablePduException;
@Path("users/notifications")
@Produces(MediaType.APPLICATION_JSON)
@@ -62,8 +68,10 @@ public class NotificationResource extends BaseResource {
@Path("test")
@POST
- public Response testMail() throws MessagingException {
+ public Response testMessage() throws MessagingException, RecoverablePduException,
+ UnrecoverablePduException, SmppTimeoutException, SmppChannelException, InterruptedException {
NotificationMail.sendMailSync(getUserId(), new Event("test", 0), null);
+ NotificationSms.sendSmsSync(getUserId(), new Event("test", 0), null);
return Response.noContent().build();
}
diff --git a/src/org/traccar/database/NotificationManager.java b/src/org/traccar/database/NotificationManager.java
index 4ae173c6a..48caa615c 100644
--- a/src/org/traccar/database/NotificationManager.java
+++ b/src/org/traccar/database/NotificationManager.java
@@ -1,5 +1,5 @@
/*
- * Copyright 2016 Anton Tananaev (anton@traccar.org)
+ * Copyright 2016 - 2017 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.
@@ -32,6 +32,7 @@ import org.traccar.model.Event;
import org.traccar.model.Notification;
import org.traccar.model.Position;
import org.traccar.notification.NotificationMail;
+import org.traccar.notification.NotificationSms;
public class NotificationManager {
@@ -65,6 +66,9 @@ public class NotificationManager {
if (notification.getMail()) {
NotificationMail.sendMailAsync(userId, event, position);
}
+ if (notification.getSms()) {
+ NotificationSms.sendSmsAsync(userId, event, position);
+ }
}
}
}
@@ -131,8 +135,9 @@ public class NotificationManager {
Notification cachedNotification = getUserNotificationByType(notification.getUserId(), notification.getType());
if (cachedNotification != null) {
if (cachedNotification.getWeb() != notification.getWeb()
- || cachedNotification.getMail() != notification.getMail()) {
- if (!notification.getWeb() && !notification.getMail()) {
+ || cachedNotification.getMail() != notification.getMail()
+ || cachedNotification.getSms() != notification.getSms()) {
+ if (!notification.getWeb() && !notification.getMail() && !notification.getSms()) {
try {
dataManager.removeNotification(cachedNotification);
} catch (SQLException error) {
@@ -149,6 +154,7 @@ public class NotificationManager {
try {
cachedNotification.setWeb(notification.getWeb());
cachedNotification.setMail(notification.getMail());
+ cachedNotification.setSms(notification.getSms());
cachedNotification.setAttributes(notification.getAttributes());
} finally {
notificationsLock.writeLock().unlock();
@@ -162,7 +168,7 @@ public class NotificationManager {
} else {
notification.setId(cachedNotification.getId());
}
- } else if (notification.getWeb() || notification.getMail()) {
+ } else if (notification.getWeb() || notification.getMail() || notification.getSms()) {
try {
dataManager.addNotification(notification);
} catch (SQLException error) {
diff --git a/src/org/traccar/model/Notification.java b/src/org/traccar/model/Notification.java
index dd5f66f15..6c61cafaf 100644
--- a/src/org/traccar/model/Notification.java
+++ b/src/org/traccar/model/Notification.java
@@ -56,4 +56,14 @@ public class Notification extends Extensible {
public void setMail(boolean mail) {
this.mail = mail;
}
+
+ private boolean sms;
+
+ public boolean getSms() {
+ return sms;
+ }
+
+ public void setSms(boolean sms) {
+ this.sms = sms;
+ }
}
diff --git a/src/org/traccar/model/User.java b/src/org/traccar/model/User.java
index a89a75dd8..274f2b2a2 100644
--- a/src/org/traccar/model/User.java
+++ b/src/org/traccar/model/User.java
@@ -42,6 +42,16 @@ public class User extends Extensible {
this.email = email;
}
+ private String phone;
+
+ public String getPhone() {
+ return phone;
+ }
+
+ public void setPhone(String phone) {
+ this.phone = phone;
+ }
+
private boolean readonly;
public boolean getReadonly() {
diff --git a/src/org/traccar/notification/NotificationFormatter.java b/src/org/traccar/notification/NotificationFormatter.java
index b68d53ee0..1e3072d53 100644
--- a/src/org/traccar/notification/NotificationFormatter.java
+++ b/src/org/traccar/notification/NotificationFormatter.java
@@ -1,5 +1,6 @@
/*
- * Copyright 2016 Anton Tananaev (anton@traccar.org)
+ * Copyright 2016 - 2017 Anton Tananaev (anton@traccar.org)
+ * Copyright 2017 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.
@@ -33,7 +34,7 @@ public final class NotificationFormatter {
private NotificationFormatter() {
}
- public static MailMessage formatMessage(long userId, Event event, Position position) {
+ private static VelocityContext prepareContext(long userId, Event event, Position position) {
Device device = Context.getIdentityManager().getDeviceById(event.getDeviceId());
VelocityContext velocityContext = new VelocityContext();
@@ -47,13 +48,20 @@ public final class NotificationFormatter {
velocityContext.put("geofence", Context.getGeofenceManager().getGeofence(event.getGeofenceId()));
}
velocityContext.put("webUrl", Context.getVelocityEngine().getProperty("web.url"));
+ return velocityContext;
+ }
+ public static MailMessage formatMailMessage(long userId, Event event, Position position) {
+ VelocityContext velocityContext = prepareContext(userId, event, position);
+ String mailTemplatesPath = Context.getConfig().getString("mail.templatesPath", "mail") + "/";
Template template = null;
try {
- template = Context.getVelocityEngine().getTemplate(event.getType() + ".vm", StandardCharsets.UTF_8.name());
+ template = Context.getVelocityEngine().getTemplate(mailTemplatesPath + event.getType() + ".vm",
+ StandardCharsets.UTF_8.name());
} catch (ResourceNotFoundException error) {
Log.warning(error);
- template = Context.getVelocityEngine().getTemplate("unknown.vm", StandardCharsets.UTF_8.name());
+ template = Context.getVelocityEngine().getTemplate(mailTemplatesPath + "unknown.vm",
+ StandardCharsets.UTF_8.name());
}
StringWriter writer = new StringWriter();
@@ -61,4 +69,21 @@ public final class NotificationFormatter {
String subject = (String) velocityContext.get("subject");
return new MailMessage(subject, writer.toString());
}
+
+ public static String formatSmsMessage(long userId, Event event, Position position) {
+ VelocityContext velocityContext = prepareContext(userId, event, position);
+ String smsTemplatesPath = Context.getConfig().getString("sms.templatesPath", "sms") + "/";
+ Template template = null;
+ try {
+ template = Context.getVelocityEngine().getTemplate(smsTemplatesPath + event.getType() + ".vm",
+ StandardCharsets.UTF_8.name());
+ } catch (ResourceNotFoundException error) {
+ Log.warning(error);
+ template = Context.getVelocityEngine().getTemplate(smsTemplatesPath + "unknown.vm",
+ StandardCharsets.UTF_8.name());
+ }
+ StringWriter writer = new StringWriter();
+ template.merge(velocityContext, writer);
+ return writer.toString();
+ }
}
diff --git a/src/org/traccar/notification/NotificationMail.java b/src/org/traccar/notification/NotificationMail.java
index 7b7ef6e74..41cb2e681 100644
--- a/src/org/traccar/notification/NotificationMail.java
+++ b/src/org/traccar/notification/NotificationMail.java
@@ -1,5 +1,6 @@
/*
- * Copyright 2016 Anton Tananaev (anton@traccar.org)
+ * Copyright 2016 - 2017 Anton Tananaev (anton@traccar.org)
+ * Copyright 2017 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.
@@ -106,7 +107,7 @@ public final class NotificationMail {
}
message.addRecipient(Message.RecipientType.TO, new InternetAddress(user.getEmail()));
- MailMessage mailMessage = NotificationFormatter.formatMessage(userId, event, position);
+ MailMessage mailMessage = NotificationFormatter.formatMailMessage(userId, event, position);
message.setSubject(mailMessage.getSubject());
message.setContent(mailMessage.getBody(), "text/html; charset=utf-8");
diff --git a/src/org/traccar/notification/NotificationSms.java b/src/org/traccar/notification/NotificationSms.java
new file mode 100644
index 000000000..cb5dd563a
--- /dev/null
+++ b/src/org/traccar/notification/NotificationSms.java
@@ -0,0 +1,50 @@
+/*
+ * Copyright 2017 Anton Tananaev (anton@traccar.org)
+ * Copyright 2017 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;
+
+import org.traccar.Context;
+import org.traccar.model.Event;
+import org.traccar.model.Position;
+import org.traccar.model.User;
+
+import com.cloudhopper.smpp.type.RecoverablePduException;
+import com.cloudhopper.smpp.type.SmppChannelException;
+import com.cloudhopper.smpp.type.SmppTimeoutException;
+import com.cloudhopper.smpp.type.UnrecoverablePduException;
+
+public final class NotificationSms {
+
+ private NotificationSms() {
+ }
+
+ public static void sendSmsAsync(long userId, Event event, Position position) {
+ User user = Context.getPermissionsManager().getUser(userId);
+ if (Context.getSmppManager() != null && user.getPhone() != null) {
+ Context.getSmppManager().sendMessageAsync(user.getPhone(),
+ NotificationFormatter.formatSmsMessage(userId, event, position));
+ }
+ }
+
+ public static void sendSmsSync(long userId, Event event, Position position) throws RecoverablePduException,
+ UnrecoverablePduException, SmppTimeoutException, SmppChannelException, InterruptedException {
+ User user = Context.getPermissionsManager().getUser(userId);
+ if (Context.getSmppManager() != null && user.getPhone() != null) {
+ Context.getSmppManager().sendMessageSync(user.getPhone(),
+ NotificationFormatter.formatSmsMessage(userId, event, position));
+ }
+ }
+}
diff --git a/src/org/traccar/smpp/ClientSmppSessionHandler.java b/src/org/traccar/smpp/ClientSmppSessionHandler.java
new file mode 100644
index 000000000..2cf03871c
--- /dev/null
+++ b/src/org/traccar/smpp/ClientSmppSessionHandler.java
@@ -0,0 +1,67 @@
+/*
+ * Copyright 2017 Anton Tananaev (anton@traccar.org)
+ * Copyright 2017 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.smpp;
+
+import org.traccar.helper.Log;
+
+import com.cloudhopper.commons.charset.CharsetUtil;
+import com.cloudhopper.smpp.SmppConstants;
+import com.cloudhopper.smpp.impl.DefaultSmppSessionHandler;
+import com.cloudhopper.smpp.pdu.DeliverSm;
+import com.cloudhopper.smpp.pdu.PduRequest;
+import com.cloudhopper.smpp.pdu.PduResponse;
+
+public class ClientSmppSessionHandler extends DefaultSmppSessionHandler {
+
+ private SmppClient smppClient;
+
+ public ClientSmppSessionHandler(SmppClient smppClient) {
+ this.smppClient = smppClient;
+ }
+
+ @Override
+ public void firePduRequestExpired(PduRequest pduRequest) {
+ Log.warning("PDU request expired: " + pduRequest);
+ }
+
+ @Override
+ public PduResponse firePduRequestReceived(PduRequest request) {
+ PduResponse response = null;
+ try {
+ if (request instanceof DeliverSm) {
+ Log.debug("Message Received: "
+ + CharsetUtil.decode(((DeliverSm) request).getShortMessage(),
+ smppClient.mapDataCodingToCharset(((DeliverSm) request).getDataCoding()))
+ + ", Source Address: "
+ + ((DeliverSm) request).getSourceAddress().getAddress());
+ }
+ response = request.createResponse();
+ } catch (Throwable error) {
+ Log.warning(error);
+ response = request.createResponse();
+ response.setResultMessage(error.getMessage());
+ response.setCommandStatus(SmppConstants.STATUS_UNKNOWNERR);
+ }
+ return response;
+ }
+
+ @Override
+ public void fireChannelUnexpectedlyClosed() {
+ Log.warning("Smpp session channel unexpectedly closed");
+ smppClient.scheduleReconnect();
+ }
+}
diff --git a/src/org/traccar/smpp/EnquireLinkTask.java b/src/org/traccar/smpp/EnquireLinkTask.java
new file mode 100644
index 000000000..22347b6f4
--- /dev/null
+++ b/src/org/traccar/smpp/EnquireLinkTask.java
@@ -0,0 +1,56 @@
+/*
+ * Copyright 2017 Anton Tananaev (anton@traccar.org)
+ * Copyright 2017 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.smpp;
+
+import org.traccar.helper.Log;
+
+import com.cloudhopper.smpp.SmppSession;
+import com.cloudhopper.smpp.pdu.EnquireLink;
+import com.cloudhopper.smpp.type.RecoverablePduException;
+import com.cloudhopper.smpp.type.SmppChannelException;
+import com.cloudhopper.smpp.type.SmppTimeoutException;
+import com.cloudhopper.smpp.type.UnrecoverablePduException;
+
+public class EnquireLinkTask implements Runnable {
+
+ private SmppClient smppClient;
+ private Integer enquireLinkTimeout;
+
+ public EnquireLinkTask(SmppClient smppClient, Integer enquireLinkTimeout) {
+ this.smppClient = smppClient;
+ this.enquireLinkTimeout = enquireLinkTimeout;
+ }
+
+ @Override
+ public void run() {
+ SmppSession smppSession = smppClient.getSession();
+ if (smppSession != null && smppSession.isBound()) {
+ try {
+ smppSession.enquireLink(new EnquireLink(), enquireLinkTimeout);
+ } catch (SmppTimeoutException | SmppChannelException
+ | RecoverablePduException | UnrecoverablePduException error) {
+ Log.warning("Enquire link failed, executing reconnect: " + error);
+ smppClient.reconnect();
+ } catch (InterruptedException error) {
+ Log.info("Enquire link interrupted, probably killed by reconnecting");
+ }
+ } else {
+ Log.error("Enquire link running while session is not connected");
+ }
+ }
+
+}
diff --git a/src/org/traccar/smpp/ReconnectionTask.java b/src/org/traccar/smpp/ReconnectionTask.java
new file mode 100644
index 000000000..c9d9173ae
--- /dev/null
+++ b/src/org/traccar/smpp/ReconnectionTask.java
@@ -0,0 +1,31 @@
+/*
+ * Copyright 2017 Anton Tananaev (anton@traccar.org)
+ * Copyright 2017 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.smpp;
+
+public class ReconnectionTask implements Runnable {
+
+ private final SmppClient smppClient;
+
+ protected ReconnectionTask(SmppClient smppClient) {
+ this.smppClient = smppClient;
+ }
+
+ @Override
+ public void run() {
+ smppClient.reconnect();
+ }
+}
diff --git a/src/org/traccar/smpp/SmppClient.java b/src/org/traccar/smpp/SmppClient.java
new file mode 100644
index 000000000..a1d56c2bf
--- /dev/null
+++ b/src/org/traccar/smpp/SmppClient.java
@@ -0,0 +1,218 @@
+/*
+ * Copyright 2017 Anton Tananaev (anton@traccar.org)
+ * Copyright 2017 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.smpp;
+
+import java.util.concurrent.ExecutorService;
+import java.util.concurrent.Executors;
+import java.util.concurrent.ScheduledExecutorService;
+import java.util.concurrent.ScheduledFuture;
+import java.util.concurrent.ThreadFactory;
+import java.util.concurrent.TimeUnit;
+
+import org.traccar.Context;
+import org.traccar.helper.Log;
+
+import com.cloudhopper.commons.charset.CharsetUtil;
+import com.cloudhopper.smpp.SmppBindType;
+import com.cloudhopper.smpp.SmppConstants;
+import com.cloudhopper.smpp.SmppSession;
+import com.cloudhopper.smpp.SmppSessionConfiguration;
+import com.cloudhopper.smpp.impl.DefaultSmppClient;
+import com.cloudhopper.smpp.impl.DefaultSmppSessionHandler;
+import com.cloudhopper.smpp.pdu.SubmitSm;
+import com.cloudhopper.smpp.pdu.SubmitSmResp;
+import com.cloudhopper.smpp.type.Address;
+import com.cloudhopper.smpp.type.RecoverablePduException;
+import com.cloudhopper.smpp.type.SmppChannelException;
+import com.cloudhopper.smpp.type.SmppTimeoutException;
+import com.cloudhopper.smpp.type.UnrecoverablePduException;
+
+public class SmppClient {
+
+ private SmppSessionConfiguration sessionConfig = new SmppSessionConfiguration();
+ private SmppSession smppSession;
+ private DefaultSmppSessionHandler sessionHandler = new ClientSmppSessionHandler(this);
+ private ExecutorService executorService = Executors.newCachedThreadPool();
+ private DefaultSmppClient clientBootstrap = new DefaultSmppClient(executorService, 1);
+
+ private ScheduledExecutorService enquireLinkExecutor;
+ private ScheduledFuture<?> enquireLinkTask;
+ private Integer enquireLinkPeriod;
+ private Integer enquireLinkTimeout;
+
+ private ScheduledExecutorService reconnectionExecutor;
+ private ScheduledFuture<?> reconnectionTask;
+ private Integer reconnectionDelay;
+
+ private String sourceAddress;
+ private int submitTimeout;
+ private String charsetName;
+ private byte dataCoding;
+
+ private byte sourceTon;
+ private byte sourceNpi;
+
+ private byte destTon;
+ private byte destNpi;
+
+ public SmppClient() {
+ sessionConfig.setName("Traccar.smppSession");
+ sessionConfig.setInterfaceVersion(
+ (byte) Context.getConfig().getInteger("sms.smpp.version", SmppConstants.VERSION_3_4));
+ sessionConfig.setType(SmppBindType.TRANSCEIVER);
+ sessionConfig.setHost(Context.getConfig().getString("sms.smpp.host", "localhost"));
+ sessionConfig.setPort(Context.getConfig().getInteger("sms.smpp.port", 2775));
+ sessionConfig.setSystemId(Context.getConfig().getString("sms.smpp.username", "user"));
+ sessionConfig.setPassword(Context.getConfig().getString("sms.smpp.password", "password"));
+ sessionConfig.getLoggingOptions().setLogBytes(false);
+ sessionConfig.getLoggingOptions().setLogPdu(Context.getConfig().getBoolean("sms.smpp.logPdu"));
+
+ sourceAddress = Context.getConfig().getString("sms.smpp.sourceAddress", "");
+ submitTimeout = Context.getConfig().getInteger("sms.smpp.submitTimeout", 10000);
+
+ charsetName = Context.getConfig().getString("sms.smpp.charsetName", CharsetUtil.NAME_UCS_2);
+ dataCoding = (byte) Context.getConfig().getInteger("sms.smpp.dataCoding", SmppConstants.DATA_CODING_UCS2);
+
+ sourceTon = (byte) Context.getConfig().getInteger("sms.smpp.sourceTon", SmppConstants.TON_ALPHANUMERIC);
+ sourceNpi = (byte) Context.getConfig().getInteger("sms.smpp.sourceNpi", SmppConstants.NPI_UNKNOWN);
+
+ destTon = (byte) Context.getConfig().getInteger("sms.smpp.destTon", SmppConstants.TON_INTERNATIONAL);
+ destNpi = (byte) Context.getConfig().getInteger("sms.smpp.destNpi", SmppConstants.NPI_E164);
+
+ enquireLinkPeriod = Context.getConfig().getInteger("sms.smpp.enquireLinkPeriod", 60000);
+ enquireLinkTimeout = Context.getConfig().getInteger("sms.smpp.enquireLinkTimeout", 10000);
+ enquireLinkExecutor = Executors.newScheduledThreadPool(1, new ThreadFactory() {
+ @Override
+ public Thread newThread(Runnable runnable) {
+ Thread thread = new Thread(runnable);
+ String name = sessionConfig.getName();
+ thread.setName("EnquireLink-" + name);
+ return thread;
+ }
+ });
+
+ reconnectionDelay = Context.getConfig().getInteger("sms.smpp.reconnectionDelay", 10000);
+ reconnectionExecutor = Executors.newSingleThreadScheduledExecutor(new ThreadFactory() {
+ @Override
+ public Thread newThread(Runnable runnable) {
+ Thread thread = new Thread(runnable);
+ String name = sessionConfig.getName();
+ thread.setName("Reconnection-" + name);
+ return thread;
+ }
+ });
+
+ scheduleReconnect();
+ }
+
+ public synchronized SmppSession getSession() {
+ return smppSession;
+ }
+
+ public String mapDataCodingToCharset(byte dataCoding) {
+ switch (dataCoding) {
+ case SmppConstants.DATA_CODING_LATIN1:
+ return CharsetUtil.NAME_ISO_8859_1;
+ case SmppConstants.DATA_CODING_UCS2:
+ return CharsetUtil.NAME_UCS_2;
+ default:
+ return CharsetUtil.NAME_GSM;
+ }
+ }
+
+ protected synchronized void reconnect() {
+ try {
+ disconnect();
+ smppSession = clientBootstrap.bind(sessionConfig, sessionHandler);
+ stopReconnectionkTask();
+ runEnquireLinkTask();
+ Log.info("Smpp session connected");
+ } catch (SmppTimeoutException | SmppChannelException
+ | UnrecoverablePduException | InterruptedException error) {
+ Log.warning("Unable to connect to smpp server: ", error);
+ }
+ }
+
+ public void scheduleReconnect() {
+ reconnectionTask = reconnectionExecutor.scheduleWithFixedDelay(
+ new ReconnectionTask(this),
+ reconnectionDelay, reconnectionDelay, TimeUnit.MILLISECONDS);
+ }
+
+ private void stopReconnectionkTask() {
+ if (reconnectionTask != null) {
+ reconnectionTask.cancel(false);
+ }
+ }
+
+ private void disconnect() {
+ stopEnquireLinkTask();
+ destroySession();
+ }
+
+ private void runEnquireLinkTask() {
+ enquireLinkTask = enquireLinkExecutor.scheduleWithFixedDelay(
+ new EnquireLinkTask(this, enquireLinkTimeout),
+ enquireLinkPeriod, enquireLinkPeriod, TimeUnit.MILLISECONDS);
+ }
+
+ private void stopEnquireLinkTask() {
+ if (enquireLinkTask != null) {
+ enquireLinkTask.cancel(true);
+ }
+ }
+
+ private void destroySession() {
+ if (smppSession != null) {
+ Log.debug("Cleaning up smpp session... ");
+ smppSession.destroy();
+ smppSession = null;
+ }
+ }
+
+ public synchronized void sendMessageSync(String destAddress, String message) throws RecoverablePduException,
+ UnrecoverablePduException, SmppTimeoutException, SmppChannelException, InterruptedException {
+ if (getSession() != null && getSession().isBound()) {
+ byte[] textBytes = CharsetUtil.encode(message, charsetName);
+
+ SubmitSm submit = new SubmitSm();
+ submit.setSourceAddress(new Address(sourceTon, sourceNpi, sourceAddress));
+ submit.setDestAddress(new Address(destTon, destNpi, destAddress));
+ submit.setRegisteredDelivery(SmppConstants.REGISTERED_DELIVERY_SMSC_RECEIPT_REQUESTED);
+ submit.setDataCoding((byte) dataCoding);
+ submit.setShortMessage(textBytes);
+ SubmitSmResp submitResponce = getSession().submit(submit, submitTimeout);
+ Log.debug("SMS submited, msg_id: " + submitResponce.getMessageId());
+ } else {
+ throw new SmppChannelException("Smpp session is not connected");
+ }
+ }
+
+ public void sendMessageAsync(final String destAddress, final String message) {
+ executorService.execute(new Runnable() {
+ @Override
+ public void run() {
+ try {
+ sendMessageSync(destAddress, message);
+ } catch (InterruptedException | RecoverablePduException | UnrecoverablePduException
+ | SmppTimeoutException | SmppChannelException error) {
+ Log.warning(error);
+ }
+ }
+ });
+ }
+}