开关机订阅

#include "PdtSubscriptionHandler.hxx"
#include "PdtSipApp.hxx"

#include <iostream>

#include "resip/stack/PSip.hxx"
#include "rutil/Data.hxx"
#include "resip/stack/NameAddr.hxx"
#include "resip/stack/PlainContents.hxx"

#include "CallData.h"
#include "PdtCommService.h"
#include "CallMsgHandler.h"
#include "TrunkedControllerRegistration.h"
#include "GPSData3UPDUModule.h"
#include "GPS3UModule.h"
#include "GPSData3UModule.h"
#include "GPSUnsubscribeMudule.h"

#include "PropRegResponseModule.h"

#include "resip/stack/PdtMapXml.hxx"
#include "CallQualification.h"
#include <map>
#include "TimerData.h"

using namespace resip;
using namespace std;
#define RESIPROCATE_SUBSYSTEM resip::Subsystem::APP

#define VIRTUAL_SOURCEID 0x1E240
#define VIRTUAL_SUBTIME 1800
#define VIRTUAL_PERIOD 30

struct OnGoingServer
{
    struct Server
    {
        SipMessage *m_subscriptMsg;
        uint32_t m_waitOpTime;            //record the time of waiting server     ms

        uint32_t m_durationTime;
        uint32_t m_periodTime;
        SPATimer *m_spatimer;
        Server()
        {
        }
        Server(SipMessage *subscriptMsg)
        {
            m_subscriptMsg = (SipMessage*)subscriptMsg->clone();
            m_waitOpTime = 0;
            
            m_durationTime = subscriptMsg->header(h_Expires).value();
            m_periodTime = subscriptMsg->header(h_MinExpires).value();
        }
        ~Server()
        {
            delete m_subscriptMsg;
        }
    };

    struct GPSServer
    {
        map<uint32_t, list<Server*>> mOngoingMap;    //    the frist is target ms

        GPSServer()
        {
        }
        ~GPSServer()
        {
            std::map<uint32_t, std::list<Server*>>::iterator iter = mOngoingMap.begin();
            for(;iter != mOngoingMap.end(); iter++)
            {
                std::list<Server*>::iterator lIter = iter->second.begin();
                for(; lIter != iter->second.end(); lIter++)
                {
                    delete *lIter;
                }
            }
        }
        
    
        list<bool> timerAdd(uint32_t radioId)
        {
            list<bool> procesPermision;
        
            list<Server*>::iterator iter = mOngoingMap[radioId].begin();
            for(; iter != mOngoingMap[radioId].end(); iter++)
            {
                (*iter)->m_waitOpTime += 180;    //per 3U pass 180ms
    
                if((*iter)->m_waitOpTime >= ((*iter)->m_durationTime * 1000))
                {
                    (*iter)->m_waitOpTime = -1;
                }
                else if((*iter)->m_waitOpTime >= ((*iter)->m_periodTime * 1000))
                {
                    (*iter)->m_waitOpTime = 0;
                }
                
                procesPermision.push_back((*iter)->m_waitOpTime == 0 ? true : false);
            }
            return procesPermision;
        }
        void ClearGpsTimeoutServer(uint32_t radioId)
        {
            list<Server*>::iterator iter = mOngoingMap[radioId].begin();
            for(; iter != mOngoingMap[radioId].end(); iter++)
            {
                if((*iter)->m_waitOpTime == -1)
                {
                    delete (*iter);
                    iter = mOngoingMap[radioId].erase(iter);
                }
            }
        }
    
        std::list<uint32_t> getSrcId(uint32_t radioId)
        {
            std::list<Server*>tmpList = mOngoingMap[radioId];
            std::list<uint32_t> ret;
            for(std::list<Server*>::iterator iter = tmpList.begin(); iter != tmpList.end(); iter++)
            {
                Data tmpSrcId = (*iter)->m_subscriptMsg->header(h_From).uri().host();
                uint32_t srcId= PSip::str2Int(tmpSrcId.getBuf(-1));
                ret.push_back(srcId);
            }
            return ret;
        }
        std::list<uint32_t> operator[](uint32_t radioId)
        {
            return getSrcId(radioId);
        }    
        void addServer(SipMessage *subRequest)
        {
            Data tarId = subRequest->header(h_RequestLine).uri().host();
            uint32_t radioId = PSip::str2Int(tarId.getBuf(-1)); 
            mOngoingMap[radioId].push_back(new Server(subRequest));
    
            
            Data tmpSrcId_ = subRequest->header(h_From).uri().host();
            uint32_t tmpSrcId = PSip::str2Int(tmpSrcId_.getBuf(-1));    
        }
        void delServer(SipMessage *subRequest)
        {
            Data tmpTarId = subRequest->header(h_RequestLine).uri().host();
            Data tmpSrcId = subRequest->header(h_From).uri().host();
    
            uint32_t radioId = PSip::str2Int(tmpTarId.getBuf(-1));
            uint32_t dispatchId = PSip::str2Int(tmpSrcId.getBuf(-1));
            
            std::list<Server*>&tmpList = mOngoingMap[radioId];
            std::list<Server*>::iterator iter = tmpList.begin();
            for(; iter != tmpList.end();)
            {
                Data tmpSrcId = (*iter)->m_subscriptMsg->header(h_From).uri().host();
                uint32_t srcId= PSip::str2Int(tmpSrcId.getBuf(-1));
                if(dispatchId && (srcId != dispatchId))
                {    
                    iter++;
                }
                else
                {    
                    delete *iter;
                    iter = tmpList.erase(iter);
                }
            }
        }
    };


