Ejemplo n.º 1
0
/**
  Connect a class of devices using the platform Boot Manager policy.

  The ConnectDeviceClass() function allows the caller to request that the Boot
  Manager connect a class of devices.

  If Class is EFI_BOOT_MANAGER_POLICY_CONSOLE_GUID then the Boot Manager will
  use platform policy to connect consoles. Some platforms may restrict the
  number of consoles connected as they attempt to fast boot, and calling
  ConnectDeviceClass() with a Class value of EFI_BOOT_MANAGER_POLICY_CONSOLE_GUID
  must connect the set of consoles that follow the Boot Manager platform policy,
  and the EFI_SIMPLE_TEXT_INPUT_PROTOCOL, EFI_SIMPLE_TEXT_INPUT_EX_PROTOCOL, and
  the EFI_SIMPLE_TEXT_OUTPUT_PROTOCOL are produced on the connected handles.
  The Boot Manager may restrict which consoles get connect due to platform policy,
  for example a security policy may require that a given console is not connected.

  If Class is EFI_BOOT_MANAGER_POLICY_NETWORK_GUID then the Boot Manager will
  connect the protocols the platforms supports for UEFI general purpose network
  applications on one or more handles. If more than one network controller is
  available a platform will connect, one, many, or all of the networks based
  on platform policy. Connecting UEFI networking protocols, like EFI_DHCP4_PROTOCOL,
  does not establish connections on the network. The UEFI general purpose network
  application that called ConnectDeviceClass() may need to use the published
  protocols to establish the network connection. The Boot Manager can optionally
  have a policy to establish a network connection.

  If Class is EFI_BOOT_MANAGER_POLICY_CONNECT_ALL_GUID then the Boot Manager
  will connect all UEFI drivers using the UEFI Boot Service
  EFI_BOOT_SERVICES.ConnectController(). If the Boot Manager has policy
  associated with connect all UEFI drivers this policy will be used.

  A platform can also define platform specific Class values as a properly generated
  EFI_GUID would never conflict with this specification.

  @param[in] This  A pointer to the EFI_BOOT_MANAGER_POLICY_PROTOCOL instance.
  @param[in] Class A pointer to an EFI_GUID that represents a class of devices
                   that will be connected using the Boot Mangers platform policy.

  @retval EFI_SUCCESS      At least one devices of the Class was connected.
  @retval EFI_DEVICE_ERROR Devices were not connected due to an error.
  @retval EFI_NOT_FOUND    The Class is not supported by the platform.
  @retval EFI_UNSUPPORTED  The current TPL is not TPL_APPLICATION.
**/
EFI_STATUS
EFIAPI
BootManagerPolicyConnectDeviceClass (
  IN EFI_BOOT_MANAGER_POLICY_PROTOCOL *This,
  IN EFI_GUID                         *Class
  )
{
  if (EfiGetCurrentTpl () != TPL_APPLICATION) {
    return EFI_UNSUPPORTED;
  }

  if (CompareGuid (Class, &gEfiBootManagerPolicyConnectAllGuid)) {
    ConnectAllAndCreateNetworkDeviceList ();
    return EFI_SUCCESS;
  }

  if (CompareGuid (Class, &gEfiBootManagerPolicyConsoleGuid)) {
    return EfiBootManagerConnectAllDefaultConsoles ();
  }

  if (CompareGuid (Class, &gEfiBootManagerPolicyNetworkGuid)) {
    return ConnectNetwork ();
  }

  return EFI_NOT_FOUND;
}
Ejemplo n.º 2
0
int main(int argc, char** argv)
{
	int rc = 0;
	unsigned char buf[1024];
	unsigned char readbuf[1024];

	Network n;
	Client c;

	signal(SIGINT, cfinish);
	signal(SIGTERM, cfinish);

	NewNetwork(&n);
	ConnectNetwork(&n, "eu.airvantage.net", 1883);
	MQTTClient(&c, &n, 1000, buf, 1024, readbuf, 1024);
 
	MQTTPacket_connectData data = MQTTPacket_connectData_initializer;       
	data.willFlag = 0;
	data.MQTTVersion = 3;
	data.clientID.cstring = deviceId;
	data.username.cstring = "00000000B6AF4A9D";
	data.password.cstring = "toto";

	data.keepAliveInterval = 10000;
	data.cleansession = 1;
	printf("Connecting to %s %d\n", "tcp://eu.airvantage.net", 1883);
	
	rc = MQTTConnect(&c, &data);
	printf("Connected %d\n", rc);
    

	char* topic = malloc(strlen(deviceId)+13);
	sprintf(topic, "%s/tasks/json", deviceId);

        printf("Subscribing to %s\n", topic);
	rc = MQTTSubscribe(&c, topic, 0, messageArrived);
	printf("Subscribed %d\n", rc);

	int err1 = pthread_create(&reading_tid, NULL, &readMeasuresHandler, (void*)&c);
	int err2 = pthread_create(&uploading_tid, NULL, &uploadMeasuresHandler, (void*) &c);
	if(err1 != 0 || err2 != 0)
		printf("Can't create simulator (%s, %d)\n", strerror(err1), err2);
	else
	{
		while (!toStop)
		{
			MQTTYield(&c, 1000);	
		}
	}
	
	printf("Stopping\n");

	MQTTDisconnect(&c);
	n.disconnect(&n);

	return 0;
}
Ejemplo n.º 3
0
static enum cmd_status cmd_mqtt_connect_exec(char *cmd)
{
	int32_t cnt;
	char addr_str[15];
	uint32_t port;
	int32_t rc;
	uint32_t i;

