void ICACHE_FLASH_ATTR mqttPublishedCb(uint32_t *args) {
	MQTT_Client* client = (MQTT_Client*) args;
#ifdef ESP8266DEBUG
	os_printf("MQTT: Published\r\n");
#endif
}
Beispiel #2
0
/******************************************************************************
 * FunctionName : upgrade_download
 * Description  : Processing the upgrade data from the host
 * Parameters   : bin -- server number
 *                pusrdata -- The upgrade data (or NULL when the connection has been closed!)
 *                length -- The length of upgrade data
 * Returns      : none
*******************************************************************************/
LOCAL void ICACHE_FLASH_ATTR
upgrade_download(void *arg, char *pusrdata, unsigned short length){
    char *ptr = NULL;
    char *ptmp2 = NULL;
    char lengthbuffer[32], returncode[4];
    uint8_t md5_calc[16],i = 0,progress = 0;
    char output[64] = {0};
    struct upgrade_server_info *server = (struct upgrade_server_info *)upgrade_conn->reverse;
    uint32_t  count;

    //检查返回码
    if (totallength == 0){
        ptr = (char *)os_strstr(pusrdata, "HTTP/1.1 ");
        os_memset(returncode, 0, sizeof(returncode));
        os_memcpy(returncode, ptr+9, 3);

        if(os_strcmp(returncode ,"200")){ //下载失败
            UPGRADE_DBG("http download return code  error\n");
            upgrade_check(server);
            return;
        }
    }
   if (totallength == 0 && (ptr = (char *)os_strstr(pusrdata, "\r\n\r\n")) != NULL &&
            (ptr = (char *)os_strstr(pusrdata, "Content-Length")) != NULL) {
        ptr = (char *)os_strstr(pusrdata, "\r\n\r\n");
        length -= ptr - pusrdata;
        length -= 4;
        totallength += length;
        UPGRADE_DBG("upgrade file download start.\n");
        file_info_clear();
        MD5Init(&_ctx);
        MD5Update(&_ctx, ptr + 4, length);
        system_upgrade(ptr + 4, length);
        ptr = (char *)os_strstr(pusrdata, "Content-Length: ");

        if (ptr != NULL) {
            ptr += 16;
            ptmp2 = (char *)os_strstr(ptr, "\r\n");

            if (ptmp2 != NULL) {
                os_memset(lengthbuffer, 0, sizeof(lengthbuffer));
                os_memcpy(lengthbuffer, ptr, ptmp2 - ptr);
                sumlength = atoi(lengthbuffer);
            } else {
                UPGRADE_DBG("sumlength failed\n");
                upgrade_check(server);
                return;
            }
        } else {
            upgrade_check(server);
            UPGRADE_DBG("Content-Length: failed\n");
            return;
        }
    } else {
        if(totallength + length > sumlength)
        {length = sumlength - totallength;}
        totallength += length;
        os_printf("totallen = %d\n",totallength);
        MD5Update(&_ctx, pusrdata, length);
        system_upgrade(pusrdata, length);
    }

    progress = totallength*100/sumlength;
    os_memset(output, 0, sizeof(output));
    os_sprintf(output,"%s:2,%d\r\n", CMD_DOWN_FILE, progress);
    at_port_print(output);       //正在下载  显示下载进度
    //at_response_ok();

    if ((totallength == sumlength)) {
        UPGRADE_DBG("upgrade file download finished.\n");
        MD5Final(md5_calc, &_ctx);
        os_memset(output, 0, sizeof(output));
        for(i = 0; i < 16; i++)
        {
            os_sprintf(output + (i * 2), "%02x", md5_calc[i]);
        }
        os_printf("md5 = %s\n",output);
        if(!os_strcmp(server->md5,output)){
            UPGRADE_DBG("md5 check ok.\n");
            system_upgrade_flag_set(UPGRADE_FLAG_FINISH);
            //保存文件
            file_info->file_size = sumlength;
            file_info->file_start_sec = UPDATE_CACHE_WIFIAPP_SEC_START;
            file_info_write(file_info);

            totallength = 0;
            sumlength = 0;
            upgrade_check(server);
            return;
        }
        UPGRADE_DBG("md5 check error.\n");
        upgrade_check(server);
        return;
    }

    if (upgrade_conn->state != ESPCONN_READ) {
        totallength = 0;
        sumlength = 0;
        os_timer_disarm(&upgrade_rev_timer);
        os_timer_setfn(&upgrade_rev_timer, (os_timer_func_t *)upgrade_check, server);
        os_timer_arm(&upgrade_rev_timer, 10, 0);
    }
}
Beispiel #3
0
/**
 * Create a new socket.
 * if `ipAddress == 0`, creates a server otherwise creates a client (and automatically connects). Returns >=0 on success.
 */