    struct MergeGroupServer
    {
        typedef map<uint32_t, CallData::UniteGroup*> UnitGroup;
        UnitGroup &m_uniteGroupMap;
        map<uint32_t, list<Server*>> mOngoingMap;    //    the frist is target ms

        MergeGroupServer(UnitGroup &unitGroupMap):m_uniteGroupMap(unitGroupMap)
        {
        }
        ~MergeGroupServer()
        {
        }

        CallData::UniteGroup* operator[](uint32_t subGroupId)
        {
            for(UnitGroup::iterator iter = m_uniteGroupMap.begin(); iter != m_uniteGroupMap.end(); iter++)
            {
                for(int i = 0; i < iter->second->memberNum; i++)
                {
                    if(subGroupId == (iter->second->groupMemberId)[i])
                    {
                        return iter->second;
                    }
                }
            }
        }
    };

    struct OpenOffServer
    {
        map<uint32_t, list<Server*>> mOngoingMap;    //    the frist is target ms
        void insertData(uint32_t key, SipMessage *subscriptMsg, TCContext* tcContext)
        {
            Server *insertid  = new Server(subscriptMsg);
            mOngoingMap[key].push_back(insertid);

            TimerData *timerData = new TimerData(TimerData::PDT_SIP_GET_OPENOFF_TIMER);
            Data &tmp = *(const_cast<Data*>(&(subscriptMsg->header(h_RequestLine).uri().host())));
            uint32_t targetID = PSip::str2Int(tmp.data(), tmp.size());
            Data &tmp1 = *(const_cast<Data*>(&(subscriptMsg->header(h_From).uri().host())));
            uint32_t sourceID = PSip::str2Int(tmp1.data(), tmp1.size());
            
            timerData->setSourceId(sourceID);
            timerData->setTargetId(targetID);
            insertid->m_spatimer = tcContext->service->startTimer(insertid->m_periodTime, timerData);
        }
    };

    OnGoingServer(MergeGroupServer::UnitGroup &unitGroupMap):m_MergeGroupServer(unitGroupMap)
    {
    }
    ~OnGoingServer()
    {
    }

    OpenOffServer m_OpenoffServer;
    GPSServer m_GpsServer;
    MergeGroupServer m_MergeGroupServer;
};

PdtSubscriptionHandler::PdtSubscriptionHandler(PdtSipApp* sipApp)
: mSipApp(sipApp)
, mDum(&sipApp->mDum)
, mUasAors(sipApp->mUasAors)
, mUacRecord(*mUasAors.front())
{
    mDum->addServerSubscriptionHandler(Data("gg"), this);
    mDum->addClientSubscriptionHandler(Data("gg"), this);
    mDum->addServerSubscriptionHandler(Data("get-gps"), this);
    mDum->addClientSubscriptionHandler(Data("get-gps"), this);
    
    mDum->addServerSubscriptionHandler(Data("mg"), this);
    mDum->addClientSubscriptionHandler(Data("mg"), this);
    mDum->addServerSubscriptionHandler(Data("merge_group_get"), this);
    mDum->addClientSubscriptionHandler(Data("merge_group_get"), this);

    mDum->addServerSubscriptionHandler(Data("ss"), this);
    mDum->addClientSubscriptionHandler(Data("ss"), this);
    mDum->addServerSubscriptionHandler(Data("state_sub"), this);
    mDum->addClientSubscriptionHandler(Data("state_sub"), this);
    
    mOngoingServer = new OnGoingServer(mSipApp->mCallMsgHandler->getCallQualification()->uniteGroupMap);
}

