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;
}
Example #2
0
bool ClientHandler::initClientHandler(String httpMethod, char *server, int serverPort, String path) {
  _server = server;
  _path = path;
  resetRequest();

  int connected = 0;
  while (!connected) {
    Serial.println("Trying connection");
    if (_client->connect(_server, serverPort)) {
      Serial.println("connected");
      connected = 1;
    } 
    else {
      Serial.println("connection failed");
      _requestReady = false;
      return _requestReady;
    }
  }

  String requestLine = httpMethod + " ";
  requestLine.concat(path);
  requestLine.concat(" HTTP/1.1");
  String hostLine = "Host: " + String(server);
  _client->println(requestLine);
  _client->println(hostLine);

  _requestReady = true;
  return _requestReady;
}
Example #3
0
void AsiMS2000::where()
{
    int arglen = _args.length();
    char buffer [25];
    if(arglen == 0)
    {
      _isAxis.x = true;
      _isAxis.y = true;
      _isAxis.z = true;
    }
    
    String response = ":A ";
    //char buffer [25];
    if(_isAxis.x) 
    {
      
      dtostrf(AsiSettings.currentPos.x,1,1,buffer);
      response.concat(String(buffer) + " ");
    }
  
    if(_isAxis.y) 
    {
      dtostrf(AsiSettings.currentPos.y,1,1,buffer);
      response.concat(String(buffer) + " ");
    }
    
    if(_isAxis.z) 
    {
      dtostrf(AsiSettings.currentPos.z,1,1,buffer);
      response.concat(String(buffer) + " ");
    }
  
    serialPrintln(response);
}
Example #4
0
File create_gps_file() {
	int year;
	unsigned long age;
	byte month, day, hour, minute, second, hundredth;
	gps.crack_datetime(&year, &month, &day, &hour, &minute, &second, &hundredth, &age);

	String filename;
	filename.concat(GPS_DIR);
	filename.concat('/');
	filename.concat(year);
	filename.concat('/');
	filename.concat(month);
	filename.concat('/');
	filename.concat(day);
	filename.concat('/');
	filename.concat(hour);
	filename.concat(minute);
	filename.concat(second);
	filename.concat(".GPS");

	char buf[filename.length() + 1];
	filename.toCharArray(buf, sizeof(buf));

	Serial.print("Criando arquivo... ");
	Serial.println(buf);
	return create_file(buf);
}
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 #6
0
String Turret::toString(void)
{
	String str = "Azimuth: ";
	str.concat(_position.azimuth);
	str.concat(" Elevation: ");
	str.concat(_position.elevation);
	str.concat(" Weapon: ");
	str.concat(_motorPowerState);
	return str;
}
Example #7
0
// -------- Functions --------------------
char *formatTempToBody(float temperature, int tempIndex) {
    static char retbuf[64];
    String s = "{\"value\": ";
    s.concat(String(temperature));
    s.concat("}");
    s.toCharArray(retbuf, 64);
    oDispatch(tempIndex, temperature);
    return retbuf;

}
Example #8
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 #9
0
String IPAddress::toString()
{
	String res;
    for (int i =0; i < 3; i++)
    {
    	res.concat(_address[i]);
    	res.concat('.');
    }
    res.concat(_address[3]);
    return res;
}
Example #10
0
	void testConcat() {
		const String hello("Hello");
		const String space(", ");
		const String world("world!");
		const String target("Hello, world!");

		CPPUNIT_ASSERT_EQUAL(hello, String::Empty.concat(hello));
		CPPUNIT_ASSERT_EQUAL(hello, hello.concat(String::Empty));

		CPPUNIT_ASSERT_EQUAL(target, hello.concat(space.concat(world)));
        CPPUNIT_ASSERT_EQUAL(target, hello.concat(", world!"));
	}
