Example #1
0
	void checkLootGroupEntryRecursive(LootGroupMap* lootGroupMap, String& entryName, Vector<String>* parentGroups) {
		if (entryName.isEmpty())
			return;

		//Check for infinite recursion
		for (int i = 0; i < parentGroups->size(); i++) {
			String parentName = parentGroups->get(i);

			EXPECT_FALSE( parentName == entryName ) << "Loot group " << std::string(parentName.toCharArray()) << " failed recursion check.";

			if (parentName == entryName)
				return;
		}

		if (lootGroupMap->lootGroupExists(entryName)) {

			LootGroupTemplate* lootGroupTemplate = lootGroupMap->getLootGroupTemplate(entryName);

			for (int j = 0; j < lootGroupTemplate->size(); j++) {

				String entry = lootGroupTemplate->getLootGroupEntryAt(j);

				parentGroups->add(entryName);

				checkLootGroupEntryRecursive(lootGroupMap, entry, parentGroups);
			}

		} else {
			Reference<LootItemTemplate*> itemTemplate = lootGroupMap->getLootItemTemplate( entryName );
			EXPECT_TRUE( itemTemplate != NULL ) << "Item template " << std::string(entryName.toCharArray()) << " from " << std::string(parentGroups->get(parentGroups->size() - 1).toCharArray()) << " was not found in LootGroupMap";
		}
	}
