Example #1
0
int Request::timeParamToSeconds(String param)
{
	try {
		int s = 0;

		if(param.contains("h"))
		{
			String hours = param;
			param = hours.cut('h');
			s+= hours.toInt()*3600;

			if(!param.contains("m") && !param.contains("s"))
				param+= 'm';
		}

		if(param.contains("m"))
		{
			String minutes = param;
			param = minutes.cut('m');
			s+= minutes.toInt()*60;
		}

		param.cut('s');
		s+= param.toInt();
		return s;
	}
	catch(const std::exception &e)
	{
		return -1;
	}
}
Example #2
0
static void callback(char* topic, byte* payload, unsigned int length) {
  StaticJsonBuffer<200> jsonBuffer;

//  Serial.print("Message arrived [");
//  Serial.print(topic);
//  Serial.print("] ");
//  for (int i = 0; i < length; i++) {
//    Serial.print((char)payload[i]);
//  }
//  Serial.println();

  JsonObject& root = jsonBuffer.parseObject((char *)payload);
  if (!root.success()) {
    Serial.println("Failed to parse incoming JSON message.");
    return;
  }

  String keyname = root["keyname"];
  String value = root["value"];
//  Serial.print("Got key: ");
//  Serial.println(keyname);

//  Serial.print("Value: ");
//  Serial.println(value);

  if (keyname == "new_mode") {
    g_settings.mode = value.toInt() ? MODE_COOL:MODE_HEAT;
    Serial.print("Updated MODE to: ");
    Serial.println(g_settings.mode);
  }  else if (keyname == "new_compmode") {
    g_settings.comp_mode = value.toInt();
    Serial.print("Updated COMPRESSOR MODE to: ");
    Serial.println(g_settings.comp_mode);
  }  else if (keyname == "full_status") {
    full_status = value.toInt();
    Serial.print("Force full status update");
    Serial.println(full_status);
  }  else if (keyname == "new_setpoint") {
    g_settings.setpoint = value.toInt();
    Serial.print("Updated setpoint to: ");
    Serial.println(g_settings.setpoint);
  }  else if (keyname == "new_hyst") {
    g_settings.hysteresis = value.toInt();
    Serial.print("Updated hysteresis to: ");
    Serial.println(g_settings.hysteresis);
  }

}
Example #3
0
int HttpRequest::getContentLength()
{
	String len = getHeader("Content-Length");
	if (len.length() == 0) return -1;

	return len.toInt();
}
Example #4
0
bool NetworkJob::handleFTPHeader(const String& header)
{
    size_t spacePos = header.find(' ');
    if (spacePos == notFound)
        return false;
    String statusCode = header.left(spacePos);
    switch (statusCode.toInt()) {
    case 213:
        m_isFTPDir = false;
        break;
    case 530:
        purgeCredentials();
        sendRequestWithCredentials(ProtectionSpaceServerFTP, ProtectionSpaceAuthenticationSchemeDefault, "ftp");
        break;
    case 230:
        storeCredentials();
        break;
    case 550:
        // The user might have entered an URL which point to a directory but forgot type '/',
        // e.g., ftp://ftp.trolltech.com/qt/source where 'source' is a directory. We need to
        // added '/' and try again.
        if (m_handle && !m_handle->firstRequest().url().path().endsWith("/"))
            m_needsRetryAsFTPDirectory = true;
        break;
    }

    return true;
}
Example #5
0
void InspectorState::loadFromSettings()
{
    for (PropertyMap::iterator i = m_properties.begin(); i != m_properties.end(); ++i) {
        if (i->second.m_preferenceName.length()) {
            String value;
            m_client->populateSetting(i->second.m_preferenceName, &value);
            switch (i->second.m_value->type()) {
            case InspectorValue::TypeBoolean:
                if (value.length())
                    i->second.m_value = InspectorBasicValue::create(value == "true");
                break;
            case InspectorValue::TypeString:
                i->second.m_value = InspectorString::create(value);
                break;
            case InspectorValue::TypeNumber:
                if (value.length())
                    i->second.m_value = InspectorBasicValue::create((double)value.toInt());
                break;
            default:
                ASSERT(false);
                break;
            }
        }
    }
}
void DefaultPolicyDelegate::decidePolicyForNavigationAction(WebView* webView, 
    /*[in]*/ WebActionPropertyBag* actionInformation, 
    /*[in]*/ WebMutableURLRequest* request, 
    /*[in]*/ WebFrame* /*frame*/, 
    /*[in]*/ WebFramePolicyListener* listener)
{
    int navType = 0;

    String ret = actionInformation->Read(WebActionNavigationTypeKey);
    navType = ret.toInt();

    bool canHandleRequest = webView->canHandleRequest(request);
    if (canHandleRequest)
        listener->use();
    else if (navType == WebNavigationTypePlugInRequest)
        listener->use();
    else {
        String url = request->URL();
        // A file URL shouldn't fall through to here, but if it did,
        // it would be a security risk to open it.
        if (!url.startsWith("file:")) {
            // FIXME: Open the URL not by means of a webframe, but by handing it over to the system and letting it determine how to open that particular URL scheme.  See documentation for [NSWorkspace openURL]
            ;
        }
        listener->ignore();
    }
}
Example #7
0
int divHandler(String command) {
	int div = (int) command.toInt();

	// This will cause a divide-by-zero error when 0 is passed in the data
	int result = 1000 / div;

	return result;
}
int GetMoveTimer()
{
    //Parse the int timer from the string
    String moveTimerString = slaveCommand.substring(slaveCommand.indexOf('[') + 1 ,slaveCommand.indexOf(']'));
    //Convert the string into a int.
    int moveTimerInt = moveTimerString.toInt();
    return moveTimerInt;
}
void TextTrackRegion::parseSettingValue(RegionSetting setting, const String& value)
{
    DEFINE_STATIC_LOCAL(const AtomicString, scrollUpValueKeyword, ("up", AtomicString::ConstructFromLiteral));

    bool isValidSetting;
    String numberAsString;
    int number;
    unsigned position;
    FloatPoint anchorPosition;

    switch (setting) {
    case Id:
        if (value.find("-->") == notFound)
            m_id = value;
        break;
    case Width:
        number = WebVTTParser::parseFloatPercentageValue(value, isValidSetting);
        if (isValidSetting)
            m_width = number;
        else
            LOG(Media, "TextTrackRegion::parseSettingValue, invalid Width");
        break;
    case Height:
        position = 0;

        numberAsString = WebVTTParser::collectDigits(value, &position);
        number = value.toInt(&isValidSetting);

        if (isValidSetting && number >= 0)
            m_heightInLines = number;
        else
            LOG(Media, "TextTrackRegion::parseSettingValue, invalid Height");
        break;
    case RegionAnchor:
        anchorPosition = WebVTTParser::parseFloatPercentageValuePair(value, ',', isValidSetting);
        if (isValidSetting)
            m_regionAnchor = anchorPosition;
        else
            LOG(Media, "TextTrackRegion::parseSettingValue, invalid RegionAnchor");
        break;
    case ViewportAnchor:
        anchorPosition = WebVTTParser::parseFloatPercentageValuePair(value, ',', isValidSetting);
        if (isValidSetting)
            m_viewportAnchor = anchorPosition;
        else
            LOG(Media, "TextTrackRegion::parseSettingValue, invalid ViewportAnchor");
        break;
    case Scroll:
        if (value == scrollUpValueKeyword)
            m_scroll = true;
        else
            LOG(Media, "TextTrackRegion::parseSettingValue, invalid Scroll");
        break;
    case None:
        break;
    }
}
	//SmartThings Shield data handler (receives configuration data from ST - polling interval, and adjusts on the fly)
	void PS_AdafruitAM2320_TempHumid::beSmart(const String &str)
	{
		String s = str.substring(str.indexOf(' ') + 1);

		if (s.toInt() != 0) {
			st::PollingSensor::setInterval(s.toInt() * 1000);
			if (st::PollingSensor::debug) {
				Serial.print(F("PS_AdafruitAM2320_TempHumid::beSmart set polling interval to "));
				Serial.println(s.toInt());
			}
		}
		else {
			if (st::PollingSensor::debug) 
			{
				Serial.print(F("PS_AdafruitAM2320_TempHumid::beSmart cannot convert "));
				Serial.print(s);
				Serial.println(F(" to an Integer."));
			}
		}
	}
