Esempio n. 1
0
uint8_t RF24::read_register(uint8_t reg, uint8_t* buf, uint8_t len)
{
  uint8_t status;

  #if defined (RF24_LINUX)
  beginTransaction(); //configures the spi settings for RPi, locks mutex and setting csn low
  uint8_t * prx = spi_rxbuff;
  uint8_t * ptx = spi_txbuff;
  uint8_t size = len + 1; // Add register value to transmit buffer

  *ptx++ = ( R_REGISTER | ( REGISTER_MASK & reg ) );

  while (len--){ *ptx++ = NOP; } // Dummy operation, just for reading
  
  _SPI.transfernb( (char *) spi_txbuff, (char *) spi_rxbuff, size);
  
  status = *prx++; // status is 1st byte of receive buffer

  // decrement before to skip status byte
  while ( --size ){ *buf++ = *prx++; } 
  endTransaction(); //unlocks mutex and setting csn high

#else

  beginTransaction();
  status = _SPI.transfer( R_REGISTER | ( REGISTER_MASK & reg ) );
  while ( len-- ){
    *buf++ = _SPI.transfer(0xff);
  }
  endTransaction();

#endif

  return status;
}
Esempio n. 2
0
uint8_t RF24::read_register(uint8_t reg)
{
  uint8_t result;
  
  #if defined (RF24_LINUX)
	
  beginTransaction();
  
  uint8_t * prx = spi_rxbuff;
  uint8_t * ptx = spi_txbuff;	
  *ptx++ = ( R_REGISTER | ( REGISTER_MASK & reg ) );
  *ptx++ = NOP ; // Dummy operation, just for reading
  
  _SPI.transfernb( (char *) spi_txbuff, (char *) spi_rxbuff, 2);
  result = *++prx;   // result is 2nd byte of receive buffer
  
  endTransaction();
  #else

  beginTransaction();
  _SPI.transfer( R_REGISTER | ( REGISTER_MASK & reg ) );
  result = _SPI.transfer(0xff);
  endTransaction();

  #endif

  return result;
}
Esempio n. 3
0
uint8_t RF24::write_register(uint8_t reg, const uint8_t* buf, uint8_t len)
{
  uint8_t status;

  #if defined (RF24_LINUX) 
  beginTransaction();
  uint8_t * prx = spi_rxbuff;
  uint8_t * ptx = spi_txbuff;
  uint8_t size = len + 1; // Add register value to transmit buffer

  *ptx++ = ( W_REGISTER | ( REGISTER_MASK & reg ) );
  while ( len-- )
    *ptx++ = *buf++;
  
  _SPI.transfernb( (char *) spi_txbuff, (char *) spi_rxbuff, size);
  status = *prx; // status is 1st byte of receive buffer
  endTransaction();
  #else

  beginTransaction();
  status = _SPI.transfer( W_REGISTER | ( REGISTER_MASK & reg ) );
  while ( len-- )
    _SPI.transfer(*buf++);
  endTransaction();

  #endif

  return status;
}
Esempio n. 4
0
uint8_t RF24::write_register(uint8_t reg, uint8_t value)
{
  uint8_t status;

  IF_SERIAL_DEBUG(printf_P(PSTR("write_register(%02x,%02x)\r\n"),reg,value));

  #if defined (RF24_LINUX)
    beginTransaction();
	uint8_t * prx = spi_rxbuff;
	uint8_t * ptx = spi_txbuff;
	*ptx++ = ( W_REGISTER | ( REGISTER_MASK & reg ) );
	*ptx = value ;	
  	
	_SPI.transfernb( (char *) spi_txbuff, (char *) spi_rxbuff, 2);
	status = *prx++; // status is 1st byte of receive buffer
	endTransaction();
  #else

  beginTransaction();
  status = _SPI.transfer( W_REGISTER | ( REGISTER_MASK & reg ) );
  _SPI.transfer(value);
  endTransaction();

  #endif

  return status;
}
Esempio n. 5
0
//----------------------------------------------------------------------------
void ctkPluginStorageSQL::cleanupDB()
{
  QSqlDatabase database = getConnection();
  QSqlQuery query(database);

  beginTransaction(&query, Write);

  try
  {
    // remove all plug-ins marked as UNINSTALLED
    QString statement = "DELETE FROM " PLUGINS_TABLE " WHERE StartLevel==-2";
    executeQuery(&query, statement);

    // remove all old plug-in generations
    statement = "DELETE FROM " PLUGINS_TABLE
                " WHERE K NOT IN (SELECT K FROM (SELECT K, MAX(Generation) FROM " PLUGINS_TABLE " GROUP BY ID))";
  }
  catch (...)
  {
    rollbackTransaction(&query);
    throw;
  }

  commitTransaction(&query);
}
void Device::addMiniDriver( void ) {

    if( 0 != memcmp( g_DotNetSmartCardAtr, m_DeviceState.rgbAtr, m_DeviceState.cbAtr ) ) {
    
        throw MiniDriverException( SCARD_E_UNKNOWN_CARD ); 
    }

    try {
    
        // Create a card module service
        m_MiniDriver.reset( new MiniDriver( ) );

        m_MiniDriver->setSmartCardReader( m_SmartCardReader.get( ) );

        beginTransaction( );

        m_MiniDriver->read( s_bEnableCache );

        m_SmartCardReader->setCardHandle( m_MiniDriver->getCardHandle( ) );

        m_bIsLastAuth = m_MiniDriver->isAuthenticated( ); 
    
    } catch( ... ) {
    
    }

    endTransaction( );
}
bool LocalyticsDatabase::addCloseEventWithBlobString(QString blob)
{
    QString t(QLatin1String("add_close_event"));
    bool success = beginTransaction(t);

    int event_id;
    // Add close event.
    if (success) 
      {
        success = addEventWithBlobString(blob, &event_id);
      }

    // Record row id to localytics_info so that it can be removed if the session resumes.
    if (success) {
        QSqlQuery q(_databaseConnection);
        q.prepare(QLatin1String("UPDATE localytics_info SET last_close_event = (SELECT event_id FROM events WHERE rowid = :rowid)"));
        q.bindValue(QLatin1String(":rowid"), event_id);
        success = q.exec();
    }

    if (success) {
        releaseTransaction(t);
    } else {
        rollbackTransaction(t);
    }
    return success;
}
Esempio n. 8
0
int I2C::writeRead(const void *wbuf, size_t wlength, void *rbuf, size_t rlength,
		bool ignoreNack, bool noAck)
{
	bool was_transaction = true;

	// If not already in a transaction, make a transaction state
	if (!transactionState)
	{
		was_transaction = false;
		beginTransaction();
	}

	if (write(wbuf, wlength, ignoreNack) < 0)
		return -1;
	if (read(rbuf, rlength, noAck) < 0)
		return -1;

	// Commit transaction if the system was not already in a
	// transaction state
	if (!was_transaction)
	{
		if (endTransaction() < 0)
		{
			iooo_error(
					"I2C::writeRead() Unable to perform consecutive write and read\n");
			return -1;
		}
	}

	return 0;
}
bool LocalyticsDatabase::incrementLastSessionNumber(int *sessionNumber)
{
    QString t(QLatin1String("increment_session_number"));
    bool success = true;

    success = beginTransaction(t);
    QSqlQuery q(_databaseConnection);

    if (success)
      {
        // Increment value
        success = q.exec(QLatin1String("UPDATE localytics_info "
                                       "SET last_session_number = (last_session_number + 1)"));
      }

    if (success) 
      {
        // Retrieve new value
        success = q.exec(QLatin1String("SELECT last_session_number FROM localytics_info"));
        if (q.next()) 
          {
            *sessionNumber = q.value(0).toInt();
          }
      }

    if (success) 
      {
        releaseTransaction(t);
      } 
    else
      {
        rollbackTransaction(t);
      }
    return success;
}
Esempio n. 10
0
static void writeNode(void* abstractSelf) {
    osm2olm* self = (osm2olm*) abstractSelf;
    
    //printf("Write node\n");
    for(int c = 0; c < self->countriesCount; c++) {
        //printf("Check if belongs Country %i\n", c);
        if(nodeBelongsCountry(self, self->countries + c)) {
            //printf("Write node in country\n");
            
            addTree16Node(&(self->countries[c].nodesIndex), self->node.id, self->node.id);
            //printf("Added to index\n");
            //printf("Adding to db with statement: %x\n", self->countries[c].insertNodeStatement);
            beginTransaction(self->countries[c].db);       
            sqlite3_bind_int64(self->countries[c].insertNodeStatement, 1, self->node.id);
            sqlite3_bind_int(self->countries[c].insertNodeStatement, 2, self->node.lat);
            sqlite3_bind_int(self->countries[c].insertNodeStatement, 3, self->node.lon);
            sqlite3_bind_int64(self->countries[c].insertNodeStatement, 4, self->node.timestamp);
            //printf("Binded\n");
            sqlite3_step(self->countries[c].insertNodeStatement);
            //printf("Written\n");
            sqlite3_reset(self->countries[c].insertNodeStatement);
            //printf("Reset\n");
            writeTags(self, &(self->tags), self->countries[c].insertNodeTagStatement, self->node.id);
            //printf("Writing tags\n");
            commitTransaction(self->countries[c].db);
        }
    }
    //printf("Write node - end\n");
    self->tags.count = 0;
}
Esempio n. 11
0
static void updateNode(void* abstractSelf) {
    osm2olm* self = (osm2olm*) abstractSelf;
    
    //printf("Write node\n");
    for(int c = 0; c < self->countriesCount; c++) {
        //printf("Check if belongs Country %i\n", c);
        if(nodeBelongsCountry(self, self->countries + c)) {
            //printf("Write node in country\n");
            //            printf("Updating node %i\n", self->node.id);
            addTree16Node(&(self->countries[c].nodesIndex), self->node.id, self->node.id);
            //printf("Added to index\n");
            //printf("Adding to db with statement: %x\n", self->countries[c].insertNodeStatement);
            beginTransaction(self->countries[c].db);
            sqlite3_bind_int(self->countries[c].updateNodeStatement, 1, self->node.id);
            sqlite3_bind_int(self->countries[c].updateNodeStatement, 2, self->node.lat);
            sqlite3_bind_int(self->countries[c].updateNodeStatement, 3, self->node.lon);
            //printf("Binded\n");
            sqlite3_step(self->countries[c].updateNodeStatement);
            //printf("Written\n");
            sqlite3_reset(self->countries[c].updateNodeStatement);
            //printf("Reset\n");
            deleteFromDbById(self->countries[c].db, self->countries[c].deleteNodeTagsStatement, self->node.id);
            writeTags(self, &(self->tags), self->countries[c].insertNodeTagStatement, self->node.id);
            //printf("Writing tags\n");
            commitTransaction(self->countries[c].db);
        } else {
            deleteNodeFromCountry(self->countries + c, self->node.id);
        }
    }
    //printf("Write node - end\n");
    removeAllPlainTags(&(self->tags));
}
bool LocalyticsDatabase::resetAnalyticsData() {
    // Delete or zero all analytics data.
    // Reset: headers, events, session number, upload number, last session start, last close event, and last flow event.
    // Unaffected: schema version, opt out status, install ID (deprecated), and app key.

    QString t(QLatin1String("reset_analytics_data"));
    bool success = beginTransaction(t);
    QSqlQuery q(_databaseConnection);

    success &= q.exec(QLatin1String("DELETE FROM events"));
    success &= q.exec(QLatin1String("DELETE FROM upload_headers"));
    success &= q.exec(QLatin1String("DELETE FROM localytics_amp_rule"));
    success &= q.exec(QLatin1String("DELETE FROM localytics_amp_ruleevent"));
    success &= q.exec(QLatin1String("UPDATE localytics_info SET "
                                    " last_session_number = 0, last_upload_number = 0,"
                                    " last_close_event = null, last_flow_event = null, last_session_start = null, "
                                    " custom_d0 = null, custom_d1 = null, custom_d2 = null, custom_d3 = null, "
                                    " customer_id = null, queued_close_event_blob = null "));
    if (success) {
        releaseTransaction(t);
    } else {
        rollbackTransaction(t);
    }

    return success;
}
Esempio n. 13
0
  void IncrementalParser::codeGenTransaction(Transaction* T) {
    // codegen the transaction
    assert(T->getCompilationOpts().CodeGeneration && "CodeGen turned off");
    assert(T->getState() == Transaction::kCompleted && "Must be completed");
    assert(hasCodeGenerator() && "No CodeGen");

    // Could trigger derserialization of decls.
    Transaction* deserT = beginTransaction(CompilationOptions());


    // Commit this transaction first - T might need symbols from it, so
    // trigger emission of weak symbols by providing use.
    ParseResultTransaction PRT = endTransaction(deserT);
    commitTransaction(PRT);
    deserT = PRT.getPointer();

    // This llvm::Module is done; finalize it and pass it to the execution
    // engine.
    if (!T->isNestedTransaction() && hasCodeGenerator()) {
      // The initializers are emitted to the symbol "_GLOBAL__sub_I_" + filename.
      // Make that unique!
      deserT = beginTransaction(CompilationOptions());
      // Reset the module builder to clean up global initializers, c'tors, d'tors
      getCodeGenerator()->HandleTranslationUnit(getCI()->getASTContext());
      auto PRT = endTransaction(deserT);
      commitTransaction(PRT);
      deserT = PRT.getPointer();

      std::unique_ptr<llvm::Module> M(getCodeGenerator()->ReleaseModule());

      if (M) {
        m_Interpreter->addModule(M.get(), T->getCompilationOpts().OptLevel);
        T->setModule(std::move(M));
      }

      if (T->getIssuedDiags() != Transaction::kNone) {
        // Module has been released from Codegen, reset the Diags now.
        DiagnosticsEngine& Diags = getCI()->getSema().getDiagnostics();
        Diags.Reset(/*soft=*/true);
        Diags.getClient()->clear();
      }

      // Create a new module.
      StartModule();
    }
  }
