Beispiel #1
0
/* ======================================================================
Function: sendJSON 
Purpose : dump all values in JSON
Input   : linked list pointer on the concerned data
          true to dump all values, false for only modified ones
Output  : - 
Comments: -
====================================================================== */
void sendJSON(void)
{
  ValueList * me = tinfo.getList();
  String response = "";
  
  // Got at least one ?
  if (me) {
    // Json start
    response += FPSTR(FP_JSON_START);
    response += F("\"_UPTIME\":");
    response += seconds;

    // Loop thru the node
    while (me->next) {
      // go to next node
      me = me->next;
      response += F(",\"") ;
      response += me->name ;
      response += F("\":") ;
      formatNumberJSON(response, me->value);
    }
   // Json end
   response += FPSTR(FP_JSON_END) ;

  } else {
    server.send ( 404, "text/plain", "No data" );
  }
  server.send ( 200, "text/json", response );
}
Beispiel #2
0
void Sensor::Sensing(SensingInfo* info) {
	uint32_t currentTime = millis();
	if ( (currentTime - lastTime) > 2000 ) {
		
		if (count >= MAX_COUNT) {
			StaticJsonBuffer<SENSORDATA_JSON_SIZE>* jsonBuffer = new StaticJsonBuffer<SENSORDATA_JSON_SIZE>; 
			JsonObject& root = jsonBuffer->createObject();
			
			root[FPSTR(TEMPERATURE_KEY)] = prevTemp = nomalization(temperature);
			root[FPSTR(HUMIDITY_KEY)] = prevHumid = nomalization(humidity);
			
			String SensingData = "";
			
			root.printTo(SensingData);
			info->deserialize(SensingData);

			delete jsonBuffer;
			
			requireUpdate = true;
			count = 0;
		}

		checkHumData(count);
		checkTemData(count);
		count++;

		lastTime = currentTime;
	}
}
Beispiel #3
0
/* ======================================================================
Function: getSpiffsJSONData 
Purpose : Return JSON string containing list of SPIFFS files
Input   : Response String
Output  : - 
Comments: -
====================================================================== */
void getSpiffsJSONData(String & response)
{
  char buffer[32];
  bool first_item = true;

  // Json start
  response = FPSTR(FP_JSON_START);

  // Files Array  
  response += F("\"files\":[\r\n");

  // Loop trough all files
  Dir dir = SPIFFS.openDir("/");
  while (dir.next()) {    
    String fileName = dir.fileName();
    size_t fileSize = dir.fileSize();
    if (first_item)  
      first_item=false;
    else
      response += ",";

    response += F("{\"na\":\"");
    response += fileName.c_str();
    response += F("\",\"va\":\"");
    response += fileSize;
    response += F("\"}\r\n");
  }
  response += F("],\r\n");


  // SPIFFS File system array
  response += F("\"spiffs\":[\r\n{");
  
  // Get SPIFFS File system informations
  FSInfo info;
  SPIFFS.info(info);
  response += F("\"Total\":");
  response += info.totalBytes ;
  response += F(", \"Used\":");
  response += info.usedBytes ;
  response += F(", \"ram\":");
  response += system_get_free_heap_size() ;
  response += F("}\r\n]"); 

  // Json end
  response += FPSTR(FP_JSON_END);
}
Beispiel #4
0
bool EE_LoadData(void) {
  bool ret = false;
  char data[EE_SIZE];
  uint16_t i;

  DEBUG_PRINT("EEPROM loading...\n");
  for (i = 0; i < EE_SIZE; i++) {
    yield();
    data[i] = EEPROM.read(i);
    // DEBUG_PRINT("%c", data[i]);
  }
  DEBUG_PRINT("\n");

  DynamicJsonBuffer jsonBuffer;
  JsonObject &root = jsonBuffer.parseObject(data);

  // Test if parsing succeeds.
  if (root.success() == 1) {
    const char *ssid = root[FPSTR("ssid")];
    DEBUG_PRINT("ssid: %s\n", ssid);
    const char *password = root[FPSTR("password")];
    DEBUG_PRINT("password: %s\n", password);
    const char *uid = root[FPSTR("uid")];
    DEBUG_PRINT("uid: %s\n", uid);
    const char *domain = root[FPSTR("domain")];
    DEBUG_PRINT("domain: %s\n", domain);
    const char *nodename = root[FPSTR("nodename")];
    DEBUG_PRINT("nodename: %s\n", nodename);
    if ((ssid != NULL) && (password != NULL) && (uid != NULL) &&
        (domain != NULL) && (nodename != NULL)) {
      ee_ssid = String(ssid);
      ee_password = String(password);
      ee_uid = String(uid);
      ee_domain = String(domain);
      ee_nodename = String(nodename);
      DEBUG_PRINT("EEPROM ok\n");
      ret = true;
    } else {
      DEBUG_PRINT("EEPROM content not ok\n");
    }
  } else {
    DEBUG_PRINT("parseObject() failed\n");
  }

  return ret;
}
Beispiel #5
0
// Handler Event when ESP8266 server receive request
String ESPHB::httpHandlerEvent(String *request){
	String cssid,cpassword,ckey,cserver,respone="";
	GETValue(request,"key",&ckey);
	GETValue(request,"ssid",&cssid);
	GETValue(request,"password",&cpassword);
	GETValue(request,"server",&cserver);
	if((ckey==String(WF_INF.WF_KEY))&&(cssid.length()<=MAX_SSID_LEN)&&(cpassword.length()<=MAX_PASSWORD_LEN)&&(cserver.length()<=MAX_SERVER_LEN)){
		StringToArray(&cssid, WF_INF.WF_SSID, MAX_SSID_LEN);
        StringToArray(&cpassword, WF_INF.WF_PASSWORD, MAX_PASSWORD_LEN);
        StringToArray(&cserver, WF_INF.MASTER_SERVER, MAX_SERVER_LEN);
        EEPROMSave(50,&WF_INF);        
		jsonEncode(ONEJSON,&respone,"result",F("Success"));
		if(DEBUG){
            Serial.println(FPSTR(lb_CHANGE_SUCCESS));
            Serial.print(FPSTR(lb_SSID));
            Serial.print(FPSTR(lb_TO));
            Serial.println(cssid);
            Serial.print(FPSTR(lb_PASSWORD));
            Serial.print(FPSTR(lb_TO));
            Serial.println(cpassword);
            Serial.print(FPSTR(lb_SERVER));
            Serial.print(FPSTR(lb_TO));
            Serial.println(cserver);            
        };
	}else{
        jsonEncode(ONEJSON,&respone,"result",F("Error"));
    }
    return respone;
}
Beispiel #6
0
// display the list of commands in response to the 'help' command
void
Menu::_help(void)
{
    int		i;

    Serial.println("Commands:");
    for (i = 0; i < _entries; i++)
        Serial.printf("  %S\n", FPSTR(_commands[i].command));
}
Beispiel #7
0
/* ======================================================================
Function: wifiScanJSON 
Purpose : scan Wifi Access Point and return JSON code
Input   : -
Output  : - 
Comments: -
====================================================================== */
void wifiScanJSON(void)
{
  String response = "";
  bool first = true;

  // Just to debug where we are
  Debug(F("Serving /wifiscan page..."));

  int n = WiFi.scanNetworks();

  // Json start
  response += F("[\r\n");

  for (uint8_t i = 0; i < n; ++i)
  {
    int8_t rssi = WiFi.RSSI(i);
    
    uint8_t percent;

    // dBm to Quality
    if(rssi<=-100)      percent = 0;
    else if (rssi>=-50) percent = 100;
    else                percent = 2 * (rssi + 100);

    if (first) 
      first = false;
    else
      response += F(",");

    response += F("{\"ssid\":\"");
    response += WiFi.SSID(i);
    response += F("\",\"rssi\":") ;
    response += rssi;
    response += FPSTR(FP_JSON_END);
  }

  // Json end
  response += FPSTR("]\r\n");

  Debug(F("sending..."));
  server.send ( 200, "text/json", response );
  Debugln(F("Ok!"));
}
String RelaySetting::serialize(bool rev) {
	// Jsonbuffer 동적할당
	StaticJsonBuffer<RELAY_JSON_SIZE>* jsonBuffer = new StaticJsonBuffer<RELAY_JSON_SIZE>;

	// Relay Data를 JSON 로 변환
	JsonObject& root = jsonBuffer->createObject();
	
	root[FPSTR(TEMPERATURE_KEY)] = data->temperature;
	root[FPSTR(HUMIDITY_KEY)] = data->humidity;

	// JSON을 스트링으로 변환
	String json = "";
	root.printTo(json);

	// 동적할당한 메모리 반환
	delete jsonBuffer;

	return json;
}
Beispiel #9
0
// display the list of commands in response to the 'help' command
void
Menu::_help(void)
{
    int i;

    _port->println_P(PSTR("Commands:"));
    for (i = 0; i < _entries; i++) {
		delay(10);
        _port->printf_P(PSTR("  %S\n"), FPSTR(_commands[i].command));
	}
}
Beispiel #10
0
void  WIFI_CONFIG::Safe_Setup()
{
		#ifdef CAPTIVE_PORTAL_FEATURE
		dnsServer.stop();
		delay(100);
		#endif
		WiFi.disconnect();
		//setup Soft AP
		WiFi.mode(WIFI_AP);
		IPAddress local_ip (DEFAULT_IP_VALUE[0],DEFAULT_IP_VALUE[1],DEFAULT_IP_VALUE[2],DEFAULT_IP_VALUE[3]);
		IPAddress gateway (DEFAULT_GATEWAY_VALUE[0],DEFAULT_GATEWAY_VALUE[1],DEFAULT_GATEWAY_VALUE[2],DEFAULT_GATEWAY_VALUE[3]);
		IPAddress subnet (DEFAULT_MASK_VALUE[0],DEFAULT_MASK_VALUE[1],DEFAULT_MASK_VALUE[2],DEFAULT_MASK_VALUE[3]);
		String ssid = FPSTR(DEFAULT_SSID);
		String pwd = FPSTR(DEFAULT_PASSWORD);
		WiFi.softAP(ssid.c_str(),pwd.c_str());
		delay(500);
		WiFi.softAPConfig( local_ip,  gateway,  subnet);
		delay(1000);
		Serial.println(F("M117 Safe mode started"));
}
Beispiel #11
0
bool CONFIG::reset_config()
{
  if(!CONFIG::write_byte(EP_WIFI_MODE,DEFAULT_WIFI_MODE))return false;
  if(!CONFIG::write_string(EP_SSID,String(FPSTR(DEFAULT_SSID)).c_str(),strlen_P(DEFAULT_SSID)))return false;
  if(!CONFIG::write_string(EP_PASSWORD,String(FPSTR(DEFAULT_PASSWORD)).c_str(),strlen_P(DEFAULT_PASSWORD)))return false;
  if(!CONFIG::write_byte(EP_IP_MODE,DEFAULT_IP_MODE))return false;
  if(!CONFIG::write_buffer(EP_IP_VALUE,DEFAULT_IP_VALUE,IP_LENGH))return false;
  if(!CONFIG::write_buffer(EP_MASK_VALUE,DEFAULT_MASK_VALUE,IP_LENGH))return false;
  if(!CONFIG::write_buffer(EP_GATEWAY_VALUE,DEFAULT_GATEWAY_VALUE,IP_LENGH))return false;
  if(!CONFIG::write_buffer(EP_BAUD_RATE,(const byte *)&DEFAULT_BAUD_RATE,INTEGER_LENGH))return false;
  if(!CONFIG::write_byte(EP_PHY_MODE,DEFAULT_PHY_MODE))return false;
  if(!CONFIG::write_byte(EP_SLEEP_MODE,DEFAULT_SLEEP_MODE))return false;
  if(!CONFIG::write_byte(EP_CHANNEL,DEFAULT_CHANNEL))return false;
  if(!CONFIG::write_byte(EP_AUTH_TYPE,DEFAULT_AUTH_TYPE))return false;
  if(!CONFIG::write_byte(EP_SSID_VISIBLE,DEFAULT_SSID_VISIBLE))return false;
  if(!CONFIG::write_buffer(EP_WEB_PORT,(const byte *)&DEFAULT_WEB_PORT,INTEGER_LENGH))return false;
  if(!CONFIG::write_buffer(EP_DATA_PORT,(const byte *)&DEFAULT_DATA_PORT,INTEGER_LENGH))return false;
  if(!CONFIG::write_byte(EP_POLLING_TIME,DEFAULT_POLLING_TIME))return false;
  return true;
}
bool RelaySetting::deserialize(String json, bool rev) {
	// Jsonbuffer 동적할당
	StaticJsonBuffer<RELAY_JSON_SIZE>* jsonBuffer = new StaticJsonBuffer<RELAY_JSON_SIZE>;

	// JSON 분석
	JsonObject& root = jsonBuffer->parseObject(json);
	if( !root.success() ) {
		delete jsonBuffer;
		return false;
	}

	// 분석한 데이터 입력
	// 온, 습도를 조절할 릴레이의 정보가 각각 배열로 되어있으며 인덱스는 릴레이 위치 = 0, 현재 상태 = 1 로 되어 있음.
	data->temperature = root[FPSTR(TEMPERATURE_KEY)];
	data->humidity = root[FPSTR(HUMIDITY_KEY)];
	
	// 동적할당한 메모리 반환
	delete jsonBuffer;
	
	return true;
}
Beispiel #13
0
/* ======================================================================
Function: handleReset 
Purpose : reset the module
Input   : -
Output  : - 
Comments: -
====================================================================== */
void handleReset(void)
{
  // Just to debug where we are
  Debug(F("Serving /reset page..."));
  Debug(F("sending..."));
  server.send ( 200, "text/plain", FPSTR(FP_RESTART) );
  Debugln(F("Ok!"));
  delay(1000);
  ESP.restart();
  while (true)
    delay(1);

}
Beispiel #14
0
String EspClass::getFullVersion()
{
    return   String(F("SDK:")) + system_get_sdk_version()
           + F("/Core:") + FPSTR(arduino_esp8266_git_ver)
           + F("=") + String(esp8266::coreVersionNumeric())
#if LWIP_VERSION_MAJOR == 1
           + F("/lwIP:") + String(LWIP_VERSION_MAJOR) + "." + String(LWIP_VERSION_MINOR) + "." + String(LWIP_VERSION_REVISION)
#if LWIP_VERSION_IS_DEVELOPMENT
             + F("-dev")
#endif
#if LWIP_VERSION_IS_RC
             + F("rc") + String(LWIP_VERSION_RC)
#endif
#else // LWIP_VERSION_MAJOR != 1
             + F("/lwIP:")
#if LWIP_IPV6
             + F("IPv6+")
#endif // LWIP_IPV6
             + F(LWIP_HASH_STR)
#endif // LWIP_VERSION_MAJOR != 1
             + FPSTR(bearssl_version)
           ;
}
Beispiel #15
0
bool CONFIG::reset_config()
{
  if(!CONFIG::write_byte(EP_WIFI_MODE,DEFAULT_WIFI_MODE))return false;
  if(!CONFIG::write_string(EP_SSID,FPSTR(DEFAULT_SSID)))return false;
  if(!CONFIG::write_string(EP_PASSWORD,FPSTR(DEFAULT_PASSWORD)))return false;
  if(!CONFIG::write_byte(EP_IP_MODE,DEFAULT_IP_MODE))return false;
  if(!CONFIG::write_buffer(EP_IP_VALUE,DEFAULT_IP_VALUE,IP_LENGTH))return false;
  if(!CONFIG::write_buffer(EP_MASK_VALUE,DEFAULT_MASK_VALUE,IP_LENGTH))return false;
  if(!CONFIG::write_buffer(EP_GATEWAY_VALUE,DEFAULT_GATEWAY_VALUE,IP_LENGTH))return false;
  if(!CONFIG::write_buffer(EP_BAUD_RATE,(const byte *)&DEFAULT_BAUD_RATE,INTEGER_LENGTH))return false;
  if(!CONFIG::write_byte(EP_PHY_MODE,DEFAULT_PHY_MODE))return false;
  if(!CONFIG::write_byte(EP_SLEEP_MODE,DEFAULT_SLEEP_MODE))return false;
  if(!CONFIG::write_byte(EP_CHANNEL,DEFAULT_CHANNEL))return false;
  if(!CONFIG::write_byte(EP_AUTH_TYPE,DEFAULT_AUTH_TYPE))return false;
  if(!CONFIG::write_byte(EP_SSID_VISIBLE,DEFAULT_SSID_VISIBLE))return false;
  if(!CONFIG::write_buffer(EP_WEB_PORT,(const byte *)&DEFAULT_WEB_PORT,INTEGER_LENGTH))return false;
  if(!CONFIG::write_buffer(EP_DATA_PORT,(const byte *)&DEFAULT_DATA_PORT,INTEGER_LENGTH))return false;
  if(!CONFIG::write_byte(EP_REFRESH_PAGE_TIME,DEFAULT_REFRESH_PAGE_TIME))return false;
  if(!CONFIG::write_string(EP_HOSTNAME,wifi_config.get_default_hostname()))return false;
  if(!CONFIG::write_buffer(EP_XY_FEEDRATE,(const byte *)&DEFAULT_XY_FEEDRATE,INTEGER_LENGTH))return false;
  if(!CONFIG::write_buffer(EP_Z_FEEDRATE,(const byte *)&DEFAULT_Z_FEEDRATE,INTEGER_LENGTH))return false;
  if(!CONFIG::write_buffer(EP_E_FEEDRATE,(const byte *)&DEFAULT_E_FEEDRATE,INTEGER_LENGTH))return false;
  return true;
}
Beispiel #16
0
//Read configuration settings and apply them
bool WIFI_CONFIG::Setup()
{
    char pwd[MAX_PASSWORD_LENGTH+1];
    char sbuf[MAX_SSID_LENGTH+1];
    char hostname [MAX_HOSTNAME_LENGTH+1];
    int wstatus;
    IPAddress currentIP;
    byte bflag=0;

    //set the sleep mode
    if (!CONFIG::read_byte(EP_SLEEP_MODE, &bflag )) {
        return false;
    }
    wifi_set_sleep_type ((sleep_type)bflag);
    sleep_mode=bflag;
    //AP or client ?
    if (!CONFIG::read_byte(EP_WIFI_MODE, &bflag ) ||  !CONFIG::read_string(EP_SSID, sbuf , MAX_SSID_LENGTH) ||!CONFIG::read_string(EP_PASSWORD, pwd , MAX_PASSWORD_LENGTH)) {
        return false;
    }
    if (!CONFIG::read_string(EP_HOSTNAME, hostname , MAX_HOSTNAME_LENGTH)) {
        strcpy(hostname,get_default_hostname());
    }
    //disconnect if connected
    WiFi.disconnect();
    //this is AP mode
    if (bflag==AP_MODE) {
        //setup Soft AP
        WiFi.mode(WIFI_AP);
        WiFi.softAP(sbuf, pwd);
        //setup PHY_MODE
        if (!CONFIG::read_byte(EP_PHY_MODE, &bflag )) {
            return false;
        }
        wifi_set_phy_mode((phy_mode)bflag);
        //get current config
        struct softap_config apconfig;
        wifi_softap_get_config(&apconfig);
        //set the chanel
        if (!CONFIG::read_byte(EP_CHANNEL, &bflag )) {
            return false;
        }
        apconfig.channel=bflag;
        //set Authentification type
        if (!CONFIG::read_byte(EP_AUTH_TYPE, &bflag )) {
            return false;
        }
        apconfig.authmode=(AUTH_MODE)bflag;
        //set the visibility of SSID
        if (!CONFIG::read_byte(EP_SSID_VISIBLE, &bflag )) {
            return false;
        }
        apconfig.ssid_hidden=!bflag;
        //no need to add these settings to configuration just use default ones
        apconfig.max_connection=DEFAULT_MAX_CONNECTIONS;
        apconfig.beacon_interval=DEFAULT_BEACON_INTERVAL;
        //apply settings to current and to default
        if (!wifi_softap_set_config(&apconfig) || !wifi_softap_set_config_current(&apconfig)) {
            Serial.println(F("M117 Error Wifi AP!"));
            delay(1000);
        }
    } else {
        //setup station mode
        WiFi.mode(WIFI_STA);
        WiFi.begin(sbuf, pwd);
        delay(500);
        //setup PHY_MODE
        if (!CONFIG::read_byte(EP_PHY_MODE, &bflag )) {
            return false;
        }
        wifi_set_phy_mode((phy_mode)bflag);
        delay(500);
        byte i=0;
        //try to connect
        while (WiFi.status() != WL_CONNECTED && i<40) {
            switch(WiFi.status()) {
            case 1:
                Serial.print(FPSTR(M117_));
                Serial.println(F("No SSID found!"));
                break;

            case 4:
                Serial.print(FPSTR(M117_));
                Serial.println(F("No Connection!"));
                break;

            default:
                Serial.print(FPSTR(M117_));
                Serial.println(F("Connecting..."));
                break;
            }
            delay(500);
            i++;
        }
        if (WiFi.status() != WL_CONNECTED) {
            return false;
        }
        WiFi.hostname(hostname);
    }

    //DHCP or Static IP ?
    if (!CONFIG::read_byte(EP_IP_MODE, &bflag )) {
        return false;
    }
    if (bflag==STATIC_IP_MODE) {
        byte ip_buf[4];
        //get the IP
        if (!CONFIG::read_buffer(EP_IP_VALUE,ip_buf , IP_LENGTH)) {
            return false;
        }
        IPAddress local_ip (ip_buf[0],ip_buf[1],ip_buf[2],ip_buf[3]);
        //get the gateway
        if (!CONFIG::read_buffer(EP_GATEWAY_VALUE,ip_buf , IP_LENGTH)) {
            return false;
        }
        IPAddress gateway (ip_buf[0],ip_buf[1],ip_buf[2],ip_buf[3]);
        //get the mask
        if (!CONFIG::read_buffer(EP_MASK_VALUE,ip_buf , IP_LENGTH)) {
            return false;
        }
        IPAddress subnet (ip_buf[0],ip_buf[1],ip_buf[2],ip_buf[3]);
        //apply according active wifi mode
        if (wifi_get_opmode()==WIFI_AP || wifi_get_opmode()==WIFI_AP_STA) {
            WiFi.softAPConfig( local_ip,  gateway,  subnet);
        } else {
            WiFi.config( local_ip,  gateway,  subnet);
        }
    }
#ifdef MDNS_FEATURE
    // Set up mDNS responder:
    if (!mdns.begin(hostname)) {
        Serial.print(FPSTR(M117_));
        Serial.println(F("Error with mDNS!"));
        delay(1000);
    }
#endif
    //Get IP
    if (wifi_get_opmode()==WIFI_STA) {
        currentIP=WiFi.localIP();
    } else {
        currentIP=WiFi.softAPIP();
    }
    Serial.print(FPSTR(M117_));
    Serial.println(currentIP);
    return true;
}
Beispiel #17
0
// run the menu
void
Menu::run(void)
{
    int8_t ret;
    uint8_t len, i;
    uint8_t argc;
    int c;
    char                *s;

	if (_port == NULL) {
		// default to main serial port
		_port = &Serial;
	}

    // loop performing commands
    for (;; ) {

        // run the pre-prompt function, if one is defined
        if ((NULL != _ppfunc) && !_ppfunc())
            return;

        // loop reading characters from the input
        len = 0;
        _port->printf_P(PSTR("%S] "), FPSTR(_prompt));
        for (;; ) {
            c = _port->read();
            if (-1 == c)
                continue;
            // carriage return -> process command
            if ('\r' == c) {
                _inbuf[len] = '\0';
                _port->write('\r');
                _port->write('\n');
                break;
            }
            // backspace
            if ('\b' == c) {
                if (len > 0) {
                    len--;
                    _port->write('\b');
                    _port->write(' ');
                    _port->write('\b');
                    continue;
                }
            }
            // printable character
            if (isprint(c) && (len < (MENU_COMMANDLINE_MAX - 1))) {
                _inbuf[len++] = c;
                _port->write((char)c);
                continue;
            }
        }

        // split the input line into tokens
        argc = 0;
        _argv[argc++].str = strtok_r(_inbuf, " ", &s);
        // XXX should an empty line by itself back out of the current menu?
        while (argc <= MENU_ARGS_MAX) {
            _argv[argc].str = strtok_r(NULL, " ", &s);
            if ('\0' == _argv[argc].str)
                break;
            _argv[argc].i = atol(_argv[argc].str);
            _argv[argc].f = atof(_argv[argc].str);      // calls strtod, > 700B !
            argc++;
        }

        if (_argv[0].str == NULL) {
            continue;
        }

        // populate arguments that have not been specified with "" and 0
        // this is safer than NULL in the case where commands may look
        // without testing argc
        i = argc;
        while (i <= MENU_ARGS_MAX) {
            _argv[i].str = "";
            _argv[i].i = 0;
            _argv[i].f = 0;
            i++;
        }

        bool cmd_found = false;
        // look for a command matching the first word (note that it may be empty)
        for (i = 0; i < _entries; i++) {
            if (!strcasecmp_P(_argv[0].str, _commands[i].command)) {
                ret = _call(i, argc);
                cmd_found=true;
                if (-2 == ret)
                    return;
                break;
            }
        }

        // implicit commands
        if (i == _entries) {
            if (!strcmp(_argv[0].str, "?") || (!strcasecmp_P(_argv[0].str, PSTR("help")))) {
                _help();
                cmd_found=true;
            } else if (!strcasecmp_P(_argv[0].str, PSTR("exit"))) {
                return;
            }
        }

        if (cmd_found==false)
        {
            _port->println_P(PSTR("Invalid command, type 'help'"));
        }

    }
}
Beispiel #18
0
String EE_GetFirebaseServerKey() {
  return FPSTR(ee_fb_cloud_messaging_server_key);
}
Beispiel #19
0
String EE_GetFirebaseUrl() { return FPSTR(ee_fb_url); }
Beispiel #20
0
//////////////////////////////////////////
///     Group function for Serial	   ///
//////////////////////////////////////////
void ESPHB::SerialEvent(void) {
	while (Serial.available()){
		char inChar = (char)Serial.read();
		SERIAL_RECEIVER += inChar;
		if (inChar == '\n') {SERIAL_COMPLETE = true;}   
		if(SERIAL_COMPLETE){
			String command=SERIAL_RECEIVER.substring(0,SERIAL_RECEIVER.indexOf("=="));
			String value=SERIAL_RECEIVER.substring(SERIAL_RECEIVER.indexOf("==")+2,SERIAL_RECEIVER.length()-1);
			if((command=="login")&&(!LOGINED)){
				if(value!=String(DV_INF.DV_ADMIN)){
					Serial.println(FPSTR(lb_LOGIN_FAILED));
				}else{
					Serial.println(FPSTR(lb_LOGIN_SUCCESS));
					LOGINED=true;					
				}
			}	
			else if((command=="status")&&LOGINED){
                Serial.print(FPSTR(lb_KEY));    Serial.println(WF_INF.WF_KEY);
				Serial.print(FPSTR(lb_SERIAL)); Serial.println(DV_INF.DV_SERIAL);
				Serial.print(FPSTR(lb_SSID));   Serial.println(WF_INF.WF_SSID);
                Serial.print(FPSTR(lb_PASSWORD));   Serial.println(WF_INF.WF_PASSWORD);
                Serial.print(FPSTR(lb_SERVER));   Serial.println(WF_INF.MASTER_SERVER);
                Serial.print(FPSTR(lb_SERVER));   Serial.println(WF_INF.MASTER_SERVER_PORT);
                Serial.print(FPSTR(lb_CONNECT_STATUS)); if(CONNECTED)   Serial.println(FPSTR(lb_CONNECTED)); else   Serial.println(FPSTR(lb_FAILED_CONNECT));
                Serial.print(FPSTR(lb_STA));    Serial.print(FPSTR(lb_MAC_ADDRESS));    Serial.println(WiFi.macAddress());
                Serial.print(FPSTR(lb_STA));    Serial.print(FPSTR(lb_IP));    Serial.println(WiFi.localIP());	
			}
			else if((command=="debug")&&LOGINED){
                DV_INF.DEBUG=true;
				EEPROMSave(0,&DV_INF);
                Serial.println(FPSTR(lb_DEBUG_ENABLE));
				ESP.restart();
			}
			else if((command=="normal")&&LOGINED){
                DV_INF.DEBUG=false;
				EEPROMSave(0,&DV_INF);
                Serial.println(FPSTR(lb_DEBUG_ENABLE));
				ESP.restart();
			}
			else if((command=="reboot")&&LOGINED){
				Serial.println(FPSTR(lb_REBOOT));
				ESP.restart();
			}
			else if((command=="restore")&&LOGINED){
				Serial.println(FPSTR(lb_RESTORE));
				Restore();
				ESP.restart();
			}
			else if((command=="serial")&&LOGINED){
				if(StringToArray(&value, DV_INF.DV_SERIAL, MAX_SERIAL_LEN)){
                    EEPROMSave(0,&DV_INF);
					Serial.print(FPSTR(lb_CHANGE_SUCCESS));
                    Serial.print(FPSTR(lb_SERIAL));
                    Serial.print(FPSTR(lb_TO));
					Serial.println(value);	
				}else{
                    Serial.print(FPSTR(lb_CHANGE_FAILED));
                    Serial.print(FPSTR(lb_SERIAL));
                    Serial.print(FPSTR(lb_TO));
					Serial.println(value);
                };
			}
			else if((command=="ssid")&&LOGINED){
				if(StringToArray(&value, WF_INF.WF_SSID, MAX_SSID_LEN)){
                    EEPROMSave(50,&WF_INF);
					Serial.print(FPSTR(lb_CHANGE_SUCCESS));
                    Serial.print(FPSTR(lb_SSID));
                    Serial.print(FPSTR(lb_TO));
					Serial.println(value);	
				}else{
                    Serial.print(FPSTR(lb_CHANGE_FAILED));
                    Serial.print(FPSTR(lb_SSID));
                    Serial.print(FPSTR(lb_TO));
					Serial.println(value);
                };
			}
			else if((command=="password")&&LOGINED){
				if(StringToArray(&value, WF_INF.WF_PASSWORD, MAX_PASSWORD_LEN)){
                    EEPROMSave(50,&WF_INF);
					Serial.print(FPSTR(lb_CHANGE_SUCCESS));
                    Serial.print(FPSTR(lb_PASSWORD));
                    Serial.print(FPSTR(lb_TO));
					Serial.println(value);	
				}else{
                    Serial.print(FPSTR(lb_CHANGE_FAILED));
                    Serial.print(FPSTR(lb_PASSWORD));
                    Serial.print(FPSTR(lb_TO));
					Serial.println(value);
                };
			}
			else if((command=="key")&&LOGINED){
				if(StringToArray(&value, WF_INF.WF_KEY, MAX_KEY_LEN)){
                    EEPROMSave(50,&WF_INF);
					Serial.print(FPSTR(lb_CHANGE_SUCCESS));
                    Serial.print(FPSTR(lb_KEY));
                    Serial.print(FPSTR(lb_TO));
					Serial.println(value);	
				}else{
                    Serial.print(FPSTR(lb_CHANGE_FAILED));
                    Serial.print(FPSTR(lb_KEY));
                    Serial.print(FPSTR(lb_TO));
					Serial.println(value);
                };
			}
			else if((command=="admin")&&LOGINED){
				if(StringToArray(&value, DV_INF.DV_ADMIN, MAX_ADMIN_LEN)){
                    EEPROMSave(0,&DV_INF);
					Serial.print(FPSTR(lb_CHANGE_SUCCESS));
                    Serial.print(FPSTR(lb_ADMIN_PASSWORD));
                    Serial.print(FPSTR(lb_TO));
					Serial.println(value);	
				}else{
                    Serial.print(FPSTR(lb_CHANGE_FAILED));
                    Serial.print(FPSTR(lb_ADMIN_PASSWORD));
                    Serial.print(FPSTR(lb_TO));
					Serial.println(value);
                };
			}
			else if((command=="server")&&LOGINED){
				if(StringToArray(&value, WF_INF.MASTER_SERVER, MAX_SERVER_LEN)){
                    EEPROMSave(50,&WF_INF);
					Serial.print(FPSTR(lb_CHANGE_SUCCESS));
                    Serial.print(FPSTR(lb_SERVER));
                    Serial.print(FPSTR(lb_TO));
					Serial.println(value);	
				}else{
                    Serial.print(FPSTR(lb_CHANGE_FAILED));
                    Serial.print(FPSTR(lb_SERVER));
                    Serial.print(FPSTR(lb_TO));
					Serial.println(value);
                };
			}
			else if((command=="port")&&LOGINED){
                WF_INF.MASTER_SERVER_PORT=value.toInt();
                EEPROMSave(50,&WF_INF);
				Serial.print(FPSTR(lb_CHANGE_SUCCESS));
                Serial.print(FPSTR(lb_SERVER_PORT));
                Serial.print(FPSTR(lb_TO));
			    Serial.println(value);
			}else if((command=="setDHT")&&LOGINED){
                // String setup: setDHT==ON/OFF-type-pin
                // ex: setDHT==ON-22-14
                uint8_t _dhttype,_dhtpin,_sepa,_nextsepa;
                _sepa = value.indexOf("-");
                _nextsepa = value.indexOf("-",_sepa);
                String _dhtset=value.substring(0,sepa);
                _dhttype = (value.substring( _sepa + 1, _nextsepa)).toInt();
                _dhtpin = (value.substring( _nextsepa + 1, value.length())).toInt();
                if(_dhtset=="ON"){
                    DV_INF.USE_DHT = 1;
                    DV_INF.DHT_TYPE = _dhttype;
                    DV_INF.DHT_PIN = _dhtpin;
                }else{
                    DV_INF.USE_DHT = 0;
                }
                
                
                WF_INF.MASTER_SERVER_PORT=value.toInt();
                EEPROMSave(50,&DV_INF);
				Serial.print(FPSTR(lb_CHANGE_SUCCESS));
                Serial.print(FPSTR(lb_SERVER_PORT));
                Serial.print(FPSTR(lb_TO));
			    Serial.println(value);
			}
			else if((command=="ip")&&LOGINED){
				WF_INF.WF_STATICIP = StringToIPAdress(value);
                EEPROMSave(50,&WF_INF);
				Serial.print(FPSTR(lb_CHANGE_SUCCESS));
                Serial.print(FPSTR(lb_STATIC));
                Serial.print(FPSTR(lb_IP));
                Serial.print(FPSTR(lb_TO));
				Serial.println(value);	
			}
			else if((command=="DHCP")&&LOGINED){
                if(WF_INF.IS_STATICIP!=1){
                    WF_INF.IS_STATICIP = 1;
                    Serial.println(FPSTR(lb_DHCP_ENABLE));
                }else{
                    WF_INF.IS_STATICIP = 0;
                    Serial.println(FPSTR(lb_DHCP_DISABLE));	
                }
                EEPROMSave(50,&WF_INF);
			}else{
				Serial.println(FPSTR(lb_COMMAND_ERROR));
			}
			SERIAL_RECEIVER="";
			SERIAL_COMPLETE = false;
		}
	}
}
Beispiel #21
0
/* ======================================================================
Function: getConfigJSONData 
Purpose : Return JSON string containing configuration data
Input   : Response String
Output  : - 
Comments: -
====================================================================== */
void getConfJSONData(String & r)
{
  // Json start
  r = FPSTR(FP_JSON_START); 

  r+="\"";
  r+=CFG_FORM_SSID;      r+=FPSTR(FP_QCQ); r+=config.ssid;           r+= FPSTR(FP_QCNL); 
  r+=CFG_FORM_PSK;       r+=FPSTR(FP_QCQ); r+=config.psk;            r+= FPSTR(FP_QCNL); 
  r+=CFG_FORM_HOST;      r+=FPSTR(FP_QCQ); r+=config.host;           r+= FPSTR(FP_QCNL); 
  r+=CFG_FORM_AP_PSK;    r+=FPSTR(FP_QCQ); r+=config.ap_psk;         r+= FPSTR(FP_QCNL); 
  r+=CFG_FORM_EMON_HOST; r+=FPSTR(FP_QCQ); r+=config.emoncms.host;   r+= FPSTR(FP_QCNL); 
  r+=CFG_FORM_EMON_PORT; r+=FPSTR(FP_QCQ); r+=config.emoncms.port;   r+= FPSTR(FP_QCNL); 
  r+=CFG_FORM_EMON_URL;  r+=FPSTR(FP_QCQ); r+=config.emoncms.url;    r+= FPSTR(FP_QCNL); 
  r+=CFG_FORM_EMON_KEY;  r+=FPSTR(FP_QCQ); r+=config.emoncms.apikey; r+= FPSTR(FP_QCNL); 
  r+=CFG_FORM_EMON_NODE; r+=FPSTR(FP_QCQ); r+=config.emoncms.node;   r+= FPSTR(FP_QCNL); 
  r+=CFG_FORM_EMON_FREQ; r+=FPSTR(FP_QCQ); r+=config.emoncms.freq;   r+= FPSTR(FP_QCNL); 
  r+=CFG_FORM_OTA_AUTH;  r+=FPSTR(FP_QCQ); r+=config.ota_auth;       r+= FPSTR(FP_QCNL); 
  r+=CFG_FORM_OTA_PORT;  r+=FPSTR(FP_QCQ); r+=config.ota_port;       r+= FPSTR(FP_QCNL);

  r+=CFG_FORM_JDOM_HOST; r+=FPSTR(FP_QCQ); r+=config.jeedom.host;   r+= FPSTR(FP_QCNL); 
  r+=CFG_FORM_JDOM_PORT; r+=FPSTR(FP_QCQ); r+=config.jeedom.port;   r+= FPSTR(FP_QCNL); 
  r+=CFG_FORM_JDOM_URL;  r+=FPSTR(FP_QCQ); r+=config.jeedom.url;    r+= FPSTR(FP_QCNL); 
  r+=CFG_FORM_JDOM_KEY;  r+=FPSTR(FP_QCQ); r+=config.jeedom.apikey; r+= FPSTR(FP_QCNL); 
  r+=CFG_FORM_JDOM_ADCO; r+=FPSTR(FP_QCQ); r+=config.jeedom.adco;   r+= FPSTR(FP_QCNL); 
  r+=CFG_FORM_JDOM_FREQ; r+=FPSTR(FP_QCQ); r+=config.jeedom.freq;  

  r+= F("\""); 
  // Json end
  r += FPSTR(FP_JSON_END);

}
Beispiel #22
0
String EE_GetFirebaseSecret() { return FPSTR(ee_fb_secret); }
Beispiel #23
0
bool FOTAService(void) {

  FOTA_StateMachine_t state_current;
  String storage_bucket = EE_GetFirebaseStorageBucket();

  state_current = state;

  switch (state) {
  case FOTA_Sm_IDLE:
    break;

  case FOTA_Sm_GET_MD5: {
    String md5file_url = String(F("/v0/b/")) + storage_bucket +
                         String(F("/o/")) + VERS_HW_VER +
                         String(FPSTR(md5file_name)) + String(F("?alt=media"));
    addr = String(F("https://")) + String(FPSTR(storage_host)) + md5file_url;
    DEBUG_PRINT("FOTA_Sm_GET_MD5 %s\n", addr.c_str());
    http = new HTTPClient;
    http->setReuse(true);
    http->setTimeout(3000);
    bool res = http->begin(addr, storage_fingerprint);
    if (res == true) {
      int httpCode = http->GET();
      // httpCode will be negative on error
      if (httpCode > 0) {
        // HTTP header has been send and Server response header has been handled
        DEBUG_PRINT("[HTTP] GET... code: %d\n", httpCode);
        // file found at server
        if (httpCode == HTTP_CODE_OK) {
          int size = http->getSize();
          if (size == DIGEST_MD5_SIZE) {
            DEBUG_PRINT("md5file size %d\n", size);
            WiFiClient *stream = http->getStreamPtr();
            digest_MD5 = (uint8_t *)malloc(DIGEST_MD5_SIZE);
            stream->read(digest_MD5, size);
            state = FOTA_Sm_CHECK;
          } else {
            DEBUG_PRINT("md5file size error: %d\n", size);
            state = FOTA_Sm_ERROR;
          }
        } else {
          DEBUG_PRINT("md5file httpCode error: %d\n", httpCode);
          state = FOTA_Sm_ERROR;
        }
      } else {
        DEBUG_PRINT("[HTTP] GET... failed, error: %s\n",
                    http->errorToString(httpCode).c_str());
        state = FOTA_Sm_ERROR;
      }
    } else {
      DEBUG_PRINT("[HTTP] begin... failed, error: %d\n", res);
      state = FOTA_Sm_ERROR;
    }
  } break;

  case FOTA_Sm_CHECK: {
    String file_url = String(F("/v0/b/")) + storage_bucket + String(F("/o/")) +
                      VERS_HW_VER + String(FPSTR(file_name)) +
                      String(F("?alt=media"));
    addr = String(F("https://")) + String(FPSTR(storage_host)) + file_url;
    DEBUG_PRINT("FOTA_Sm_CHECK %s\n", addr.c_str());
    http->setReuse(true);
    bool res = http->begin(addr, storage_fingerprint);
    if (res == true) {
      int httpCode = http->GET();
      // httpCode will be negative on error
      if (httpCode > 0) {
        http->end();
        // HTTP header has been send and Server response header has been handled
        DEBUG_PRINT("[HTTP] GET... code: %d\n", httpCode);
        int size = http->getSize();
        DEBUG_PRINT("file size %d\n", size);

        block = 0;
        num_blocks = (size + block_size - 1) / block_size;
        if (Update.begin(size, 0)) {
          Update.setMD5((char *)digest_MD5);
          buffer = (uint8_t *)malloc(block_size);
          state = FOTA_Sm_GET_BLOCK;
        } else {
          state = FOTA_Sm_ERROR;
        }
      } else {
        DEBUG_PRINT("file httpCode error: %d\n", httpCode);
        state = FOTA_Sm_ERROR;
      }
    } else {
      state = FOTA_Sm_ERROR;
    }
  } break;

  case FOTA_Sm_GET_BLOCK: {
    http->setReuse(true);
    bool res = http->begin(addr, storage_fingerprint);
    if (res == true) {
      String range = String(F("bytes=")) + String(block * block_size) +
                     String(F("-")) + String(((block + 1) * block_size) - 1);
      http->addHeader(String(F("Range")), range);
      int httpCode = http->GET();
      // httpCode will be negative on error
      if (httpCode > 0) {
        // HTTP header has been send and Server response header has been handled
        // Serial.printf("[HTTP] GET... code: %d\n", httpCode);

        int len = http->getSize();

        // get tcp stream
        WiFiClient *stream = http->getStreamPtr();
        int pos = 0;
        bool run = true;
        bool fail = false;

        while (run == true) {
          delay(1);
          if (pos < len) {
            size_t size = stream->available();
            if (size) {
              uint16_t c = stream->readBytes(&buffer[pos], size);
              pos += c;
            }
            if (!http->connected() && (pos < len)) {
              run = false;
              fail = true;
            }
          } else {
            run = false;
          }
        }

        if (fail == false) {
          Update.write(buffer, pos);

          DEBUG_PRINT("[%03d]: %02d%% -- %d\r", block, 100 * block / num_blocks,
                      ESP.getFreeHeap());

          block++;
          if (block < num_blocks) {
            /* move to next block */
            state = FOTA_Sm_GET_BLOCK;
          } else {
            if (!Update.end()) {
              DEBUG_PRINT("Update Error\n");
            }
            state = FOTA_Sm_COMPLETE;
          }
        } else {
          state = FOTA_Sm_ERROR;
        }
      } else {
        DEBUG_PRINT("[HTTP] GET... failed, error: %s\n",
                    http->errorToString(httpCode).c_str());
        state = FOTA_Sm_ERROR;
      }
    } else {
      DEBUG_PRINT("begin error @ %d\n", block);
      state = FOTA_Sm_ERROR;
    }
  } break;

  case FOTA_Sm_ERROR: {
    if (http_fail_cnt++ < 20) {
      DEBUG_PRINT("retry %d\n", http_fail_cnt);
      state = state_last;
    } else {
      /* give-up */
      DEBUG_PRINT("retry give-up\n");
      Serial.flush();
      ESP.restart();
    }
  } break;

  case FOTA_Sm_COMPLETE: {
    DEBUG_PRINT("closing connection\n");
    Serial.flush();
    free(buffer);
    /* restar node anycase */
    ESP.restart();
    state = FOTA_Sm_IDLE;
  } break;
  }

  state_last = state_current;

  return (state != FOTA_Sm_IDLE);
}
Beispiel #24
0
/* ======================================================================
Function: handleNotFound 
Purpose : default WEB routing when URI is not found
Input   : -
Output  : - 
Comments: -
====================================================================== */
void handleNotFound(void) 
{
  String response = "";
  boolean found = false;  

  // Led on
  LedBluON();

  // try to return SPIFFS file
  found = handleFileRead(server.uri());

  // Try Teleinfo ETIQUETTE
  if (!found) {
    // We check for an known label
    ValueList * me = tinfo.getList();
    const char * uri;
    // convert uri to char * for compare
    uri = server.uri().c_str();

    Debugf("handleNotFound(%s)\r\n", uri);

    // Got at least one and consistent URI ?
    if (me && uri && *uri=='/' && *++uri ) {
      
      // Loop thru the linked list of values
      while (me->next && !found) {

        // go to next node
        me = me->next;

        //Debugf("compare to '%s' ", me->name);
        // Do we have this one ?
        if (stricmp (me->name, uri) == 0 )
        {
          // no need to continue
          found = true;

          // Add to respone
          response += F("{\"") ;
          response += me->name ;
          response += F("\":") ;
          formatNumberJSON(response, me->value);
          response += F("}\r\n");
        }
      }
    }

    // Got it, send json
    if (found) 
      server.send ( 200, "text/json", response );
  }

  // All trys failed
  if (!found) {
    // send error message in plain text
    String message = F("File Not Found\n\n");
    message += F("URI: ");
    message += server.uri();
    message += F("\nMethod: ");
    message += ( server.method() == HTTP_GET ) ? "GET" : "POST";
    message += F("\nArguments: ");
    message += server.args();
    message += FPSTR(FP_NL);

    for ( uint8_t i = 0; i < server.args(); i++ ) {
      message += " " + server.argName ( i ) + ": " + server.arg ( i ) + FPSTR(FP_NL);
    }

    server.send ( 404, "text/plain", message );
  }

  // Led off
  LedBluOFF();
}
Beispiel #25
0
String EE_GetFirebaseStorageBucket() { return FPSTR(ee_fb_storage_bucket); }