Example #11
0
bool EncoderList::read() {

	//If the list is not empty
	if(_size != 0) {

		String str = "";
		int i = 0; //current encoder index
		bool has_read = false;

		while(serial->available()) {
			has_read = true;
			char incoming_char = (char) serial->read();

			if(incoming_char == RESET) {
				reset();
			}

			if(incoming_char != TOKEN) {
				str += incoming_char;
			} else {
				//Checks if the number of encoders sent on the serial
				//is equals to the expected
				if(i < _size) {
					this->get(i)->add(str.toInt());
					str = "";
					i ++;
				}
			}
		}

		if(has_read) {
			this->get(i)->add(str.toInt());
			serial->println(ACKNOWLEDGEMENT);
		}
		// serial->print("message = ");
		// print();

		return true;
	}
	return false;
}
Example #12
0
void Location::setPort(const String& portString, DOMWindow* activeWindow, DOMWindow* firstWindow)
{
    if (!m_frame)
        return;
    KURL url = m_frame->document()->url();
    int port = portString.toInt();
    if (port < 0 || port > 0xFFFF || portString.isEmpty())
        url.removePort();
    else
        url.setPort(port);
    m_frame->domWindow()->setLocation(url.string(), activeWindow, firstWindow);
}
int GetMoveCommand()
{
    //Parse out the move command.
    String moveCommand = slaveCommand.substring(slaveCommand.indexOf(':')+1,slaveCommand.indexOf('['));

    int MoveItemInt = moveCommand.toInt();


    if(MoveItemInt >= 0)
    {
        return MoveItemInt;
    }
    return 0;
}
Example #14
0
/*******************************************************************************
 * Function Name  : tinkerAnalogWrite
 * Description    : Writes an analog value (PWM) to the specified pin
 * Input          : Pin and Value (0 to 255)
 * Output         : None.
 * Return         : 1 on success and a negative number on failure
 *******************************************************************************/