	/* get param */
	cnt = cmd_sscanf(cmd, "server=%15s port=%u",
			 addr_str, &port);

	/* check param */
	if (cnt != 2) {
		CMD_ERR("invalid param number %d\n", cnt);
		return CMD_STATUS_INVALID_ARG;
	}

	i = 10;
	char* address = addr_str;
	while ((rc = ConnectNetwork(&network, address, port)) != 0)
	{
		CMD_WRN("Return code from network connect is %d\n", rc);
		cmd_msleep(2000);
		if (!(i--))
			return CMD_STATUS_FAIL;
	}

	if ((rc = MQTTConnect(&client, &connectData)) != 0) {
		CMD_ERR("Return code from MQTT connect is %d\n", rc);
		return CMD_STATUS_FAIL;
	}
	else
		CMD_DBG("MQTT Connected\n");



	if (OS_ThreadCreate(&mqtt_bg_thread,
		                "",
		                cmd_mqtt_bg,
		                NULL,
		                OS_PRIORITY_NORMAL,
		                CMD_MQTT_BG_THREAD_STACK_SIZE) != OS_OK) {
		CMD_ERR("create mqtt background failed\n");
		return CMD_STATUS_FAIL;
	}


	return CMD_STATUS_OK;
}
Ejemplo n.º 4
0
/**
* Function used to initialize the IoTF client
* @param client - Reference to the Iotfclient
*
* @return int return code
*/
int connectiotf(Iotfclient *client)
{

	int rc = 0;
	if(strcmp(client->config.org,"quickstart") == 0){
		isQuickstart = 1 ;
	}

	const char* messagingUrl = ".messaging.internetofthings.ibmcloud.com";

	char hostname[strlen(client->config.org) + strlen(messagingUrl) + 1];
	
	sprintf(hostname, "%s%s", client->config.org, messagingUrl);

    //TODO : change to 8883 if registered, add support when available in MQTTClient
    int port = 1883;

    char clientId[strlen(client->config.org) + strlen(client->config.type) + strlen(client->config.id) + 5];
    sprintf(clientId, "d:%s:%s:%s", client->config.org, client->config.type, client->config.id);

	NewNetwork(&client->n);
	ConnectNetwork(&client->n, hostname, port);
	MQTTClient(&client->c, &client->n, 1000, buf, 100, readbuf, 100);
 
	MQTTPacket_connectData data = MQTTPacket_connectData_initializer;       
	data.willFlag = 0;
	data.MQTTVersion = 3;
	data.clientID.cstring = clientId;

	if(!isQuickstart) {
		printf("Connecting to registered service with org %s\n", client->config.org);
		data.username.cstring = "use-token-auth";
		printf ("the auth token being used is [%s]\n", client->config.authtoken);
		data.password.cstring = client->config.authtoken;
	}

	data.keepAliveInterval = 10;
	data.cleansession = 1;
	
	rc = MQTTConnect(&client->c, &data);

	if(!isQuickstart) {
		//Subscibe to all commands
		subscribeCommands(client);
	}

	return rc;
}
Ejemplo n.º 5
0
static inline void mqtt_task()
{
    struct Network network;
    char client_id[20];
    uint8_t mqtt_buf[100];
    uint8_t mqtt_readbuf[100];
    MQTTPacket_connectData data = MQTTPacket_connectData_initializer;

    NewNetwork( &network );
    strcpy(client_id, "esp-gizmo-ir");

    if (ConnectNetwork(&network, config_get_mqtt_host(),
                config_get_mqtt_port()) != 0) {
        printf("Connect to MQTT server failed\n");
        return;
    }

    NewMQTTClient(&mqtt_client, &network, 5000, mqtt_buf, 100, mqtt_readbuf, 100);

    data.willFlag       = 0;
    data.MQTTVersion    = 3;
    data.clientID.cstring   = client_id;
    data.username.cstring   = NULL;
    data.password.cstring   = NULL;
    data.keepAliveInterval  = 10;
    data.cleansession   = 0;

    printf("Send MQTT connect ... \n");
    if (MQTTConnect(&mqtt_client, &data) != 0) {
        printf("MQTT connect failed\n");
        return;
    }

    const char *topic = config_get_cmd_topic();
    printf("Sibscribe to topic: %s\n", topic);
    if (MQTTSubscribe(&mqtt_client, topic, QOS1, topic_received) != 0) {
        printf("Subscription failed\n");
        return;
    }

    while (MQTTYield(&mqtt_client, 1000) != DISCONNECTED) {
        printf("free heap: %d bytes\n", xPortGetFreeHeapSize());
        uint16_t free_stack = uxTaskGetStackHighWaterMark(xTaskGetCurrentTaskHandle());
        printf("minimum free stack: %d bytes\n", free_stack);
    };

    printf("Connection dropped, request restart\n");
}
Ejemplo n.º 6
0
//ev init
void mqtt_client_init(EV_ALL *cev, char *host, int port)
{
	int rc;
	if(cev->client.send_queue)
		llqueue_free(cev->client.send_queue);
	cev->client.send_queue = llqueue_new();
	rc = ConnectNetwork(cev->client.ipstack, host, port);
//	if(rc <0)
//	{
//		printf("ConnectNetwork failed\n");
//		MQTTReConnect(&cev->client);
//	}
	snprintf(cev->client.mqtt_server, SERVER_MAX_LEN-1, "%s", host);
	cev->client.mqtt_port = port;
	mqtt_client_initw(cev);  //watchers init
}
Ejemplo n.º 7
0
int main(int argc, char** argv)
{
	int rc = 0;
	unsigned char buf[100];
	unsigned char readbuf[100];

	/**********UART************/
	int		fd = FALSE;
    int 	ret;
    unsigned char	rcv_buf[512];
	unsigned char 	send_buf[64];
	Data_t	rcv_data;
    int i;
	int j;

    cJSON *root,*img,*thm;
    char *out;
	/* Our "gallery" item: */
	root=cJSON_CreateObject();
	cJSON_AddItemToObject(root, "Image", img=cJSON_CreateObject());
	cJSON_AddNumberToObject(img,"Width",800);
	cJSON_AddNumberToObject(img,"Height",600);
	cJSON_AddStringToObject(img,"Title","View from 15th Floor");
	cJSON_AddItemToObject(img, "Thumbnail", thm=cJSON_CreateObject());
	cJSON_AddStringToObject(thm, "Url", "http:/*www.example.com/image/481989943");
	cJSON_AddNumberToObject(thm,"Height",125);
	cJSON_AddStringToObject(thm,"Width","100");
	out=cJSON_Print(root);	cJSON_Delete(root);	printf("%s\n",out);	free(out);	/* Print to text, Delete the cJSON, print it, release the string. */

	fd = UART_Open(fd,"/dev/ttyS1");
    if(FALSE == fd){
	   printf("open error\n");
	   exit(1);
    }
    ret  = UART_Init(fd,115200,0,8,1,'N');
    if (FALSE == fd){
	   printf("Set Port Error\n");
	   exit(1);
    }
    ret  = UART_Send(fd,"*IDN?\n",6);
    if(FALSE == ret){
	   printf("write error!\n");
	   exit(1);
    }
    printf("command: %s\n","*IDN?");
    memset(rcv_buf,0,sizeof(rcv_buf));

	if (argc < 2)
		usage();

	char* topic = argv[1];

//	if (strchr(topic, '#') || strchr(topic, '+'))
//		opts.showtopics = 1;
//	if (opts.showtopics)
//		printf("topic is %s\n", topic);

	getopts(argc, argv);

	Network n;
	Client c;
	MQTTMessage message={0,0,0,0,"hello",5};//dup,qos,retained,packetid,payload,payloadlen


	NewNetwork(&n);
	ConnectNetwork(&n, opts.host, opts.port);
	MQTTClient(&c, &n, 1000, buf, 100, readbuf, 100);

	MQTTPacket_connectData data = MQTTPacket_connectData_initializer;
	data.willFlag = 0;
	data.MQTTVersion = 3;
	data.clientID.cstring = opts.clientid;
	data.username.cstring = opts.username;
	data.password.cstring = opts.password;

	data.keepAliveInterval = 10;
	data.cleansession = 1;
	printf("Connecting to %s %d\n", opts.host, opts.port);

	rc = MQTTConnect(&c, &data);
	printf("Connected %d\n", rc);

//test
while(1)
{
		message.payload = "efewewreweefer";
        message.payloadlen = strlen(message.payload);
			MQTTPublish(&c,topic,&message);
}
	while (!toStop)
	{
		MQTTYield(&c, 1000);
	}
	printf("Stopping\n");
	UART_Close(fd);
	MQTTDisconnect(&c);
	n.disconnect(&n);

	return 0;
}
Ejemplo n.º 8
0
Archivo: mpush.c Proyecto: cgoder/cpush
int Cpush_connect(unsigned int* clientHandle,struct connectOpt* pOpt)
{
	int ret = CPUSH_RET_OK;
	*clientHandle = 0;
	unsigned char* buf = 0;
	unsigned char* readbuf = 0;
	Network* network = NULL;
	Client* pClient = NULL;

	if (!pOpt) {
		ret = CPUSH_RET_ERROR_PARA;
		goto FAIL;
	}

	/*check client id*/
	if ((!pOpt->clientid)|| (strlen((const char*)pOpt->clientid) > MOSQ_MQTT_ID_MAX_LENGTH)){
		ret = CPUSH_RET_ERROR_PARA;
		goto FAIL;
	}

	/*connect to host*/
	// Network n;
	network = (Network*)calloc(1,sizeof(Network));
	if (!network) {
		ret = CPUSH_RET_FAIL;
		goto FAIL;
	}
	NewNetwork(network);
	if (ConnectNetwork(network, (char*)pOpt->host, pOpt->port) < 0) {
		printf("connect to %s:%d error!\n", pOpt->host, pOpt->port);
		ret = CPUSH_RET_ERROR_CONNECTFAIL;
		goto FAIL;
	}

	/*init mqtt client*/
	pClient = (Client*)calloc(1,sizeof(Client));
	if (!pClient) {
		ret = CPUSH_RET_FAIL;
		goto FAIL;
	}
	buf = (unsigned char*)calloc(MOSQ_MQTT_BUFFER_MAX_SIZE,sizeof(char));
	if (!buf) {
		ret = CPUSH_RET_FAIL;
		goto FAIL;
	}
	readbuf = (unsigned char*)calloc(MOSQ_MQTT_BUFFER_MAX_SIZE,sizeof(char));
	if (!readbuf) {
		ret = CPUSH_RET_FAIL;
		goto FAIL;
	}
	MQTTClient(pClient, network, 1000, buf, MOSQ_MQTT_BUFFER_MAX_SIZE, readbuf, MOSQ_MQTT_BUFFER_MAX_SIZE);

	/*connect to mqtt server*/
	MQTTPacket_connectData data = MQTTPacket_connectData_initializer;       
	data.willFlag = 0;
	data.MQTTVersion = 4;
	data.cleansession = 1;
	data.clientID.cstring = pOpt->clientid;
	if (pOpt->username) {
		data.username.cstring = pOpt->username;		
	}
	if (pOpt->password) {
		data.password.cstring = pOpt->password;		
	}
	data.keepAliveInterval = 10;
	printf("Connecting to %s %d\n", pOpt->host, pOpt->port);
	int rc = MQTTConnect(pClient, &data);
	printf("Connected %d\n", rc);
	if (SUCCESS != rc) {
		printf("Cpush_connect fail! ret:%d", rc);
		ret = CPUSH_RET_FAIL;
		goto FAIL;
	}
	printf("Cpush_connect OK!");
	ret = CPUSH_RET_OK;
	*clientHandle = (unsigned int)pClient;
	return CPUSH_RET_OK;

FAIL:
	if (0 != network->my_socket) {network->disconnect(network);}
	if (network) {free(network);}
	if (buf) {free(buf);}
	if (readbuf) {free(readbuf);}
	if (pClient) {free(pClient);}
	return ret;
}
Ejemplo n.º 9
0
static void  mqtt_task(void *pvParameters)
{
    int ret         = 0;
    struct Network network;
    MQTTClient client   = DefaultClient;
    char mqtt_client_id[20];
    uint8_t mqtt_buf[100];
    uint8_t mqtt_readbuf[100];
    MQTTPacket_connectData data = MQTTPacket_connectData_initializer;

    NewNetwork( &network );
    memset(mqtt_client_id, 0, sizeof(mqtt_client_id));
    strcpy(mqtt_client_id, "ESP-");
    strcat(mqtt_client_id, get_my_id());

    while(1) {
        xSemaphoreTake(wifi_alive, portMAX_DELAY);
        printf("%s: started\n\r", __func__);
        printf("%s: (Re)connecting to MQTT server %s ... ",__func__,
               MQTT_HOST);
        ret = ConnectNetwork(&network, MQTT_HOST, MQTT_PORT);
        if( ret ){
            printf("error: %d\n\r", ret);
            taskYIELD();
            continue;
        }
        printf("done\n\r");
        NewMQTTClient(&client, &network, 5000, mqtt_buf, 100,
                      mqtt_readbuf, 100);

        data.willFlag       = 0;
        data.MQTTVersion    = 3;
        data.clientID.cstring   = mqtt_client_id;
        data.username.cstring   = MQTT_USER;
        data.password.cstring   = MQTT_PASS;
        data.keepAliveInterval  = 10;
        data.cleansession   = 0;
        printf("Send MQTT connect ... ");
        ret = MQTTConnect(&client, &data);
        if(ret){
            printf("error: %d\n\r", ret);
            DisconnectNetwork(&network);
            taskYIELD();
            continue;
        }
        printf("done\r\n");
        MQTTSubscribe(&client, "/esptopic", QOS1, topic_received);
        xQueueReset(publish_queue);

        while(1){

            char msg[PUB_MSG_LEN - 1] = "\0";
            while(xQueueReceive(publish_queue, (void *)msg, 0) ==
                  pdTRUE){
                printf("got message to publish\r\n");
                MQTTMessage message;
                message.payload = msg;
                message.payloadlen = PUB_MSG_LEN;
                message.dup = 0;
                message.qos = QOS1;
                message.retained = 0;
                ret = MQTTPublish(&client, "/beat", &message);
                if (ret != SUCCESS ){
                    printf("error while publishing message: %d\n", ret );
                    break;
                }
            }

            ret = MQTTYield(&client, 1000);
            if (ret == DISCONNECTED)
                break;
        }
        printf("Connection dropped, request restart\n\r");
        DisconnectNetwork(&network);
        taskYIELD();
    }
}
Ejemplo n.º 10
0
/*
 * Application's entry point dynamic schedule.  Main is somewhat too large because of the MQTT stuff
 * allmighty whileloop
 */
