Beispiel #1
0
void initSensor(Sensor * sensor) {
	/* esempio di configurazione cablata nel codice:
	 * ID 1 -> allarme
	 * ID 2 -> allarme e confidenzialità
	 * ID 3 -> niente
	 */
	if (sensor->ID < 3) {
			setAlarm(sensor, True);
			setTreshold(sensor, UPPER_TRESHOLD, LOWER_TRESHOLD);
	} else setAlarm(sensor, False);

	if (sensor->ID == 2) sensor->confidential=True;
	else sensor->confidential=False;
}
/*
 * STUB: once registerhandler is called, this routine
 * gets called each time SIGNAL_TYPE is sent to this process
 */
void 
interruptHandler(int sig, siginfo_t *sip, void *contextVP)
{

  /* Tell compiler not to complain about unused variable
     in this stub version of the fuction */
  /*NOTUSED*/
  ucontext_t *context = (ucontext_t *)contextVP;

  /*
   * SIGALRM is masked on entry 
   */
  sigset_t mask;
  int ret = sigprocmask(0, NULL, &mask);
  assert(!ret);
  assert(sigismember(&mask, SIGALRM));

  if(loud){
    printf("Made it to handler with interrupted thread's state at %p\n",
           context);
  }
  setAlarm();


  /* 
   * Your code here 
   */

  return;
}
int thread_yield(){

#ifdef O_PREEMPTION
  interruptsOff();
#endif
  
  //le thread courant
  thread *th1 = getRunningThread();
  //le prochain thread
  thread *th2 = prochainThread();

#ifdef O_PRIORITE
  updatePriority(th1);
#endif

#ifdef O_PREEMTION
  setAlarm();
#endif   
  if(th2->tid != th1->tid){
    addInFifo(th1);
    setRunningThread(th2);
#ifdef O_PREEMPTION
  interruptsOn();
#endif
    swapcontext(th1->context,th2->context);
  }
  return 0;
}
Beispiel #4
0
bool RTC_DS3231::setAlarm(uint8_t alarm, alarm_t tm, uint8_t mode) {

   setAlarm(alarm);

   Wire.beginTransmission(DS3231_ADDRESS);
   Wire.write(alarm_addr[alarm-1]);

   if(alarm==DS3231_ALARM_1) {
      if(mode>0)
         Wire.write(bin2bcd(tm.ss) & ~0x80 );    // bit A*M1 = 0
      else
         Wire.write(0x80);                    // bit A*M1 = 1
   }
   if(mode>1)
      Wire.write(bin2bcd(tm.mm) & ~0x80 );       // bit A*M2 = 0
   else
      Wire.write(0x80);                       // bit A*M2 = 0

   if(mode>2)
      Wire.write(bin2bcd(tm.hh) & ~0x80 );       // bit A*M3 = 0
   else
      Wire.write(0x80);                       // bit A*M3 = 1

   if(mode>3)
      Wire.write(bin2bcd(tm.d) & ~0xC0 );     // bit A*M4 = 0, bit DY/DT = 0
   else
      Wire.write(0x80);                       // bit A*M4 = 1

   Wire.endTransmission();

   return true;
   // This code below to check Time was set right or not
   // alarm_t tmr = readAlarmTime(alarm);
   // return (tmr.d==tm.d && tmr.hh==tm.hh && tmr.mm==tm.mm && tmr.ss==tm.ss) ? true : false;
}
/*
 * Should be called when you initialize threads package.
 * Many of the calls won't make sense at first -- study the
 * man pages!
 */