int tinkerAnalogWrite(String command)
{
    //convert ascii to integer
    int pinNumber = command.charAt(1) - '0';
    //Sanity check to see if the pin numbers are within limits
    if (pinNumber< 0 || pinNumber >7) return -1;

    String value = command.substring(3);

    if(command.startsWith("D"))
    {
        pinMode(pinNumber, OUTPUT);
        analogWrite(pinNumber, value.toInt());
        return 1;
    }
    else if(command.startsWith("A"))
    {
        pinMode(pinNumber+10, OUTPUT);
        analogWrite(pinNumber+10, value.toInt());
        return 1;
    }
    else return -2;
}
Example #15
0
void ROTankWire::handleCmd(String var, String val) {
    if(var == "tdsoffset") {
        double offset = val.toFloat();
        //TheSensorsMem.TdsOffset = offset;
        TheTDSSensor.Update(offset);
    }
    else if(var == "phoffset") {
        double offset = val.toFloat();
        //ThePHSensor.Update(offset);
    }
    else if(var == "tdsVolts") {
        double volts = val.toFloat();
        TheTDSSensor.UpdateVolts(volts);
    }
    else if(var == "tdsMin") {
        int tdsMin = val.toInt();
        TheTDSSensor.UpdateTdsMin(tdsMin);
    }
    else if(var == "doseDurr") {
        int doseDurr = val.toInt();
        TheTDSSensor.UpdateRunDurration(doseDurr);
    }

}
Example #16
0
void PluginPackage::determineModuleVersionFromDescription()
{
    // It's a bit lame to detect the plugin version by parsing it
    // from the plugin description string, but it doesn't seem that
    // version information is available in any standardized way at
    // the module level, like in Windows

    if (m_description.isEmpty())
        return;

    if (m_description.startsWith("Shockwave Flash") && m_description.length() >= 19) {
        // The flash version as a PlatformModuleVersion differs on Unix from Windows
        // since the revision can be larger than a 8 bits, so we allow it 16 here and
        // push the major/minor up 8 bits. Thus on Unix, Flash's version may be
        // 0x0a000000 instead of 0x000a0000.

        Vector<String> versionParts;
        m_description.substring(16).split(' ', /*allowEmptyEntries =*/ false, versionParts);
        if (versionParts.isEmpty())
            return;

        if (versionParts.size() >= 1) {
            Vector<String> majorMinorParts;
            versionParts[0].split('.', majorMinorParts);
            if (majorMinorParts.size() >= 1) {
                bool converted = false;
                unsigned major = majorMinorParts[0].toUInt(&converted);
                if (converted)
                    m_moduleVersion = (major & 0xff) << 24;
            }
            if (majorMinorParts.size() == 2) {
                bool converted = false;
                unsigned minor = majorMinorParts[1].toUInt(&converted);
                if (converted)
                    m_moduleVersion |= (minor & 0xff) << 16;
            }
        }

        if (versionParts.size() >= 2) {
            String revision = versionParts[1];
            if (revision.length() > 1 && (revision[0] == 'r' || revision[0] == 'b')) {
                revision.remove(0, 1);
                m_moduleVersion |= revision.toInt() & 0xffff;
            }
        }
    }
}
Example #17
0
/**********************************************************
 * @brief  readData
 * @param  
 * @retval None
**********************************************************/
static int readData()
{ 
char c=0;        
String readString;

  while (c != '\n')
  {
    if (Serial.available() >0)
    {
      c = Serial.read();  //gets one byte from serial buffer
      if ( c != '$')
        readString += c; //makes the string readString
    } 
  }    

  return readString.toInt();
}
Example #18
0
void MqttFlare::initFromProgmem(){

  byte isSet = EEPROM.read(0);

  if (isSet==42){
    int index = 4;
    String current = "";
    int argIndex=0;
    while(index<100){
      char c = EEPROM.read(index);
      if (c=='&'){
        switch(argIndex){
        case 0:
          sprintf(server,"%s",current.c_str());
          break;
        case 1:
          port = current.toInt();
          break;
        case 2:
          sprintf(ssid,"%s",current.c_str());
          break;
        case 3:
          sprintf(code,"%s",current.c_str());
          break;
        }
        current="";
        index+=3;
        argIndex++;
      }
      else{
        current+=c;
        index++;
      }
    }
  }  
  else{
    Serial.println("Saving Default Settings");
    String defaultSettings = "s=150.140.5.11&p=1883&w=ssid&c=default&";
    EEPROM.write(0,42);
    EEPROM.write(1,1);
    for (int i=0;i<defaultSettings.length();i++){
      EEPROM.write(2+i,defaultSettings[i]);
    }
  }
}
Example #19
0
err_t HttpClient::onReceive(pbuf *buf)
{
	if (buf == NULL)
	{
		// Disconnected, close it
		TcpClient::onReceive(buf);
	}
	else
	{
		int startPos = 0;
		if (waitParse)
		{
			String http = NetUtils::pbufStrCopy(buf, 0, 4);
			http.toUpperCase();
			if (http == "HTTP" && code == 0)
			{
				int codeStart = NetUtils::pbufFindChar(buf, ' ', 4);
				int codeEnd = NetUtils::pbufFindChar(buf, ' ', codeStart + 1);
				if (codeStart != -1 && codeEnd != -1 && codeEnd - codeStart < 5)
				{
					String strCode = NetUtils::pbufStrCopy(buf, codeStart, codeEnd);
					code = strCode.toInt();
				}
				else
					code = 0;
			}
			int headerEnd = NetUtils::pbufFindStr(buf, "\r\n\r\n");
			if (headerEnd != -1)
			{
				debugf("Header pos: %d", headerEnd);
				startPos = headerEnd + 4;
				waitParse = false;
				if (headerEnd < NETWORK_MAX_HTTP_PARSING_LEN)
					parseHeaders(buf, headerEnd);
			}
		}

		if (!waitParse) writeRawData(buf, startPos);

		// Fire ReadyToSend callback
		TcpClient::onReceive(buf);
	}

	return ERR_OK;
}
Example #20
0
void WindowFeatures::setWindowFeature(const String& keyString,
                                      const String& valueString) {
    int value;

    // Listing a key with no value is shorthand for key=yes
    if (valueString.isEmpty() || valueString == "yes")
        value = 1;
    else
        value = valueString.toInt();

    // We treat keyString of "resizable" here as an additional feature rather than
    // setting resizeable to true.  This is consistent with Firefox, but could
    // also be handled at another level.

    if (keyString == "left" || keyString == "screenx") {
        xSet = true;
        x = value;
    } else if (keyString == "top" || keyString == "screeny") {
        ySet = true;
        y = value;
    } else if (keyString == "width" || keyString == "innerwidth") {
        widthSet = true;
        width = value;
    } else if (keyString == "height" || keyString == "innerheight") {
        heightSet = true;
        height = value;
    } else if (keyString == "menubar") {
        menuBarVisible = value;
    } else if (keyString == "toolbar") {
        toolBarVisible = value;
    } else if (keyString == "location") {
        locationBarVisible = value;
    } else if (keyString == "status") {
        statusBarVisible = value;
    } else if (keyString == "fullscreen") {
        fullscreen = value;
    } else if (keyString == "scrollbars") {
        scrollbarsVisible = value;
    } else if (keyString == "noopener") {
        noopener = true;
    } else if (value == 1) {
        additionalFeatures.append(keyString);
    }
}
Example #21
0
//this function automagically gets called upon a matching POST request
int updateServo(String command)
{
  // convert string to integer
  uint8_t pos = command.toInt();

  // process if integer is 0 - 180
  if(pos <= 180)
  {
    // tell servo to go to position in variable 'pos'
    myservo.write(pos);

    // return an integer success code that can be processed by our app
    return 200;
  }
  else {
    // return an integer error code that can be processed by our app
    return -1;
  }
}
Example #22
0
void ParseRGBBLEND(String input, PIXEL_HELPER_CLASS* p_helper) {
  p_helper->LEDMode = RGBMode_BLEND;
  
  input.remove(0, 9);
  BlendModeSettings.RGB1 = p_helper->RGBStringToRGB(input.substring(0, input.indexOf(',')));

  input.remove(0, input.indexOf(',') + 1);
  BlendModeSettings.RGB2 = p_helper->RGBStringToRGB(input.substring(0, input.indexOf(',')));

  input.remove(0, input.indexOf(',') + 1);
  BlendModeSettings.Cycles = input.substring(0, input.indexOf(',')).toInt();

  input.remove(0, input.indexOf(',') + 1);
  BlendModeSettings.Interval = input.toInt();

  BlendModeSettings.CycleNumber = 0;
  BlendModeSettings.Progress = 0;
  BlendModeSettings.Direction = 1;
  p_helper->previousMillis = millis() - BlendModeSettings.Interval;

}
int* splitcommand(String command, char flag, int length){
	int i;
	String parameter;
	int parameters[5];
	int commaPosition;
	for (i = 0; i < length - 1; i++)
	{
		commaPosition = command.indexOf(flag);
		if (commaPosition == -1){
			parameters[i] = -1;
			break;
		}

		parameter = command.substring(0, commaPosition);
		command = command.substring(commaPosition + 1, command.length());
		parameters[i] = parameter.toInt();
	}
	parameters[length - 1] = command.toInt();

	return parameters;
}
Example #24
0
int MyEeprom::GetIoTMSPortNumberFromEeprom(void)
{
	String portnumber;
	char ch;
	int i;

	for(i = EEP_IOTMS_PORT_START_ADDR ; i < (EEP_IOTMS_PORT_START_ADDR + EEP_PORTNUM_SIZE) ; i++)
	{
		ch = EEPROM[i];
		if(ch == '\0')
		{
			break;
		}
		else
		{
			portnumber += ch;
		}

		Serial.println(portnumber);
	}
	
	Serial.println(portnumber);
	return (int)(portnumber.toInt());
}
Example #25
0
// The cookie String passed into this method will only contian the name value pairs as well as other related cookie
// attributes such as max-age and domain. Set-Cookie should never be part of this string.
ParsedCookie* CookieParser::parseOneCookie(const String& cookie, unsigned start, unsigned end, double curTime)
{
    ParsedCookie* res = new ParsedCookie(curTime);

    if (!res)
        LOG_AND_DELETE("Out of memory");

    res->setProtocol(m_defaultCookieURL.protocol());

    // Parse [NAME "="] VALUE
    unsigned tokenEnd = start; // Token end contains the position of the '=' or the end of a token
    unsigned pairEnd = start; // Pair end contains always the position of the ';'

    // find the *first* ';' and the '=' (if they exist)
    bool quoteFound = false;
    bool foundEqual = false;
    while (pairEnd < end && (cookie[pairEnd] != ';' || quoteFound)) {
        if (tokenEnd == start && cookie[pairEnd] == '=') {
            tokenEnd = pairEnd;
            foundEqual = true;
        }
        if (cookie[pairEnd] == '"')
            quoteFound = !quoteFound;
        pairEnd++;
    }

    unsigned tokenStart = start;

    bool hasName = false; // This is a hack to avoid changing too much in this
                          // brutally brittle code.
    if (tokenEnd != start) {
        // There is a '=' so parse the NAME
        unsigned nameEnd = tokenEnd;

        // The tokenEnd is the position of the '=' so the nameEnd is one less
        nameEnd--;

        // Remove lightweight spaces.
        while (nameEnd && isLightweightSpace(cookie[nameEnd]))
            nameEnd--;

        while (tokenStart < nameEnd && isLightweightSpace(cookie[tokenStart]))
            tokenStart++;

        if (nameEnd + 1 <= tokenStart)
            LOG_AND_DELETE("Empty name. Rejecting the cookie");

        String name = cookie.substring(tokenStart, nameEnd + 1 - start);
        res->setName(name);
        hasName = true;
    }

    // Now parse the VALUE
    tokenStart = tokenEnd + 1;
    if (!hasName)
        --tokenStart;

    // Skip lightweight spaces in our token
    while (tokenStart < pairEnd && isLightweightSpace(cookie[tokenStart]))
        tokenStart++;

    tokenEnd = pairEnd;
    while (tokenEnd > tokenStart && isLightweightSpace(cookie[tokenEnd - 1]))
        tokenEnd--;

    String value;
    if (tokenEnd == tokenStart) {
        // Firefox accepts empty value so we will do the same
        value = String();
    } else
        value = cookie.substring(tokenStart, tokenEnd - tokenStart);

    if (hasName)
        res->setValue(value);
    else if (foundEqual) {
        delete res;
        return 0;
    } else
        res->setName(value); // No NAME=VALUE, only NAME

    while (pairEnd < end) {
        // Switch to the next pair as pairEnd is on the ';' and fast-forward any lightweight spaces.
        pairEnd++;
        while (pairEnd < end && isLightweightSpace(cookie[pairEnd]))
            pairEnd++;

        tokenStart = pairEnd;
        tokenEnd = tokenStart; // initialize token end to catch first '='

        while (pairEnd < end && cookie[pairEnd] != ';') {
            if (tokenEnd == tokenStart && cookie[pairEnd] == '=')
                tokenEnd = pairEnd;
            pairEnd++;
        }

        // FIXME : should we skip lightweight spaces here ?

        unsigned length = tokenEnd - tokenStart;
        unsigned tokenStartSvg = tokenStart;

        String parsedValue;
        if (tokenStart != tokenEnd) {
            // There is an equal sign so remove lightweight spaces in VALUE
            tokenStart = tokenEnd + 1;
            while (tokenStart < pairEnd && isLightweightSpace(cookie[tokenStart]))
                tokenStart++;

            tokenEnd = pairEnd;
            while (tokenEnd > tokenStart && isLightweightSpace(cookie[tokenEnd - 1]))
                tokenEnd--;

            parsedValue = cookie.substring(tokenStart, tokenEnd - tokenStart);
        } else {
            // If the parsedValue is empty, initialise it in case we need it
            parsedValue = String();
            // Handle a token without value.
            length = pairEnd - tokenStart;
        }

       // Detect which "cookie-av" is parsed
       // Look at the first char then parse the whole for performance issue
        switch (cookie[tokenStartSvg]) {
        case 'P':
        case 'p' : {
            if (length >= 4 && cookie.find("ath", tokenStartSvg + 1, false)) {
                // We need the path to be decoded to match those returned from KURL::path().
                // The path attribute may or may not include percent-encoded characters. Fortunately
                // if there are no percent-encoded characters, decoding the url is a no-op.
                res->setPath(decodeURLEscapeSequences(parsedValue));
            } else
                LOG_AND_DELETE("Invalid cookie %s (path)", cookie.ascii().data());
            break;
        }

        case 'D':
        case 'd' : {
            if (length >= 6 && cookie.find("omain", tokenStartSvg + 1, false)) {
                if (parsedValue.length() > 1 && parsedValue[0] == '"' && parsedValue[parsedValue.length() - 1] == '"')
                    parsedValue = parsedValue.substring(1, parsedValue.length() - 2);
                // If the domain does not start with a dot, add one for security checks,
                // For example: ab.c.com dose not domain match b.c.com;
                String realDomain = parsedValue[0] == '.' ? parsedValue : "." + parsedValue;
                res->setDomain(realDomain);
            } else
                LOG_AND_DELETE("Invalid cookie %s (domain)", cookie.ascii().data());
            break;
        }

        case 'E' :
        case 'e' : {
            if (length >= 7 && cookie.find("xpires", tokenStartSvg + 1, false))
                res->setExpiry(parsedValue);
            else
                LOG_AND_DELETE("Invalid cookie %s (expires)", cookie.ascii().data());
            break;
        }

        case 'M' :
        case 'm' : {
            if (length >= 7 && cookie.find("ax-age", tokenStartSvg + 1, false))
                res->setMaxAge(parsedValue);
            else
                LOG_AND_DELETE("Invalid cookie %s (max-age)", cookie.ascii().data());
            break;
        }

        case 'C' :
        case 'c' : {
            if (length >= 7 && cookie.find("omment", tokenStartSvg + 1, false))
                // We do not have room for the comment part (and so do Mozilla) so just log the comment.
                LOG(Network, "Comment %s for ParsedCookie : %s\n", parsedValue.ascii().data(), cookie.ascii().data());
            else
                LOG_AND_DELETE("Invalid cookie %s (comment)", cookie.ascii().data());
            break;
        }

        case 'V' :
        case 'v' : {
            if (length >= 7 && cookie.find("ersion", tokenStartSvg + 1, false)) {
                // Although the out-of-dated Cookie Spec(RFC2965, http://tools.ietf.org/html/rfc2965) defined
                // the value of version can only contain DIGIT, some random sites, e.g. https://devforums.apple.com
                // would use double quotation marks to quote the digit. So we need to get rid of them for compliance.
                if (parsedValue.length() > 1 && parsedValue[0] == '"' && parsedValue[parsedValue.length() - 1] == '"')
                    parsedValue = parsedValue.substring(1, parsedValue.length() - 2);

                if (parsedValue.toInt() != 1)
                    LOG_AND_DELETE("ParsedCookie version %d not supported (only support version=1)", parsedValue.toInt());
            } else
                LOG_AND_DELETE("Invalid cookie %s (version)", cookie.ascii().data());
            break;
        }

        case 'S' :
        case 's' : {
            // Secure is a standalone token ("Secure;")
            if (length >= 6 && cookie.find("ecure", tokenStartSvg + 1, false))
                res->setSecureFlag(true);
            else
                LOG_AND_DELETE("Invalid cookie %s (secure)", cookie.ascii().data());
            break;
        }
        case 'H':
        case 'h': {
            // HttpOnly is a standalone token ("HttpOnly;")
            if (length >= 8 && cookie.find("ttpOnly", tokenStartSvg + 1, false))
                res->setIsHttpOnly(true);
            else
                LOG_AND_DELETE("Invalid cookie %s (HttpOnly)", cookie.ascii().data());
            break;
        }

        default : {
            // If length == 0, we should be at the end of the cookie (case : ";\r") so ignore it
            if (length)
                LOG_ERROR("Invalid token for cookie %s", cookie.ascii().data());
        }
        }
    }

    // Check if the cookie is valid with respect to the size limit.
    if (!res->isUnderSizeLimit())
        LOG_AND_DELETE("ParsedCookie %s is above the 4kb in length : REJECTED", cookie.ascii().data());

    // If some pair was not provided, during parsing then apply some default value
    // the rest has been done in the constructor.

    // If no domain was provided, set it to the host
    if (!res->domain())
        res->setDefaultDomain(m_defaultCookieURL);

    // According to the Cookie Specificaiton (RFC6265, section 4.1.2.4 and 5.2.4, http://tools.ietf.org/html/rfc6265),
    // If no path was provided or the first character of the path value is not '/', set it to the host's path
    //
    // REFERENCE
    // 4.1.2.4. The Path Attribute
    //
    // The scope of each cookie is limited to a set of paths, controlled by
    // the Path attribute. If the server omits the Path attribute, the user
    // agent will use the "directory" of the request-uri's path component as
    // the default value. (See Section 5.1.4 for more details.)
    // ...........
    // 5.2.4. The Path Attribute
    //
    // If the attribute-name case-insensitively matches the string "Path",
    // the user agent MUST process the cookie-av as follows.
    //
    // If the attribute-value is empty or if the first character of the
    // attribute-value is not %x2F ("/"):
    //
    // Let cookie-path be the default-path.
    //
    // Otherwise:
    //
    // Let cookie-path be the attribute-value.
    //
    // Append an attribute to the cookie-attribute-list with an attribute-
    // name of Path and an attribute-value of cookie-path.
    if (!res->path() || !res->path().length() || !res->path().startsWith("/", false)) {
        String path = m_defaultCookieURL.string().substring(m_defaultCookieURL.pathStart(), m_defaultCookieURL.pathAfterLastSlash() - m_defaultCookieURL.pathStart() - 1);
        if (path.isEmpty())
            path = "/";
        // Since this is reading the raw url string, it could contain percent-encoded sequences. We
        // want it to be comparable to the return value of url.path(), which is not percent-encoded,
        // so we must remove the escape sequences.
        res->setPath(decodeURLEscapeSequences(path));
    }
 
    return res;
}
Example #26
0
void Settings::setMetadataSettings(const String& key, const String& value)
{
    if (key == "width") {
        if (value == "device-width") {
            m_viewport_width = 0;
        } else {
            int width = value.toInt();
            if (width <= 10000) {
                if (width <= 320) {
                    // This is a hack to accommodate the pages designed for the
                    // original iPhone. The new version, since 10/2007, is to
                    // use device-width which works for both portrait and
                    // landscape modes.
                    m_viewport_width = 0;
                } else {
                    m_viewport_width = width;
                }
            }
        }
    } else if (key == "height") {
        if (value == "device-height") {
            m_viewport_height = 0;
        } else {
            int height = value.toInt();
            if (height >= 200 && height <= 10000) {
                m_viewport_height = height;
            }
        }
    } else if (key == "initial-scale") {
        int scale = int(value.toFloat() * 100);
        if (scale >= 1 && scale <= 1000) {
            m_viewport_initial_scale = scale;
        }
    } else if (key == "minimum-scale") {
        int scale = int(value.toFloat() * 100);
        if (scale >= 1 && scale <= 1000) {
            m_viewport_minimum_scale = scale;
        }
    } else if (key == "maximum-scale") {
        int scale = int(value.toFloat() * 100);
        if (scale >= 1 && scale <= 1000) {
            m_viewport_maximum_scale = scale;
        }
    } else if (key == "user-scalable") {
        // even Apple doc says using "no", "0" is common in the real world, and
        // some sites, e.g. gomoviesapp.com, use "false".
        if (value == "no" || value == "0" || value == "false") {
            m_viewport_user_scalable = false;
        }
    } else if (key == "target-densitydpi") {
        if (value == "device-dpi") {
            m_viewport_target_densitydpi = 0;
        } else if (value == "low-dpi") {
            m_viewport_target_densitydpi = 120;
        } else if (value == "medium-dpi") {
            m_viewport_target_densitydpi = 160;
        } else if (value == "high-dpi") {
            m_viewport_target_densitydpi = 240;
        } else {
            int dpi = value.toInt();
            if (dpi >= 70 && dpi <= 400) {
                m_viewport_target_densitydpi = dpi;
            }
        }
    } else if (key == "telephone") {
        if (value == "no") {
            m_format_detection_telephone = false;
        }
    } else if (key == "address") {
        if (value == "no") {
            m_format_detection_address = false;
        }
    } else if (key == "email") {
        if (value == "no") {
            m_format_detection_email = false;
        }
    } else if (key == "format-detection") {
        // even Apple doc says "format-detection" should be the name of the
        // <meta> tag. In the real world, e.g. amazon.com, use
        // "format-detection=no" in the "viewport" <meta> tag to disable all
        // format detection.
        if (value == "no") {
            m_format_detection_telephone = false;
            m_format_detection_address = false;
            m_format_detection_email = false;
        }
    }
}
Example #27
0
void loop()
{
  // If there is incoming value
  if(Serial.available() > 0)
  {
    // read the value
    char ch = Serial.read();
  
    /*
    *  If ch isn't a newline
    *  (linefeed) character,
    *  we will add the character
    *  to the incomingString
    */
    if (ch != 10){
      // Print out the value received
      // so that we can see what is
      // happening
      Serial.print("I have received: ");
      Serial.print(ch, DEC);
      Serial.print('\n');
    
      // Add the character to
      // the incomingString
      incomingString += ch;
    }
    // received a newline (linefeed) character
    // this means we are done making a string
    else
    {
      // print the incoming string
      Serial.println("I am printing the entire string");
      Serial.println(incomingString);
    
      // Convert the string to an integer
      int val = incomingString.toInt();
    
      // print the integer
      Serial.println("Printing the value: ");
      Serial.println(val);
    
      /*
      *  We only want to write an integer between
      *  0 and 180 to the motor. 
      */
      if (val > -1 && val < 181)
     {
       // Print confirmation that the
       // value is between 0 and 180
       Serial.println("Value is between 0 and 180");
       // Write to Servo
       myMotor.write(val);
     }
     // The value is not between 0 and 180.
     // We do not want write this value to0
     // the motor.
     else
     {
       Serial.println("Value is NOT between 0 and 180");
      
       // IT'S a TRAP!
       Serial.println("Error with the input");
     }
    
      // Reset the value of the incomingString
      incomingString = "";
    }
  }
}
Example #28
0
void TextTrackCue::parseSettings(const String& input)
{
    unsigned position = 0;

    while (position < input.length()) {

        // The WebVTT cue settings part of a WebVTT cue consists of zero or more of the following components, in any order, 
        // separated from each other by one or more U+0020 SPACE characters or U+0009 CHARACTER TABULATION (tab) characters. 
        while (position < input.length() && WebVTTParser::isValidSettingDelimiter(input[position]))
            position++;
        if (position >= input.length())
            break;

        // When the user agent is to parse the WebVTT settings given by a string input for a text track cue cue, 
        // the user agent must run the following steps:
        // 1. Let settings be the result of splitting input on spaces.
        // 2. For each token setting in the list settings, run the following substeps:
        //    1. If setting does not contain a U+003A COLON character (:), or if the first U+003A COLON character (:) 
        //       in setting is either the first or last character of setting, then jump to the step labeled next setting.
        unsigned endOfSetting = position;
        String setting = WebVTTParser::collectWord(input, &endOfSetting);
        CueSetting name;
        size_t colonOffset = setting.find(':', 1);
        if (colonOffset == notFound || colonOffset == 0 || colonOffset == setting.length() - 1)
            goto NextSetting;

        // 2. Let name be the leading substring of setting up to and excluding the first U+003A COLON character (:) in that string.
        name = settingName(setting.substring(0, colonOffset));

        // 3. Let value be the trailing substring of setting starting from the character immediately after the first U+003A COLON character (:) in that string.
        position += colonOffset + 1;
        if (position >= input.length())
            break;

        // 4. Run the appropriate substeps that apply for the value of name, as follows:
        switch (name) {
        case Vertical:
            {
            // If name is a case-sensitive match for "vertical"
            // 1. If value is a case-sensitive match for the string "rl", then let cue's text track cue writing direction 
            //    be vertical growing left.
            String writingDirection = WebVTTParser::collectWord(input, &position);
            if (writingDirection == verticalGrowingLeftKeyword())
                m_writingDirection = VerticalGrowingLeft;
            
            // 2. Otherwise, if value is a case-sensitive match for the string "lr", then let cue's text track cue writing 
            //    direction be vertical growing right.
            else if (writingDirection == verticalGrowingRightKeyword())
                m_writingDirection = VerticalGrowingRight;
            }
            break;
        case Line:
            {
            // 1-2 - Collect chars that are either '-', '%', or a digit.
            // 1. If value contains any characters other than U+002D HYPHEN-MINUS characters (-), U+0025 PERCENT SIGN 
            //    characters (%), and characters in the range U+0030 DIGIT ZERO (0) to U+0039 DIGIT NINE (9), then jump
            //    to the step labeled next setting.
            StringBuilder linePositionBuilder;
            while (position < input.length() && (input[position] == '-' || input[position] == '%' || isASCIIDigit(input[position])))
                linePositionBuilder.append(input[position++]);
            if (position < input.length() && !WebVTTParser::isValidSettingDelimiter(input[position]))
                break;

            // 2. If value does not contain at least one character in the range U+0030 DIGIT ZERO (0) to U+0039 DIGIT 
            //    NINE (9), then jump to the step labeled next setting.
            // 3. If any character in value other than the first character is a U+002D HYPHEN-MINUS character (-), then 
            //    jump to the step labeled next setting.
            // 4. If any character in value other than the last character is a U+0025 PERCENT SIGN character (%), then
            //    jump to the step labeled next setting.
            String linePosition = linePositionBuilder.toString();
            if (linePosition.find('-', 1) != notFound || linePosition.reverseFind("%", linePosition.length() - 2) != notFound)
                break;

            // 5. If the first character in value is a U+002D HYPHEN-MINUS character (-) and the last character in value is a 
            //    U+0025 PERCENT SIGN character (%), then jump to the step labeled next setting.
            if (linePosition[0] == '-' && linePosition[linePosition.length() - 1] == '%')
                break;

            // 6. Ignoring the trailing percent sign, if any, interpret value as a (potentially signed) integer, and 
            //    let number be that number. 
            // NOTE: toInt ignores trailing non-digit characters, such as '%'.
            bool validNumber;
            int number = linePosition.toInt(&validNumber);
            if (!validNumber)
                break;

            // 7. If the last character in value is a U+0025 PERCENT SIGN character (%), but number is not in the range 
            //    0 ≤ number ≤ 100, then jump to the step labeled next setting.
            // 8. Let cue's text track cue line position be number.
            // 9. If the last character in value is a U+0025 PERCENT SIGN character (%), then let cue's text track cue 
            //    snap-to-lines flag be false. Otherwise, let it be true.
            if (linePosition[linePosition.length() - 1] == '%') {
                if (number < 0 || number > 100)
                    break;

                // 10 - If '%' then set snap-to-lines flag to false.
                m_snapToLines = false;
            }

            m_linePosition = number;
            }
            break;
        case Position:
            {
            // 1. If value contains any characters other than U+0025 PERCENT SIGN characters (%) and characters in the range 
            //    U+0030 DIGIT ZERO (0) to U+0039 DIGIT NINE (9), then jump to the step labeled next setting.
            // 2. If value does not contain at least one character in the range U+0030 DIGIT ZERO (0) to U+0039 DIGIT NINE (9),
            //    then jump to the step labeled next setting.
            String textPosition = WebVTTParser::collectDigits(input, &position);
            if (textPosition.isEmpty())
                break;
            if (position >= input.length())
                break;

            // 3. If any character in value other than the last character is a U+0025 PERCENT SIGN character (%), then jump
            //    to the step labeled next setting.
            // 4. If the last character in value is not a U+0025 PERCENT SIGN character (%), then jump to the step labeled
            //    next setting.
            if (input[position++] != '%')
                break;
            if (position < input.length() && !WebVTTParser::isValidSettingDelimiter(input[position]))
                break;

            // 5. Ignoring the trailing percent sign, interpret value as an integer, and let number be that number.
            // 6. If number is not in the range 0 ≤ number ≤ 100, then jump to the step labeled next setting.
            // NOTE: toInt ignores trailing non-digit characters, such as '%'.
            bool validNumber;
            int number = textPosition.toInt(&validNumber);
            if (!validNumber)
                break;
            if (number < 0 || number > 100)
              break;

            // 7. Let cue's text track cue text position be number.
            m_textPosition = number;
            }
            break;
        case Size:
            {
            // 1. If value contains any characters other than U+0025 PERCENT SIGN characters (%) and characters in the
            //    range U+0030 DIGIT ZERO (0) to U+0039 DIGIT NINE (9), then jump to the step labeled next setting.
            // 2. If value does not contain at least one character in the range U+0030 DIGIT ZERO (0) to U+0039 DIGIT 
            //    NINE (9), then jump to the step labeled next setting.
            String cueSize = WebVTTParser::collectDigits(input, &position);
            if (cueSize.isEmpty())
                break;
            if (position >= input.length())
                break;

            // 3. If any character in value other than the last character is a U+0025 PERCENT SIGN character (%),
            //    then jump to the step labeled next setting.
            // 4. If the last character in value is not a U+0025 PERCENT SIGN character (%), then jump to the step
            //    labeled next setting.
            if (input[position++] != '%')
                break;
            if (position < input.length() && !WebVTTParser::isValidSettingDelimiter(input[position]))
                break;

            // 5. Ignoring the trailing percent sign, interpret value as an integer, and let number be that number.
            // 6. If number is not in the range 0 ≤ number ≤ 100, then jump to the step labeled next setting.
            bool validNumber;
            int number = cueSize.toInt(&validNumber);
            if (!validNumber)
                break;
            if (number < 0 || number > 100)
                break;

            // 7. Let cue's text track cue size be number.
            m_cueSize = number;
            }
            break;
        case Align:
            {
            String cueAlignment = WebVTTParser::collectWord(input, &position);

            // 1. If value is a case-sensitive match for the string "start", then let cue's text track cue alignment be start alignment.
            if (cueAlignment == startKeyword())
                m_cueAlignment = Start;

            // 2. If value is a case-sensitive match for the string "middle", then let cue's text track cue alignment be middle alignment.
            else if (cueAlignment == middleKeyword())
                m_cueAlignment = Middle;

            // 3. If value is a case-sensitive match for the string "end", then let cue's text track cue alignment be end alignment.
            else if (cueAlignment == endKeyword())
                m_cueAlignment = End;
            }
            break;
        case None:
            break;
        }

NextSetting:
        position = endOfSetting;
    }
}
/**
 * handle the WebSocket header reading
 * @param client WSclient_t *  ptr to the client struct
 */