Esempio n. 14
0
 Transaction* IncrementalParser::Parse(llvm::StringRef input,
                                       const CompilationOptions& Opts) {
   Transaction* CurT = beginTransaction(Opts);
   ParseInternal(input);
   Transaction* EndedT = endTransaction(CurT);
   assert(EndedT == CurT && "Not ending the expected transaction.");
   return EndedT;
 }
Esempio n. 15
0
void CassandraStorage::executeRangeErase_p2(const Bucket& bucket, CommitCallback cb, ReadSet* rs, const String& timestamp) {
	beginTransaction(bucket);
    for(ReadSet::iterator it = (*rs).begin(); it != (*rs).end(); it++) {
        String key = it->first;
        erase(bucket, key);
    }
    mIOService->post(std::tr1::bind(&CassandraStorage::commitTransaction, this, bucket, cb, timestamp));
}
Esempio n. 16
0
static void deleteNodeFromCountry(LCountry* country, OsmId id) {
    beginTransaction(country->db);
    if(deleteFromDbById(country->db, country->deleteNodeTagsStatement, id) &&
       deleteFromDbById(country->db, country->deleteNodeStatement, id)) {
        commitTransaction(country->db);
    } else {
        rollbackTransaction(country->db);
    }
}
Esempio n. 17
0
void ad75019SPIMgr::send(const uint8_t vec[], int size) const{ // a vector of bytes, the vector is not overwritten by the reply
  uint8_t newVec[size];
  for (int i=0;i<size;i++){
    newVec[i] = vec[i];
  }
  beginTransaction();
  SPI.transfer(newVec,size);
  endTransaction();
}
Esempio n. 18
0
void JucerDocument::timerCallback()
{
    if (! Component::isMouseButtonDownAnywhere())
    {
        stopTimer();
        beginTransaction();

        flushChangesToDocuments();
    }
}
Esempio n. 19
0
void fCacheDB::createTable()
{
    beginTransaction();
    executeSQL(std::string("CREATE TABLE IF NOT EXISTS " + std::string(TABLE_NAME) +
                "(id TEXT PRIMARY KEY, timestamp INTEGER, persistent INTEGER DEFAULT 0, data BLOB)").c_str());
    executeSQL(std::string("CREATE INDEX IF NOT EXISTS idx_id ON '" + std::string(TABLE_NAME) + "' (id);").c_str());
    executeSQL(std::string("CREATE INDEX IF NOT EXISTS idx_timestamp ON '" + std::string(TABLE_NAME) + "' (timestamp);").c_str());
    executeSQL(std::string("CREATE INDEX IF NOT EXISTS idx_persistent ON '" + std::string(TABLE_NAME) + "' (persistent);").c_str());
    commitTransaction();
}
Esempio n. 20
0
static void deleteWay(void* abstractSelf) {
    osm2olm* self = (osm2olm*) abstractSelf;
    //printf("Deleting way %i\n", self->way.id);
    for(int c = 0; c < self->countriesCount; c++) {
        beginTransaction(self->countries[c].db);
        deleteWayFromCountry(self->countries + c, self->way.id);
        commitTransaction(self->countries[c].db);
    }    
    removeAllPlainTags(&(self->tags));
    removeAllWayNodes(&(self->wayNodes));
}
void
AutomaticIPod::PlayCountsDatabase::bootstrap()
{
    qDebug() << "Starting bootstrapping...";
    
    static_cast<TwiddlyApplication*>(qApp)->sendBusMessage( "container://Notification/Twiddly/Bootstrap/Started" );

    beginTransaction();    
    
    QSqlQuery query( m_db );
    // this will fail if the metadata table doesn't exist, which is fine
    query.exec( "DELETE FROM metadata WHERE key='bootstrap_complete'" );
    query.exec( "DELETE FROM metadata WHERE key='plugin_ctime'" );
    query.exec( "DELETE FROM " TABLE_NAME_OLD );
    query.exec( "DELETE FROM " TABLE_NAME );

    ITunesLibrary lib;
    
    // for wizard progress screen
    std::cout << lib.trackCount() << std::endl;
    
    int i = 0;

    while (lib.hasTracks())
    {
        try
        {
            ITunesLibrary::Track const t = lib.nextTrack();
            QString const plays = QString::number( t.playCount() );

            query.exec( "INSERT OR IGNORE INTO " TABLE_NAME " ( persistent_id, play_count ) "
                        "VALUES ( '" + t.uniqueId() + "', '" + plays + "' )" );

        }
        catch ( ... )
        {
            // Move on...
        }

        std::cout << ++i << std::endl;
    }

    // if either INSERTS fail we'll rebootstrap next time
    query.exec( "CREATE TABLE metadata (key VARCHAR( 32 ), value VARCHAR( 32 ))" );
    query.exec( "INSERT INTO metadata (key, value) VALUES ('bootstrap_complete', 'true')" );
    
    QString const t = QString::number( common::fileCreationTime( pluginPath() ) );
    query.exec( "INSERT INTO metadata (key, value) VALUES ('plugin_ctime', '"+t+"')" );


    endTransaction();

    static_cast<TwiddlyApplication*>(qApp)->sendBusMessage( "container://Notification/Twiddly/Bootstrap/Finished" );
}
Esempio n. 22
0
  void IncrementalParser::Initialize() {
    if (hasCodeGenerator())
      getCodeGenerator()->Initialize(getCI()->getASTContext());

    CompilationOptions CO;
    CO.DeclarationExtraction = 0;
    CO.ValuePrinting = CompilationOptions::VPDisabled;
    CO.CodeGeneration = hasCodeGenerator();

    // pull in PCHs
    const std::string& PCHFileName
      = m_CI->getInvocation ().getPreprocessorOpts().ImplicitPCHInclude;
    if (!PCHFileName.empty()) {
      
      Transaction* CurT = beginTransaction(CO);
      m_CI->createPCHExternalASTSource(PCHFileName,
                                       true /*DisablePCHValidation*/,
                                       true /*AllowPCHWithCompilerErrors*/,
                                       0 /*DeserializationListener*/);
      Transaction* EndedT = endTransaction(CurT);
      commitTransaction(EndedT);
    }

    Transaction* CurT = beginTransaction(CO);
    Sema* TheSema = &m_CI->getSema();
    m_Parser.reset(new Parser(m_CI->getPreprocessor(), *TheSema,
                              false /*skipFuncBodies*/));
    m_CI->getPreprocessor().EnterMainSourceFile();
    // Initialize the parser after we have entered the main source file.
    m_Parser->Initialize();
    // Perform initialization that occurs after the parser has been initialized
    // but before it parses anything. Initializes the consumers too.
    TheSema->Initialize();

    ExternalASTSource *External = TheSema->getASTContext().getExternalSource();
    if (External)
      External->StartTranslationUnit(m_Consumer);

    Transaction* EndedT = endTransaction(CurT);
    commitTransaction(EndedT);
  }