int main(int argc, char** argv)
{

    /* Stop WDT and initialize lcd, clcks, main interfaces */
    stopWDT();
    init_clocks(); //init clock for LCD
    init_lcd();
    initClk(); //init clock for wifi
    Delay(5);
    init_main();
    Delay(5);

    load_data();

    int rc = 0;
    unsigned char buf[100];
    unsigned char readbuf[100];

    NewNetwork(&n);
    rc = ConnectNetwork(&n, MQTT_BROKER_SERVER, 1883);

    if (rc != 0) {
        CLI_Write(" Failed to connect to MQTT broker \n\r");
    }

    MQTTClient(&hMQTTClient, &n, 1000, buf, 100, readbuf, 100);
    MQTTPacket_connectData cdata = MQTTPacket_connectData_initializer;
    cdata.MQTTVersion = 3;
    cdata.clientID.cstring = "daniel";
    rc = MQTTConnect(&hMQTTClient, &cdata);

    if (rc != 0) {
        CLI_Write(" Failed to start MQTT client \n\r");
        //LOOP_FOREVER();
    }

    rc = MQTTSubscribe(&hMQTTClient, SUBSCRIBE_TOPIC, QOS0, messageArrived);

    if (rc != 0) {
        CLI_Write(" Failed to subscribe to /msp/cc3100/demo topic \n\r");
        //LOOP_FOREVER();
    }

    MQTTYield(&hMQTTClient, 10);
    int8_t buffer[2] = "on";
    MQTTMessage msg;
    msg.dup = 0;
    msg.id = 0;
    msg.payload = buffer;
    msg.payloadlen = 8;
    msg.qos = QOS0;
    msg.retained = 0;
    MQTTPublish(&hMQTTClient, PUBLISH_TOPIC, &msg);
    Delay(20);

    backlight_off();
    while(1) {
        MQTTYield(&hMQTTClient, 10);
        debounce++;

        if(send_goal_bool) {
            int8_t buffer2[15] = "               ";
            sprintf(buffer2, "%d", goal_steps);
            msg;
            msg.dup = 0;
            msg.id = 0;
            msg.payload = buffer2;
            msg.payloadlen = 15;
            msg.qos = QOS0;
            msg.retained = 0;
            MQTTPublish(&hMQTTClient, PUBLISH_TOPIC, &msg);
            Delay(20);
            send_goal_bool = 0;
        }else if(send_on_bool) {
            int8_t buffer2[2] = "on";
            msg;
            msg.dup = 0;
            msg.id = 0;
            msg.payload = buffer2;
            msg.payloadlen = 2;
            msg.qos = QOS0;
            msg.retained = 0;
            MQTTPublish(&hMQTTClient, PUBLISH_TOPIC, &msg);
            Delay(20);
            send_on_bool = 0;
        } else if( (P3IN & BIT5) == 0 && debounce > 20) {
          debounce = 0;
          menu_select();
        } else if ( (P1IN & BIT4) == 0 && debounce > 10) {
          debounce = 0;
          menu();
        } else if ( steps_taken >= goal_steps && active_bool == 1 ) {
          P1OUT &= ~BIT0;
          int8_t buffer2[1] = "g";
          msg;
          msg.dup = 0;
          msg.id = 0;
          msg.payload = buffer2;
          msg.payloadlen = 1;
          msg.qos = QOS0;
          msg.retained = 0;
          MQTTPublish(&hMQTTClient, "on", &msg);
          Delay(20);
          MAP_Interrupt_disableInterrupt(INT_ADC14);
          active_bool = 0;
          view_goal_menu();
        }
    }
}
Ejemplo n.º 11
0
MqttReturnCode mqttClient_connect(AJBMqttClient *client, char *host,int port){
    
    int rc = 0;//return code of mqtt function
    
    if (host != client->host) {
        strcpy(client->host, host);
    }
    
    client->port = port;
    NewNetwork(&client->n);
    
    int interval = client->aliveAttr.recon_int;
    interval = interval>0?interval:1;
    int max = client->aliveAttr.recon_max;
    client->c.indexTag = client->indexTag;
reconnect:
    rc = ConnectNetwork(&client->n, host, port);
//    MqttLog("connect result -------> %d",rc);
    MQTTClient(&client->c, &client->n, client->timout_ms, client->sendBuf, PACKET_BUF_SIZE, client->readBuf, PACKET_BUF_SIZE);
    
    MQTTPacket_connectData data = MQTTPacket_connectData_initializer;
    
    //    data.willFlag = 0;
    data.MQTTVersion = 4;
    data.clientID.cstring = client->clientId;
    data.username.cstring = client->username;
    data.password.cstring = client->password;
    data.keepAliveInterval = client->keepAlive;
    data.cleansession = client->cleanSession;
    
    if (client->will.willFlag) {
        data.willFlag = client->will.willFlag;
        data.will.message.cstring = client->will.willContent;
        data.will.qos = 2;
        data.will.retained = client->will.retain;
        data.will.topicName.cstring = client->will.willTopic;
    }
    MqttLog("[CONNECT request] %s:%d",host,port);
    rc = MQTTConnect(&client->c, &data);
    
    client->isConnected = (rc==SUCCESS);
    
    if(rc == SUCCESS){
        printf("%s,%16s:%d,%4d ----------------ok\n",client->clientId,host,port,client->cleanSession);
        reportOnline(client);
    }
    else{
        client->n.disconnect(&client->n);
        if (client->dispatcher.onLoop) {
            client->dispatcher.onLoop(client);
        }
        MqttLog("[CONNECT failed] %s:%d",host,port);
        logToLocal(client->indexTag,log_erro_path,"[CONNECT failed] %s:%d ---> %s %d",host,port,client->clientId,client->keepworking);
        if (client->keepworking) {
            if (client->aliveAttr.auto_con && ((client->aliveAttr.recon_max==0) || (--max >0)) ) {
                sleep(interval);
                goto reconnect;
            }
        }
    }
    
    return rc;
}
Ejemplo n.º 12
0
int main(int argc, char** argv)
{
	int rc = 0;
    struct pando_buffer *bin_buf;
    uint16_t payload_type = 0;
    MQTTMessage msg;
	unsigned char buf[500];
	unsigned char readbuf[500];
    char payload_type_c[] = {'c', 'e', 'd'};
    
    bin_buf = construct_data_package_to_server(&payload_type);
    decode_data(bin_buf, PAYLOAD_TYPE_DATA);

    /* command test, event is same as command except the type */
    bin_buf = constuct_event_package_to_server(&payload_type);
    decode_command(bin_buf, PAYLOAD_TYPE_COMMAND);
    return 0;
    
	if (argc < 2)
		usage();
	
	char* topic = argv[1];

    getopts(argc, argv);
    
	if (strchr(topic, '#') || strchr(topic, '+'))
		opts.showtopics = 1;
	if (opts.showtopics)
		printf("topic is %s\n", topic);

		

	Network n;
	Client c;

	signal(SIGINT, cfinish);
	signal(SIGTERM, cfinish);

	NewNetwork(&n);
	ConnectNetwork(&n, opts.host, opts.port);
	MQTTClient(&c, &n, 1000, buf, 100, readbuf, 100);
 
	MQTTPacket_connectData data = MQTTPacket_connectData_initializer;       
	data.willFlag = 0;
	data.MQTTVersion = 3;
	data.clientID.cstring = opts.clientid;
	data.username.cstring = opts.username;
	data.password.cstring = opts.password;

	data.keepAliveInterval = 10;
	data.cleansession = 1;
	printf("Connecting to %s %d\n", opts.host, opts.port);
	
	rc = MQTTConnect(&c, &data);
	printf("Connected %d\n", rc);
    
    printf("Subscribing to %s\n", topic);
	rc = MQTTSubscribe(&c, topic, opts.qos, messageArrived);
	printf("Subscribed %d\n", rc);

	while (!toStop)
	{        
		MQTTYield(&c, 1000);
        
        if (toSend)
        {
            if (strstr(topic, "/d"))
            {
                /* data test */
                bin_buf = construct_data_package_to_server(&payload_type);
                //decode_data(bin_buf, PAYLOAD_TYPE_DATA);
            }

            if (strstr(topic, "/e"))
            {
                /* command test */
                bin_buf = constuct_event_package_to_server(&payload_type);
                //decode_command(bin_buf, PAYLOAD_TYPE_COMMAND);
            }
            msg.qos = opts.qos;
            msg.retained = 0;
            msg.dup = 0;
            
            msg.payload = bin_buf->buffer + bin_buf->offset;
            msg.payloadlen = bin_buf->buff_len - bin_buf->offset;

            /* 
                        before publish a message, you need to generate a topic with payload_type
                        max device id is 8 bytes, hex to char need 8*2 bytes, '/' need 1 byte, type need 1 byte 
                    */
            char publish_topic[8*2 + 1 + 1];
            memset(publish_topic, 0, sizeof(publish_topic));
            sprintf(publish_topic, "%s/%c", opts.clientid, payload_type_c[payload_type - 1]);
            printf(publish_topic);
            
            rc = MQTTPublish(&c, publish_topic, &msg);
            toSend = 0;
            pd_free(bin_buf);
            printf("published rc %d, len %d\n", rc, (int)msg.payloadlen);
        }

	}
	
	printf("Stopping\n");

	MQTTDisconnect(&c);
	n.disconnect(&n);

	return 0;
}