void MP3Player::Halt()
{
	Timer1.detachInterrupt();
	PLAY=false; 
	while(!myFile.close())
	{
	   #if DEBUG
	   Serial.println("close audio file");
	   #endif 
	}
	//AMPSHUTDOWN();
	#if DEBUG
    Serial.println("finish");
	#endif 
	delayMicroseconds(100000);
	name = "";
	  if(isPlayAll)
		PlayTrack("",0,"");
}
Example #2
0
int wcs(const char *oname)
{
//  char name[PATHLEN];

//  strcpy(name, oname);
  
  Eofseen = 0;  
//  vpos = 0;

  switch (wctxpn(oname)) {
   case ERROR:
     return ERROR;
   case ZSKIP:
     return OK;
  }

//  ++Filcnt;
  if(!Zmodem && wctx(fout.fileSize())==ERROR)
    return ERROR;
  return 0;
}
void setup() {
  Serial.begin(115200);
  while (!Serial.available()) SPARK_WLAN_Loop();
  while (Serial.available()) Serial.read();

  // initialize the SD card at SPI_FULL_SPEED for best performance.
  // try SPI_HALF_SPEED if bus errors occur.
  // Initialize HARDWARE SPI with user defined chipSelect
  if (!card.init(SPI_FULL_SPEED, chipSelect)) error("card.init failed");
  
  // Initialize SOFTWARE SPI
  //if (!card.init(mosiPin, misoPin, clockPin, chipSelect)) error("card.init failed");

  // initialize a FAT volume
  if (!volume.init(&card)) error("volume.init failed!");

  Serial.print("Type is FAT");
  Serial.println(volume.fatType(), DEC);

  if (!root.openRoot(&volume)) error("openRoot failed");
}
Example #4
0
void printCardInfo() {
    Serial.print(F("Data logging is "));
    if (disableLogging) {
        Serial.println(F("DISABLED"));
    } else {
        Serial.println(F("ENABLED"));
    }
    Serial.println();

    Serial.print("\nCard type: ");
    switch (card.type()) {
        case SD_CARD_TYPE_SD1:
            Serial.println("SD1");
            break;
        case SD_CARD_TYPE_SD2:
            Serial.println("SD2");
            break;
        case SD_CARD_TYPE_SDHC:
            Serial.println("SDHC");
            break;
        default:
            Serial.println("Unknown");
    }

    Serial.print("\nVolume type is FAT");
    Serial.println(volume.fatType(), DEC);

    unsigned long volumesize;
    volumesize = volume.blocksPerCluster();
    volumesize *= volume.clusterCount();
    volumesize /= 2;
    volumesize /= 1024;
    Serial.print("Volume size: ");
    Serial.print(volumesize, DEC);
    Serial.println("MB");

    Serial.println("name\tdate\tsize");
    root.ls(LS_R | LS_DATE | LS_SIZE);
    Serial.println();
}
Example #5
0
void setup(void) {
  Serial.begin(BPS_115200);
  Serial.println();
  PgmPrintln("Type any character to start");
  while (!Serial.available());
  
  //PgmPrint("FreeRam: ");
  //Serial.println(FreeRam());
  
  // initialize the SD card at SPI_HALF_SPEED to avoid bus errors with
  // breadboards.  use SPI_FULL_SPEED for better performance.
  if (!card.init(SPI_HALF_SPEED)) error("card.init failed");

  // initialize a FAT volume
  if (!volume.init(&card)) error("volume.init failed");

  // open the root directory
  if (!root.openRoot(&volume)) error("openRoot failed");
  
  strcpy_P(buf, PSTR("APPEND.TXT"));
  // open for read
  if (!from.open(&root, buf, O_READ)) {
    PgmPrint("Can't open "); 
    Serial.println(buf);
    PgmPrintln("Run the append example to create the file.");
    error("from.open failed");
  }
  strcpy_P(buf, PSTR("ACOPY.TXT"));
  // create if needed, truncate to zero length, open for write
  if (!copy.open(&root, buf, O_CREAT | O_TRUNC | O_WRITE)) {
    error("copy.open failed");
  }
  // count for printing periods
  uint16_t p = 0;
  int16_t n;  
  while ((n = from.read(buf, sizeof(buf))) > 0) {
    if (copy.write(buf, n) != n) error("write failed");
    // print progress periods
    if (!(p++ % 25)) Serial.print('.');
    if (!(p % 500)) Serial.println();
  }
  Serial.println();
  if (n != 0) error ("read");
  // force write of directory entry and last data
  if (!copy.close()) error("copy.close failed");
  PgmPrintln("Copy done.");
}
Example #6
0
void setupLog() {
    if (!card.init(SPI_HALF_SPEED, SD_CS)) {
        Serial.println(F("No SD card inserted, disabling data logger."));
        disableLogging = true;
    }

    if (!disableLogging && !volume.init(card)) {
        Serial.println(F("Unable to initialize SD volume"));
        disableLogging = true;
    }

    if (!disableLogging && !root.openRoot(volume)) {
        Serial.println(F("Unable to open volume root"));
        disableLogging = true;
    }

#ifdef DEBUG
    printCardInfo();
#endif

    if (!disableLogging) {
        openLog();
    }
}
Example #7
0
void SD_ListFiles(void)
{

    Serial.begin(9600);
    while (!Serial) {}
    delay(1000);
    Serial.println();
    while (file.openNext(sdf.vwd(), O_READ)) {
        file.printFileSize(&Serial);
        Serial.write(' ');
        file.printModifyDateTime(&Serial);
        Serial.write(' ');
        file.printName(&Serial);
        if (file.isDir()) {
            // Indicate a directory.
            Serial.write('/');
        }
        Serial.println();
        file.close();
    }
}
Example #8
0
void writeSettings() {

    char wrtBuffer[80];
    
    if (!settingsFile.open(&root, settingsFileName, O_WRITE|O_CREAT)) {
        // bitch.... ();
        return;
	}
    console.printf("DBG: Opened Settings File: %s\r\n",settingsFileName);
    snprintf(wrtBuffer,80,"NPW!%s\n",networkPassword);
    settingsFile.write(wrtBuffer,strlen(wrtBuffer));
    snprintf(wrtBuffer,80,"NJN!%s\n",networkSSID);
    settingsFile.write(wrtBuffer,strlen(wrtBuffer));
    snprintf(wrtBuffer,80,"PKY!%s\n",pachubeKey);
    settingsFile.write(wrtBuffer,strlen(wrtBuffer));
    snprintf(wrtBuffer,80,"PFD!%s\n",pachubeFeed);
    settingsFile.write(wrtBuffer,strlen(wrtBuffer));
    settingsFile.close();
    console.printf("DBG: Closing Settings File: %s\r\n",settingsFileName);
    
    
}
Example #9
0
/*
 * create enough files to force a cluster to be allocated to dir.
 */
