Example #1
0
static void HandleTestA
(
    int32_t x,
    void* contextPtr
)
{
    static int count=0;
    count++;

    LE_PRINT_VALUE("%i", x);

    if ( contextPtr == ClientMessage )
    {
        LE_DEBUG("HandleTestA: context pointer works");
        LE_PRINT_VALUE( "'%s'", (char *)contextPtr );
    }
    else
    {
        LE_DEBUG("HandleTestA: context pointer fails");
    }

    // Re-do the test again for the given number of times.
    if ( count < 2 )
    {
        banner("Test 2 again");
        LE_PRINT_VALUE("%i", count);

        HandlerRef = AddTestAHandler(HandleTestA, (void*)ClientMessage);
        LE_PRINT_VALUE("%p", HandlerRef);

        LE_DEBUG("Triggering TestA yet again for count=%i\n", count);
        TriggerTestA();
    }
}
Example #2
0
// -------------------------------------------------------------------------------------------------
static void NetRegStateHandler
(
    le_mrc_NetRegState_t state,   ///< [IN] The new state of the modem.
    void*                contextPtr
)
{
    // Record the change of state to the chat log.
    if (OutputFilePtr)
    {
        fprintf(OutputFilePtr, "## %s ##\n", GetNetStateString(state));
        fflush(OutputFilePtr);
    }

    // For traceablity, make sure that this event is recorded.
    LE_DEBUG("%s", GetNetStateString(state));

    // If we are going back on net, and have been configured to do so, send our "on network" message
    // now.
    if (((state == LE_MRC_REG_HOME)
       || (state == LE_MRC_REG_ROAMING))
       && (DestNumValid))
    {
        LE_DEBUG("Sending On Network Message.");
        SendMessage(DestNum, "Getting back on network.");
    }
}
Example #3
0
//--------------------------------------------------------------------------------------------------
static void FieldActionHandler
(
    assetData_InstanceDataRef_t instanceRef,
    int fieldId,
    assetData_ActionTypes_t action,
    void* contextPtr
)
{
    // Get the handler data from the contextPtr
    LE_ASSERT( contextPtr != NULL );
    FieldEventData_t* handlerDataPtr = contextPtr;

    // Ensure the action happens on the desired instance.  This could happen since we register
    // against the asset, rather than an instance of the asset.
    // NOTE: Don't need to check for fieldId, since they should always match.
    if ( handlerDataPtr->instRef != instanceRef )
    {
        LE_DEBUG("Action %i not expected for this instance, so ignore it", action);
        return;
    }

    LE_DEBUG("Got action=%i, for field='%s'", action, handlerDataPtr->fieldName);

    // Call the user supplied handler
    handlerDataPtr->handlerPtr(handlerDataPtr->safeRef,
                               handlerDataPtr->fieldName,
                               handlerDataPtr->contextPtr);
}
Example #4
0
static void TestGetDir(void)
{
    int i;
    char dirname[100];

    // Test the standard strings.
    for (i = 0; i < NUM_TEST_STRS; i++)
    {
        LE_TEST( (le_path_GetDir(PathNames[i], "/", dirname, 100) == LE_OK) &&
                  (strcmp(dirname, DirNames[i]) == 0) );
        LE_DEBUG("Dir: '%s'", dirname);
    }

    // Test with multibyte separators.
    for (i = 0; i < NUM_TEST_STRS; i++)
    {
        LE_TEST( (le_path_GetDir(SepPathNames[i], "**", dirname, 100) == LE_OK) &&
                  (strcmp(dirname, SepDirNames[i]) == 0) );
        LE_DEBUG("Dir: '%s'", dirname);
    }

    // Test an overflow condition.
    LE_TEST( (le_path_GetDir(PathNames[1], "/", dirname, 21) == LE_OVERFLOW) &&
             (strcmp(dirname, "/long/path/with/trai") == 0) );
    LE_DEBUG("Dir: '%s'", dirname);
}
Example #5
0
void test3(void)
{
    banner("Test 3");

    // Test what happens if an event is triggered, then the handler is removed.  The registered
    // handler should not be called, even if there is a pending event, because the handler has
    // been removed.
    TestAHandlerRef_t handlerRef = AddTestAHandler(NewHandleTestA, NULL);
    LE_PRINT_VALUE("%p", handlerRef);

    LE_DEBUG("Triggering New TestA\n");
    TriggerTestA();

    RemoveTestAHandler(handlerRef);


    // Test function callback parameters.
    int result;

    // This is not used in the test; this parameter was added to test a code generation bug fix.
    uint8_t dataArray[] = { 1, 2 };

    result = TestCallback(10, dataArray, 2, CallbackTestHandler, NULL);
    LE_PRINT_VALUE("%d", result);

    LE_DEBUG("Triggering CallbackTest");
    TriggerCallbackTest(100);

    // Need to allow the event loop to process the trigger.
    // The rest of the test will be continued in the handler.
}
Example #6
0
static void HandleTestA
(
    int32_t x,
    void* contextPtr
)
{
    LE_PRINT_VALUE("%i", x);

    if ( contextPtr == &SomeData )
    {
        LE_DEBUG("HandleTestA: context pointer works");
        LE_PRINT_VALUE( "%u", *((uint32_t*)contextPtr) );
    }
    else
    {
        LE_DEBUG("HandleTestA: context pointer fails");
    }

    // continue the rest of the test
    LE_DEBUG("Removing TestA");
    RemoveTestAHandler(HandlerRef);

    LE_DEBUG("Triggering TestA again");
    TriggerTestA();

    // Continue with next test
    test3();
}
Example #7
0
int mqttClient_connectUser(mqttClient_t* clientData, const char* password)
{
  int32_t rc = LE_OK;

  LE_ASSERT(clientData);
  LE_ASSERT(password);

  if (!clientData->session.isConnected)
  {
    LE_DEBUG("pw('%s')", password);
    strcpy(clientData->session.secret, password);

    if (!clientData->dataConnectionState)
    {
      clientData->dataConnectionState = le_data_AddConnectionStateHandler(mqttClient_dataConnectionStateHandler, clientData);
    }

    LE_DEBUG("initiated data connection");
    rc = mqttClient_connectData(clientData);
    if (rc)
    {
      LE_ERROR("mqttClient_connectData() failed(%d)", rc);
      goto cleanup;
    }
  }
  else
  {
    LE_KILL_CLIENT("The MQTT client is already connected");
  }

cleanup:
  return rc;
}
Example #8
0
//--------------------------------------------------------------------------------------------------
void le_sup_ctrl_RestartLegato
(
    le_sup_ctrl_ServerCmdRef_t cmdRef,
    bool manualRestart
)
{
    LE_DEBUG("Received request to restart Legato.");

    if (State == STATE_NORMAL)
    {
        // Save the command reference to use in the response later.
        AsyncApiCmdRef = cmdRef;

        if (manualRestart)
        {
            State = STATE_RESTARTING_MANUAL;
        }
        else
        {
            State = STATE_RESTARTING;
        }

        // Start the process of shutting down the framework.
        BeginShutdown();
    }
    else
    {
        LE_DEBUG("Ignoring request to restart Legato in state %d.", State);

        le_sup_ctrl_RestartLegatoRespond(cmdRef, LE_DUPLICATE);
    }
}
Example #9
0
int main(int argc, char* argv[])
{
    arg_SetArgs((size_t)argc, (char**)argv);

    LE_DEBUG("== Starting Executable '%s' ==", STRINGIZE(LE_EXECUTABLE_NAME));

    LE_LOG_SESSION = log_RegComponent( STRINGIZE(LE_COMPONENT_NAME), &LE_LOG_LEVEL_FILTER_PTR);

    // Connect to the Log Control Daemon.
    // The sooner we can connect to the Log Control Daemon, the better, because that is when
    // we obtain any non-default log settings that have been set using the interactive log
    // control tool.  However, we can't do that until we have a working IPC messaging system.
    // However, the Log Control Daemon shouldn't try to connect to itself.
    // Also, the Service Directory shouldn't try to use the messaging system, so it can't
    // connect to the Log Control Daemon either.  Besides, the Service Directory starts before
    // the Log Control Daemon starts.
    #ifndef NO_LOG_CONTROL
        log_ConnectToControlDaemon();
    #endif

    //@todo: Block all signals that the user intends to handle with signal events.

    // Queue up all the component initialization functions to be called by the Event Loop after
    // it processes any messages that were received from the Log Control Daemon.
    event_QueueComponentInit(_le_event_InitializeComponent);


    LE_DEBUG("== Starting Event Processing Loop ==");

    le_event_RunLoop();

    LE_FATAL("SHOULDN'T GET HERE!");
}
Example #10
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);
        }
    }
}
Example #11
0
static int mangoh_bridge_air_vantage_pushString(void* param, const unsigned char* data, uint32_t size)
{
    mangoh_bridge_air_vantage_t* airVantage = (mangoh_bridge_air_vantage_t*)param;
    int32_t res = LE_OK;

    LE_ASSERT(airVantage);
    LE_ASSERT(data);

    LE_DEBUG("---> PUSH STRING");
    uint8_t* ptr = (uint8_t*)data;

    uint8_t len = 0;
    memcpy(&len, ptr, sizeof(len));
    LE_DEBUG("len(%u)", len);
    ptr += sizeof(len);

    char fieldName[MANGOH_BRIDGE_AIR_VANTAGE_FIELD_NAME_MAX_LEN] = {0};
    memcpy(fieldName, ptr, len);
    LE_DEBUG("field('%s')", fieldName);
    ptr += len;

    char val[MANGOH_BRIDGE_AIR_VANTAGE_VALUE_MAX_LEN] = {0};
    memcpy(val, ptr, size - len - sizeof(len));
    LE_DEBUG("value('%s')", val);

    dataRouter_WriteString(fieldName, val, time(NULL));

    dataRouter_DataUpdateHandlerRef_t dataUpdateHandlerRef = le_hashmap_Get(airVantage->dataUpdateHandlers, fieldName);
    if (!dataUpdateHandlerRef)
    {
        LE_DEBUG("add data update handler('%s')", fieldName);
        dataUpdateHandlerRef = dataRouter_AddDataUpdateHandler(fieldName, mangoh_bridge_air_vantage_dataUpdateHdlr, airVantage);
        if (!dataUpdateHandlerRef)
        {
            LE_ERROR("ERROR dataRouter_AddDataUpdateHandler() failed");
            res = LE_FAULT;
            goto cleanup;
        }

        if (le_hashmap_Put(airVantage->dataUpdateHandlers, fieldName, dataUpdateHandlerRef))
        {
            LE_ERROR("ERROR le_hashmap_Put() failed");
            res = LE_FAULT;
            goto cleanup;
        }
    }

    res = mangoh_bridge_sendResult(airVantage->bridge, 0);
    if (res != LE_OK)
    {
        LE_ERROR("ERROR mangoh_bridge_sendResult() failed(%d)", res);
        goto cleanup;
    }

cleanup:
    return res;
}
Example #12
0
//--------------------------------------------------------------------------------------------------
int32_t le_hex_StringToBinary
(
    const char *stringPtr,     ///< [IN] string to convert
    uint32_t    stringLength,  ///< [IN] string length
    uint8_t    *binaryPtr,     ///< [OUT] binary result
    uint32_t    binarySize     ///< [IN] size of the binary table.  Must be >= stringLength / 2
)
{
    uint32_t idxString;
    uint32_t idxBinary;
    char*    refStrPtr = "0123456789ABCDEF";

    if (stringLength > strlen(stringPtr))
    {
        LE_DEBUG("The stringLength (%" PRIu32 ") is more than size of stringPtr (%s)",
                 stringLength, stringPtr);
        return -1;
    }

    if (stringLength % 2 != 0)
    {
        LE_DEBUG("The input stringLength=%" PRIu32 " is not a multiple of 2", stringLength);
        return -1;
    }

    if (stringLength / 2 > binarySize)
    {
        LE_DEBUG(
            "The stringLength (%" PRIu32 ") is too long to convert"
            " into a byte array of length (%" PRIu32 ")",
            stringLength,
            binarySize);
        return -1;
    }

    for (idxString=0,idxBinary=0 ; idxString<stringLength ; idxString+=2,idxBinary++)
    {
        char* ch1Ptr;
        char* ch2Ptr;

        if ( ((ch1Ptr = strchr(refStrPtr, toupper((int)stringPtr[idxString]))) && *ch1Ptr) &&
             ((ch2Ptr = strchr(refStrPtr, toupper((int)stringPtr[idxString+1]))) && *ch2Ptr) )
        {
            binaryPtr[idxBinary] = ((ch2Ptr - refStrPtr) & 0x0F) |
                                   (((ch1Ptr - refStrPtr)<<4) & 0xF0);
        }
        else
        {
            LE_DEBUG("Invalid string to convert (%s)", stringPtr);
            return -1;
        }
    }

    return idxBinary;
}
Example #13
0
//--------------------------------------------------------------------------------------------------
static void CleanupClientData
(
    le_msg_SessionRef_t sessionRef,
    void *contextPtr
)
{
    LE_DEBUG("Client %p is closed !!!", sessionRef);

    // Iterate over the server data reference map and remove anything that matches
    // the client session.
    _LOCK

    le_ref_IterRef_t iterRef = le_ref_GetIterator(_HandlerRefMap);
    le_result_t result = le_ref_NextNode(iterRef);
    _ServerData_t const* serverDataPtr;

    while ( result == LE_OK )
    {
        serverDataPtr =  le_ref_GetValue(iterRef);

        if ( sessionRef != serverDataPtr->clientSessionRef )
        {
            LE_DEBUG("Found session ref %p; does not match",
                     serverDataPtr->clientSessionRef);
        }
        else
        {
            LE_DEBUG("Found session ref %p; match found, so needs cleanup",
                     serverDataPtr->clientSessionRef);

            // Remove the handler, if the Remove handler functions exists.
            if ( serverDataPtr->removeHandlerFunc != NULL )
            {
                serverDataPtr->removeHandlerFunc( serverDataPtr->handlerRef );
            }

            // Release the server data block
            le_mem_Release((void*)serverDataPtr);

            // Delete the associated safeRef
            le_ref_DeleteRef( _HandlerRefMap, (void*)le_ref_GetSafeRef(iterRef) );

            // Since the reference map was modified, the iterator is no longer valid and
            // so has to be re-initalized.  This means that some values may get revisited,
            // but eventually this will iterate over the whole reference map.
            // todo: Is there an easier way?
            iterRef = le_ref_GetIterator(_HandlerRefMap);
        }

        // Get the next value in the reference mpa
        result = le_ref_NextNode(iterRef);
    }

    _UNLOCK
}
Example #14
0
//--------------------------------------------------------------------------------------------------
tdb_TreeRef_t tu_GetRequestedTree
(
    tu_UserRef_t userRef,            ///< [IN] Get a tree for this user.
    tu_TreePermission_t permission,  ///< [IN] Try to get a tree with this permission.
    const char* pathPtr              ///< [IN] The path to check.
)
//--------------------------------------------------------------------------------------------------
{
    char treeName[MAX_TREE_NAME_BYTES] = "";

    // If the path has the tree name embedded, extract it now.  Otherwise, check to see if the user
    // is trying to write to the default tree.  If it is we extract the tree name for checking
    // permission just like if they explicitly specifed the tree name.  If the user is simply trying
    // to read from their default tree, then we grant it without resorting to an ACL lookup.
    if (tp_PathHasTreeSpecifier(pathPtr) == true)
    {
        tp_GetTreeName(treeName, pathPtr);
        LE_DEBUG("** Specific tree requested, '%s'.", treeName);

        // Make sure that this isn't the user's didn't just specify their own default tree.  If they
        // did and they're looking for read access, then just go ahead and grant it.
        if (   (permission == TU_TREE_READ)
            && (strcmp(treeName, userRef->treeName) == 0))
        {
            return tdb_GetTree(userRef->treeName);
        }
    }
    else if (permission == TU_TREE_WRITE)
    {
        LE_DEBUG("** Attempting write access on the default tree, '%s'.", userRef->treeName);
        strcpy(treeName, userRef->treeName);
    }
    else
    {
        LE_DEBUG("** Opening the default tree, '%s' with read only access.", userRef->treeName);
        return tdb_GetTree(userRef->treeName);
    }

    // If we got this far, it's because we have a tree that we need to do an ACL lookup on.  So do
    // so now, if that check fails, we simply bail.
    if (   (ic_CheckTreePermission(permission, userRef->userName, treeName) == false)
        && (userRef->userId != 0))
    {
        LE_ERROR("The user, '%s', id: %d, does not have %s permission on the tree '%s'.",
                 userRef->userName,
                 userRef->userId,
                 PermissionStr(permission),
                 treeName);

        return NULL;
    }

    // Looks like the user has permission, so grab the tree.
    return tdb_GetTree(treeName);
}
Example #15
0
//--------------------------------------------------------------------------------------------------
static void LoadECallSettings
(
    int32_t*  hMinAccuracyPtr,
    int32_t*  dirMinAccuracyPtr
)
{
    char psapStr[LE_MDMDEFS_PHONE_NUM_MAX_BYTES] = {0};

    LE_DEBUG("Start reading eCall app settings in Configuration Tree");

    le_cfg_IteratorRef_t eCallCfgRef = le_cfg_CreateReadTxn(CFG_ECALL_APP_PATH);

    // Get PSAP
    if (le_cfg_NodeExists(eCallCfgRef, CFG_NODE_PSAP))
    {
        if ( le_cfg_GetString(eCallCfgRef, CFG_NODE_PSAP, psapStr, sizeof(psapStr), "") != LE_OK )
        {
            LE_FATAL("No node value set for '%s', exit the app!", CFG_NODE_PSAP);
        }
        LE_DEBUG("eCall settings, PSAP number is %s", psapStr);
        if (le_ecall_SetPsapNumber(psapStr) != LE_OK)
        {
            LE_FATAL("Cannot set PSAP number, exit the app!");
        }
    }
    else
    {
        LE_FATAL("No value set for '%s', restart the app!", CFG_NODE_PSAP);
    }

    // Get minimum horizontal accuracy
    if (le_cfg_NodeExists(eCallCfgRef, CFG_NODE_H_MIN_ACCURACY))
    {
        *hMinAccuracyPtr = le_cfg_GetInt(eCallCfgRef, CFG_NODE_H_MIN_ACCURACY, DEFAULT_H_ACCURACY);
        LE_DEBUG("eCall app settings, horizontal accuracy is %d meter(s)", *hMinAccuracyPtr);
    }
    else
    {
        *hMinAccuracyPtr = DEFAULT_H_ACCURACY;
    }

    // Get minimum direction accuracy
    if (le_cfg_NodeExists(eCallCfgRef, CFG_NODE_DIR_MIN_ACCURACY))
    {
        *dirMinAccuracyPtr = le_cfg_GetInt(eCallCfgRef, CFG_NODE_DIR_MIN_ACCURACY, DEFAULT_DIR_ACCURACY);
        LE_DEBUG("eCall app settings, direction accuracy is %d degree(s)", *dirMinAccuracyPtr);
    }
    else
    {
        *dirMinAccuracyPtr = DEFAULT_DIR_ACCURACY;
    }

    le_cfg_CancelTxn(eCallCfgRef);
}
// -------------------------------------------------------------------------------------------------
void le_cfgAdmin_ExportTree
(
    le_cfgAdmin_ServerCmdRef_t commandRef,  ///< [IN] Reference used to generate a reply for this
                                            ///<      request.
    le_cfg_IteratorRef_t externalRef,       ///< [IN] Write iterator that is being used for the
                                            ///<      export.
    const char* filePathPtr,                ///< [IN] Export the tree data to the this file.
    const char* nodePathPtr                 ///< [IN] Where in the tree should this export happen?
                                            ///<      Leave as an empty string to use the iterator's
                                            ///<      current node.
)
// -------------------------------------------------------------------------------------------------
{
    LE_DEBUG("** Exporting a tree from node '%s' into file '%s', using iterator, '%p'.",
             nodePathPtr, filePathPtr, externalRef);

    ni_IteratorRef_t iteratorRef = GetIteratorFromRef(externalRef);

    if (iteratorRef == NULL)
    {
        le_cfgAdmin_ExportTreeRespond(commandRef, LE_OK);
        return;
    }

    LE_DEBUG("Opening file '%s'.", filePathPtr);

    FILE* filePtr = NULL;

    filePtr = fopen(filePathPtr, "w+");

    if (!filePtr)
    {
        LE_ERROR("File '%s' could not be opened.", filePathPtr);
        le_cfgAdmin_ExportTreeRespond(commandRef, LE_IO_ERROR);

        return;
    }


    LE_DEBUG("Exporting config data.");

    le_result_t result = LE_OK;

    if (tdb_WriteTreeNode(ni_GetNode(iteratorRef, nodePathPtr), filePtr) != LE_OK)
    {
        result = LE_FAULT;
    }

    fclose(filePtr);

    le_cfgAdmin_ExportTreeRespond(commandRef, result);
}
Example #17
0
static int mqttClient_processPublish(mqttClient_t* clientData)
{
  MQTTString topicName;
  mqttClient_msg_t msg;
  int len = 0;
  int32_t rc = LE_OK;

  LE_DEBUG("---> PUBLISH");
  LE_ASSERT(clientData);

  if (MQTTDeserialize_publish((unsigned char*)&msg.dup, (int*)&msg.qos, (unsigned char*)&msg.retained, (unsigned short*)&msg.id, &topicName,
          (unsigned char**)&msg.payload, (int*)&msg.payloadLen, clientData->session.rx.buf, sizeof(clientData->session.rx.buf)) != 1)
  {
    LE_ERROR("MQTTDeserialize_publish() failed");
    rc = LE_BAD_PARAMETER;
    goto cleanup;
  }

  if (msg.qos != MQTT_CLIENT_QOS0)
  {
    if (msg.qos == MQTT_CLIENT_QOS1)
      len = MQTTSerialize_ack(clientData->session.tx.buf, sizeof(clientData->session.tx.buf), PUBACK, 0, msg.id);
    else if (msg.qos == MQTT_CLIENT_QOS2)
      len = MQTTSerialize_ack(clientData->session.tx.buf, sizeof(clientData->session.tx.buf), PUBREC, 0, msg.id);

    if (len <= 0)
    {
      LE_ERROR("MQTTSerialize_ack() failed(%d)", len);
      rc = LE_BAD_PARAMETER;
      goto cleanup;
    }
        
    LE_DEBUG("<--- PUBACK");
    rc = mqttClient_write(clientData, len);
    if (rc)
    {
      LE_ERROR("mqttClient_write() failed(%d)", rc);
      goto cleanup;
    }
  }

  rc = mqttClient_deliverMsg(clientData, &topicName, &msg);
  if (rc)
  {
    LE_ERROR("mqttClient_deliverMsg() failed(%d)", rc);
    goto cleanup;
  }

cleanup:
  return rc;
}
Example #18
0
static int mqttClient_processConnAck(mqttClient_t* clientData)
{
  int32_t rc = LE_OK;
  uint8_t sessionPresent = 0;
  uint8_t connack_rc = 0;

  LE_DEBUG("---> CONNACK");
  LE_ASSERT(clientData);

  rc = le_timer_Stop(clientData->session.cmdTimer);
  if (rc)
  {
    LE_ERROR("le_timer_Stop() failed(%d)", rc);
    goto cleanup;
  }


  rc = MQTTDeserialize_connack((unsigned char*)&sessionPresent, &connack_rc, clientData->session.rx.buf, sizeof(clientData->session.rx.buf));
  if (rc != 1)
  {
    LE_ERROR("MQTTDeserialize_connack() failed(%d)", rc);
    rc = LE_BAD_PARAMETER;
    goto cleanup;
  }

  LE_DEBUG("session present(%u) connection ACK(%u)", sessionPresent, connack_rc);
  clientData->session.isConnected = (connack_rc == MQTT_CLIENT_CONNECT_SUCCESS);

  if (clientData->session.isConnected)
  {
    mqttClient_SendConnStateEvent(true, 0, rc);

    LE_INFO("subscribe('%s')", clientData->subscribeTopic);
    rc = mqttClient_subscribe(clientData, clientData->subscribeTopic, 0, mqttClient_onIncomingMessage);
    if (rc)
    {
      LE_ERROR("mqttClient_subscribe() failed(%d)", rc);
      goto cleanup;
    }
  }
  else
  {
    LE_ERROR("response('%s')", mqttClient_connectionRsp(connack_rc));
    rc = LE_BAD_PARAMETER;
    goto cleanup;
  }

cleanup:
  return rc;
}
static int l_processEvents(lua_State *L)
{
    le_result_t res = LE_WOULD_BLOCK;

    L_eventloop = L;
    do {
        LE_DEBUG("=> serviceLoop");
        res = le_event_ServiceLoop();
        LE_DEBUG("<= serviceLoop, res = %d", res);
    } while(res == LE_OK);

    lua_pushstring(L, "ok");
    return 1;
}
Example #20
0
//--------------------------------------------------------------------------------------------------
le_result_t le_mrc_GetSignalQual
(
    uint32_t*   qualityPtr  ///< [OUT] The received signal strength quality (0 = no signal strength,
                            ///        5 = very good signal strength).
)
{
    le_result_t   res;
    int32_t       rssi;   // The received signal strength (in dBm).
    int32_t       thresholds[] = {-113, -100, -90, -80, -65}; // TODO: Verify thresholds !
    uint32_t      i=0;
    size_t        thresholdsCount = NUM_ARRAY_MEMBERS(thresholds);

    if (qualityPtr == NULL)
    {
        LE_KILL_CLIENT("qualityPtr is NULL !");
        return LE_FAULT;
    }

    if ((res=pa_mrc_GetSignalQuality(&rssi)) == LE_OK)
    {
        for (i=0; i<thresholdsCount; i++)
        {
            if (rssi <= thresholds[i])
            {
                *qualityPtr = i;
                break;
            }
        }
        if (i == thresholdsCount)
        {
            *qualityPtr = i;
        }

        LE_DEBUG("pa_mrc_GetSignalQuality has returned rssi=%ddBm", rssi);
        return LE_OK;
    }
    else if (res == LE_OUT_OF_RANGE)
    {
        LE_DEBUG("pa_mrc_GetSignalQuality has returned LE_OUT_OF_RANGE");
        *qualityPtr = 0;
        return LE_OK;
    }
    else
    {
        LE_ERROR("pa_mrc_GetSignalQuality has returned %d", res);
        *qualityPtr = 0;
        return LE_NOT_POSSIBLE;
    }
}
Example #21
0
//--------------------------------------------------------------------------------------------------
static le_result_t LoadRatList
(
    const char  *ratPath,
    uint32_t    *ratMaskPtr
)
{
    uint32_t idx=0;
    LE_DEBUG("Load Rat Preference <%s>",ratPath);

    le_cfg_IteratorRef_t ratCfg = le_cfg_CreateReadTxn(ratPath);

    *ratMaskPtr = 0;
    do {
        // Get the node name.
        char ratNodeName[LIMIT_MAX_PATH_BYTES] = {0};
        char ratNodeValue[LIMIT_MAX_PATH_BYTES] = {0};

        sprintf(ratNodeName,PATTERN_RAT"%d",idx);

        // This is the exist state for the loop
        if (le_cfg_IsEmpty(ratCfg, ratNodeName))
        {
            LE_DEBUG("'%s' does not exist. stop reading configuration", ratNodeName);
            break;
        }

        if ( le_cfg_GetString(ratCfg,ratNodeName,ratNodeValue,sizeof(ratNodeValue), "") != LE_OK )
        {
            LE_WARN("Node value string for '%s' too large.",ratNodeName);
            le_cfg_CancelTxn(ratCfg);
            return LE_NOT_POSSIBLE;
        }

        if ( strncmp(ratNodeName,"",sizeof(ratNodeName)) == 0 )
        {
            LE_WARN("No node value set for '%s'",ratNodeName);
            le_cfg_CancelTxn(ratCfg);
            return LE_NOT_POSSIBLE;
        }

        *ratMaskPtr |= ConvertRatValue(ratNodeValue);

        ++idx;
    } while (true);

    le_cfg_CancelTxn(ratCfg);

    return LE_OK;
}
Example #22
0
//--------------------------------------------------------------------------------------------------
static void StartFramework
(
    void
)
{
    // Start a daemon start-up watchdog timer.
    // If we don't cancel this timer within 30 seconds, a SIGALRM will be generated, which will
    // kill the Supervisor.
    alarm(30);

    // Start all framework daemons.
    fwDaemons_Start();

    // Connect to the services we need from the framework daemons.
    LE_DEBUG("---- Connecting to services ----");
    le_cfg_ConnectService();
    logFd_ConnectService();
    le_instStat_ConnectService();

    // Cancel the start-up watchdog timer.
    alarm(0);

    // Insert kernel modules
    kernelModules_Insert();

    // Advertise services.
    LE_DEBUG("---- Advertising the Supervisor's APIs ----");
    le_sup_ctrl_AdvertiseService();
    le_sup_wdog_AdvertiseService();
    le_appInfo_AdvertiseService();
    le_appProc_AdvertiseService();

    // Initialize the apps sub system.
    apps_Init();

    State = STATE_NORMAL;

    if (AppStartMode == APP_START_AUTO)
    {
        // Launch all user apps in the config tree that should be launched on system startup.
        LE_INFO("Auto-starting apps.");
        apps_AutoStart();
    }
    else
    {
        LE_INFO("Skipping app auto-start.");
    }
}
Example #23
0
//--------------------------------------------------------------------------------------------------
static void SetObject9InstanceForApp
(
    const char* appName,                     ///< The name of the application in question.
    assetData_InstanceDataRef_t instanceRef  ///< The instance of object 9 to link to.  Pass NULL if
                                             ///<   the link is to be cleared.
)
//--------------------------------------------------------------------------------------------------
{
    le_cfg_IteratorRef_t iterRef = le_cfg_CreateWriteTxn(CFG_OBJECT_INFO_PATH);

    if (instanceRef != NULL)
    {
        int instanceId;
        LE_ASSERT(assetData_GetInstanceId(instanceRef, &instanceId) == LE_OK);

        le_cfg_GoToNode(iterRef, appName);
        le_cfg_SetInt(iterRef, "oiid", instanceId);

        LE_DEBUG("Application '%s' mapped to instance %d.", appName, instanceId);
    }
    else
    {
        le_cfg_DeleteNode(iterRef, appName);
    }

    le_cfg_CommitTxn(iterRef);
}
Example #24
0
//--------------------------------------------------------------------------------------------------
static void ResetClientWatchdog
(
    int32_t timeout ///< [IN] The timeout to reset the watchdog timer to (in milliseconds).
)
{
    le_clk_Time_t timeoutValue;
    WatchdogObj_t* watchDogPtr = GetClientWatchdogPtr();
    if (watchDogPtr != NULL)
    {
        le_timer_Stop(watchDogPtr->timer);
        if (timeout == TIMEOUT_KICK)
        {
            timeoutValue = watchDogPtr->kickTimeoutInterval;
        }
        else
        {
            timeoutValue = MakeTimerInterval(timeout);
        }

        if (timeout != LE_WDOG_TIMEOUT_NEVER)
        {
            // timer should be stopped here so this should never fail
            // testing
            LE_ASSERT(LE_OK == le_timer_SetInterval(watchDogPtr->timer, timeoutValue));
            le_timer_Start(watchDogPtr->timer);
        }
        else
        {
            LE_DEBUG("Timeout set to NEVER!");
        }
    }
}
Example #25
0
void CallbackTestHandler
(
    uint32_t data,
    const char* namePtr,
    int dataFile,
    void* contextPtr
)
{
    LE_PRINT_VALUE("%d", data);
    LE_PRINT_VALUE("'%s'", namePtr);
    LE_PRINT_VALUE("%p", contextPtr);

    LE_PRINT_VALUE("%i", dataFile);

    // Read and print out whatever is read from the dataFile fd.
    writeFdToLog(dataFile);

    // This should fail, because the callback can only be called once.
    LE_DEBUG("Triggering CallbackTest second time -- should FATAL");
    TriggerCallbackTest(257);

    // Continue with the next test
    // todo: can't continue because the previous test fails -- maybe need to separate tests
    //le_event_QueueFunction(testFinal, NULL, NULL);
}
Example #26
0
//--------------------------------------------------------------------------------------------------
void Testle_sms_msg_SendText()
{
    le_result_t           res;
    le_sms_msg_Ref_t      myMsg;

    myMsg = le_sms_msg_Create();
    CU_ASSERT_PTR_NOT_NULL(myMsg);

    LE_DEBUG("-TEST- Create Msg %p", myMsg);

    testHdlrRef=le_sms_msg_AddRxMessageHandler(TestRxHandler, NULL);
    CU_ASSERT_PTR_NOT_NULL(testHdlrRef);

    res=le_sms_msg_SetDestination(myMsg, DEST_TEST_PATTERN);
    CU_ASSERT_EQUAL(res, LE_OK);

    res=le_sms_msg_SetText(myMsg, LARGE_TEXT_TEST_PATTERN);
    CU_ASSERT_EQUAL(res, LE_OK);

    res=le_sms_msg_Send(myMsg);
    CU_ASSERT_NOT_EQUAL(res, LE_FAULT);
    CU_ASSERT_NOT_EQUAL(res, LE_FORMAT_ERROR);

    res=le_sms_msg_SetText(myMsg, SHORT_TEXT_TEST_PATTERN);
    CU_ASSERT_EQUAL(res, LE_OK);

    res=le_sms_msg_Send(myMsg);
    CU_ASSERT_NOT_EQUAL(res, LE_FAULT);
    CU_ASSERT_NOT_EQUAL(res, LE_FORMAT_ERROR);

    le_sms_msg_Delete(myMsg);
}
Example #27
0
//--------------------------------------------------------------------------------------------------
void tu_Init
(
    void
)
//--------------------------------------------------------------------------------------------------
{
    LE_DEBUG("** Initialize Tree User subsystem.");

    LE_ASSERT(sizeof(uint32_t) >= sizeof(uid_t));

    // Startup the internal Legato user API.
    user_Init();

    // Create our memory pools and allocate the info for the root user.
    UserPoolRef = le_mem_CreatePool(CFG_USER_POOL_NAME, sizeof(User_t));
    UserCollectionRef = le_hashmap_Create(CFG_USER_COLLECTION_NAME,
                                          31,
                                          le_hashmap_HashUInt32,
                                          le_hashmap_EqualsUInt32);

    le_mem_SetDestructor(UserPoolRef, UserDestructor);

    // Create our default root user/tree association.
    CreateUserInfo(0, "root", "system");
}
Example #28
0
//--------------------------------------------------------------------------------------------------
static void SetObj9State_
(
    assetData_InstanceDataRef_t instanceRef,  ///< THe instance to update.
    UpdateState state,                        ///< The new state.
    UpdateResult result,                      ///< The new result.
    bool isSaveState,                         ///< Save state to configtree?
    const char* functionNamePtr,              ///< Name of the function that called this one.
    size_t line                               ///< The line of this file this function was called
                                              ///<   from.
)
//--------------------------------------------------------------------------------------------------
{
    int instanceId;

    if (instanceRef == NULL)
    {
        LE_WARN("Setting state on NULL object.");
        return;
    }

    assetData_GetInstanceId(instanceRef, &instanceId);
    LE_DEBUG("<%s: %zu>: Set object 9 state/result on instance %d: (%d) %s / (%d) %s",
             functionNamePtr,
             line,
             instanceId,
             state,
             UpdateStateToStr(state),
             result,
             UpdateResultToStr(result));

    LE_ASSERT(assetData_client_SetInt(instanceRef, O9F_UPDATE_STATE, state) == LE_OK);
    LE_ASSERT(assetData_client_SetInt(instanceRef, O9F_UPDATE_RESULT, result) == LE_OK);
}
Example #29
0
//--------------------------------------------------------------------------------------------------
void smack_RevokeSubject
(
    const char* subjectLabelPtr     ///< [IN] Subject label.
)
{
    // Open the SMACK revoke file.
    int fd;

    do
    {
        fd = open(SMACK_REVOKE_FILE, O_WRONLY);
    }
    while ( (fd == -1) && (errno == EINTR) );

    LE_FATAL_IF(fd == -1, "Could not open %s.  %m.\n", SMACK_REVOKE_FILE);

    // Write the label to the SMACK revoke file.
    int numBytes = 0;

    do
    {
        numBytes = write(fd, subjectLabelPtr, strlen(subjectLabelPtr));
    }
    while ( (numBytes == -1) && (errno == EINTR) );

    LE_FATAL_IF(numBytes < 0, "Could not revoke SMACK label '%s'.  %m.", subjectLabelPtr);

    fd_Close(fd);

    LE_DEBUG("Revoked SMACK label '%s'.", subjectLabelPtr);
}
Example #30
0
//--------------------------------------------------------------------------------------------------
static void OnChildSignal
(
    int sigNum  ///< Id of the signal that fired.
)
//--------------------------------------------------------------------------------------------------
{
    pid_t pid;
    int status;

    LE_INFO("Child signal received.");

    // Get the result code from the child process.
    do
    {
        pid = waitpid(-1, &status, WNOHANG | WUNTRACED | WCONTINUED);
    }
    while (   (pid < 0)
           && (errno == EINTR));

    LE_DEBUG("Server: Child PID %d, exit status: %d.", pid, status);

    // Now, if this is the child process we launched earlier, attempt to call the registered
    // callback.
    if (pid == Current.pid)
    {
        if (Current.handlerPtr != NULL)
        {
            Current.handlerPtr(status, Current.contextPtr);
        }

        Current.pid = -1;
        Current.handlerPtr = NULL;
        Current.contextPtr = NULL;
    }
}