int net_ESP8266_BOARD_createSocket(
		JsNetwork *net,     //!< The Network we are going to use to create the socket.
		uint32_t ipAddress, //!< The address of the partner of the socket or 0 if we are to be a server.
		unsigned short port //!< The port number that the partner is listening upon.
	) {
	os_printf("> net_ESP8266_BOARD_createSocket: host: %d.%d.%d.%d, port:%d \n", ((char *)(&ipAddress))[0], ((char *)(&ipAddress))[1], ((char *)(&ipAddress))[2], ((char *)(&ipAddress))[3], port);

	bool isServer = (ipAddress == 0);

	struct socketData *pSocketData = allocateNewSocket();
	if (pSocketData == NULL) { // No free socket
		os_printf("< net_ESP8266_BOARD_createSocket: No free sockets\n");
		return -1;
	}

	int newSocket = pSocketData->socketId;
	pSocketData->pEspconn = (struct espconn *)os_malloc(sizeof(struct espconn));
	assert(pSocketData->pEspconn);

	struct espconn *pEspconn = pSocketData->pEspconn;

	pEspconn->type      = ESPCONN_TCP;
	pEspconn->state     = ESPCONN_NONE;
	pEspconn->proto.tcp = (esp_tcp *)os_malloc(sizeof(esp_tcp));
	pEspconn->reverse   = pSocketData;
	assert(pEspconn->proto.tcp != NULL);
	os_memset(pEspconn->proto.tcp, 0, sizeof(esp_tcp));

	// NOTE: We must not call these functions until AFTER we have allocated storage
	// for the 'esp_tcp' structure.
  espconn_regist_disconcb(pEspconn, esp8266_callback_disconnectCB);
  espconn_regist_reconcb(pEspconn, esp8266_callback_reconnectCB);
  espconn_regist_sentcb(pEspconn, esp8266_callback_sentCB);
  espconn_regist_recvcb(pEspconn, esp8266_callback_recvCB);
  espconn_regist_write_finish(pEspconn, esp8266_callback_writeFinishedCB);

	struct ip_info ipconfig;
	wifi_get_ip_info(STATION_IF, &ipconfig); // Get the local IP address
	os_memcpy(pEspconn->proto.tcp->local_ip, &ipconfig.ip, 4);

	// If we are not a server ...
	if (isServer == false) {
		pSocketData->state = SOCKET_STATE_CONNECTING;
		pSocketData->creationType = SOCKET_CREATED_OUTBOUND;
		pEspconn->proto.tcp->remote_port = port;
		pEspconn->proto.tcp->local_port  = espconn_port();

		*(uint32 *)(pEspconn->proto.tcp->remote_ip) = ipAddress;

		// Ensure that we have flagged this socket as NOT connected
		pSocketData->isConnected = false;

		espconn_regist_connectcb(pEspconn, esp8266_callback_connectCB_outbound);

		// Make a call to espconn_connect.
		int rc = espconn_connect(pEspconn);
		if (rc != 0) {
			os_printf("Err: net_ESP8266_BOARD_createSocket -> espconn_connect returned: %d.  Using local port: %d\n", rc, pEspconn->proto.tcp->local_port);
			setSocketInError(newSocket, "espconn_connect", rc);
		}
	}
	// If the ipAddress IS 0 ... then we are a server.
	else
	{
    // We are going to set ourselves up as a server
		pSocketData->state        = SOCKET_STATE_IDLE;
		pSocketData->creationType = SOCKET_CREATED_SERVER;
		pEspconn->proto.tcp->local_port = port;

		espconn_regist_connectcb(pEspconn, esp8266_callback_connectCB_inbound);

		// Make a call to espconn_accept
		int rc = espconn_accept(pEspconn);
		if (rc != 0) {
			os_printf("Err: net_ESP8266_BOARD_createSocket -> espconn_accept returned: %d.  Using local port: %d\n", rc, pEspconn->proto.tcp->local_port);
			setSocketInError(newSocket, "espconn_accept", rc);
		}
	}

	dumpEspConn(pEspconn);
	os_printf("< net_ESP8266_BOARD_createSocket, socket=%d\n", newSocket);
	return newSocket;
}
Beispiel #4
0
static void ICACHE_FLASH_ATTR prHeapTimerCb(void *arg) {
  os_printf("Heap: %ld\n", (unsigned long)system_get_free_heap_size());
}
void ICACHE_FLASH_ATTR
light_set_aim(uint32 r,uint32 g,uint32 b,uint32 cw,uint32 ww,uint32 period)
{
    struct pwm_param *tmp = LightEvtMalloc();    
    if(tmp != NULL){
        tmp->period = (period<10000?period:10000);
	uint32 duty_max_limit = (period*1000/45);
		
        tmp->duty[LIGHT_RED] = (r<duty_max_limit?r:duty_max_limit);
        tmp->duty[LIGHT_GREEN] = (g<duty_max_limit?g:duty_max_limit);
        tmp->duty[LIGHT_BLUE] = (b<duty_max_limit?b:duty_max_limit);
        tmp->duty[LIGHT_COLD_WHITE] = (cw<duty_max_limit?cw:duty_max_limit);
        tmp->duty[LIGHT_WARM_WHITE] = (ww<duty_max_limit?ww:duty_max_limit);//chg

#if LIGHT_CURRENT_LIMIT
        uint32 cur_r,cur_g,cur_b,cur_rgb;
        
        //if(cw>0 || ww>0){
        cur_r = light_get_cur(tmp->duty[LIGHT_RED] , LIGHT_RED, tmp->period);
		
        cur_g =  light_get_cur(tmp->duty[LIGHT_GREEN] , LIGHT_GREEN, tmp->period);
        cur_b =  light_get_cur(tmp->duty[LIGHT_BLUE] , LIGHT_BLUE, tmp->period);
        cur_rgb = (cur_r+cur_g+cur_b);
        //}
        uint32 cur_cw = light_get_cur( tmp->duty[LIGHT_COLD_WHITE],LIGHT_COLD_WHITE, tmp->period);
        uint32 cur_ww = light_get_cur( tmp->duty[LIGHT_WARM_WHITE],LIGHT_WARM_WHITE, tmp->period);
	 uint32 cur_remain,cur_mar;
	        cur_remain = (LIGHT_TOTAL_CURRENT_MAX - cur_rgb -LIGHT_CURRENT_MARGIN);
		cur_mar = LIGHT_CURRENT_MARGIN;

/*
	 if((cur_cw < 50000) || (cur_ww < 50000)){
	        cur_remain = (LIGHT_TOTAL_CURRENT_MAX - cur_rgb -LIGHT_CURRENT_MARGIN);
		cur_mar = LIGHT_CURRENT_MARGIN;
 	}else if((cur_cw < 99000) || (cur_ww < 99000)){
	        cur_remain = (LIGHT_TOTAL_CURRENT_MAX - cur_rgb -LIGHT_CURRENT_MARGIN_L2);
		cur_mar = LIGHT_CURRENT_MARGIN_L2;
	}else{
	        cur_remain = (LIGHT_TOTAL_CURRENT_MAX - cur_rgb -LIGHT_CURRENT_MARGIN_L3);
		cur_mar = LIGHT_CURRENT_MARGIN_L2;
	}

	*/
	 
	 /*
	 if((LIGHT_TOTAL_CURRENT_MAX-cur_rgb)>120){
	        cur_remain = (LIGHT_TOTAL_CURRENT_MAX - cur_rgb -LIGHT_CURRENT_MARGIN);
		cur_mar = LIGHT_CURRENT_MARGIN;
 	}else if((LIGHT_TOTAL_CURRENT_MAX-cur_rgb)>100){
	        cur_remain = (LIGHT_TOTAL_CURRENT_MAX - cur_rgb -LIGHT_CURRENT_MARGIN_L2);
		cur_mar = LIGHT_CURRENT_MARGIN_L2;
	}else{
	        cur_remain = (LIGHT_TOTAL_CURRENT_MAX - cur_rgb -LIGHT_CURRENT_MARGIN_L3);
		cur_mar = LIGHT_CURRENT_MARGIN_L2;
	}
	*/


		
        os_printf("cur_remain: %d \r\n",cur_remain);
        while((cur_cw+cur_ww) > cur_remain){
            tmp->duty[LIGHT_COLD_WHITE] =  tmp->duty[LIGHT_COLD_WHITE] * 9 / 10;
            tmp->duty[LIGHT_WARM_WHITE] =  tmp->duty[LIGHT_WARM_WHITE] * 9 / 10;
            cur_cw = light_get_cur( tmp->duty[LIGHT_COLD_WHITE],LIGHT_COLD_WHITE, tmp->period);
            cur_ww = light_get_cur( tmp->duty[LIGHT_WARM_WHITE],LIGHT_WARM_WHITE, tmp->period);
        }	    
	os_printf("debug : %d %d %d %d %d\r\n",cur_r/1000,cur_g/1000,cur_b/1000,cur_cw/1000,cur_ww/1000);
	
	os_printf("debug:total current after adj : %d + %d mA \r\n",(cur_cw+cur_ww+cur_r+cur_g+cur_b)/1000,cur_mar/1000);
#endif



		
	os_printf("prd:%u  r : %u  g: %u  b: %u  cw: %u  ww: %u \r\n",period,
		         tmp->duty[0],tmp->duty[1],tmp->duty[2],tmp->duty[3],tmp->duty[4]);
        light_pwm_smooth_adj_proc();
    }
    else{
        os_printf("light para full\n");
    }
}
Beispiel #6
0
int ICACHE_FLASH_ATTR alink_demo()
{
	struct device_info main_dev;

	memset(&main_dev, 0, sizeof(main_dev));
	alink_fill_deviceinfo(&main_dev);	// 必须根据PRD表格更新设备信息
										//alink_set_loglevel(ALINK_LL_DEBUG | ALINK_LL_INFO | ALINK_LL_WARN | ALINK_LL_ERROR);
	alink_set_loglevel(ALINK_LL_ERROR);
	//alink_enable_sandbox_mode();                                      // 线上环境需要注解此函数
	main_dev.sys_callback[ALINK_FUNC_SERVER_STATUS] = alink_handler_systemstates_callback;
	alink_set_callback(ALINK_FUNC_AVAILABLE_MEMORY, print_mem_callback);

	/* ALINK_CONFIG_LEN 2048 */
	alink_register_cb(ALINK_FUNC_READ_CONFIG, (void *)&read_config);
	alink_register_cb(ALINK_FUNC_WRITE_CONFIG, (void *)&write_config);
	alink_register_cb(ALINK_FUNC_GET_STATUS, alink_get_debuginfo);
	//alink_enable_sandbox(&main_dev);                                      // 线上环境需要注解此函数
	alink_register_cb(ALINK_FUNC_OTA_FIRMWARE_SAVE, esp_ota_firmware_update);
	alink_register_cb(ALINK_FUNC_OTA_UPGRADE, esp_ota_upgrade);
	/*start alink-sdk */
#ifdef PASS_THROUGH		//透传方式(设备与服务器采用raw data通讯)
	alink_start_rawdata(&main_dev, rawdata_get_callback, rawdata_set_callback);
#else // 非透传方式(设备与服务器采用json格式数据通讯)
	main_dev.dev_callback[ACB_GET_DEVICE_STATUS] = main_dev_get_device_status_callback;
	main_dev.dev_callback[ACB_SET_DEVICE_STATUS] = main_dev_set_device_status_callback;

	alink_start(&main_dev);	//register main device here
#endif //PASS_THROUGH

	os_printf("%s %d wait time=%d \n", __FUNCTION__, __LINE__, ALINK_WAIT_FOREVER);

	ESP_DBG(("^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^"));
	if (ALINK_OK == alink_wait_connect(NULL, ALINK_WAIT_FOREVER))	//wait main device login, -1 means wait forever
	{
#if USER_UART_CTRL_DEV_EN
		char send_buf_alink_connOK[] = { 0x31, 0x31, 0x31, 0x31 }; // demo data to tell uart mcu dev, alink conn success
		uart0_write_data(send_buf_alink_connOK, sizeof(send_buf_alink_connOK));
#endif
	}
	else
	{
#if USER_UART_CTRL_DEV_EN
		char send_buf_alink_connFailed[] = { 0x32, 0x32, 0x32, 0x32 }; // demo data to tell uart mcu dev, alink conn success
		uart0_write_data(send_buf_alink_connFailed, sizeof(send_buf_alink_connFailed));
#endif
	}
	if (need_notify_app) {
		need_notify_app = 0;
		uint8 macaddr[6];
		char mac[17 + 1];
		if (wifi_get_macaddr(0, macaddr)) {
			os_printf("macaddr=%02x:%02x:%02x:%02x:%02x:%02x\n", MAC2STR(macaddr));
			snprintf(mac, sizeof(mac), "%02x:%02x:%02x:%02x:%02x:%02x", MAC2STR(macaddr));
			zconfig_notify_app(DEV_MODEL, mac, ""); // if not factory reset , 
		}
	}
	//printf("%s %d \n",__FUNCTION__,__LINE__);

	//printf("alink_demo heap_size %d\n",system_get_free_heap_size());
	//system_print_meminfo();


	/* 设备主动上报数据 */
	while (sample_running) {

		//os_printf("%s %d \n",__FUNCTION__,__LINE__);
#ifdef PASS_THROUGH
		alink_device_post_raw_data();
#else
		alink_device_post_data(NULL);
#endif //PASS_THROUGH

		if (need_factory_reset) {
			wsf_deb("key to factory_reset\n");
			need_factory_reset = 0;
			alink_factory_reset();
		}
		alink_sleep(1000);
	}

	/*  设备退出alink-sdk */
	alink_end();

	return 0;
}
Beispiel #7
0
void genSM_Event (TI_HANDLE hGenSM, TI_UINT32 uEvent, void *pData)
{
	TGenSM              *pGenSM =       (TGenSM*)hGenSM;
	TGenSM_actionCell   *pCell;

#ifdef TI_DBG
	/* sanity check */
	if (pGenSM == NULL)
	{
		os_printf("genSM_Event: Handle is NULL!!\n");
		return;
	}
	if (uEvent >= pGenSM->uEventNum)
	{
		TRACE3(pGenSM->hReport, REPORT_SEVERITY_ERROR , "genSM_Event: module: %d received event %d, which is out of events boundry %d\n", pGenSM->uModuleLogIndex, uEvent, pGenSM->uEventNum);
	}
	if (TI_TRUE == pGenSM->bEventPending)
	{
		TRACE3(pGenSM->hReport, REPORT_SEVERITY_ERROR , "genSM_Event: module: %d received event %d, when event %d is pending execution!\n", pGenSM->uModuleLogIndex, uEvent, pGenSM->uEvent);
	}
#endif

	/* mark that an event is pending */
	pGenSM->bEventPending = TI_TRUE;

	/* save event and data */
	pGenSM->uEvent = uEvent;
	pGenSM->pData = pData;

	/* if an event is currently executing, return (new event will be handled when current event is done) */
	if (TI_TRUE == pGenSM->bInAction)
	{
		TRACE1(pGenSM->hReport, REPORT_SEVERITY_INFORMATION , ": module: %d delaying execution of event \n", pGenSM->uModuleLogIndex);
		return;
	}

	/* execute events, until none is pending */
	while (TI_TRUE == pGenSM->bEventPending)
	{
		/* get the cell pointer for the current state and event */
		pCell = &(pGenSM->tMatrix[ (pGenSM->uCurrentState * pGenSM->uEventNum) + pGenSM->uEvent ]);


		/* print state transition information */
		TRACE4(pGenSM->hReport, REPORT_SEVERITY_INFORMATION, "genSM_Event: module %d <currentState = %d, event = %d> --> nextState = %d\n", pGenSM->uModuleLogIndex, pGenSM->uCurrentState, uEvent, pCell->uNextState);

		/* mark that event execution is in place */
		pGenSM->bInAction = TI_TRUE;

		/* mark that pending event is being handled */
		pGenSM->bEventPending = TI_FALSE;

		/* update current state */
		pGenSM->uCurrentState = pCell->uNextState;

		/* run transition function */
		(*(pCell->fAction)) (pGenSM->pData);

		/* mark that event execution is complete */
		pGenSM->bInAction = TI_FALSE;
	}
}
Beispiel #8
0
/*JSON{
  "type"     : "staticmethod",
  "class"    : "ESP8266WiFi",
  "name"     : "stopAP",
  "generate" : "jswrap_ESP8266WiFi_stopAP"
}
 * Stop being an access point.
*/
void jswrap_ESP8266WiFi_stopAP() {
  os_printf("Wifi: switching to Station mode.");
  wifi_set_opmode_current(STATION_MODE);
}
Beispiel #9
0
/*JSON{
  "type"     : "staticmethod",
  "class"    : "ESP8266WiFi",
  "name"     : "restart",
  "generate" : "jswrap_ESP8266WiFi_restart"
}
 * Ask the physical ESP8266 device to restart itself.
 */
