void ICACHE_FLASH_ATTR wifiConnectCb(uint8_t status){
	if(status == STATION_GOT_IP){
		MQTT_Connect(&mqttClient);
	} else {
		MQTT_Disconnect(&mqttClient);
	}
}
Esempio n. 2
0
File: app.c Progetto: flo90/esp-ginx
static void ICACHE_FLASH_ATTR mqtt_app_timer_cb(void *arg){

	
	struct ip_info ipConfig;
	
	wifi_get_ip_info(STATION_IF, &ipConfig);	
	wifiStatus = wifi_station_get_connect_status();

	//check wifi
	if(wifiStatus != lastWifiStatus){

		lastWifiStatus = wifiStatus;
		
		if(wifiStatus==STATION_GOT_IP && ipConfig.ip.addr != 0){
        	MQTT_DBG("MQTT: Detected wifi network up");
        	MQTT_Connect(&mqtt_client);       
	    }
	    else{
	    	MQTT_DBG("MQTT: Detected wifi network down");
	    	MQTT_Disconnect(&mqtt_client);    
	    }

	}
	    
}
Esempio n. 3
0
bool ICACHE_FLASH_ATTR checkSmartConfig(enum SmartConfigAction action) {
	static doingSmartConfig = false;

	switch (action) {
	case SC_CHECK:
		break;
	case SC_HAS_STOPPED:
		os_printf("Finished smartConfig\n");
		stopFlash();
		doingSmartConfig = false;
		MQTT_Connect(&mqttClient);
		break;
	case SC_TOGGLE:
		if (doingSmartConfig) {
			os_printf("Stop smartConfig\n");
			stopFlash();
			smartconfig_stop();
			doingSmartConfig = false;
			wifi_station_disconnect();
			wifi_station_connect();
		} else {
			os_printf("Start smartConfig\n");
			MQTT_Disconnect(&mqttClient);
			mqttConnected = false;
			startFlash(100, true);
			doingSmartConfig = true;
			smartconfig_start(smartConfig_done, true);
		}
		break;
	}
	return doingSmartConfig;
}
static void ICACHE_FLASH_ATTR MQTTLogonTimerCb(void *arg)
{
static int resetCnt=0;

if (allow_mqtt_init)
	{
	if (!logged_on_to_network)
		{
		int x=wifi_station_get_connect_status();
		if (x==STATION_GOT_IP)
			{
			logged_on_to_network = 1;
			if (!logged_on_to_mqtt)
				{
				INFO("\n\rNETWRK OK\n");
				mqtt_init();
				MQTT_Connect(&mqttClient);
				INFO("MQTT OK\r\n");
				logged_on_to_mqtt = 1;
				}
			}
		else
			{
			if (logged_on_to_mqtt) // Disconnect and reconnect later
				{
				MQTT_Disconnect(&mqttClient);
				INFO("Left MQTT\r\n");
				logged_on_to_mqtt = 0;
				}
			}

		}
	}
}
Esempio n. 5
0
void wifi_connect_cb(uint8_t status)
{
	if(status == STATION_GOT_IP){
		MQTT_Connect(&mqttClient);
	} else {
		MQTT_Disconnect(&mqttClient);
	}
}
Esempio n. 6
0
void ICACHE_FLASH_ATTR mqttDisconnectedCb(uint32_t *args) {
//	MQTT_Client* client = (MQTT_Client*)args;
	os_printf("MQTT Disconnected\n");
	mqttConnected = false;
	if (!checkSmartConfig(SC_CHECK)) {
		MQTT_Connect(&mqttClient);
	}
}
Esempio n. 7
0
void ICACHE_FLASH_ATTR
MQTT_Task(os_event_t *e)
{
	MQTT_Client* client = (MQTT_Client*)e->par;
	uint8_t dataBuffer[MQTT_BUF_SIZE];
	uint16_t dataLen;
	sint8 res;
	switch(client->connState){

	case TCP_RECONNECT_REQ:
		break;
	case TCP_RECONNECT:
		MQTT_Connect(client);
//spam		INFO("TCP:Reconect to: %s:%d\r\n", client->host, client->port);
		client->connState = TCP_CONNECTING;
		break;
	case MQTT_CONNECT_SEND:
		mqtt_msg_init(&client->mqtt_state.mqtt_connection, client->mqtt_state.out_buffer, client->mqtt_state.out_buffer_length);
		client->mqtt_state.outbound_message = mqtt_msg_connect(&client->mqtt_state.mqtt_connection, client->mqtt_state.connect_info);
		if(client->security){
			res = espconn_secure_sent(client->pCon, client->mqtt_state.outbound_message->data, client->mqtt_state.outbound_message->length);
		}
		else
		{
			res = espconn_sent(client->pCon, client->mqtt_state.outbound_message->data, client->mqtt_state.outbound_message->length);
		}
		if (res != ESPCONN_OK) {
//spam			INFO("MQTT: espconn_sent returned %d at line %d\r\n", res, __LINE__);
		}

//spam		INFO("MQTT: Send mqtt connection info, to broker %s:%d\r\n", client->host, client->port);
		client->connState = MQTT_CONNECT_SENDING;
		client->mqtt_state.outbound_message = NULL;
		break;
	case MQTT_DATA:

		if(QUEUE_Gets(&client->msgQueue, dataBuffer, &dataLen, MQTT_BUF_SIZE) == 0){
//spam			INFO("MQTT: Sending..\r\n");
			if(client->security){
				res = espconn_secure_sent(client->pCon, dataBuffer, dataLen);
			}
			else{
				res = espconn_sent(client->pCon, dataBuffer, dataLen);
			}
			if (res != ESPCONN_OK) {
//spam				INFO("MQTT: espconn_sent returned %d at line %d\r\n", res, __LINE__);
			}

			client->mqtt_state.outbound_message = NULL;
			if(client->mqtt_state.pending_msg_type == MQTT_MSG_TYPE_PUBLISH && client->mqtt_state.pending_msg_id == 0)
//spam				INFO("MQTT: Publish message is done!\r\n");
			break;
		}
		break;
//spam	default:
//spam		INFO("MQTT: Unhandled state %d!\r\n", client->connState);
	}
}
Esempio n. 8
0
void onWifiEvent(System_Event_t *event) {
	if (event->event == EVENT_STAMODE_GOT_IP) {
		DEBUG_PRINT("[HAP]Got IP\n");
		if (hapAddress) {
			DEBUG_PRINT("[HAP]Reconnecting to MQTT\n");
			MQTT_Connect(&mqttClient);
		}
	}
}
Esempio n. 9
0
void ICACHE_FLASH_ATTR wifiConnectCb(uint8_t status) {
	os_printf("WiFi status: %d\r\n", status);
	if (status == STATION_GOT_IP) {
		MQTT_Connect(&mqttClient);
	} else {
		mqttConnected = false;
		MQTT_Disconnect(&mqttClient);
	}
}
Esempio n. 10
0
void ICACHE_FLASH_ATTR
MQTT_Reconnect(MQTT_Client* client) {
  DBG_MQTT("MQTT: Reconnect requested\n");
  if (client->connState == MQTT_DISCONNECTED)
    MQTT_Connect(client);
  else if (client->connState == MQTT_CONNECTED)
    mqtt_doAbort(client);
  // in other cases we're already in the reconnecting process
}
Esempio n. 11
0
void ICACHE_FLASH_ATTR
wifiConnectCb(uint8_t status) {

  // Use the hex encoded system_get_chip_id() value as
  // an unique topic (that still fits on the screen)
  os_sprintf(clientid, "/%0x", system_get_chip_id());

  if (status == STATION_GOT_IP) {
    MQTT_Connect(&mqttClient);
  }
}
Esempio n. 12
0
/*
 * @brief: Timer function to handle timeouts
 */