Esempio n. 23
0
static void deleteNode(void* abstractSelf) {
    osm2olm* self = (osm2olm*) abstractSelf;
    
    //    printf("Deleting node %i\n", self->node.id);
    for(int c = 0; c < self->countriesCount; c++) {
        beginTransaction(self->countries[c].db);
        deleteNodeFromCountry(self->countries + c, self->node.id);
        commitTransaction(self->countries[c].db);
    }
    //printf("Delete node - end\n");
    removeAllPlainTags(&(self->tags));
}
Esempio n. 24
0
void KFileItemListView::setPreviewsShown(bool show)
{
    if (!m_modelRolesUpdater) {
        return;
    }

    if (m_modelRolesUpdater->previewsShown() != show) {
        beginTransaction();
        m_modelRolesUpdater->setPreviewsShown(show);
        onPreviewsShownChanged(show);
        endTransaction();
    }
}
Esempio n. 25
0
bool QgsTransaction::begin( QString& errorMsg, int statementTimeout )
{
  if ( mTransactionActive )
    return false;

  //Set all layers to direct edit mode
  if ( !beginTransaction( errorMsg, statementTimeout ) )
    return false;

  setLayerTransactionIds( this );
  mTransactionActive = true;
  return true;
}
Esempio n. 26
0
 Result Connection::transaction(TransactionType type, tr1::function<bool(Connection &)> action) {
     Result ret = beginTransaction(type);
     if (!ret) {
         return ret;
     }
     
     if (action(*this)) {
         return commit();
     }
     else {
         return rollback();
     }
 }