void jswrap_ESP8266WiFi_restart() {
  os_printf("> jswrap_ESP8266WiFi_restart\n");
  system_restart();
}
Beispiel #10
0
/**
 * Callback function that is invoked at the culmination of a scan.
 */
static void scanCB(void *arg, STATUS status) {
  /**
   * Create a JsVar that is an array of JS objects where each JS object represents a
   * retrieved access point set of information.   The structure of a record will be:
   * o authMode
   * o isHidden
   * o rssi
   * o channel
   * o ssid
   * When the array has been built, invoke the callback function passing in the array
   * of records.
   */

  os_printf(">> scanCB\n");
  // Create the Empty JS array that will be passed as a parameter to the callback.
  JsVar *accessPointArray = jsvNewArray(NULL, 0);
  struct bss_info *bssInfo;

  bssInfo = (struct bss_info *)arg;
  while(bssInfo != NULL) {
    // Add a new object to the JS array that will be passed as a parameter to
    // the callback.  The ESP8266 bssInfo structure contains the following:
    // ---
    // uint8 bssid[6]
    // uint8 ssid[32]
    // uint8 channel
    // sint8 rssi \96 The received signal strength indication
    // AUTH_MODE authmode
    //  Open = 0
    //  WEP = 1
    //  WPA_PSK = 2
    //  WPA2_PSK = 3
    //  WPA_WPA2_PSK = 4
    // uint8 is_hidden
    // sint16 freq_offset
    // ---
    // Create, populate and add a child ...
    JsVar *currentAccessPoint = jspNewObject(NULL, "AccessPoint");
    jsvUnLock(jsvObjectSetChild(currentAccessPoint, "rssi", jsvNewFromInteger(bssInfo->rssi)));
    jsvUnLock(jsvObjectSetChild(currentAccessPoint, "channel", jsvNewFromInteger(bssInfo->channel)));
    jsvUnLock(jsvObjectSetChild(currentAccessPoint, "authMode", jsvNewFromInteger(bssInfo->authmode)));
    jsvUnLock(jsvObjectSetChild(currentAccessPoint, "isHidden", jsvNewFromBool(bssInfo->is_hidden)));
    // The SSID may **NOT** be NULL terminated ... so handle that.
    char ssid[sizeof(bssInfo->ssid) + 1];
    os_strncpy((char *)ssid, (char *)bssInfo->ssid, sizeof(bssInfo->ssid));
    ssid[sizeof(ssid)-1] = '\0';
    jsvUnLock(jsvObjectSetChild(currentAccessPoint, "ssid", jsvNewFromString(ssid)));

    // Add the new record to the array
    jsvArrayPush(accessPointArray, currentAccessPoint);

    os_printf(" - ssid: %s\n", bssInfo->ssid);
    bssInfo = STAILQ_NEXT(bssInfo, next);
  }

  // We have now completed the scan callback, so now we can invoke the JS callback.
  JsVar *params[1];
  params[0] = accessPointArray;
  jsiQueueEvents(NULL, g_jsScanCallback, params, 1);
  jsvUnLock(g_jsScanCallback);
  os_printf("<< scanCB\n");
}
Beispiel #11
0
/*JSON{
  "type"     : "staticmethod",
  "class"    : "ESP8266WiFi",
  "name"     : "connect",
  "generate" : "jswrap_ESP8266WiFi_connect",
  "params"   : [
    ["ssid","JsVar","The network id of the access point."],
    ["password","JsVar","The password to the access point"],
    ["gotIpCallback", "JsVar", "An optional callback invoked when we have an IP"]
  ]
}
 *
 * Connect the station to an access point.
 */