void WebSocketsClient::handleHeader(WSclient_t * client, String * headerLine) {

    headerLine->trim(); // remove \r

    if(headerLine->length() > 0) {
        DEBUG_WEBSOCKETS("[WS-Client][handleHeader] RX: %s\n", headerLine->c_str());

        if(headerLine->startsWith("HTTP/1.")) {
            // "HTTP/1.1 101 Switching Protocols"
            client->cCode = headerLine->substring(9, headerLine->indexOf(' ', 9)).toInt();
        } else if(headerLine->indexOf(':')) {
            String headerName = headerLine->substring(0, headerLine->indexOf(':'));
            String headerValue = headerLine->substring(headerLine->indexOf(':') + 2);

            if(headerName.equalsIgnoreCase("Connection")) {
                if(headerValue.equalsIgnoreCase("upgrade")) {
                    client->cIsUpgrade = true;
                }
            } else if(headerName.equalsIgnoreCase("Upgrade")) {
                if(headerValue.equalsIgnoreCase("websocket")) {
                    client->cIsWebsocket = true;
                }
            } else if(headerName.equalsIgnoreCase("Sec-WebSocket-Accept")) {
                client->cAccept = headerValue;
                client->cAccept.trim(); // see rfc6455
            } else if(headerName.equalsIgnoreCase("Sec-WebSocket-Protocol")) {
                client->cProtocol = headerValue;
            } else if(headerName.equalsIgnoreCase("Sec-WebSocket-Extensions")) {
                client->cExtensions = headerValue;
            } else if(headerName.equalsIgnoreCase("Sec-WebSocket-Version")) {
                client->cVersion = headerValue.toInt();
            }
        } else {
            DEBUG_WEBSOCKETS("[WS-Client][handleHeader] Header error (%s)\n", headerLine->c_str());
        }

        (*headerLine) = "";
#if (WEBSOCKETS_NETWORK_TYPE == NETWORK_ESP8266_ASYNC)
        client->tcp->readStringUntil('\n', &(client->cHttpLine), std::bind(&WebSocketsClient::handleHeader, this, client, &(client->cHttpLine)));
#endif

    } else {
        DEBUG_WEBSOCKETS("[WS-Client][handleHeader] Header read fin.\n");
        DEBUG_WEBSOCKETS("[WS-Client][handleHeader] Client settings:\n");

        DEBUG_WEBSOCKETS("[WS-Client][handleHeader]  - cURL: %s\n", client->cUrl.c_str());
        DEBUG_WEBSOCKETS("[WS-Client][handleHeader]  - cKey: %s\n", client->cKey.c_str());

        DEBUG_WEBSOCKETS("[WS-Client][handleHeader] Server header:\n");
        DEBUG_WEBSOCKETS("[WS-Client][handleHeader]  - cCode: %d\n", client->cCode);
        DEBUG_WEBSOCKETS("[WS-Client][handleHeader]  - cIsUpgrade: %d\n", client->cIsUpgrade);
        DEBUG_WEBSOCKETS("[WS-Client][handleHeader]  - cIsWebsocket: %d\n", client->cIsWebsocket);
        DEBUG_WEBSOCKETS("[WS-Client][handleHeader]  - cAccept: %s\n", client->cAccept.c_str());
        DEBUG_WEBSOCKETS("[WS-Client][handleHeader]  - cProtocol: %s\n", client->cProtocol.c_str());
        DEBUG_WEBSOCKETS("[WS-Client][handleHeader]  - cExtensions: %s\n", client->cExtensions.c_str());
        DEBUG_WEBSOCKETS("[WS-Client][handleHeader]  - cVersion: %d\n", client->cVersion);

        bool ok = (client->cIsUpgrade && client->cIsWebsocket);

        if(ok) {
            switch(client->cCode) {
                case 101:  ///< Switching Protocols

                    break;
                case 403: ///< Forbidden
                    // todo handle login
                default:   ///< Server dont unterstand requrst
                    ok = false;
                    DEBUG_WEBSOCKETS("[WS-Client][handleHeader] serverCode is not 101 (%d)\n", client->cCode);
                    clientDisconnect(client);
                    break;
            }
        }

        if(ok) {

            if(client->cAccept.length() == 0) {
                ok = false;
            } else {
                // generate Sec-WebSocket-Accept key for check
                String sKey = acceptKey(client->cKey);
                if(sKey != client->cAccept) {
                    DEBUG_WEBSOCKETS("[WS-Client][handleHeader] Sec-WebSocket-Accept is wrong\n");
                    ok = false;
                }
            }
        }

        if(ok) {

            DEBUG_WEBSOCKETS("[WS-Client][handleHeader] Websocket connection init done.\n");
            headerDone(client);


            runCbEvent(WStype_CONNECTED, (uint8_t *) client->cUrl.c_str(), client->cUrl.length());

        } else {
            DEBUG_WEBSOCKETS("[WS-Client][handleHeader] no Websocket connection close.\n");
            client->tcp->write("This is a webSocket client!");
            clientDisconnect(client);
        }
    }
}
Example #30
0
bool WebServerTask::parse(String key, String value) {

    DSKey newKey;

    if (key.equals("tz")) {
        newKey = DS_TIMEZONE;
    } else if (key.equals("brightness")) {
        newKey = DS_BRIGHTNESS;
    } else if (key.equals("hour_color")) {
        newKey = DS_HOUR_COLOR;
    } else if (key.equals("minute_color")) {
        newKey = DS_MINUTE_COLOR;
    } else if (key.equals("second_color")) {
        newKey = DS_SECOND_COLOR;
    } else if (key.equals("animation")) {
        newKey = DS_CLOCK_ANIMATION;
    } else if (key.equals("night_mode_enable")) {
        newKey = DS_NIGHT_MODE_ENABLE;
    } else if (key.equals("night_mode_brightness")) {
        newKey = DS_NIGHT_MODE_BRIGHTNESS;
    } else if (key.equals("gamma")) {
        newKey = DS_GAMMA;
    } else {
        return false;
    }

    int newVal;
    float f;

    switch(newKey) {

        case DS_TIMEZONE:
        case DS_BRIGHTNESS:
        case DS_CLOCK_ANIMATION:
        case DS_NIGHT_MODE_ENABLE:
        case DS_NIGHT_MODE_BRIGHTNESS:
            newVal = value.toInt();
            break;

        case DS_HOUR_COLOR:
        case DS_MINUTE_COLOR:
        case DS_SECOND_COLOR:
            // Convert the hex string to an int. Offset to remove the preceding # symbol.
            newVal = (int)strtol(&value[1], NULL, 16);
            break;

        case DS_GAMMA:
            // Force the 32-bit float into an int type for storage
            f = value.toFloat();
            newVal = *reinterpret_cast<int*>(&f);
            break;

        default:
            newVal = -1;
            break;
    }

    Serial.println(key + "," + value + " -> " +
                   String(newKey) + "," + String(newVal));

    return DataStore.set(newKey, newVal);
}