QSqlDatabase &TActionContext::getDatabase(int id)
{
    T_TRACEFUNC("id:%d", id);

    if (id < 0 || id >= Tf::app()->databaseSettingsCount())
        return sqlDatabases[Tf::app()->databaseSettingsCount()];  // invalid db
    
    QSqlDatabase &db = sqlDatabases[id];
    if (!db.isValid()) {
        db = TSqlDatabasePool::instance()->pop(id);
        beginTransaction(db);
    }
    return db;
}
Esempio n. 28
0
  Transaction* IncrementalParser::Compile(llvm::StringRef input,
                                          const CompilationOptions& Opts) {

    Transaction* CurT = beginTransaction(Opts);
    EParseResult ParseRes = ParseInternal(input);

    if (ParseRes == kSuccessWithWarnings)
      CurT->setIssuedDiags(Transaction::kWarnings);
    else if (ParseRes == kFailed)
      CurT->setIssuedDiags(Transaction::kErrors);

    endTransaction();
    commitTransaction(CurT);

    return CurT;
  }
bool LocalyticsDatabase::deleteUploadedData()
{
    // Delete all headers and staged events.
    QString t(QLatin1String("delete_upload_data"));
    bool success = beginTransaction(t);

    QSqlQuery q(_databaseConnection);
    success &= q.exec(QLatin1String("DELETE FROM events WHERE upload_header IS NOT NULL"));
    success &= q.exec(QLatin1String("DELETE FROM upload_headers"));

    if (success) {
        releaseTransaction(t);
    } else {
        rollbackTransaction(t);
    }
    return success;
}
Esempio n. 30
0
QSqlDatabase &TActionContext::getSqlDatabase(int id)
{
    T_TRACEFUNC("id:%d", id);

    if (!Tf::app()->isSqlDatabaseAvailable()) {
        return sqlDatabases[0];  // invalid database
    }

    if (id < 0 || id >= Tf::app()->sqlDatabaseSettingsCount()) {
        throw RuntimeException("error database id", __FILE__, __LINE__);
    }

    QSqlDatabase &db = sqlDatabases[id];
    if (!db.isValid()) {
        db = TSqlDatabasePool2::instance()->database(id);
        beginTransaction(db);
    }
    return db;
}