Example #1
0
String TextDecoder::decode(const char* start,
                           size_t length,
                           const TextDecodeOptions& options,
                           ExceptionState& exceptionState) {
    WTF::FlushBehavior flush = options.stream() ? WTF::DoNotFlush : WTF::DataEOF;

    bool sawError = false;
    String s = m_codec->decode(start, length, flush, m_fatal, sawError);

    if (m_fatal && sawError) {
        exceptionState.throwTypeError("The encoded data was not valid.");
        return String();
    }

    if (!m_ignoreBOM && !m_bomSeen && !s.isEmpty()) {
        m_bomSeen = true;
        String name(m_encoding.name());
        if ((name == "UTF-8" || name == "UTF-16LE" || name == "UTF-16BE") &&
                s[0] == 0xFEFF)
            s.remove(0);
    }

    if (flush)
        m_bomSeen = false;

    return s;
}
Example #2
0
TparameterResult ApplicationMQTTClient::dissectParameter(String Parameter){

	TparameterResult par;
	par.count = 0;
    for (int i = 0; i < 11; i++) {
    	par.item[i] = "";
    }

    String str = Parameter;

    int index = -1;
    int i = 0;

    do{
     index = str.indexOf(",");
     if (index != -1){
    	 par.item[i] = str.substring(0, index);
         //Serial.println("Parameter[" + String(i) + "] = " + par.item[i]);
         str.remove(0, index +1);
         i++;
         if (str.indexOf(",") == -1 and str.length() > 0){    //best of the rest
        	 index = -1;
        	 par.item[i] = str;
        	 //Serial.println("Parameter[" + String(i) + "] = " + par.item[i]);
        	 i++;
         }
  	  }else{
  	  }
    } while (index != -1);

    par.count = i;
    return par;

}
Example #3
0
/*
Open connection dialog with TreeItem data to CREATE a brand-new connection.
*/
void ConnectionsDock::_open_connection_dialog(TreeItem &item) {

	String signal = item.get_metadata(0).operator Dictionary()["name"];
	String signalname = signal;
	String midname = selectedNode->get_name();
	for (int i = 0; i < midname.length(); i++) { //TODO: Regex filter may be cleaner.
		CharType c = midname[i];
		if (!((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9') || c == '_')) {
			if (c == ' ') {
				//Replace spaces with underlines.
				c = '_';
			} else {
				//Remove any other characters.
				midname.remove(i);
				i--;
				continue;
			}
		}
		midname[i] = c;
	}

	Node *dst_node = selectedNode->get_owner() ? selectedNode->get_owner() : selectedNode;
	StringName dst_method = "_on_" + midname + "_" + signal;

	Connection c;
	c.source = selectedNode;
	c.signal = StringName(signalname);
	c.target = dst_node;
	c.method = dst_method;

	connect_dialog->init(c);
	connect_dialog->set_title(TTR("Connect Signal: ") + signalname);
	connect_dialog->popup_centered_ratio();
}
Example #4
0
bool cutBefore(String &str, const String& pat)
{
    int pos = str.indexOf(pat);
    if(pos < 0) return false;
    str.remove(0, pos);
    return true;
}
static bool verifyCustomHandlerURL(const String& baseURL, const String& url, ExceptionCode& ec)
{
    // The specification requires that it is a SYNTAX_ERR if the "%s" token is
    // not present.
    static const char token[] = "%s";
    int index = url.find(token);
    if (-1 == index) {
        ec = SYNTAX_ERR;
        return false;
    }

    // It is also a SYNTAX_ERR if the custom handler URL, as created by removing
    // the "%s" token and prepending the base url, does not resolve.
    String newURL = url;
    newURL.remove(index, WTF_ARRAY_LENGTH(token) - 1);

    URL base(ParsedURLString, baseURL);
    URL kurl(base, newURL);

    if (kurl.isEmpty() || !kurl.isValid()) {
        ec = SYNTAX_ERR;
        return false;
    }

    return true;
}
Example #6
0
String TextDecoder::decode(ArrayBufferView* input, const Dictionary& options, ExceptionState& exceptionState)
{
    bool stream = false;
    options.get("stream", stream);

    const char* start = input ? static_cast<const char*>(input->baseAddress()) : 0;
    size_t length = input ? input->byteLength() : 0;

    WTF::FlushBehavior flush = stream ? WTF::DoNotFlush : WTF::DataEOF;

    bool sawError = false;
    String s = m_codec->decode(start, length, flush, m_fatal, sawError);

    if (m_fatal && sawError) {
        exceptionState.throwDOMException(EncodingError, "The encoded data was not valid.");
        return String();
    }

    if (!m_ignoreBOM && !m_bomSeen && !s.isEmpty()) {
        m_bomSeen = true;
        String name(m_encoding.name());
        if ((name == "UTF-8" || name == "UTF-16LE" || name == "UTF-16BE") && s[0] == 0xFEFF)
            s.remove(0);
    }

    if (flush)
        m_bomSeen = false;

    return s;
}
Example #7
0
static void removeMarkupPrefix(String& markup)
{
    // The markup prefix is not harmful, but we remove it from the string anyway, so that
    // we can have consistent results with other ports during the layout tests.
    if (markup.startsWith(gMarkupPrefix))
        markup.remove(0, gMarkupPrefix.length());
}
String sendData(String tcpHeader, String data){
  int x;
  SerialUSB.println("Wi-Fi Sending data...");
  Serial1.setTimeout(5000);
  Serial1.println(tcpHeader);
  Serial1.flush();
  Serial1.println(data);
  Serial1.flush();
  String response = Serial1.readStringUntil(Serial1.available());
  if(response.length() > 2){
    x = findString("OK", response);
                           } 
  else{
    SerialUSB.println("Wi-Fi Sending data Timeout!");
    return "";
      }

  if(x != -1){
    SerialUSB.println("Wi-Fi data sent");
    response.remove(0, findString("alive",response) + 9);
    Serial1.setTimeout(1000);
    return response;
             }
  else{
    SerialUSB.println("Wi-Fi couldn't send the data!");
    Serial1.setTimeout(1000);
    return "";
       }

                                                               }
Example #9
0
bool cutAfter(String &str, const String& pat)
{
    int pos = str.indexOf(pat);
    if(pos < 0) return false;
    pos += pat.size();
    str.remove(pos, str.size() - pos);
    return true;
}
Example #10
0
String HTMLTextAreaElement::defaultValue() const
{
    String value = "";

    // Since there may be comments, ignore nodes other than text nodes.
    for (Node* n = firstChild(); n; n = n->nextSibling()) {
        if (n->isTextNode())
            value += static_cast<Text*>(n)->data();
    }

    UChar firstCharacter = value[0];
    if (firstCharacter == '\r' && value[1] == '\n')
        value.remove(0, 2);
    else if (firstCharacter == '\r' || firstCharacter == '\n')
        value.remove(0, 1);

    return value;
}
Example #11
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;

}
Example #12
0
String StyledMarkupAccumulator::stringValueForRange(const Text& node)
{
    if (m_start.isNull())
        return node.data();

    String str = node.data();
    if (m_start.text() == node)
        str.truncate(m_end.offset());
    if (m_end.text() == node)
        str.remove(0, m_start.offset());
    return str;
}
Example #13
0
String StyledMarkupAccumulator::stringValueForRange(const Node& node, const Range* range)
{
    if (!range)
        return node.nodeValue();

    String nodeValue = node.nodeValue();
    if (&node == &range->endContainer())
        nodeValue.truncate(range->endOffset());
    if (&node == &range->startContainer())
        nodeValue.remove(0, range->startOffset());
    return nodeValue;
}
Example #14
0
String StyledMarkupAccumulator::stringValueForRange(const Node* node, const Range* range)
{
    if (!range)
        return node->nodeValue();

    String str = node->nodeValue();
    if (node == range->endContainer())
        str.truncate(range->endOffset());
    if (node == range->startContainer())
        str.remove(0, range->startOffset());
    return str;
}
Example #15
0
PEGASUS_NAMESPACE_BEGIN

// Clone the path as a C String but discard trailing slash if any:

static CString _clonePath(const String& path)
{
    String clone = path;

    if (clone.size() && clone[clone.size()-1] == '/')
        clone.remove(clone.size()-1);

    return clone.getCString();
}
Example #16
0
String StyledMarkupAccumulator::stringValueForRange(const Node& node, const Range* range)
{
    if (!node.isTextNode())
        return emptyString();
    String text = toText(node).data();
    if (!range)
        return text;
    if (node == range->endContainer())
        text.truncate(range->endOffset());
    if (node == range->startContainer())
        text.remove(0, range->startOffset());
    return text;
}
Example #17
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 #18
0
String LocaleWin::shortTimeFormat()
{
    if (!m_timeFormatWithoutSeconds.isNull())
        return m_timeFormatWithoutSeconds;
    String format = getLocaleInfoString(LOCALE_SSHORTTIME);
    // Vista or older Windows doesn't support LOCALE_SSHORTTIME.
    if (format.isEmpty()) {
        format = getLocaleInfoString(LOCALE_STIMEFORMAT);
        StringBuilder builder;
        builder.append(getLocaleInfoString(LOCALE_STIME));
        builder.append("ss");
        size_t pos = format.reverseFind(builder.toString());
        if (pos != notFound)
            format.remove(pos, builder.length());
    }
    m_timeFormatWithoutSeconds = convertWindowsDateTimeFormat(format);
    return m_timeFormatWithoutSeconds;
}
Example #19
0
void CharacterData::deleteData(unsigned offset, unsigned count, ExceptionCode& ec)
{
    checkCharDataOperation(offset, ec);
    if (ec)
        return;

    unsigned realCount;
    if (offset + count > length())
        realCount = length() - offset;
    else
        realCount = count;

    String newStr = m_data;
    newStr.remove(offset, realCount);

    setDataAndUpdate(newStr.impl(), offset, count, 0);

    document()->textRemoved(this, offset, realCount);
}
Example #20
0
void CharacterData::replaceData(unsigned offset, unsigned count, const String& data, ExceptionCode& ec)
{
    checkCharDataOperation(offset, ec);
    if (ec)
        return;

    unsigned realCount;
    if (offset + count > length())
        realCount = length() - offset;
    else
        realCount = count;

    String newStr = m_data;
    newStr.remove(offset, realCount);
    newStr.insert(data, offset);

    setDataAndUpdate(newStr.impl(), offset, count, data.length());

    // update the markers for spell checking and grammar checking
    document()->textRemoved(this, offset, realCount);
    document()->textInserted(this, offset, data.length());
}
Example #21
0
void SmoothADC::dbgInfo()			// needs SCI initialized in sketch setup
{
	#ifdef DEBUG
	String		dbgInfo = "";
	uint8_t		c;
	
	dbgInfo += "!> ";
	dbgInfo += "Pin A";
	dbgInfo += (getPin() - A0);
	dbgInfo += ",\tRate: ";
	dbgInfo += getPeriod();
	dbgInfo += "ms";
	Serial.println(dbgInfo);
	dbgInfo.remove(0);
	dbgInfo += "!> ";
	dbgInfo += "Tab :\t";
	for (c = 0 ; c < DEF_NB_ACQ ; c++)
	{
		dbgInfo += ADCChannel.ADCTab[c];
		dbgInfo += "\t";
	}
	Serial.println(dbgInfo);
	#endif
}
/**
 * phasing the url for all needed informations
 * @param url String
 * @param httpsFingerprint String
 */
void HTTPClient::begin(String url, String httpsFingerprint) {

    DEBUG_HTTPCLIENT("[HTTP-Client][begin] url: %s\n", url.c_str());

    _httpsFingerprint = httpsFingerprint;
    _returnCode = 0;
    _size = -1;

    _Headers = "";

    String protocol;
    // check for : (http: or https:
    int index = url.indexOf(':');
    //int index2;
    bool hasPort = false;
    if(index >= 0) {
        protocol = url.substring(0, index);
        url.remove(0, (index + 3)); // remove http:// or https://

        index = url.indexOf('/');
        String host = url.substring(0, index);
        url.remove(0, index); // remove host part

        // get Authorization
        index = host.indexOf('@');
        if(index >= 0) {
            // auth info
            String auth = host.substring(0, index);
            host.remove(0, index + 1); // remove auth part including @
            _base64Authorization = base64::encode(auth);
        }

        // get port
        index = host.indexOf(':');
        if(index >= 0) {
            _host = host.substring(0, index); // hostname
            host.remove(0, (index + 1)); // remove hostname + :
            _port = host.toInt(); // get port
            hasPort = true;
        } else {
            _host = host;
        }

        _url = url;

        if(protocol.equalsIgnoreCase("http")) {
            _https = false;
            if(!hasPort) {
                _port = 80;
            }
        } else if(protocol.equalsIgnoreCase("https")) {
            _https = true;
            if(!hasPort) {
                _port = 443;
            }
        } else {
            DEBUG_HTTPCLIENT("[HTTP-Client][begin] protocol: %s unknown?!\n", protocol.c_str());
            return;
        }

    }

    DEBUG_HTTPCLIENT("[HTTP-Client][begin] host: %s port: %d url: %s https: %d httpsFingerprint: %s\n", _host.c_str(), _port, _url.c_str(), _https, _httpsFingerprint.c_str());

}
Example #23
0
/*
 * Reads the entire Godot API to a list
 */
List<ClassAPI> generate_c_api_classes() {

	List<ClassAPI> api;

	List<StringName> classes;
	ClassDB::get_class_list(&classes);

	for (List<StringName>::Element *e = classes.front(); e != NULL; e = e->next()) {
		StringName class_name = e->get();

		ClassAPI class_api;
		class_api.api_type = ClassDB::get_api_type(e->get());
		class_api.class_name = class_name;
		class_api.super_class_name = ClassDB::get_parent_class(class_name);
		{
			String name = class_name;
			if (name.begins_with("_")) {
				name.remove(0);
			}
			class_api.is_singleton = GlobalConfig::get_singleton()->has_singleton(name);
		}
		class_api.is_instanciable = !class_api.is_singleton && ClassDB::can_instance(class_name);

		{
			bool is_reference = false;
			List<StringName> inheriters;
			ClassDB::get_inheriters_from_class("Reference", &inheriters);
			is_reference = inheriters.find(class_name) < 0;
			// @Unclear
			class_api.memory_own = !class_api.is_singleton && is_reference;
		}

		// constants
		{
			List<String> constant;
			ClassDB::get_integer_constant_list(class_name, &constant, true);
			for (List<String>::Element *c = constant.front(); c != NULL; c = c->next()) {
				ConstantAPI constant_api;
				constant_api.constant_name = c->get();
				constant_api.constant_value = ClassDB::get_integer_constant(class_name, c->get());

				class_api.constants.push_back(constant_api);
			}
		}

		// signals
		{
			List<MethodInfo> signals_;
			ClassDB::get_signal_list(class_name, &signals_, true);

			for (int i = 0; i < signals_.size(); i++) {
				SignalAPI signal;

				MethodInfo method_info = signals_[i];
				signal.name = method_info.name;

				for (int j = 0; j < method_info.arguments.size(); j++) {
					PropertyInfo argument = method_info.arguments[j];
					String type;
					String name = argument.name;

					if (argument.name.find(":") != -1) {
						type = argument.name.get_slice(":", 1);
						name = argument.name.get_slice(":", 0);
					} else if (argument.hint == PROPERTY_HINT_RESOURCE_TYPE) {
						type = argument.hint_string;
					} else if (argument.type == Variant::NIL) {
						type = "Variant";
					} else {
						type = Variant::get_type_name(argument.type);
					}

					signal.argument_names.push_back(name);
					signal.argument_types.push_back(type);
				}

				Vector<Variant> default_arguments = method_info.default_arguments;

				int default_start = signal.argument_names.size() - default_arguments.size();

				for (int j = 0; j < default_arguments.size(); j++) {
					signal.default_arguments[default_start + j] = default_arguments[j];
				}

				class_api.signals_.push_back(signal);
			}
		}

		//properties
		{
			List<PropertyInfo> properties;
			ClassDB::get_property_list(class_name, &properties, true);

			for (List<PropertyInfo>::Element *p = properties.front(); p != NULL; p = p->next()) {
				PropertyAPI property_api;

				property_api.name = p->get().name;
				property_api.getter = ClassDB::get_property_getter(class_name, p->get().name);
				property_api.setter = ClassDB::get_property_setter(class_name, p->get().name);

				if (p->get().name.find(":") != -1) {
					property_api.type = p->get().name.get_slice(":", 1);
					property_api.name = p->get().name.get_slice(":", 0);
				} else if (p->get().hint == PROPERTY_HINT_RESOURCE_TYPE) {
					property_api.type = p->get().hint_string;
				} else if (p->get().type == Variant::NIL) {
					property_api.type = "Variant";
				} else {
					property_api.type = Variant::get_type_name(p->get().type);
				}

				if (!property_api.setter.empty() || !property_api.getter.empty()) {
					class_api.properties.push_back(property_api);
				}
			}
		}

		//methods
		{
			List<MethodInfo> methods;
			ClassDB::get_method_list(class_name, &methods, true);

			for (List<MethodInfo>::Element *m = methods.front(); m != NULL; m = m->next()) {
				MethodAPI method_api;
				MethodBind *method_bind = ClassDB::get_method(class_name, m->get().name);
				MethodInfo &method_info = m->get();

				//method name
				method_api.method_name = m->get().name;
				//method return type
				if (method_bind && method_bind->get_return_type() != StringName()) {
					method_api.return_type = method_bind->get_return_type();
				} else if (method_api.method_name.find(":") != -1) {
					method_api.return_type = method_api.method_name.get_slice(":", 1);
					method_api.method_name = method_api.method_name.get_slice(":", 0);
				} else if (m->get().return_val.type != Variant::NIL) {
					method_api.return_type = m->get().return_val.hint == PROPERTY_HINT_RESOURCE_TYPE ? m->get().return_val.hint_string : Variant::get_type_name(m->get().return_val.type);
				} else {
					method_api.return_type = "void";
				}

				method_api.argument_count = method_info.arguments.size();
				method_api.has_varargs = method_bind && method_bind->is_vararg();

				// Method flags
				if (method_bind && method_bind->get_hint_flags()) {
					const uint32_t flags = method_bind->get_hint_flags();
					method_api.is_editor = flags & METHOD_FLAG_EDITOR;
					method_api.is_noscript = flags & METHOD_FLAG_NOSCRIPT;
					method_api.is_const = flags & METHOD_FLAG_CONST;
					method_api.is_reverse = flags & METHOD_FLAG_REVERSE;
					method_api.is_virtual = flags & METHOD_FLAG_VIRTUAL;
					method_api.is_from_script = flags & METHOD_FLAG_FROM_SCRIPT;
				}

				// method argument name and type

				for (int i = 0; i < method_api.argument_count; i++) {
					String arg_name;
					String arg_type;
					PropertyInfo arg_info = method_info.arguments[i];

					arg_name = arg_info.name;

					if (arg_info.name.find(":") != -1) {
						arg_type = arg_info.name.get_slice(":", 1);
						arg_name = arg_info.name.get_slice(":", 0);
					} else if (arg_info.hint == PROPERTY_HINT_RESOURCE_TYPE) {
						arg_type = arg_info.hint_string;
					} else if (arg_info.type == Variant::NIL) {
						arg_type = "Variant";
					} else {
						arg_type = Variant::get_type_name(arg_info.type);
					}

					method_api.argument_names.push_back(arg_name);
					method_api.argument_types.push_back(arg_type);

					if (method_bind && method_bind->has_default_argument(i)) {
						method_api.default_arguments[i] = method_bind->get_default_argument(i);
					}
				}

				class_api.methods.push_back(method_api);
			}
		}

		api.push_back(class_api);
	}

	return api;
}
Example #24
0
/* color parsing that tries to match as close as possible IE 6. */
void StyledElement::addCSSColor(Attribute* attr, int id, const String& c)
{
    // this is the only case no color gets applied in IE.
    if (!c.length())
        return;

    if (!attr->decl())
        createMappedDecl(attr);

    if (attr->decl()->setProperty(id, c, false))
        return;

    String color = c;
    // not something that fits the specs.

    // we're emulating IEs color parser here. It maps transparent to black, otherwise it tries to build a rgb value
    // out of everything you put in. The algorithm is experimentally determined, but seems to work for all test cases I have.

    // the length of the color value is rounded up to the next
    // multiple of 3. each part of the rgb triple then gets one third
    // of the length.
    //
    // Each triplet is parsed byte by byte, mapping
    // each number to a hex value (0-9a-fA-F to their values
    // everything else to 0).
    //
    // The highest non zero digit in all triplets is remembered, and
    // used as a normalization point to normalize to values between 0
    // and 255.

    if (!equalIgnoringCase(color, "transparent")) {
        if (color[0] == '#')
            color.remove(0, 1);
        int basicLength = (color.length() + 2) / 3;
        if (basicLength > 1) {
            // IE ignores colors with three digits or less
            int colors[3] = { 0, 0, 0 };
            int component = 0;
            int pos = 0;
            int maxDigit = basicLength-1;
            while (component < 3) {
                // search forward for digits in the string
                int numDigits = 0;
                while (pos < (int)color.length() && numDigits < basicLength) {
                    colors[component] <<= 4;
                    if (isASCIIHexDigit(color[pos])) {
                        colors[component] += toASCIIHexValue(color[pos]);
                        maxDigit = min(maxDigit, numDigits);
                    }
                    numDigits++;
                    pos++;
                }
                while (numDigits++ < basicLength)
                    colors[component] <<= 4;
                component++;
            }
            maxDigit = basicLength - maxDigit;

            // normalize to 00-ff. The highest filled digit counts, minimum is 2 digits
            maxDigit -= 2;
            colors[0] >>= 4 * maxDigit;
            colors[1] >>= 4 * maxDigit;
            colors[2] >>= 4 * maxDigit;

            color = String::format("#%02x%02x%02x", colors[0], colors[1], colors[2]);
            if (attr->decl()->setProperty(id, color, false))
                return;
        }
    }
void Attack::sendResults(){
  size_t _size = getSize();
  if (debug) Serial.print("getting attacks JSON ("+(String)_size+")...");
  sendHeader(200, "text/json", _size);

  String json = "{\"aps\":[";
  
  int _selected = 0;
  for (int i = 0; i < apScan.results; i++) {
    if (apScan.isSelected(i)) {
      json += "\"" + apScan.getAPName(i) + "\",";
      _selected++;
    }
  }
  if (_selected > 0) json.remove(json.length() - 1);
  sendToBuffer(json);

  
  json = "],\"clients\":[";

  _selected = 0;
  for (int i = 0; i < clientScan.results; i++) {
    if (clientScan.getClientSelected(i)) {
      json += "\"" + clientScan.getClientMac(i).toString() + " " + clientScan.getClientVendor(i) + " - " + clientScan.getClientName(i) + "\",";
      _selected++;
    }
  }
  if (_selected == 0) json += "\"FF:FF:FF:FF:FF:FF - BROADCAST\"";
  else json.remove(json.length() - 1);

  sendToBuffer(json);

  json = "],\"attacks\":[";
  for (int i = 0; i < attacksNum; i++) {
    json += "{";
    json += "\"name\":\"" + attackNames[i] + "\",";
    json += "\"status\":\"" + stati[i] + "\",";
    json += "\"running\":" + (String)isRunning[i] + "";
    json += "}";
    if (i != attacksNum - 1) json += ",";
  }
  json += "],";
  sendToBuffer(json);
  
  if(ssidChange){
    json = "\"ssid\":[";
    sendToBuffer(json);
    for (int i = 0; i < ssidList.len; i++) {
      json = "[";
      json += "\"" + ssidList.get(i) + "\",";
      json += (String)ssidList.isEncrypted(i) + "";
      json += "]";
      if (i != ssidList.len - 1) json += ",";
      sendToBuffer(json);
    }
    json = "],";
    sendToBuffer(json);
    ssidChange = false;
  }
  
  json = "\"randomMode\":" + (String)randomMode + "}";
  sendToBuffer(json);
  
  sendBuffer();
  if (debug) Serial.println("done");
}
size_t Attack::getSize(){
  if(apScan.selectedSum == 0) stati[0] = "no AP";
  
  size_t jsonSize = 0;
  
  String json = "{\"aps\":[";
  
  int _selected = 0;
  for (int i = 0; i < apScan.results; i++) {
    if (apScan.isSelected(i)) {
      json += "\"" + apScan.getAPName(i) + "\",";
      _selected++;
    }
  }
  if (_selected > 0) json.remove(json.length() - 1);

  jsonSize += json.length();
  
  json = "],\"clients\":[";

  _selected = 0;
  for (int i = 0; i < clientScan.results; i++) {
    if (clientScan.getClientSelected(i)) {
      json += "\"" + clientScan.getClientMac(i).toString() + " " + clientScan.getClientVendor(i) + " - " + clientScan.getClientName(i) + "\",";
      _selected++;
    }
  }
  if (_selected == 0) json += "\"FF:FF:FF:FF:FF:FF - BROADCAST\"";
  else json.remove(json.length() - 1);

  jsonSize += json.length();

  json = "],\"attacks\":[";
  for (int i = 0; i < attacksNum; i++) {
    json += "{";
    json += "\"name\":\"" + attackNames[i] + "\",";
    json += "\"status\":\"" + stati[i] + "\",";
    json += "\"running\":" + (String)isRunning[i] + "";
    json += "}";
    if (i != attacksNum - 1) json += ",";
  }
  json += "],";
  jsonSize += json.length();

  if(ssidChange){
    json = "\"ssid\":[";
    jsonSize += json.length();
    for (int i = 0; i < ssidList.len; i++) {
      json = "[";
      json += "\"" + ssidList.get(i) + "\",";
      json += String( ssidList.isEncrypted(i) ) + "";
      Serial.print(ssidList.isEncrypted(i));
      json += "]";
      if (i != ssidList.len - 1) json += ",";
      jsonSize += json.length();
    }
    json = "],";
    jsonSize += json.length();
  }
  json = "\"randomMode\":" + (String)randomMode + "}";
  jsonSize += json.length();

  return jsonSize;
}
Example #27
0
//===> dissect incomming subscribe <-------------------------------------------
TdissectResult ApplicationMQTTClient::dissectPayload(String subTopic, String subValue){
  TdissectResult dissectResult;
  String Topics[4];
  for (int i = 0; i < 4; i++) {
    Topics[i] = NULL;
  }

  String str = subTopic;
  if (str.startsWith("/")) str.remove(0, 1);
  if (str.endsWith("/")) str.remove(str.length()-1,str.length());
  dissectResult.topic = str;
  dissectResult.value = subTopic;

  //Serial.print("dissectPayload subTopic = "); Serial.println(str);

  int index = -1;
  int i = 0;
  do{
   index = str.indexOf("/");
   if (index != -1){
      Topics[i] = str.substring(0, index);
      //Serial.println("Topic[" + String(i) + "] = " + Topics[i]);
	  str.remove(0, index +1);
	  i++;
	  if (str.indexOf("/") == -1 and str.length() > 0){    //best of the rest
	    index = -1;
		Topics[i] = str;
		//Serial.println("Topic[" + String(i) + "] = " + Topics[i]);
		i++;
	  }
	}else{
	}
  } while (index != -1);
  int depth = i;
  int countDepth = 0;
  //Serial.println("TreeDepth = " + String(i));

  //find item index
  String itemPath = "";
  bool found_e1 = false;
  if (depth > 1 and Topics[1] != NULL){
    for (int i = 0; i < topic.sub.E1.count; i++) {
	  if (topic.sub.E1.item[i] != NULL){
	    	//Serial.println(topic.sub.E1.item[i] + " / " + Topics[1]);
	    if (topic.sub.E1.item[i] == Topics[1]){
	    	//Serial.println("----> gefunden!");
	    	//Serial.println("");
          dissectResult.E1 = i;
		  itemPath = String(i);
		  dissectResult.found = true;
		  found_e1 = true;
		  countDepth++;
		  break;
        }else dissectResult.found = false;
	  }
    }
  }

  bool found_e2 = false;
  if (depth > 2 and Topics[2] != NULL and found_e1){
    for (int i = 0; i < topic.sub.E2.count; i++) {
	  if (topic.sub.E2.item[dissectResult.E1][i] != NULL){
	    	//Serial.println(topic.sub.E2.item[dissectResult.E1][i] + " / " + Topics[2]);
	    if (topic.sub.E2.item[dissectResult.E1][i] == Topics[2]){
	    	//Serial.println("----> gefunden!");
	    	//Serial.println("");
          dissectResult.E2 = i;
		  itemPath += "/";
		  itemPath += String(i);
		  dissectResult.found = true;
		  found_e2 = true;
		  countDepth++;
		  break;
        }else dissectResult.found = false;
	  }
    }
  }

  bool found_e3 = false;
  if (depth > 3 and Topics[3] != NULL and found_e1 and found_e2){
    for (int i = 0; i < topic.sub.E3.count; i++) {
	  if (topic.sub.E3.item[dissectResult.E1][dissectResult.E2][i] != NULL){
	    	//Serial.println(topic.sub.E3.item[dissectResult.E1][dissectResult.E2][i] + " / " + Topics[3]);
	    if (topic.sub.E3.item[dissectResult.E1][dissectResult.E2][i] == Topics[3]){
	    	//Serial.println("----> gefunden!");
	    	//Serial.println("");
          dissectResult.E3 = i;
		  itemPath += "/";
		  itemPath += String(i);
		  dissectResult.found = true;
		  found_e3 = true;
		  countDepth++;
		  break;
        }else dissectResult.found = false;
	  }
    }
  }
  if (depth == countDepth+1){
	  Serial.println("dissectResult found!");
	  dissectResult.itemPath = itemPath;

  }else{
	  dissectResult.found = false;
	  Serial.println("no dissectResult found!");
  }
  return dissectResult;
}
Example #28
0
void BootNormal::_mqttCallback(char* topic, char* payload) {
  String message = String(payload);
  String unified = String(topic);
  unified.remove(0, strlen(Config.get().mqtt.baseTopic) + strlen(Config.get().deviceId) + 1); // Remove devices/${id}/ --- +1 for /

  // Device properties
  if (Config.get().ota.enabled && unified == "$ota") {
    if (message != this->_interface->firmware.version) {
      Logger.log(F("✴ OTA available (version "));
      Logger.log(message);
      Logger.logln(F(")"));
      if (strlen(payload) + 1 <= MAX_FIRMWARE_VERSION_LENGTH) {
        strcpy(this->_otaVersion, payload);
        this->_flaggedForOta = true;
        Logger.logln(F("Flagged for OTA"));
      } else {
        Logger.logln(F("Version string received is too long"));
      }
    }
    return;
  } else if (unified == "$reset" && message == "true") {
    this->_fillMqttTopic(PSTR("/$reset"));
    MqttClient.publish("false", true);
    this->_flaggedForReset = true;
    Logger.logln(F("Flagged for reset by network"));
    return;
  }

  // Implicit node properties
  unified.remove(unified.length() - 4, 4); // Remove /set
  unsigned int separator = 0;
  for (unsigned int i = 0; i < unified.length(); i++) {
    if (unified.charAt(i) == '/') {
      separator = i;
      break;
    }
  }
  String node = unified.substring(0, separator);
  String property = unified.substring(separator + 1);

  int homieNodeIndex = -1;
  for (int i = 0; i < this->_interface->registeredNodesCount; i++) {
    const HomieNode* homieNode = this->_interface->registeredNodes[i];
    if (node == homieNode->getId()) {
      homieNodeIndex = i;
      break;
    }
  }

  if (homieNodeIndex == -1) {
    Logger.log(F("Node "));
    Logger.log(node);
    Logger.logln(F(" not registered"));
    return;
  }

  const HomieNode* homieNode = this->_interface->registeredNodes[homieNodeIndex];

  int homieNodePropertyIndex = -1;
  for (int i = 0; i < homieNode->getSubscriptionsCount(); i++) {
    Subscription subscription = homieNode->getSubscriptions()[i];
    if (property == subscription.property) {
      homieNodePropertyIndex = i;
      break;
    }
  }

  if (!homieNode->getSubscribeToAll() && homieNodePropertyIndex == -1) {
    Logger.log(F("Node "));
    Logger.log(node);
    Logger.log(F(" not subscribed to "));
    Logger.logln(property);
    return;
  }

  Logger.logln(F("Calling global input handler..."));
  bool handled = this->_interface->globalInputHandler(node, property, message);
  if (handled) return;

  Logger.logln(F("Calling node input handler..."));
  handled = homieNode->getInputHandler()(property, message);
  if (handled) return;

  if (homieNodePropertyIndex != -1) { // might not if subscribed to all only
    Subscription homieNodeSubscription = homieNode->getSubscriptions()[homieNodePropertyIndex];
    Logger.logln(F("Calling property input handler..."));
    handled = homieNodeSubscription.inputHandler(message);
  }

  if (!handled){
    Logger.logln(F("No handlers handled the following packet:"));
    Logger.log(F("  • Node ID: "));
    Logger.logln(node);
    Logger.log(F("  • Property: "));
    Logger.logln(property);
    Logger.log(F("  • Value: "));
    Logger.logln(message);
  }
}