void dirAllocTest(SdFile &dir) {
  char buf[13], name[13];
  SdFile file;
  uint16_t n; 
  uint32_t size = dir.fileSize();
 
  // create files and write name to file
  for (n = 0; ; n++){
    // make file name
    sprintf(name, "%u.TXT", n);
   
    // open start time
    uint32_t t0 = millis();
    if (!file.open(&dir, name, O_WRITE | O_CREAT | O_EXCL)) {
      error("open for write failed");
    }
   
    // open end time and write start time
    uint32_t t1 = millis();
    // write file name to file
    file.print(name);
    if (!file.close()) error("close write");
   
    // write end time
    uint32_t t2 = millis();
    PgmPrint("WR ");
    Serial.print(n);
    Serial.print(' ');
   
    // print time to create file
    Serial.print(t1 - t0);
    Serial.print(' ');
   
    // print time to write file
    Serial.println(t2 - t1);
   
    // directory size will change when a cluster is added
    if (dir.fileSize() != size) break;
  }

  // read files and check content
  for (uint16_t i = 0; i <= n; i++) {
    sprintf(name, "%u.TXT", i);
   
    // open start time
    uint32_t t0 = millis();
    if (!file.open(&dir, name, O_READ)) {
      error("open for read failed");
    }
    
    // open end time and read start time
    uint32_t t1 = millis();
    int16_t nr = file.read(buf, 13);
    if (nr < 5) error("file.read failed");
    
    // read end time
    uint32_t t2 = millis();
    
    // check file content
    if (strlen(name) != (uint16_t)nr || strncmp(name, buf, nr)) {
      error("content compare failed");
    }
    if (!file.close()) error("close read failed");
    
    PgmPrint("RD ");
    Serial.print(i);
    Serial.print(' ');
    
    // print open time
    Serial.print(t1 - t0);
    Serial.print(' ');
    
    // print read time
    Serial.println(t2 - t1);
  }
}
Example #10
0
bool open(char* fileName) {
  // Create LDxxxx.CSV for the lowest value of x.

  #ifdef SDCARD
  uint16_t i = 0;
  do {
    fileName[2] = (i/1000) % 10 + '0';
    fileName[3] = (i/100)  % 10 + '0';
    fileName[4] = (i/10)   % 10 + '0';
    fileName[5] = i        % 10 + '0';
    i++;
  }
  while(sd.exists(fileName));


  if(!file.open(fileName, O_CREAT | O_WRITE | O_EXCL)) {
//    error_P("file open");
    return false;
  }
  file.clearWriteError();
  
  // write data header
  file.print("time (s)");

  #endif
  
  Serial.print("v");
  Serial.println(FIRMWARE_VERSION);

  Serial.print("File: ");
  Serial.println(fileName);

  // write data header
  Serial.print("time (s)");
  
  /* We are no longer using the junction temperature in our data output.
  // write data header
  file.print("time (s), ambient");
  Serial.print("time (s), ambient");
  
  switch(temperatureUnit) {
  case TEMPERATURE_UNITS_C:
    file.print(" (C)");
    Serial.print(" (C)");
    break;
  case TEMPERATURE_UNITS_F:
    file.print(" (F)");
    Serial.print(" (F)");
    break;
  case TEMPERATURE_UNITS_K:
    file.print(" (K)");
    Serial.print(" (K)");
    break;
    
  }*/

  for (uint8_t i = 0; i < SENSOR_COUNT; i++) {
    #ifdef SDCARD
    file.print(", temp_");
    file.print(i, DEC);
    #endif
    
    Serial.print(", temp_");
    Serial.print(i, DEC);
    
    switch(temperatureUnit) {
    case TEMPERATURE_UNITS_C:
      #ifdef SDCARD
      file.print(" (C)");
      #endif
      Serial.print(" (C)");
      break;
    case TEMPERATURE_UNITS_F:
      #ifdef SDCARD
      file.print(" (F)");
      #endif
      Serial.print(" (F)");
      break;
    case TEMPERATURE_UNITS_K:
      #ifdef SDCARD
      file.print(" (K)");
      #endif
      Serial.print(" (K)");
      break;
    }
  }
  #ifdef SDCARD
  file.println();
  file.flush();
  #endif
  Serial.println();

  #ifdef SDCARD
  return (file.getWriteError() == false);
  #else
    return true;
  #endif
}
Example #11
0
void close() {
  #ifdef SDCARD
  file.close();
  #endif
}
Example #12
0
namespace sd {

#ifdef SDCARD
SdFat sd;
SdFile file;
#endif

uint32_t syncTime      = 0;     // time of last sync(), in millis()

//void error_P(const char* str) {
//  Serial.print("error: ");
//  Serial.print(str);
//  
//  // Stop the SD card
//  close();
//}

void init() {
  close();
  #ifdef SDCARD
  if (!sd.begin(SD_CS, SPI_FULL_SPEED)) {
//    error_P("card.init");
    return;
  }
  #endif
}

bool open(char* fileName) {
  // Create LDxxxx.CSV for the lowest value of x.

  #ifdef SDCARD
  uint16_t i = 0;
  do {
    fileName[2] = (i/1000) % 10 + '0';
    fileName[3] = (i/100)  % 10 + '0';
    fileName[4] = (i/10)   % 10 + '0';
    fileName[5] = i        % 10 + '0';
    i++;
  }
  while(sd.exists(fileName));


  if(!file.open(fileName, O_CREAT | O_WRITE | O_EXCL)) {
//    error_P("file open");
    return false;
  }
  file.clearWriteError();
  
  // write data header
  file.print("time (s)");

  #endif
  
  Serial.print("v");
  Serial.println(FIRMWARE_VERSION);

  Serial.print("File: ");
  Serial.println(fileName);

  // write data header
  Serial.print("time (s)");
  
  /* We are no longer using the junction temperature in our data output.
  // write data header
  file.print("time (s), ambient");
  Serial.print("time (s), ambient");
  
  switch(temperatureUnit) {
  case TEMPERATURE_UNITS_C:
    file.print(" (C)");
    Serial.print(" (C)");
    break;
  case TEMPERATURE_UNITS_F:
    file.print(" (F)");
    Serial.print(" (F)");
    break;
  case TEMPERATURE_UNITS_K:
    file.print(" (K)");
    Serial.print(" (K)");
    break;
    
  }*/

  for (uint8_t i = 0; i < SENSOR_COUNT; i++) {
    #ifdef SDCARD
    file.print(", temp_");
    file.print(i, DEC);
    #endif
    
    Serial.print(", temp_");
    Serial.print(i, DEC);
    
    switch(temperatureUnit) {
    case TEMPERATURE_UNITS_C:
      #ifdef SDCARD
      file.print(" (C)");
      #endif
      Serial.print(" (C)");
      break;
    case TEMPERATURE_UNITS_F:
      #ifdef SDCARD
      file.print(" (F)");
      #endif
      Serial.print(" (F)");
      break;
    case TEMPERATURE_UNITS_K:
      #ifdef SDCARD
      file.print(" (K)");
      #endif
      Serial.print(" (K)");
      break;
    }
  }
  #ifdef SDCARD
  file.println();
  file.flush();
  #endif
  Serial.println();

  #ifdef SDCARD
  return (file.getWriteError() == false);
  #else
    return true;
  #endif
}

void close() {
  #ifdef SDCARD
  file.close();
  #endif
}

bool log(char* message) {
  // TODO: Test if file is open first
  
  // log time to file
  #ifdef SDCARD
  file.println(message);
  #endif

  sync(false);

  #ifdef SDCARD
  return (file.getWriteError() == false);
  #else
    return true;
  #endif
}

void sync(boolean force) {
  // TODO: Test if file is open first?
  
  //don't sync too often - requires 2048 bytes of I/O to SD card
  
  if (!force && (millis() - syncTime) <  SYNC_INTERVAL) {
    return;
  }
  
  syncTime = millis();
  #ifdef SDCARD
  file.flush();
  #endif
}

} // namespace sd
Example #13
0
void logData(char *data) {
    int n;
    n=file.write(data,strlen(data));
    console.printf("DBG: Logging (%d)'%s'",n,data);
    file.sync();
}
Example #14
0
void setup() {

    int logNo;
	char configLineBuffer[LINE_BUFFER_MAX];
    spi.begin(SPI_281_250KHZ, MSBFIRST, 0);
	
	pinMode(GRN_LED,OUTPUT);
	pinMode(ORN_LED,OUTPUT);
	pinMode(RED_LED,OUTPUT);
	digitalWrite(GRN_LED,HIGH);
	digitalWrite(ORN_LED,LOW);
	digitalWrite(RED_LED,LOW);

    iwdg_init(IWDG_PRE_256, WATCHDOG_TIMEOUT);
    Watchdog_Reset();

	
    if (!card.init(&spi)) { 
    //if (!card.init()) { 
        console.printf("FTL: card.init failed");
    }
    delay(100);
    
    // initialize a FAT volume
    if (!volume.init(&card)) {
        console.printf("FTL: volume.init failed");
    }
    
    // open the root directory
    if (!root.openRoot(&volume)) 
        ;//SerialUSB.println("FTL: openRoot failed");
    
    for (logNo=0; (!logOpened) && logNo<512; logNo++) {
        Watchdog_Reset();
       //int snprintf(char *str, size_t size, const char *format, ...);
        snprintf(logFileName,15,"LOG%03d.TXT",logNo);
        if (file.open(&root, logFileName, O_READ)) {
            //SerialUSB.print("DBG: Exists  :"); SerialUSB.println(logFileName);
            file.close();
        } else if (file.open(&root, logFileName, O_CREAT|O_READ|O_WRITE)) {
            //SerialUSB.print("DBG: New File:"); SerialUSB.println(logFileName); 
            logOpened=true;
            file.sync();
            file.close();
            file.open(&root,logFileName,O_WRITE|O_READ);
			while (file.read(configLineBuffer,LINE_BUFFER_MAX)) {
				
			}
            file.sync();
        }    
    }
    //if (!logOpened) SerialUSB.println("FTL: openRoot failed");

	digitalWrite(GRN_LED,LOW);
	digitalWrite(RED_LED,HIGH);
    readSettings();
	console.printf("LSV:" BOM_VERSION "\r\n");
    console.printf("NST: %s\r\n",networkStatus()?"CONNECTED":"NOT CONNECTED");
	digitalWrite(ORN_LED,HIGH);
	digitalWrite(RED_LED,networkStatus()?HIGH:LOW);
	
}
Example #15
0
void web::ProcessWebClients()
{
	// listen for incoming clients
	EthernetClient client = m_server->available();
	if (client)
	{
		bool bReset = false;
#ifdef ARDUINO
		FILE stream_file;
		FILE * pFile = &stream_file;
		setup_sendbuf();
		fdev_setup_stream(pFile, stream_putchar, NULL, _FDEV_SETUP_WRITE);
		stream_file.udata = &client;
#else
		FILE * pFile = fdopen(client.GetSocket(), "w");
#endif
		freeMemory();
		trace(F("Got a client\n"));
		//ShowSockStatus();
		KVPairs key_value_pairs;
		char sPage[35];

		if (!ParseHTTPHeader(client, &key_value_pairs, sPage, sizeof(sPage)))
		{
			trace(F("ERROR!\n"));
			ServeError(pFile);
		}
		else
		{

			trace(F("Page:%s\n"), sPage);
			//ShowSockStatus();

			if (strcmp(sPage, "bin/setSched") == 0)
			{
				if (SetSchedule(key_value_pairs))
				{
					if (GetRunSchedules())
						ReloadEvents();
					ServeHeader(pFile, 200, "OK", false);
				}
				else
					ServeError(pFile);
			}
			else if (strcmp(sPage, "bin/setZones") == 0)
			{
				if (SetZones(key_value_pairs))
				{
					ReloadEvents();
					ServeHeader(pFile, 200, "OK", false);
				}
				else
					ServeError(pFile);
			}
			else if (strcmp(sPage, "bin/delSched") == 0)
			{
				if (DeleteSchedule(key_value_pairs))
				{
					if (GetRunSchedules())
						ReloadEvents();
					ServeHeader(pFile, 200, "OK", false);
				}
				else
					ServeError(pFile);
			}
			else if (strcmp(sPage, "bin/setQSched") == 0)
			{
				if (SetQSched(key_value_pairs))
				{
					ServeHeader(pFile, 200, "OK", false);
				}
				else
					ServeError(pFile);
			}
			else if (strcmp(sPage, "bin/settings") == 0)
			{
				if (SetSettings(key_value_pairs))
				{
					ReloadEvents();
					ServeHeader(pFile, 200, "OK", false);
				}
				else
					ServeError(pFile);
			}
			else if (strcmp(sPage, "bin/manual") == 0)
			{
				if (ManualZone(key_value_pairs))
				{
					ServeHeader(pFile, 200, "OK", false);
				}
				else
					ServeError(pFile);
			}
			else if (strcmp(sPage, "bin/run") == 0)
			{
				if (RunSchedules(key_value_pairs))
				{
					ReloadEvents();
					ServeHeader(pFile, 200, "OK", false);
				}
				else
					ServeError(pFile);
			}
			else if (strcmp(sPage, "bin/factory") == 0)
			{
				ResetEEPROM();
				ReloadEvents();
				ServeHeader(pFile, 200, "OK", false);
			}
			else if (strcmp(sPage, "bin/reset") == 0)
			{
				ServeHeader(pFile, 200, "OK", false);
				bReset = true;
			}
			else if (strcmp(sPage, "json/schedules") == 0)
			{
				JSONSchedules(key_value_pairs, pFile);
			}
			else if (strcmp(sPage, "json/zones") == 0)
			{
				JSONZones(key_value_pairs, pFile);
			}
			else if (strcmp(sPage, "json/settings") == 0)
			{
				JSONSettings(key_value_pairs, pFile);
			}
			else if (strcmp(sPage, "json/state") == 0)
			{
				JSONState(key_value_pairs, pFile);
			}
			else if (strcmp(sPage, "json/schedule") == 0)
			{
				JSONSchedule(key_value_pairs, pFile);
			}
			else if (strcmp(sPage, "json/wcheck") == 0)
			{
				JSONwCheck(key_value_pairs, pFile);
			}
#ifdef LOGGING
			else if (strcmp(sPage, "json/logs") == 0)
			{
				JSONLogs(key_value_pairs, pFile);
			}
			else if (strcmp(sPage, "json/tlogs") == 0)
			{
				JSONtLogs(key_value_pairs, pFile);
			}
#endif
			else if (strcmp(sPage, "ShowSched") == 0)
			{
				freeMemory();
				ServeSchedPage(pFile);
			}
			else if (strcmp(sPage, "ShowZones") == 0)
			{
				freeMemory();
				ServeZonesPage(pFile);
			}
			else if (strcmp(sPage, "ShowEvent") == 0)
			{
				ServeEventPage(pFile);
			}
			else if (strcmp(sPage, "ReloadEvent") == 0)
			{
				ReloadEvents(true);
				ServeEventPage(pFile);
			}
			else
			{
				if (strlen(sPage) == 0)
					strcpy(sPage, "index.htm");
				// prepend path
				memmove(sPage + 5, sPage, sizeof(sPage) - 5);
				memcpy(sPage, "/web/", 5);
				sPage[sizeof(sPage)-1] = 0;
				trace(F("Serving Page: %s\n"), sPage);
				SdFile theFile;
				if (!theFile.open(sPage, O_READ))
					Serve404(pFile);
				else
				{
					if (theFile.isFile())
						ServeFile(pFile, sPage, theFile, client);
					else
						Serve404(pFile);
					theFile.close();
				}
			}
		}

#ifdef ARDUINO
		flush_sendbuf(client);
		// give the web browser time to receive the data
		delay(1);
#else
		fflush(pFile);
		fclose(pFile);
#endif
		// close the connection:
		client.stop();

		if (bReset)
			sysreset();
	}
}
Example #16
0
void handleConsoleInput() {
    uint8_t retval;
	uint8_t index=0;
	uint8_t ch='0';
	SdFile finger;
    
    switch (console.keyValue()) {
        case _DIR_:
			console.printf("SOD:\r\n");
            root.ls(LS_DATE | LS_SIZE);
 			console.printf("EOD:\r\n");
			break;
        case _LSV_:
			console.printf("LSV:" BOM_VERSION "\r\n");
			break;
        case _TYP_:  
            typeFile(console.arguments());
            break;
        case _NSC_:  
			console.printf("SOD:\r\n");
			retval=networkScan();
			console.printf("EOD:\r\n");
            console.printf("\nDBG: found=%d\r\n",retval);
            break;
        case _NJN_:  
			//console.printf("SOD:\r\n");
			retval=networkJoin(console.arguments());
			//console.printf("EOD:\r\n");
            console.printf("\nDBG: joined=%s\r\n",retval?"TRUE":"FALSE");
            break;
        case _NPW_:  
			//console.printf("SOD:\r\n");
			retval=networkSetPassword(console.arguments());
			//console.printf("EOD:\r\n");
            console.printf("\nDBG: pwd set=%s\r\n",retval?"TRUE":"FALSE");
            break;
        case _NST_:  
			retval=networkStatus();
            console.printf("NST: %s\r\n",retval?"CONNECTED":"NOT CONNECTED");
            break;
		case _FMT_: // there really should be some REALLY do you mean this here but.....
			root.openRoot(&volume);
			if (finger.open(&root, ".", O_WRITE|O_READ)) {
				console.printf("\nDBG: Opened / \r\n");
				finger.rmRfStar();
			} else {
				console.printf("\nDBG: FAIL \r\n");
			}	
			break;
            
		case _TPT_:
			toPachube(1, console.arguments());
			break;
        case _TX2_:
            radio.printf("%s",console.arguments());
            index=0;
            // delay(1000);
            while (radio.available()) {
                inBuffer[index++]=ch=radio.read();
				if( index>= 99 || ((ch== '\n') || ch !='\r')) {
					inBuffer[index]='\0';
					console.puts(inBuffer);
					index=0; 
					delay(100);
				}
            } 
            inBuffer[index]='\0';
            console.puts(inBuffer);
			console.puts((char *) "\r\n");
            break;
// set to one to test output for.
#if 1
        case _TS1_: toPachube(0, console.arguments()); break;
        case _TS2_: toPachube(1, console.arguments()); break;
        case _TS3_: toPachube(2, console.arguments()); break;
        case _TS4_: toPachube(3, console.arguments()); break;
        case _TS5_: toPachube(4, console.arguments()); break;
        case _FAN_: toPachube(5, console.arguments()); break;
        case _CHL_: toPachube(6, console.arguments()); break;
        case _STC_: toPachube(7, console.arguments()); break;
#endif			

        case _PKY_:
            strncpy(pachubeKey, console.arguments(), MAX_PATCHUBE_KEY_LENGHT-1);
            stripcrlf(pachubeKey);
            break;
        case _PFD_:
            strncpy(pachubeFeed, console.arguments(), MAX_PATCHUBE_FEED_LENGHT-1);
            stripcrlf(pachubeFeed);
            break;
        case _SGT_ :
            readSettings();
            break;
        case _SSV_ :
            writeSettings();
            break;
            
        default:
            console.printf("DBG: forwarding (%s) to device\r\n",console.key());
            device.puts(console.line());
            //device.puts("\r\n");
            break;
    }
    
    
}
Example #17
0
void loop() {
    unsigned long tick = millis();
    long diff = tick - lastTick;
    avgTickDelay = expAvg(avgTickDelay, diff);
    lastTick = tick;
    if (printTicks > printTicksI) {
        Serial.print("tick delay: ");
        Serial.print(diff);
        Serial.println("ms");
    }

    // Radio tick.
    radio->tick();

    // Send helo.
    diff = tick - lastSent;
    if ((lastAck < lastSent && diff > MAX_SEND_WAIT)
        || diff > MIN_SEND_WAIT
    ) {
        avgSendDelay = expAvg(avgSendDelay, diff);
        lastSent = tick;
        if (printTicks > printTicksI) {
            printTicksI++;
            Serial.print("send delay: ");
            Serial.print(diff);
            Serial.println("ms");
        }

        if (sendInfx) {
            Message msg("he");
            radio->send(&msg);
        } else {
            Message msg("lo");
            radio->send(&msg);
        }
        sendInfx = !sendInfx;
    }

    // Update metrics.
    tick = millis();
    if (tick - lastUpdate > UPDATE_WAIT) {
        memcpy(&mLast, &m, sizeof(metrics));
        lastUpdate = tick;
        lastVcc = readVcc();

        sinceLastAck = (int) ((lastUpdate - lastAck) / 1000L);
        if (sinceLastAck < 0) {
#ifdef DEBUG
            Serial.println("sinceLastAck less than 0");
            Serial.print("round((");
            Serial.print(lastUpdate);
            Serial.print(" - ");
            Serial.print(lastAck);
            Serial.print(") / 1000.0) = ");
            Serial.println(sinceLastAck);
#endif

            sinceLastAck = 0;
        }

        if (lastAck + TIMEOUT_WAIT < lastSent) {
            lastRoundtrip = NO_READING_INT;
            lastRssi = NO_READING_INT;
        }

        writeLog();
    }

    // Pipeline tick.
    pipe->tick();

    // Serial commands.
    if (Serial.available()) {
        String cmd = Serial.readStringUntil('\n');
        if (cmd[0] == 'D') {
            dataFile.close();
            if (!dataFile.open(root, logFilename, O_READ)) {
                Serial.println();
                Serial.println("Could not open file for reading");
                return;
            }
            uint32_t offset;
            long cmdOffset = cmd.substring(1).toInt();
            if (cmdOffset < 0) {
                offset = dataFile.fileSize() + cmdOffset;
            } else {
                offset = cmdOffset;
            }
            dataFile.seekSet(offset);
            char buf[128];
            int16_t read;
            bool firstRead = true;
            do {
                read = dataFile.read(buf, 127);
                buf[read] = 0;
                if (firstRead && read > 0) {
                    firstRead = false;
                    char *firstNewline = strchr(buf, '\n');
                    Serial.print(++firstNewline);
                } else {
                    Serial.print(buf);
                }
            } while (read > 0);
            Serial.println();
            dataFile.close();

        } else if (cmd[0] == 'L') {
            printCardInfo();

        } else if (cmd[0] == 'I') {
            Serial.print(F("Average tick delay: "));
            Serial.print(avgTickDelay);
            Serial.println(F("ms"));
            Serial.print(F("Average send delay: "));
            Serial.print(avgSendDelay);
            Serial.println(F("ms"));
            Serial.print(F("RAM free: "));
            Serial.print(freeRam());
            Serial.println(F(" bytes"));
            printTicks = (int) cmd.substring(1).toInt();
            printTicksI = 0;
        } else if (cmd[0] == 'G') {
            Serial.print(F("Location: "));
            Serial.print(m.latitude, 6);
            Serial.print(F(","));
            Serial.println(m.longitude, 6);
        } else if (cmd[0] == 'U') {
            Message msg("up");
            radio->send(&msg);
        } else if (cmd[0] == 'F') {
            if (m.logging != MODULE_ENABLED) {
                Serial.println(F("Requesting to enable logging"));
            } else {
                Serial.println(F("Requesting to disable logging"));
            }
            Message msg("tl");
            radio->send(&msg);
        } else if (cmd[0] == 'T') {
            Serial.print(F("Remote data logging is "));
            Serial.println(m.logging == MODULE_ENABLED ? "enabled" : "disabled");
        }
    }
}
Example #18
0
void writeLog() {
    if (disableLogging) {
        return;
    }

    if (!dataFile.isOpen()) {
        if (!dataFile.open(root, logFilename, O_WRITE | O_APPEND)) {
#ifdef DEBUG
            Serial.println(F("Could not open file for writing"));
#endif
            disableLogging = true;
            return;
        }
    }

    // Local sensor readings
    logFileSize += dataFile.print(lastUpdate);
    logFileSize += dataFile.print(F("\t"));
    logFileSize += dataFile.print(sinceLastAck);
    logFileSize += dataFile.print(F("\t"));
    logFileSize += dataFile.print(lastVcc);
    logFileSize += dataFile.print(F("\t"));
    if (validReadingi(lastRoundtrip)) {
        logFileSize += dataFile.print(lastRoundtrip);
    }
    logFileSize += dataFile.print(F("\t"));
    if (validReadingi(lastRssi)) {
        logFileSize += dataFile.print(lastRssi);
    }
    logFileSize += dataFile.print(F("\t"));

    // Remote sensor readings
    if (validReadingi(m.vcc)) {
        logFileSize += dataFile.print(m.vcc);
    }
    logFileSize += dataFile.print(F("\t"));
    if (validReadingi(m.rssi)) {
        logFileSize += dataFile.print(m.rssi);
    }
    logFileSize += dataFile.print(F("\t"));
    if (validReadingi(m.vibration)) {
        logFileSize += dataFile.print(m.vibration);
    }
    logFileSize += dataFile.print(F("\t"));
    if (validReadingf(m.altitudeGps)) {
        logFileSize += dataFile.print(m.altitudeGps);
    }
    logFileSize += dataFile.print(F("\t"));
    if (validReadingf(m.altitude)) {
        logFileSize += dataFile.print(m.altitude);
    }
    logFileSize += dataFile.print(F("\t"));
    if (validReadingf(m.temp)) {
        logFileSize += dataFile.print(m.temp);
    }
    logFileSize += dataFile.print(F("\t"));
    if (validReadingf(m.temp2)) {
        logFileSize += dataFile.print(m.temp2);
    }
    logFileSize += dataFile.print(F("\t"));
    if (validReadingf(m.latitude)) {
        logFileSize += dataFile.print(m.latitude, 6);
    }
    logFileSize += dataFile.print(F("\t"));
    if (validReadingf(m.longitude)) {
        logFileSize += dataFile.print(m.longitude, 6);
    }
    logFileSize += dataFile.print(F("\t"));
    if (validReadingf(m.accelX)) {
        logFileSize += dataFile.print(m.accelX);
    }
    logFileSize += dataFile.print(F("\t"));
    if (validReadingf(m.accelY)) {
        logFileSize += dataFile.print(m.accelY);
    }
    logFileSize += dataFile.print(F("\t"));
    if (validReadingf(m.accelZ)) {
        logFileSize += dataFile.print(m.accelZ);
    }
    logFileSize += dataFile.print(F("\t"));
    if (validReadingf(m.magX)) {
        logFileSize += dataFile.print(m.magX);
    }
    logFileSize += dataFile.print(F("\t"));
    if (validReadingf(m.magY)) {
        logFileSize += dataFile.print(m.magY);
    }
    logFileSize += dataFile.print(F("\t"));
    if (validReadingf(m.magZ)) {
        logFileSize += dataFile.print(m.magZ);
    }
    logFileSize += dataFile.print(F("\t"));
    if (validReadingf(m.gyroX)) {
        logFileSize += dataFile.print(m.gyroX);
    }
    logFileSize += dataFile.print(F("\t"));
    if (validReadingf(m.gyroY)) {
        logFileSize += dataFile.print(m.gyroY);
    }
    logFileSize += dataFile.print(F("\t"));
    if (validReadingf(m.gyroZ)) {
        logFileSize += dataFile.print(m.gyroZ);
    }
    logFileSize += dataFile.print(F("\t"));
    if (validReadingf(m.accel2X)) {
        logFileSize += dataFile.print(m.accel2X);
    }
    logFileSize += dataFile.print(F("\t"));
    if (validReadingf(m.accel2Y)) {
        logFileSize += dataFile.print(m.accel2Y);
    }
    logFileSize += dataFile.print(F("\t"));
    if (validReadingf(m.accel2Z)) {
        logFileSize += dataFile.print(m.accel2Z);
    }
    logFileSize += dataFile.print(F("\t"));
    if (validReadingf(m.mag2X)) {
        logFileSize += dataFile.print(m.mag2X);
    }
    logFileSize += dataFile.print(F("\t"));
    if (validReadingf(m.mag2Y)) {
        logFileSize += dataFile.print(m.mag2Y);
    }
    logFileSize += dataFile.print(F("\t"));
    if (validReadingf(m.mag2Z)) {
        logFileSize += dataFile.print(m.mag2Z);
    }
    logFileSize += dataFile.print(F("\t"));
    if (validReadingf(m.gyro2X)) {
        logFileSize += dataFile.print(m.gyro2X);
    }
    logFileSize += dataFile.print(F("\t"));
    if (validReadingf(m.gyro2Y)) {
        logFileSize += dataFile.print(m.gyro2Y);
    }
    logFileSize += dataFile.print(F("\t"));
    if (validReadingf(m.gyro2Z)) {
        logFileSize += dataFile.print(m.gyro2Z);
    }
    logFileSize += dataFile.println(F("\t"));
    dataFile.sync();
    if (logFileSize >= logFileMax) {
        dataFile.close();
        rotateLog();
        openLog();
    }
}
Example #19
0
void LogTemps(){
   if (!file.open(root, filename, O_CREAT | O_APPEND | O_WRITE)) {
     //error(“open”);
   }
   
// write values to the file

          sensorsa.requestTemperatures(); 
          sensorsb.requestTemperatures(); 
          sensorsc.requestTemperatures(); 
          sensorsd.requestTemperatures(); 
          

file.print(now() );
file.print("|");
file.print(sensorsa.getTempCByIndex(0));
file.print("|");
file.print(sensorsb.getTempCByIndex(0));
file.print("|");
file.print(sensorsc.getTempCByIndex(0));
file.print("|");
file.print(sensorsd.getTempCByIndex(0));
file.print("\n");

if (!file.close() || file.writeError){
 // error(“close/write”);
}
  
}
void CardReader::openFile(char* name, bool read, bool replace_current/*=true*/, bool lcd_status/*=true*/) {
  if (!cardOK) return;
  if (file.isOpen()) { //replacing current file by new file, or subfile call
    if (!replace_current) {
      if (file_subcall_ctr > SD_PROCEDURE_DEPTH - 1) {
        ECHO_LMV(ER, MSG_SD_MAX_DEPTH, SD_PROCEDURE_DEPTH);
        kill(PSTR(MSG_KILLED));
        return;
      }

      ECHO_SMV(DB, "SUBROUTINE CALL target:\"", name);
      ECHO_M("\" parent:\"");

      //store current filename and position
      getAbsFilename(filenames[file_subcall_ctr]);

      ECHO_V(filenames[file_subcall_ctr]);
      ECHO_EMV("\" pos", sdpos);
      filespos[file_subcall_ctr] = sdpos;
      file_subcall_ctr++;
    }
    else {
     ECHO_LMV(DB, "Now doing file: ", name);
    }
    file.close();
  }
  else { // opening fresh file
    file_subcall_ctr = 0; // resetting procedure depth in case user cancels print while in procedure
    ECHO_LMV(DB, "Now fresh file: ", name);
  }
  sdprinting = false;

  SdFile myDir;
  curDir = &root;
  char *fname = name;

  char *dirname_start, *dirname_end;
  if (name[0] == '/') {
    dirname_start = &name[1];
    while (dirname_start > 0) {
      dirname_end = strchr(dirname_start, '/');
      if (dirname_end > 0 && dirname_end > dirname_start) {
        char subdirname[FILENAME_LENGTH];
        strncpy(subdirname, dirname_start, dirname_end - dirname_start);
        subdirname[dirname_end - dirname_start] = 0;
        ECHO_EV(subdirname);
        if (!myDir.open(curDir, subdirname, O_READ)) {
          ECHO_MV(MSG_SD_OPEN_FILE_FAIL, subdirname);
          ECHO_C('.');
          return;
        }
        else {
          //ECHO_EM("dive ok");
        }

        curDir = &myDir;
        dirname_start = dirname_end + 1;
      }
      else { // the remainder after all /fsa/fdsa/ is the filename
        fname = dirname_start;
        //ECHO_EM("remainder");
        //ECHO_EV(fname);
        break;
      }
    }
  }
  else { //relative path
    curDir = &workDir;
  }

  if (read) {
    if (file.open(curDir, fname, O_READ)) {
      filesize = file.fileSize();
      ECHO_MV(MSG_SD_FILE_OPENED, fname);
      ECHO_EMV(MSG_SD_SIZE, filesize);
      sdpos = 0;

      ECHO_EM(MSG_SD_FILE_SELECTED);
      getfilename(0, fname);
      if(lcd_status) lcd_setstatus(longFilename[0] ? longFilename : fname);
    }
    else {
      ECHO_MV(MSG_SD_OPEN_FILE_FAIL, fname);
      ECHO_PGM(".\n");
    }
  }
  else { //write
    if (!file.open(curDir, fname, O_CREAT | O_APPEND | O_WRITE | O_TRUNC)) {
      ECHO_MV(MSG_SD_OPEN_FILE_FAIL, fname);
      ECHO_PGM(".\n");
    }
    else {
      saving = true;
      ECHO_EMV(MSG_SD_WRITE_TO_FILE, name);
      if(lcd_status) lcd_setstatus(fname);
    }
  }
}
/**
 * Dive into a folder and recurse depth-first to perform a pre-set operation lsAction:
 *   LS_Count       - Add +1 to nrFiles for every file within the parent
 *   LS_GetFilename - Get the filename of the file indexed by nrFiles
 *   LS_SerialPrint - Print the full path of each file to serial output
 */
