Package servers

Source Code of servers.Modem

package servers;

import java.io.IOException;
import java.util.ArrayList;

import org.json.JSONException;
import org.json.JSONObject;
import org.smslib.AGateway;
import org.smslib.GatewayException;
import org.smslib.IInboundMessageNotification;
import org.smslib.InboundMessage;
import org.smslib.Library;
import org.smslib.OutboundMessage;
import org.smslib.Service;
import org.smslib.Settings;
import org.smslib.TimeoutException;
import org.smslib.InboundMessage.MessageClasses;
import org.smslib.Message.MessageTypes;
import org.smslib.modem.SerialModemGateway;

import utils.ConsoleIO;

import org.apache.log4j.BasicConfigurator;
import org.apache.log4j.ConsoleAppender;
import org.apache.log4j.FileAppender;
import org.apache.log4j.Level;
import org.apache.log4j.Logger;
import org.apache.log4j.PropertyConfigurator;
import org.apache.log4j.SimpleLayout;
import org.apache.log4j.xml.XMLLayout;



public class Modem implements IInboundMessageNotification{

  private static final Logger logger = Logger.getLogger(Modem.class);

  private Service service;

  private SerialModemGateway gateway;

  private InboundMessage incommingMessage;

  private OutboundMessage outcommingMessage;

  private ArrayList inbox = new ArrayList();

  private int messagesQueued = 0;

  private boolean deleteMessageOnReceive = true;

  private boolean newMessagesAvailable = false;

  private boolean usingModem = true;

  /*
  [0] "/dev/tty.usbserial"
  [1] "/dev/cu.usbserial"

  /dev/cu.PL2303-00002006
   */

  private String modemSerialPort = "/dev/tty.usbserial";

  private ModemListener receiver;

  private Modem(){};

  public Modem(ModemListener smsReceiver, boolean usingModem){

    this.receiver = smsReceiver;

    logger.info("+++++++++++++INICIANDO MODEM+++++++++++++++");


    this.usingModem = usingModem;

    if(usingModem){

      setup(smsReceiver);

    }else{

      logger.warn("INCIANDO MODEM EN MODO OFFLINE");
    }

  }




  private void setup(ModemListener smsReceiver){

    try {

      logger.info( Library.getLibraryDescription() );
      logger.info( Library.getLibraryVersion() );



      gateway = new SerialModemGateway( "SER LIQUIDO", modemSerialPort, 38400, "MultiTech","GPRS" );

      gateway.setInbound(true);
      gateway.setOutbound(true);
    //  gateway.getATHandler().setStorageLocations("SMMTMESR");

      service = new Service();
      service.addGateway( gateway );
      service.startService();

      //service.getSettings().SERIAL_POLLING = true;
      // service.getSettings().SERIAL_POLLING_INTERVAL = 30;

      //service.setInboundNotification(this);
      service.setInboundMessageNotification(this);
      logger.info( "MODEM: " + gateway.getManufacturer() );
      logger.info( "MODEL: " + gateway.getModel() );
      logger.info( "SERIAL: " + gateway.getSerialNo() );
      logger.info( "SIGNAL: " + gateway.getSignalLevel() );
      logger.info( "BATTERY: " + gateway.getBatteryLevel() );

      logger.info( "**************************************************");
      logger.info( "***********MODEM INCIADO OK***********************");
      logger.info( "**************************************************");

      Settings s = service.getSettings();
      Logger l = Logger.getLogger("smslib");
      l.setLevel(Level.ERROR);


    }    catch (Exception e) {

      logger.error( "**************************************************");
      logger.error( "***********PROBLEMA AL INICIAR MODEM**************");
      logger.error( "**************************************************");

      logger.error("ERROR: ", e);

      System.exit(0);
    }


  }