void 
registerHandler()
{
  struct sigaction action;
  int error;
  static int hasBeenCalled = 0;

  assert(!hasBeenCalled); /* should only register once */
  hasBeenCalled = 1;
  
  action.sa_handler = NULL;
  action.sa_sigaction = interruptHandler;
  error = sigemptyset(&action.sa_mask);/* SIGNAL_TYPE will be blocked by default
                                        * while handler invoked.
                                        * No mask needed */
  assert(!error);
  action.sa_flags = SA_SIGINFO; /* use sa_sigaction as handler
                                 * instead of sa_handler*/

  if(sigaction(SIGNAL_TYPE, &action, NULL)){
    perror("Setting up signal handler");
    assert(0);
  }
 
  setAlarm();
}
void CalendarCondition::doRestore(const QVariantMap& data)
{
    setNoAllDay(data[KEY_NO_ALL_DAY].toBool());
    setAlarm(data[KEY_ALARM].toBool());
    setRecurring(data[KEY_RECURRING].toBool());
    setCollectionId(data[KEY_COLLECTION].toString());
    setKeyword(data[KEY_KEYWORD].toString());
}
Beispiel #7
0
bool RTC_DS3231::setAlarmRepeat(uint8_t alarm) {
   setAlarm(alarm);
   Wire.beginTransmission(DS3231_ADDRESS);
   Wire.write(alarm_addr[alarm-1]);
   if(alarm==DS3231_ALARM_1) {
      Wire.write(0x80);                    // bit A*M1 = 1
   }
   Wire.write(0x80);                    // bit A*M1 = 1
   Wire.write(0x80);                    // bit A*M1 = 1
   Wire.write(0x80);                    // bit A*M1 = 1
   Wire.endTransmission();
   return true;
}
// Output the time of day, followed by the current Alarm's reminder
// Then set an alarm for the next reminder
void writeAlarm(int sig)
{
	if(registeredaddr != (struct sockaddr *)NULL)
	{
		
		sendPacket();
		if(currentAlarm != NULL)
		{
			currentAlarm = currentAlarm->next;
			setAlarm();
		}
		
	}
	
}
Beispiel #9
0
bool RTC_DS3231::setAlarmHour(uint8_t alarm, uint8_t hh) {

   setAlarm(alarm);
   Wire.beginTransmission(DS3231_ADDRESS);
   Wire.write(alarm_addr[alarm-1]);
   if(alarm==DS3231_ALARM_1)
      Wire.write(0);                             // second = 0 and A*M1 = 0
   Wire.write(0);                                // minute = 0 and A*M2 = 0
   Wire.write(bin2bcd(hh) & ~0x80);              // hour = hh and A*M3 = 0
   Wire.write(0x80);                             // A*M4 = 1;
   Wire.endTransmission();

   return true;
   // This code below to check Time was set right or not
   // return (hh==readAlarmTime(alarm).hh) ? true:false;
}
Beispiel #10
0
//Creates an alarm from the cloud
//hh.mm.ss.b.b.b.d (b = 1/0) (d = - or 1,2,3,4,5,6,7)
int createAlarm(String command) {
    if(command.length() != 16) {
        return -1;
    }
    int hour = command.substring(0,2).toInt();
    int minute = command.substring(3,5).toInt();
    int second = command.substring(6,8).toInt();
    int isOnce = command.substring(9,10).toInt();
    int light = command.substring(11,12).toInt();
    int sound = command.substring(13,14).toInt();
    int dayOfWeek;
    if(command.substring(15) == "-") {
        dayOfWeek = -1;
    } else {
        dayOfWeek = command.substring(15).toInt();
    }
    setAlarm(hour, minute, second, isOnce, light, sound, dayOfWeek);
    return 1;
}
void RTCAlarm_IRQHandler(void)
{
	if (RTC->CRH & RTC_CRL_ALRF)
	{
		osSignalSet(osAlarmTask, 0x02);
		
		/* This bit is set by hardware when the 32-bit programmable counter reaches the threshold set 
			 in the RTC_ALR register. An interrupt is generated if ALRIE=1 in the RTC_CRH register. It
			 can be cleared only by software. Writing ‘1’ has no effect. */
		
		/* Clear the corresponding RTC pending bit */
		RTC->CRL &= (uint16_t)~RTC_CRL_ALRF;

		//Set pending register
	  EXTI->PR |= EXTI_PR_PR17 ;

		/* Set immediately alarm to obtain the best accuracy */
		setAlarm(15);
  }
}
Beispiel #12
0
// We return Ok if we have the lock,
// Fail if we timed out
// Error for other cases
//
retCode timedLock(lockedPo l,double tmout)
{
  if(fabs(tmout)<0.001){
    if(pthread_mutex_trylock(&l->lock.mutex)!=0)
      return Fail;
    else
      return Ok;
  }
  else{
    setAlarm(tmout,NULL,NULL);
    switch(pthread_mutex_lock(&l->lock.mutex)){
    case 0:
      cancelAlarm();
      return Ok;
    case ETIMEDOUT:
      cancelAlarm();
      return Fail;
    default:
      cancelAlarm();
      return Error;
    }
  }
}
Beispiel #13
0
//Add alarms from eeprom
void addAlarms() {
    for(int i=0; i<vectorAlarmTimes.size(); ++i) {
        setAlarm(vectorAlarmTimes.at(i).at(0), vectorAlarmTimes.at(i).at(1), vectorAlarmTimes.at(i).at(2),
                 vectorAlarmTimes.at(i).at(3), vectorAlarmTimes.at(i).at(4), vectorAlarmTimes.at(i).at(5), vectorAlarmTimes.at(i).at(6));
    }
}
Beispiel #14
0
void parseAlarmJson(char* content){
    int r;
    int i = 2;
	
	int startidx = 0;
	int charAmount = 0;

    int usedAlarms[maxAlarms()];
    int j;
    
    jsmn_parser p;
    jsmntok_t token[160]; /* We expect no more than 128 tokens */

    jsmn_init(&p);
    r = jsmn_parse(&p, content, strlen(content), token, sizeof(token)/sizeof(token[0]));
    if (r <= 0) {
        printf("Failed to parse JSON: %d \n", r);
        return;
    }else{
        printf("Aantal tokens found: %d \n", r);
    }


    struct _tm time = GetRTCTime();
    for(j = 0; j < maxAlarms(); j++){
        usedAlarms[j] = 0;
    }
    for(i = 2; i < r; i++)
    {
        int id = 0;
        u_short port = 0;
        char url[24];
        char ip[24];
        char name[17];
        char str2[16];
        char st = -1;
        char oo = -1;
        memset(url, 0, 24);
        memset(ip, 0, 24);
        memset(name, 0, 17);

        for (i = i; (st == -1 && i < r); i+=2) {                                //Zodra ST is gevonden, betekent dit de laatste token van een alarm.
            if (jsoneq(content, &token[i], "YYYY") == 0) {
                time.tm_year= getIntegerToken(content, &token[i + 1]) - 1900;
            }else if (jsoneq(content, &token[i], "MM") == 0) {
                time.tm_mon=  getIntegerToken(content, &token[i + 1]) - 1;
            }else if (jsoneq(content, &token[i], "DD") == 0) {
                time.tm_mday =  getIntegerToken(content, &token[i + 1]);
            }else if (jsoneq(content, &token[i], "hh") == 0) {
                time.tm_hour = 	getIntegerToken(content, &token[i + 1]);
            }else if (jsoneq(content, &token[i], "mm") == 0) {
                time.tm_min = getIntegerToken(content, &token[i + 1]);
            }else if (jsoneq(content, &token[i], "ss") == 0) {
                time.tm_sec = getIntegerToken(content, &token[i + 1]);
            }else if (jsoneq(content, &token[i], "id") == 0) {
                id = getIntegerToken(content, &token[i + 1]);
            }else if (jsoneq(content, &token[i], "port") == 0) {
                port = getIntegerToken(content, &token[i + 1]);
            }else if (jsoneq(content, &token[i], "ip") == 0) {
                getStringToken(content, &token[i + 1], ip, 24);
            }else if (jsoneq(content, &token[i], "url") == 0) {
                getStringToken(content, &token[i + 1], url, 24);
            }else if (jsoneq(content, &token[i], "name") == 0) {
                getStringToken(content, &token[i + 1], name, 18);
            }else if (jsoneq(content, &token[i], "oo") == 0) {
                oo = getIntegerToken(content, &token[i + 1]);
            }else if (jsoneq(content, &token[i], "st") == 0) {
                st = getIntegerToken(content, &token[i + 1]);
            }
        }

        int idx = alarmExist(id);
        if(idx == -1){
            printf("New alarm found!\n");
            printf("Alarm time is: %02d:%02d:%02d\n", time.tm_hour, time.tm_min, time.tm_sec);
            printf("Alarm date is: %02d.%02d.%02d\n", time.tm_mday, (time.tm_mon + 1), (time.tm_year + 1900));
            printf("Alarm stream data is: %s:%d%s\n", ip, port, url);
            printf("Alarm id and name and st is: %d %s %d\n\n", id, name, st);
			
			charAmount = 0;
			for (i = 0; i < 16;i++){
				if (name[i] != 0){
					charAmount = charAmount + 1;
				}
			}
			
			startidx = (8-(charAmount/2));
			
			charAmount = 0;
			for(i = 0; i < 16; i++){
				if (i >= startidx){
					if (name[charAmount] != 0){
						str2[i] = name[charAmount];
					} else {
						str2[i] = ' ';
					}	
					charAmount++;
				} else {
					str2[i] = ' ';
				}
			}
			

            //zoek naar een vrije plaats in de alarm array
            for(j = 0; j < maxAlarms(); j++){
                if(usedAlarms[j] == 0){ //Dit is een lege plaats, hier kunnen we ons nieuwe alarm plaatsen
					if (oo == 1){
						eenmaligAlarm(time,str2,ip,port,url,st,id,j);
					} else {
						setAlarm(time, str2, ip, port, url, st, id, j);
					}
                    usedAlarms[j] = 1;
                    j = 10;             //Uit de for loop
                }
            }
        }else{
            usedAlarms[idx] = 1; //Alarm bestaat al, dus we houden deze plaats vrij voor dat alarm
        }
    }
    for(j = 0; j < maxAlarms(); j++){ //Alle overige plaatsen, die wij niet gezet hebben, verwijderen.
        if(usedAlarms[j] == 0){
            deleteAlarm(j);
        };
    }
}
Beispiel #15
0
int main(int argc, char **argv){
  sqlite3_int64 iBegin;        /* Start time of this program */
  int quietFlag = 0;           /* True if --quiet or -q */
  int verboseFlag = 0;         /* True if --verbose or -v */
  char *zInsSql = 0;           /* SQL statement for --load-db or --load-sql */
  int iFirstInsArg = 0;        /* First argv[] to use for --load-db or --load-sql */
  sqlite3 *db = 0;             /* The open database connection */
  sqlite3_stmt *pStmt;         /* A prepared statement */
  int rc;                      /* Result code from SQLite interface calls */
  Blob *pSql;                  /* For looping over SQL scripts */
  Blob *pDb;                   /* For looping over template databases */
  int i;                       /* Loop index for the argv[] loop */
  int onlySqlid = -1;          /* --sqlid */
  int onlyDbid = -1;           /* --dbid */
  int nativeFlag = 0;          /* --native-vfs */
  int rebuildFlag = 0;         /* --rebuild */
  int vdbeLimitFlag = 0;       /* --limit-vdbe */
  int timeoutTest = 0;         /* undocumented --timeout-test flag */
  int runFlags = 0;            /* Flags sent to runSql() */
  char *zMsg = 0;              /* Add this message */
  int nSrcDb = 0;              /* Number of source databases */
  char **azSrcDb = 0;          /* Array of source database names */
  int iSrcDb;                  /* Loop over all source databases */
  int nTest = 0;               /* Total number of tests performed */
  char *zDbName = "";          /* Appreviated name of a source database */
  const char *zFailCode = 0;   /* Value of the TEST_FAILURE environment variable */
  int cellSzCkFlag = 0;        /* --cell-size-check */
  int sqlFuzz = 0;             /* True for SQL fuzz testing. False for DB fuzz */
  int iTimeout = 120;          /* Default 120-second timeout */
  int nMem = 0;                /* Memory limit */
  char *zExpDb = 0;            /* Write Databases to files in this directory */
  char *zExpSql = 0;           /* Write SQL to files in this directory */

  iBegin = timeOfDay();
#ifdef __unix__
  signal(SIGALRM, timeoutHandler);
#endif
  g.zArgv0 = argv[0];
  zFailCode = getenv("TEST_FAILURE");
  for(i=1; i<argc; i++){
    const char *z = argv[i];
    if( z[0]=='-' ){
      z++;
      if( z[0]=='-' ) z++;
      if( strcmp(z,"cell-size-check")==0 ){
        cellSzCkFlag = 1;
      }else
      if( strcmp(z,"dbid")==0 ){
        if( i>=argc-1 ) fatalError("missing arguments on %s", argv[i]);
        onlyDbid = integerValue(argv[++i]);
      }else
      if( strcmp(z,"export-db")==0 ){
        if( i>=argc-1 ) fatalError("missing arguments on %s", argv[i]);
        zExpDb = argv[++i];
      }else
      if( strcmp(z,"export-sql")==0 ){
        if( i>=argc-1 ) fatalError("missing arguments on %s", argv[i]);
        zExpSql = argv[++i];
      }else
      if( strcmp(z,"help")==0 ){
        showHelp();
        return 0;
      }else
      if( strcmp(z,"limit-mem")==0 ){
        if( i>=argc-1 ) fatalError("missing arguments on %s", argv[i]);
        nMem = integerValue(argv[++i]);
      }else
      if( strcmp(z,"limit-vdbe")==0 ){
        vdbeLimitFlag = 1;
      }else
      if( strcmp(z,"load-sql")==0 ){
        zInsSql = "INSERT INTO xsql(sqltext) VALUES(CAST(readfile(?1) AS text))";
        iFirstInsArg = i+1;
        break;
      }else
      if( strcmp(z,"load-db")==0 ){
        zInsSql = "INSERT INTO db(dbcontent) VALUES(readfile(?1))";
        iFirstInsArg = i+1;
        break;
      }else
      if( strcmp(z,"m")==0 ){
        if( i>=argc-1 ) fatalError("missing arguments on %s", argv[i]);
        zMsg = argv[++i];
      }else
      if( strcmp(z,"native-vfs")==0 ){
        nativeFlag = 1;
      }else
      if( strcmp(z,"quiet")==0 || strcmp(z,"q")==0 ){
        quietFlag = 1;
        verboseFlag = 0;
      }else
      if( strcmp(z,"rebuild")==0 ){
        rebuildFlag = 1;
      }else
      if( strcmp(z,"result-trace")==0 ){
        runFlags |= SQL_OUTPUT;
      }else
      if( strcmp(z,"sqlid")==0 ){
        if( i>=argc-1 ) fatalError("missing arguments on %s", argv[i]);
        onlySqlid = integerValue(argv[++i]);
      }else
      if( strcmp(z,"timeout")==0 ){
        if( i>=argc-1 ) fatalError("missing arguments on %s", argv[i]);
        iTimeout = integerValue(argv[++i]);
      }else
      if( strcmp(z,"timeout-test")==0 ){
        timeoutTest = 1;
#ifndef __unix__
        fatalError("timeout is not available on non-unix systems");
#endif
      }else
      if( strcmp(z,"verbose")==0 || strcmp(z,"v")==0 ){
        quietFlag = 0;
        verboseFlag = 1;
        runFlags |= SQL_TRACE;
      }else
      {
        fatalError("unknown option: %s", argv[i]);
      }
    }else{
      nSrcDb++;
      azSrcDb = safe_realloc(azSrcDb, nSrcDb*sizeof(azSrcDb[0]));
      azSrcDb[nSrcDb-1] = argv[i];
    }
  }
  if( nSrcDb==0 ) fatalError("no source database specified");
  if( nSrcDb>1 ){
    if( zMsg ){
      fatalError("cannot change the description of more than one database");
    }
    if( zInsSql ){
      fatalError("cannot import into more than one database");
    }
  }

  /* Process each source database separately */
  for(iSrcDb=0; iSrcDb<nSrcDb; iSrcDb++){
    rc = sqlite3_open(azSrcDb[iSrcDb], &db);
    if( rc ){
      fatalError("cannot open source database %s - %s",
      azSrcDb[iSrcDb], sqlite3_errmsg(db));
    }
    rc = sqlite3_exec(db,
       "CREATE TABLE IF NOT EXISTS db(\n"
       "  dbid INTEGER PRIMARY KEY, -- database id\n"
       "  dbcontent BLOB            -- database disk file image\n"
       ");\n"
       "CREATE TABLE IF NOT EXISTS xsql(\n"
       "  sqlid INTEGER PRIMARY KEY,   -- SQL script id\n"
       "  sqltext TEXT                 -- Text of SQL statements to run\n"
       ");"
       "CREATE TABLE IF NOT EXISTS readme(\n"
       "  msg TEXT -- Human-readable description of this file\n"
       ");", 0, 0, 0);
    if( rc ) fatalError("cannot create schema: %s", sqlite3_errmsg(db));
    if( zMsg ){
      char *zSql;
      zSql = sqlite3_mprintf(
               "DELETE FROM readme; INSERT INTO readme(msg) VALUES(%Q)", zMsg);
      rc = sqlite3_exec(db, zSql, 0, 0, 0);
      sqlite3_free(zSql);
      if( rc ) fatalError("cannot change description: %s", sqlite3_errmsg(db));
    }
    if( zInsSql ){
      sqlite3_create_function(db, "readfile", 1, SQLITE_UTF8, 0,
                              readfileFunc, 0, 0);
      rc = sqlite3_prepare_v2(db, zInsSql, -1, &pStmt, 0);
      if( rc ) fatalError("cannot prepare statement [%s]: %s",
                          zInsSql, sqlite3_errmsg(db));
      rc = sqlite3_exec(db, "BEGIN", 0, 0, 0);
      if( rc ) fatalError("cannot start a transaction");
      for(i=iFirstInsArg; i<argc; i++){
        sqlite3_bind_text(pStmt, 1, argv[i], -1, SQLITE_STATIC);
        sqlite3_step(pStmt);
        rc = sqlite3_reset(pStmt);
        if( rc ) fatalError("insert failed for %s", argv[i]);
      }
      sqlite3_finalize(pStmt);
      rc = sqlite3_exec(db, "COMMIT", 0, 0, 0);
      if( rc ) fatalError("cannot commit the transaction: %s", sqlite3_errmsg(db));
      rebuild_database(db);
      sqlite3_close(db);
      return 0;
    }
    if( zExpDb!=0 || zExpSql!=0 ){
      sqlite3_create_function(db, "writefile", 2, SQLITE_UTF8, 0,
                              writefileFunc, 0, 0);
      if( zExpDb!=0 ){
        const char *zExDb = 
          "SELECT writefile(printf('%s/db%06d.db',?1,dbid),dbcontent),"
          "       dbid, printf('%s/db%06d.db',?1,dbid), length(dbcontent)"
          "  FROM db WHERE ?2<0 OR dbid=?2;";
        rc = sqlite3_prepare_v2(db, zExDb, -1, &pStmt, 0);
        if( rc ) fatalError("cannot prepare statement [%s]: %s",
                            zExDb, sqlite3_errmsg(db));
        sqlite3_bind_text64(pStmt, 1, zExpDb, strlen(zExpDb),
                            SQLITE_STATIC, SQLITE_UTF8);
        sqlite3_bind_int(pStmt, 2, onlyDbid);
        while( sqlite3_step(pStmt)==SQLITE_ROW ){
          printf("write db-%d (%d bytes) into %s\n",
             sqlite3_column_int(pStmt,1),
             sqlite3_column_int(pStmt,3),
             sqlite3_column_text(pStmt,2));
        }
        sqlite3_finalize(pStmt);
      }
      if( zExpSql!=0 ){
        const char *zExSql = 
          "SELECT writefile(printf('%s/sql%06d.txt',?1,sqlid),sqltext),"
          "       sqlid, printf('%s/sql%06d.txt',?1,sqlid), length(sqltext)"
          "  FROM xsql WHERE ?2<0 OR sqlid=?2;";
        rc = sqlite3_prepare_v2(db, zExSql, -1, &pStmt, 0);
        if( rc ) fatalError("cannot prepare statement [%s]: %s",
                            zExSql, sqlite3_errmsg(db));
        sqlite3_bind_text64(pStmt, 1, zExpSql, strlen(zExpSql),
                            SQLITE_STATIC, SQLITE_UTF8);
        sqlite3_bind_int(pStmt, 2, onlySqlid);
        while( sqlite3_step(pStmt)==SQLITE_ROW ){
          printf("write sql-%d (%d bytes) into %s\n",
             sqlite3_column_int(pStmt,1),
             sqlite3_column_int(pStmt,3),
             sqlite3_column_text(pStmt,2));
        }
        sqlite3_finalize(pStmt);
      }
      sqlite3_close(db);
      return 0;
    }
  
    /* Load all SQL script content and all initial database images from the
    ** source db
    */
    blobListLoadFromDb(db, "SELECT sqlid, sqltext FROM xsql", onlySqlid,
                           &g.nSql, &g.pFirstSql);
    if( g.nSql==0 ) fatalError("need at least one SQL script");
    blobListLoadFromDb(db, "SELECT dbid, dbcontent FROM db", onlyDbid,
                       &g.nDb, &g.pFirstDb);
    if( g.nDb==0 ){
      g.pFirstDb = safe_realloc(0, sizeof(Blob));
      memset(g.pFirstDb, 0, sizeof(Blob));
      g.pFirstDb->id = 1;
      g.pFirstDb->seq = 0;
      g.nDb = 1;
      sqlFuzz = 1;
    }
  
    /* Print the description, if there is one */
    if( !quietFlag ){
      int i;
      zDbName = azSrcDb[iSrcDb];
      i = strlen(zDbName) - 1;
      while( i>0 && zDbName[i-1]!='/' && zDbName[i-1]!='\\' ){ i--; }
      zDbName += i;
      sqlite3_prepare_v2(db, "SELECT msg FROM readme", -1, &pStmt, 0);
      if( pStmt && sqlite3_step(pStmt)==SQLITE_ROW ){
        printf("%s: %s\n", zDbName, sqlite3_column_text(pStmt,0));
      }
      sqlite3_finalize(pStmt);
    }

    /* Rebuild the database, if requested */
    if( rebuildFlag ){
      if( !quietFlag ){
        printf("%s: rebuilding... ", zDbName);
        fflush(stdout);
      }
      rebuild_database(db);
      if( !quietFlag ) printf("done\n");
    }
  
    /* Close the source database.  Verify that no SQLite memory allocations are
    ** outstanding.
    */
    sqlite3_close(db);
    if( sqlite3_memory_used()>0 ){
      fatalError("SQLite has memory in use before the start of testing");
    }

    /* Limit available memory, if requested */
    if( nMem>0 ){
      void *pHeap;
      sqlite3_shutdown();
      pHeap = malloc(nMem);
      if( pHeap==0 ){
        fatalError("failed to allocate %d bytes of heap memory", nMem);
      }
      sqlite3_config(SQLITE_CONFIG_HEAP, pHeap, nMem, 128);
    }
  
    /* Register the in-memory virtual filesystem
    */
    formatVfs();
    inmemVfsRegister();
    
    /* Run a test using each SQL script against each database.
    */
    if( !verboseFlag && !quietFlag ) printf("%s:", zDbName);
    for(pSql=g.pFirstSql; pSql; pSql=pSql->pNext){
      for(pDb=g.pFirstDb; pDb; pDb=pDb->pNext){
        int openFlags;
        const char *zVfs = "inmem";
        sqlite3_snprintf(sizeof(g.zTestName), g.zTestName, "sqlid=%d,dbid=%d",
                         pSql->id, pDb->id);
        if( verboseFlag ){
          printf("%s\n", g.zTestName);
          fflush(stdout);
        }else if( !quietFlag ){
          static int prevAmt = -1;
          int idx = pSql->seq*g.nDb + pDb->id - 1;
          int amt = idx*10/(g.nDb*g.nSql);
          if( amt!=prevAmt ){
            printf(" %d%%", amt*10);
            fflush(stdout);
            prevAmt = amt;
          }
        }
        createVFile("main.db", pDb->sz, pDb->a);
        openFlags = SQLITE_OPEN_CREATE | SQLITE_OPEN_READWRITE;
        if( nativeFlag && pDb->sz==0 ){
          openFlags |= SQLITE_OPEN_MEMORY;
          zVfs = 0;
        }
        rc = sqlite3_open_v2("main.db", &db, openFlags, zVfs);
        if( rc ) fatalError("cannot open inmem database");
#ifdef SQLITE_ENABLE_JSON1
        {
          extern int sqlite3_json_init(sqlite3*);
          sqlite3_json_init(db);
        }
#endif
        if( cellSzCkFlag ) runSql(db, "PRAGMA cell_size_check=ON", runFlags);
        setAlarm(iTimeout);
#ifndef SQLITE_OMIT_PROGRESS_CALLBACK
        if( sqlFuzz || vdbeLimitFlag ){
          sqlite3_progress_handler(db, 100000, progressHandler, &vdbeLimitFlag);
        }
#endif
        do{
          runSql(db, (char*)pSql->a, runFlags);
        }while( timeoutTest );
        setAlarm(0);
        sqlite3_close(db);
        if( sqlite3_memory_used()>0 ) fatalError("memory leak");
        reformatVfs();
        nTest++;
        g.zTestName[0] = 0;

        /* Simulate an error if the TEST_FAILURE environment variable is "5".
        ** This is used to verify that automated test script really do spot
        ** errors that occur in this test program.
        */
        if( zFailCode ){
          if( zFailCode[0]=='5' && zFailCode[1]==0 ){
            fatalError("simulated failure");
          }else if( zFailCode[0]!=0 ){
            /* If TEST_FAILURE is something other than 5, just exit the test
            ** early */
            printf("\nExit early due to TEST_FAILURE being set\n");
            iSrcDb = nSrcDb-1;
            goto sourcedb_cleanup;
          }
        }
      }
    }
    if( !quietFlag && !verboseFlag ){
      printf(" 100%% - %d tests\n", g.nDb*g.nSql);
    }
  
    /* Clean up at the end of processing a single source database
    */
  sourcedb_cleanup:
    blobListFree(g.pFirstSql);
    blobListFree(g.pFirstDb);
    reformatVfs();
 
  } /* End loop over all source databases */

  if( !quietFlag ){
    sqlite3_int64 iElapse = timeOfDay() - iBegin;
    printf("fuzzcheck: 0 errors out of %d tests in %d.%03d seconds\n"
           "SQLite %s %s\n",
           nTest, (int)(iElapse/1000), (int)(iElapse%1000),
           sqlite3_libversion(), sqlite3_sourceid());
  }
  free(azSrcDb);
  return 0;
}
Beispiel #16
0
int rec_resp_receiver(int fd, unsigned char * buffer, unsigned int length, unsigned char bcc2) {
	setAlarm();

	unsigned char addr = 0;
	unsigned char ctrl = 0;

	int i = START_FLAG;
	STOP = FALSE;

	while (STOP == FALSE) {
		unsigned char c = 0;

		if (alarmCount >= linklayer.numTransmissions) {
			printf("EXCEDED NUMBER OF TRIES\n");
			close_port_file(fd);
			return -1;
		} else if (alarmFlag == 1) {
			printf("RE-SEND RR!!!\n");
			send_data(fd, buffer, length);
			alarmFlag = 0;
			alarm(linklayer.timeout);
		}

		if (read(fd, &c, 1)) {
			switch (i) {
				case START_FLAG:
					if (c == FLAG)
						i = ADDR;
					break;
				case ADDR:
					if (c == ADDR_REC_RESP) {
						addr = c;
						i = CTRL;
					} else if (c != FLAG) {
						i = START_FLAG;
					}
					break;
				case CTRL:
					if ((c == CTRL_REC_READY(NEXT_INDEX(linklayer.sequenceNumber))) || (c == CTRL_REC_READY(linklayer.sequenceNumber)) || (c == CTRL_REC_REJECT(linklayer.sequenceNumber))) {
						ctrl = c;
						i = BCC1;
					} else if (c == FLAG) {
						i = ADDR;
					} else {
						i = START_FLAG;
					}
					break;
				case BCC1:
					if (c == (addr ^ ctrl)) {
						i = END_FLAG;
					} else if (c == FLAG) {
						i = ADDR;
					} else {
						i = START_FLAG;
					}
					break;
				case END_FLAG:
					if (c == FLAG) {
						if (ctrl == CTRL_REC_READY(NEXT_INDEX(linklayer.sequenceNumber))) {
							alarm(0);
							STOP = TRUE;
						} else if (ctrl == CTRL_REC_REJECT(linklayer.sequenceNumber)) {
							send_data(fd, buffer, length);
							i = START_FLAG;
							alarm(linklayer.timeout);
						} else if (ctrl == CTRL_REC_READY(linklayer.sequenceNumber)) {
							alarm(0);
							STOP = TRUE;
						} else {
							i = ADDR;
						}
					} else {
						i = START_FLAG;
					}
					break;
			}
		}
	}

	return 0;
}
Beispiel #17
0
int rec_ua(int fd, unsigned int flag) {
	setAlarm();

	unsigned int addr = 0;
	unsigned int ctrl = 0;

	int i = START_FLAG;
	STOP = FALSE;

	while (STOP == FALSE) {
		unsigned char c = 0;

		if (alarmCount >= linklayer.numTransmissions) {
			printf("EXCEDED NUMBER OF TRIES!\n");
			close_port_file(fd);
			return -1;
		} else if (alarmFlag == 1) {
			printf("RE-SEND UA!!!\n");
			if (flag == SENDER) {
				send_set(fd);
			} else if (flag == RECEIVER) {
				send_disc(fd, flag);
			}

			alarmFlag = 0;
			alarm(linklayer.timeout);
		}
		if (read(fd, &c, 1)) {
			switch (i) {
				case START_FLAG:
					if (c == FLAG)
						i = ADDR;
					break;
				case ADDR:
					if ((flag == SENDER && c == ADDR_REC_RESP) || (flag == RECEIVER && c == ADDR_TRANS_RESP)) {
						addr = c;
						i = CTRL;
					} else if (c != FLAG) {
						i = START_FLAG;
					}
					break;
				case CTRL:
					if (c == CTRL_UA) {
						ctrl = c;
						i = BCC1;
					} else if (c == FLAG) {
						i = ADDR;
					} else {
						i = START_FLAG;
					}
					break;
				case BCC1:
					if (c == (addr ^ ctrl)) {
						i = END_FLAG;
					} else if (c == FLAG) {
						i = ADDR;
					} else {
						i = START_FLAG;
					}
					break;
				case END_FLAG:
					if (c == FLAG) {
						STOP = TRUE;
					} else {
						i = START_FLAG;
					}
					break;
			}
		}
	}
	return 0;
}
Beispiel #18
0
/*----------------------------------------------------------------------*
 * Set an alarm time. Sets the alarm registers only.  To cause the      *
 * INT pin to be asserted on alarm match, use alarmInterrupt().         *
 * This method can set either Alarm 1 or Alarm 2, depending on the      *
 * value of alarmType (use a value from the ALARM_TYPES_t enumeration). *
 * However, when using this method to set Alarm 1, the seconds value    *
 * is set to zero. (Alarm 2 has no seconds register.)                   *
 *----------------------------------------------------------------------*/
