Cellular library for MTS Socket Modem Arduino Shield devices from Multi-Tech Systems

Dependents:   mtsas mtsas mtsas mtsas

Cellular/EasyIP.cpp

Committer:
Vanger
Date:
2014-06-30
Revision:
27:ec44d5a9544f
Parent:
26:2b769ed8de4f
Child:
28:f93d7b3f7c2e

File content as of revision 27:ec44d5a9544f:

// This is a template from UIP.cpp for now, will modify code and implement it as I go



#include "mbed.h"
#include "EasyIP.h"
#include "MTSText.h"
#include "MTSLog.h"
#include "CellUtils.h"



using namespace mts;

EasyIP::EasyIP(Radio type)
{
    //Not sure how the construction process is done, 
    //but assuming it works for both EasyIP and UIP the same way.
    this->type = type;
    io = NULL;
    dcd = NULL;
    dtr = NULL;
    resetLine = NULL;
    echoMode = true;
    pppConnected = false;
    socketMode = TCP;
    socketOpened = false;
    socketCloseable = true;
    local_port = 0;
    local_address = "";
    host_port = 0;
}

EasyIP::~EasyIP()
{
    //Same reasoning for the destructor as the constructor,
    //assuming it works for UIP, it will work for EasyIP
    if (dtr != NULL) {
        dtr->write(1);
    }
    
    delete dcd;
    delete dtr;
    delete resetLine;
}

//Initializes the MTS IO Buffer
bool EasyIP::init(MTSBufferedIO* io)
{
    if (! Cellular::init(io)) {
        return false;
    }

    logDebug("radio type: %s", Cellular::getRadioNames(type).c_str());
    return true;
}

bool EasyIP::connect()
{
    //Check if socket is open
    //flag stored in Cellular.h
    if(socketOpened) {
        return true;
    }

    //Check if already connected
    //by calling the function isConnected() in EasyIP.cpp
    if(isConnected()) {
        return true;
    }
    //Create an mbed timer object
    Timer tmr;

    //Check Registration: AT+CREG? == 0,1
    //(Does the AT command inside Cellular class)
    tmr.start();
    do {
        Registration registration = getRegistration();
        if(registration != REGISTERED) {
            logTrace("Not Registered [%d] ... waiting", (int)registration);
            wait(1);
        } else {
            break;
        }
    } while(tmr.read() < 30);

    //Check RSSI: AT+CSQ
    //Does the command inside Cellular
    tmr.reset();
    do {
        int rssi = getSignalStrength();
        logDebug("Signal strength: %d", rssi);
        if(rssi == 99) {
            logTrace("No Signal ... waiting");
            wait(1);
        } else {
            break;
        }
    } while(tmr.read() < 30);

    //Similar to AT#CONNECTIONSTART: Make a PPP connection
    if (type == MTSMC_H5 || type == MTSMC_G3) {
        logDebug("Making PPP Connection Attempt. APN[%s]", apn.c_str());
    } else {
        logDebug("Making PPP Connection Attempt");
    }
    //The main thing going on; Sends the AT command to start a connection
    //Assuming context is already stored in the modem...If not, will need to set context from classes/data
    std::string pppResult = sendCommand("AT#SGACT=1,1", 120000);
  
    if(pppResult.find("OK") != std::string::npos) {
        std::vector<std::string> parts = Text::split(pppResult, "\r\n");
        if(parts.size() >= 2) {
            parts = Text::split(parts[1], " ");
            local_address = parts[1];
        }
        logInfo("PPP Connection Established: IP[%s]", local_address.c_str());
        pppConnected = true;

    } else {
        pppConnected = false;
    }

    return pppConnected;
}

void EasyIP::disconnect()
{
    //AT#SGACT=1,0: Close a PPP connection
    logDebug("Closing PPP Connection");

    if(socketOpened) {
        close(); //Calls another EasyIP 
                 //function to close socket before disconnect
    }
    //Sends AT#SGACT=1,0 command
    
    if(sendBasicCommand("AT#SGACT=1,0", 10000) == MTS_SUCCESS) {
        logDebug("Successfully closed PPP Connection");
    } else {
        logError("Closing PPP Connection. Continuing ...");
    }
    pppConnected = false; //We can do this since the cell will drop their side after timeout
}

bool EasyIP::isConnected()
{
    
    
    
    return pppConnected;
}
//Binds the socket to a specific port if able
bool EasyIP::bind(unsigned int port)
{
   
   
    return true;
}

bool EasyIP::open(const std::string& address, unsigned int port, Mode mode)
{
   
    return socketOpened;
}

bool EasyIP::isOpen()
{
    
    return socketOpened;
}

bool EasyIP::close()
{
    
    return true;
}

int EasyIP::read(char* data, int max, int timeout)
{
   
    return 1;
}

int EasyIP::write(const char* data, int length, int timeout)
{
    
    return 1;
}

unsigned int EasyIP::readable()
{
    
    return io->readable();
}

unsigned int EasyIP::writeable()
{
    

    return io->writeable();
}

bool EasyIP::setDeviceIP(std::string address)
{
    if (address.compare("DHCP") == 0) {
        return true;
    } else {
        logWarning("Radio does not support static IPs, using DHCP.\n\r");
        return false;
    }
}

Code EasyIP::setApn(const std::string& apn)
{
    if (type == MTSMC_H5 || type == MTSMC_G3) {
         //Set IP,PPP,IPv6
        Code code = sendBasicCommand("AT+CGDCONT=1,PPP," + apn, 1000);
        if (code != MTS_SUCCESS) {
            return code;
        }
        this->apn = apn;
        return code; //This will return MTS_SUCCESS
    } else {
        logInfo("CDMA radios don't need an APN");
        return MTS_SUCCESS;
    }
}

void EasyIP::reset()
{
}

std::string EasyIP::getDeviceIP()
{
    return local_address;
}

//Turns off echo when it receives a 1, turns on when it receives anything else
Code EasyIP::echo(bool state)
{
    Code code;
    if (state) {
        code = sendBasicCommand("ATE0", 1000);
        echoMode = (code == MTS_SUCCESS) ? false : echoMode;
    } else {
        code = sendBasicCommand("ATE1", 1000);
        echoMode = (code == MTS_SUCCESS) ? true : echoMode;
    }
    return code;
}

bool EasyIP::ping(const std::string& address)
{
    char buffer[256] = {0};
    std::vector<std::string> parts;
    int pingsRec=0;
    int TTL=0;
    int Timeout=0;
    
    //Format parameters for sending to radio
    sprintf(buffer, "AT#PING=%s,1,32,%d", address.c_str(), (10*PINGDELAY));
    
    for(int pngs=0; pngs<PINGNUM; pngs++) {
        std::string response = sendCommand(buffer, (PINGDELAY*1500)); //Send 1 ping
        if(response.empty()) continue; //Skip current loop if send command fails
        parts = Text::split(response, "\r\n");
        parts = Text::split(parts[1], ",");
        //Parse TTL and Timeout values
        Timeout = std::atoi(parts[2].c_str());
        TTL = std::atoi(parts[3].c_str());
                
        if((Timeout < 600) && (TTL < 255)) {
            pingsRec++;
        }
    }   //Success if less than 50% packet loss
        if( ((pingsRec/PINGNUM)>= 0.5) ) {
            return true;
        }
    return false;
}

//Pass 1 to enable socket closeable
//Pass 0 to disable socket closeable
Code EasyIP::setSocketCloseable(bool enabled)
{

    return MTS_SUCCESS;
}