void CardReader::lsDive(const char *prepend, SdFile parent, const char * const match/*=NULL*/) {
  dir_t p;
  uint8_t cnt = 0;

  // Read the next entry from a directory
  while (parent.readDir(p, longFilename) > 0) {

    // If the entry is a directory and the action is LS_SerialPrint
    if (DIR_IS_SUBDIR(&p) && lsAction != LS_Count && lsAction != LS_GetFilename) {

      // Get the short name for the item, which we know is a folder
      char lfilename[FILENAME_LENGTH];
      createFilename(lfilename, p);

      // Allocate enough stack space for the full path to a folder, trailing slash, and nul
      boolean prepend_is_empty = (prepend[0] == '\0');
      int len = (prepend_is_empty ? 1 : strlen(prepend)) + strlen(lfilename) + 1 + 1;
      char path[len];

      // Append the FOLDERNAME12/ to the passed string.
      // It contains the full path to the "parent" argument.
      // We now have the full path to the item in this folder.
      strcpy(path, prepend_is_empty ? "/" : prepend); // root slash if prepend is empty
      strcat(path, lfilename); // FILENAME_LENGTH-1 characters maximum
      strcat(path, "/");       // 1 character

      // Serial.print(path);

      // Get a new directory object using the full path
      // and dive recursively into it.
      SdFile dir;
      if (!dir.open(parent, lfilename, O_READ)) {
        if (lsAction == LS_SerialPrint) {
          ECHO_LMV(ER, MSG_SD_CANT_OPEN_SUBDIR, lfilename);
        }
      }
      lsDive(path, dir);
      // close() is done automatically by destructor of SdFile
    }
    else {
      char pn0 = p.name[0];
      if (pn0 == DIR_NAME_FREE) break;
      if (pn0 == DIR_NAME_DELETED || pn0 == '.') continue;
      if (longFilename[0] == '.') continue;

      if (!DIR_IS_FILE_OR_SUBDIR(&p)) continue;

      filenameIsDir = DIR_IS_SUBDIR(&p);

      if (!filenameIsDir && (p.name[8] != 'G' || p.name[9] == '~')) continue;

      switch (lsAction) {
        case LS_Count:
          nrFiles++;
          break;
        case LS_SerialPrint:
          createFilename(filename, p);
          ECHO_V(prepend);
          ECHO_EV(filename);
          break;
        case LS_GetFilename:
          createFilename(filename, p);
          if (match != NULL) {
            if (strcasecmp(match, filename) == 0) return;
          }
          else if (cnt == nrFiles) return;
          cnt++;
          break;
      }
    }
  } // while readDir
}
Example #22
0
void setup()
{
	bool loginit(false);
	bool sdinit(false);
	bool dbinit(false);

	uint8_t	tlpins[] = { INNER_LIGHTS_PINS, OUTER_LIGHTS_PINS };

	Serial.begin( BAUDRATE );
#ifdef VERBOSE
	delay(10);
	Serial.print(CMNT);
	for( char c = 0; c < 79; ++c ) Serial.print('>');
	Serial.println();
#endif
	I2c.begin();
	I2c.timeOut(1000);

	g_display.init();		//	calls Wire.begin()

	g_display.print( freeMemory() );
	g_loop.init( PIN_INNERLOOP, PIN_OUTERLOOP, LOOP_ACTIVE );

	setup433();
	g_codeready = false;
	g_code = 0;

#ifdef USE_IOEXTENDER_OUTPUTS
	g_outputs.set(0xff);
#else
	{
		uint8_t	all_output_pins[8] = { ALL_RAW_OUTPUT_PINS };
		g_outputs.init(all_output_pins, RELAY_OFF);
	}
#endif
	if((sdinit = g_sd.begin( SS, SPI_HALF_SPEED ))) {
		if( !(loginit = g_logger.init()) )
			Serial.println(F("Logger fail"));
	} else
		Serial.println(F("SD fail"));

	dbinit = g_db.init();

	g_display.print( ' ' );
	g_display.print( sdinit );
	g_display.print( ' ' );
	g_display.print( loginit );
	g_display.print( ' ' );
	g_display.print( dbinit );

	//runlight
	for( uint8_t pin = 0; pin < sizeof(tlpins) + 3; ++pin ) {
		if(pin < sizeof(tlpins)) {
			g_outputs.set( tlpins[pin], RELAY_ON);
		}
		if(pin > 2)
			g_outputs.set(tlpins[pin-3], RELAY_OFF);
		delay(150);
	}

	if( !loginit )
	{
		delay(100);
		for( int i = 0; i < 3;  ++i ) {
			g_outputs.set( PIN_IN_RED, RELAY_ON );
			g_outputs.set( PIN_OUT_RED, RELAY_ON );
			delay( 500 );
			g_outputs.set( PIN_IN_RED, RELAY_OFF );
			g_outputs.set( PIN_OUT_RED, RELAY_OFF );
			delay( 500 );
		}
	}

	g_clk.init( DS3231_INTCN );
	g_timevalid = updatedt();
#ifdef VERBOSE
	Serial.print(CMNT);
	Serial.println(F("DS3231 init done."));
#endif
	g_logger.log( logwriter::INFO, g_time, F("Reset") );

	g_display.clear();
	if(sdinit)
	{
		SdFile	f;
		if(f.open("IMPORT"))
		{
			f.close();
			g_display.print(F("IMPORTING "));
			uint16_t	imported(importdb(0, 1023));
			if(imported != (uint16_t) -1) {
				g_display.print(imported);
				g_sd.remove("IMPORT");
			} else
				g_display.print(F("FAIL"));

			delay(2000);
			g_display.clear();
		}
	}

#ifdef VERBOSE
	Serial.print(CMNT);
	for( char c = 0; c < 79; ++c ) Serial.print('<');
	Serial.println();
#endif
}
Example #23
0
void CardReader::openFile(char* name, bool read, bool replace_current/*=true*/) {
  if (!cardOK) return;
  if (file.isOpen()) { //replacing current file by new file, or subfile call
    if (!replace_current) {
     if (file_subcall_ctr > SD_PROCEDURE_DEPTH - 1) {
       SERIAL_ERROR_START;
       SERIAL_ERRORPGM("trying to call sub-gcode files with too many levels. MAX level is:");
       SERIAL_ERRORLN(SD_PROCEDURE_DEPTH);
       kill();
       return;
     }

     SERIAL_ECHO_START;
     SERIAL_ECHOPGM("SUBROUTINE CALL target:\"");
     SERIAL_ECHO(name);
     SERIAL_ECHOPGM("\" parent:\"");

     //store current filename and position
     getAbsFilename(filenames[file_subcall_ctr]);

     SERIAL_ECHO(filenames[file_subcall_ctr]);
     SERIAL_ECHOPGM("\" pos");
     SERIAL_ECHOLN(sdpos);
     filespos[file_subcall_ctr] = sdpos;
     file_subcall_ctr++;
    }
    else {
     SERIAL_ECHO_START;
     SERIAL_ECHOPGM("Now doing file: ");
     SERIAL_ECHOLN(name);
    }
    file.close();
  }
  else { //opening fresh file
    file_subcall_ctr = 0; //resetting procedure depth in case user cancels print while in procedure
    SERIAL_ECHO_START;
    SERIAL_ECHOPGM("Now fresh file: ");
    SERIAL_ECHOLN(name);
  }
  sdprinting = false;

  SdFile myDir;
  curDir = &root;
  char *fname = name;

  char *dirname_start, *dirname_end;
  if (name[0] == '/') {
    dirname_start = &name[1];
    while(dirname_start > 0) {
      dirname_end = strchr(dirname_start, '/');
      //SERIAL_ECHO("start:");SERIAL_ECHOLN((int)(dirname_start - name));
      //SERIAL_ECHO("end  :");SERIAL_ECHOLN((int)(dirname_end - name));
      if (dirname_end > 0 && dirname_end > dirname_start) {
        char subdirname[FILENAME_LENGTH];
        strncpy(subdirname, dirname_start, dirname_end - dirname_start);
        subdirname[dirname_end - dirname_start] = 0;
        SERIAL_ECHOLN(subdirname);
        if (!myDir.open(curDir, subdirname, O_READ)) {
          SERIAL_PROTOCOLPGM(MSG_SD_OPEN_FILE_FAIL);
          SERIAL_PROTOCOL(subdirname);
          SERIAL_PROTOCOLCHAR('.');
          return;
        }
        else {
          //SERIAL_ECHOLN("dive ok");
        }

        curDir = &myDir;
        dirname_start = dirname_end + 1;
      }
      else { // the remainder after all /fsa/fdsa/ is the filename
        fname = dirname_start;
        //SERIAL_ECHOLN("remainder");
        //SERIAL_ECHOLN(fname);
        break;
      }
    }
  }
  else { //relative path
    curDir = &workDir;
  }

  if (read) {
    if (file.open(curDir, fname, O_READ)) {
      filesize = file.fileSize();
      SERIAL_PROTOCOLPGM(MSG_SD_FILE_OPENED);
      SERIAL_PROTOCOL(fname);
      SERIAL_PROTOCOLPGM(MSG_SD_SIZE);
      SERIAL_PROTOCOLLN(filesize);
      sdpos = 0;

      SERIAL_PROTOCOLLNPGM(MSG_SD_FILE_SELECTED);
      getfilename(0, fname);
      lcd_setstatus(longFilename[0] ? longFilename : fname);
    }
    else {
      SERIAL_PROTOCOLPGM(MSG_SD_OPEN_FILE_FAIL);
      SERIAL_PROTOCOL(fname);
      SERIAL_PROTOCOLCHAR('.');
    }
  }
  else { //write
    if (!file.open(curDir, fname, O_CREAT | O_APPEND | O_WRITE | O_TRUNC)) {
      SERIAL_PROTOCOLPGM(MSG_SD_OPEN_FILE_FAIL);
      SERIAL_PROTOCOL(fname);
      SERIAL_PROTOCOLCHAR('.');
    }
    else {
      saving = true;
      SERIAL_PROTOCOLPGM(MSG_SD_WRITE_TO_FILE);
      SERIAL_PROTOCOLLN(name);
      lcd_setstatus(fname);
    }
  }
}
Example #24
0
void CardReader::openFile(char* name,bool read)
{
    if(!cardOK)
        return;
    file.close();
    sdprinting = false;


    SdFile myDir;
    curDir=&root;
    char *fname=name;

    char *dirname_start,*dirname_end;
    if(name[0]=='/')
    {
        dirname_start=strchr(name,'/')+1;
        while(dirname_start>0)
        {
            dirname_end=strchr(dirname_start,'/');
            //SERIAL_ECHO("start:");SERIAL_ECHOLN((int)(dirname_start-name));
            //SERIAL_ECHO("end  :");SERIAL_ECHOLN((int)(dirname_end-name));
            if(dirname_end>0 && dirname_end>dirname_start)
            {
                char subdirname[13];
                strncpy(subdirname, dirname_start, dirname_end-dirname_start);
                subdirname[dirname_end-dirname_start]=0;
                SERIAL_ECHOLN(subdirname);
                if(!myDir.open(curDir,subdirname,O_READ))
                {
                    SERIAL_PROTOCOLPGM(MSG_SD_OPEN_FILE_FAIL);
                    SERIAL_PROTOCOL(subdirname);
                    SERIAL_PROTOCOLLNPGM(".");
                    return;
                }
                else
                {
                    //SERIAL_ECHOLN("dive ok");
                }

                curDir=&myDir;
                dirname_start=dirname_end+1;
            }
            else // the reminder after all /fsa/fdsa/ is the filename
            {
                fname=dirname_start;
                //SERIAL_ECHOLN("remaider");
                //SERIAL_ECHOLN(fname);
                break;
            }

        }
    }
    else //relative path
    {
        curDir=&workDir;
    }
    if(read)
    {
        if (file.open(curDir, fname, O_READ))
        {
            filesize = file.fileSize();
            SERIAL_PROTOCOLPGM(MSG_SD_FILE_OPENED);
            SERIAL_PROTOCOL(fname);
            SERIAL_PROTOCOLPGM(MSG_SD_SIZE);
            SERIAL_PROTOCOLLN(filesize);
            sdpos = 0;

            SERIAL_PROTOCOLLNPGM(MSG_SD_FILE_SELECTED);
            LCD_MESSAGE(fname);
        }
        else
        {
            SERIAL_PROTOCOLPGM(MSG_SD_OPEN_FILE_FAIL);
            SERIAL_PROTOCOL(fname);
            SERIAL_PROTOCOLLNPGM(".");
        }
    }
    else
    {   //write
        if (!file.open(curDir, fname, O_CREAT | O_APPEND | O_WRITE | O_TRUNC))
        {
            SERIAL_PROTOCOLPGM(MSG_SD_OPEN_FILE_FAIL);
            SERIAL_PROTOCOL(fname);
            SERIAL_PROTOCOLLNPGM(".");
        }
        else
        {
            saving = true;
            SERIAL_PROTOCOLPGM(MSG_SD_WRITE_TO_FILE);
            SERIAL_PROTOCOLLN(name);
            LCD_MESSAGE(fname);
        }
    }

}
Example #25
0
void loop()
{
  if(count >=500)
  {  
    led2 = !led2;
    digitalWrite(redLEDpin, led2);
    count = 0;
  }
  count +=1;

  char clientline[BUFSIZ];
  char *filename;
  int image = 0;
  int index = 0;

  Client client = server.available();
  if (client) {
    boolean current_line_is_blank = true;

    index = 0;

    while (client.connected()) {
      if (client.available()) {
        char c = client.read();

        if (c != '\n' && c != '\r') {
          clientline[index] = c;
          index++;
          if (index >= BUFSIZ) 
            index = BUFSIZ -1;

          continue;
        }

        clientline[index] = 0;
        filename = 0;

        Serial.println(clientline);
       
        if (strstr(clientline, "GET /?") != 0) 
        {  
			if (!filename) filename = clientline + 5; 
			{
			Serial.println(filename);
			
                     
			int a=atoi(&filename[1]);
			Serial.println(a);
			
		int pin_num=0;
		int on_off=0;
		
			switch (a)
			{
				case 10
				pin_num=1;
				on_off=LOW;
				break;
				case 11
				pin_num=1;
				on_off=HIGH;
				break;
				
				case 20
				pin_num=2;
				on_off=LOW;
				break;
				case 21
				pin_num=2;
				on_off=HIGH;
				break;
				
				case 30
				pin_num=3;
				on_off=LOW;
				break;
				case 31
				pin_num=3;
				on_off=HIGH;
				break;
				
				case 40
				pin_num=4;
				on_off=LOW;
				break;
				case 41
				pin_num=4;
				on_off=HIGH;
				break;
				
				case 50
				pin_num=5;
				on_off=LOW;
				break;
				case 51
				pin_num=5;
				on_off=HIGH;
				break;
				
				case 60
				pin_num=6;
				on_off=LOW;
				break;
				case 61
				pin_num=6;
				on_off=HIGH;
				break;
				
				case 70
				pin_num=7;
				on_off=LOW;
				break;
				case 71
				pin_num=7;
				on_off=HIGH;
				break;
				
				case 80
				pin_num=8;
				on_off=LOW;
				break;
				case 81
				pin_num=8;
				on_off=HIGH;
				break;
				
			}
		
		if(pin_num!=0)
		{
			Serial.print("Pin:");
			Serial.print(pin_num);
			Serial.print(" State:");
			Serial.print(on_off);
			digitalWrite(pin_num, on_off);
		}
		
		
		
			
			
			}

        } 
        if (strstr(clientline, "GET / ") != 0) {
          filename = rootFileName;

        } 
        if (strstr(clientline, "GET /") != 0) {
          if (!filename) filename = clientline + 5; 

          (strstr(clientline, " HTTP"))[0] = 0;

          Serial.println(filename);

          if (! file.open(&root, filename, O_READ)) {
            client.println("HTTP/1.1 4041 Not Found");
            client.println("Content-Type: text/html");
            client.println();
            client.println("<h2>Error 4041</h2>");
            client.println("<s2>The file does not exist.<s2>");
            client.println("");
            break;
          }

          Serial.println("Opened!");
          //File types
          client.println("HTTP/1.1 200 OK");
          if (strstr(filename, ".htm") != 0)
            client.println("Content-Type: text/html");
          else if (strstr(filename, ".css") != 0)
            client.println("Content-Type: text/css");
          else if (strstr(filename, ".png") != 0)
            client.println("Content-Type: image/png");
          else if (strstr(filename, ".jpg") != 0)
            client.println("Content-Type: image/jpeg");
          else if (strstr(filename, ".gif") != 0)
            client.println("Content-Type: image/gif");
          else if (strstr(filename, ".3gp") != 0)
            client.println("Content-Type: video/mpeg");
          else if (strstr(filename, ".pdf") != 0)
            client.println("Content-Type: application/pdf");
          else if (strstr(filename, ".js") != 0)
            client.println("Content-Type: application/x-javascript");
          else if (strstr(filename, ".xml") != 0)
            client.println("Content-Type: application/xml");
          else
            client.println("Content-Type: text");
          client.println();

          int16_t c;
          while ((c = file.read()) >= 0) {
            //Serial.print((char)c); //Prints all HTML code to serial (For debuging)
            client.print((char)c); //Prints all HTML code for web page
          }

          //Hit counter math
          if(units >= 2)
          {
            hits ++;
            units = 0;
          }
          units +=1;
          //End hit counter math


          client.print("<html><body>"); //HTML code starts here
          client.print("<P align=\"center\">"); 
          client.print("Hits since reset: <b>");   
          client.print(hits); //Print hits to client
          client.print("</b><br>");

          photocellReading = analogRead(photocellPin); 
          client.print("Light reading: "); 
          client.print(photocellReading); //Prints light reading to client

          // A few threshholds
          if (photocellReading < 10) {
            client.print(" - Dark");
          } 
          else if (photocellReading < 200) {
            client.print(" - Dim");
          } 
          else if (photocellReading < 500) {
            client.print(" - Light");
          } 
          else if (photocellReading < 800) {
            client.print(" - Bright");
          } 
          else {
            client.print(" - Very bright");
          }

          client.print("</p></body></html>"); //HTML code ends here
          //End hit counter and light value

          file.close();

        } 
        else {
          client.println("HTTP/1.1 4042 Not Found");
          client.println("Content-Type: text/html");
          client.println();
          client.println("<h2>Error 4042</h2>");
          client.println("");
        }
        break;
      }
    }
    digitalWrite(greenLEDandBEEP, HIGH);
    delay(1);
    digitalWrite(greenLEDandBEEP, LOW);
    client.stop();
  }
Example #26
0
void  CardReader::lsDive(const char *prepend,SdFile parent)
{
    dir_t p;
    uint8_t cnt=0;

    while (parent.readDir(p, longFilename) > 0)
    {
        if( DIR_IS_SUBDIR(&p) && lsAction!=LS_Count && lsAction!=LS_GetFilename) // hence LS_SerialPrint
        {

            char path[13*2];
            char lfilename[13];
            createFilename(lfilename,p);

            path[0]=0;
            if(strlen(prepend)==0) //avoid leading / if already in prepend
            {
                strcat(path,"/");
            }
            strcat(path,prepend);
            strcat(path,lfilename);
            strcat(path,"/");

            //Serial.print(path);

            SdFile dir;
            if(!dir.open(parent,lfilename, O_READ))
            {
                if(lsAction==LS_SerialPrint)
                {
                    SERIAL_ECHO_START;
                    SERIAL_ECHOLN(MSG_SD_CANT_OPEN_SUBDIR);
                    SERIAL_ECHOLN(lfilename);
                }
            }
            lsDive(path,dir);
            //close done automatically by destructor of SdFile


        }
        else
        {
            if (p.name[0] == DIR_NAME_FREE) break;
            if (p.name[0] == DIR_NAME_DELETED || p.name[0] == '.'|| p.name[0] == '_') continue;
            if ( p.name[0] == '.')
            {
                if ( p.name[1] != '.')
                    continue;
            }

            if (!DIR_IS_FILE_OR_SUBDIR(&p)) continue;
            filenameIsDir=DIR_IS_SUBDIR(&p);


            if(!filenameIsDir)
            {
                if(p.name[8]!='G') continue;
                if(p.name[9]=='~') continue;
            }
            //if(cnt++!=nr) continue;
            createFilename(filename,p);
            if(lsAction==LS_SerialPrint)
            {
                SERIAL_PROTOCOL(prepend);
                SERIAL_PROTOCOLLN(filename);
            }
            else if(lsAction==LS_Count)
            {
                nrFiles++;
            }
            else if(lsAction==LS_GetFilename)
            {
                if(cnt==nrFiles)
                    return;
                cnt++;

            }
        }
    }
}
Example #27
0
void CardReader::removeFile(char* name)
{
    if(!cardOK)
        return;
    file.close();
    sdprinting = false;


    SdFile myDir;
    curDir=&root;
    char *fname=name;

    char *dirname_start,*dirname_end;
    if(name[0]=='/')
    {
        dirname_start=strchr(name,'/')+1;
        while(dirname_start>0)
        {
            dirname_end=strchr(dirname_start,'/');
            //SERIAL_ECHO("start:");SERIAL_ECHOLN((int)(dirname_start-name));
            //SERIAL_ECHO("end  :");SERIAL_ECHOLN((int)(dirname_end-name));
            if(dirname_end>0 && dirname_end>dirname_start)
            {
                char subdirname[13];
                strncpy(subdirname, dirname_start, dirname_end-dirname_start);
                subdirname[dirname_end-dirname_start]=0;
                SERIAL_ECHOLN(subdirname);
                if(!myDir.open(curDir,subdirname,O_READ))
                {
                    SERIAL_PROTOCOLPGM("open failed, File: ");
                    SERIAL_PROTOCOL(subdirname);
                    SERIAL_PROTOCOLLNPGM(".");
                    return;
                }
                else
                {
                    //SERIAL_ECHOLN("dive ok");
                }

                curDir=&myDir;
                dirname_start=dirname_end+1;
            }
            else // the reminder after all /fsa/fdsa/ is the filename
            {
                fname=dirname_start;
                //SERIAL_ECHOLN("remaider");
                //SERIAL_ECHOLN(fname);
                break;
            }

        }
    }
    else //relative path
    {
        curDir=&workDir;
    }
    if (file.remove(curDir, fname))
    {
        SERIAL_PROTOCOLPGM("File deleted:");
        SERIAL_PROTOCOL(fname);
        sdpos = 0;
    }
    else
    {
        SERIAL_PROTOCOLPGM("Deletion failed, File: ");
        SERIAL_PROTOCOL(fname);
        SERIAL_PROTOCOLLNPGM(".");
    }

}
Example #28
0
int UTFT_SdRaw::pan(int dispx, int dispy, int sx, int sy, unsigned long offsetx, unsigned long offsety, unsigned long sizex, unsigned long sizey, char *filename, bool iswap)
{
	char buffer[2*sx];
	int cx, cy, cp;
	word temp, result;
	unsigned long temp1,temp2;
	temp1=sizex*2;
	temp2=offsetx*2;
	if (dataFile.open(filename))
	{
		cbi(_UTFT->P_CS, _UTFT->B_CS);
		cx=0;
		cy=0;
		result=sx;
		if (_UTFT->orient==PORTRAIT)
		{
			_UTFT->setXY(dispx, dispy, dispx+sx-1, dispy+sy-1);
		}
		for(int n=0;n<sy;n++)
		{
			dataFile.seekSet(((n+offsety)*temp1)+temp2);
			result=dataFile.read(&buffer,2*sx);
			if (_UTFT->orient==PORTRAIT)
			{
				for (int i=0; i<result; i+=2)
				{
					if(iswap==1)
					{
						_UTFT->LCD_Write_DATA(buffer[i+1],buffer[i]);
					}
					else
					{
					_UTFT->LCD_Write_DATA(buffer[i],buffer[i+1]);
					}						
				}
			}
			else
			{
				cp=0;
				while (cp<result)
				{
					if (((result-cp)/2)<(sx-cx))
					{
						_UTFT->setXY(dispx+cx, dispy+cy, dispx+cx+((result-cp)/2)-1, dispy+cy);
						for (int i=(result-cp)-2; i>=0; i-=2)
						{
							if(iswap==1)
							{
								_UTFT->LCD_Write_DATA(buffer[cp+i+1],buffer[cp+i]);
							}
							else
							{
								_UTFT->LCD_Write_DATA(buffer[cp+i],buffer[cp+i+1]);
							}						
						}
						cx+=((result-cp)/2);
						cp=result;
					}
					else
					{
						_UTFT->setXY(dispx+cx, dispy+cy, dispx+sx-1, dispy+cy);
						for (int i=sx-cx-1; i>=0; i--)
						{
							if(iswap==1)
							{
								_UTFT->LCD_Write_DATA(buffer[cp+(i*2)+1],buffer[cp+(i*2)]);
							}
							else
							{
								_UTFT->LCD_Write_DATA(buffer[cp+(i*2)],buffer[cp+(i*2)+1]);
							}
						}
						cp+=(sx-cx)*2;
						cx=0;
						cy++;
					}
				}
			}              
		}
		dataFile.close();
		_UTFT->setXY(0,0,_UTFT->getDisplayXSize()-1,_UTFT->getDisplayYSize()-1);
		sbi(_UTFT->P_CS, _UTFT->B_CS);
		return 0;
	}
	else
	{
		return 99;
	}
}
Example #29
0
File SDClass::open(const char *filepath, uint8_t mode) {
  /*

     Open the supplied file path for reading or writing.

     The file content can be accessed via the `file` property of
     the `SDClass` object--this property is currently
     a standard `SdFile` object from `sdfatlib`.

     Defaults to read only.

     If `write` is true, default action (when `append` is true) is to
     append data to the end of the file.

     If `append` is false then the file will be truncated first.

     If the file does not exist and it is opened for writing the file
     will be created.

     An attempt to open a file for reading that does not exist is an
     error.

   */

  int pathidx;

  // do the interative search
  SdFile parentdir = getParentDir(filepath, &pathidx);
  // no more subdirs!

  filepath += pathidx;

  if (! filepath[0]) {
    // it was the directory itself!
    return File(parentdir, "/");
  }

  // Open the file itself
  SdFile file;

  // failed to open a subdir!
  if (!parentdir.isOpen())
    return File();

  // there is a special case for the Root directory since its a static dir
  if (parentdir.isRoot()) {
    if ( ! file.open(SD.root, filepath, mode)) {
      // failed to open the file :(
      return File();
    }
    // dont close the root!
  } else {
    if ( ! file.open(parentdir, filepath, mode)) {
      return File();
    }
    // close the parent
    parentdir.close();
  }

  if (mode & (O_APPEND | O_WRITE)) 
    file.seekSet(file.fileSize());
  return File(file, filepath);
}
Example #30
0
void setup()
{
  Serial.begin(BPS_115200);
  PgmPrintln("Type any character to start");
  while (!Serial.available());

  Serial.print("\nInitializing SD card...");
  // On the Ethernet Shield, CS is pin 4. It's set as an output by default.
  // Note that even if it's not used as the CS pin, the hardware SS pin 
  // (10 on most Arduino boards, 53 on the Mega) must be left as an output 
  // or the SD library functions will not work. 
  //pinMode(10, OUTPUT);     // change this to 53 on a mega


  // we'll use the initialization code from the utility libraries
  // since we're just testing if the card is working!
  if (!card.init(SPI_HALF_SPEED, chipSelect)) {
    Serial.println("initialization failed. Things to check:");
    Serial.println("* is a card is inserted?");
    Serial.println("* Is your wiring correct?");
    Serial.println("* did you change the chipSelect pin to match your shield or module?");
    return;
  } else {
   Serial.println("Wiring is correct and a card is present."); 
  }

  // print the type of card
  Serial.print("\nCard type: ");
  switch(card.type()) {
    case SD_CARD_TYPE_SD1:
      Serial.println("SD1");
      break;
    case SD_CARD_TYPE_SD2:
      Serial.println("SD2");
      break;
    case SD_CARD_TYPE_SDHC:
      Serial.println("SDHC");
      break;
    default:
      Serial.println("Unknown");
  }

  // Now we will try to open the 'volume'/'partition' - it should be FAT16 or FAT32
  if (!volume.init(card)) {
    Serial.println("Could not find FAT16/FAT32 partition.\nMake sure you've formatted the card");
    return;
  }


  // print the type and size of the first FAT-type volume
  uint32_t volumesize;
  Serial.print("\nVolume type is FAT");
  Serial.println(volume.fatType(), DEC);
  Serial.println();
  
  volumesize = volume.blocksPerCluster();    // clusters are collections of blocks
  volumesize *= volume.clusterCount();       // we'll have a lot of clusters
  volumesize *= 512;                            // SD card blocks are always 512 bytes
  Serial.print("Volume size (bytes): ");
  Serial.println(volumesize);
  Serial.print("Volume size (Kbytes): ");
  volumesize /= 1024;
  Serial.println(volumesize);
  Serial.print("Volume size (Mbytes): ");
  volumesize /= 1024;
  Serial.println(volumesize);

  
  Serial.println("\nFiles found on the card (name, date and size in bytes): ");
  root.openRoot(volume);
  
  // list all files in the card with date and size
  root.ls(LS_R | LS_DATE | LS_SIZE);
}