void serialEvent1()
{
    char inchar = (char) Serial1.read();
    sensorstringEC += inchar;
    sensorstringECRaw += inchar;
    if (inchar == ',')
    {
        sensorstringEC = "";
    }
    if (inchar == '\r')
    {
        char tempEC[6];
        sensorstringEC.toCharArray(tempEC, 5);
        actualEC = 0;
        actualEC = atof(tempEC);
        sensorstringEC = "";
        Serial.println(sensorstringECRaw);
        sensorstringECRaw = "";

    }
}
void InternetButton::playSong(String song){
    char inputStr[200];
    song.toCharArray(inputStr,200);
    
    Serial.println(inputStr);
    
    char *note = strtok(inputStr,",");
    char *duration = strtok(NULL,",");
    playNote(note,atoi(duration));
    
    while(duration != NULL){
        note = strtok(NULL,",");
        Serial.println(note);
        duration = strtok(NULL,", \n");
        Serial.println(duration);
        //if(atoi(duration) <= 0){
        //    break;
        //}
        playNote(note,atoi(duration));
    }
}
int NameManager::validateFirstName(const String& name, int species) {
	if (name.isEmpty())
		return NameManagerResult::DECLINED_EMPTY;

	if (name.length() < 3 || name.length() > 15)
		return NameManagerResult::DECLINED_RACE_INAPP;

	if (isProfane(name))
		return NameManagerResult::DECLINED_PROFANE;

	if (isDeveloper(name))
		return NameManagerResult::DECLINED_DEVELOPER;

	if (isFiction(name))
		return NameManagerResult::DECLINED_FICT_RESERVED;

	if (isReserved(name))
		return NameManagerResult::DECLINED_RESERVED;

	//Make sure that only valid characters are allowed in the name.
	if (strspn(name.toCharArray(), "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'-") != name.length())
		return NameManagerResult::DECLINED_SYNTAX;

	//If the name has a hyphen or apostrophe, make sure they are the proper species.
	if (name.indexOf("'") != -1 || name.indexOf("-") != -1) {
		//Must be a human, twilek, moncal, or zabrak to have a hyphen or apostrophe.
		if (species != CreatureObjectImplementation::HUMAN && species != CreatureObjectImplementation::TWILEK && species != CreatureObjectImplementation::MONCAL && species != CreatureObjectImplementation::ZABRAK)
			return NameManagerResult::DECLINED_RACE_INAPP;

		//Moncal's aren't allowed to have apostrophes.
		if (species == CreatureObjectImplementation::MONCAL && name.indexOf("'") != -1)
			return NameManagerResult::DECLINED_RACE_INAPP;

		//Make sure they only have one hyphen and apostrophe in firstname.
		if (name.indexOf('\'') != name.lastIndexOf('\'') || name.indexOf('-') != name.lastIndexOf('-'))
			return NameManagerResult::DECLINED_RACE_INAPP;
	}

	return NameManagerResult::ACCEPTED;
}
Beispiel #4
0
void DataClass::sendSD(Sensor* sensor, int newTrial, int trialNum, 
int timeDec, int valueDec) 
{
  String filename = _filenameForSD(sensor->_name);
  char buf[filename.length()+1];
  filename.toCharArray(buf, filename.length()+1);

  File dataFile = SD.open(buf, FILE_WRITE);

  if (!sensor->_SDOpen) {
    sensor->_SDOpen = true;
  }
  if (newTrial) {
    dataFile.println("---");
    dataFile.println("Trial " + String(trialNum));
    dataFile.println("Time,Value");
  }

  dataFile.println(FloatToString(sensor->_timer.duration(), timeDec)
    + "," + FloatToString(sensor->readValue(), valueDec));
  dataFile.close();
}
Beispiel #5
0
void SyslogClass::logger(uint8_t facility, uint8_t severity, const char tag[], const char timestamp[], const char message[]) {
  String Pri;

  Pri="<";
  Pri+=(8 * facility + severity);
  Pri+=">";
  
  char UDPBufferPri[Pri.length()+1];
  Pri.toCharArray(UDPBufferPri,Pri.length()+1);

  SyslogUdp.beginPacket(ip_syslogserver, SYSLOG_DEFAULT_PORT);

  SyslogUdp.write(UDPBufferPri);
  SyslogUdp.write("1");//Write Version (1)
  SyslogUdp.write(" ");
  SyslogUdp.write(timestamp);
  SyslogUdp.write(" ");
  SyslogUdp.write(tag); //Hostname
  SyslogUdp.write(" ");
  SyslogUdp.write(message);
  SyslogUdp.endPacket();
}
Beispiel #6
0
//Next/Previous button function.
void NTGVS1053::NextPrevious(bool _isNextButton){

	//Stop the currently played audio file.
	vs1053.stopPlaying();
	//Add or substract one point from mp3Index.
	if(_isNextButton){ mp3Index ++; }
	else if(!_isNextButton){ mp3Index --; }
	/*
	Just incase the mp3Index is beyond the available file, so we need to
		bound the value of mp3Index.
	*/
	mp3Index = BoundAndInvertValue(mp3Index, mp3IndexMin, mp3IndexMax);
	//Convert the integer to String.
	mp3IndexBufferString = String(mp3Index) + ".mp3";
	//Convert the String into character array.
	mp3IndexBufferString.toCharArray(mp3IndexBufferCharArray, 50);
	//Play the music based on the mp3 index in character array.
	Play(mp3IndexBufferCharArray);
	if(_isNextButton){ Serial.println("Next button just pressed."); }
	else if(!_isNextButton){ Serial.println("Previous button just pressed."); }

}
Beispiel #7
0
void MavlinkModem::readAtsAll(int rows[]) {
  if (startCmdMode()) {
    String cmd;
    String value;
    for (int i = 1; i < 16; i++) {
      cmd = "ATS" + String(i) + "?\r";
      value = runCmd(cmd, ATI_DELAY, false);
      value.replace(cmd, "");
      value.replace("\r\n", "");

      if (i == 8 || i == 9) {
      char tarray[10];
        value.toCharArray(tarray, sizeof(tarray));
        long lValue = atol(tarray);
        rows[i-1] = lValue / 1000;
      } else {
        rows[i-1] = value.toInt();
      }
    }
    stopCmdMode();
  }
}
Beispiel #8
0
// get position (longitude and latitude)
String GSM3ShieldV2::getPosition()
{
	String Result = "";
	String number;
	// AT command for obtain the current Location
	String modemResponse = modemAccess.writeModemCommand("AT+QCELLLOC=1", 1000);
	// Parse and check response
	char res_to_compare[modemResponse.length()];
	modemResponse.toCharArray(res_to_compare, modemResponse.length());
	if(strstr(res_to_compare,"OK") == NULL)
	{	
		if(debug==true) Serial.println(modemResponse);
		Result =" Position not lock ";
	}
	else
	{
		if(debug==true) Serial.println(modemResponse);
		Result = modemResponse.substring(12, 33);
		
	}
	return Result;	
}
char* Esp8266HttpClient::send(const char* request, const char* serverUrl, int port) {

    String response = "";

    if (sclient.connect(serverUrl, port)) {

        // Send the request
        sclient.println(request);
        sclient.println();
        delay(delayTime);

        while(sclient.connected()){
          // Read the headers
          String line = sclient.readStringUntil('\n');
          if (line == "\r") {
            break;
          }
        }
        // Read the body
        response = sclient.readStringUntil('\n');
        //Serial.println("reply was:");
        //Serial.println("==========");
        //Serial.println(response);

        sclient.stop();
    } else {
        // connection was unsuccessful
        sclient.stop();
        return "can't setup SSL connection";
    }

    // convert the string into a char and return
    int len = response.length();
    char* response_char = new char[len + 1]();
    Serial.println(response_char);
    response.toCharArray(response_char, len + 1);
    return response_char;
}
void loop() {

  if (!mqttClient.connected()) {
    long now = millis();
    if (now - lastReconnectAttempt > 5000) {
      lastReconnectAttempt = now;
      // Attempt to reconnect
      if (reconnect()) {
        lastReconnectAttempt = 0;
      }
    }
  } else {
    mqttClient.loop();
  }

  YunClient client = server.accept();

  if (client) {
    process(client);
    client.stop();
  }

  long audioSensorNow = millis();
  if (audioSensorNow - lastAudioSensorPublish > 25) {
    lastAudioSensorPublish = audioSensorNow;
    sound_value = analogRead(soundAnalogPin);
    if (sound_value) {
      String str = "{'Value':'";
      str += sound_value;
      str = str + "'}";
      int str_len = str.length() + 1;
      char char_array[str_len];
      str.toCharArray(char_array, str_len);
      mqttClient.publish("Aurduino/HomeAutomation.Audio/102/event",char_array);
    }
  }

}
Beispiel #11
0
// Create MQTT message payload for temperature sensor
bool createMQTTPayloadTemperature(
  char* msg, const uint8_t idx,
  const float temp, const float hum=0 ) 
{
  String dataMsg = "{";
//  SEND_FIRMWARE
  dataMsg.concat(F("\"idx\":"));
  dataMsg.concat(idx);
  dataMsg.concat(F(",\"nvalue\":0"));

  dataMsg.concat(F(",\"svalue\":\""));
  dataMsg.concat(temp);
  if ( hum!=0 ) {
    dataMsg.concat(F(";"));
    dataMsg.concat(hum);
    dataMsg.concat(F(";0"));
  }
  dataMsg.concat("\"}");

  dataMsg.toCharArray( msg, dataMsg.length()+1 );
  
  return ( dataMsg.length()>0 );
}
void WebSocketRailsChannel::dispatch(String eventName, 
	String data) {
	
	if(eventName.equals("websocket_rails.channel_token")) {
		JsonParser<16> parser;	

		char buffer[data.length() + 1];
		data.toCharArray(buffer, data.length() + 1);

		Parser::JsonObject frame = parser.parse(buffer);
		this->token = frame["token"];
	}
	else {
		if (! callbacks.contains(eventName))
			return;
		
		LinkedList<EventCompletionBlock> eventCallbacks = callbacks[eventName];
		for(int i = 0; i < eventCallbacks.size(); i++){
			EventCompletionBlock callback = eventCallbacks.get(i);
			callback(data);
		}
	}	
}
Beispiel #13
0
String rn2483::base16encode(String input)
{
  char charsOut[input.length()*2+1];
  char charsIn[input.length()+1];
  input.trim();
  input.toCharArray(charsIn, input.length()+1);
  
  int i = 0;
  for(i = 0; i<input.length()+1; i++)
  {
    if(charsIn[i] == '\0') break;
    
    int value = int(charsIn[i]);
    
    char buffer[3];
    sprintf(buffer, "%02x", value);
    charsOut[2*i] = buffer[0];
    charsOut[2*i+1] = buffer[1];
  }
  charsOut[2*i] = '\0';
  String toReturn = String(charsOut);
  return toReturn;
}
Beispiel #14
0
char *getTemp(int tempIndex) {
    static char retbuf[64];
    //sensor.requestTemperatures();  // I am getting the tempratures each time in the loop, try moving this up to the fuction prior to the loop

    // Maybe this is bad,  to do it this way,  I am resetting the index each time.
    //sensor.getAddress(deviceIndexArray[tempIndex], tempIndex);   //Why do I need to get the address here?

    //temperature=sensor.getTempC(deviceIndexArray[tempIndex]);

    temperature=sensor.getTempF(deviceIndexArray[tempIndex]);



    //temperature=sensor.getTempCByIndex( tempIndex );// moved off of get address by index to get it by address
    //sprintf(retbuf, "{\"value\":%.4f}", temperature*1.8 + 32);
    String s = "{\"value\": ";
    s.concat(String(temperature));
    s.concat("}");
    s.toCharArray(retbuf, 64);
    oDispatch(tempIndex, temperature, deviceIndexArray[tempIndex]);
    return retbuf;

}
Beispiel #15
0
//GETリクエストをしてbody部分を受信
void CogleMasterConfig::httpGet(String url,char* body,int body_size){
  client.print(String("GET ")
                + url
                + " HTTP/1.1\r\n" 
                + "Host: " + COFIG_SERVER_API_HOST + "\r\n"
                + "Connection: close\r\n\r\n");
  delay(100);
  
  while(client.available()){
    String line = client.readStringUntil('\r');
    line.trim();
    //Serial.println( "line:"+line );
    if(line.length() == 0){
        //空行の後がbody
        String resp = "";
        while(client.available()){
          resp += client.readStringUntil('\r');
        }
        resp.trim();
        resp.toCharArray(body,body_size);
    }
  }      
}
Beispiel #16
0
int StringArray::GetStringAsInt(int index)
{
  String tempData = "";
  if (index >= elements)
    return 0x00;

  Liste* tempList = completeListe;
  for (int i = 0; i  <= index; i++)
  {
    if (i == index)
    {
      tempData = tempList->data;
      break;
    }
    tempList = tempList->next;
  }

  char tempArray[tempData.length() + 1];
  tempData.toCharArray(tempArray,tempData.length() + 1);
  tempArray[tempData.length()] = '\0';
  int tempInt = atoi(tempArray);

  return tempInt;
}
Beispiel #17
0
void QRcode::drawQRCode(int16_t xOffset, int16_t yOffset, String message) {

  // create QR code
  message.toCharArray((char *)strinbuf,260);
  qrencode();

  // print QR Code
  for (byte x = 0; x < WD; x+=2) {
    for (byte y = 0; y < WD; y++) {
      if ( QRBIT(x,y) &&  QRBIT((x+1),y)) {
        // black square on top of black square
        render(x * scale + xOffset, y * scale + yOffset, foregroundColor);
        render((x+1) * scale + xOffset, y * scale + yOffset, foregroundColor);
      }
      if (!QRBIT(x,y) &&  QRBIT((x+1),y)) {
        // white square on top of black square
        render(x * scale + xOffset, y * scale + yOffset, backgroundColor);
        render((x+1) * scale + xOffset, y * scale + yOffset, foregroundColor);
      }
      if ( QRBIT(x,y) && !QRBIT((x+1),y)) {
        // black square on top of white square
        render(x * scale + xOffset, y * scale + yOffset, foregroundColor);
        render((x+1) * scale + xOffset, y * scale + yOffset, backgroundColor);
      }
      if (!QRBIT(x,y) && !QRBIT((x+1),y)) {
        // white square on top of white square
        render(x * scale + xOffset, y * scale + yOffset, backgroundColor);
        render((x+1) * scale + xOffset, y * scale + yOffset, backgroundColor);
      }
    }
    Serial.println();
  }



}
Beispiel #18
0
int wifiChat::sendData(String outString)
{
  //WiFiClient client = server.available();
  if(!client.connected())
    client = server.available();
    
  if(!client.connected()) 
    return -1;

  client.flush();
  char outChar[25];
  outString.concat(END_TRANSMISSION);
  outString.toCharArray(outChar,25);
  client.write(outChar);client.write("\r\n");
  Serial.print("Writing across WiFi: ");
  Serial.println(outChar);

  //client.write("Quit");client.write("\r\n");
  //Serial.print("Writing across WiFi: ");
  //Serial.print("Quit");
  
  return 0;
  
}
Beispiel #19
0
// expects string such as "SOCKSTATUS: 1,1,0102,10,10,0"
// returns nth chunk of data, delimited by commas
int Modem::SocketStringSlice(int n, String s) {
	String slice = s.substring(NthIndexOf(n-1, ',', s) + 1, NthIndexOf(n, ',', s));
	char cArray[slice.length() + 1];
	slice.toCharArray(cArray, sizeof(cArray));
	return atoi(cArray);
}
Beispiel #20
0
void HttpResponse::setBody(String body) {
	this->_body = (char*) calloc(body.length() + 1, sizeof(char));
	body.toCharArray(this->_body, body.length() + 1);
}
Beispiel #21
0
Datei: MEDP.cpp Projekt: Gpx/MEDP
int MEDP::parseInt(String value) {
  char charValue[value.length()+1];
  value.toCharArray(charValue, sizeof(charValue));
  return atoi(charValue);
}
boolean OTAUpdateClass::begin(const char* host, const char* port, const char* path) {
    DEBUG_UPDATE("OTAUpdate::begin - %s %s\r\n", host, path);

    // initialize our memory structures
    this->initialized = false;
    memset(this->firmware_name, 0, OTA_MAX_PATH_LEN);
    memset(this->firmware_digest, 0, DIGEST_SIZE_CHAR);
    memset(this->host, 0, OTA_MAX_PATH_LEN);
    memset(this->path, 0, OTA_MAX_PATH_LEN);
    memset(this->port, 0, OTA_MAX_PATH_LEN);
    strncpy(this->host, host, OTA_MAX_PATH_LEN-1);
    strncpy(this->path, path, OTA_MAX_PATH_LEN-1);
    strncpy(this->port, port, OTA_MAX_PATH_LEN-1);

    // read the firmware information
    LFlash.begin();
    LFile cfg = LFlash.open("autostart.txt", FILE_READ);
    if (!cfg) {
        DEBUG_UPDATE("OTAUpdateClass::begin - could not read autostart.txt\r\n");
        return false;
    }

    DEBUG_UPDATE("OTAUpdateClass::begin - reading autostart.txt\r\n");
    while (cfg.available()) {
        String line = "";
        char c = '\n';
        // read the setting part of the line
        while (cfg.available()) {
            c = cfg.read();
            line += c;
            if(c == '\n') {
                break;
            }
        }

        // look for = in the config line
        line.trim();
        int idx = line.indexOf("=");

        if(idx >= 0) {
            String setting = line.substring(0, idx);
            String value = line.substring(idx+1);

            setting.trim();
            value.trim();

            DEBUG_UPDATE("autostart.txt: %s=%s\r\n", setting.c_str(), value.c_str());
            if(setting == "App") {
                value.toCharArray(firmware_name, OTA_MAX_PATH_LEN);
                this->initialized = true;
                break;
            }
        }
    }
    cfg.close();

    if(this->initialized) {
        // we found the app name... calculate the md5 sum
        md5sum(this->firmware_name, this->firmware_digest);
        DEBUG_UPDATE("OTAUpdate::begin - %s [%s]\r\n", this->firmware_name, this->firmware_digest);
    } else {
        DEBUG_UPDATE("OTAUpdate::begin - could not find firmware name\r\n");
        return false;
    }

    return true;
}
void CustomizationVariables::parseFromClientString(const String& custString) {
	/*const char* array = custString.toCharArray();

	StringBuffer str;
	str << "parsing CustomizationString [" << custString.length() << "] " << uppercase << hex;

	for (int i = 0; i < custString.length(); ++i) {
		unsigned int byte = ((unsigned int) array[i]) & 0xFF;

		if ((byte & 0xF0) == 0)
			str << "0" << hex << byte  << " ";
		else
			str << hex << byte  << " ";
	}

	Logger::console.info(str.toString(), true);

	 */
	removeAll();
	keyIndex.removeAll();

	if (custString.length() < 2)
		return;

	try {
		unknown = (uint8) custString.charAt(0);
		//uint8 type = 0;

		int totalVars = (uint8) custString.charAt(1);
		int offset = 1;

		if (totalVars == 0xFF)
			return;

		for (int i = 0; i < totalVars; ++i) {
			uint8 type = (uint8) custString.charAt(++offset);
			uint8 value = (uint8) custString.charAt(++offset);

			setVariable(type, value);
		}
	} catch (Exception& e) {
		removeAll();
		StackTrace::printStackTrace();
		Logger::console.error("Exception in CustomizationVariables& operator=(String& custString)\n");

		const char* array = custString.toCharArray();

		StringBuffer str;
		str << "parsing CustomizationString [" << custString.length() << "] " << uppercase << hex;

		for (int i = 0; i < custString.length(); ++i) {
			unsigned int byte = ((unsigned int) array[i]) & 0xFF;

			if ((byte & 0xF0) == 0)
				str << "0" << hex << byte  << " ";
			else
				str << hex << byte  << " ";
		}

		Logger::console.error(str.toString());
	}

}
Beispiel #24
0
// check the phrase lists
void NaughtyFilter::checkphrase(char *file, off_t filelen, const String *url, const String *domain,
	unsigned int filtergroup, unsigned int phraselist, int limit, bool searchterms)
{
	int weighting = 0;
	int cat;
	std::string weightedphrase;
	
	// checkme: translate this?
	String currcat("Embedded URLs");

	// found categories list & reusable iterators
	std::map<int, listent> listcategories;

	// check for embedded references to banned sites/URLs.
	// have regexes that check for URLs in pages (look for attributes (src, href, javascript location)
	// or look for protocol strings (in which case, incl. ftp)?) and extract them.
	// then check the extracted list against the banned site/URL lists.
	// ADs category lists do not want to add to the possibility of a site being banned.
	// Exception lists are not checked.
	// Do not do full-blown category retrieval/duplicate checking; simply add the
	// "Embedded URLs" category.
	// Put a warning next to the option in the config file that this will take lots of CPU.
	// Support phrase mode 1/2 distinction (duplicate sites/URLs).
	// Have weight configurable per filter group, not globally or with a list directive - 
	//   a weight of 0 will disable the option, effectively making this functionality per-FG itself.

	// todo: if checkphrase is passed the domain & existing URL, it can create full URLs from relative ones.
	// if a src/href URL starts with a /, append it to the domain; otherwise, append it to the existing URL.
	// chop off anything after a ?, run through realPath, then put through the URL lists.

#ifdef HAVE_PCRE
	// if weighted phrases are enabled, and we have been passed a URL and domain, and embedded URL checking is enabled...
	// then check for embedded URLs!
	if (url != NULL && o.fg[filtergroup]->embedded_url_weight > 0) {
		std::map<int, listent>::iterator ourcat;
		bool catinited = false;
		std::map<String, unsigned int> found;
		std::map<String, unsigned int>::iterator founditem;

		String u;
		char* j;

		// check for absolute URLs
		if (absurl_re.match(file)) {
			// each match generates 2 results (because of the brackets in the regex), we're only interested in the first
#ifdef DGDEBUG
			std::cout << "Found " << absurl_re.numberOfMatches()/2 << " absolute URLs:" << std::endl;
#endif
			for (int i = 0; i < absurl_re.numberOfMatches(); i+=2) {
				// chop off quotes
				u = absurl_re.result(i);
				u = u.subString(1,u.length()-2);
#ifdef DGDEBUG
				std::cout << u << std::endl;
#endif
				if ((((j = o.fg[filtergroup]->inBannedSiteList(u)) != NULL) && !(o.lm.l[o.fg[filtergroup]->banned_site_list]->lastcategory.contains("ADs")))
					|| (((j = o.fg[filtergroup]->inBannedURLList(u)) != NULL) && !(o.lm.l[o.fg[filtergroup]->banned_url_list]->lastcategory.contains("ADs"))))
				{
					// duplicate checking
					// checkme: this should really be being done *before* we search the lists.
					// but because inBanned* methods do some cleaning up of their own, we don't know the form to check against.
					// we actually want these cleanups do be done before passing to inBanned*/inException* - this would
					// speed up ConnectionHandler a bit too.
					founditem = found.find(j);
					if ((o.fg[filtergroup]->weighted_phrase_mode == 2) && (founditem != found.end())) {
						founditem->second++;
					} else {
						// add the site to the found phrases list
						found[j] = 1;
						if (weightedphrase.length() == 0)
							weightedphrase = "[";
						else
							weightedphrase += " ";
						weightedphrase += j;
						if (!catinited) {
							listcategories[-1] = listent(o.fg[filtergroup]->embedded_url_weight,currcat);
							ourcat = listcategories.find(-1);
							catinited = true;
						} else
							ourcat->second.weight += o.fg[filtergroup]->embedded_url_weight;
					}
				}
			}
		}

		found.clear();

		// check for relative URLs
		if (relurl_re.match(file)) {
			// we don't want any parameters on the end of the current URL, since we append to it directly
			// when forming absolute URLs from relative ones. we do want a / on the end, too.
			String currurl(*url);
			if (currurl.contains("?"))
				currurl = currurl.before("?");
			if (currurl[currurl.length()-1] != '/')
				currurl += "/";

			// each match generates 2 results (because of the brackets in the regex), we're only interested in the first
#ifdef DGDEBUG
			std::cout << "Found " << relurl_re.numberOfMatches()/2 << " relative URLs:" << std::endl;
#endif
			for (int i = 0; i < relurl_re.numberOfMatches(); i+=2) {
				u = relurl_re.result(i);
				
				// can't find a way to negate submatches in PCRE, so it is entirely possible
				// that some absolute URLs have made their way into this list. we don't want them.
				if (u.contains("://"))
					continue;

#ifdef DGDEBUG
				std::cout << u << std::endl;
#endif
				// remove src/href & quotes
				u = u.after("=");
				u.removeWhiteSpace();
				u = u.subString(1,u.length()-2);
				
				// create absolute URL
				if (u[0] == '/')
					u = (*domain) + u;
				else
					u = currurl + u;
#ifdef DGDEBUG
				std::cout << "absolute form: " << u << std::endl;
#endif
				if ((((j = o.fg[filtergroup]->inBannedSiteList(u)) != NULL) && !(o.lm.l[o.fg[filtergroup]->banned_site_list]->lastcategory.contains("ADs")))
					|| (((j = o.fg[filtergroup]->inBannedURLList(u)) != NULL) && !(o.lm.l[o.fg[filtergroup]->banned_url_list]->lastcategory.contains("ADs"))))
				{
					// duplicate checking
					// checkme: this should really be being done *before* we search the lists.
					// but because inBanned* methods do some cleaning up of their own, we don't know the form to check against.
					// we actually want these cleanups do be done before passing to inBanned*/inException* - this would
					// speed up ConnectionHandler a bit too.
					founditem = found.find(j);
					if ((o.fg[filtergroup]->weighted_phrase_mode == 2) && (founditem != found.end())) {
						founditem->second++;
					} else {
						// add the site to the found phrases list
						found[j] = 1;
						if (weightedphrase.length() == 0)
							weightedphrase = "[";
						else
							weightedphrase += " ";
						weightedphrase += j;
						if (!catinited) {
							listcategories[-1] = listent(o.fg[filtergroup]->embedded_url_weight,currcat);
							ourcat = listcategories.find(-1);
							catinited = true;
						} else
							ourcat->second.weight += o.fg[filtergroup]->embedded_url_weight;
					}
				}
			}
		}
		if (catinited) {
			weighting = ourcat->second.weight;
			weightedphrase += "]";
#ifdef DGDEBUG
			std::cout << weightedphrase << std::endl;
			std::cout << "score from embedded URLs: " << ourcat->second.weight << std::endl;
#endif
		}
	}
#endif

	std::string bannedphrase;
	std::string exceptionphrase;
	String bannedcategory;
	int type, index, weight, time;
	bool allcmatched = true, bannedcombi = false;
	std::string s1;

	// this line here searches for phrases contained in the list - the rest of the code is all sorting
	// through it to find the categories, weightings, types etc. of what has actually been found.
	std::map<std::string, std::pair<unsigned int, int> > found;
	o.lm.l[phraselist]->graphSearch(found, file, filelen);

	// cache reusable iterators
	std::map<std::string, std::pair<unsigned int, int> >::iterator foundend = found.end();
	std::map<std::string, std::pair<unsigned int, int> >::iterator foundcurrent;

	// look for combinations first
	//if banned must wait for exception later
	std::string combifound;
	std::string combisofar;

	std::vector<int>::iterator combicurrent = o.lm.l[phraselist]->combilist.begin();
	std::map<int, listent>::iterator catcurrent;
	int lowest_occurrences = 0;

	while (combicurrent != o.lm.l[phraselist]->combilist.end()) {
		// Grab the current combination phrase part
		index = *combicurrent;
		// Do stuff if what we have is an end marker (end of one list of parts)
		if (index == -2) {
			// Were all the parts in this combination matched?
			if (allcmatched) {
				type = *(++combicurrent);
				// check this time limit against the list of time limits
				time = *(++combicurrent);
				if (not (o.lm.l[phraselist]->checkTimeAtD(time))) {
					// nope - so don't take any notice of it
#ifdef DGDEBUG
					combicurrent++;
					cat = (*++combicurrent);
					std::cout << "Ignoring combi phrase based on time limits: " << combisofar << "; "
						<< o.lm.l[phraselist]->getListCategoryAtD(cat) << std::endl;
#else
					combicurrent += 2;
#endif
					combisofar = "";
				}
				else if (type == -1) {	// combination exception
					isItNaughty = false;
					isException = true;
					// Combination exception phrase found:
					// Combination exception search term found:
					message_no = searchterms ? 456 : 605;
					whatIsNaughtyLog = o.language_list.getTranslation(message_no);
					whatIsNaughtyLog += combisofar;
					whatIsNaughty = "";
					++combicurrent;
					cat = *(++combicurrent);
					whatIsNaughtyCategories = o.lm.l[phraselist]->getListCategoryAtD(cat);
					return;
				}
				else if (type == 1) {	// combination weighting
					weight = *(++combicurrent);
					weighting += weight * (o.fg[filtergroup]->weighted_phrase_mode == 2 ? 1 : lowest_occurrences);
					if (weight > 0) {
						cat = *(++combicurrent);
						//category index -1 indicates an uncategorised list
						if (cat >= 0) {
							//don't output duplicate categories
							catcurrent = listcategories.find(cat);
							if (catcurrent != listcategories.end()) {
								catcurrent->second.weight += weight * (o.fg[filtergroup]->weighted_phrase_mode == 2 ? 1 : lowest_occurrences);
							} else {
								currcat = o.lm.l[phraselist]->getListCategoryAtD(cat);
								listcategories[cat] = listent(weight,currcat);
							}
						}
					} else {
						// skip past category for negatively weighted phrases
						combicurrent++;
					}
					if (weightedphrase.length() > 0) {
						weightedphrase += "+";
					}
					weightedphrase += "(";
					if (weight < 0) {
						weightedphrase += "-" + combisofar;
					} else {
						weightedphrase += combisofar;
					}
#ifdef DGDEBUG
					std::cout << "found combi weighted phrase ("<< o.fg[filtergroup]->weighted_phrase_mode << "): "
						<< combisofar << " x" << lowest_occurrences << " (per phrase: "
						<< weight << ", calculated: "
						<< (weight * (o.fg[filtergroup]->weighted_phrase_mode == 2 ? 1 : lowest_occurrences)) << ")"
						<< std::endl;
#endif

					weightedphrase += ")";
					combisofar = "";
				}
				else if (type == 0) {	// combination banned
					bannedcombi = true;
					combifound += "(" + combisofar + ")";
					combisofar = "";
					combicurrent += 2;
					cat = *(combicurrent);
					bannedcategory = o.lm.l[phraselist]->getListCategoryAtD(cat);
				}
			} else {
				// We had an end marker, but not all the parts so far were matched.
				// Reset the match flag ready for the next chain, and advance to its first part.
				allcmatched = true;
				combicurrent += 4;
				lowest_occurrences = 0;
			}
		} else {
			// We didn't get an end marker - just an individual part.
			// If all parts in the current chain have been matched so far, look for this one as well.
			if (allcmatched) {
				s1 =o.lm.l[phraselist]->getItemAtInt(index);
				if ((foundcurrent = found.find(s1)) == foundend) {
					allcmatched = false;
					combisofar = "";
				} else {
					if (combisofar.length() > 0) {
						combisofar += ", ";
					}
					combisofar += s1;
					// also track lowest number of times any one part occurs in the text
					// as this will correspond to the number of times the whole chain occurs
					if ((lowest_occurrences == 0) || (lowest_occurrences > foundcurrent->second.second)) {
						lowest_occurrences = foundcurrent->second.second;
					}
				}
			}
		}
		// Advance to the next part in the current chain
		combicurrent++;
	}

	// even if we already found a combi ban, we must still wait; there may be non-combi exceptions to follow

	// now check non-combi phrases
	foundcurrent = found.begin();
	while (foundcurrent != foundend) {
		// check time for current phrase
		if (not o.lm.l[phraselist]->checkTimeAt(foundcurrent->second.first)) {
#ifdef DGDEBUG
			std::cout << "Ignoring phrase based on time limits: "
				<< foundcurrent->first << ", "
				<< o.lm.l[phraselist]->getListCategoryAt(foundcurrent->second.first) << std::endl;
#endif
			foundcurrent++;
			continue;
		}
		// 0=banned, 1=weighted, -1=exception, 2=combi, 3=weightedcombi
		type = o.lm.l[phraselist]->getTypeAt(foundcurrent->second.first);
		if (type == 0) {
			// if we already found a combi ban, we don't need to know this stuff
			if (!bannedcombi) {
				isItNaughty = true;
				bannedphrase = foundcurrent->first;
				bannedcategory = o.lm.l[phraselist]->getListCategoryAt(foundcurrent->second.first, &cat);
			}
		}
		else if (type == 1) {
			// found a weighted phrase - either add one lot of its score, or one lot for every occurrence, depending on phrase filtering mode
			weight = o.lm.l[phraselist]->getWeightAt(foundcurrent->second.first) * (o.fg[filtergroup]->weighted_phrase_mode == 2 ? 1 : foundcurrent->second.second);
			weighting += weight;
			if (weight > 0) {
				currcat = o.lm.l[phraselist]->getListCategoryAt(foundcurrent->second.first, &cat);
				if (cat >= 0) {
					//don't output duplicate categories
					catcurrent = listcategories.find(cat);
					if (catcurrent != listcategories.end()) {
						// add one or N times the weight to this category's score
						catcurrent->second.weight += weight * (o.fg[filtergroup]->weighted_phrase_mode == 2 ? 1 : foundcurrent->second.second);
					} else {
						listcategories[cat] = listent(weight,currcat);
					}
				}
			}

			if (o.show_weighted_found) {
				if (weightedphrase.length() > 0) {
					weightedphrase += "+";
				}
				if (weight < 0) {
					weightedphrase += "-";
				}

				weightedphrase += foundcurrent->first;
			}
#ifdef DGDEBUG
			std::cout << "found weighted phrase ("<< o.fg[filtergroup]->weighted_phrase_mode << "): "
				<< foundcurrent->first << " x" << foundcurrent->second.second << " (per phrase: "
				<< o.lm.l[phraselist]->getWeightAt(foundcurrent->second.first)
				<< ", calculated: " << weight << ")" << std::endl;
#endif
		}
		else if (type == -1) {
			isException = true;
			isItNaughty = false;
			// Exception phrase found:
			// Exception search term found:
			message_no = searchterms ? 457 : 604;
			whatIsNaughtyLog = o.language_list.getTranslation(message_no);
			whatIsNaughtyLog += foundcurrent->first;
			whatIsNaughty = "";
			whatIsNaughtyCategories = o.lm.l[phraselist]->getListCategoryAt(foundcurrent->second.first, NULL);
			return;  // no point in going further
		}
		foundcurrent++;
	}

#ifdef DGDEBUG
	std::cout << "WEIGHTING: " << weighting << std::endl;
#endif

	// store the lowest negative weighting or highest positive weighting out of all filtering runs, preferring to store positive weightings.
	if ((weighting < 0 && naughtiness <= 0 && weighting < naughtiness) || (naughtiness >= 0 && weighting > naughtiness) || (naughtiness < 0 && weighting > 0) ) {
		naughtiness = weighting;
	}

#ifdef DGDEBUG
	std::cout << "NAUGHTINESS: " << naughtiness << std::endl;
#endif

	// *now* we can safely get down to the whole banning business!

	if (bannedcombi) {
		isItNaughty = true;
		// Banned combination phrase found:
		// Banned combination search term found:
		message_no = searchterms ? 452: 400;
		whatIsNaughtyLog = o.language_list.getTranslation(message_no);
		whatIsNaughtyLog += combifound;
		// Banned combination phrase found.
		// Banned combination search term found.
		whatIsNaughty = o.language_list.getTranslation(searchterms ? 453 : 401);
		whatIsNaughtyCategories = bannedcategory.toCharArray();
		return;
	}

	if (isItNaughty) {
		// Banned phrase found:
		// Banned search term found:
		message_no = searchterms ? 450: 300;
		whatIsNaughtyLog = o.language_list.getTranslation(message_no);
		whatIsNaughtyLog += bannedphrase;
		// Banned phrase found.
		// Banned search term found.
		whatIsNaughty = o.language_list.getTranslation(searchterms ? 451 : 301);
		whatIsNaughtyCategories = bannedcategory.toCharArray();
		return;
	}

	if (weighting > limit) {
		isItNaughty = true;
		// Weighted phrase limit of
		// Weighted search term limit of
		message_no = searchterms ? 454: 401;
		whatIsNaughtyLog = o.language_list.getTranslation(message_no);
		whatIsNaughtyLog += String(limit).toCharArray();
		whatIsNaughtyLog += " : ";
		whatIsNaughtyLog += String(weighting).toCharArray();
		if (o.show_weighted_found) {
			whatIsNaughtyLog += " (";
			whatIsNaughtyLog += weightedphrase;
			whatIsNaughtyLog += ")";
		}
		// Weighted phrase limit exceeded.
		// Weighted search term limit exceeded.
		whatIsNaughty = o.language_list.getTranslation(searchterms ? 455 : 403);
		// Generate category list, sorted with highest scoring first.
		bool nonempty = false;
		bool belowthreshold = false;
		String categories;
		std::deque<listent> sortable_listcategories;
		catcurrent = listcategories.begin();
		while (catcurrent != listcategories.end()) {
			sortable_listcategories.push_back(catcurrent->second);
			catcurrent++;
		}
		std::sort(sortable_listcategories.begin(), sortable_listcategories.end());
		std::deque<listent>::iterator k = sortable_listcategories.begin();
		while (k != sortable_listcategories.end()) {
			// if category display threshold is in use, apply it
			if (!belowthreshold && (o.fg[filtergroup]->category_threshold > 0)
				&& (k->weight < o.fg[filtergroup]->category_threshold))
			{
				whatIsNaughtyDisplayCategories = categories.toCharArray();
				belowthreshold = true;
				usedisplaycats = true;
			}
			if (k->string.length() > 0) {
				if (nonempty) categories += ", ";
				categories += k->string;
				nonempty = true;
			}
			k++;
			// if category threshold is set to show only the top category,
			// everything after the first loop is below the threshold
			if (!belowthreshold && o.fg[filtergroup]->category_threshold < 0) {
				whatIsNaughtyDisplayCategories = categories.toCharArray();
				belowthreshold = true;
				usedisplaycats = true;
			}
		}
		whatIsNaughtyCategories = categories.toCharArray();
		return;
	}
	// whatIsNaughty is what is displayed in the browser
	// whatIsNaughtyLog is what is logged in the log file if at all
}
void LeweiTcpClient::sendSensorValue(String sensorName,String sensorValue)
{
	if (_clientRevCtrl.connected())
	{
		//checkFreeMem();
		String connStr = "{\"method\": \"upload\", \"data\":[";
		connStr+=_sensorValueStr;
		connStr+="{\"Name\":\"";
		connStr+=sensorName;
		connStr+="\",\"Value\":\"";
		connStr+=sensorValue;
		connStr+="\"}]}&^!";
		char* c = (char*)malloc(connStr.length()+1);
		if(c)
		{
			connStr.toCharArray(c,connStr.length()+1);
			_clientRevCtrl.print(c);
			_starttime = millis();//reset the reconneting count
			free(c);
			c = NULL;
		}
		else
		{
			Serial.println("malloc:F");
		}
		connStr = "";
		_sensorValueStr = "";
		
		//checkFreeMem();
		
	}
	else 
	{
		// if you didn't get a connection to the server:
		Serial.print("Send");
		Serial.println("Fail");
	}
	
	
	
	/*
	//using open.lewei50.com to upload data
	if (_clientUpload.connect(uploadServer, 80))
	{
		Serial.println("clientUploader connected");
		
		String connStr ="POST /api/V1/gateway/UpdateSensors/01 HTTP/1.1\r\nuserkey:";
		connStr +=_userKey;
		connStr +="\r\nHost:open.lewei50.com\r\nContent-Length:";
		connStr +=(24+sensorName.length()+sensorValue.length());
		connStr +="\r\nConnection: close\r\n\r\n[{\"Name\":\"";
		connStr +=sensorName;
		connStr +="\",\"Value\":\"";
		connStr +=sensorValue;
		connStr +="\"}]";
		Serial.println(connStr);
		
		char* c = (char*)malloc(connStr.length()+1);
		connStr.toCharArray(c,connStr.length()+1);
		_clientUpload.print(c);
		free(c);
		c = NULL;
		connStr = "";
		_clientUpload.stop();
	}
	else
	{
		// if you couldn't make a connection:
		Serial.println("connection failed");
		Serial.println("disconnecting.");
		_clientUpload.stop();
	}
	
	*/
	
}
Beispiel #26
0
void serialHandler()
{
    // open the tty
    ttyFid = open( port, O_RDWR );
    if (ttyFid == -1)
    {
        printf( "Error unable to open port: %s\n", port );
        return -1;
    }
    
    // get the current options:
    tcgetattr( ttyFid, &termOptions );

    // Set the input/output speed to 9600
    cfsetispeed( &termOptions, BAUDRATE );

    // Now set the term options (set immediately)
    tcsetattr( ttyFid, TCSANOW, &termOptions );
	
	//
	// **************************************************************
	//
	byte bufferIndex = 0;
    char buffer[25];

    // read the position command from the serial port
    // should look like:
    //      D20BIX+00733Y+00080S99\r\n
    //  
    // and we need the X+00000 and Y+00000 parts
    //
    if (Serial.available() > 0)
	{
        while (Serial.available() > 0 && bufferIndex < 25)
		{
            buffer[bufferIndex] = Serial.read();

            if (buffer[bufferIndex++] == '\n')
			{
                buffer[bufferIndex] = '\0';
                break;
            }
        }

        Serial.flush();

		// check to see if we have good orientation on the buffer by
		// checking for lines starting with model identifier 'D'
		String input = String(buffer);

		if (buffer[0] == 'D' && bufferIndex <=24)
		{  
			int x_result = data[1];
			int y_result = data[4];
			String check;
			char token_buffer[8] = {'0', '0', '0', '0', '0', '0', '0', '0' };

			// scan for x, target token is X+00000
			String x_token = input.substring(5, 11);
			check = x_token.substring(2, 6);
			check.toCharArray(token_buffer, 8);

			x_result = atoi(token_buffer);
			if (x_token[1] == '-')
			{
				x_result *= -1;
			}

			// scan for y, target token is Y+00000
			String y_token = input.substring(12, 18);
			check = y_token.substring(2, 6);
			check.toCharArray(token_buffer, 8);

			y_result = atoi(token_buffer);
			if (y_token[1] == '-')
			{
				y_result *= -1;
			}

			// finalize results
			data[1] = x_result;
			data[4] = y_result;
		}
	}
}
void api_call_http(byte amsg_server[], char body[]) {

	char path[ 30 ];
	char host[ 30 ];
	strcpy_P(path, msg_server_path);
	strcpy_P(host, msg_server_host);

	EthernetClient client;


	if (!client) {
		Serial.println("Ethernet client not available!");
		return;
	}

	Serial.print("HTTP opening connection to ");
	Serial.println(host);
	/*
	if (!ether.dnsLookup(website))
		  Serial.println("DNS failed");
	else
		  Serial.println("DNS resolution done");
	ether.printIp("SRV IP:\t", ether.hisip);
	*/

	if (!client.connect(amsg_server, pgm_read_word(&msg_server_port))) {
		Serial.println("HTTP failed");
		return;
	}

	char d;
	//TODO: add serial number, hash message, JSON
	String postbuf = body;
	String netbuf = "POST ";
	netbuf += path;
	netbuf += " HTTP/1.0\nHost: ";
	netbuf += host;
	netbuf += "\nContent-Type: application/x-www-form-urlencoded\nContent-length:";
	netbuf += postbuf.length();
	netbuf += "\nConnection: close\n\n";
	netbuf += postbuf;
  //compile error on arduino 1.6.2
  //it's just a memory optimization
	//postbuf = NULL;

	Serial.println("HTTP connected");
	Serial.print(netbuf);

	char sockbuf[ netbuf.length() +1];
	netbuf.toCharArray(sockbuf, netbuf.length()+1);
	client.write(sockbuf);
	delay(300);
	while(client.connected()) {
		while(client.available())   {
			d = client.read();
			if (d == '\n')
				Serial.print("\r\n");
			else
				Serial.print(d);
		}
	}
	client.stop();
	Serial.println();
}
Beispiel #28
0
// initialise the plugin - determine icap ip, port & url
int icapinstance::init(void* args)
{
	// always include these lists
	if (!readStandardLists()) {
		return DGCS_ERROR;
	}

	icapurl = cv["icapurl"];  // format: icap://icapserver:1344/avscan
	if (icapurl.length() < 3) {
		if (!is_daemonised)
			std::cerr << "Error reading icapurl option." << std::endl;
		syslog(LOG_ERR, "Error reading icapurl option.");
		return DGCS_ERROR;
		// it would be far better to do a test connection
	}
	icaphost = icapurl.after("//");
	icapport = icaphost.after(":").before("/").toInteger();
	if (icapport == 0) {
		icapport = 1344;
	}
	icaphost = icaphost.before("/");
	if (icaphost.contains(":")) {
		icaphost = icaphost.before(":");
	}
	struct hostent *host;
	if ((host = gethostbyname(icaphost.toCharArray())) == 0) {
		if (!is_daemonised)
			std::cerr << "Error resolving icap host address." << std::endl;
		syslog(LOG_ERR, "Error resolving icap host address.");
		return DGCS_ERROR;
	}
	icapip = inet_ntoa(*(struct in_addr *) host->h_addr_list[0]);

#ifdef DGDEBUG
	std::cerr << "ICAP server address:" << icapip << std::endl;
#endif

	// try to connect to the ICAP server and perform an OPTIONS request
	Socket icapsock;
	try {
		if (icapsock.connect(icapip.toCharArray(), icapport) < 0) {
			throw std::runtime_error("Could not connect to server");
		}
		String line("OPTIONS " + icapurl + " ICAP/1.0\r\nHost: " + icaphost + "\r\n\r\n");
		icapsock.writeString(line.toCharArray());
		// parse the response
		char buff[8192];
		// first line - look for 200 OK
		icapsock.getLine(buff, 8192, o.content_scanner_timeout);
		line = buff;
#ifdef DGDEBUG
		std::cout << "ICAP/1.0 OPTIONS response:" << std::endl << line << std::endl;
#endif
		if (line.after(" ").before(" ") != "200") {
			if (!is_daemonised)
				std::cerr << "ICAP response not 200 OK" << std::endl;
			syslog(LOG_ERR, "ICAP response not 200 OK");
			return DGCS_WARNING;
			//throw std::runtime_error("Response not 200 OK");
		}
		while (icapsock.getLine(buff, 8192, o.content_scanner_timeout) > 0) {
			line = buff;
#ifdef DGDEBUG
			std::cout << line << std::endl;
#endif
			if (line.startsWith("\r")) {
				break;
			}
			else if (line.startsWith("Preview:")) {
				usepreviews = true;
				previewsize = line.after(": ").toInteger();
			}
			else if (line.startsWith("Server:")) {
				if (line.contains("AntiVir-WebGate")) {
					needsBody = true;
				}
			}
			else if (line.startsWith("X-Allow-Out:")) {
				if (line.contains("X-Infection-Found")) {
					supportsXIF = true;
				}
			}
		}
		icapsock.close();
	} catch(std::exception& e) {
		if (!is_daemonised)
			std::cerr << "ICAP server did not respond to OPTIONS request: " << e.what() << std::endl;
		syslog(LOG_ERR, "ICAP server did not respond to OPTIONS request: %s", e.what());
		return DGCS_ERROR;
	}
#ifdef DGDEBUG
	if (usepreviews)
		std::cout << "Message previews enabled; size: " << previewsize << std::endl;
	else
		std::cout << "Message previews disabled" << std::endl;
#endif
	return DGCS_OK;
}
Beispiel #29
0
bool RFduinoGZLLClass::sendToDevice(device_t device, String &data)
{
  char buf[32];
  data.toCharArray(buf, sizeof(buf));
  return sendToDevice(device, buf);
}
Beispiel #30
0
bool RFduinoGZLLClass::sendToHost(String &data)
{
  char buf[32];
  data.toCharArray(buf, sizeof(buf));
  return sendToHost(buf);
}