PdtSubscriptionHandler::~PdtSubscriptionHandler()
{
    delete mOngoingServer;
}

void PdtSubscriptionHandler::timerExpire(SPATimer *timer)
{
    TimerData *timerData = (TimerData*)timer->getCtx();
    uint32_t source = timerData->getSourceId();
    uint32_t target = timerData->getTargetId();

    switch(timerData->getType())
    {
        case TimerData::PDT_SIP_GET_GPS_TIMER:
        {
            break;
        }
        case TimerData::PDT_SIP_GET_MERGEGROUP_TIMER:
        {
            break;
        }
        case TimerData::PDT_SIP_GET_OPENOFF_TIMER:
        {
            static int cnt = 0;
            if(++cnt > 1)
            {
                return;
            }
            RegistrationMap_t regMap = mSipApp->mTcContext->registration->getRegisterMap();    
            
            uint32_t tar = source;
            string tmpTarget = PSip::convertId2DialNum(to_string(tar).c_str(), PSip::NumberType::INDIVIDUAL, PSip::SupplementType::SITENAME);
            
            NameAddr nameAddrTarget(tmpTarget.c_str(), false, true);        
            string tmpId;            
            tmpId = "p:";
            tmpId += to_string(target);
            NameAddr fromId(tmpId.c_str(), false, true);
            string tmpId1;
            tmpId1 = "p:";
            tmpId1 += to_string(source);
            NameAddr toId(tmpId1.c_str(), false, true);
            
            auto notifyMsg = mDum->makeNotify(nameAddrTarget, true, fromId, toId);
            PdtMapXml info(true, PdtMapXml::RG_TUPLE);
            info.tuple().mRGTuple.RG = regMap.find(target) != regMap.end();

            notifyMsg->setContents(&info);
            mDum->send(notifyMsg);

            break;
        }
    }
}