  // TODO reimplementar correctamente este metodo
  public JSONObject[] getMessages(){

    JSONObject[] messages = null;

    try {


      messagesQueued = service.readMessages( inbox, MessageClasses.ALL);

      logger.info("MESSAGE POOL: " + messagesQueued);

      messages = new JSONObject[messagesQueued];

      for(int i = 0 ; i < inbox.size(); i ++){

        InboundMessage newMessage = (InboundMessage) inbox.get(i);
        messages[i] = new JSONObject();

        logger.trace("MESSAGE: \n" + newMessage);

        try {


          messages[i].put("date", newMessage.getDate());
          messages[i].put("id", newMessage.getId());
          messages[i].put("originator", newMessage.getOriginator());
          messages[i].put("text", newMessage.getText())

          if(deleteMessageOnReceive) service.deleteMessage(newMessage);

          if(!messages[i].get("originator").equals("")) receiver.modemEvent(messages[i]);

        } catch (JSONException e) {
          logger.warn(e);
          e.printStackTrace();
        }
      }

    } catch (TimeoutException e) {
      logger.error(e);
    } catch (GatewayException e) {
      logger.error(e);
    } catch (IOException e) {
      logger.error(e);
    } catch (InterruptedException e) {
      logger.error(e);
    }

    return messages;
  }   


  /**
   * Envio de mensajes desde la aplicacion hacia el exterior
   * @param msg el mensaje que quiero enviar
   */
  public void sendMessage(OutboundMessage msg){

    logger.info("ENVIANDO MENSAJE");   
    logger.info("DEST: " + msg.getRecipient());
    logger.info("MSG: " + msg.getText());


    // MSG:
    // GTW: SER LIQUIDO: CMS Error 50: Quit retrying, message lost...
    // NO HAY CREDITO

    if(usingModem){

      try {
        service.sendMessage(msg);     
        // TODO disparar exception if FAILED
        logger.error( msg.getMessageStatus());
       
      } catch (Exception e) {
        logger.error( "ERROR: No se pudo enviar el mensaje", e);       
      }
    }
  }


  /**
   * Callback llamado por el modem cuando recibe un nuevo SMS
   */
  public void process(AGateway service, MessageTypes msgType, InboundMessage inboundMessage) {
 
    /*
    if (msgType == MessageTypes.INBOUND) System.out.println(">>> New Inbound message detected from Gateway: " + gateway.getGatewayId());
    else if (msgType == MessageTypes.STATUSREPORT) System.out.println(">>> New Inbound Status Report message detected from Gateway: " + gateway.getGatewayId());
    System.out.println(inboundMessage);
    */
   
    JSONObject message = new JSONObject();

   

    if (msgType == MessageTypes.INBOUND){
   
      logger.info("NEW MESSAGE RECEIVED: " + inboundMessage);
     
     
      try {

        message.put("date", inboundMessage.getDate());
        message.put("id", inboundMessage.getId());
        message.put("originator", inboundMessage.getOriginator());
        message.put("text", inboundMessage.getText())

        if(true) service.deleteMessage(inboundMessage);

        receiver.modemEvent(message);

      } catch (Exception e) { 
        logger.error("ERROR PARSING MESSAGE: " ,e);     
      }
    }else{
     
      logger.info("NEW MESSAGE: " + inboundMessage);
     
     
    }
   
   
  }


  /**
   * Metodo utilizado para enviar un mensaje falso
   * i.e: sin que el modem este conectado
   * (PARA TESTING)
   */
  public void dummyMessage(){

    JSONObject message = new JSONObject();

    logger.info("CREATING DUMMY MESSAGE");

    try {

      message.put("date", "Tue Jun 22 20:22:21 BRT 2010");
      message.put("id", "");
      message.put("originator", ConsoleIO.prompt("NUMERO DE TELEFONO: "));
      message.put("text", ConsoleIO.prompt("NOMBRE: "))

      receiver.modemEvent(message);

    } catch (Exception e) { 

      logger.error("ERROR PARSING MESSAGE: " ,e);     

    }
  }
}
TOP

Related Classes of servers.Modem

TOP
Copyright © 2018 www.massapi.com. All rights reserved.
All source code are property of their respective owners. Java is a trademark of Sun Microsystems, Inc and owned by ORACLE Inc. Contact coftware#gmail.com.