Example #2
0
void WipeCommand::rm(File dir, String tempPath) {
  while(true) {
    File entry =  dir.openNextFile();
    String localPath;

    if (entry) {
      if (entry.isDirectory()) {
        localPath = tempPath + entry.name() + "/" + '\0';
        char folderBuf[localPath.length()];
        localPath.toCharArray(folderBuf, localPath.length());
        rm(entry, folderBuf);
        SD.rmdir(folderBuf);
      }
      else {
        localPath = tempPath + entry.name() + '\0';
        char charBuf[localPath.length()];
        localPath.toCharArray(charBuf, localPath.length() );
        SD.remove(charBuf);
      }
    } 
    else {
      break; // break out of recursion when finished
    }
  }
}
Example #3
0
void NTGVS1053::NTGVS1053Setup(){


	ntgRFIDReader.NTGRFIDReaderSetup();




	//Verify all components.
	if(!vs1053.begin()){

	}

	if(!vs1053.useInterrupt(VS1053_FILEPLAYER_PIN_INT)){

	}

	if(!SD.begin(CARDCS)){

	}

	//Print the directory inside the Sd card into Serial console.
	DebugPrintFileDirectory(SD.open("/"), 0);
	//Set the default volume.
	vs1053.setVolume(20, 20);
	//Set the default .mp3 file.
	mp3IndexBufferString = String(mp3Index) + ".mp3";
	mp3IndexBufferString.toCharArray(mp3IndexBufferCharArray, 50);
	Play(mp3IndexBufferCharArray);

}
Example #4
0
void VDRIVE2::WriteFileString(String DATA, bool n) {
    byte cr = 0x0d;
    char data[DATA.length()+1];
    DATA.toCharArray(data, DATA.length()+1);
    Serial1.print("WRF ");
    int Size = DATA.length()+2;
    Serial1.print(Size, DEC);
    Serial1.write(cr);
    int i = 0;
    while (i < DATA.length()+1) {
      Serial1.write(data[i]);
      i++;
    }
    Serial1.write(0x0a); //LineFeed
    Serial1.write(cr);
    delay(10);
    
    digitalWrite(_CTS, LOW);
    while (Serial1.available() > 0) {
		if (n == true) {
			char a = Serial1.read();
			if (a == 0x0d) {
				Serial.println();
			}
			else {
				Serial.write(a);
			}
		}
		else {
			Serial1.read();
		}
	}
    delay(10);
    digitalWrite(_CTS, HIGH);
}
Example #5
0
int WalnutCentral::addDevice(BluetoothDeviceAddress address) {
    char tx[MAX_BUF_SIZE];
    char rx[MAX_BUF_SIZE];
    int rx_len = 0;
  

    String tempStr = "AT+DEVADD=" + address.toString();
    tempStr.toCharArray(tx, MAX_BUF_SIZE);
    #ifdef PRINT_DEBUG_MESSAGES
        Serial.println(tx);
    #endif
    
    int err_code = sendString(tx, strlen(tx));
    if (err_code != 0) {
        return err_code;
    }
  
    err_code = receiveString(rx, &rx_len);
    if (err_code != 0) {
        return err_code;
    }

    if (strcmp(rx, "OK") == 0) {
        return 0;
    } else {
        return 1;
    }
}
Example #6
0
ToyControl::ToyControl(String json)
{
	char jsonCharArray[512];
  json.toCharArray(jsonCharArray, 512);
	
	init(jsonCharArray);
}
void ArduinoConnectEthernet::parseRequest(String str) 
{
    RC4 rc4;
    char b64out[50];
    
    str.toCharArray(buffer, 50);
    
    base64_decode(b64out,buffer,strlen(buffer));
    // Change this key
    rc4.Encrypt(b64out,"SecretKey");
    
    Serial.print("Msg: ");
    Serial.println(b64out);

    char *p = b64out;
    String strtk;
    byte i = 0;
    memset(result,'\0',sizeof(result));
    if(str == "continueFlow")
	{
		result[0] = str;
	}
	else
	{
	    while((strtk = strtok_r(p, ":", &p)) != NULL)
	    {
			result[i] = strtk;
			i++;
			delay(50);
	    }
	}
}
Example #8
0
void VDRIVE2::CloseFile(String FILENAME, bool n) {
    byte cr = 0x0d;
    char filename[FILENAME.length()+1];
    FILENAME.toCharArray(filename, FILENAME.length()+1);
    Serial1.print("CLF ");
    Serial1.print(filename);
    Serial1.write(cr);
	
    digitalWrite(_CTS, LOW);
    while (Serial1.available() > 0) {
		if (n == true) {
			char a = Serial1.read();
			if (a == 0x0d) {
				Serial.println();
			}
			else {
				Serial.write(a);
			}
		}
		else {
			Serial1.read();
		}
	}
    delay(10);
    digitalWrite(_CTS, HIGH);
}
Example #9
0
char* HttpServer::ParseUrl(char *str)
{
  int8_t r=-1;
  int8_t i = 0;
  int index = 4;
  int index1 = 0;
  int plen = 0;
  char ch = str[index];
  char clientline[CMDBUF];
  while( ch != ' ' && index < CMDBUF)
  {
    clientline[index1++] = ch;
    ch = str[++index];
  }
  clientline[index1] = '\0';

  // convert clientline into a proper
  // string for further processing
  String urlString = String(clientline);

  // extract the operation
  String op = urlString.substring(0,urlString.indexOf(' '));

  // we're only interested in the first part...
  urlString = urlString.substring(urlString.indexOf('/'), urlString.indexOf(' ', urlString.indexOf('/')));

  // put what's left of the URL back in client line
  urlString.toCharArray(clientline, CMDBUF);

  return clientline;
}
Example #10
0
// send ICAP request headers, returning success or failure
bool icapinstance::doHeaders(Socket & icapsock, HTTPHeader *reqheader, HTTPHeader *respheader, unsigned int objectsize)
{
	int rc = icapsock.connect(icapip.toCharArray(), icapport);
	if (rc) {
#ifdef DGDEBUG
		std::cerr << "Error connecting to ICAP server" << std::endl;
#endif
		lastmessage = "Error connecting to ICAP server";
		syslog(LOG_ERR, "Error connecting to ICAP server");
		return false;
	}
	char objectsizehex[32];
	// encapsulated HTTP request header:
	// use a dummy unless it proves absolutely necessary to do otherwise,
	// as using real data could lead to e.g. yet another source of password
	// leakage over the network.
	String encapsulatedheader("GET " + reqheader->getUrl() + " HTTP/1.0\r\n\r\n");
	// body chunk size in hex - either full body, or just preview
	if (usepreviews && (objectsize > previewsize)) {
		snprintf(objectsizehex, sizeof(objectsizehex), "%x\r\n", previewsize);
	} else {
		snprintf(objectsizehex, sizeof(objectsizehex), "%x\r\n", objectsize);
	}
	// encapsulated HTTP response header:
	// use real data, because scanners can use this to aid the process
	/*String httpresponseheader;
	for (std::deque<String>::iterator i = respheader->header.begin(); i != respheader->header.end(); i++) {
		httpresponseheader += (*i) + "\r\n";
	}
	httpresponseheader += "\r\n";*/
	String httpresponseheader("HTTP/1.0 200 OK\r\n\r\n");
	// ICAP header itself
	String icapheader("RESPMOD " + icapurl + " ICAP/1.0\r\nHost: " + icaphost + "\r\nAllow: 204\r\nEncapsulated: req-hdr=0, res-hdr=" + String(encapsulatedheader.length()) + ", res-body=" + String(httpresponseheader.length() + encapsulatedheader.length()));
	if (usepreviews && (objectsize > previewsize)) {
		icapheader += "\r\nPreview: " + String(previewsize);
	}
	icapheader += "\r\n\r\n";

#ifdef DGDEBUG
	std::cerr << "About to send icapheader:\n" << icapheader << encapsulatedheader << httpresponseheader << objectsizehex << std::endl;
#endif
	try {
		icapsock.writeString(icapheader.toCharArray());
		icapsock.writeString(encapsulatedheader.toCharArray());
		icapsock.writeString(httpresponseheader.toCharArray());
		icapsock.writeString(objectsizehex);
	}
	catch(std::exception & e) {
#ifdef DGDEBUG
		std::cerr << "Exception sending headers to ICAP: " << e.what() << std::endl;
#endif
		lastmessage = "Exception sending headers to ICAP";
		syslog(LOG_ERR, "Exception sending headers to ICAP: %s", e.what());
		return false;
	}
	return true;
}
Example #11
0
void InternetButton::playNote(String note, int duration){
    int noteNum = 0;
    int octave = 5;
    int freq = 256;
    
     //if(9 - int(command.charAt(1)) != null){
    char octavo[5];
    String tempString = note.substring(1,2);
    tempString.toCharArray(octavo,5);
    octave = atoi(octavo);
    //}
    
    if(duration != 0){
        duration = 1000/duration;
    }
    
    switch(note.charAt(0)){
        case 'C':
            noteNum = 0;
            break;
        case 'D':
            noteNum = 2;
            break;
        case 'E':
            noteNum = 4;
            break;
        case 'F':
            noteNum = 5;
            break;
        case 'G':
            noteNum = 7;
            break;
        case 'A':
            noteNum = 9;
            break;
        case 'B':
            noteNum = 11;
            break;
        case 'R':          // Rest note
            octave = -1;
            break;
        default:
            break;
            //return -1;
    }
    
    // based on equation at http://www.phy.mtu.edu/~suits/NoteFreqCalcs.html and the Verdi tuning
    // fn = f0*(2^1/12)^n where n = number of half-steps from the reference frequency f0
    freq = float(256*pow(1.05946,(     12.0*(octave-4)        +noteNum)));
    //          C4^  (2^1/12)^    12 half-steps in an octave      ^how many extra half-steps within that octave, 0 for a C
    
    tone(D2,int(freq),duration);
    delay(duration);
    noTone(D2);
    //return freq;
}
Example #12
0
void Store_String(uint8_t addr, String string)
{
    char  charBuf[string.length()+1];
    string.toCharArray(charBuf, string.length()+1);

    for (int t=  0; t<sizeof(charBuf); t++)
    {
        EEPROM.write(addr + t,charBuf[t]);
    }
}
Example #13
0
TEST_F(LuaMobileTest, LuaMobileTemplatesTest) {
	CreatureTemplateManager::DEBUG_MODE = 1;

	// Verify that all mobiles load
	ASSERT_EQ(CreatureTemplateManager::instance()->loadTemplates(), 0);

	// Verify loot group map loads
	LootGroupMap* lootGroupMap = LootGroupMap::instance();
	ASSERT_EQ(lootGroupMap->initialize(), 0);

	HashTableIterator<uint32, Reference<CreatureTemplate*> > iter = CreatureTemplateManager::instance()->iterator();
	while (iter.hasNext()) {
		CreatureTemplate* creature = iter.next();
		std::string templateName( creature->getTemplateName().toCharArray() );

		// Verify loot group percentages
		LootGroupCollection* groupCollection = creature->getLootGroups();
		if( groupCollection->count() > 0 ){


			for( int i = 0; i < groupCollection->count(); i++ ){

				LootGroupCollectionEntry* collectionEntry = groupCollection->get(i);
				LootGroups* groups = collectionEntry->getLootGroups();
				if( groups->count() > 0){

					int totalChance = 0;
					for( int j = 0; j < groups->count(); j++ ){

						LootGroupEntry* lootGroup = groups->get(j);
						totalChance += lootGroup->getLootChance();

						// Verify loot group is configured correctly
						LootGroupTemplate* foundGroup = lootGroupMap->getLootGroupTemplate( lootGroup->getLootGroupName() );
						std::string groupName( lootGroup->getLootGroupName().toCharArray() );
						EXPECT_TRUE( foundGroup != NULL ) << "Loot group " << groupName << " from " << templateName << " was not found in LootGroupMap";

					}

					EXPECT_EQ( 10000000, totalChance ) << "Loot groups total chance is incorrect " << templateName;
				}
			}
		}

		// Verify weapon groups exist
		Vector<String> weapons = creature->getWeapons();
		for (int i = 0; i < weapons.size(); i++) {
			String weaponGroup = weapons.get(i);
			std::string groupName( weaponGroup.toCharArray() );
			Vector<String> group = CreatureTemplateManager::instance()->getWeapons(weaponGroup);
			EXPECT_TRUE( group.size() > 0 ) << "Weapon group " << groupName << " from " << templateName << " was not found in weaponMap";
		}
	}

}
Example #14
0
//subscribe to the mqtt topic so we can receive data from the server.
void ATTDevice::MqttSubscribe()
{
	String MqttString = "client/" + _clientId + "/in/device/" + _deviceId + "/asset/+/command";  //the arduino is only interested in the actuator commands, no management commands
	char Mqttstring_buff[MqttString.length()+1];
    MqttString.toCharArray(Mqttstring_buff, MqttString.length()+1);
    _mqttclient->subscribe(Mqttstring_buff);

	#ifdef DEBUG
    Serial.print(F("MQTT Client subscribed"));
	#endif
}
Example #15
0
bool PushBullet::send(const char *pTitle, String sBody, const char *pToken)
{
  strncpy(m_szTitle, pTitle, sizeof(m_szTitle) );
  sBody.toCharArray(m_szBody, sizeof(m_szBody) );
  strncpy(m_szToken, pToken, sizeof(m_szToken) );

  if(m_ac.connected())
    m_ac.stop();

  return m_ac.connect( host, 443, true);
}
// get IMEI
String GSM3ShieldV1ModemVerification::getIMEI()
{
    String number(NULL);
    // AT command for obtain IMEI
    String modemResponse = modemAccess.writeModemCommand("AT+GSN", 2000);
    // Parse and check response
    char res_to_compare[modemResponse.length()];
    modemResponse.toCharArray(res_to_compare, modemResponse.length());
    if(strstr(res_to_compare,"OK") != NULL)
        number = modemResponse.substring(1, 17);
    return number;
}
int relayOff(String command){
    // Ritual incantation to convert String into Int
    char inputStr[64];
    command.toCharArray(inputStr,64);
    int i = atoi(inputStr);
    
    // Turn the desired relay off
    myRelays.off(i);
    
    // Respond
    return 1;    
}
Example #18
0
// the old string code does not define toCharArray() as const
// this simple but ugly workaround is for Arduino 0022 and
// should someday be removed.  For more info, see
// http://code.google.com/p/arduino/issues/detail?id=552
void Test_Equal(char *testString, char *expected, String actual)
#endif
{
  char buf[100]; actual.toCharArray(buf, 100);
  boolean b = (strcmp(buf, expected) == 0);
  ATS_PrintTestStatus(testString, b);
  if (!b) {
    Serial.print("expected '");
    Serial.print(expected);
    Serial.print("', actual '");
    Serial.print(actual);
    Serial.println("'");
  }
}
Example #19
0
void Syslog::log(String msgtype, String msg){

	String *packet = new String(msgtype + SP+ SYSLOG_VER + SP +NILVAL + SP + hname + SP + \
			               SYSLOG_APPNAME + SP + NILVAL + SP + NILVAL + SP + NILVAL + SP + msg);

	packet->toCharArray(buf,480);
	int pktsize=packet->length();
	delete packet;
	if (pktsize>480) {
		pktsize=480;
	}
	udp.begin(port);
	udp.sendPacket(buf, pktsize, server, port);
	udp.stop();
}
Example #20
0
CommandPacket HoofSerial::decodeJson(String jsonString)
{    
  char jsonChar[jsonString.length() + 1];    
  jsonString.toCharArray(jsonChar, sizeof(jsonChar));         //Convert to char array

  StaticJsonBuffer<200> jsonBuffer; 
  JsonObject& root = jsonBuffer.parseObject(jsonChar);

  if (root.success())
  {
    return (CommandPacket) { root["type"], root["command"], root["parameter"], root["value"] };
  }

  return (CommandPacket) { 0, "null", "null", "null" };
}
void Manager::ReadCommand()
{
    EthernetClient _client = server->available();
    char *response;
    char c[512];
    String sr = "";

    if (_client)
    {
        Serial.print("Free memory before: ");Serial.println(freeMemory());
        while (_client.connected())
        {
            int i = 0;
            while (_client.available() && i < LIMIT)
            {
                // Fill the buffer or read all the data client has received.
                char tmp = _client.read();
                
                if (tmp == MESSAGE_BREAK) break;
                //c[i++] = tmp;
                sr += tmp;
                i++;
            }
            
            char buf[sr.length()+1];
            sr.toCharArray(buf, sr.length()+1);
            
            // If we received a message, try to execute it.
            aJsonObject *object = aJson.parse(buf);
            
            //if (i > 0) response = parser.Execute(parser.toJson(c));
            if (i > 0) parser.Execute(object, &response);
            
            _client.println(response);
            _client.flush();
            
            // Handle memory management.
            aJson.deleteItem(object);
            free(response);
            //free(c);
            
            _client.stop();
            Serial.print("Free memory after: ");Serial.println(freeMemory());
            break;
        }
    }
}
Example #22
0
void SyslogClass::logger(uint8_t facility, uint8_t severity, const char tag[], 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(tag);
        SyslogUdp.write(" ");
        SyslogUdp.write(message);
        SyslogUdp.endPacket();
}
Example #23
0
String GSM3ShieldV1ScanNetworks::getSignalStrength()
{
    String modemResponse = modem.writeModemCommand("AT+CSQ", 2000);
    char res_to_split[modemResponse.length()];
    modemResponse.toCharArray(res_to_split, modemResponse.length());
    if((strstr(res_to_split,"ERROR") == NULL) | (strstr(res_to_split,"99") == NULL)) {
        // Tokenizer
        char *ptr_token;
        ptr_token = strtok(res_to_split, ":");
        ptr_token = strtok(NULL, ":");
        ptr_token = strtok(ptr_token, ",");
        String final_result = ptr_token;
        final_result.trim();
        return final_result;
    } else {
        return String(NULL);
    }
}
Example #24
0
String GSM3ShieldV1ScanNetworks::getCurrentCarrier()
{
    String modemResponse = modem.writeModemCommand("AT+COPS?", 2000);

    // Parse and check response
    char res_to_split[modemResponse.length()];
    modemResponse.toCharArray(res_to_split, modemResponse.length());
    if(strstr(res_to_split,"ERROR") == NULL) {
        // Tokenizer
        char *ptr_token;
        ptr_token = strtok(res_to_split, "\"");
        ptr_token = strtok(NULL, "\"");
        String final_result = ptr_token;
        return final_result;
    } else {
        return String(NULL);
    }
}
Example #25
0
void VDRIVE2::WriteFileData(double* DATA, int columns, bool n) { 
    byte cr = 0x0d;
    int i=0;
    String WriteVal;
    while (i < columns) {  //4=size of int
      String DATA2 = printDouble( DATA[i], 6);
      WriteVal += DATA2;
      WriteVal += ", ";
      i++;
    }
    
    char data[WriteVal.length()+1];
    WriteVal.toCharArray(data, WriteVal.length()+1);
    Serial1.print("WRF ");
    int Size = WriteVal.length()+2;
    Serial1.print(Size, DEC);
    Serial1.write(cr);
    i = 0;
    while (i < WriteVal.length()+1) {
      Serial1.write(data[i]);
      i++;
    }
    Serial1.write(0x0a); //LineFeed
    Serial1.write(cr);
    delay(10);
    
    digitalWrite(_CTS, LOW);
    while (Serial1.available() > 0) {
		if (n == true) {
			char a = Serial1.read();
			if (a == 0x0d) {
				Serial.println();
			}
			else {
				Serial.write(a);
			}
		}
		else {
			Serial1.read();
		}
	}
    delay(10);
    digitalWrite(_CTS, HIGH);
}
bool AndroidBluetooth::send(String test) {
	if (state == CONNECTED) {
        char *buffer = {"hello"};
        test.toCharArray(buffer, test.length()+1);
//        write('~');
//        write('#');
        for (int i = 0; i < test.length(); i++) {
            print(buffer[i]);
        }
//        write('#');
        write('~');
		delay(1);
        return true;
    }
#ifdef DEBUG
    Serial.println("Not connected, no data sent.");
#endif
    return false;
}
Example #27
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 = NTGVS1053::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);

}
Example #28
0
void HoofSerial::println(String jsonString, bool disableAck = false)
{ 
  char jsonChar[jsonString.length() + 1];  
  jsonString.toCharArray(jsonChar, sizeof(jsonChar));  

  //Serial.println(jsonChar);

  Tx16Request tx;
  
  if(!disableAck)
  {
    tx = Tx16Request(0x0005, (unsigned char*) jsonChar, sizeof(jsonChar));
  }
  else
  {
    tx = Tx16Request(0x0005, 0x0001, (unsigned char*) jsonChar, sizeof(jsonChar), 0x0000);
  }   

  _xbee.send(tx);
}
Example #29
0
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));
    }
}
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 = "";

    }
}