void PdtSubscriptionHandler::handle(CallData*& callData)
{
    uint32_t src = callData->getSourceID();
    uint32_t tar = callData->getTargetId();
    
    uint32_t siteId = callData->getOrigSiteID();

    //Because the src is the dispatching and the tar is the Ms
    /*
    if(mUacRecord.isMyUas(tar, callData->isGroupService))
    {
        return;
    }    
    */

    switch(callData->getOpcode())
    {        
        case OPCODE::GPSRequestPDU:
        {
            break;
            string tmpId;
            
            tmpId = "p:";
            tmpId += to_string(tar);
            NameAddr target(tmpId.c_str());

            tmpId = "p:";
            tmpId += to_string(src);
            NameAddr source(tmpId.c_str());

            string dialNum = PSip::convertId2DialNum((to_string(tar)).c_str(), PSip::NumberType::INDIVIDUAL, PSip::SupplementType::SITENAME);

            GPSRequestPDU* gpsRequestPdu = (GPSRequestPDU*)(const_cast<MASNType*>(callData->getPdu()));

            uint32_t durationTime = gpsRequestPdu->m_payload.m_interval.getValue();
            uint32_t periodTime = gpsRequestPdu->m_payload.m_intervalValue.getValue();
            
            auto subMsg = mDum->makeSubscription(target, source, durationTime, periodTime, Data("gg"), true);
            subMsg->header(h_RequestLine).setPSipUri(Data(dialNum.c_str()));
            subMsg->header(h_To).toUriFormat() = NameAddr::SAME_AS_REQUEST_URI;

            GPSRequestPDU *gpsReqPdu = (GPSRequestPDU*)const_cast<MASNType *>(callData->getPdu());

            //mOngoingServer->addServer(callData, &(*subMsg));

            callData = NULL;
                
            mDum->send(subMsg);
            break;
        }
        case OPCODE::GPS3U:
        {
            //GPS3U Data is send every 180 ms
            GPS3UPDU *gpsData;
            gpsData = (GPS3UPDU*)(const_cast<MASNType *>(callData->getPdu()));

            /*
                EW         :    0    G
                NDEG    :    0    FE
                NMINmm    :    0    DCBA98
                NMINF    :    0    7654321        1    GFE
                EDEG    :    1    DCB
                EMINmm    :    1    A98765
                m_EMINF :     1    4321        2    GFEDCB
                
                GFED CBA9 8765 4321
                0000 0000 0000 0000
            */
            /*
            uint16_t sendData[3] = { 0 };
            sendData[0] |= (gpsData->m_payload.m_EW & 0x1) << 15;
            sendData[0] |= (gpsData->m_payload.m_NDEG & 0x3) << 13;
            sendData[0] |= (gpsData->m_payload.m_NMINmm & 0x3f) << 7;
            sendData[0] |= (gpsData->m_payload.m_NMINF & 0x3f8) >> 3;
            sendData[1] |= (gpsData->m_payload.m_NMINF & 0x7) << 13;
            sendData[1] |= (gpsData->m_payload.m_EDEG & 0x7) << 10;
            sendData[1] |= (gpsData->m_payload.m_EMINmm & 0x3f) << 4;
            sendData[1] |= (gpsData->m_payload.m_EMINF & 0x3c0) >> 6;
            sendData[2] |= (gpsData->m_payload.m_EMINF & 0x3f) << 10;

            char * sendStr = (char *)sendData;
            */    

            src = gpsData->m_payload.m_radioId.getValue();

            string tmpId;            
            tmpId = "p:";
            tmpId += to_string(src);
            NameAddr fromId(tmpId.c_str(), false, true);

            string sendStr = "";
            
            uint8_t* dataBuf = gpsData->m_payload.m_aiData.getValue();
            int dataBufLen = gpsData->m_payload.m_aiData.getStringLen();

            for(int i = 0; i < dataBufLen; i++)
            {
                int tmp = dataBuf[i];
                sendStr += PSip::int2Bit(tmp);
            }
            
            PlainContents *msgContent = new PlainContents(Data(sendStr.c_str()), Mime("a", "bn", true), true);

            list<bool>procesPermit = mOngoingServer->m_GpsServer.timerAdd(src);
            list<uint32_t> tarList = mOngoingServer->m_GpsServer.getSrcId(src);

            list<bool>::iterator permitIter = procesPermit.begin();
            list<uint32_t>::iterator iter = tarList.begin();
            for(; iter!= tarList.end(); iter++, permitIter++)
            {    
                if(*permitIter)
                {

                    cout<<"\n===============SEND=DATA===================\n";
                    tar = *iter;    
                    tmpId = to_string(tar);
    
                    string tmpTarget = PSip::convertId2DialNum(to_string(tar).c_str(), PSip::NumberType::INDIVIDUAL, PSip::SupplementType::SITENAME);
    
                    NameAddr target(tmpTarget.c_str(), false, true);
                    
                    tmpId = "p:";
                    tmpId += to_string(tar);
                    NameAddr toId(tmpId.c_str(), false, true);
    
                    auto notifyMsg = mDum->makeNotify(target, true, fromId, toId, (Contents*)msgContent);
                    mDum->send(notifyMsg);
                }
            }
            mOngoingServer->m_GpsServer.ClearGpsTimeoutServer(src);
            
            delete msgContent;
            break;
        }
        case OPCODE::GPSUnsubscribePDU:
        {
            /*
            GPSUnsubscribePDU *unsubPdu = (GPSUnsubscribePDU *)const_cast<MASNType*>(callData->getPdu());

            SipMessage* oldSub = mOngoingServer->m_GpsServer->exsistServer(callData);
            
            if(oldSub)
            {
                //Send    Interrupt    MSG
                //oldSub->remove(h_Accept);
                oldSub->remove(h_MinExpires);
                //oldSub->remove(h_Contact);
                oldSub->header(h_Expires).value() = 0;

                std::shared_ptr<SipMessage> intertuptMsg(new SipMessage);
                *intertuptMsg = *oldSub;
                mDum->send(intertuptMsg);
                mOngoingServer->m_GpsServer->deleteServer(callData);
                delete callData;
                callData = NULL;
            }
            */
            /*
            GPSUnsubscribePDU *unSubPdu = (GPSUnsubscribePDU *)const_cast<MASNType*>(callData->getPdu());

            cout<<"\n================================================\n"
                <<"\n target : "<<callData->getTargetId()
                <<"\n source : "<<callData->getSourceID()
                <<"\n m_functionType : "<<unSubPdu->m_payload.m_functionType.getValue()
                <<"\n m_radioId : "<<unSubPdu->m_payload.m_radioId.getValue()
                <<"\n m_subscribe : "<<unSubPdu->m_payload.m_subscribe.getValue()
                <<"\n m_VRCAddress : "<<unSubPdu->m_payload.m_VRCAddress.getValue()<<endl;
            */
            break;
        }
        case OPCODE::GPSInfoPDU:
        case OPCODE::BcastGPSPDU:
        case OPCODE::GPSResponsePDU:
        case OPCODE::GPSPollingDataPDU:
            break;
        case OPCODE::uniteGroupRequestPDU:
        {
            break;
        }
        case OPCODE::propRegRequestPDU:
        {
            
        }
        default:
            break;
    }
}