void DS3232RTC::setAlarm(ALARM_TYPES_t alarmType, byte minutes, byte hours, byte daydate)
{
    setAlarm(alarmType, 0, minutes, hours, daydate);
}
void main()
{
    unsigned char sec,min,hour,day,month,year;
	uint8_t option=0;
	
	#define Button PIND
    #define up 5
    #define down 4
	#define select 3
	#define cancel 2
	
	DDRD = 0XF0; //Switches as input, lcd dataline as output
	PORTD = 0XFF; //Internal pull up enabled for switches
	DDRB  |= (1<<buzzer_pin); // buzzer as output

	LCD_Init(4,2,16);
	LCD_Printf(" Explore Time !");
	_delay_ms(2000);
	LCD_Clear();
	
    RTC_Init();
	
	//segments for creating large font stored in RAM.
	
	LCD_CreateCC(LT,0);
	LCD_CreateCC(UB,1);
	LCD_CreateCC(RT,2);
	LCD_CreateCC(LL,3);
	LCD_CreateCC(LB,4);
	LCD_CreateCC(LR,5);
	LCD_CreateCC(UMB,6);
	LCD_CreateCC(LMB,7);

	/*Set the time and Date only once */
//	RTC_SetTime(0x23,0x40,0x20);  //  11:40:20 pm
//	RTC_SetDate(0x14,0x11,0x12);  //  14th Nov 2012
	
	while(1)
	{		       
		if(util_IsBitCleared(Button,select))
		 {   
			while(util_IsBitCleared(Button,select));
			 
			do
			{
				option = LCD_DisplayMenu();
				switch(option)
				{
				 case 0: setTime(hour,min,sec);break;
				 case 1: setDate(day,month,year);break;
				 case 2: setAlarm(); break;
				 case 3: setDisplayStyle(); break;
				 case 4: setTimeFormat(); break;
				 default: break;
				}
			} while(util_IsBitSet(Button,cancel));
			
			LCD_Clear(); 	 
		 }
	
		RTC_GetTime(&hour,&min,&sec);      
		RTC_GetDate(&day, &month, &year);
		LCD_DisplayTime(hour, min, sec);
		LCD_DisplayDate(day, month, year);
		
		checkAlarm();
				
	}

}