//--------------------------------------------------------------------------------------------------
void pa_gnssSimu_ReportEvent
(
    void
)
{
    // Build the data for the user's event handler.
    pa_Gnss_Position_t* posDataPtr = le_mem_ForceAlloc(PositionEventDataPool);
    memcpy(posDataPtr, &GnssPositionData, sizeof(pa_Gnss_Position_t));
    le_event_ReportWithRefCounting(GnssEventId, posDataPtr);
    char* strDataPtr = le_mem_ForceAlloc(NmeaEventDataPool);
    strncpy(strDataPtr, "nmea", NMEA_STR_LEN);
    le_event_ReportWithRefCounting(NmeaEventId, strDataPtr);
}
Exemplo n.º 2
0
//--------------------------------------------------------------------------------------------------
void atmachinestring_AddInList
(
    le_dls_List_t *list,          ///< List of atmachinestring_t
    const char   **patternListPtr ///< List of pattern
)
{
    uint32_t i = 0;

    if (!patternListPtr) {
        return;
    }

    while(patternListPtr[i] != NULL) {
        atmachinestring_t* newStringPtr = le_mem_ForceAlloc(AtStringPool);

        LE_FATAL_IF(
            (strlen(patternListPtr[i])>ATSTRING_SIZE),
                    "%s is too long (%zd): Max size %d",
                    patternListPtr[i],strlen(patternListPtr[i]),ATSTRING_SIZE);

        strncpy(newStringPtr->line,patternListPtr[i],ATSTRING_SIZE);
        newStringPtr->line[ATSTRING_SIZE-1]='\0';

        newStringPtr->link = LE_DLS_LINK_INIT;
        le_dls_Queue(list,&(newStringPtr->link));
        i++;
    }
}
Exemplo n.º 3
0
//--------------------------------------------------------------------------------------------------
static le_result_t GetFirmwareItem
(
    json_t *jsonItemPtr,                    ///<[IN] json object containing firmware item.
    Manifest_t *manPtr                      ///<[IN] Object containing manifest header.
)
{
    Item_t* item = le_mem_ForceAlloc(ItemPoolRef);

    item->type = LE_UPDATE_FIRMWARE;

    // Now add item in the linked list
    le_dls_Queue(&(manPtr->itemList), &(item->link));

    memset((item->ActionItem).firmware.version,
           0,
           sizeof((item->ActionItem).firmware.version));

    // Get firmware version. This is optional field
    le_result_t result = GetJsonStrField(jsonItemPtr,
                                         JSON_FIELD_VERSION,
                                         (item->ActionItem).firmware.version,
                                         sizeof((item->ActionItem).firmware.version));

    result = GetJsonSizeField(jsonItemPtr,
                              JSON_FIELD_SIZE,
                              &((item->ActionItem).firmware.size));
    LE_DEBUG("Got firmware item: %p, size: %zd",
              item,
              (item->ActionItem).firmware.size);

    return result;
}
Exemplo n.º 4
0
//--------------------------------------------------------------------------------------------------
properties_Iter_Ref_t properties_CreateIter
(
    const char* fileNamePtr                 ///< [IN] File name of the .properties file.
)
{
    // Open the .properties file.
    FILE* filePtr;

    do
    {
        filePtr = fopen(fileNamePtr, "r");
    }
    while ( (filePtr == NULL) && (errno == EINTR) );

    if (filePtr == NULL)
    {
        LE_ERROR("File '%s' could not be opened.  %m.", fileNamePtr);
        return NULL;
    }

    // Create the iterator.
    PropertiesIter_t* iterPtr = le_mem_ForceAlloc(PropertiesIterPool);

    iterPtr->streamPtr = filePtr;
    iterPtr->propertyBuf[0] = '\0';
    iterPtr->keyPtr = NULL;
    iterPtr->valuePtr = NULL;

    // The stored file name is only used for debug log messages so it is fine if the file name gets
    // truncated.  No need to check the return value.
    le_utf8_Copy(iterPtr->fileName, fileNamePtr, LIMIT_MAX_PATH_BYTES, NULL);

    return iterPtr;
}
Exemplo n.º 5
0
//--------------------------------------------------------------------------------------------------
static _ClientThreadData_t* InitClientThreadData
(
    const char* serviceInstanceName
)
{
    // Open a session.
    le_msg_ProtocolRef_t protocolRef;
    le_msg_SessionRef_t sessionRef;

    // The instance name must not be an empty string
    if ( serviceInstanceName[0] == '\0' )
    {
        LE_FATAL("Undefined client service instance name (Was StartClient() called?)");
    }

    protocolRef = le_msg_GetProtocolRef(PROTOCOL_ID_STR, sizeof(_Message_t));
    sessionRef = le_msg_CreateSession(protocolRef, serviceInstanceName);
    le_msg_SetSessionRecvHandler(sessionRef, ClientIndicationRecvHandler, NULL);
    le_msg_OpenSessionSync(sessionRef);

    // Store the client sessionRef in thread-local storage, since each thread requires
    // its own sessionRef.
    _ClientThreadData_t* clientThreadPtr = le_mem_ForceAlloc(_ClientThreadDataPool);
    clientThreadPtr->sessionRef = sessionRef;
    if (pthread_setspecific(_ThreadDataKey, clientThreadPtr) != 0)
    {
        LE_FATAL("pthread_setspecific() failed!");
    }

    return clientThreadPtr;
}
Exemplo n.º 6
0
//--------------------------------------------------------------------------------------------------
proc_Ref_t proc_Create
(
    const char* cfgPathRootPtr,     ///< [IN] The path in the config tree for this process.
    app_Ref_t appRef                ///< [IN] Reference to the app that we are part of.
)
{
    Process_t* procPtr = le_mem_ForceAlloc(ProcessPool);

    // Copy the config path.
    if (le_utf8_Copy(procPtr->cfgPathRoot,
                     cfgPathRootPtr,
                     sizeof(procPtr->cfgPathRoot),
                     NULL) == LE_OVERFLOW)
    {
        LE_ERROR("Config path '%s' is too long.", cfgPathRootPtr);

        le_mem_Release(procPtr);
        return NULL;
    }



    procPtr->name = le_path_GetBasenamePtr(procPtr->cfgPathRoot, "/");

    procPtr->appRef = appRef;
    procPtr->faultTime = 0;
    procPtr->paused = false;
    procPtr->pid = -1;  // Processes that are not running are assigned -1 as its pid.
    procPtr->cmdKill = false;

    return procPtr;
}
Exemplo n.º 7
0
//--------------------------------------------------------------------------------------------------
event_PerThreadRec_t* fa_event_CreatePerThreadInfo
(
    void
)
{
    event_LinuxPerThreadRec_t* recPtr = le_mem_ForceAlloc(PerThreadPool);

    // Create the epoll file descriptor for this thread.  This will be used to monitor for
    // events on various file descriptors.
    recPtr->epollFd = epoll_create1(0);
    LE_FATAL_IF(recPtr->epollFd < 0, "epoll_create1(0) failed with errno %d.", errno);

    // Open an eventfd for this thread.  This will be uses to signal to the epoll fd that there
    // are Event Reports on the Event Queue.
    recPtr->eventQueueFd = eventfd(0, 0);
    LE_FATAL_IF(recPtr->eventQueueFd < 0, "eventfd() failed with errno %d.", errno);

    // Add the eventfd to the list of file descriptors to wait for using epoll_wait().
    struct epoll_event ev;
    memset(&ev, 0, sizeof(ev));
    ev.events = EPOLLIN | EPOLLWAKEUP;
    ev.data.ptr = NULL;     // This being set to NULL is what tells the main event loop that this
                            // is the Event Queue FD, rather than another FD that is being
                            // monitored.
    if (epoll_ctl(recPtr->epollFd, EPOLL_CTL_ADD, recPtr->eventQueueFd, &ev) == -1)
    {
        LE_FATAL(   "epoll_ctl(ADD) failed for fd %d. errno = %d",
                    recPtr->eventQueueFd,
                    errno);
    }

    return &recPtr->portablePerThreadRec;
}
Exemplo n.º 8
0
//--------------------------------------------------------------------------------------------------
le_mrc_ScanInformation_Ref_t le_mrc_GetFirstCellularNetworkScan
(
    le_mrc_ScanInformation_ListRef_t  scanInformationListRef ///< [IN] The list of scan information.
)
{
    pa_mrc_ScanInformation_t* nodePtr;
    le_dls_Link_t*          linkPtr;

    le_mrc_ScanInformationList_t* scanInformationListPtr = le_ref_Lookup(ScanInformationListRefMap,
                                                                         scanInformationListRef);

    if (scanInformationListPtr == NULL)
    {
        LE_KILL_CLIENT("Invalid reference (%p) provided!", scanInformationListRef);
        return NULL;
    }

    linkPtr = le_dls_Peek(&(scanInformationListPtr->paScanInformationList));
    if (linkPtr != NULL)
    {
        nodePtr = CONTAINER_OF(linkPtr, pa_mrc_ScanInformation_t, link);
        scanInformationListPtr->currentLink = linkPtr;

        le_mrc_ScanInformationSafeRef_t* newScanInformationPtr = le_mem_ForceAlloc(ScanInformationSafeRefPool);
        newScanInformationPtr->safeRef = le_ref_CreateRef(ScanInformationRefMap,nodePtr);
        newScanInformationPtr->link = LE_DLS_LINK_INIT;
        le_dls_Queue(&(scanInformationListPtr->safeRefScanInformationList),&(newScanInformationPtr->link));

        return (le_mrc_ScanInformation_Ref_t)newScanInformationPtr->safeRef;
    }
    else
    {
        return NULL;
    }
}
Exemplo n.º 9
0
//--------------------------------------------------------------------------------------------------
le_msg_SessionEventHandlerRef_t le_msg_AddServiceCloseHandler
(
    le_msg_ServiceRef_t             serviceRef, ///< [in] Reference to the service.
    le_msg_SessionEventHandler_t    handlerFunc,///< [in] Handler function.
    void*                           contextPtr  ///< [in] Opaque pointer value to pass to handler.
)
//--------------------------------------------------------------------------------------------------
{
    LE_FATAL_IF(serviceRef == NULL,
                "Service doesn't exist. Make sure service is started before setting handlers");
    LE_FATAL_IF(serviceRef->serverThread != le_thread_GetCurrent(),
                "Service (%s:%s) not owned by calling thread.",
                serviceRef->id.name,
                le_msg_GetProtocolIdStr(serviceRef->id.protocolRef));

    // Create the node.
    SessionEventHandler_t* closeEventPtr = le_mem_ForceAlloc(HandlerEventPoolRef);

    // Initialize the node.
    closeEventPtr->handler = handlerFunc;
    closeEventPtr->contextPtr = contextPtr;
    closeEventPtr->link = LE_DLS_LINK_INIT;
    closeEventPtr->listPtr = &serviceRef->closeListPtr;

    // Add the node to the head of the list by passing in the node's link.
    le_dls_Stack(&serviceRef->closeListPtr, &closeEventPtr->link);

    // Need to return a unique reference that will be used by the remove function.
    closeEventPtr->ref = le_ref_CreateRef(HandlersRefMap, &closeEventPtr->link);

    return closeEventPtr->ref;
}
Exemplo n.º 10
0
static void Handle_AddTestAHandler
(
    le_msg_MessageRef_t _msgRef

)
{
    // Get the message buffer pointer
    uint8_t* _msgBufPtr = ((_Message_t*)le_msg_GetPayloadPtr(_msgRef))->buffer;

    // Needed if we are returning a result or output values
    uint8_t* _msgBufStartPtr = _msgBufPtr;

    // Unpack the input parameters from the message


    void* contextPtr;
    _msgBufPtr = UnpackData( _msgBufPtr, &contextPtr, sizeof(void*) );

    // Create a new server data object and fill it in
    _ServerData_t* serverDataPtr = le_mem_ForceAlloc(_ServerDataPool);
    serverDataPtr->clientSessionRef = le_msg_GetSession(_msgRef);
    serverDataPtr->contextPtr = contextPtr;
    serverDataPtr->handlerRef = NULL;
    serverDataPtr->removeHandlerFunc = NULL;
    contextPtr = serverDataPtr;

    // Define storage for output parameters


    // Call the function
    TestAHandlerRef_t _result;
    _result = AddTestAHandler ( AsyncResponse_AddTestAHandler, contextPtr );

    // Put the handler reference result and a pointer to the associated remove function
    // into the server data object.  This function pointer is needed in case the client
    // is closed and the handlers need to be removed.
    serverDataPtr->handlerRef = (le_event_HandlerRef_t)_result;
    serverDataPtr->removeHandlerFunc = (RemoveHandlerFunc_t)RemoveTestAHandler;

    // Return a safe reference to the server data object as the reference.
    _LOCK
    _result = le_ref_CreateRef(_HandlerRefMap, serverDataPtr);
    _UNLOCK


    // Re-use the message buffer for the response
    _msgBufPtr = _msgBufStartPtr;

    // Pack the result first
    _msgBufPtr = PackData( _msgBufPtr, &_result, sizeof(_result) );

    // Pack any "out" parameters


    // Return the response
    LE_DEBUG("Sending response to client session %p : %ti bytes sent",
             le_msg_GetSession(_msgRef),
             _msgBufPtr-_msgBufStartPtr);
    le_msg_Respond(_msgRef);
}
Exemplo n.º 11
0
//--------------------------------------------------------------------------------------------------
static void CGEVUnsolHandler
(
    void* reportPtr
)
{
    atmgr_UnsolResponse_t* unsolPtr = reportPtr;
    uint32_t  numParam=0;
    pa_mdc_SessionStateData_t *sessionStatePtr=NULL;

    LE_DEBUG("Handler received -%s-",unsolPtr->line);

    if ( ( FIND_STRING("+CGEV: NW DEACT", unsolPtr->line) )
        ||
         ( FIND_STRING("+CGEV: ME DEACT", unsolPtr->line) )
       )
    {
        numParam = atcmd_CountLineParameter(unsolPtr->line);

        if (numParam == 4) {
            sessionStatePtr = le_mem_ForceAlloc(NewSessionStatePool);
            sessionStatePtr->profileIndex = atoi(atcmd_GetLineParameter(unsolPtr->line,4));
            sessionStatePtr->newState = LE_MDC_DISCONNECTED;

            SetCurrentDataSessionIndex(INVALID_PROFILE_INDEX);

            LE_DEBUG("Send Event for %d with state %d",
                        sessionStatePtr->profileIndex,sessionStatePtr->newState);
            le_event_ReportWithRefCounting(NewSessionStateEvent,sessionStatePtr);
        } else {
            LE_WARN("this Response pattern is not expected -%s-",unsolPtr->line);
        }
    }
}
Exemplo n.º 12
0
//--------------------------------------------------------------------------------------------------
le_sem_Ref_t CreateSemaphore
(
    const char* nameStr,
    int         initialCount,
    bool        isTraceable
)
//--------------------------------------------------------------------------------------------------
{
    // Allocate a semaphore object and initialize it.
    Semaphore_t* semaphorePtr = le_mem_ForceAlloc(SemaphorePoolRef);
    semaphorePtr->semaphoreListLink = LE_DLS_LINK_INIT;
    semaphorePtr->waitingList = LE_DLS_LIST_INIT;
    pthread_mutex_init(&semaphorePtr->waitingListMutex, NULL);  // Default attributes = Fast mutex.
    semaphorePtr->isTraceable = isTraceable;
    if (le_utf8_Copy(semaphorePtr->nameStr, nameStr, sizeof(semaphorePtr->nameStr), NULL) == LE_OVERFLOW)
    {
        LE_WARN("Semaphore name '%s' truncated to '%s'.", nameStr, semaphorePtr->nameStr);
    }

    // Initialize the underlying POSIX semaphore shared between thread.
    int result = sem_init(&semaphorePtr->semaphore,0, initialCount);
    if (result != 0)
    {
        LE_FATAL("Failed to set the semaphore . errno = %d (%m).", errno);
    }

    // Add the semaphore to the process's Semaphore List.
    LOCK_SEMAPHORE_LIST();
    le_dls_Queue(&SemaphoreList, &semaphorePtr->semaphoreListLink);
    UNLOCK_SEMAPHORE_LIST();

    return semaphorePtr;
}
Exemplo n.º 13
0
//--------------------------------------------------------------------------------------------------
static void AppendNetworkScanResult
(
    le_mrc_Rat_t   rat,                   /// [IN] Requested simulated RAT result
    le_dls_List_t *scanInformationListPtr ///< [OUT] list of pa_mrc_ScanInformation_t
)
{
    pa_mrc_ScanInformation_t *newScanInformationPtr = NULL;

    char mccStr[LE_MRC_MCC_BYTES];
    char mncStr[LE_MRC_MNC_BYTES];

    newScanInformationPtr = le_mem_ForceAlloc(ScanInformationPool);

    memset(newScanInformationPtr, 0, sizeof(*newScanInformationPtr));
    newScanInformationPtr->link = LE_DLS_LINK_INIT;

    // @TODO Default to SIM MCC/MNC
    strcpy(mccStr, PA_SIMU_SIM_DEFAULT_MCC);
    strcpy(mncStr, PA_SIMU_SIM_DEFAULT_MNC);

    newScanInformationPtr->rat = rat;
    strcpy(newScanInformationPtr->mobileCode.mcc, mccStr);
    strcpy(newScanInformationPtr->mobileCode.mnc, mncStr);
    newScanInformationPtr->isInUse = IsNetworkInUse(rat, mccStr, mncStr);
    newScanInformationPtr->isAvailable = !(newScanInformationPtr->isInUse);
    newScanInformationPtr->isHome = true;
    newScanInformationPtr->isForbidden = false;

    le_dls_Queue(scanInformationListPtr, &(newScanInformationPtr->link));
}
Exemplo n.º 14
0
//--------------------------------------------------------------------------------------------------
static le_json_ParsingSessionRef_t NewParser
(
    le_json_EventHandler_t  eventHandler,   ///< Function to call when normal parsing events happen.
    le_json_ErrorHandler_t  errorHandler,   ///< Function to call when errors happen.
    void* opaquePtr   ///< Opaque pointer to be fetched by handlers using le_json_GetOpaquePtr().
)
{
    Parser_t *parserPtr;

    LE_UNUSED(eventHandler);

    // Create a Parser.
    parserPtr = le_mem_ForceAlloc(ParserPool);
    memset(parserPtr, 0, sizeof(*parserPtr));

    parserPtr->next = EXPECT_OBJECT_OR_ARRAY;
    parserPtr->line = 1;

    parserPtr->errorHandler = errorHandler;
    parserPtr->opaquePtr = opaquePtr;

    // Register a thread destructor to be called to clean up this parser if the thread dies.
    parserPtr->threadDestructor = le_thread_AddDestructor(ThreadDeathHandler, parserPtr);

    parserPtr->contextStack = LE_SLS_LIST_INIT;

    return parserPtr;
}
Exemplo n.º 15
0
static void Handle_TestCallback
(
    le_msg_MessageRef_t _msgRef

)
{
    // Get the message buffer pointer
    uint8_t* _msgBufPtr = ((_Message_t*)le_msg_GetPayloadPtr(_msgRef))->buffer;

    // Needed if we are returning a result or output values
    uint8_t* _msgBufStartPtr = _msgBufPtr;

    // Unpack the input parameters from the message
    uint32_t someParm;
    _msgBufPtr = UnpackData( _msgBufPtr, &someParm, sizeof(uint32_t) );

    size_t dataArrayNumElements;
    _msgBufPtr = UnpackData( _msgBufPtr, &dataArrayNumElements, sizeof(size_t) );

    uint8_t dataArray[dataArrayNumElements];
    _msgBufPtr = UnpackData( _msgBufPtr, dataArray, dataArrayNumElements*sizeof(uint8_t) );



    void* contextPtr;
    _msgBufPtr = UnpackData( _msgBufPtr, &contextPtr, sizeof(void*) );

    // Create a new server data object and fill it in
    _ServerData_t* serverDataPtr = le_mem_ForceAlloc(_ServerDataPool);
    serverDataPtr->clientSessionRef = le_msg_GetSession(_msgRef);
    serverDataPtr->contextPtr = contextPtr;
    serverDataPtr->handlerRef = NULL;
    serverDataPtr->removeHandlerFunc = NULL;
    contextPtr = serverDataPtr;

    // Define storage for output parameters


    // Call the function
    int32_t _result;
    _result = TestCallback ( someParm, dataArray, dataArrayNumElements, AsyncResponse_TestCallback, contextPtr );



    // Re-use the message buffer for the response
    _msgBufPtr = _msgBufStartPtr;

    // Pack the result first
    _msgBufPtr = PackData( _msgBufPtr, &_result, sizeof(_result) );

    // Pack any "out" parameters


    // Return the response
    LE_DEBUG("Sending response to client session %p : %ti bytes sent",
             le_msg_GetSession(_msgRef),
             _msgBufPtr-_msgBufStartPtr);
    le_msg_Respond(_msgRef);
}
Exemplo n.º 16
0
//--------------------------------------------------------------------------------------------------
le_mcc_CallRef_t le_mcc_Create
(
    const char* phoneNumPtr
        ///< [IN]
        ///< The target number we are going to
        ///< call.
)
{
    if (phoneNumPtr == NULL)
    {
        LE_KILL_CLIENT("phoneNumPtr is NULL !");
        return NULL;
    }

    if(strlen(phoneNumPtr) > (LE_MDMDEFS_PHONE_NUM_MAX_BYTES-1))
    {
        LE_KILL_CLIENT("strlen(phoneNumPtr) > %d", (LE_MDMDEFS_PHONE_NUM_MAX_BYTES-1));
        return NULL;
    }

    // Create the Call object.
    le_mcc_Call_t* mccCallPtr = GetCallObject(phoneNumPtr, -1, false);

    if (mccCallPtr != NULL)
    {
        le_mem_AddRef(mccCallPtr);
        mccCallPtr->refCount++;
    }
    else
    {
        mccCallPtr = CreateCallObject (phoneNumPtr,
                                        -1,
                                        LE_MCC_EVENT_TERMINATED,
                                        LE_MCC_TERM_UNDEFINED,
                                        -1);
    }

    // Manage client session
    SessionRefNode_t* newSessionRefPtr = le_mem_ForceAlloc(SessionRefPool);
    newSessionRefPtr->sessionRef = le_mcc_GetClientSessionRef();
    newSessionRefPtr->link = LE_DLS_LINK_INIT;

    // Add the new sessionRef into the the sessionRef list
    le_dls_Queue(&mccCallPtr->sessionRefList,
                    &(newSessionRefPtr->link));

    if (mccCallPtr==NULL)
    {
        LE_ERROR("mccCallPtr null!!!!");
        return NULL;
    }

    LE_DEBUG("Create Call ref.%p", mccCallPtr->callRef);

    // Return a Safe Reference for this Call object.
    return (mccCallPtr->callRef);
}
Exemplo n.º 17
0
//--------------------------------------------------------------------------------------------------
le_result_t le_media_PlayDtmf
(
    le_audio_Stream_t*   streamPtr, ///< [IN] Stream object
    const char*          dtmfPtr,   ///< [IN] The DTMFs to play.
    uint32_t             duration,  ///< [IN] The DTMF duration in milliseconds.
    uint32_t             pause      ///< [IN] The pause duration between tones in milliseconds.
)
{
    le_result_t       res;
    DtmfThreadCtx_t*  threadCtxPtr = le_mem_ForceAlloc(DtmfThreadContextPool);

    memset(threadCtxPtr, 0, sizeof(DtmfThreadCtx_t));

    streamPtr->samplePcmConfig.sampleRate = 16000;
    streamPtr->samplePcmConfig.bitsPerSample = 16;
    streamPtr->samplePcmConfig.channelsCount = 1;
    streamPtr->samplePcmConfig.fileSize = -1;
    streamPtr->samplePcmConfig.pcmFormat = PCM_RAW;

    threadCtxPtr->duration = duration;
    threadCtxPtr->pause = pause;
    threadCtxPtr->sampleRate = 16000;
    threadCtxPtr->dtmfPtr = dtmfPtr;
    if (pipe(threadCtxPtr->pipefd) == -1)
    {
        LE_ERROR("Failed to create the pipe");
        le_mem_Release(threadCtxPtr);
        return LE_FAULT;
    }

    streamPtr->fd = threadCtxPtr->pipefd[0];

    if ((res=pa_audio_PlaySamples(streamPtr->audioInterface,
                                  streamPtr->fd,
                                  &streamPtr->samplePcmConfig)) == LE_OK)
    {
        LE_INFO("Spawn DTMF thread");
        if (DtmfTreadRef == NULL)
        {
            DtmfTreadRef = le_thread_Create("PlayDtmfs", PlayDtmfThread, threadCtxPtr);

            le_thread_AddChildDestructor(DtmfTreadRef,
                                        DestroyPlayDtmfThread,
                                        threadCtxPtr);

            le_thread_Start(DtmfTreadRef);
        }
    }
    else
    {
        le_mem_Release(threadCtxPtr);
        LE_ERROR("Cannot spawn DTMF thread!");
    }

    return res;
}
Exemplo n.º 18
0
//--------------------------------------------------------------------------------------------------
le_event_FdMonitorRef_t le_event_CreateFdMonitor
(
    const char*     name,       ///< [in] Name of the object (for diagnostics).
    int             fd          ///< [in] File descriptor to be monitored for events.
)
//--------------------------------------------------------------------------------------------------
{
    // Get a pointer to the thread-specific event loop data record.
    event_PerThreadRec_t* perThreadRecPtr = thread_GetEventRecPtr();

    // Allocate the object.
    FdMonitor_t* fdMonitorPtr = le_mem_ForceAlloc(FdMonitorPool);

    // Initialize the object.
    fdMonitorPtr->link = LE_DLS_LINK_INIT;
    fdMonitorPtr->fd = fd;
    fdMonitorPtr->threadRecPtr = perThreadRecPtr;
    memset(fdMonitorPtr->handlerArray, 0, sizeof(fdMonitorPtr->handlerArray));

    // To start with, no events are in the set to be monitored.  They will be added as handlers
    // are registered for them. (Although, EPOLLHUP and EPOLLERR will always be monitored
    // regardless of what flags we specify).  We use epoll in "level-triggered mode".
    fdMonitorPtr->epollEvents = 0;

    // Assume that the event should wake up the system; can be changed later.
    fdMonitorPtr->wakeUp = true;

    // Copy the name into it.
    if (le_utf8_Copy(fdMonitorPtr->name, name, sizeof(fdMonitorPtr->name), NULL) == LE_OVERFLOW)
    {
        LE_WARN("FD Monitor object name '%s' truncated to '%s'.", name, fdMonitorPtr->name);
    }

    LOCK

    // Create a safe reference for the object.
    fdMonitorPtr->safeRef = le_ref_CreateRef(FdMonitorRefMap, fdMonitorPtr);

    // Add it to the thread's FD Monitor list.
    le_dls_Queue(&perThreadRecPtr->fdMonitorList, &fdMonitorPtr->link);

    // Tell epoll(7) to start monitoring this fd.
    struct epoll_event ev;
    ev.events = fdMonitorPtr->epollEvents;
    ev.data.ptr = fdMonitorPtr->safeRef;
    if (epoll_ctl(perThreadRecPtr->epollFd, EPOLL_CTL_ADD, fd, &ev) == -1)
    {
        LE_FATAL("epoll_ctl(ADD) failed for fd %d. errno = %d (%m)", fd, errno);
    }

    UNLOCK

    return fdMonitorPtr->safeRef;
}
Exemplo n.º 19
0
//--------------------------------------------------------------------------------------------------
ni_IteratorRef_t ni_CreateIterator
(
    le_msg_SessionRef_t sessionRef,  ///< The user session this request occured on.
    tu_UserRef_t userRef,            ///< Create the iterator for this user.
    tdb_TreeRef_t treeRef,           ///< The tree to create the iterator with.
    ni_IteratorType_t type,          ///< The type of iterator we are creating, read or write?
    const char* initialPathPtr       ///< The node to move to in the specified tree.
)
//--------------------------------------------------------------------------------------------------
{
    LE_ASSERT(sessionRef != NULL);
    LE_ASSERT(userRef != NULL);
    LE_ASSERT(treeRef != NULL);

    // Allocate the object and setup it's initial properties.
    ni_IteratorRef_t iteratorRef = le_mem_ForceAlloc(IteratorPoolRef);

    iteratorRef->sessionRef = sessionRef;
    iteratorRef->userRef = userRef;
    iteratorRef->treeRef = treeRef;
    iteratorRef->type = type;
    iteratorRef->reference = NULL;
    iteratorRef->isClosed = false;

    // If this is a write iterator, then shadow the tree instead of accessing it directly.
    if (iteratorRef->type == NI_WRITE)
    {
        iteratorRef->treeRef = tdb_ShadowTree(iteratorRef->treeRef);
    }

    // Get the root node of the requested tree, or if this is a write iterator...  Get the shadowed
    // root node of the tree.
    iteratorRef->currentNodeRef = tdb_GetRootNode(iteratorRef->treeRef);
    iteratorRef->pathIterRef = le_pathIter_CreateForUnix("/");

    LE_DEBUG("Created a new %s iterator object <%p> for user %u (%s) on tree %s.",
             TypeString(type),
             iteratorRef,
             tu_GetUserId(userRef),
             tu_GetUserName(userRef),
             tdb_GetTreeName(treeRef));

     // If we were given an initial path, go to it now.  Otherwise stay on the root node.
    if (initialPathPtr)
    {
        ni_GoToNode(iteratorRef, initialPathPtr);
    }

    // Update the tree so that it can keep track of this iterator.
    tdb_RegisterIterator(treeRef, iteratorRef);

    // All done.
    return iteratorRef;
}
Exemplo n.º 20
0
//--------------------------------------------------------------------------------------------------
static int MessageArrivedHandler
(
    void* contextPtr,
    char* topicNamePtr,
    int topicLen,
    MQTTClient_message* messagePtr
)
{
    mqtt_Session* s = le_ref_Lookup(SessionRefMap, contextPtr);
    if (s == NULL)
    {
        LE_WARN("Session doesn't exist");
        return true;
    }

    mqtt_Message* storedMsgPtr = le_mem_ForceAlloc(MessagePoolRef);
    LE_ASSERT(storedMsgPtr);
    memset(storedMsgPtr, 0, sizeof(*storedMsgPtr));

    LE_DEBUG("MessageArrivedHandler called for topic=%s. Storing session=0x%p", topicNamePtr, contextPtr);
    storedMsgPtr->sessionRef = contextPtr;

    // When topicLen is 0 it means that the topic contains embedded nulls and can't be treated as a
    // normal C string
    storedMsgPtr->topicLength = (topicLen == 0) ? (strlen(topicNamePtr) + 1) : topicLen;
    storedMsgPtr->topicPtr = le_mem_ForceAlloc(TopicPoolRef);
    LE_ASSERT(storedMsgPtr->topicPtr);
    memset(storedMsgPtr->topicPtr, 0, sizeof(MQTT_MAX_TOPIC_LENGTH));
    memcpy(storedMsgPtr->topicPtr, topicNamePtr, storedMsgPtr->topicLength);

    storedMsgPtr->payloadLength = messagePtr->payloadlen;
    storedMsgPtr->payloadPtr = le_mem_ForceAlloc(PayloadPoolRef);
    LE_ASSERT(storedMsgPtr->payloadPtr);
    memset(storedMsgPtr->payloadPtr, 0, sizeof(MQTT_MAX_PAYLOAD_LENGTH));
    memcpy(storedMsgPtr->payloadPtr, messagePtr->payload, storedMsgPtr->payloadLength);

    le_event_Report(ReceiveThreadEventId, &storedMsgPtr, sizeof(mqtt_Message*));

    return true;
}
Exemplo n.º 21
0
//--------------------------------------------------------------------------------------------------
static ThreadObj_t* CreateThread
(
    const char*             name,       ///< [in] Name of the thread.
    le_thread_MainFunc_t    mainFunc,   ///< [in] The thread's main function.
    void*                   context     ///< [in] Value to pass to mainFunc when it is called.
)
{
    // Create a new thread object.
    ThreadObj_t* threadPtr = le_mem_ForceAlloc(ThreadPool);

    // Copy the name.  We will make the names unique by adding the thread ID later so we allow any
    // string as the name.
    LE_WARN_IF(le_utf8_Copy(threadPtr->name, name, sizeof(threadPtr->name), NULL) == LE_OVERFLOW,
               "Thread name '%s' has been truncated to '%s'.",
               name,
               threadPtr->name);

    // Initialize the pthreads attribute structure.
    LE_ASSERT(pthread_attr_init(&(threadPtr->attr)) == 0);

    // Make sure when we create the thread it takes it attributes from the attribute object,
    // as opposed to inheriting them from its parent thread.
    if (pthread_attr_setinheritsched(&(threadPtr->attr), PTHREAD_EXPLICIT_SCHED) != 0)
    {
        LE_CRIT("Could not set scheduling policy inheritance for thread '%s'.", name);
    }

    // By default, Legato threads are not joinable (they are detached).
    if (pthread_attr_setdetachstate(&(threadPtr->attr), PTHREAD_CREATE_DETACHED) != 0)
    {
        LE_CRIT("Could not set the detached state for thread '%s'.", name);
    }

    threadPtr->isJoinable = false;
    threadPtr->isStarted = false;
    threadPtr->mainFunc = mainFunc;
    threadPtr->context = context;
    threadPtr->destructorList = LE_SLS_LIST_INIT;
    threadPtr->threadHandle = 0;

    memset(&threadPtr->mutexRec, 0, sizeof(threadPtr->mutexRec));
    memset(&threadPtr->semaphoreRec, 0, sizeof(threadPtr->semaphoreRec));
    memset(&threadPtr->eventRec, 0, sizeof(threadPtr->eventRec));
    memset(&threadPtr->timerRec, 0, sizeof(threadPtr->timerRec));

    // Create a safe reference for this object.
    Lock();
    threadPtr->safeRef = le_ref_CreateRef(ThreadRefMap, threadPtr);
    Unlock();

    return threadPtr;
}
Exemplo n.º 22
0
//--------------------------------------------------------------------------------------------------
le_mrc_ScanInformation_ListRef_t le_mrc_PerformCellularNetworkScan
(
    le_mrc_Rat_t ratMask ///< [IN] Technology mask
)
{
    le_result_t result;
    le_mrc_ScanInformationList_t* newScanInformationListPtr = NULL;
    uint32_t networkScan = 0;

    newScanInformationListPtr = le_mem_ForceAlloc(ScanInformationListPool);
    newScanInformationListPtr->paScanInformationList = LE_DLS_LIST_INIT;
    newScanInformationListPtr->safeRefScanInformationList = LE_DLS_LIST_INIT;
    newScanInformationListPtr->currentLink = NULL;

    if (ratMask == LE_MRC_RAT_ALL) {
        networkScan |= PA_MRC_METWORK_MASK_GSM;
        networkScan |= PA_MRC_METWORK_MASK_UTMS;
        networkScan |= PA_MRC_METWORK_MASK_LTE;
        networkScan |= PA_MRC_METWORK_MASK_TD_SCDMA;
    }
    else
    {
        if (ratMask&LE_MRC_RAT_GSM)
        {
            networkScan |= PA_MRC_METWORK_MASK_GSM;
        }
        if (ratMask&LE_MRC_RAT_UTMS)
        {
            networkScan |= PA_MRC_METWORK_MASK_UTMS;
        }
        if (ratMask&LE_MRC_RAT_LTE)
        {
            networkScan |= PA_MRC_METWORK_MASK_LTE;
        }
        if (ratMask&LE_MRC_RAT_TC_SCDMA)
        {
            networkScan |= PA_MRC_METWORK_MASK_LTE;
        }
    }

    result = pa_mrc_PerformNetworkScan(networkScan,PA_MRC_SCAN_PLMN,
                                       &(newScanInformationListPtr->paScanInformationList));

    if (result != LE_OK)
    {
        le_mem_Release(newScanInformationListPtr);

        return NULL;
    }

    return le_ref_CreateRef(ScanInformationListRefMap, newScanInformationListPtr);
}
Exemplo n.º 23
0
void ipcTest_EchoLargeEnum
(
    ipcTest_ServerCmdRef_t serverCmdPtr,
    ipcTest_LargeEnum_t InValue
)
{
    ipcTest_LargeEnum_t* valuePtr = le_mem_ForceAlloc(ValuePool);
    *valuePtr = InValue;

    le_event_QueueFunction(AsyncServer_EchoLargeEnumRespond,
                           serverCmdPtr,
                           valuePtr);
}
Exemplo n.º 24
0
//--------------------------------------------------------------------------------------------------
static void ReportStatus
(
    uint32_t        simCard,  ///< [IN] Sim Card Number
    le_sim_States_t simState  ///< [IN] Sim Card Status
)
{
    pa_sim_Event_t* eventPtr = le_mem_ForceAlloc(SimEventPoolRef);
    eventPtr->num   = simCard;
    eventPtr->state = simState;

    LE_DEBUG("Send Event SIM number %d, SIM state %d",eventPtr->num,eventPtr->state);
    le_event_ReportWithRefCounting(EventNewSimStateId,eventPtr);
}
Exemplo n.º 25
0
//--------------------------------------------------------------------------------------------------
LE_SHARED appCfg_Iter_t appCfg_CreateAppsIter
(
    void
)
{
    AppsIter_t* iterPtr = le_mem_ForceAlloc(AppIterPool);

    iterPtr->type = ITER_TYPE_APP;
    iterPtr->cfgIter = le_cfg_CreateReadTxn(CFG_APPS_LIST);
    iterPtr->atFirst = true;

    return iterPtr;
}
Exemplo n.º 26
0
//--------------------------------------------------------------------------------------------------
static dstr_Ref_t NewSegment
(
    void
)
//--------------------------------------------------------------------------------------------------
{
    dstr_Ref_t newSegmentRef = le_mem_ForceAlloc(DynamicStringPoolRef);

    memset(newSegmentRef->body.value, 0, SEGMENT_SIZE);
    newSegmentRef->body.link = LE_SLS_LINK_INIT;

    return newSegmentRef;
}
Exemplo n.º 27
0
//--------------------------------------------------------------------------------------------------
dstr_Ref_t dstr_New
(
    void
)
//--------------------------------------------------------------------------------------------------
{
    dstr_Ref_t newHeadRef = le_mem_ForceAlloc(DynamicStringPoolRef);

    newHeadRef->head.magic = HEADER_MAGIC;
    newHeadRef->head.list = LE_SLS_LIST_INIT;

    return newHeadRef;
}
Exemplo n.º 28
0
//--------------------------------------------------------------------------------------------------
le_result_t mqtt_CreateSession
(
    const char* brokerURIPtr,           ///< [IN] The URI of the MQTT broker to connect to.  Should be in
                                        ///  the form protocol://host:port. eg. tcp://1.2.3.4:1883 or
                                        ///  ssl://example.com:8883
    const char* clientIdPtr,            ///< [IN] Any unique string.  If a client connects to an MQTT
                                        ///  broker using the same clientId as an existing session, then
                                        ///  the existing session will be terminated.
    mqtt_SessionRef_t* sessionRefPtr    ///< [OUT] The created session if the return result is LE_OK
)
{
    mqtt_Session* s = le_mem_ForceAlloc(MQTTSessionPoolRef);
    LE_ASSERT(s);
    memset(s, 0, sizeof(*s));
    const MQTTClient_connectOptions initConnOpts = MQTTClient_connectOptions_initializer;
    memcpy(&(s->connectOptions), &initConnOpts, sizeof(initConnOpts));

    const MQTTClient_SSLOptions initSslOpts = MQTTClient_SSLOptions_initializer;
    memcpy(&(s->sslOptions), &initSslOpts, sizeof(initSslOpts));
    s->sslOptions.trustStore = SslCaCertsPathPtr;

    const int createResult = MQTTClient_create(
            &(s->client),
            brokerURIPtr,
            clientIdPtr,
            MQTTCLIENT_PERSISTENCE_NONE,
            NULL);
    if (createResult != MQTTCLIENT_SUCCESS)
    {
        LE_ERROR("Couldn't create MQTT session.  Paho error code: %d", createResult);
        le_mem_Release(s);
        return LE_FAULT;
    }

    le_msg_SessionRef_t clientSession = mqtt_GetClientSessionRef();
    s->clientSession = clientSession;

    *sessionRefPtr = le_ref_CreateRef(SessionRefMap, s);

    LE_ASSERT(MQTTClient_setCallbacks(
            s->client,
            *sessionRefPtr,
            &ConnectionLostHandler,
            &MessageArrivedHandler,
            NULL) == MQTTCLIENT_SUCCESS);

    return LE_OK;
}
Exemplo n.º 29
0
//--------------------------------------------------------------------------------------------------
le_avdata_AssetInstanceRef_t le_avdata_Create
(
    const char* assetName
        ///< [IN]
)
{
    // Get the client's credentials.
    pid_t pid;
    uid_t uid;

    if (le_msg_GetClientUserCreds(le_avdata_GetClientSessionRef(), &uid, &pid) != LE_OK)
    {
        LE_KILL_CLIENT("Could not get credentials for the client.");
        return NULL;
    }


    // Look up the process's application name.
    char appName[LE_LIMIT_APP_NAME_LEN+1];

    le_result_t result = le_appInfo_GetName(pid, appName, sizeof(appName));
    LE_FATAL_IF(result == LE_OVERFLOW, "Buffer too small to contain the application name.");

    // TODO: Should this be LE_KILL_CLIENT instead?
    LE_FATAL_IF(result != LE_OK, "Could not get app name");


    // Create an instance of the asset
    assetData_InstanceDataRef_t instRef;
    int instanceId;

    LE_ASSERT( assetData_CreateInstanceByName(appName, assetName, -1, &instRef) == LE_OK );
    LE_ASSERT( instRef != NULL );
    LE_ASSERT( assetData_GetInstanceId(instRef, &instanceId) == LE_OK );
    LE_PRINT_VALUE("%i", instanceId);

    // Return a safe reference for the instance
    InstanceRefData_t* instRefDataPtr = le_mem_ForceAlloc(InstanceRefDataPoolRef);

    instRefDataPtr->clientSessionRef = le_avdata_GetClientSessionRef();
    instRefDataPtr->instRef = instRef;

    instRef = le_ref_CreateRef(InstanceRefMap, instRefDataPtr);

    return instRef;
}
Exemplo n.º 30
0
void ipcTest_EchoString
(
    ipcTest_ServerCmdRef_t serverCmdPtr,
    const char* InString,
    size_t OutStringSize
)
{
    // Cap output string size at maximum size of buffer
    if (OutStringSize > MAX_VALUE_SIZE) { OutStringSize = MAX_VALUE_SIZE; }

    char* OutString = le_mem_ForceAlloc(ValuePool);
    strncpy(OutString, InString, OutStringSize);
    OutString[OutStringSize-1] = '\0';
    le_event_QueueFunction(AsyncServer_EchoStringRespond,
                           serverCmdPtr,
                           OutString);
}