void PdtSubscriptionHandler::onUpdatePending(resip::ClientSubscriptionHandle, const resip::SipMessage& notify, bool outOfOrder)
{
    
}

void PdtSubscriptionHandler::onUpdateActive(resip::ClientSubscriptionHandle, const resip::SipMessage& notify, bool outOfOrder)    
{
    
}

//unknown Subscription-State value
void PdtSubscriptionHandler::onUpdateExtension(resip::ClientSubscriptionHandle, const resip::SipMessage& notify, bool outOfOrder)
{
    
}

int PdtSubscriptionHandler::onRequestRetry(resip::ClientSubscriptionHandle, int retrySeconds, const resip::SipMessage& notify)
{
    
}

//subscription can be ended through a notify or a failure response.
void PdtSubscriptionHandler::onTerminated(resip::ClientSubscriptionHandle, const resip::SipMessage* msg)
{
    
}   
//not sure if this has any value - can be called for either a 200/SUBSCRIBE or a NOTIFY - whichever arrives first
void PdtSubscriptionHandler::onNewSubscription(resip::ClientSubscriptionHandle, const resip::SipMessage& notify)
{
    //NOT USE!!!!!!!!!!!!!!
    cout<<"\n===================================================\n"
        <<"\n    recv the notify from other tc and prepare to send to the my phonen"<<endl;

    std::shared_ptr<SipMessage> response200(new SipMessage);
    Helper::makeResponse(*response200, notify, 200);
    mDum->send(response200);

    PlainContents *msgContent = (PlainContents *)notify.getContents();

    char *gpsData = msgContent->text().getBuf(-1);

    GPSData3UDataPDU *gps3UData = new GPSData3UDataPDU();
    CallData *callData = new CallData(mSipApp->getCallMsgHandler()->getTcContext(), mSipApp->getCallMsgHandler());

    uint32_t targetId;
    uint32_t sourceId;

    sourceId = PSip::str2Int(const_cast<Data *>(&notify.header(h_From).uri().host())->getBuf(-1));
    targetId = PSip::str2Int(const_cast<Data *>(&notify.header(h_To).uri().host())->getBuf(-1));

    gps3UData->m_payload.m_LDSAddress.setValue(targetId);
    gps3UData->m_payload.m_radioId.setValue(sourceId);
    gps3UData->m_payload.m_NS.setValue(PSip::bit2Int(gpsData, 1));
    gps3UData->m_payload.m_EW.setValue(PSip::bit2Int(gpsData + 1, 1));
    gps3UData->m_payload.m_NDEG.setValue(PSip::bit2Int(gpsData + 2, 2));
    gps3UData->m_payload.m_NMINmm.setValue(PSip::bit2Int(gpsData + 4, 6));
    gps3UData->m_payload.m_NMINF.setValue(PSip::bit2Int(gpsData + 10, 10));
    gps3UData->m_payload.m_EDEG.setValue(PSip::bit2Int(gpsData + 20, 3));
    gps3UData->m_payload.m_EMINmm.setValue(PSip::bit2Int(gpsData + 23, 6));
    gps3UData->m_payload.m_EMINF.setValue(PSip::bit2Int(gpsData + 29, 10));

    callData->setOpcode(OPCODE::GPSData3UPDU);
    callData->qualificationResult = true;
    callData->setSourceId(sourceId);
    callData->setTargetId(targetId);
    
    callData->tgtRegRecord = new SubscriberRegistrationData;
    callData->tgtRegRecord->activityFlag = true;

    callData->qualificationResult = true;
    callData->qualificationReason = REASONCODE::REASONCODE_ENUM::reg_accepted;
    callData->registrationResult = RegistrationResult::REG_FAIL; 
    callData->registrationReason = REASONCODE::unknown;
    callData->gpsFun = GpsFunType::GPS_PERIODIC_POLL;
    callData->setUdtStoreForwardEnable(true);
    callData->m_isAzCallData = false;


    RegistrationMap_t regMap = mSipApp->getCallMsgHandler()->getTcContext()->registration->getRegisterMap();            
    int mapSize;
    mapSize = regMap.size();
    if(mapSize <= 0)
    {
        return;
    }
    
    uint32_t *siteId = new uint32_t[mapSize];        
    for(int i = 0; i < mapSize; siteId[i++] = 0);
    
    //store siteId with Hash to avoid storing the same value
    for(RegistrationMap_t::iterator regIter = regMap.begin(); regIter != regMap.end(); regIter++)
    {                
        int tmpSite = regIter->second->mySite;
        bool saveFlag = true;
        while(siteId[tmpSite % mapSize] != 0)
        {
            if(siteId[tmpSite % mapSize] == regIter->second->mySite)
            {
                saveFlag = false;
                break;
            }
            tmpSite++;
        }
        if(saveFlag)
        {
            siteId[tmpSite % mapSize] = regIter->second->mySite;
        }
    }

    
    for(int i = 0; i < mapSize; i++)
    {
        if(siteId[i])
        {
            PdtCommService::buildDescriptor(&(gps3UData->m_descriptor), OPCODE::GPSData3UPDU, siteId[i]);
            gps3UData->m_payload.m_requestId.setValue(gps3UData->m_descriptor.m_srcUniqueID.getValue());
            
            callData->setPdu((MASNType*)(gps3UData->clone()));
            callData->setOrigSiteID(siteId[i]);
            callData->tgtRegRecord->mySite = siteId[i];
    
            mSipApp->getCallMsgHandler()->processCallData(callData->clone(), true);
        }
    }
    delete []siteId;
    delete callData;
    delete gps3UData;
    callData = NULL;
}