void jswrap_ESP8266WiFi_connect(
    JsVar *jsv_ssid,     //!< The SSID of the access point to connect.
    JsVar *jsv_password, //!< The password for the access point.
    JsVar *gotIpCallback //!< The Callback function to be called when we are connected.
  ) {
    os_printf("> jswrap_ESP8266WiFi_connect\n");

  // Check that the ssid and password values aren't obviously in error.
  if (jsv_ssid == NULL || !jsvIsString(jsv_ssid)) {
      jsExceptionHere(JSET_ERROR, "No SSID.");
    return;
  }
  if (jsv_password == NULL || !jsvIsString(jsv_password)) {
      jsExceptionHere(JSET_ERROR, "No password.");
    return;
  }

  // Check that if a callback function was supplied that we actually have a callback function.
  if (gotIpCallback != NULL && !jsvIsUndefined(gotIpCallback) && !jsvIsFunction(gotIpCallback)) {
    gotIpCallback = NULL;
      jsExceptionHere(JSET_ERROR, "A callback function was supplied that is not a function.");
    return;
  }
  if (jsvIsUndefined(gotIpCallback) || jsvIsNull(gotIpCallback)) {
    gotIpCallback = NULL;
  }

  // Set the global which is the gotIP callback to null but first unlock it.
  if (g_jsGotIpCallback != NULL) {
    jsvUnLock(g_jsGotIpCallback);
    g_jsGotIpCallback = NULL;
  }

  // If we have a callback, save it for later invocation.
  if (gotIpCallback != NULL) {
    g_jsGotIpCallback = jsvLockAgainSafe(gotIpCallback);
  }

  // Debug
  // os_printf("jsGotIpCallback=%p\n", jsGotIpCallback);

  // Create strings from the JsVars for the ESP8266 API calls.
  char ssid[33];
  int len = jsvGetString(jsv_ssid, ssid, sizeof(ssid)-1);
  ssid[len]='\0';
  char password[65];
  len = jsvGetString(jsv_password, password, sizeof(password)-1);
  password[len]='\0';

  os_printf(">  - ssid=%s, password=%s\n", ssid, password);

  // Set the WiFi mode of the ESP8266
  wifi_set_opmode_current(STATION_MODE);

  struct station_config stationConfig;
  memset(&stationConfig, 0, sizeof(stationConfig));
  os_strncpy((char *)stationConfig.ssid, ssid, 32);
  if (password != NULL) {
    os_strncpy((char *)stationConfig.password, password, 64);
  } else {
    os_strcpy((char *)stationConfig.password, "");
  }

  // Set the WiFi configuration
  wifi_station_set_config(&stationConfig);

  uint8 wifiConnectStatus = wifi_station_get_connect_status();
  os_printf(" - Current connect status: %s\n", wifiConnectStatusToString(wifiConnectStatus));

  if (wifiConnectStatus == STATION_GOT_IP) {
    // See issue #618.  There are currently three schools of thought on what should happen
    // when a connect is issued and we are already connected.
    //
    // Option #1 - Always perform a disconnect.
    // Option #2 - Perform a disconnect if the SSID or PASSWORD are different from current
    // Option #3 - Fail the connect if we are already connected.
    //
#define ISSUE_618 1

#if ISSUE_618 == 1
    wifi_station_disconnect();
#elif ISSUE_618 == 2
    struct station_config existingConfig;
    wifi_station_get_config(&existingConfig);
    if (os_strncmp((char *)existingConfig.ssid, (char *)stationConfig.ssid, 32) == 0 &&
        os_strncmp((char *)existingConfig.password, (char *)stationConfig.password, 64) == 0) {
      if (jsGotIpCallback != NULL) {
        JsVar *params[2];
        params[0] = jsvNewFromInteger(STATION_GOT_IP);
         params[1] = jsvNewNull();
        jsiQueueEvents(NULL, jsGotIpCallback, params, 2);
      }
      return;

    } else {
      wifi_station_disconnect();
    }
#elif ISSUE_618 == 3
    // Add a return code to the function and return an already connected error.
#endif
  }
  // Perform the network level connection.
  wifi_station_connect();
  os_printf("< jswrap_ESP8266WiFi_connect\n");
}
Beispiel #12
0
/* espFsOpen */
EspFsFile ICACHE_FLASH_ATTR *	espFsOpen(char *	pszFilename)
{
	/* initialization */
	char *		pbHeaderOffset			= NULL;
	char *		pbTmpFile				= NULL;
	EspFsFile *	ptEspFile				= NULL;
	char 		pszFileNameBuffer[256]	= { 0 };
	EspFsHeader tEspFileHeader			= { 0 };

	/* acquire file system beginning */
#ifndef ESPFS_TEST
	int 		iEspFsOffset = 0;
	
	if (0 == system_upgrade_userbin_check())
	{
		iEspFsOffset = partition[ESPFS_PART].iOffset;
	}
	else
	{
		iEspFsOffset = partition[ESPFS_PART2].iOffset;
	}

	pbTmpFile = (char *)(iEspFsOffset + ESP_FLASH_OFFSET);
#else	
	pbTmpFile = espFsData;
#endif
	
	/* strip file name slashes */
	while (SLASH_SYMBOL_STRING == pszFilename[0])
	{
		++pszFilename;
	}

	/* locate file */
	while (1)
	{
		pbHeaderOffset = pbTmpFile;
		
		/* retrieve file header */
		os_memcpy(&tEspFileHeader, pbTmpFile, sizeof(EspFsHeader));

		if (ESPFS_MAGIC_HEADER != tEspFileHeader.magic)
		{
#ifdef ESPFS_DEBUG
			os_printf("espFsOpen: magic mismatch - file system image broken. found 0x%x instead\n", tEspFileHeader.magic);
#endif
			ptEspFile = NULL;
			goto lblCleanup;
		}

		if (tEspFileHeader.flags & FLAG_LASTFILE)
		{
#ifdef ESPFS_DEBUG
			os_printf("espFsOpen: end of image reached\n");
#endif
			ptEspFile = NULL;
			goto lblCleanup;
		}
		
		/* acquire file name */
		pbTmpFile += sizeof(EspFsHeader);
		os_memcpy(pszFileNameBuffer, pbTmpFile, sizeof(pszFileNameBuffer));

#ifdef ESPFS_DEBUG
		os_printf("espFsOpen: found file '%s'\nname length = %x, file length compressed = %x, compression = %d flags = %d\n",
				  pszFileNameBuffer, 
				  (unsigned int)tEspFileHeader.nameLen, 
				  (unsigned int)tEspFileHeader.fileLenComp, 
				  tEspFileHeader.compression, 
				  tEspFileHeader.flags);
#endif
		if (0 == os_strcmp(pszFileNameBuffer, pszFilename))
		{
			/* desired file */

			/* skip to content */
			pbTmpFile += tEspFileHeader.nameLen;

			/* allocate file descriptor */
			ptEspFile = (EspFsFile *)os_malloc(sizeof(EspFsFile));

#ifdef ESPFS_DEBUG
			os_printf("espFsOpen: file descriptor allocated at %p\n", ptEspFile);
#endif
			if (NULL == ptEspFile)
			{
				goto lblCleanup;
			}

			/* fill file descriptor */
			ptEspFile->header = (EspFsHeader *)pbHeaderOffset;
			ptEspFile->decompressor = tEspFileHeader.compression;
			ptEspFile->posComp = pbTmpFile;
			ptEspFile->posStart = pbTmpFile;
			ptEspFile->posDecomp = 0;
			
			if (COMPRESS_NONE == tEspFileHeader.compression)
			{
				ptEspFile->decompData = NULL;

#ifdef EFS_HEATSHRINK
			}
			else if (COMPRESS_HEATSHRINK == tEspFileHeader.compression)
			{
				/* compression used */
				char 					bDecoderParameter 	= { 0 };
				heatshrink_decoder *	ptDecoder 			= NULL;
				
				/* acquire decoder parameters - 1st byte */
				memcpyAligned(&bDecoderParameter, ptEspFile->posComp, 1);

				++ptEspFile->posComp;

#ifdef HEATSHRINK_DEBUG
				os_printf("espFsOpen: heatshrink compressed file, decoder parameters = %x\n", bDecoderParameter);
#endif
				ptDecoder = heatshrink_decoder_alloc(16, (bDecoderParameter >> 4) & 0xf, bDecoderParameter & 0xf);
				ptEspFile->decompData = ptDecoder;
#endif
			}
			else
			{
Beispiel #13
0
void ICACHE_FLASH_ATTR nixieClockCb() {
    os_printf("TEST");
}
/******************************************************************************
 * FunctionName : user_plug_short_press
 * Description  : key's short press function, needed to be installed
 * Parameters   : none
 * Returns      : none
 *******************************************************************************/
void ICACHE_FLASH_ATTR
peri_key_short_press(void) {
	os_printf(" 4 short press..\n");
}
Beispiel #15
0
int esp_ota_firmware_update(char * buffer, int len)
{
	os_printf("esp_ota_firmware_update \n");
	return upgrade_download(buffer, len);
}
Beispiel #16
0
void timer_interrupt_handler_1(){
	//function(args);
	os_printf("hello I'm interrupting");
	clear_interrupt(0);
	return;
}
Beispiel #17
0
int esp_ota_upgrade(void)
{
	os_printf("esp_ota_upgrade \n");
	system_upgrade_reboot();
	return 0;
}
Beispiel #18
0
void ICACHE_FLASH_ATTR CFG_print(void) {
	os_printf("saveFlag %d CFG_LOCATION %x cfg_holder %lx\n", saveFlag.flag, CFG_LOCATION, sysCfg.cfg_holder);
	os_printf("sta_ssid %s sta_type %d\n", sysCfg.sta_ssid, sysCfg.sta_type);
	os_printf("deviceName %s deviceLocation %s\n", sysCfg.deviceName, sysCfg.deviceLocation);
}
Beispiel #19
0
static  void ICACHE_FLASH_ATTR pollDHTCb(void * arg){

  int counter = 0;
  int laststate = 1;
  int i = 0;
  int bits_in = 0;
  // int bitidx = 0;
  // int bits[250];

  int data[100];

  data[0] = data[1] = data[2] = data[3] = data[4] = 0;

  // Wake up device, 250ms of high
  GPIO_OUTPUT_SET(DHT_PIN, 1);
  delay_ms(500);

  // Hold low for 20ms
  GPIO_OUTPUT_SET(DHT_PIN, 0);
  delay_ms(20);

  // High for 40ms
  // GPIO_OUTPUT_SET(2, 1);

  GPIO_DIS_OUTPUT(DHT_PIN);
  os_delay_us(40);

  // Set pin to input with pullup
  // PIN_PULLUP_EN(PERIPHS_IO_MUX_GPIO2_U);

  // os_printf("Waiting for gpio2 to drop \n");

  // wait for pin to drop?
  while (GPIO_INPUT_GET(DHT_PIN) == 1 && i < DHT_MAXCOUNT) {
    if (i >= DHT_MAXCOUNT) {
      goto fail;
    }
    i++;
  }

//  os_printf("Reading DHT\n");

  // read data!
  for (i = 0; i < MAXTIMINGS; i++) {
    // Count high time (in approx us)
    counter = 0;
    while (GPIO_INPUT_GET(DHT_PIN) == laststate) {
      counter++;
      os_delay_us(1);
      if (counter == 1000)
        break;
    }
    laststate = GPIO_INPUT_GET(DHT_PIN);

    if (counter == 1000)
      break;

    // store data after 3 reads
    if ((i > 3) && (i % 2 == 0)) {
      // shove each bit into the storage bytes
      data[bits_in / 8] <<= 1;
      if (counter > BREAKTIME) {
        //os_printf("1");
        data[bits_in / 8] |= 1;
      } else {
        //os_printf("0");
      }
      bits_in++;
    }
  }

  if (bits_in < 40) {
    os_printf("Got too few bits: %d should be at least 40", bits_in);
    goto fail;
  }
  

  int checksum = (data[0] + data[1] + data[2] + data[3]) & 0xFF;
  
  //os_printf("DHT: %02x %02x %02x %02x [%02x] CS: %02x\n", data[0], data[1],data[2],data[3],data[4],checksum);
  
  if (data[4] != checksum) {
    os_printf("Checksum was incorrect after %d bits. Expected %d but got %d",
              bits_in, data[4], checksum);
    goto fail;
  }

  reading.temperature = scale_temperature(data);
  reading.humidity = scale_humidity(data);
  //os_printf("Temp =  %d*C, Hum = %d%%\n", (int)(reading.temperature * 100), (int)(reading.humidity * 100));
  
  reading.success = 1;
  return;
fail:
  
  os_printf("Failed to get DHT reading, dying\n");
  reading.success = 0;
}
Beispiel #20
0
void user_init(void)
{
    uart_init(BIT_RATE_115200, BIT_RATE_115200);
    os_printf("SDK version:%s\n", system_get_sdk_version());
    
    // rsa_api_unit_test();
    
    os_printf("================= \n");
    
    packet_test();
    
    //json_test();
    
    //aes_api_unit_test();    
    //os_printf("================= \n");
    //crypto_api_unit_test();
    
    return;

    struct station_config station_conf;
    wifi_station_get_config(&station_conf);
    os_printf(MACSTR ",%s,%s \n", MAC2STR(station_conf.bssid), station_conf.password, station_conf.ssid);


    //struct station_config {
    //    uint8 ssid[32];
    //    uint8 password[64];
    //    uint8 bssid_set;    // Note: If bssid_set is 1, station will just connect to the router
    //                        // with both ssid[] and bssid[] matched. Please check about this.
    //    uint8 bssid[6];
    //};

    // 0c:4b:54:84:9e:2d t77y2qs4
    //station_conf.bssid[0] = 0x0c;
    //station_conf.bssid[1] = 0x4b;
    //station_conf.bssid[2] = 0x54;
    //station_conf.bssid[3] = 0x84;
    //station_conf.bssid[4] = 0x9e;
    //station_conf.bssid[5] = 0x2d;
    station_conf.bssid_set = 0;
    //os_strcpy(station_conf.ssid,     "hehao");
    //os_strcpy(station_conf.password, "ziqiangbuxi");
    wifi_station_set_config(&station_conf);

    wifi_station_get_config(&station_conf);
    os_printf(MACSTR ", %s, %s %d\n", MAC2STR(station_conf.bssid), station_conf.password, station_conf.ssid, station_conf.bssid_set);

    int8 id_buf[16] = {0};
    flash_param_get_id(id_buf);
    os_printf("get id = %s \n", id_buf);

    if (0 == os_strcmp(id_buf, CONFIG_RESET_ID))
    {
        os_printf("airkiss start ... \n");
        smart_config_start();
        user_switch_init();

        os_timer_disarm(&status_timer);
        os_timer_setfn(&status_timer, (os_timer_func_t *)led_status_center, NULL);
        os_timer_arm(&status_timer, 2000, 0);

        single_key[0] = key_init_single(PLUG_KEY_0_IO_NUM,
                                        PLUG_KEY_0_IO_MUX,
                                        PLUG_KEY_0_IO_FUNC,
                                        key_long_press,
                                        key_short_press);
        keys.key_num    = PLUG_KEY_NUM;
        keys.single_key = single_key;
        key_init(&keys);

        os_timer_disarm(&sys_timer);
        os_timer_setfn(&sys_timer, (os_timer_func_t *)system_secs_center, NULL);
        os_timer_arm(&sys_timer, 1000, 1); // 0 at once, 1 restart auto.

        switch_level = 0x01;
        user_switch_output(1);
    }
    else
    {
        schedule_create(0);
    }
}
/******************************************************************************
 * FunctionName : user_devicefind_init
 * Description  : the espconn struct parame init
 * Parameters   : none
 * Returns      : none
*******************************************************************************/
LOCAL void  
user_devicefind_task(void *pvParameters)
{
    struct sockaddr_in server_addr;
    int32 ret;
    
    struct sockaddr_in from;
    socklen_t   fromlen;
    struct ip_info ipconfig;
    
    char  *udp_msg;
    bool ValueFromReceive = false;
    portBASE_TYPE xStatus;

    int nNetTimeout=10000;// 1 Sec
    int stack_counter=0;

    memset(&ipconfig, 0, sizeof(ipconfig));
    memset(&server_addr, 0, sizeof(server_addr));
    server_addr.sin_family = AF_INET;       
    server_addr.sin_addr.s_addr = INADDR_ANY;
    server_addr.sin_port = htons(UDF_SERVER_PORT);
    server_addr.sin_len = sizeof(server_addr);

    udp_msg = (char*)malloc(len_udp_msg);

    do{
        sock_fd = socket(AF_INET, SOCK_DGRAM, 0);
        if (sock_fd == -1) {
            os_printf("ERROR:devicefind failed to create sock!\n");
            vTaskDelay(1000/portTICK_RATE_MS);
        }
    }while(sock_fd == -1);

    do{
        ret = bind(sock_fd, (struct sockaddr *)&server_addr, sizeof(server_addr));
        if (ret != 0) {
            os_printf("ERROR:devicefind failed to bind sock!\n");
            vTaskDelay(1000/portTICK_RATE_MS);
        }
    }while(ret != 0);


    while(1){
        
        xStatus = xQueueReceive(QueueStop,&ValueFromReceive,0);
        if ( pdPASS == xStatus && TRUE == ValueFromReceive){
            os_printf("user_devicefind_task rcv exit signal!\n");
            break;
        }

        memset(udp_msg, 0, len_udp_msg);
        memset(&from, 0, sizeof(from));
        
        setsockopt(sock_fd,SOL_SOCKET,SO_RCVTIMEO,(char *)&nNetTimeout,sizeof(int));
        fromlen = sizeof(struct sockaddr_in);
        ret = recvfrom(sock_fd, (u8 *)udp_msg, len_udp_msg, 0,(struct sockaddr *)&from,(socklen_t *)&fromlen);
        if (ret > 0) {
            os_printf("recieve from->port %d  %s\n",ntohs(from.sin_port),inet_ntoa(from.sin_addr));
            user_devicefind_data_process(udp_msg,ret,&from);
        }
        
        if(stack_counter++ ==1){
            stack_counter=0;
            DF_DEBUG("user_devicefind_task %d word left\n",uxTaskGetStackHighWaterMark(NULL));
        }
    }

    if(udp_msg)free(udp_msg);

    close(sock_fd);
    vQueueDelete(QueueStop);
    QueueStop = NULL;
    vTaskDelete(NULL);

}
Beispiel #22
0
void init(){
  os_printf("After system_init_done.");
}
Beispiel #23
0
/*4-17-15: - Prakash
 _assert_fail() added
 - This is a helper function for the assert() macro
 */
int _assert_fail(char *_file, unsigned int _line, char *_func)
{
    os_printf("ASSERT FAILURE: %s:%u: %s\n", _file, _line, _func);
    panic();
    return 1;
}
static void ICACHE_FLASH_ATTR ost_wifi_scan(os_event_t *events){
	os_printf("WiFi Scan...\n");
	os_delay_us(10000);
	wifi_promiscuous_enable(0);
	wifi_station_scan(NULL, wifiScan_cb);
}
static void ICACHE_FLASH_ATTR LightEvtFree(void)
{
    TotalUsedLightEvtNum--;
os_printf("free:%u\n",TotalUsedLightEvtNum);
}
Beispiel #26
0
/**
 * Sends a ping, and returns the number of microseconds it took to receive a response.
 * Will give up after maxPeriod (with false as return value)
 */
bool ICACHE_FLASH_ATTR
ping_pingUs(Ping_Data *pingData, uint32_t maxPeriod, uint32_t* response) {
  uint32_t timeOutAt = system_get_time() + maxPeriod;
  ping_echoEnded = false;
  ping_echoStarted = false;
  ping_timeStamp0 = system_get_time();

  if (!pingData->isInitiated) {
    *response = 0;
    os_printf("ping_pingUs: Error: not initiated properly.\n");
    return false;
  }
  if (ping_currentEchoPin >= 0) {
    // this should not really happend, how did you end up here?
    *response = 0;
    os_printf("ping_pingUs: Error: another ping is already running.\n");
    return false;
  }

  uint32_t echoPin = pingData->echoPin;
  uint32_t triggerPin = pingData->triggerPin;
  ping_currentEchoPin = pingData->echoPin;

  while (GPIO_INPUT_GET(echoPin)) {
    if (system_get_time() > timeOutAt) {
      // echo pin never went low, something is wrong.
      // turns out this happens whenever the sensor doesn't receive any echo at all.

      //os_printf("ping_ping: Error: echo pin %d permanently high %d?.\n", echoPin, GPIO_INPUT_GET(echoPin));
      *response = system_get_time() - ping_timeStamp0;

      // Wake up a sleeping device
      GPIO_OUTPUT_SET(triggerPin, PING_TRIGGER_DEFAULT_STATE);
      os_delay_us(50);
      GPIO_OUTPUT_SET(triggerPin, !PING_TRIGGER_DEFAULT_STATE);
      os_delay_us(50);
      GPIO_OUTPUT_SET(triggerPin, PING_TRIGGER_DEFAULT_STATE);
      ping_disableInterrupt(ping_currentEchoPin);
      ping_currentEchoPin = -1;
      return false;
    }
    os_delay_us(PING_POLL_PERIOD);
  }

  GPIO_OUTPUT_SET(triggerPin, 1);
  os_delay_us(PING_TRIGGER_LENGTH);
  GPIO_OUTPUT_SET(triggerPin, 0);
  
  if (echoPin == triggerPin) {
    // force the trigger pin low for 50us. This helps stabilise echo pin when 
    // running in single pin mode. 
    os_delay_us(50);
  }
  
  GPIO_DIS_OUTPUT(echoPin);
  gpio_pin_intr_state_set(GPIO_ID_PIN(echoPin), GPIO_PIN_INTR_POSEDGE);

  while (!ping_echoEnded) {
    if (system_get_time() > timeOutAt) {
      *response = system_get_time() - ping_timeStamp0;
      ping_disableInterrupt(ping_currentEchoPin);
      ping_currentEchoPin = -1;
      return false;
    }
    os_delay_us(PING_POLL_PERIOD);
  }

  *response = ping_timeStamp1 - ping_timeStamp0;
  if (ping_timeStamp1 < ping_timeStamp0 || *response < 50) {
    // probably a previous echo or clock overflow - false result
    ping_disableInterrupt(ping_currentEchoPin);
    ping_currentEchoPin = -1;
    return false;
  }
  return true;
}
Beispiel #27
0
uint32_t ICACHE_FLASH_ATTR
MQTTCMD_Setup(CmdPacket *cmd) {
  CmdRequest req;
  CMD_Request(&req, cmd);

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

  // create mqtt client
  uint8_t clientLen = sizeof(MQTT_Client);
  MQTT_Client* client = (MQTT_Client*)os_zalloc(clientLen);
  if (client == NULL) return 0;
  os_memset(client, 0, clientLen);

  return 0;
#if 0

  uint16_t len;
  uint8_t *client_id, *user_data, *pass_data;
  uint32_t keepalive, clean_session, cb_data;

  // get client id
  len = CMD_ArgLen(&req);
  if (len > 32) return 0; // safety check
  client_id = (uint8_t*)os_zalloc(len + 1);
  CMD_PopArg(&req, client_id, len);
  client_id[len] = 0;

  // get username
  len = CMD_ArgLen(&req);
  if (len > 32) return 0; // safety check
  user_data = (uint8_t*)os_zalloc(len + 1);
  CMD_PopArg(&req, user_data, len);
  user_data[len] = 0;

  // get password
  len = CMD_ArgLen(&req);
  if (len > 32) return 0; // safety check
  pass_data = (uint8_t*)os_zalloc(len + 1);
  CMD_PopArg(&req, pass_data, len);
  pass_data[len] = 0;

  // get keepalive
  CMD_PopArg(&req, (uint8_t*)&keepalive, 4);

  // get clean session
  CMD_PopArg(&req, (uint8_t*)&clean_session, 4);
#ifdef MQTTCMD_DBG
  os_printf("MQTT: MQTTCMD_Setup clientid=%s, user=%s, pw=%s, keepalive=%ld, clean_session=%ld\n", client_id, user_data, pass_data, keepalive, clean_session);
#endif

  // init client
  // TODO: why malloc these all here, pass to MQTT_InitClient to be malloc'd again?
  MQTT_InitClient(client, (char*)client_id, (char*)user_data, (char*)pass_data, keepalive, clean_session);

  // create callback
  MqttCmdCb* callback = (MqttCmdCb*)os_zalloc(sizeof(MqttCmdCb));

  CMD_PopArg(&req, (uint8_t*)&cb_data, 4);
  callback->connectedCb = cb_data;
  CMD_PopArg(&req, (uint8_t*)&cb_data, 4);
  callback->disconnectedCb = cb_data;
  CMD_PopArg(&req, (uint8_t*)&cb_data, 4);
  callback->publishedCb = cb_data;
  CMD_PopArg(&req, (uint8_t*)&cb_data, 4);
  callback->dataCb = cb_data;

  client->user_data = callback;

  client->cmdConnectedCb = cmdMqttConnectedCb;
  client->cmdDisconnectedCb = cmdMqttDisconnectedCb;
  client->cmdPublishedCb = cmdMqttPublishedCb;
  client->cmdDataCb = cmdMqttDataCb;

  if (CMD_GetArgc(&req) == 10) {
    CMD_PopArg(&req, (uint8_t*)&cb_data, 4);
    callback->tcpDisconnectedCb = cb_data;
    client->cmdTcpDisconnectedCb = cmdMqttTcpDisconnectedCb;
  }

  os_free(client_id);
  os_free(user_data);
  os_free(pass_data);

  return (uint32_t)client;
#endif
}
static void ICACHE_FLASH_ATTR loop(os_event_t* events)
{
    if (!initFinished)
    {
        // loop by adding this function to the task queue
        system_os_post(user_procTaskPrio, 0, 0);

        if(is_wifi_connected())
        {
            user_init2();
            initFinished = true;
        }

        return;
    }

    static bool pendingEmailAlert = false;
    // check unprocessed OOK packets to see if there are any newly
    //   triggered sensors
    bool newTriggerings = false;
    while(packets_available(&unprocessedPackets))
    {
        uint32 packet = packet_pop(&unprocessedPackets);
        char* source = my_strdup(ook_ID_to_name(packet));
        // check if the current packet is a new triggering
        bool packetIsNewTriggering = true;

#ifdef PRINT_OOK_PACKETS_DEBUG
        os_printf("%x\r\n", packet);
#endif
        // check for the key fob signals for arming/disarming
        if (packet == ARM_CODE)
            arm_alarm();
        else if (packet == DISARM_CODE)
            disarm_alarm();
        // must be some other code, or invalid
        else if (source != NULL && alarmArmed)
        {
            int i, j;
            // ensure that an already-triggered sensor is not duplicated in list
            for (i = 0; i < triggeredSensorsIter; i++)
            {
                if (triggeredSensorsNames[i] != NULL)
                    for (j = 0; source[j] == triggeredSensorsNames[i][j]; j++)
                    {
                        // reached the end of both strings and they've been the
                        // same all along
                        if (source[j] == '\0')
                            packetIsNewTriggering = false;
                    }
            }
            if (packetIsNewTriggering)
            {
                triggeredSensorsNames[triggeredSensorsIter] = source;
                triggeredSensorsTimestamps[triggeredSensorsIter] = sntp_get_current_timestamp();
                triggeredSensorsIter += 1;
                newTriggerings = true;
            }
            else
                os_free(source);
        }
    }

    if (newTriggerings)
    {
        updateWebpage();
        pendingEmailAlert = true;
    }

    // checked so that a pending email alert is cancelled if the "disarm" button is pressed after a
    //   sensor has been triggered
    if(!alarmArmed)
        pendingEmailAlert = false;
    
    if (pendingEmailAlert)
    {
        if (triggeredSensorsIter > 0 &&
            sntp_get_current_timestamp() - triggeredSensorsTimestamps[0] > ALERT_EMAIL_DELAY)
        {
            generate_email_body();
            send_email("ESP8266 Alarm", generatedEmailBody); 
#ifdef PRINT_EMAIL_DEBUG
            os_printf("trying to send email\n");
#endif
            pendingEmailAlert = false;
        }
    }

    // loop by adding this function to the task queue
    system_os_post(user_procTaskPrio, 0, 0);
}
Beispiel #29
0
uint32_t ICACHE_FLASH_ATTR
REST_Setup(CmdPacket *cmd) {
  CmdRequest req;
  uint32_t port, security;

  // start parsing the command
  CMD_Request(&req, cmd);
  if(CMD_GetArgc(&req) != 3) return 0;

  // get the hostname
  uint16_t len = CMD_ArgLen(&req);
  if (len > 128) return 0; // safety check
  uint8_t *rest_host = (uint8_t*)os_zalloc(len + 1);
  if (CMD_PopArg(&req, rest_host, len)) return 0;
  rest_host[len] = 0;

  // get the port
  if (CMD_PopArg(&req, (uint8_t*)&port, 4)) {
    os_free(rest_host);
    return 0;
  }

  // get the security mode
  if (CMD_PopArg(&req, (uint8_t*)&security, 4)) {
    os_free(rest_host);
    return 0;
  }

  // clear connection structures the first time
  if (restNum == 0xff) {
    os_memset(restClient, 0, MAX_REST * sizeof(RestClient));
    restNum = 0;
  }

  // allocate a connection structure
  RestClient *client = restClient + restNum;
  uint8_t clientNum = restNum;
  restNum = (restNum+1)%MAX_REST;

  // free any data structure that may be left from a previous connection
  if (client->header) os_free(client->header);
  if (client->content_type) os_free(client->content_type);
  if (client->user_agent) os_free(client->user_agent);
  if (client->data) os_free(client->data);
  if (client->pCon) {
    if (client->pCon->proto.tcp) os_free(client->pCon->proto.tcp);
    os_free(client->pCon);
  }
  os_memset(client, 0, sizeof(RestClient));
#ifdef CMDREST_DBG
  os_printf("REST: setup #%d host=%s port=%ld security=%ld\n", clientNum, rest_host, port, security);
#endif

  client->resp_cb = cmd->callback;

  client->host = (char *)rest_host;
  client->port = port;
  client->security = security;

  client->header = (char*)os_zalloc(4);
  client->header[0] = 0;

  client->content_type = (char*)os_zalloc(22);
  os_sprintf((char *)client->content_type, "x-www-form-urlencoded");

  client->user_agent = (char*)os_zalloc(9);
  os_sprintf((char *)client->user_agent, "esp-link");

  client->pCon = (struct espconn *)os_zalloc(sizeof(struct espconn));
  client->pCon->proto.tcp = (esp_tcp *)os_zalloc(sizeof(esp_tcp));

  client->pCon->type = ESPCONN_TCP;
  client->pCon->state = ESPCONN_NONE;
  client->pCon->proto.tcp->local_port = espconn_port();
  client->pCon->proto.tcp->remote_port = client->port;

  client->pCon->reverse = client;

  return REST_CB | (uint32_t)clientNum;
}
void ICACHE_FLASH_ATTR mqttDisconnectedCb(uint32_t *args) {
	MQTT_Client* client = (MQTT_Client*) args;
	os_printf("MQTT: Disconnected\r\n");
}