From bd2a8efaddacbd8d8386ae38f000b633845639ab Mon Sep 17 00:00:00 2001 From: Abyss777 Date: Tue, 21 Feb 2017 15:20:25 +0500 Subject: Implement SMS notifications with help smpp protocol --- src/org/traccar/smpp/SmppClient.java | 218 +++++++++++++++++++++++++++++++++++ 1 file changed, 218 insertions(+) create mode 100644 src/org/traccar/smpp/SmppClient.java (limited to 'src/org/traccar/smpp/SmppClient.java') 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); + } + } + }); + } +} -- cgit v1.2.3 From 53236979ca2298a4722512d49f5ebb07b550a914 Mon Sep 17 00:00:00 2001 From: Abyss777 Date: Wed, 22 Feb 2017 16:25:47 +0500 Subject: - Simplify delivery log message - Use warning instead of error --- src/org/traccar/smpp/ClientSmppSessionHandler.java | 17 ++++++++++++----- src/org/traccar/smpp/EnquireLinkTask.java | 4 ++-- src/org/traccar/smpp/SmppClient.java | 2 +- 3 files changed, 15 insertions(+), 8 deletions(-) (limited to 'src/org/traccar/smpp/SmppClient.java') diff --git a/src/org/traccar/smpp/ClientSmppSessionHandler.java b/src/org/traccar/smpp/ClientSmppSessionHandler.java index 2cf03871c..721243f9f 100644 --- a/src/org/traccar/smpp/ClientSmppSessionHandler.java +++ b/src/org/traccar/smpp/ClientSmppSessionHandler.java @@ -43,11 +43,18 @@ public class ClientSmppSessionHandler extends DefaultSmppSessionHandler { 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()); + if (request.getOptionalParameters() != null) { + Log.debug("Message Delivered: " + + request.getOptionalParameter(SmppConstants.TAG_RECEIPTED_MSG_ID).getValueAsString() + + ", State: " + + request.getOptionalParameter(SmppConstants.TAG_MSG_STATE).getValueAsByte()); + } else { + 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) { diff --git a/src/org/traccar/smpp/EnquireLinkTask.java b/src/org/traccar/smpp/EnquireLinkTask.java index 22347b6f4..9a3121e24 100644 --- a/src/org/traccar/smpp/EnquireLinkTask.java +++ b/src/org/traccar/smpp/EnquireLinkTask.java @@ -43,13 +43,13 @@ public class EnquireLinkTask implements Runnable { smppSession.enquireLink(new EnquireLink(), enquireLinkTimeout); } catch (SmppTimeoutException | SmppChannelException | RecoverablePduException | UnrecoverablePduException error) { - Log.warning("Enquire link failed, executing reconnect: " + 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"); + Log.warning("Enquire link running while session is not connected"); } } diff --git a/src/org/traccar/smpp/SmppClient.java b/src/org/traccar/smpp/SmppClient.java index a1d56c2bf..b93253de4 100644 --- a/src/org/traccar/smpp/SmppClient.java +++ b/src/org/traccar/smpp/SmppClient.java @@ -193,7 +193,7 @@ public class SmppClient { 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.setDataCoding(dataCoding); submit.setShortMessage(textBytes); SubmitSmResp submitResponce = getSession().submit(submit, submitTimeout); Log.debug("SMS submited, msg_id: " + submitResponce.getMessageId()); -- cgit v1.2.3 From d0ae83ef94f1e4a89b27b70ebbc60150f1c83b31 Mon Sep 17 00:00:00 2001 From: Abyss777 Date: Thu, 23 Feb 2017 10:23:46 +0500 Subject: - Combine template retrieving in one function - Do not request delivery receipt --- .../notification/NotificationFormatter.java | 37 ++++++++++------------ src/org/traccar/smpp/SmppClient.java | 1 - 2 files changed, 17 insertions(+), 21 deletions(-) (limited to 'src/org/traccar/smpp/SmppClient.java') diff --git a/src/org/traccar/notification/NotificationFormatter.java b/src/org/traccar/notification/NotificationFormatter.java index 1e3072d53..df7d73683 100644 --- a/src/org/traccar/notification/NotificationFormatter.java +++ b/src/org/traccar/notification/NotificationFormatter.java @@ -51,39 +51,36 @@ public final class NotificationFormatter { 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; + private static Template getTemplate(Event event, boolean mail) { + Template template; + String subPath = ""; + if (mail) { + subPath = Context.getConfig().getString("mail.templatesPath", "mail") + "/"; + } else { + subPath = Context.getConfig().getString("sms.templatesPath", "sms") + "/"; + } try { - template = Context.getVelocityEngine().getTemplate(mailTemplatesPath + event.getType() + ".vm", + template = Context.getVelocityEngine().getTemplate(subPath + event.getType() + ".vm", StandardCharsets.UTF_8.name()); } catch (ResourceNotFoundException error) { Log.warning(error); - template = Context.getVelocityEngine().getTemplate(mailTemplatesPath + "unknown.vm", + template = Context.getVelocityEngine().getTemplate(subPath + "unknown.vm", StandardCharsets.UTF_8.name()); } + return template; + } + public static MailMessage formatMailMessage(long userId, Event event, Position position) { + VelocityContext velocityContext = prepareContext(userId, event, position); StringWriter writer = new StringWriter(); - template.merge(velocityContext, writer); - String subject = (String) velocityContext.get("subject"); - return new MailMessage(subject, writer.toString()); + getTemplate(event, true).merge(velocityContext, writer); + return new MailMessage((String) velocityContext.get("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); + getTemplate(event, false).merge(velocityContext, writer); return writer.toString(); } } diff --git a/src/org/traccar/smpp/SmppClient.java b/src/org/traccar/smpp/SmppClient.java index b93253de4..3680d20e2 100644 --- a/src/org/traccar/smpp/SmppClient.java +++ b/src/org/traccar/smpp/SmppClient.java @@ -192,7 +192,6 @@ public class SmppClient { 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(dataCoding); submit.setShortMessage(textBytes); SubmitSmResp submitResponce = getSession().submit(submit, submitTimeout); -- cgit v1.2.3