/// called to allow app to adorn a message.
void PdtSubscriptionHandler::onReadyToSend(resip::ClientSubscriptionHandle, resip::SipMessage& msg)
{
    
}
void PdtSubscriptionHandler::onNotifyNotReceived(resip::ClientSubscriptionHandle)
{
    
}

/// Called when a TCP or TLS flow to the server has terminated.  This can be caused by socket
/// errors, or missing CRLF keep alives pong responses from the server.
//  Called only if clientOutbound is enabled on the UserProfile and the first hop server 
/// supports RFC5626 (outbound).
/// Default implementation is to re-form the subscription using a new flow
void PdtSubscriptionHandler::onFlowTerminated(resip::ClientSubscriptionHandle)
{
    
}

void PdtSubscriptionHandler::onNewSubscription(resip::ServerSubscriptionHandle serverSubscriptionHandle, const resip::SipMessage& sub)
{
    Data event = sub.header(h_Event).value();

    enum FUNCTYPE{ERROR, GPS, UNITGROUP, STATESUB};

    int funcType = FUNCTYPE::ERROR;

    if(event == Data(

"gg") || event == Data(

"get-gps"))
    {
        funcType = FUNCTYPE::GPS;
    }
    else if(event == Data(

"mg") || event == Data(

"merge_group_get"))
    {
        funcType = FUNCTYPE::UNITGROUP;
    }
    else if(event == Data(

"ss") || event == Data(

"state_sub"))
    {
        funcType = FUNCTYPE::STATESUB;
    }

    switch(funcType)
    {
        case FUNCTYPE::GPS:
        {
            handleGpsMsg(serverSubscriptionHandle, sub);
            break;
        }
        case FUNCTYPE::UNITGROUP:
        {
            handleUnitGroupMsg(serverSubscriptionHandle, sub);
            break;
        }
        case FUNCTYPE::STATESUB:
        {
            handleStatusSubMsg(serverSubscriptionHandle, sub);
            break;
        }
        default:
            break;
    }
}
void PdtSubscriptionHandler::onNewSubscriptionFromRefer(resip::ServerSubscriptionHandle, const resip::SipMessage& sub)
{
    
}
void PdtSubscriptionHandler::onRefresh(resip::ServerSubscriptionHandle, const resip::SipMessage& sub)
{
    
}
//called when a new document is Published that matches this subscription.  Also
//called when the publication is removed or expires, in which case contents 
//and attrs are passed as null pointers.
void PdtSubscriptionHandler::onPublished(resip::ServerSubscriptionHandle associated, 
resip::ServerPublicationHandle publication, 
const resip::Contents* contents,
const resip::SecurityAttributes* attrs)
{
    
}

void PdtSubscriptionHandler::onNotifyAccepted(resip::ServerSubscriptionHandle, const resip::SipMessage& msg)
{
    
}      
void PdtSubscriptionHandler::onNotifyRejected(resip::ServerSubscriptionHandle, const resip::SipMessage& msg)
{
    
}      

//called when this usage is destroyed for any reason. One of the following
//three methods will always be called before this, but this is the only
//method that MUST be implemented by a handler
void PdtSubscriptionHandler::onTerminated(resip::ServerSubscriptionHandle)
{
    
}

void PdtSubscriptionHandler::onReadyToSend(resip::ServerSubscriptionHandle, resip::SipMessage& msg)
{
    
}

