Example #1
0
int mqtt_client(void)
{
    int rc = 0, msg_len;
    void *pclient;
    iotx_conn_info_pt pconn_info;
    iotx_mqtt_param_t mqtt_params;
    iotx_mqtt_topic_info_t topic_msg;
    char msg_pub[128];
    char *msg_buf = NULL, *msg_readbuf = NULL;
    char device_name[24];
    char device_secret[64];
    char topic_update[64],topic_config[64],topic_control[64],topic_state[64];

    if (NULL == (msg_buf = (char *)HAL_Malloc(MSG_LEN_MAX))) {
        EXAMPLE_TRACE("not enough memory");
        rc = -1;
        goto do_exit;
    }

    if (NULL == (msg_readbuf = (char *)HAL_Malloc(MSG_LEN_MAX))) {
        EXAMPLE_TRACE("not enough memory");
        rc = -1;
        goto do_exit;
    }

    int fd_dv;
    int rdOrWrNum;
    char dvcSecretBuff[36];
    getClientID(device_name);
	if((fd_dv=open("./dvcSecret",O_RDWR | O_CREAT)) == -1)
	{
		PRINTF("open dvcSecret error");
		exit(1);
	}
	rdOrWrNum = read(fd_dv,dvcSecretBuff,36);
	dvcSecretBuff[rdOrWrNum] = '\0';
	if(rdOrWrNum == -1)
	{
		PRINTF("read dvcSecret error");
	}
	if(rdOrWrNum != 32)
	{
		getSecret(device_secret,device_name);
		lseek(fd_dv,0,SEEK_SET);
		rdOrWrNum = write(fd_dv,device_secret,strlen(device_secret));
		truncate("./dvcSecret", rdOrWrNum);
		close(fd_dv);
	}
	else
	{
		strcpy(device_secret,dvcSecretBuff);
	}
	if(snprintf(topic_update, sizeof(topic_update),"/%s/%s/update", PRODUCT_KEY,device_name) < 0)
	{
		PRINTF("topic too long!");
		return -1;
	}
	if(snprintf(topic_config, sizeof(topic_config),"/%s/%s/config", PRODUCT_KEY,device_name) < 0)
	{
		PRINTF("topic too long!");
		return -1;
	}
	if(snprintf(topic_control, sizeof(topic_control),"/%s/%s/control", PRODUCT_KEY,device_name) < 0)
	{
		PRINTF("topic too long!");
		return -1;
	}
	if(snprintf(topic_state, sizeof(topic_state),"/%s/%s/state", PRODUCT_KEY,device_name) < 0)
	{
			PRINTF("topic too long!");
			return -1;
	}
    /* Device AUTH */
    if (0 != IOT_SetupConnInfo(PRODUCT_KEY, device_name, device_secret, (void **)&pconn_info)) {
        EXAMPLE_TRACE("AUTH request failed!");
        rc = -1;
        goto do_exit;
    }

    /* Initialize MQTT parameter */
    memset(&mqtt_params, 0x0, sizeof(mqtt_params));

    mqtt_params.port = pconn_info->port;
    mqtt_params.host = pconn_info->host_name;
    mqtt_params.client_id = pconn_info->client_id;
    mqtt_params.username = pconn_info->username;
    mqtt_params.password = pconn_info->password;
    mqtt_params.pub_key = pconn_info->pub_key;

    mqtt_params.request_timeout_ms = 2000;
    mqtt_params.clean_session = 0;
    mqtt_params.keepalive_interval_ms = 60000;
    mqtt_params.pread_buf = msg_readbuf;
    mqtt_params.read_buf_size = MSG_LEN_MAX;
    mqtt_params.pwrite_buf = msg_buf;
    mqtt_params.write_buf_size = MSG_LEN_MAX;

    mqtt_params.handle_event.h_fp = event_handle;
    mqtt_params.handle_event.pcontext = NULL;


    /* Construct a MQTT client with specify parameter */
    pclient = IOT_MQTT_Construct(&mqtt_params);
    if (NULL == pclient) {
        EXAMPLE_TRACE("MQTT construct failed");
        rc = -1;
        goto do_exit;
    }

    /* Subscribe the specific topic */
    rc = IOT_MQTT_Subscribe(pclient, topic_config, IOTX_MQTT_QOS1, configArrived, NULL);
    if (rc < 0) {
        IOT_MQTT_Destroy(&pclient);
        EXAMPLE_TRACE("IOT_MQTT_Subscribe() failed, rc = %d", rc);
        rc = -1;
        goto do_exit;
    }
    /* Subscribe the specific topic */
	rc = IOT_MQTT_Subscribe(pclient, topic_update, IOTX_MQTT_QOS1, updateArrived, NULL);
	if (rc < 0) {
		IOT_MQTT_Destroy(&pclient);
		EXAMPLE_TRACE("IOT_MQTT_Subscribe() failed, rc = %d", rc);
		rc = -1;
		goto do_exit;
	}
	/* Subscribe the specific topic */
	rc = IOT_MQTT_Subscribe(pclient, topic_control, IOTX_MQTT_QOS1, controlrrived, NULL);
	if (rc < 0) {
		IOT_MQTT_Destroy(&pclient);
		EXAMPLE_TRACE("IOT_MQTT_Subscribe() failed, rc = %d", rc);
		rc = -1;
		goto do_exit;
	}

    HAL_SleepMs(1000);

    /* open the version record file*/
    int fd_ver;
    char rd_buf[64];
    char *p = rd_buf;
    int rdNum  = 8;
    int rRdNum = 0;
    int rdSum  = 0;

	if((fd_ver=open("./unidoli.ver",O_RDONLY)) == -1)
	{
		PRINTF("open unidoli.ver error \n");
		exit(1);
	}
	do
	{
		p += rRdNum;
		rRdNum = read(fd_ver,p,rdNum);
		if(rRdNum == -1)
		{
			PRINTF("read unidoli.ver error\n");
		}
		rdSum += rRdNum;
	}
	while(rRdNum == rdNum);
	rd_buf[rdSum] = '\0';
	close(fd_ver);

	PRINTF("unidoli.ver : %s",rd_buf);

    /* Initialize topic information */
    memset(&topic_msg, 0x0, sizeof(iotx_mqtt_topic_info_t));
    snprintf(msg_pub, sizeof(msg_pub), "{\"version\":\"%s\"}", rd_buf);
    topic_msg.qos = IOTX_MQTT_QOS1;
    topic_msg.retain = 0;
    topic_msg.dup = 0;
    topic_msg.payload = (void *)msg_pub;
    topic_msg.payload_len = strlen(msg_pub);

    rc = IOT_MQTT_Publish(pclient, topic_state, &topic_msg);
    EXAMPLE_TRACE("rc = IOT_MQTT_Publish() = %d", rc);

    do
    {
    	if(0)    //turn of loop publish
    	{
			/* Generate topic message */
			msg_len = snprintf(msg_pub, sizeof(msg_pub), "{\"attr_name\":\"temperature\", \"attr_value\":\" \"}");
			if (msg_len < 0) {
				EXAMPLE_TRACE("Error occur! Exit program");
				rc = -1;
				break;
			}

			topic_msg.payload = (void *)msg_pub;
			topic_msg.payload_len = msg_len;

			rc = IOT_MQTT_Publish(pclient, topic_state, &topic_msg);
			if (rc < 0) {
				EXAMPLE_TRACE("error occur when publish");
				rc = -1;
				break;
			}
			#ifdef MQTT_ID2_CRYPTO
				EXAMPLE_TRACE("packet-id=%u, publish topic msg='0x%02x%02x%02x%02x'...",
							  (uint32_t)rc,
							  msg_pub[0], msg_pub[1], msg_pub[2], msg_pub[3]
							 );
			#else
				EXAMPLE_TRACE("packet-id=%u, publish topic msg=%s", (uint32_t)rc, msg_pub);
			#endif
    	}
        /* handle the MQTT packet received from TCP or SSL connection */
        IOT_MQTT_Yield(pclient, 200);

    } while (loop_mqtt);
    loop_mqtt = 1;

    IOT_MQTT_Unsubscribe(pclient, topic_config);
    IOT_MQTT_Unsubscribe(pclient, topic_update);
    IOT_MQTT_Unsubscribe(pclient, topic_control);
    HAL_SleepMs(200);
    IOT_MQTT_Destroy(&pclient);
do_exit:
    if (NULL != msg_buf) {
        HAL_Free(msg_buf);
    }

    if (NULL != msg_readbuf) {
        HAL_Free(msg_readbuf);
    }
    return rc;
}
Example #2
0
bool FLockEntryMsgEx::processIncoming(struct sockaddr_in* fromAddr, Socket* sock,
   char* respBuf, size_t bufLen, HighResolutionStats* stats)
{
   /* note: this code is very similar to FLockRangeMsgEx::processIncoming(), so if you change
      something here, you probably want to change it there, too. */

   #ifdef BEEGFS_DEBUG
      const char* logContext = "FLockEntryMsg incoming";

      std::string peer = fromAddr ? Socket::ipaddrToStr(&fromAddr->sin_addr) : sock->getPeername();
      LOG_DEBUG(logContext, Log_DEBUG, std::string("Received a FLockEntryMsg from: ") + peer);
   #endif // BEEGFS_DEBUG

   App* app = Program::getApp();
   SessionStore* sessions = app->getSessions();
   MetaStore* metaStore = app->getMetaStore();

   FhgfsOpsErr clientResult = FhgfsOpsErr_INTERNAL; // reponse error code

   unsigned ownerFD = SessionTk::ownerFDFromHandleID(getFileHandleID() );

   EntryLockDetails lockDetails(getClientID(), getClientFD(), getOwnerPID(), getLockAckID(),
      getLockTypeFlags() );

   LOG_DEBUG(logContext, Log_SPAM, lockDetails.toString() );

   EntryInfo* entryInfo = getEntryInfo();

   // find sessionFile
   Session* session = sessions->referenceSession(getClientID(), true);
   SessionFileStore* sessionFiles = session->getFiles();

   SessionFile* sessionFile = sessionFiles->referenceSession(ownerFD);
   if(!sessionFile)
   { // sessionFile not exists (mds restarted?)

      // check if this is just an UNLOCK REQUEST

      if(getLockTypeFlags() & ENTRYLOCKTYPE_UNLOCK)
      { // it's an unlock => we'll just ignore it (since the locks are gone anyways)
         clientResult = FhgfsOpsErr_SUCCESS;

         goto cleanup_session;
      }

      // check if this is a LOCK CANCEL REQUEST

      if(getLockTypeFlags() & ENTRYLOCKTYPE_CANCEL)
      { // it's a lock cancel
         /* this is an important special case, because client might have succeeded in closing the
         file but the conn might have been interrupted during unlock, so we definitely have to try
         canceling the lock here */

         // if the file still exists, just do the lock cancel without session recovery attempt

         FileInode* lockCancelFile = metaStore->referenceFile(entryInfo);
         if(lockCancelFile)
         {
            lockCancelFile->flockEntry(lockDetails);
            metaStore->releaseFile(entryInfo->getParentEntryID(), lockCancelFile);
         }

         clientResult = FhgfsOpsErr_SUCCESS;

         goto cleanup_session;
      }

      // it's a LOCK REQUEST => try to recover session file to do the locking

      clientResult = MsgHelperLocking::trySesssionRecovery(entryInfo, getClientID(),
         ownerFD, sessionFiles, &sessionFile);

      // (note: sessionFile==NULL now if recovery was not successful)

   } // end of session file session recovery attempt

   if(sessionFile)
   { // sessionFile exists (or was successfully recovered)
      FileInode* file = sessionFile->getInode();
      bool lockGranted = file->flockEntry(lockDetails);
      if(!lockGranted)
         clientResult = FhgfsOpsErr_WOULDBLOCK;
      else
         clientResult = FhgfsOpsErr_SUCCESS;

      // cleanup
      sessionFiles->releaseSession(sessionFile, entryInfo);
   }


   // cleanup
cleanup_session:
   sessions->releaseSession(session);

   LOG_DEBUG(logContext, Log_SPAM, std::string("Client result: ") +
      FhgfsOpsErrTk::toErrString(clientResult) );

   // send response
   FLockEntryRespMsg respMsg(clientResult);
   respMsg.serialize(respBuf, bufLen);
   sock->sendto(respBuf, respMsg.getMsgLength(), 0,
      (struct sockaddr*)fromAddr, sizeof(struct sockaddr_in) );

   app->getNodeOpStats()->updateNodeOp(sock->getPeerIP(), MetaOpCounter_FLOCKENTRY,
      getMsgHeaderUserID() );

   return true;
}