static void ICACHE_FLASH_ATTR
mqtt_timer(void* arg) {
  MQTT_Client* client = (MQTT_Client*)arg;
  //DBG_MQTT("MQTT: timer CB\n");

  switch (client->connState) {
  default: break;

  case MQTT_CONNECTED:
    // first check whether we're timing out for an ACK
    if (client->pending_buffer != NULL && --client->timeoutTick == 0) {
      // looks like we're not getting a response in time, abort the connection
      mqtt_doAbort(client);
      client->timeoutTick = 0; // trick to make reconnect happen in 1 second
      return;
    }

    // check whether our last keep-alive timed out
    if (client->keepAliveAckTick > 0 && --client->keepAliveAckTick == 0) {
      os_printf("\nMQTT ERROR: Keep-alive timed out\n");
      mqtt_doAbort(client);
      return;
    }

    // check whether we need to send a keep-alive message
    if (client->keepAliveTick > 0 && --client->keepAliveTick == 0) {
      // timeout: we need to send a ping message
      //DBG_MQTT("MQTT: Send keepalive\n");
      mqtt_msg_pingreq(&client->mqtt_connection);
      PktBuf *buf = PktBuf_New(client->mqtt_connection.message.length);
      os_memcpy(buf->data, client->mqtt_connection.message.data,
          client->mqtt_connection.message.length);
      buf->filled = client->mqtt_connection.message.length;
      client->msgQueue = PktBuf_Unshift(client->msgQueue, buf);
      mqtt_send_message(client);
      client->keepAliveTick = client->connect_info.keepalive;
      client->keepAliveAckTick = client->sendTimeout;
    }

    break;

  case TCP_RECONNECT_REQ:
    if (client->timeoutTick == 0 || --client->timeoutTick == 0) {
      // it's time to reconnect! start by re-enqueueing anything pending
      if (client->pending_buffer != NULL) {
        client->msgQueue = PktBuf_Unshift(client->msgQueue, client->pending_buffer);
        client->pending_buffer = NULL;
      }
      client->connect_info.clean_session = 0; // ask server to keep state
      MQTT_Connect(client);
    }
  }
}
Esempio n. 13
0
void ICACHE_FLASH_ATTR
wifiStateChangeCb(uint8_t status)
{
  if (flashConfig.mqtt_enable) {
    if (status == wifiGotIP && mqttClient.connState < TCP_CONNECTING) {
      MQTT_Connect(&mqttClient);
    }
    else if (status == wifiIsDisconnected && mqttClient.connState == TCP_CONNECTING) {
      MQTT_Disconnect(&mqttClient);
    }
  }
}
Esempio n. 14
0
void sntpfn()
{
    u32_t ts = 0;
    ts = sntp_get_current_timestamp();
    os_printf("current time : %s\n", sntp_get_real_time(ts));
    if (ts == 0) {
        //os_printf("did not get a valid time from sntp server\n");
    } else {
            os_timer_disarm(&sntp_timer);
            MQTT_Connect(&mqttClient);
    }
}
Esempio n. 15
0
void ICACHE_FLASH_ATTR wifiConnectCb(uint8_t status)
{
	if(status == STATION_GOT_IP){
		MQTT_Connect(&mqttClient);
	} else {
		INFO("No wifi available. Setting 1 min timer for retry...\n");
		os_timer_disarm(&wifiReconnectTimer);
		os_timer_setfn(&wifiReconnectTimer, (os_timer_func_t *)wifiReconnectTimerCB, (void *)0);
		os_timer_arm(&wifiReconnectTimer, DELAY, 1);
		INFO("Device MODE set to LOCAL !\r\n");
		dDEVICE_MODE=1;
	}
}
Esempio n. 16
0
uint32_t ICACHE_FLASH_ATTR
MQTTCMD_Connect(CmdPacket *cmd) {
  CmdRequest req;
  cmdRequest(&req, cmd);

#ifdef MQTT_1_CLIENT

  if (mqttClient.connState == MQTT_CONNECTED && mqttClient.cmdConnectedCb) {
    mqttClient.cmdConnectedCb((uint32_t*)&mqttClient);
  }
  else if (mqttClient.connState == MQTT_DISCONNECTED && mqttClient.cmdDisconnectedCb) {
    mqttClient.cmdDisconnectedCb((uint32_t*)&mqttClient);
  }

  return 1;

#else
  if (cmdGetArgc(&req) != 4)
    return 0;

  // get mqtt client
  uint32_t client_ptr;
  cmdPopArg(&req, (uint8_t*)&client_ptr, 4);
  MQTT_Client* client = (MQTT_Client*)client_ptr;
  DBG("MQTT: MQTTCMD_Connect client ptr=%p\n", (void*)client_ptr);

  uint16_t len;

  // get host
  if (client->host)
  os_free(client->host);
  len = cmdArgLen(&req);
  if (len > 128) return 0; // safety check
  client->host = (char*)os_zalloc(len + 1);
  cmdPopArg(&req, client->host, len);
  client->host[len] = 0;

  // get port
  cmdPopArg(&req, (uint8_t*)&client->port, 4);

  // get security
  cmdPopArg(&req, (uint8_t*)&client->security, 4);
  DBG("MQTT: MQTTCMD_Connect host=%s, port=%d, security=%d\n",
    client->host,
    client->port,
    client->security);

  MQTT_Connect(client);
  return 1;
#endif
}
Esempio n. 17
0
void ICACHE_FLASH_ATTR
wifiConnectCb(uint8_t status) {

  // Use the hex encoded system_get_chip_id() value as
  // an unique topic (that still fits on the screen)
  os_sprintf(clientid, "/%0x", system_get_chip_id());
  
  if(status == STATION_GOT_IP){
    os_printf("Connecting to MQTT server %s:%d\n", MQTT_HOST, MQTT_PORT);
    MQTT_Connect(&mqttClient);
  } else {
    MQTT_Disconnect(&mqttClient);
  }
}
Esempio n. 18
0
void ICACHE_FLASH_ATTR wifiConnectCb(uint8_t status)
{
	if(status == STATION_GOT_IP){

		os_printf("Trying to find external IP address\n");
		http_get("http://wtfismyip.com/text", http_callback_IP);

		if(sysCfg.mqtt_enable==1) {
			MQTT_Connect(&mqttClient);
		} else {
			MQTT_Disconnect(&mqttClient);
		}
	}	
}
Esempio n. 19
0
void on_timer(void *arg)
{
	uint8 new_status = wifi_station_get_connect_status();

	if (new_status != wifi_status) {
		if (new_status == STATION_GOT_IP) {
			MQTT_Connect(&mqtt_client);
		} else {
			MQTT_Disconnect(&mqtt_client);
		}
	}

	wifi_status = new_status;
}
Esempio n. 20
0
static void ICACHE_FLASH_ATTR udp_received(void *arg, char *data, unsigned short len)
{
    struct espconn *udpconn= (struct espconn*)arg;
    if (len > 5 && strncmp(data, "HAP", 3) == 0)
    {
        const char* hapServer = &data[5];
        if (strcmp(settings.serverName, hapServer) != 0)
            return;

        remot_info *info = NULL;
        espconn_get_connection_info(udpconn, &info, 0);

        uint16_t port = (data[3] << 8) | data[4];
        uint32_t address = *(uint32_t*)info->remote_ip;

        if (port == hapPort && address == hapAddress)
            return;

        hapAddress = address;
        hapPort = port;

        static bool inited = false;

        DEBUG_PRINT("[HAP]Discover from "IPSTR":%d\n", IP2STR(&address), port);

        if (inited)
        {
            MQTT_Disconnect(&mqttClient);
            DEBUG_PRINT("[HAP]Disconnect MQTT\n");
        }

        char aux[20];
        os_sprintf(aux, IPSTR, IP2STR(&address));
        MQTT_InitConnection(&mqttClient, aux, hapPort);

        os_sprintf(aux, "client_%d", system_get_chip_id());
        MQTT_InitClient(&mqttClient, aux, settings.mqttUser, settings.mqttPassword, MQTT_KEEPALIVE, 1);
        MQTT_OnConnected(&mqttClient, mqttConnectedCb);
        MQTT_OnDisconnected(&mqttClient, mqttDisconnectedCb);
        MQTT_OnPublished(&mqttClient, mqttPublishedCb);
        MQTT_OnData(&mqttClient, mqttDataCb);
        MQTT_Connect(&mqttClient);

        inited = true;
    }
}
Esempio n. 21
0
void ICACHE_FLASH_ATTR
MQTT_Task(os_event_t *e)
{
	MQTT_Client* client = (MQTT_Client*)e->par;
	uint8_t dataBuffer[MQTT_BUF_SIZE];
	uint16_t dataLen;
	if(e->par == 0)
		return;
	switch(client->connState){

	case TCP_RECONNECT_REQ:
		break;
	case TCP_RECONNECT:
		MQTT_Connect(client);
		INFO("TCP: Reconnect to: %s:%d\r\n", client->host, client->port);
		client->connState = TCP_CONNECTING;
		break;
	case MQTT_DATA:
		if(QUEUE_IsEmpty(&client->msgQueue) || client->sendTimeout != 0) {
			break;
		}
		if(QUEUE_Gets(&client->msgQueue, dataBuffer, &dataLen, MQTT_BUF_SIZE) == 0){
			client->mqtt_state.pending_msg_type = mqtt_get_type(dataBuffer);
			client->mqtt_state.pending_msg_id = mqtt_get_id(dataBuffer, dataLen);


			client->sendTimeout = MQTT_SEND_TIMOUT;
			INFO("MQTT: Sending, type: %d, id: %04X\r\n",client->mqtt_state.pending_msg_type, client->mqtt_state.pending_msg_id);
			if(client->security){
				espconn_secure_sent(client->pCon, dataBuffer, dataLen);
			}
			else{
				espconn_sent(client->pCon, dataBuffer, dataLen);
			}

			client->mqtt_state.outbound_message = NULL;
			break;
		}
		break;
	case TCP_CONNECTING_ERROR:
		MQTT_Disconnect(client);
		MQTT_exit(client);
		break;
	}
}
void ICACHE_FLASH_ATTR wifi_handle_event_cb(System_Event_t *evt) {
	os_printf("event %x\n", evt->event);
	switch (evt->event) {
	case EVENT_STAMODE_CONNECTED:
		os_printf("connect to ssid %s, channel %d\n",
				evt->event_info.connected.ssid,
				evt->event_info.connected.channel);
		MQTT_Disconnect(&mqttClient);
		break;
	case EVENT_STAMODE_DISCONNECTED:
		os_printf("disconnect from ssid %s, reason %d\n",
				evt->event_info.disconnected.ssid,
				evt->event_info.disconnected.reason);
		MQTT_Disconnect(&mqttClient); //断开mqtt连接
		break;
	case EVENT_STAMODE_AUTHMODE_CHANGE:
		os_printf("mode: %d -> %d\n", evt->event_info.auth_change.old_mode,
				evt->event_info.auth_change.new_mode);
		MQTT_Disconnect(&mqttClient);
		break;
	case EVENT_STAMODE_GOT_IP:
		os_printf("ip:" IPSTR ",mask:" IPSTR ",gw:" IPSTR,
				IP2STR(&evt->event_info.got_ip.ip),
				IP2STR(&evt->event_info.got_ip.mask),
				IP2STR(&evt->event_info.got_ip.gw));
		os_printf("\n");
		os_printf("mqtt start connect!\n");
		MQTT_Connect(&mqttClient);
		break;
	case EVENT_SOFTAPMODE_STACONNECTED:
		os_printf("station: " MACSTR "join, AID = %d\n",
				MAC2STR(evt->event_info.sta_connected.mac),
				evt->event_info.sta_connected.aid);
		MQTT_Disconnect(&mqttClient);
		break;
	case EVENT_SOFTAPMODE_STADISCONNECTED:
		os_printf("station: " MACSTR "leave, AID = %d\n",
				MAC2STR(evt->event_info.sta_disconnected.mac),
				evt->event_info.sta_disconnected.aid);
		MQTT_Disconnect(&mqttClient);
		break;
	default:
		break;
	}
}
Esempio n. 23
0
void FUNCTION_ATTRIBUTE
MQTT_Task(MQTT_Client *client)
{
	INFO("MQTT TASK: state: %d\n", client->connState);
	uint8_t dataBuffer[MQTT_BUF_SIZE];

	uint16_t dataLen;
    struct data_buf buffer;
	if(client == NULL)
		return;
	switch(client->connState){
	case TCP_RECONNECT_REQ:
		break;
	case TCP_RECONNECT:
		MQTT_Connect(client);
		INFO("TCP: Reconnect to: %s:%d\r\n", client->host, client->port);
		client->connState = TCP_CONNECTING;
		break;
	case MQTT_DATA:
		INFO("MQTT TASK DATA\n");
		if(QUEUE_IsEmpty(&client->msgQueue) || client->sendTimeout != 0) {
			break;
		}
		if(QUEUE_Gets(&client->msgQueue, dataBuffer, &dataLen, MQTT_BUF_SIZE) == 0){
			INFO("%s, dataLen:%d\n", __func__, dataLen);
			client->mqtt_state.pending_msg_type = mqtt_get_type(dataBuffer);
			client->mqtt_state.pending_msg_id = mqtt_get_id(dataBuffer, dataLen);
			client->sendTimeout = MQTT_SEND_TIMOUT;
            buffer.length = dataLen;
            buffer.data = dataBuffer;
			INFO("MQTT: Sending, type: %d, id: %04X\r\n",client->mqtt_state.pending_msg_type, client->mqtt_state.pending_msg_id);
			net_tcp_send(client->pCon, buffer, client->sendTimeout);
			client->mqtt_state.outbound_message = NULL;
			break;
		}
		break;
	case TCP_CONNECTING_ERROR:
		MQTT_Disconnect(client);
		MQTT_exit(client);
		break;
	}
}
Esempio n. 24
0
uint32_t ICACHE_FLASH_ATTR
MQTTCMD_Connect(CmdPacket *cmd) {
  CmdRequest req;
  CMD_Request(&req, cmd);

  if (CMD_GetArgc(&req) != 4)
    return 0;

  // get mqtt client
  uint32_t client_ptr;
  CMD_PopArg(&req, (uint8_t*)&client_ptr, 4);
  MQTT_Client* client = (MQTT_Client*)client_ptr;
#ifdef MQTTCMD_DBG
  os_printf("MQTT: MQTTCMD_Connect client ptr=%p\n", (void*)client_ptr);
#endif

  uint16_t len;

  // get host
  if (client->host)
  os_free(client->host);
  len = CMD_ArgLen(&req);
  if (len > 128) return 0; // safety check
  client->host = (char*)os_zalloc(len + 1);
  CMD_PopArg(&req, client->host, len);
  client->host[len] = 0;

  // get port
  CMD_PopArg(&req, (uint8_t*)&client->port, 4);

  // get security
  CMD_PopArg(&req, (uint8_t*)&client->security, 4);
#ifdef MQTTCMD_DBG
  os_printf("MQTT: MQTTCMD_Connect host=%s, port=%d, security=%d\n",
    client->host,
    client->port,
    client->security);
#endif

  MQTT_Connect(client);
  return 1;
}
Esempio n. 25
0
void MQTT::connect()
{
	MQTT_Connect(&mqttClient);
}
/*******************************************************************************
*	Main
*
********************************************************************************/
int main(int argc, char** argv)
{
	IoT_Error_t rc = NONE_ERROR;
	int32_t i = 0;
	int ret =0;

	char rootCA[PATH_MAX + 1];
	char clientCRT[PATH_MAX + 1];
	char clientKey[PATH_MAX + 1];
	char CurrentWD[PATH_MAX + 1];

	char cafileName[] = "/rootCA.crt";
	char clientCRTName[] = "/aws.crt";
	char clientKeyName[] = "/aws.key";

	char* thingID;

	//
	//Register ctrl-c handler
	//
	signal(SIGINT, CTRL_C_Handler);

	//
	//Parse Input-parameters
	//
	parseInputArgsForConnectParams(argc, argv);

	//
	// Get the ThingID/MachineID
	//
	thingID = GetMachineID();

	//
	// Export GPIO12 for LED output
	//
	ret = Export_GPIO(GPIO12); 	//Export GPIO12 for LED output
	if (ret != 0) {
		ERROR("Could not export LED GPIO");
	}

	//
	//Register Event-handler for Vol+/- button
	//
	ret = RegisterEventHandler(VOL_UP_EVENT, On_VolUp_ButtonPress, (void*) thingID);
	if (ret != 0) {
		ERROR("Could not register EventHandler");
	}

	ret = RegisterEventHandler(VOL_DOWN_EVENT, On_VolDown_ButtonPress,(void*) thingID);
	if (ret != 0) {
		ERROR("Could not register EventHandler");
	}


	//
	//Create the mainloop for polling the button events
	//
	loop = g_main_loop_new( NULL, false );
	if(!loop) {
		ERROR("Could not Create Main loop");
		return -1;
	}

	//
	//Setting path to private key and certificates
	//
	sprintf(rootCA, "%s%s", certDirectory, cafileName);
	sprintf(clientCRT, "%s%s", certDirectory, clientCRTName);
	sprintf(clientKey, "%s%s", certDirectory, clientKeyName);

	INFO("ThingID:       %s", thingID);
	INFO("AWS IoT SDK:   %d.%d.%d-%s", VERSION_MAJOR, VERSION_MINOR, VERSION_PATCH, VERSION_TAG);
	INFO("rootCA:        %s", rootCA);
	INFO("clientCRT:     %s", clientCRT);
	INFO("clientKey:     %s\n", clientKey);

	struct stat reqFileStat;
	if (stat(rootCA, &reqFileStat) < 0 || stat(clientCRT, &reqFileStat) < 0 ||
	    stat(clientKey, &reqFileStat) < 0)
	{
		ERROR("Root certificate and client certificate and key MUST be present.");
		exit(1);
	}

	//
	// Connect MQTT client
	//
	INFO("Connecting to %s:%d", HostAddress, port);
	rc = MQTT_Connect(HostAddress,port, thingID, rootCA, clientCRT, clientKey);
	if (NONE_ERROR != rc) {
		ERROR("Error[%d] connecting to %s:%d", rc, HostAddress, port);
	}

	//
	// Subscribe to LED status-changes topic
	//
        char topic[512];
        sprintf(topic, led_state_sub_topic, thingID);
	INFO("Subscribing to topic:%s", topic);
	rc = MQTT_Subscribe(topic, QOS_0, MQTTcallbackHandler);
	if (NONE_ERROR != rc) {
		ERROR("Error[%d] subscribing to topic: %s", rc, led_state_sub_topic);
	}


	//iot_mqtt_yield(1000); 	//TODO: clarify

	//
	//Hook in  a function into main loop that calls iot_mqtt_yield in regular intervals
	//
	g_timeout_add(1000, timer_func, 0);



	//
	//start the main loop
	//This call is blocking until the main loop is exited with a call to g_main_loop_quit(loop)
	//from the CTRL-C handler;
	INFO("Entering main-loop, please press ctrl-c to quit the demo-app:");
	g_main_loop_run( loop );	


	INFO("Cleaning up application ...");
	
	//Unsubscribe from Topics

	//Disconnect MQTT connection

	//Unregister GPIO-EventHandlers

	//UnExport GPIO's

	//Destroy main loop
	if(loop)
		g_main_loop_unref(loop);

	return rc;
}
Esempio n. 27
0
void ICACHE_FLASH_ATTR
MQTT_Task(os_event_t *e)
{
    MQTT_Client* client = (MQTT_Client*)e->par;
    uint8_t dataBuffer[MQTT_BUF_SIZE];
    uint16_t dataLen;
    if (e->par == 0)
        return;
    switch (client->connState) {

    case TCP_RECONNECT_REQ:
        break;
    case TCP_RECONNECT:
        mqtt_tcpclient_delete(client);
        MQTT_Connect(client);
        INFO("TCP: Reconnect to: %s:%d\r\n", client->host, client->port);
        client->connState = TCP_CONNECTING;
        break;
    case MQTT_DELETING:
    case TCP_DISCONNECTING:
    case TCP_RECONNECT_DISCONNECTING:
        if (client->security) {
#ifdef MQTT_SSL_ENABLE
            espconn_secure_disconnect(client->pCon);
#else
            INFO("TCP: Do not support SSL\r\n");
#endif
        }
        else {
            espconn_disconnect(client->pCon);
        }
        break;
    case TCP_DISCONNECTED:
        INFO("MQTT: Disconnected\r\n");
        mqtt_tcpclient_delete(client);
        break;
    case MQTT_DELETED:
        INFO("MQTT: Deleted client\r\n");
        mqtt_client_delete(client);
        break;
    case MQTT_KEEPALIVE_SEND:
        mqtt_send_keepalive(client);
        break;
    case MQTT_DATA:
        if (QUEUE_IsEmpty(&client->msgQueue) || client->sendTimeout != 0) {
            break;
        }
        if (QUEUE_Gets(&client->msgQueue, dataBuffer, &dataLen, MQTT_BUF_SIZE) == 0) {
            client->mqtt_state.pending_msg_type = mqtt_get_type(dataBuffer);
            client->mqtt_state.pending_msg_id = mqtt_get_id(dataBuffer, dataLen);


            client->sendTimeout = MQTT_SEND_TIMOUT;
            INFO("MQTT: Sending, type: %d, id: %04X\r\n", client->mqtt_state.pending_msg_type, client->mqtt_state.pending_msg_id);
            if (client->security) {
#ifdef MQTT_SSL_ENABLE
                espconn_secure_send(client->pCon, dataBuffer, dataLen);
#else
                INFO("TCP: Do not support SSL\r\n");
#endif
            }
            else {
                espconn_send(client->pCon, dataBuffer, dataLen);
            }

            client->mqtt_state.outbound_message = NULL;
            break;
        }
        break;
    }
}