//will be called when a NOTIFY is not delivered(with a usage terminating
//statusCode), or the Dialog is destroyed
void PdtSubscriptionHandler::onError(resip::ServerSubscriptionHandle, const resip::SipMessage& msg)
{
    
}      

//app can synchronously decorate terminating NOTIFY messages. The only
//graceful termination mechanism is expiration, but the client can
//explicity end a subscription with an Expires header of 0.
void PdtSubscriptionHandler::onExpiredByClient(resip::ServerSubscriptionHandle, const resip::SipMessage& sub, resip::SipMessage& notify)
{
    
}
void PdtSubscriptionHandler::onExpired(resip::ServerSubscriptionHandle, resip::SipMessage& notify)
{
    
}

/// Called when a TCP or TLS flow to the server has terminated.  This can be caused by socket
/// errors, or missing CRLF keep alives pong responses from the server.
//  Called only if clientOutbound is enabled on the UserProfile and the first hop server 
/// supports RFC5626 (outbound).
/// Default implementation is to tear down the subscription
void PdtSubscriptionHandler::onFlowTerminated(resip::ServerSubscriptionHandle)
{
    
}

void PdtSubscriptionHandler::getExpires(const resip::SipMessage &msg, UInt32 &expires, int &errorResponseCode)
{
    
}

bool PdtSubscriptionHandler::hasDefaultExpires() const
{

}

UInt32 PdtSubscriptionHandler::getDefaultExpires() const
{

}

bool PdtSubscriptionHandler::hasMinExpires() const
{

}

UInt32 PdtSubscriptionHandler::getMinExpires() const
{

}

bool PdtSubscriptionHandler::hasMaxExpires() const
{

}

UInt32 PdtSubscriptionHandler::getMaxExpires() const
{

}