Example #11
0
String Dose::GetTime()
{
	String newTime = "";
	newTime.concat(name);
	newTime.concat(" at ");
	String daTime = String(pillTime);
	
	newTime.concat(daTime.substring(0,2));
	newTime.concat(":");
	newTime.concat(daTime.substring(2));
	return newTime;
}
Example #12
0
void SCC_1080::bargraph(int input) {
  mdbStart();
  //takes int from 0 to 99, graphs on given line
  String bar = "";
  if (input < 10) {
    bar.concat("0");
  }
  bar.concat(input);
  (*_port).write(0x1b);
  (*_port).write(0x35);
  (*_port).print(bar);
  mdbEnd();
}
void NetworkConnectionClass::getConfigData()
{
  String name = "";
  String value = "";
  boolean isValue = false;
  char character;
  SensorData *data;
  while (client.available() > 0) {
    character = client.read();
    if (character == '{') {
      data = new SensorData();
      name = "";
      value = "";
      isValue = false;
      continue;
    }
    if (character == ',' || character == '}') {
      if (name.equals("name")) {
        data->name = value;
      }
      else if (name.equals("code")) {
        data->code = value.toInt();
      }
      else if (name.equals("threshold")) {
        data->treshold = value.toInt();
      }
      else if (name.equals("pin")) {
        data->pin = getIntValue(value);
      }
      Serial.println(value);
      name = "";
      value = "";
      isValue = false;
      if (character == '}') {
        data->oldValue = 0;
        sensorData->insert(data);
      }
      continue;
    }
    if (character == ':') {
      isValue = true;
      continue;
    }
    if (!isValue) {
      name.concat(character);
    }
    else {
      value.concat(character);
    }
  }
}
Example #14
0
void GM862::deleteMessage(String index){
    char buf[BUF_LENGTH];
    char cmdBuf[BUF_LENGTH];
    char delflag;
    String cmd = "AT+CMGD=";
    if(index.equalsIgnoreCase("0")){
        cmd.concat("1,3");  // delete all read messages from <memr> storage, sent and unsent mobile originated messages, leaving unread messages untouched
    } else {
        index.concat(",0");
        cmd.concat(index);
    }
    cmd.toCharArray(cmdBuf,BUF_LENGTH);
    requestModem(cmdBuf, 2000,true,buf);
}
Example #15
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;
}
// Adequate to most situations, unless the user has adjust the CMD_TO value.
//  The default value of CMD_TO means that at least 400ms must elapse before
//  the $$$$ for exiting data mode will be recognized. You also need to wait
//  400ms AFTER issuing it, but that's handled by us waiting for the OK
//  response. 
BC127::opResult BC127::exitDataMode(int guardDelay)
{
  String buffer;
  String EOL = String("\n\r"); // This is just handy.
  
  delay(guardDelay);
  
  _serialPort->print("$$$$");
  _serialPort->flush();
  
  // We're going to use the internal timer to track the elapsed time since we
  //  issued the command. Bog-standard Arduino stuff.
  unsigned long loopStart = millis();
  
  // This is our timeout loop. We'll give the module 2 seconds to exit data mode.
  while (loopStart + 2000 > millis())
  {
    // Grow the current buffered data, until we receive the EOL string.    
    if (_serialPort->available() >0) buffer.concat(char(_serialPort->read()));

    if (buffer.endsWith(EOL))
    {
      if (buffer.startsWith("OK")) return SUCCESS;
      buffer = "";
    }    
  }
  return TIMEOUT_ERROR;
}
char* MtkHttpClient::sendHTTP(const char *request, const char* serverUrl, int port)
{
    /* Arduino String to build the response with. */
    String responseBuilder = "";
    if (client.connect(serverUrl, port)) {
        /* Send the requests */
        client.println(request);
        client.println();
        /* Read the request into responseBuilder. */
        delay(delayTime);
        while (client.available()) {
            char c = client.read();
            responseBuilder.concat(c);
        }
        client.stop();
    } else {
        client.stop();
        /* Error connecting. */
        return 0;
    }
    /* Copy responseBuilder into char* */
    int len = responseBuilder.length();
    char* response = new char[len + 1]();
    responseBuilder.toCharArray(response, len + 1);
    return response;
}
void VirtuinoEsp8266_WebServer::wifiRun(){
   if(espSerial->available()){                       
    char c=espSerial->read();
    commandBuffer.concat(c);
    if (c=='\n') {                                            // check command line to line
          if (DEBUG) Serial.print(commandBuffer);
          int pos = commandBuffer.indexOf("+IPD,");
          if (pos>=0){                                        // check for GET command from Virtuino app
              clearESP_buffer(500);
              int connectionId = commandBuffer.charAt(pos+5)-48;  // get connection ID
              if (DEBUG) Serial.println("ID="+ String(connectionId));
              pos = commandBuffer.indexOf("GET /");
              if (pos!=-1){                                   // We have a GET message
                  String responce = checkNetworkCommand(commandBuffer.substring(pos+5));
                  boolean b=wifiSendData(connectionId,responce);
                  // -----------  Close client connection     -------------
                  clearESP_buffer(100);
                  closeClientConnection(connectionId);           
                    
                  
              } 
          } 
        
        commandBuffer="";                                     // clear buffer for the next line
  
      }  
    
   }
}
// Create a known state for the module to start from. If a partial command is
//  already in the module's buffer, we can purge it by sending an EOL to the
//  the module. If not, we'll just get an error.
BLEMate2::opResult BLEMate2::knownStart()
{
  String EOL = String("\n\r");
  String buffer = "";
  
  _serialPort->print("\r");
  _serialPort->flush();
  
  // We're going to use the internal timer to track the elapsed time since we
  //  issued the reset. Bog-standard Arduino stuff.
  unsigned long startTime = millis();
  
  // This is our timeout loop. We're going to give our module 1s to come up
  //  with a new character, and return with a timeout failure otherwise.
  while (buffer.endsWith(EOL) != true)
  {
    // Purge the serial data received from the module, along with any data in
    //  the buffer at the time this command was sent.
    if (_serialPort->available() > 0) 
    {
      buffer.concat(char(_serialPort->read()));
      startTime = millis();
    }
    if ((startTime + 1000) < millis()) return TIMEOUT_ERROR;
  }
  if (buffer.startsWith("ERR")) return SUCCESS;
  else return SUCCESS;
}
// Similar to the command function, let's do a set parameter genrealization.
BLEMate2::opResult BLEMate2::stdSetParam(String command, String param)
{
  String buffer;
  String EOL = String("\n\r");
  
  knownStart();  // Clear Arduino and module serial buffers.
  
  _serialPort->print("SET ");
  _serialPort->print(command);
  _serialPort->print("=");
  _serialPort->print(param);
  _serialPort->print("\r");
  _serialPort->flush();
  
  // We're going to use the internal timer to track the elapsed time since we
  //  issued the reset. Bog-standard Arduino stuff.
  unsigned long startTime = millis();
  
  // This is our timeout loop. We'll give the module 2 seconds to reset.
  while ((startTime + 2000) > millis())
  {
    // Grow the current buffered data, until we receive the EOL string.    
    if (_serialPort->available() >0) buffer.concat(char(_serialPort->read()));

    if (buffer.endsWith(EOL))
    {
      if (buffer.startsWith("ER")) return MODULE_ERROR;
      else if (buffer.startsWith("OK")) return SUCCESS;
      buffer = "";
    }    
  }
  return TIMEOUT_ERROR;
}
Example #21
0
BLEMate2::opResult BLEMate2::disconnect()
{
  String buffer;
  String EOL = String("\n\r"); // This is just handy.
  
  knownStart();
  _serialPort->print("DCN\r"); 
  _serialPort->flush();
  
  // We're going to use the internal timer to track the elapsed time since we
  //  issued the connect command. Bog-standard Arduino stuff.
  unsigned long disconnectStart = millis();
  
  buffer = "";

  // The timeout on this is 5 seconds; that may be a bit long.
  while (disconnectStart + 5000 > millis())
  {
    // Grow the current buffered data, until we receive the EOL string.    
    if (_serialPort->available() >0) buffer.concat(char(_serialPort->read()));
    
    if (buffer.endsWith(EOL))
    {
      if (buffer.startsWith("ERR")) return MODULE_ERROR;
      if (buffer.startsWith("DCN")) 
      {
        stdCmd("SCN OFF"); 
        return SUCCESS;
      }
      buffer = "";    
    }
  }
  return TIMEOUT_ERROR;
}
Example #22
0
String String::operator+(const String& value)
{
	String temp = *this;
	temp.concat(value.getString());

	return temp;
}
Example #23
0
/**
Chops off the end of the menu string if it's too long given the number of characters
taken up by the value. Displaying the value takes priority over displaying the menustring 
*/
String Menu::menuString(){
  byte usableCols=_lcdCols-2; 

  //Find the maximum number of digits (including minus sign for negative numbers)
  short maxVal=_maxVal;
  short minVal=_minVal;

  if (maxVal==0){ maxVal++; } //cope with zero
  if (minVal==0){ minVal++; } //cope with zero

  byte maxChars=ceil(log10(abs(minVal)+1));
  byte minChars=ceil(log10(abs(maxVal)+1));

  if (_maxVal<0){ maxChars++; }
  if (_minVal<0){ minChars++; }

  byte maxDigits;
  if (maxChars>minChars){
    maxDigits=maxChars;
  } else {
    maxDigits=minChars;
  }

  int maxStringLength = usableCols - maxDigits-1;
  String tmpStr = _menuString;
  if (tmpStr.length() > maxStringLength){
    tmpStr = _menuString.substring(0,maxStringLength);
    tmpStr.concat(":");
  }
 
  return tmpStr;
}
Example #24
0
String String::operator+(const std::string& value)
{
	String temp = *this;
	temp.concat(value.c_str());

	return temp;
}
Example #25
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;
}
Example #26
0
void loop() {
  String content = "";
  char character;
  while(Serial.available()) { // Read from serial, if available, continue.
    character = Serial.read();
    content.concat(character);
  }
  if (content != "") {
    Serial.println(content);
    String ledToChange = getValue(content, '=', 0);
    String ledValueStr = getValue(content, '=', 1);
    int ledValueInt = ledValueStr.toInt();
    Serial.println("Changing led " + ledToChange + " to value " + ledValueStr);
    ledToChange.toLowerCase();
    if(ledToChange == "r" || ledToChange == "red") {
      analogWrite(RED_PORT, ledValueInt);
    } 
    else if (ledToChange == "g" || ledToChange == "green") {
      analogWrite(GREEN_PORT, ledValueInt);
    }  
    else if (ledToChange == "b" || ledToChange == "blue") {
      analogWrite(BLUE_PORT, ledValueInt);
    } 
    else if (ledToChange == "off") {
      analogWrite(RED_PORT, 0);
      analogWrite(GREEN_PORT, 0);
      analogWrite(BLUE_PORT, 0);
    }
  } 
  delay(100); // Just to be safe, we delay every 100miliseconds
}
Example #27
0
// Detects an incoming RFID. Returns 1 if a known ID is detected, 0 otherwise.
int Skyscraper::readRFID() {
  Serial.println("Tower "+String(_id)+":");

  String rfid = ""; // stores RFID string
  char val = 0; // stores incoming character
  int counter = 0;  // breaks loop if no RFID

  // reset readers
  for (int i = 3; i < 8; i++) {
    if (i == _rfidPin) {
      // Serial.println("  digitalWrite("+String(i)+", HIGH);");
      digitalWrite(i, HIGH);
    }
    else {
      // Serial.println("  digitalWrite("+String(i)+", LOW);");
      digitalWrite(i, LOW);
    }
  }
  delay(300);

  // read the serial port
  while (Serial.available()) {
    if (counter > 20 || rfid.length() == 12) {
      break;
    }
    else {
      val = Serial.read();
      if (isalnum(val)) rfid.concat(val);
      counter++;
    }
  }

  Serial.println("  rfid:"+rfid);
  
  // check color
  for (int i = 0; i < NUM_RINGS; i++) {
    if (rfid == clean(redID[i])) {
      Serial.println("  detected red!");
      if (_color != "red") {
        analogWrite(_red, 255); 
        analogWrite(_blue, 0);
        _color = "red";
      }
      turnServo();
      return 1;
    }
    else if (rfid == clean(blueID[i])) {
      Serial.println("  detected blue!");
      if (_color != "blue") {
        analogWrite(_red, 0); 
        analogWrite(_blue, 255);
        _color = "blue";
      }
      turnServo();
      return 1;
    }
  }

  return 0; // no rfid detected
}
Example #28
0
void temperatureJob() {
    float gotTemp = 0;
    Serial << "the device count is " << deviceCount << endl;
    sensor.requestTemperatures();  // get all the tempratures first to speed up, moved up from getTemp()
    for (int i =0; i < deviceCount; i++ ) {
        gotTemp = sensor.getTempF(*deviceAddressArray[i]);
        if (gotTemp < -195 ) continue;
        if (i+1 == 1 ) temp1 = gotTemp;
        if (i+1 == 2 ) temp2 = gotTemp;
        if (i+1 == 3 ) temp3 = gotTemp;
        if (i+1 == 4 ) temp4 = gotTemp;
        Serial << "gotTemp() = "  << i << " " << gotTemp << endl;
        request.body = formatTempToBody(gotTemp, i);
      //  if (mycounter % PUSHFREQ == 0  && PUSHTOUBIFLAG == 1 ) {
       if (mycounter % PUSHFREQ == 0  && PUSHTOUBIFLAG == 1 ) {
            String mypath = String("/api/v1.6/variables/");
            mypath.concat(ubivar[i]);
            mypath.concat("/values");
            Serial << "going to push "<< request.body << " to " << mypath << endl;
            request.path = mypath;
            http.post(request, response, headers);
            if( debug ) Serial << "http body: " << request.body << endl;

            Serial << " Did we reboot?    I hope not ";
        }
      if( debug) debugSerial(i);

    }
}
Example #29
0
void CardLogger::init() {
  while (!Serial) {
  }

  pinMode(chipSelect, OUTPUT);

  if (!SD.begin(chipSelect)) {
    return;
  }

  String directoryPreFix = "log_";

  for (int i = 0; i <= 500; i++) {

    String dir  = directoryPreFix;
    dir.concat(i);
    char charDir[dir.length()+1];
    dir.toCharArray(charDir, sizeof(charDir));

    if (!SD.exists(charDir)) {
      if(SD.mkdir(charDir)) {
        directory =  String(charDir);
        break;
      } 

    }
  }
}
Example #30
0
void Display::showPour(float p, boolean isOz) {
  String s = String(p, 1);
  s.concat(isOz ? "oz" : "L");
  writeCenter(2, s, String("Enjoy!"));

  lastMessageTs = millis();
  lastMessageDelay = pourMessageDelay;
}