Example #1
0
boolean Logger::setupFile()
{
    if (!fileRef.isOpen())  //file not open. Try to open it.
    {
        String filename;
        if (settings.appendFile == 1)
        {
            filename = String(settings.fileNameBase);
            filename.concat(".");
            filename.concat(settings.fileNameExt);
            fileRef.open(filename.c_str(), O_APPEND | O_WRITE);
        }
        else {
            filename = String(settings.fileNameBase);
            filename.concat(settings.fileNum++);
            filename.concat(".");
            filename.concat(settings.fileNameExt);
            EEPROM.write(EEPROM_PAGE, settings); //save settings to save updated filenum
            fileRef.open(filename.c_str(), O_CREAT | O_TRUNC | O_WRITE);
        }
        if (!fileRef.isOpen())
        {
            Logger::error("open failed");
            return false;
        }
    }

    //Before we add the next frame see if the buffer is nearly full. if so flush it first.
    if (fileBuffWritePtr > BUF_SIZE - 40)
    {
        flushFileBuff();
    }
    return true;
}
void AndroidBluetooth::listen() {
    if(available()){//check if there's any data sent from the remote bluetooth shield
        recvChar = read();
        //      Serial.print(recvChar);
        if(message.length() < MESSAGE_LENGTH) {
            message.concat(recvChar);
        }
    } else if(message.length() > 0){
            if(message.indexOf("+BTSTATE:1") >= 0) {
                state = DISCONNECTED;
                if(onDisconnect) onDisconnect();
            } else if(message.indexOf("+BTSTATE:4") >= 0) {
                state = CONNECTED;
                if(onConnect) onConnect();
                String temp = "blpins:D";
                temp.concat(rxPin);
                temp.concat("&D");
                temp.concat(txPin);
                send(temp);
                temp = "";
            } else if(message.indexOf("+BTSTATE:3") >= 0) {
            
            } else if(message.indexOf("CONNECT:OK") >= 0) {
                
            } else if(message.indexOf("ERROR") >= 0) {
                
            } else if(message.indexOf("pRQST") >= 0) {
                //Get Type Analog vs Digital
                (message.charAt(5) == 'A') ? type = 1 : type = 0;
                //Get state HIGH vs LOW
                if(message.indexOf("false") >= 0) isHigh = 0;
                else isHigh = 1;
                //Get Pin Number
                char *buffer = {"h"};
                message.substring(6,8).toCharArray(buffer, 3);
                pin = atoi(buffer);
                //Send data to callback
                if(onPin) onPin(type, pin, isHigh);
                if(type == 0) {
                    Serial.print("Requested:");
                    Serial.print("Digital Pin ");
                    Serial.print(pin);
                    Serial.print(" to ");
                    if(isHigh) Serial.println("HIGH");
                    else Serial.println("LOW");
                }
                else {
                    send((String)analogRead(pin));
                    Serial.print("Analog Pin ");
                    Serial.print(pin);
                    Serial.print(" Read ");
                    Serial.println(analogRead(pin));
                }
                buffer = NULL;
            }
            else if (onData) onData(message);
            message = "";
    }
}
Example #3
0
String getTimeString(time_t t = now())
{
  // String holder to return
  String dateStr;
  byte _day = weekday(t);
  byte sub1 = _day * 3;
  byte sub2 = sub1 + 3;
  dateStr = dayShortNames_P.substring(sub1, sub2);
  
  //Example "Sun "
  dateStr.concat(" ");

  int _hour = hour(t);
  if(_hour < 10) {
    dateStr.concat(" ");
  }
  dateStr.concat(_hour); // EX: "Sun 10"
  dateStr.concat(":");  // EX: "Sun 10:"
  
  int _minute = minute(t);
  if(_minute < 10) {
    dateStr.concat("0");
  }
  dateStr.concat(_minute); // EX: "Sun 10:1"
  dateStr.concat(":"); // EX: "Sun 10:1:"
  
  int _second = second(t);
  if(_second < 10) {
    dateStr.concat("0");
  }
  dateStr.concat(_second); // EX: "Sun 10:1:20"
  
  return dateStr;
}
Example #4
0
String WebServerTask::getColorCode(int value) {

    String s = String(value, HEX);
    String hexString = "\"#";

    for (int i = 6; i > s.length(); i--) {
        hexString.concat("0");
    }

    hexString.concat(s);

    hexString.concat("\"");

    return hexString;
}
Example #5
0
String String::operator+(const std::string& value)
{
	String temp = *this;
	temp.concat(value.c_str());

	return temp;
}
Example #6
0
String String::operator+(const String& value)
{
	String temp = *this;
	temp.concat(value.getString());

	return temp;
}
Example #7
0
int main() {
	String a = "Hello ", b = "world!";
	String c = a.concat(b);

	a.print();
	b.print();
	c.print();

	c.upper();
	c.print();

	String d= c.first(3);
	d.print();

	String e = c.last(3);
	e.print();

	String f = c.substr(4, 3);
	f.print();

	String g = "   trim  ";
	g.print();
	g.trim().print();

	(a + b).print();

	getc(stdin);

	return 0;
}
String thethingsiOClient_ti::read() {
    String received = "";
    if (subscription_client->connected()) {
        while (subscription_client->available())
            received.concat((char)subscription_client->read());
    }
    return received;
}
Example #9
0
void BootConfig::_onConfigRequest() {
  _interface->logger->logln(F("Received config request"));
  if (_flaggedForReboot) {
    _interface->logger->logln(F("✖ Device already configured"));
    String errorJson = String(FPSTR(PROGMEM_CONFIG_JSON_FAILURE_BEGINNING));
    errorJson.concat(F("Device already configured\"}"));
    _http.send(403, FPSTR(PROGMEM_CONFIG_APPLICATION_JSON), errorJson);
    return;
  }

  StaticJsonBuffer<MAX_JSON_CONFIG_ARDUINOJSON_BUFFER_SIZE> parseJsonBuffer;
  char* bodyCharArray = strdup(_http.arg("plain").c_str());
  JsonObject& parsedJson = parseJsonBuffer.parseObject(bodyCharArray);  // do not use plain String, else fails
  if (!parsedJson.success()) {
    free(bodyCharArray);
    _interface->logger->logln(F("✖ Invalid or too big JSON"));
    String errorJson = String(FPSTR(PROGMEM_CONFIG_JSON_FAILURE_BEGINNING));
    errorJson.concat(F("Invalid or too big JSON\"}"));
    _http.send(400, FPSTR(PROGMEM_CONFIG_APPLICATION_JSON), errorJson);
    return;
  }

  ConfigValidationResult configValidationResult = Helpers::validateConfig(parsedJson);
  if (!configValidationResult.valid) {
    free(bodyCharArray);
    _interface->logger->log(F("✖ Config file is not valid, reason: "));
    _interface->logger->logln(configValidationResult.reason);
    String errorJson = String(FPSTR(PROGMEM_CONFIG_JSON_FAILURE_BEGINNING));
    errorJson.concat(F("Config file is not valid, reason: "));
    errorJson.concat(configValidationResult.reason);
    errorJson.concat(F("\"}"));
    _http.send(400, FPSTR(PROGMEM_CONFIG_APPLICATION_JSON), errorJson);
    return;
  }

  free(bodyCharArray);
  _interface->config->write(_http.arg("plain").c_str());

  _interface->logger->logln(F("✔ Configured"));

  _http.send(200, FPSTR(PROGMEM_CONFIG_APPLICATION_JSON), F("{\"success\":true}"));

  _flaggedForReboot = true;  // We don't reboot immediately, otherwise the response above is not sent
  _flaggedForRebootAt = millis();
}
Example #10
0
Scheduler::Scheduler(unsigned int maxTasks, AbstractDebug * debug) {
	this->debug = debug;
#else
Scheduler::Scheduler(unsigned int maxTasks) {
#endif

	this->queue = new ArrayQueue<AbstractTask*>(maxTasks);

#ifdef MYSPECIALDEBUGCONSTANT
	this->debug->info("Scheduler::Scheduler: Constructed Scheduler:");
	String message ("Scheduler::Scheduler: maxTasks: ");
	message.concat(maxTasks);
	this->debug->info(message);
	message = "Scheduler::Scheduler: tasksScheduled: ";
	message.concat(this->queue->getSize());
	this->debug->info(message);
#endif

}
String thethingsiOClient_ti::read(String key, int limit) {
    String received = "";
    if (regular_client->connect(server, 80)) {
        GET(regular_client, "/v2/things/" + token + "/resources/" + key + "?limit=" + String(limit));
        delay(1000);
        while (regular_client->available())
            received.concat((char)regular_client->read());
        regular_client->stop();
    }
    return received;
}
Example #12
0
String String::operator+(const char* value)
{
	if (value == nullptr)
	{
		return *this;
	}

	String temp = *this;
	temp.concat(value);

	return temp;
}
Example #13
0
// TODO read through this and find out why it's got the 'concat('|')'.
String Robot::talkHear()
{
  String info;
  char temp;
  while (XBee.available() > 0)
  {
    temp = XBee.read();
    info = info.concat(temp);
  }

  return info;  
}
String thethingsiOClient_ti::send() {
    String received = "";
    if (POST(regular_client, "/v2/things/" + token, "{\"values\":[" + data + "]}")) {
        data = "";
        delay(1000);
        while (regular_client->available()) {
            char c = (char)regular_client->read();
            received.concat(c);
        }
    }
    return received;
}
Example #15
0
String getTimeString(schedule &s)
{
  // String holder to return
  String dateStr;
  byte _day = s.day;
  byte sub1 = _day * 3;
  byte sub2 = sub1 + 3;
  dateStr = dayShortNames_P.substring(sub1, sub2);
  
  //Example "Sun "
  dateStr.concat(" ");

  int _hour = s.hour;
  if(_hour < 10) {
    dateStr.concat(" ");
  }
  dateStr.concat(_hour); // EX: "Sun 10"
  dateStr.concat(":");  // EX: "Sun 10:"
  
  int _minute = s.minute;
  if(_minute < 10) {
    dateStr.concat("0");
  }
  dateStr.concat(_minute); // EX: "Sun 10:1"
    
  return dateStr;
}
Example #16
0
/**
For now tasks should be scheduled in chromatic order.
So first tasks in front
**/
bool Scheduler::scheduleTask(AbstractTask * task) {
	bool retVal = this->queue->push(task);

	if(!retVal) {

#ifdef MYSPECIALDEBUGCONSTANT
		this->debug->error("Scheduler::scheduleTask: Task queue is full!");
#endif

		return false;
	}

#ifdef MYSPECIALDEBUGCONSTANT
	this->debug->info("Scheduler::scheduleTask: Scheduled new task.");
	String message ("Scheduler::scheduleTask: Task scheduled at: ");
	message.concat(task->getExecutionTime());
	this->debug->info(message);
	message = "Scheduler::scheduleTask: tasksScheduled: ";
	message.concat(this->queue->getSize());
	this->debug->info(message);
#endif

	return true;
}
//Costum Function To Retrieve Date Time From Server
String thethingsiOClient_ti::readTime(String format) {
	int start;   
	int end; 
	String received = "";

    if (regular_client->connect(server, 80)) {
        GET(regular_client, "/v2/utils/date?thingToken=" + token + "&format=" + format);
        delay(1000);
        while (regular_client->available())
            received.concat((char)regular_client->read());
        regular_client->stop();
    }

//Retrieve the Time from Response
	String dummy = "value";
	dummy.concat('"');
	dummy.concat(':');
	start = received.lastIndexOf(dummy) + dummy.length();
	end	  = received.lastIndexOf("]") - 1;
	received = received.substring(start,end);

//
    return received;
}
Example #18
0
int main() {

	String foo = newString("This is FOO!");
	foo = foo.insertCharAt(&foo,'a',foo.length(&foo) - 1);
	foo.printString(&foo);


	foo = foo.substring(&foo,8,10);
	foo.printString(&foo);

	String bar = newString(" BAR");
	foo = foo.concat(&foo,&bar);
	foo.printString(&foo);

	StringArr foobar = split(&foo, " ");
	printf("%s\n",foobar[0]);
	printf("%s\n",foobar[1]);

	foo = foo.toLowerCase(&foo);
	bar = bar.toLowerCase(&bar);
	bar = bar.removeSpaces(&bar);
	foo.printString(&foo);
	bar.printString(&bar);

	if(foo.equals(&foo,&bar))
		printf("Same!\n");
	else
		printf("Not the same!\n");

	bar = newString("foo");

	if(foo.equals(&foo,&bar))
		printf("Same!\n");
	else
		printf("Not the same!\n");

	foo = foo.reverse(&foo);
	foo.printString(&foo);

	printf("%c\n",foo.charAt(&foo,1));

	bar = newString("bar");
	bar = bar.toUpperCase(&bar);
	printString(&bar);

}
Example #19
0
String Return_String(uint8_t addr, uint8_t maxlenght)
{
    byte counter=0;
    char rChar;
    String retString = "";

    while (counter < maxlenght)
    {
        rChar = EEPROM.read(addr + counter);
        if (rChar == 0) break;
        if (counter > 31) break;
        counter++;
        retString.concat(rChar);

    }
    return retString;
}
Example #20
0
void check_serial_cmd()
{
	while (Serial.available())
	{
		delay(1);
		static String command;
		char input = Serial.read();

		if (input == '\r')
		{

		} 
		else if (input == '\n')
		{
			if (command.equals(("size")))
			{
				PTS("Schedule size: ");
				PTL(node_size());
			} else if (command.equals(("mem"))) {
				PTLS("Reading");
				for (int i = 0; i < MAX_NODE; i++) {
					schedule s = node_get(i);
					PT(i); PTS(", ");
					PT(s.day); PTS(", ");
					PT(s.hour); PTS(", ");
					PT(s.minute); PTS(", ");
					PT(s.temperature); PTL();
				}
			} else if (command.equals(("RESET"))) {
				PTLS("Resetting Memory");
				node_RESET();
			}
			command = "";
		}
		else
		{
			command.concat(input);
		}

	}
}
Example #21
0
void ROTankWire::Receive(int bytes) {
    //!!DONT PUT SERIAL.PRINTS IN HERE IT WILL SCREW UP WIRE COMM!!

    _wireRequest = "";
    _cmd = "";
    _cmdData = "";
    if(bytes == _wireReqLength) {
        while (Wire.available() > 0) {
            char c = Wire.read();
            _wireRequest.concat(c);
        }
        //Serial.print("Wire Request: ");
        //Serial.println(_wireRequest);
        _wireRequest.trim();
        if(_wireRequest.startsWith("/")) {
            _cmd = _wireRequest;
            Serial.print(F("cmd: "));
            Serial.println(_cmd);
        }
        else {
            _cmdData = _wireRequest;
            Serial.print(F("cmdData: "));
            Serial.println(_cmdData);
            String var = SplitString(_cmdData, '=', 0);
            String val = SplitString(_cmdData, '=', 1);

            if(val == "-") { // means null value sent in, so do nothing with cmd.
                //Transmit("-");
                return;
            }

            handleCmd(var, val);
        }
    }
    else {
        Serial.print(F("Unexpected number of bytes received: "));
        Serial.println(bytes);
    }
}
Example #22
0
String wifiChat::checkForRequest()
{
  tryConnect();
  String requestString = "";
  WiFiClient client = server.available();
  Serial.print(client);
  if(!client) 
    return requestString;

  //Serial.print("Client.available() = ");
  //Serial.print(client.available());
  if (client.available() > 0) {
    
    char thisChar = client.read();
    while(thisChar != '\n' && client.available() > 0)
    {
      requestString.concat(thisChar);
      thisChar = client.read();
    }
  }
  return requestString;
    
}
 void VirtuinoEthernet_WebServer::run(){
    EthernetServer server(serverPort);  
    EthernetClient client = server.available();
  if (client) {
    char c;
   if (DEBUG) Serial.println(clientConnected);
    
    while (client.connected()) {
      if (client.available()) {
        c = client.read();
        lineBuffer.concat(c);
        if (DEBUG)  Serial.write(c);
      }
      if (c == '\n' ) {
              int pos = lineBuffer.indexOf("GET /");
              if (pos!=-1){                                   // We have a GET message
                   if (DEBUG) Serial.println("\n\r LineBuffer="+lineBuffer);
                  String responce = checkNetworkCommand(lineBuffer.substring(pos+5));
                   if (DEBUG) Serial.println("\n\r Responce="+responce);
                  delay(10);
                  client.flush();
                  client.println("HTTP/1.1 200 OK");
                  client.println("Content-Type: text/html");
                  client.println("Connection: close");
                  client.println();
                  client.println(responce);
                  lineBuffer="";
                  break;
                } // if pos
             lineBuffer="";
        } // if c=='\n'
    } // if client.available
    delay(1);
    client.stop();  // close the connection:
    if (DEBUG) Serial.println(clientDisconnected);
  }
  }
Example #24
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;
  
}
Example #25
0
void loop() {
    // after 2 seconds button push, enter set_time_mode
    if( set_time_mode == false and waiting_for_release == true and ( millis() - time_last_push ) > 2000 )
    {
        Serial.println( "set_time_mode => true" );
        set_time_mode = true;
        brew_for_minutes = 0;
        moveServoDown( 90 );
        time_last_push = millis();
    }

    if( set_time_mode == true and waiting_for_release == false and ( millis() - time_last_push ) > 5000 )
    {
        Serial.println( "set_time_mode => false" );
        set_time_mode = false;

        // brew_for_minutes of 0 (no time set) is illegal, so set to 1
        if( brew_for_minutes == 0 ){
            brew_for_minutes = 1;
        }
        for( uint16_t i = 0; i < brew_for_minutes; i++ ){
            moveServoDown( 30 );
        }
    }

    if( jiggle_servo_down == true ){
        moveServoDown( 10 );
        jiggle_servo_down = false;
    }

    // If coming back from sleep
    if( running_since < 0 ){
        WiFi.off();
        pinMode( BUTTON_PIN, INPUT_PULLUP);
        attachInterrupt( BUTTON_PIN, buttonIRQ, CHANGE );
        running_since = millis();
        brewing = false;
        jiggle_servo_down = true;
    }

    // brew_for_minutes is in minutes, so it should eventually be * 60000
    if( brewing == true and millis() > brew_finish_time )
    {
        Serial.println( "Tea is finished" );
        tea_servo.write( position_up );
        Particle.connect();
        while( not Particle.connected() ){
            delay( 100 );
        }
        String json = "{\"tea\":\"finished\",\"brew_time\":";
        json.concat( brew_for_minutes );
        json.concat( "}" );
        Particle.publish( "tea", json );
        Serial.println( "Going to sleep now..." );
        running_since = -1;
        brewing = false;
        // Give the servo time to act before sleeping
        delay( 1000 );
        System.sleep( BUTTON_PIN, FALLING );
    }
    if( brewing == false and ( millis() - running_since ) > sleep_after ){
        Serial.println( "Going to sleep now..." );
        running_since = -1;
        delay( 10 );
        System.sleep( BUTTON_PIN, FALLING );
    }
}
Example #26
0
void Robot::talkSend(String info)
{
  info = info.concat("|");
  XBee.print(info);
}
Example #27
0
void WebServerTask::handleSettingsGet() {

    String json = "{";
    
    json.concat("\"timezone\":" + String(DataStore.get(DS_TIMEZONE)));
    json.concat(",\"brightness\":" + String(DataStore.get(DS_BRIGHTNESS)));
    json.concat(",\"hour_color\":" + getColorCode(DataStore.get(DS_HOUR_COLOR)));
    json.concat(",\"minute_color\":" + getColorCode(DataStore.get(DS_MINUTE_COLOR)));
    json.concat(",\"second_color\":" + getColorCode(DataStore.get(DS_SECOND_COLOR)));
    json.concat(",\"animation\":" + String(DataStore.get(DS_CLOCK_ANIMATION)));

    json.concat(",\"night_mode\":{");
        json.concat("\"enabled\":" + String(DataStore.get(DS_NIGHT_MODE_ENABLE)));
        json.concat(",\"brightness\":" + String(DataStore.get(DS_NIGHT_MODE_BRIGHTNESS)));
    json.concat("}");

    int i = DataStore.get(DS_GAMMA);
    float gamma = *reinterpret_cast<float*>(&i);
    json.concat(",\"gamma\":" + String(gamma));

    json.concat("}");
    
    server.send(200, "application/json", json);
}
// The loop function is called in an endless loop
void loop() {



	// if there's incoming data from the net connection.
	// send it out the serial port. This is for debugging
	// purposes only:
	if (client.available()) {
		char c = client.read();
		Serial.print(c);
	}

	// if there's no net connection, but there was one last time
	// through the loop, then stop the client:
	if (!client.connected() && wasConnected) {
		Serial.println();
		Serial.println("disconnecting.");
		client.stop();
		wasConnected = false;
	}

	if (PowerSerial::solar.count < 0) {
		int waitTime = millis() - lastupdate;
		if (waitTime > 30000) {
			String jsonResult = PowerSerial::solar.jsonResult;
			Serial.println("transmit Every 30 seconds");
			lastupdate = millis();

			lmillis = tmillis; //timing to determine amount of time since last call
			tmillis = millis();

			delay(1000);
			if (!client.connected()) {
				Serial.println(jsonResult);
				// if there's a successful connection:
				Serial.println("!client.connected() --> 1");

//				DNSClient dns;
//				IPAddress remote_addr;
//				dns.begin(Ethernet.dnsServerIP());
//				int ret = dns.getHostByName(serverName, remote_addr);
//				  if (ret == 1) {
//				    Serial.println(serverName);
//				    Serial.println(remote_addr);
//				  } else {
//					    Serial.println("Fail !!!");
//				  }


				if (client.connect(serverName, 80)) {
					delay(1000);
					Serial.println("!client.connect() --> 2");
					wasConnected = true;
					Serial.println("connecting...");
					// send the HTTP PUT request:
					String str = "GET ";
						str.concat(input);
    					str.concat(apikey);
						str.concat(inputJson);
						str.concat(jsonResult);
						str.concat(" HTTP/1.0");

					client.println(str);
					client.println("Host: emoncms.org");
					client.println("User-Agent: arduino-ethernet");
					client.println("Connection: close");
					client.println();
					client.flush();
					Serial.println(str);
					Serial.println("Respons:");
					Serial.println(client.readString());
					PowerSerial::solar.count = 0;
				} else {
					delay(1000);
					// if you couldn't make a connection:
					Serial.println("connection failed");
					Serial.println();
					Serial.println("disconnecting.");
					client.stop();
				}

			}
		} else {
//			Serial.print("Still waiting: ");
//			Serial.println(waitTime);
		}
	} else {
		Serial.println("Powerserial has no result .... waiting: ");
	}

	if (PowerSerial::solar.count >= 0){
		PowerSerial::parse();
	}

}
String thethingsiOClient_ti::activate(String activationCode) {
    token = "";
    String body = "";
    String find_token = "thingToken\":\"";
    int start;
    char c;
    if (POST(regular_client, "/v2/things/", "{ \"activationCode\":\"" + activationCode + "\"}")) {
        delay(1000);
        while (regular_client->available() && (c = (char)regular_client->read()) != '{');
        if (c == '{') {
            while (regular_client->available() && (c = (char)regular_client->read()) != '\n') body.concat(c);
            if ((start = body.indexOf(find_token)) >= 0) {
                start = start + find_token.length();
                token = body.substring(start, start + TOKEN_SIZE);
            }
        }
    }
    return token;
}