void PdtSubscriptionHandler::handleGpsMsg(resip::ServerSubscriptionHandle &serverSubscriptionHandle, const resip::SipMessage &sub)
{
    ServerSubscription *serverManage = serverSubscriptionHandle.get();

    Data tarId = sub.header(h_RequestLine).uri().host();
    uint32_t tar = PSip::str2Int(tarId.getBuf(-1)); 

    uint32_t src = VIRTUAL_SOURCEID;

    uint32_t subTime = VIRTUAL_SUBTIME;
    uint32_t subPeriod = VIRTUAL_PERIOD;

    bool endFlag = false;
    
    if(sub.header(h_Expires).value())
    {
        if(mOngoingServer->m_GpsServer.mOngoingMap[tar].size() == 0)
        {
            CallData *callData = new CallData(mSipApp->getCallMsgHandler()->getTcContext(), mSipApp->getCallMsgHandler());
            GPSRequestPDU *gpsPdu = new GPSRequestPDU();
            
            gpsPdu->m_payload.m_VRCAddress.setValue(src);
            gpsPdu->m_payload.m_radioId.setValue(tar);
            gpsPdu->m_payload.m_interval.setValue(subTime);
            gpsPdu->m_payload.m_intervalValue.setValue(subPeriod);
            gpsPdu->m_payload.m_distance.setValue(0);
            gpsPdu->m_payload.m_distanceValue.setValue(0);
            gpsPdu->m_payload.m_ig.setValue(0);
            gpsPdu->m_payload.m_functionType.setValue(GpsFunType::GpsFunType_ENUM::GPS_PERIODIC_POLL);
            
            callData->setOpcode(OPCODE::GPSRequestPDU);
            callData->qualificationResult = true;
            callData->setSourceId(src);
            callData->setTargetId(tar);
            callData->channelMgrResult =  CallData::TARGET_BUSY;

            callData->tgtRegRecord = new SubscriberRegistrationData;
            callData->tgtRegRecord->activityFlag = true;

            callData->qualificationResult = true;
            callData->qualificationReason = REASONCODE::REASONCODE_ENUM::reg_accepted;
            callData->registrationResult = RegistrationResult::REG_FAIL; 
            callData->registrationReason = REASONCODE::unknown;
            callData->gpsFun = GpsFunType::GPS_PERIODIC_POLL;
            callData->setUdtStoreForwardEnable(true);
            callData->m_isAzCallData = false;

            RegistrationMap_t regMap = mSipApp->getCallMsgHandler()->getTcContext()->registration->getRegisterMap();            

            if(!regMap[callData->getTargetId()])
            {
                serverSubscriptionHandle.get()->send(serverSubscriptionHandle.get()->reject(406));
                return ;
            }
            uint32_t siteId = regMap[callData->getTargetId()]->mySite;

            PdtCommService::buildDescriptor(&(gpsPdu->m_descriptor), OPCODE::GPSRequestPDU, siteId);
            gpsPdu->m_payload.m_requestId.setValue(gpsPdu->m_descriptor.m_srcUniqueID.getValue());
            callData->setPdu((MASNType*)(gpsPdu));
            callData->setOrigSiteID(siteId);
            callData->tgtRegRecord->mySite = siteId;
            //callData->setPSip();

            mSipApp->getCallMsgHandler()->processCallData(callData, true);
        }
        mOngoingServer->m_GpsServer.addServer(const_cast<SipMessage*>(&sub));
    }
    else
    {
        //Interrupt GPS Server
        mOngoingServer->m_GpsServer.delServer(const_cast<SipMessage*>(&sub));

        if(mOngoingServer->m_GpsServer.mOngoingMap[tar].size() == 0)
        {
            CallData *callData = new CallData(mSipApp->getCallMsgHandler()->getTcContext(), mSipApp->getCallMsgHandler());
            GPSUnsubscribePDU *gpsPdu = new GPSUnsubscribePDU();
            
            gpsPdu->m_payload.m_VRCAddress.setValue(src);
            gpsPdu->m_payload.m_radioId.setValue(tar);

            gpsPdu->m_payload.m_functionType.setValue(GpsFunType::GpsFunType_ENUM::GPS_PERIODIC_POLL);
            gpsPdu->m_payload.m_subscribe.setValue(0);

            callData->setOpcode(OPCODE::GPSUnsubscribePDU);
            callData->setSourceId(src);
            callData->setTargetId(tar);
            callData->channelMgrResult =  CallData::TARGET_BUSY;

            callData->tgtRegRecord = new SubscriberRegistrationData;
            callData->tgtRegRecord->activityFlag = true;

            callData->qualificationResult = true;
            callData->qualificationReason = REASONCODE::REASONCODE_ENUM::reg_accepted;
            callData->registrationResult = RegistrationResult::REG_FAIL; 
            callData->registrationReason = REASONCODE::unknown;
            callData->gpsFun = GpsFunType::GPS_PERIODIC_POLL;
            callData->setUdtStoreForwardEnable(true);
            callData->m_isAzCallData = false;

            RegistrationMap_t regMap = mSipApp->getCallMsgHandler()->getTcContext()->registration->getRegisterMap();            
            uint32_t siteId = regMap[callData->getTargetId()]->mySite;

            PdtCommService::buildDescriptor(&(gpsPdu->m_descriptor), OPCODE::GPSUnsubscribePDU, siteId);
            gpsPdu->m_payload.m_requestId.setValue(gpsPdu->m_descriptor.m_srcUniqueID.getValue());
            
            callData->setPdu((MASNType*)(gpsPdu));
            callData->setOrigSiteID(siteId);
            callData->tgtRegRecord->mySite = siteId;
            //callData->setPSip();
            mSipApp->getCallMsgHandler()->processCallData(callData, true);

            endFlag = true;
        }
    }


    serverManage->send(serverManage->accept(200));
    if(endFlag)
    {
        serverManage->end();
    }
}

void PdtSubscriptionHandler::handleUnitGroupMsg(resip::ServerSubscriptionHandle &serverSubscriptionHandle, const resip::SipMessage &sub)
{    
    ServerSubscription *server = serverSubscriptionHandle.get();

    Data &tmp = *(const_cast<Data*>(&(sub.header(h_RequestLine).uri().host())));
    uint32_t subGroup = PSip::str2Int(tmp.data(), tmp.size());
    CallData::UniteGroup *unitGroup = mOngoingServer->m_MergeGroupServer[subGroup];

    PdtMapXml::MergeGroupTuple *content = new PdtMapXml::MergeGroupTuple;

    for(int i = 0; i < unitGroup->memberNum; i++)
    {
        content->MG.push_back(unitGroup->groupMemberId[i]);    
    }
    
    auto notifyMsg = server->neutralNotify();
    notifyMsg->setContents((Contents*)content);
    server->send(notifyMsg);

    delete content;
}

void PdtSubscriptionHandler::handleStatusSubMsg(resip::ServerSubscriptionHandle &serverSubscriptionHandle, const resip::SipMessage &sub)
{
    const Data &tmp = sub.header(h_RequestLine).uri().host();
    uint32_t targetID = PSip::str2Int(tmp.data(), tmp.size());

    mOngoingServer->m_OpenoffServer.insertData(targetID, const_cast<SipMessage*>(&sub), mSipApp->mTcContext);
}


 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值