bool NetworkConnectorEngine::tryServeWishListItem() {
    const bool hasIpv6 =
        !Connection::Ipv6AddressesEqual(iController->getNode().ipv6Addr(),
                                        KNullIpv6Addr) ;
    iModel->lock() ;
    Node* n = iModel->nodeModel().nextConnectionWishListItem()  ;
    iModel->unlock() ;
    if ( n ) {
        QHostAddress addrOfNode ;
        if (n->DNSAddr().length() > 0 &&
                performDNSLookup(&addrOfNode,
                                 n->DNSAddr(),
                                 hasIpv6 )) {
            addrOfNode.setAddress(n->DNSAddr()) ;
        } else {
            if (!Connection::Ipv6AddressesEqual( n->ipv6Addr(),
                                                 KNullIpv6Addr ) 
		&& // try connect only if we ourselves have ipv6:
		hasIpv6 ) {
                addrOfNode.setAddress( n->ipv6Addr() ) ;
            } else if (  n->ipv4Addr() ) {
                addrOfNode.setAddress( n->ipv4Addr() ) ;
            } else {
                // tor addresses?
                delete n ;
                LOG_STR("Connection wishlist-item had no ipv4/ipv6/dns addr") ;
                return false ;
            }
        }
        iModel->lock() ;
        for ( int i = 0 ; i < iAddressesInOrderToConnect.size() ; i++ ) {

            MNodeModelProtocolInterface::HostConnectQueueItem addrFromList = iAddressesInOrderToConnect.at(0) ;
            if (addrFromList.iAddress == addrOfNode ) {
                // item is already on our list -> discard
                delete n ;
                LOG_STR("Connection wishlist-item was already on list..") ;
                iModel->unlock() ;
                return false ;
            }
        }
        iModel->unlock() ;
        spawnNewConnection(addrOfNode,
                           n->port(),
                           n->nodeFingerPrint()) ;
        delete n ;
        return true ;

    } else {
        return false ; // nothing on wishlist
    }
}
void NetworkConnectorEngine::run() {
    LOG_STR("NetworkConnectorEngine::run in") ;
    time_t timeOfLastNodeListUpdate (0) ;
    int connectedCount = 0 ; // initially must be, later ask datamodel

    // subscribe to cleanup activities
    connect(this, SIGNAL(finished()),
	    this, SLOT(aboutToFinish())) ; 

    if (   iBroadCastSocket == NULL ) {
        iBroadCastSocket = new QUdpSocket() ;
    }
    while (iNeedsToRun ) {
        sendBroadCast() ;
        createConnectionsToNodesStoringPrivateMessages() ;
        if ( tryServeWishListItem() == false ) {
            // if there is nothing in wishlist, do "normal procedure"
            // every 350 seconds
            if ( timeOfLastNodeListUpdate+50 < QDateTime::currentDateTimeUtc().toTime_t() ) {
                updateListOfNodesToConnect() ;
                timeOfLastNodeListUpdate = QDateTime::currentDateTimeUtc().toTime_t() ;
            }
            if (   connectedCount < KMaxOpenConnections ) {
                // so, lets start with list above ..
                if ( iAddressesInOrderToConnect.size() > 0 ) {
                    MNodeModelProtocolInterface::HostConnectQueueItem connectionItem = iAddressesInOrderToConnect.at(0) ;
                    QHostAddress a = connectionItem.iAddress ;
                    int p = connectionItem.iPort ;
                    spawnNewConnection(a,p,connectionItem.iNodeHash) ;
                    iAddressesInOrderToConnect.removeAt(0) ;
                }
            } else {
                // take a break, we have connections..
            }
            // in the end, query open open connections
            iModel->lock() ;
            QList <Connection *> currentConnections = iModel->getConnections()  ;
            connectedCount = currentConnections.size() ;
            iModel->unlock() ;
        }
        // looks like we don't get "deleteLater()" signals processed
        // without this
        QCoreApplication::processEvents(QEventLoop::ExcludeUserInputEvents) ;
        msleep(800) ;
    }
    delete iBroadCastSocket ;
    iBroadCastSocket = NULL ;
    LOG_STR("NetworkConnectorEngine::run out thread = " + QString::number((qulonglong)(QThread::currentThreadId()))) ;
}
CaDbRecord::CaDbRecord() :
    iSearchNumber(std::numeric_limits<qint64>::min()),
    iIsEncrypted(false),
    iTimeOfPublish(0),
    iIsSignatureVerified(false) {
    LOG_STR("CaDbRecord::CaDbRecord()") ;
}
Esempio n. 4
0
        void HttpSource::async_open(
            framework::string::Url const & url,
            boost::uint64_t beg, 
            boost::uint64_t end, 
            response_type const & resp)
        {
            flag_ = true;

            boost::system::error_code ec;
            util::protocol::HttpRequest request;
            util::protocol::HttpRequestHead & head = request.head();
            head.path = url.path_all();
            head["Accept"] = "{*.*}";
            head.host = url.host_svc();
            head.connection = util::protocol::http_field::Connection::keep_alive;
            if (beg != 0 || end != (boost::uint64_t)-1) {
                head.range.reset(util::protocol::http_field::Range((boost::int64_t)beg, (boost::int64_t)end));
            } else {
                head.range.reset();
            }
            std::ostringstream oss;
            head.get_content(oss);
            LOG_STR(framework::logger::Trace, ("http_request_head", oss.str()));

            http_.async_open(request, resp);
        }
MockUpModel::MockUpModel( MController *aController ) :
    iNetworkRequests(NULL),
    iController(aController),
    iProfileModel(NULL),
    iBinaryFileModel(NULL),
    iCAModel(NULL),
    iPrivMsgModel(NULL),
    iContentEncryptionModel(NULL),
    iProfileCommentModel(NULL),
    iSearchModel(NULL),
    iCaDbRecordModel(NULL),
    iTclModel(NULL) {
    LOG_STR("MockUpModel::MockUpModel in\n") ;

    SSL_load_error_strings() ;
    SSL_library_init() ;
    QFile randomFile("/dev/urandom") ;
    randomFile.open(QIODevice::ReadOnly) ; 
    QByteArray randomBytes = randomFile.read(1024) ;
    char *randomBytesPointer = randomBytes.data() ;
    RAND_seed(randomBytesPointer, 1024);
    iNodeModel = new MockUpNodeModel(iController) ;
    iProfileModel = new ProfileModel(aController, *this)  ;
    iBinaryFileModel = new BinaryFileModel(aController, *this) ;
    iCAModel = new ClassifiedAdsModel(aController, *this) ;
    iPrivMsgModel = new PrivMessageModel(aController, *this) ;
    iProfileCommentModel = new ProfileCommentModel(aController, *this) ;
    iContentEncryptionModel = new ContentEncryptionModel(aController, *this) ;
    iSearchModel = new SearchModel(*this,*iController) ;
    iSearchModel->setObjectName("CA SearchModel test") ;
    iCaDbRecordModel = new CaDbRecordModel(iController, *this) ; 
    iTclModel = new TclModel(iController, *this) ; 
    iConnections = new QList<Connection *>() ;
    iNetReqQueue = new QList <NetworkRequestExecutor::NetworkRequestQueueItem>();
    iDb = QSqlDatabase::addDatabase("QSQLITE", "ca-test-db") ; 
    QString path(QDir::home().path());
    path.append(QDir::separator()).append(".classified_ads");
    if (!QDir(path).exists()) {
        QDir().mkdir(path) ;
    }
    path.append(QDir::separator()).append("sqlite_db");
    path = QDir::toNativeSeparators(path);
    iDb.setDatabaseName(path);
    // Open database
    iDb.open() ;
    LOG_STR("MockUpModel::MockUpModel out\n") ;
}
Esempio n. 6
0
 bool HttpSource::is_open(
     boost::system::error_code & ec)
 {
     bool result = http_.is_open(ec);
     if(flag_ && result){
         util::protocol::HttpResponseHead head = http_.response().head();
         std::ostringstream oss;
         head.get_content(oss);
         LOG_STR(framework::logger::Trace, ("http_response_head", oss.str()));
         flag_ = false;
     }
     return result;
 }
void MySqlFactoryDal::CleanupOldRecords(nlib::DateTime olderThanDate, nlib::DateTime olderThanAlertDate)
{
	nlib::DateTime currTime = nlib::CurrentUniversalTime();

	const char *pszQry[] ={
		"DELETE FROM CommandParameters WHERE CommandID IN (SELECT C.CommandID from Commands C WHERE C.TimePosted < \"%s\");",	// +24*7
		"DELETE FROM Commands WHERE TimePosted < \"%s\";",	// +24*7
		"DELETE FROM CommandParameters WHERE CommandID IN (SELECT C.CommandID from Commands C WHERE C.TimePosted < \"%s\" AND (C.CommandStatus = 2 OR C.CommandStatus = 3));",
		"DELETE FROM Commands WHERE TimePosted < \"%s\" AND (CommandStatus = 2 OR CommandStatus = 3);",
		"DELETE FROM DeviceReadingsHistory WHERE ReadingTime < \"%s\";",
		//there is other approach
		//"DELETE FROM DeviceHistory WHERE Timestamp < \"%s\";",
		"DELETE FROM DeviceHealthHistory WHERE Timestamp < \"%s\";",
		"DELETE FROM NeighborHealthHistory WHERE Timestamp < \"%s\";",
		"DELETE FROM AlertNotifications WHERE AlertTime < \"%s\";",
		"DELETE FROM DeviceChannelsHistory WHERE Timestamp < \"%s\";",
		"DELETE FROM ISACSConfirmDataBuffer WHERE Timestamp < \"%s\";",
		"DELETE FROM Firmwares WHERE UploadStatus = 5 AND UploadDate < \"%s\";"
	};

	LOG("DEBUG CleanupOldRecords START [%s] [%s]", nlib::ToString(olderThanDate).c_str(), nlib::ToString(currTime - nlib::util::hours(24*7)).c_str());
	for( int i = 0; i< sizeof(pszQry) / sizeof(pszQry[0]); ++i)
	{	char szQry[ 1024 ];
		snprintf( szQry, sizeof(szQry), pszQry[i], (i>=2)
			? nlib::ToString(olderThanDate).c_str() 
			: (nlib::ToString(currTime - nlib::util::hours(24*7)).c_str()) );
		szQry[ sizeof(szQry)-1 ] = 0;
		std::string obQry( szQry );
		MySQLCommand command(connection, obQry);
		try
		{
			BeginTransaction();
			command.ExecuteNonQuery();
			CommitTransaction();
		}
		catch(std::exception& ex)
		{
			LOG_ERROR("CATCH(exception): CleanupOldRecords failed at step=" << i << " error=" << ex.what());
			RollbackTransaction();
		}
		catch(...)
		{
			LOG_ERROR("CATCH(...): CleanupOldRecords failed at step=" << i );
			RollbackTransaction();
		}
	}
	LOG_STR("DEBUG CleanupOldRecords END");

}
TrustTreeModel::TrustTreeModel(MController *aController,
                               const MModelProtocolInterface &aModel)
    :     iController(*aController),
          iModel(aModel),
          iTrustTree(NULL),
          iLastUpdateTime(0) {
    LOG_STR("TrustTreeModel::TrustTreeModel()") ;
    connect(this,
            SIGNAL(  error(MController::CAErrorSituation,
                           const QString&) ),
            aController,
            SLOT(handleError(MController::CAErrorSituation,
                             const QString&)),
            Qt::QueuedConnection ) ;
    iTrustTree = new QMap<Hash, TrustTreeItem>() ;
}
MockUpModel::~MockUpModel() {
    iDb.close() ; 
    QSqlDatabase::removeDatabase("ca-test-db") ; 
    delete iNetworkRequests ;
    delete iNodeModel ;
    delete iProfileModel ;
    delete iBinaryFileModel ;
    delete iCAModel ;
    delete iPrivMsgModel ;
    delete iProfileCommentModel ;
    delete iContentEncryptionModel ;
    delete iSearchModel;
    delete iCaDbRecordModel;
    delete iTclModel;
    LOG_STR("MockUpModel::~MockUpModel\n") ;
}
Esempio n. 10
0
void DialogBase::attachButtonClicked() {
    LOG_STR("DialogBase::attachButtonClicked\n") ;

    QString fileName = QFileDialog::getOpenFileName(this, tr("Select file to be published"),
                       "",
                       tr("Files (*.*)"));
    if ( fileName.length() > 0 ) {
        QFile f ( fileName ) ;
        if ( f.open(QIODevice::ReadOnly) ) {
            if ( f.size() > ( KMaxProtocolItemSize * 10 ) ) {
                emit error ( MController::FileOperationError, tr("File way too big")) ;
            } else {
                QByteArray content ( f.read(f.size() ) ) ;
                QByteArray compressedContent ( qCompress(content) ) ;
                LOG_STR2("Size of content = %d", (int) (content.size())) ;
                LOG_STR2("Size of compressed = %d", (int) (compressedContent.size())) ;
                if (content.size() > (qint64)(( KMaxProtocolItemSize - ( 50*1024 ) )) &&
                        compressedContent.size() > (qint64)(( KMaxProtocolItemSize - ( 50*1024 ) )) ) {
                    emit error ( MController::FileOperationError, tr("File too big")) ;
                } else {
                    // file was not too big. here now just mark the filename
                    // for later use.
                    if ( iFilesAboutToBeAttached.count() != 0 ) {
                        iFilesAboutToBeAttached.clear() ;
                    }
                    MetadataQueryDialog::MetadataResultSet metadata ;
                    metadata.iFileName = fileName ;
                    MetadataQueryDialog metadataDialog(this,
                                                       *iController,
                                                       metadata ) ;
                    if ( metadataDialog.exec() == QDialog::Accepted ) {
                        iFilesAboutToBeAttached.append(metadata) ;

                        iAttachmentListLabel->setText(metadata.iFileName) ;
                    } else {
                        iAttachmentListLabel->setText(QString()) ;
                    }
                }
            }
        } else {
            emit error ( MController::FileOperationError, tr("File open error")) ;
        }
    }
}
void NetworkConnectorEngine::spawnNewConnection(const QHostAddress& aAddr,const int aPort, const Hash& aHashOfNodeToConnect) {
    NetworkListener *networkListener = iController->networkListener() ;
    QThread* t = new QThread();
    Connection *c =
        new   Connection(aAddr,aPort,
                         *networkListener, // connection observer
                         *iModel,
                         *iController,
                         aHashOfNodeToConnect);
    // as "NULL" was passed as parent to new connection, someone
    // (now datamodel destructor) needs to clean away the open
    // outgoing connections

    // datamodel is responsible for deleting outgoing connections,
    // with special connection state that incoming connections in turn
    // do not need use
    iModel->lock() ;
    // here we have a bug .. if IP addr changes, we'll advertise
    // our old address for the first peer to connect .. would
    // need to delay construction of node greeting to the moment
    // when we're already in connected state and can check
    // for local address of the socket.
    iModel->addOpenNetworkConnection(c) ;
    iModel->unlock() ;
    connect(t, SIGNAL(started()), c, SLOT(run()));

    connect(c, SIGNAL(finished()), t, SLOT(quit())) ;
    connect(t, SIGNAL(finished()), t, SLOT(deleteLater()));
    // after thread is gone, remove the connection too
    connect(t, SIGNAL(finished()), c, SLOT(deleteLater()));
    connect(c, SIGNAL(blackListNetworkAddr(QHostAddress ) ),
            this, SLOT(blackListNetworkAddr(QHostAddress ) ),
            Qt::QueuedConnection ) ;
    connect(c, SIGNAL(connectionAttemptFailed(const Hash&) ),
            networkListener, SLOT(connectionAttemptFailed(const Hash&) ) ) ;
    c->moveToThread(t) ;
    t->start();
    LOG_STR("NetworkConnectorEngine::spawnNewConnection out") ;
}
/// delete firmware transfers when older than 7 days, regardless of the download status
/// TODO: keep application alerts longer
void MySqlFactoryDal::CleanupOldAlarmsAndFW(nlib::DateTime olderThanDate)
{
	nlib::DateTime currTime = nlib::CurrentUniversalTime();

	const char *pszQry[] ={
		"DELETE FROM FirmwareDownloads WHERE StartedOn < \"%s\";",	// +24*7
		"DELETE FROM AlertNotifications WHERE AlertTime < \"%s\";" };

		LOG("DEBUG CleanupOldRecords for Alarms and FW START [%s] [%s]", nlib::ToString(olderThanDate).c_str(), nlib::ToString(currTime - nlib::util::hours(24*1)).c_str());
		for( int i = 0; i< sizeof(pszQry) / sizeof(pszQry[0]); ++i)
		{	char szQry[ 1024 ];
		snprintf( szQry, sizeof(szQry), pszQry[i], (i>=1)
			? nlib::ToString(olderThanDate).c_str() 
			: (nlib::ToString(currTime - nlib::util::hours(24*7)).c_str()) );
		szQry[ sizeof(szQry)-1 ] = 0;
		std::string obQry( szQry );
		MySQLCommand command(connection, obQry);
		try
		{
			BeginTransaction();
			command.ExecuteNonQuery();
			CommitTransaction();
		}
		catch(std::exception& ex)
		{
			LOG_ERROR("CATCH(exception): CleanupOldRecords failed at step=" << i << " error=" << ex.what());
			RollbackTransaction();
		}
		catch(...)
		{
			LOG_ERROR("CATCH(...): CleanupOldRecords failed at step=" << i );
			RollbackTransaction();
		}
		}
		LOG_STR("DEBUG CleanupOldRecords for Alarms and FW END");
}
Esempio n. 13
0
void usb_host_task(void)
#endif
{
  #define DEVICE_DEFAULT_MAX_ERROR_COUNT  2
  static uint8_t device_default_error_count;

#ifdef HOST_VBUS_LOW_TIMEOUT
  extern t_cpu_time timer_vbus_low;
#endif
  static bool sav_int_sof_enable;
  uint8_t pipe;

#ifdef FREERTOS_USED
  portTickType xLastWakeTime;

  xLastWakeTime = xTaskGetTickCount();
  while (true)
  {
    vTaskDelayUntil(&xLastWakeTime, configTSK_USB_HST_PERIOD);

#endif  // FREERTOS_USED
    switch (device_state)
    {
#ifdef HOST_VBUS_LOW_TIMEOUT
    case DEVICE_VBUS_LOW:
      Usb_disable_vbus();
      if (cpu_is_timeout(&timer_vbus_low))
        usb_host_task_init();
      break;
#endif

    //------------------------------------------------------
    //   DEVICE_UNATTACHED state
    //
    //   - Default init state
    //   - Try to give device power supply
    //
    case DEVICE_UNATTACHED:
      device_default_error_count = 0;
      nb_interface_supported = 0;
      Host_clear_device_status();     // Reset device status
      Usb_clear_all_event();          // Clear all software events
      Host_disable_sof();
      host_disable_all_pipes();
      Usb_enable_vbus();              // Give at least device power supply!
      // If VBus OK, wait for device connection
      if (Is_usb_vbus_high())
        device_state = DEVICE_ATTACHED;
      break;

    //------------------------------------------------------
    //   DEVICE_ATTACHED state
    //
    //   - VBus is on
    //   - Try to detect device connection
    //
    case DEVICE_ATTACHED:
      if (Is_host_device_connection() || Is_usb_event(EVT_HOST_CONNECTION) )  // Device pull-up detected
      {
device_attached_retry:
        if( Is_usb_event(EVT_HOST_CONNECTION) ) {
          Usb_ack_event(EVT_HOST_CONNECTION);
        }
        Usb_ack_bconnection_error_interrupt();
        Usb_ack_vbus_error_interrupt();
        Host_ack_device_connection();

        Host_clear_device_status();   // Reset device status
        cpu_irq_disable();
        Host_disable_device_disconnection_interrupt();
        Host_send_reset();            // First USB reset
        (void)Is_host_sending_reset();
        cpu_irq_enable();
        Usb_ack_event(EVT_HOST_SOF);
        // Active wait for end of reset send
        while (Is_host_sending_reset())
        {
          // The USB macro does not signal the end of reset when a disconnection occurs
          if (Is_host_device_disconnection())
          {
            // Stop sending USB reset
            Host_stop_sending_reset();
          }
        }
        Host_ack_reset_sent();
        Host_enable_sof();            // Start SOF generation
        Host_enable_sof_interrupt();  // SOF will be detected under interrupt
        if (!Is_host_device_disconnection())
        {
          // Workaround for some buggy devices with powerless pull-up
          // usually low-speed where data line rises slowly and can be interpreted as disconnection
          for (sof_cnt = 0; sof_cnt < 0xFFFF; sof_cnt++)  // Basic time-out counter
          {
            // If we detect SOF, device is still alive and connected, just clear false disconnect flag
            if (Is_usb_event(EVT_HOST_SOF) && Is_host_device_disconnection())
            {
              Host_ack_device_connection();
              Host_ack_device_disconnection();
              break;
            }
          }
        }
        Host_enable_device_disconnection_interrupt();
        sof_cnt = 0;
        while (sof_cnt < 100)         // Wait 100 ms after USB reset
        {
          if (Is_usb_event(EVT_HOST_SOF)) Usb_ack_event(EVT_HOST_SOF), sof_cnt++; // Count SOFs
          if (Is_host_emergency_exit() || Is_usb_bconnection_error_interrupt()) goto device_attached_error;
        }
        device_state = DEVICE_POWERED;
        LOG_STR(log_device_connected);
        Host_device_connection_action();
        sof_cnt = 0;
      }
device_attached_error:
      // Device connection error, or VBus pb -> Retry the connection process from the beginning
      if (Is_usb_bconnection_error_interrupt() || Is_usb_vbus_error_interrupt() || Is_usb_vbus_low())
      {
        if (device_state != DEVICE_VBUS_LOW)
          device_state = DEVICE_UNATTACHED;
        Usb_ack_bconnection_error_interrupt();
        Usb_ack_vbus_error_interrupt();
        Host_disable_sof();
      }
      break;

    //------------------------------------------------------
    //   DEVICE_POWERED state
    //
    //   - Device connection (attach) has been detected,
    //   - Wait 100 ms and configure default control pipe
    //
    case DEVICE_POWERED:
      if (Is_usb_event(EVT_HOST_SOF))
      {
        Usb_ack_event(EVT_HOST_SOF);
        if (sof_cnt++ >= 100)         // Wait 100 ms
        {
          Host_enable_pipe(P_CONTROL);
          (void)Host_configure_pipe(P_CONTROL,
                                    0,
                                    EP_CONTROL,
                                    TYPE_CONTROL,
                                    TOKEN_SETUP,
                                    8,
                                    SINGLE_BANK);
          device_state = DEVICE_DEFAULT;
        }
      }
      break;

    //------------------------------------------------------
    //   DEVICE_DEFAULT state
    //
    //   - Get device descriptor
    //   - Reconfigure control pipe according to device control endpoint
    //   - Assign device address
    //
    case DEVICE_DEFAULT:
      // Get first device descriptor
      if (host_get_device_descriptor_incomplete() == CONTROL_GOOD)
      {
        sof_cnt = 0;
        while (sof_cnt < 20)          // Wait 20 ms before USB reset (special buggy devices...)
        {
          if (Is_usb_event(EVT_HOST_SOF)) Usb_ack_event(EVT_HOST_SOF), sof_cnt++;
          if (Is_host_emergency_exit() || Is_usb_bconnection_error_interrupt()) break;
        }
        cpu_irq_disable();
        Host_disable_device_disconnection_interrupt();
        Host_send_reset();            // First USB reset
        (void)Is_host_sending_reset();
        cpu_irq_enable();
        Usb_ack_event(EVT_HOST_SOF);
        // Active wait for end of reset send
        while (Is_host_sending_reset())
        {
          // The USB macro does not signal the end of reset when a disconnection occurs
          if (Is_host_device_disconnection())
          {
            // Stop sending USB reset
            Host_stop_sending_reset();
          }
        }
        Host_ack_reset_sent();
        if (!Is_host_device_disconnection())
        {
          // Workaround for some buggy devices with powerless pull-up
          // usually low-speed where data line rises slowly and can be interpreted as disconnection
          for (sof_cnt = 0; sof_cnt < 0xFFFF; sof_cnt++)  // Basic time-out counter
          {
            // If we detect SOF, device is still alive and connected, just clear false disconnect flag
            if (Is_usb_event(EVT_HOST_SOF) && Is_host_device_disconnection())
            {
              Host_ack_device_connection();
              Host_ack_device_disconnection();
              break;
            }
          }
        }
        Host_enable_device_disconnection_interrupt();
        sof_cnt = 0;
        while (sof_cnt < 200)         // Wait 200 ms after USB reset
        {
          if (Is_usb_event(EVT_HOST_SOF)) Usb_ack_event(EVT_HOST_SOF), sof_cnt++;
          if (Is_host_emergency_exit() || Is_usb_bconnection_error_interrupt()) break;
        }
        Host_disable_pipe(P_CONTROL);
        Host_unallocate_memory(P_CONTROL);
        Host_enable_pipe(P_CONTROL);
        // Reconfigure the control pipe according to the device control endpoint
        (void)Host_configure_pipe(P_CONTROL,
                                  0,
                                  EP_CONTROL,
                                  TYPE_CONTROL,
                                  TOKEN_SETUP,
                                  data_stage[OFFSET_FIELD_MAXPACKETSIZE],
                                  SINGLE_BANK);
        // Give an absolute device address
        if (host_set_address(DEVICE_ADDRESS) == CONTROL_GOOD)
        {
          for (pipe = 0; pipe < MAX_PEP_NB; pipe++)
            Host_configure_address(pipe, DEVICE_ADDRESS);
          device_state = DEVICE_ADDRESSED;
        }
        else if (device_state != DEVICE_VBUS_LOW)
          device_state = DEVICE_ERROR;
      }
      else
      {
        if (device_state != DEVICE_VBUS_LOW)
        {
          if (++device_default_error_count > DEVICE_DEFAULT_MAX_ERROR_COUNT)
          device_state = DEVICE_ERROR;
          else
          {
            Host_disable_sof();
            Host_disable_pipe(P_CONTROL);
            Host_unallocate_memory(P_CONTROL);
            device_state = DEVICE_ATTACHED;
            goto device_attached_retry;
          }
        }
        Usb_ack_bconnection_error_interrupt();
        Usb_ack_vbus_error_interrupt();
        Host_disable_sof();
      }
      break;

    //------------------------------------------------------
    //   DEVICE_ADDRESSED state
    //
    //   - Check if VID PID is in supported list
    //
    case DEVICE_ADDRESSED:
      if (host_get_device_descriptor() == CONTROL_GOOD)
      {
        // Detect if the device connected belongs to the supported devices table
        if (host_check_VID_PID())
        {
          Host_set_device_supported();
          Host_device_supported_action();
          device_state = DEVICE_CONFIGURED;
        }
        else
        {
#if HOST_STRICT_VID_PID_TABLE == ENABLE
          device_state = DEVICE_ERROR;
          LOG_STR(log_unsupported_device);
#else
          device_state = DEVICE_CONFIGURED;
#endif
          Host_device_not_supported_action();
        }
      }
      else if (device_state != DEVICE_VBUS_LOW)
        device_state = DEVICE_ERROR; // Can not get device descriptor
      break;

    //------------------------------------------------------
    //   DEVICE_CONFIGURED state
    //
    //   - Configure pipes for the supported interface
    //   - Send Set_configuration() request
    //   - Go to full operating mode (device ready)
    //
    case DEVICE_CONFIGURED:
      {
        uint8_t configuration_index = 0;

        if (host_get_configuration_descriptor(configuration_index) == CONTROL_GOOD)
        {
          if (host_check_class())       // Class support OK?
          {
#if HOST_AUTO_CFG_ENDPOINT == DISABLE
            User_configure_endpoint();  // User call here instead of autoconfig
            Host_set_configured();      // Assumes config is OK with user config
#endif
            if (Is_host_configured())
            {
              if (host_set_configuration(data_stage[OFFSET_FIELD_CONFIGURATION_NB]) == CONTROL_GOOD)  // Send Set_configuration
              {
                // Device and host are now fully configured
                // go to DEVICE_READY normal operation
                device_state = DEVICE_READY;
                // Monitor device disconnection under interrupt
                Host_enable_device_disconnection_interrupt();
                // If user host application requires SOF interrupt event
                // Keep SOF interrupt enabled, otherwise disable this interrupt
#if HOST_CONTINUOUS_SOF_INTERRUPT == DISABLE
                cpu_irq_disable();
                Host_disable_sof_interrupt();
                (void)Is_host_sof_interrupt_enabled();
                cpu_irq_enable();
#endif
                Host_new_device_connection_action();
                cpu_irq_enable();
                LOG_STR(log_device_enumerated);
              }
              else if (device_state != DEVICE_VBUS_LOW)
                device_state = DEVICE_ERROR; // Problem during Set_configuration request...
            }
          }
          else  // Device class not supported...
          {
            device_state = DEVICE_UNSUPPORTED;
            LOG_STR(log_unsupported_device);
            Host_device_class_not_supported_action();
          }
        }
        else if (device_state != DEVICE_VBUS_LOW)
          device_state = DEVICE_ERROR; // Can not get configuration descriptors...
      }
      break;

    //------------------------------------------------------
    //   DEVICE_READY state
    //
    //   - Full standard operating mode
    //   - Nothing to do...
    //
    case DEVICE_READY:                // Host full standard operating mode!
      break;

    //------------------------------------------------------
    //   DEVICE_UNSUPPORTED state
    //
    case DEVICE_UNSUPPORTED:
      break;

    //------------------------------------------------------
    //   DEVICE_ERROR state
    //
    //   - Error state
    //   - Do custom action call (probably go to default mode...)
    //
    case DEVICE_ERROR:                //! @todo
#if HOST_ERROR_RESTART == ENABLE
      device_state = DEVICE_UNATTACHED;
#endif
      Host_device_error_action();
      break;

    //------------------------------------------------------
    //   DEVICE_SUSPENDED state
    //
    //   - Host application request to suspend the device activity
    //   - State machine comes here thanks to Host_request_suspend()
    //
    case DEVICE_SUSPENDED:
      if (Is_device_supports_remote_wakeup()) // If the connected device supports remote wake-up
      {
        host_set_feature_remote_wakeup(); // Enable this feature...
      }
      LOG_STR(log_usb_suspended);
      sav_int_sof_enable = Is_host_sof_interrupt_enabled(); //Save current SOF interrupt enable state
      cpu_irq_disable();
      Host_disable_sof_interrupt();
      (void)Is_host_sof_interrupt_enabled();
      cpu_irq_enable();
      Host_ack_sof();
      Host_disable_sof();             // Stop SOF generation, this generates the suspend state
      Host_ack_hwup();
      Host_enable_hwup_interrupt();   // Enable host wake-up interrupt
                                      // (this is the unique USB interrupt able to wake up the CPU core from power-down mode)
      (void)Is_host_hwup_interrupt_enabled(); // Make sure host wake-up interrupt is enabled
      Usb_freeze_clock();
      //! @todo Implement this on the silicon version
      //Stop_pll();
      Host_suspend_action();          // Custom action here! (e.g. go to power-save mode...)
      device_state = DEVICE_WAIT_RESUME;  // Wait for device resume event
      break;

    //------------------------------------------------------
    //   DEVICE_WAIT_RESUME state
    //
    //   Wait in this state till:
    //   - the host receives an upstream resume from the device
    //   - or the host software request the device to resume
    //
    case DEVICE_WAIT_RESUME:
      if (Is_usb_event(EVT_HOST_HWUP) || Is_host_request_resume())  // Remote wake-up has been detected
                                                                    // or local resume request has been received
      {
        if (Is_host_request_resume())     // Not a remote wake-up, but a host application request
        {
          // CAUTION: HWUP can be cleared only when USB clock is active
          //! @todo Implement this on the silicon version
          //Pll_start_auto();               // First Restart the PLL for USB operation
          //Wait_pll_ready();               // Make sure PLL is locked
          Usb_unfreeze_clock();           // Enable clock on USB interface
          (void)Is_usb_clock_frozen();    // Make sure USB interface clock is enabled
          cpu_irq_disable();
          Host_disable_hwup_interrupt();  // Wake-up interrupt should be disabled as host is now awoken!
          (void)Is_host_hwup_interrupt_enabled();
          cpu_irq_enable();
          Host_ack_hwup();                // Clear HWUP interrupt flag
        }
        Host_enable_sof();
        Host_send_resume();               // Send downstream resume
        while (!Is_host_down_stream_resume());  // Wait for downstream resume sent
        Host_ack_remote_wakeup();         // Ack remote wake-up reception
        Host_ack_request_resume();        // Ack software request
        Host_ack_down_stream_resume();    // Ack downstream resume sent
        Usb_ack_event(EVT_HOST_HWUP);     // Ack software event
        if (sav_int_sof_enable) Host_enable_sof_interrupt();  // Restore SOF interrupt enable state before suspend
        device_state = DEVICE_READY;      // Come back to full operating mode
        LOG_STR(log_usb_resumed);
      }
      break;

    //------------------------------------------------------
    //   default state
    //
    //   - Default case: ERROR
    //   - Go to DEVICE_UNATTACHED state
    //
    default:
      device_state = DEVICE_UNATTACHED;
      break;
    }
#ifdef FREERTOS_USED
  }
#endif
}
Esempio n. 14
0
__interrupt
#endif
static void usb_general_interrupt(void)

#endif
{
#ifdef FREERTOS_USED
  portBASE_TYPE task_woken = pdFALSE;
#endif
#if USB_HOST_FEATURE == true && USB_HOST_PIPE_INTERRUPT_TRANSFER == ENABLE
  U8 i;
#endif

// ---------- DEVICE/HOST events management ------------------------------------
#if USB_DEVICE_FEATURE == true && USB_HOST_FEATURE == true
  // ID pin change detection
  if (Is_usb_id_transition() && Is_usb_id_interrupt_enabled())
  {
    g_usb_mode = (Is_usb_id_device()) ? USB_MODE_DEVICE : USB_MODE_HOST;
    Usb_ack_id_transition();
    if (g_usb_mode != g_old_usb_mode) // Basic debounce
    {
      // Previously in device mode, check if disconnection was detected
      if (g_old_usb_mode == USB_MODE_DEVICE)
      {
        if (usb_connected)
        {
          // Device mode disconnection actions
          usb_connected = false;
          usb_configuration_nb = 0;
          Usb_vbus_off_action();
        }
      }
      // Previously in host mode, check if disconnection was detected
      else if (Is_host_attached())
      {
        // Host mode disconnection actions
        device_state = DEVICE_UNATTACHED;
        Host_device_disconnection_action();
      }

      //LOG_STR(log_pin_id_changed);
      if (Is_usb_id_device() == USB_MODE_DEVICE) { LOG_STR(log_pin_id_changed_to_device); }
		else { LOG_STR(log_pin_id_changed_to_host); }
	  
	  Usb_send_event((Is_usb_device()) ? EVT_USB_DEVICE_FUNCTION :
                                         EVT_USB_HOST_FUNCTION);
      Usb_id_transition_action();

	  // Easier to recover from ID signal de-bounce and ID pin transitions by shutting down the USB and resetting state machine to re-init
#if ID_PIN_CHANGE_SHUTDOWN_USB == ENABLE
      Usb_disable();
      Usb_disable_otg_pad();

extern void UsbResetStateMachine(void);
	  UsbResetStateMachine();

    #ifdef FREERTOS_USED
      // Release the semaphore in order to start a new device/host task
      taskENTER_CRITICAL();
      xSemaphoreGiveFromISR(usb_tsk_semphr, &task_woken);
      taskEXIT_CRITICAL();
	#endif
#endif

#if ID_PIN_CHANGE_GENERATE_RESET == ENABLE
      Reset_CPU();
#endif
    }
  }
#endif  // End DEVICE/HOST FEATURE MODE

// ---------- DEVICE events management -----------------------------------------
#if USB_DEVICE_FEATURE == true
  #if USB_HOST_FEATURE == true
  // If both device and host features are enabled, check if device mode is engaged
  // (accessing the USB registers of a non-engaged mode, even with load operations,
  // may corrupt USB FIFO data).
  if (Is_usb_device())
  #endif
  {
    // VBus state detection
    if (Is_usb_vbus_transition() && Is_usb_vbus_interrupt_enabled())
    {
      Usb_ack_vbus_transition();
      if (Is_usb_vbus_high())
      {
        usb_start_device();
        Usb_send_event(EVT_USB_POWERED);
        Usb_vbus_on_action();
      }
      else
      {
        Usb_unfreeze_clock();
        Usb_detach();
        usb_connected = false;
        usb_configuration_nb = 0;
        Usb_send_event(EVT_USB_UNPOWERED);
        Usb_vbus_off_action();
  #ifdef FREERTOS_USED
        // Release the semaphore in order to start a new device/host task
        taskENTER_CRITICAL();
        xSemaphoreGiveFromISR(usb_tsk_semphr, &task_woken);
        taskEXIT_CRITICAL();
  #endif
      }
    }
    // Device Start-of-Frame received
    if (Is_usb_sof() && Is_usb_sof_interrupt_enabled())
    {
      Usb_ack_sof();
      Usb_sof_action();
    }
    // Device Suspend event (no more USB activity detected)
    if (Is_usb_suspend() && Is_usb_suspend_interrupt_enabled())
    {
      Usb_ack_suspend();
      Usb_enable_wake_up_interrupt();
      (void)Is_usb_wake_up_interrupt_enabled();
      Usb_freeze_clock();
      Usb_send_event(EVT_USB_SUSPEND);
      Usb_suspend_action();
    }
    // Wake-up event (USB activity detected): Used to resume
    if (Is_usb_wake_up() && Is_usb_wake_up_interrupt_enabled())
    {
      Usb_unfreeze_clock();
      (void)Is_usb_clock_frozen();
      Usb_ack_wake_up();
      Usb_disable_wake_up_interrupt();
      Usb_wake_up_action();
      Usb_send_event(EVT_USB_WAKE_UP);
    }
    // Resume state bus detection
    if (Is_usb_resume() && Is_usb_resume_interrupt_enabled())
    {
      Usb_disable_wake_up_interrupt();
      Usb_ack_resume();
      Usb_disable_resume_interrupt();
      Usb_resume_action();
      Usb_send_event(EVT_USB_RESUME);
    }
    // USB bus reset detection
    if (Is_usb_reset() && Is_usb_reset_interrupt_enabled())
    {
      Usb_ack_reset();
      usb_init_device();
      Usb_reset_action();
      Usb_send_event(EVT_USB_RESET);
    }
  }
#endif  // End DEVICE FEATURE MODE

// ---------- HOST events management -------------------------------------------
#if USB_HOST_FEATURE == true
  #if USB_DEVICE_FEATURE == true
  // If both device and host features are enabled, check if host mode is engaged
  // (accessing the USB registers of a non-engaged mode, even with load operations,
  // may corrupt USB FIFO data).
  else
  #endif
  {
    // The device has been disconnected
    if (Is_host_device_disconnection() && Is_host_device_disconnection_interrupt_enabled())
    {
      host_disable_all_pipes();
      Host_ack_device_disconnection();
  #if USB_HOST_PIPE_INTERRUPT_TRANSFER == ENABLE
      reset_it_pipe_str();
  #endif
      device_state = DEVICE_UNATTACHED;
      LOG_STR(log_device_disconnected);
      Usb_send_event(EVT_HOST_DISCONNECTION);
      Host_device_disconnection_action();
  #ifdef FREERTOS_USED
      // Release the semaphore in order to start a new device/host task
      taskENTER_CRITICAL();
      xSemaphoreGiveFromISR(usb_tsk_semphr, &task_woken);
      taskEXIT_CRITICAL();
  #endif
    }
    // Device connection
    if (Is_host_device_connection() && Is_host_device_connection_interrupt_enabled())
    {
      Host_ack_device_connection();
      host_disable_all_pipes();
      Host_device_connection_action();
    }
    // Host Start-of-Frame has been sent
    if (Is_host_sof() && Is_host_sof_interrupt_enabled())
    {
      Host_ack_sof();
      Usb_send_event(EVT_HOST_SOF);
#if (USB_HIGH_SPEED_SUPPORT==true)
      if( Is_usb_full_speed_mode() )
      {
         private_sof_counter++;
      }else{
         private_sof_counter_HS++;
         if( 0 == (private_sof_counter_HS%8) )
         {
            private_sof_counter++;
         }
      }
#else
      private_sof_counter++;
#endif
      // Delay time-out management for interrupt transfer mode in host mode
  #if USB_HOST_PIPE_INTERRUPT_TRANSFER == ENABLE && TIMEOUT_DELAY_ENABLE == ENABLE
      if (private_sof_counter >= 250) // Count 250 ms (SOF @ 1 ms)
      {
        private_sof_counter = 0;
        for (i = 0; i < MAX_PEP_NB; i++)
        {
          if (it_pipe_str[i].enable &&
              ++it_pipe_str[i].timeout > TIMEOUT_DELAY && Host_get_pipe_type(i) != TYPE_INTERRUPT)
          {
            it_pipe_str[i].enable = false;
            it_pipe_str[i].status = PIPE_DELAY_TIMEOUT;
            Host_reset_pipe(i);
            if (!is_any_interrupt_pipe_active() && !g_sav_int_sof_enable) // If no more transfer is armed
            {
              Host_disable_sof_interrupt();
            }
            it_pipe_str[i].handler(PIPE_DELAY_TIMEOUT, it_pipe_str[i].nb_byte_processed);
          }
        }
      }
  #endif
      Host_sof_action();
    }
    // Host Wake-up has been received
    if (Is_host_hwup() && Is_host_hwup_interrupt_enabled())
    {
      // CAUTION: HWUP can be cleared only when USB clock is active (not frozen)!
      //! @todo Implement this on the silicon version
      //Pll_start_auto();               // First Restart the PLL for USB operation
      //Wait_pll_ready();               // Make sure PLL is locked
      Usb_unfreeze_clock();           // Enable clock on USB interface
      (void)Is_usb_clock_frozen();    // Make sure USB interface clock is enabled
      Host_disable_hwup_interrupt();  // Wake-up interrupt should be disabled as host is now awoken!
      Host_ack_hwup();                // Clear HWUP interrupt flag
      Usb_send_event(EVT_HOST_HWUP);  // Send software event
      Host_hwup_action();             // Map custom action
    }
  #if USB_HOST_PIPE_INTERRUPT_TRANSFER == ENABLE
    // Host pipe interrupts
    while ((i = Host_get_interrupt_pipe_number()) < MAX_PEP_NB) usb_pipe_interrupt(i);
  #endif
  }
#endif  // End HOST FEATURE MODE

#ifdef FREERTOS_USED
  return task_woken;
#endif
}
Esempio n. 15
0
ISR(usb_general_interrupt, AVR32_USBB_IRQ_GROUP, USB_INT_LEVEL)

#endif
{
#ifdef FREERTOS_USED
  portBASE_TYPE task_woken = pdFALSE;
#endif
  uint8_t i;
  /* avoid Cppcheck Warning */
  UNUSED(i);

// ---------- DEVICE/HOST events management ------------------------------------
#if USB_DEVICE_FEATURE == true && USB_HOST_FEATURE == true
  // ID pin change detection
  if (Is_usb_id_transition() && Is_usb_id_interrupt_enabled())
  {
    g_usb_mode = (Is_usb_id_device()) ? USB_MODE_DEVICE : USB_MODE_HOST;
    Usb_ack_id_transition();
    if (g_usb_mode != g_old_usb_mode) // Basic debounce
    {
      // Previously in device mode, check if disconnection was detected
      if (g_old_usb_mode == USB_MODE_DEVICE)
      {
        if (usb_connected)
        {
          // Device mode diconnection actions
          usb_connected = false;
          usb_configuration_nb = 0;
          Usb_vbus_off_action();
        }
      }
      // Previously in host mode, check if disconnection was detected
      else if (Is_host_attached())
      {
        // Host mode diconnection actions
        device_state = DEVICE_UNATTACHED;
        Host_device_disconnection_action();
      }
      LOG_STR(log_pin_id_changed);
      Usb_send_event((Is_usb_device()) ? EVT_USB_DEVICE_FUNCTION :
                                         EVT_USB_HOST_FUNCTION);
      Usb_id_transition_action();
      //! @todo ID pin hot state change!!!
      // Preliminary management: HARDWARE RESET!!!
  #if ID_PIN_CHANGE_GENERATE_RESET == ENABLE
      // Hot ID transition generates CPU reset
      Usb_disable();
      Usb_disable_otg_pad();
    #ifdef FREERTOS_USED
      // Release the semaphore in order to start a new device/host task
      taskENTER_CRITICAL();
      xSemaphoreGiveFromISR(usb_tsk_semphr, &task_woken);
      taskEXIT_CRITICAL();
    #else
#if defined(CPU_RESET_CALLBACK)
      CPU_RESET_CALLBACK();
#endif
      Reset_CPU();
    #endif
  #endif
      g_old_usb_mode = g_usb_mode;  // Store current USB mode, for mode change detection
    }
  }
#endif  // End DEVICE/HOST FEATURE MODE

// ---------- DEVICE events management -----------------------------------------
#if USB_DEVICE_FEATURE == true
  #if USB_HOST_FEATURE == true
  // If both device and host features are enabled, check if device mode is engaged
  // (accessing the USB registers of a non-engaged mode, even with load operations,
  // may corrupt USB FIFO data).
  if (Is_usb_device())
  #endif
  {
    // VBus state detection
    if (Is_usb_vbus_transition() && Is_usb_vbus_interrupt_enabled())
    {
      Usb_ack_vbus_transition();
      if (Is_usb_vbus_high())
      {
        usb_start_device();
        Usb_send_event(EVT_USB_POWERED);
        Usb_vbus_on_action();
      }
      else
      {
        Usb_unfreeze_clock();
        Usb_detach();
        usb_connected = false;
        usb_configuration_nb = 0;
        Usb_send_event(EVT_USB_UNPOWERED);
        Usb_vbus_off_action();
  #ifdef FREERTOS_USED
        // Release the semaphore in order to start a new device/host task
        taskENTER_CRITICAL();
        xSemaphoreGiveFromISR(usb_tsk_semphr, &task_woken);
        taskEXIT_CRITICAL();
  #endif
      }
    }
    // Device Start-of-Frame received
    if (Is_usb_sof() && Is_usb_sof_interrupt_enabled())
    {
      Usb_ack_sof();
      Usb_sof_action();
    }
    // Device Suspend event (no more USB activity detected)
    if (Is_usb_suspend() && Is_usb_suspend_interrupt_enabled())
    {
      Usb_ack_suspend();
      Usb_enable_wake_up_interrupt();
      (void)Is_usb_wake_up_interrupt_enabled();
      Usb_freeze_clock();
      Usb_send_event(EVT_USB_SUSPEND);
      Usb_suspend_action();
    }
    // Wake-up event (USB activity detected): Used to resume
    if (Is_usb_wake_up() && Is_usb_wake_up_interrupt_enabled())
    {
      Usb_unfreeze_clock();
      (void)Is_usb_clock_frozen();
      Usb_ack_wake_up();
      Usb_disable_wake_up_interrupt();
      Usb_wake_up_action();
      Usb_send_event(EVT_USB_WAKE_UP);
    }
    // Resume state bus detection
    if (Is_usb_resume() && Is_usb_resume_interrupt_enabled())
    {
      Usb_disable_wake_up_interrupt();
      Usb_ack_resume();
      Usb_disable_resume_interrupt();
      Usb_resume_action();
      Usb_send_event(EVT_USB_RESUME);
    }
    // USB bus reset detection
    if (Is_usb_reset() && Is_usb_reset_interrupt_enabled())
    {
      Usb_ack_reset();
      usb_init_device();
      Usb_reset_action();
      Usb_send_event(EVT_USB_RESET);
    }
  }
#endif  // End DEVICE FEATURE MODE

// ---------- HOST events management -------------------------------------------
#if USB_HOST_FEATURE == true
  #if USB_DEVICE_FEATURE == true
  // If both device and host features are enabled, check if host mode is engaged
  // (accessing the USB registers of a non-engaged mode, even with load operations,
  // may corrupt USB FIFO data).
  else
  #endif
  {
    // The device has been disconnected
    if (Is_host_device_disconnection() && Is_host_device_disconnection_interrupt_enabled())
    {
      host_disable_all_pipes();
      Host_ack_device_disconnection();
  #if USB_HOST_PIPE_INTERRUPT_TRANSFER == ENABLE
      reset_it_pipe_str();
  #endif
  #ifdef HOST_VBUS_LOW_TIMEOUT
      cpu_set_timeout(HOST_VBUS_LOW_TIMEOUT, &timer_vbus_low);
      device_state = DEVICE_VBUS_LOW;
  #else
      device_state = DEVICE_UNATTACHED;
  #endif
      LOG_STR(log_device_disconnected);
      Usb_send_event(EVT_HOST_DISCONNECTION);
      Host_device_disconnection_action();
  #ifdef FREERTOS_USED
      // Release the semaphore in order to start a new device/host task
      taskENTER_CRITICAL();
      xSemaphoreGiveFromISR(usb_tsk_semphr, &task_woken);
      taskEXIT_CRITICAL();
  #endif
    }
    // Device connection
    if (Is_host_device_connection() && Is_host_device_connection_interrupt_enabled())
    {
      Host_ack_device_connection();
      host_disable_all_pipes();
      Usb_send_event(EVT_HOST_CONNECTION);
      Host_device_connection_action();
    }
    // Host Start-of-Frame has been sent
    if (Is_host_sof() && Is_host_sof_interrupt_enabled())
    {
      Host_ack_sof();
      Usb_send_event(EVT_HOST_SOF);
      private_sof_counter++;
      // Delay time-out management for interrupt tranfer mode in host mode
  #if USB_HOST_PIPE_INTERRUPT_TRANSFER == ENABLE && TIMEOUT_DELAY_ENABLE == ENABLE
      if (private_sof_counter >= 250) // Count 250 ms (SOF @ 1 ms)
      {
        private_sof_counter = 0;
        for (i = 0; i < MAX_PEP_NB; i++)
        {
          if (it_pipe_str[i].enable &&
              ++it_pipe_str[i].timeout > TIMEOUT_DELAY && Host_get_pipe_type(i) != TYPE_INTERRUPT)
          {
            it_pipe_str[i].enable = false;
            it_pipe_str[i].status = PIPE_DELAY_TIMEOUT;
            Host_reset_pipe(i);
            if (!is_any_interrupt_pipe_active() && !g_sav_int_sof_enable) // If no more transfer is armed
            {
              Host_disable_sof_interrupt();
            }
            it_pipe_str[i].handler(PIPE_DELAY_TIMEOUT, it_pipe_str[i].nb_byte_processed);
          }
        }
      }
  #endif
      Host_sof_action();
    }
    // Host Wake-up has been received
    if (Is_host_hwup() && Is_host_hwup_interrupt_enabled())
    {
      // CAUTION: HWUP can be cleared only when USB clock is active (not frozen)!
      //! @todo Implement this on the silicon version
      //Pll_start_auto();               // First Restart the PLL for USB operation
      //Wait_pll_ready();               // Make sure PLL is locked
      Usb_unfreeze_clock();           // Enable clock on USB interface
      (void)Is_usb_clock_frozen();    // Make sure USB interface clock is enabled
      Host_disable_hwup_interrupt();  // Wake-up interrupt should be disabled as host is now awoken!
      Host_ack_hwup();                // Clear HWUP interrupt flag
      Usb_send_event(EVT_HOST_HWUP);  // Send software event
      Host_hwup_action();             // Map custom action
    }

    Host_int_action();

    while ((i = Host_get_interrupt_pipe_number()) < MAX_PEP_NB)
    {
      if (Is_host_in_received(i) && Is_host_in_received_interrupt_enabled(i))
      {
        Host_freeze_pipe(i);
        Host_disable_in_received_interrupt(i);
      }
    }

  #if defined(USB_HIGH_SPEED_SUPPORT) && USB_HIGH_SPEED_SUPPORT == true && \
    defined(PIPE_AUDIO_IN)
    // Workaround - freeze the IN audio pipe
    if (Is_host_in_received(PIPE_AUDIO_IN))
    {
      extern void workaround_freeze_iso_in(void);
      workaround_freeze_iso_in();
    }
  #endif // USB_HIGH_SPEED_SUPPORT == true

  #if USB_HOST_PIPE_INTERRUPT_TRANSFER == ENABLE
    // Host pipe interrupts
    while ((i = Host_get_interrupt_pipe_number()) < MAX_PEP_NB) usb_pipe_interrupt(i);
  #endif
  }
#endif  // End HOST FEATURE MODE

#ifdef FREERTOS_USED
  return task_woken;
#endif
}
ContactListingModel::~ContactListingModel() {
    LOG_STR("ContactListingModel::~ContactListingModel") ;
}
Esempio n. 17
0
void Fls_MainFunction(void) {
	/** @req FLS255 */
	/** @req FLS266 */
	/** @req FLS038 */
	/** !req FLS040  No support for Fls_ConfigSetType.FlsMaxXXXX */
	/** !req FLS104 */
	/** !req FLS105 */
	/** !req FLS106 */
	/** !req FLS154 */
	/** !req FLS200 */
	/** !req FLS022 */
	/** !req FLS055 */
	/** !req FLS056 */
	/** !req FLS052 */
	/** !req FLS232 */
	/** !req FLS233 */
	/** !req FLS234 */
	/** !req FLS235 */
	/** !req FLS272 */
	/** !req FLS196 */



	uint32 flashStatus;
	int result;
	uint32 eccErrReg = 0;

	uint32 chunkSize;

	/** @req FLS117 */
	VALIDATE_NO_RV(Fls_Global.status != MEMIF_UNINIT,FLS_MAIN_FUNCTION_ID, FLS_E_UNINIT );

	/** @req FLS039 */
	if ( Fls_Global.jobResultType == MEMIF_JOB_PENDING) {
		switch (Fls_Global.jobType) {
		case FLS_JOB_COMPARE:
		    /** @req FLS243 */

			// NOT implemented. Hardware error = FLS_E_COMPARE_FAILED
			// ( we are reading directly from flash so it makes no sense )

			chunkSize = MIN( Fls_Global.length, Fls_Global.readChunkSize );

		    /** @req FLS244 */
			result = memcmp((void *)Fls_Global.ramAddr,
					        (void *)Fls_Global.flashAddr, chunkSize );

			Fls_Global.ramAddr += chunkSize;
			Fls_Global.flashAddr += chunkSize;
			Fls_Global.length -= chunkSize;

			McuE_GetECCError(&eccErrReg);
			if( eccErrReg & FLASH_NON_CORRECTABLE_ERROR ){
				fls_ReadFail();
			} else {
				if( 0 != Fls_Global.length ) {
					if (result == 0) {
						Fls_Global.jobResultType = MEMIF_JOB_OK;
					} else {
						Fls_Global.jobResultType = MEMIF_BLOCK_INCONSISTENT;
					}
					Fls_Global.status = MEMIF_IDLE;
					Fls_Global.jobType = FLS_JOB_NONE;
				} else {
					/* Do nothing, wait for next loop */
				}
			}

			break;
		case FLS_JOB_ERASE: {

			flashStatus = Flash_CheckStatus(Fls_Global.config->FlsInfo, (uint32_t *)Fls_Global.flashAddr, Fls_Global.length );

			if (flashStatus == EE_OK ) {
				Fls_Global.jobResultType = MEMIF_JOB_OK;
				Fls_Global.jobType = FLS_JOB_NONE;
				Fls_Global.status = MEMIF_IDLE;
				FEE_JOB_END_NOTIFICATION();
			} else if (flashStatus == EE_INFO_HVOP_INPROGRESS) {
				/* Busy, Do nothing */
			} else {
				// Error
				fls_EraseFail();
			}
            break;
		}
		case FLS_JOB_READ:
			/** @req FLS238 */
			/** @req FLS239 */

			// NOT implemented. Hardware error = FLS_E_READ_FAILED
			// ( we are reading directly from flash so it makes no sense )
			// Read ECC-error to clear it
			McuE_GetECCError(&eccErrReg);


			chunkSize = MIN( Fls_Global.length, Fls_Global.readChunkSize );

			memcpy( (void *)Fls_Global.ramAddr, (void *) Fls_Global.flashAddr, chunkSize );

			Fls_Global.ramAddr += chunkSize;
			Fls_Global.flashAddr += chunkSize;
			Fls_Global.length -= chunkSize;

			McuE_GetECCError(&eccErrReg);
			if( eccErrReg & FLASH_NON_CORRECTABLE_ERROR ){
				fls_ReadFail();
			} else {
				if( 0 == Fls_Global.length ) {
					Fls_Global.jobResultType = MEMIF_JOB_OK;
					Fls_Global.status = MEMIF_IDLE;
					Fls_Global.jobType = FLS_JOB_NONE;
					FEE_JOB_END_NOTIFICATION();
					LOG_STR("Fls_RP() OK\n");
				}
			}
			break;

		case FLS_JOB_WRITE:
		{
			/* We are writing in chunks. If we want to write 6 chunks in total but
			 * only 2 at a time:
			 *
			 * Call
			 *  #1   The Fls_Write
			 *  #2   Wait for Flash_CheckStatus(), Flash_ProgramPageStart().. function return
			 *      -> 1 verified write, 1 pending
			 *  #3  Wait for Flash_CheckStatus(), Flash_ProgramPageStart()
			 *      Wait for Flash_CheckStatus(), Flash_ProgramPageStart() .. function return
			 *      -> 3 verified writes, 1 pending
			 *  #4  Wait for Flash_CheckStatus(), Flash_ProgramPageStart()
			 *      Wait for Flash_CheckStatus(), Flash_ProgramPageStart() .. function return
			 *      -> 5 verified writes, 1 pending
			 *  #5  Wait for Flash_CheckStatus(), ...function return
			 *      -> 6 verified writes,
			 */



			int32_t chunkSize = MIN(Fls_Global.flashWriteInfo.chunkSize, Fls_Global.flashWriteInfo.left);

		    do {
				flashStatus = Flash_CheckStatus(
										Fls_Global.config->FlsInfo,
										(uint32_t *) Fls_Global.flashWriteInfo.pDest,
										Fls_Global.flashWriteInfo.pLeft - Fls_Global.flashWriteInfo.left);



				if (flashStatus == EE_OK) {

					LOG_HEX1("Fls_CS() OK ",Fls_Global.flashWriteInfo.pDest);

					if (Fls_Global.flashWriteInfo.left == 0) {
						/* Done! */
						Fls_Global.jobResultType = MEMIF_JOB_OK;
						Fls_Global.status = MEMIF_IDLE;
						Fls_Global.jobType = FLS_JOB_NONE;
						FEE_JOB_END_NOTIFICATION();
						break;
					}

					/* Write more */
					Fls_Global.flashWriteInfo.pDest = Fls_Global.flashWriteInfo.dest;
					Fls_Global.flashWriteInfo.pLeft = Fls_Global.flashWriteInfo.left;

					/* Double word programming */
					LOG_HEX2("Fls_PP() ",Fls_Global.flashWriteInfo.dest," ", Fls_Global.flashWriteInfo.left);

					flashStatus = Flash_ProgramPageStart(
											Fls_Global.config->FlsInfo,
											&Fls_Global.flashWriteInfo.dest,
											&Fls_Global.flashWriteInfo.source,
											&Fls_Global.flashWriteInfo.left, NULL);
					if (flashStatus != EE_OK) {
						fls_WriteFail();
						break;
					}

					chunkSize = chunkSize - (int32_t)(Fls_Global.flashWriteInfo.pLeft - Fls_Global.flashWriteInfo.left);

				} else if (flashStatus == EE_INFO_HVOP_INPROGRESS) {
					/* Wait for it */
				} else {
					fls_WriteFail();
					/* Nothing to do, quit loop */
					break;
				}

			} while (chunkSize > 0 );

			break;
		}
		case FLS_JOB_NONE:
			assert(0);
			break;

		default:
		    break;
		} /* switch */

	}   /* if */
}
NewProfileCommentDialog::~NewProfileCommentDialog() {
    LOG_STR("NewProfileCommentDialog::~NewProfileCommentDialog") ;
}
TrustTreeModel::~TrustTreeModel() {
    LOG_STR("TrustTreeModel::~TrustTreeModel()") ;
    delete iTrustTree ;
}
void NewProfileCommentDialog::okButtonClicked() {
    LOG_STR("NewProfileCommentDialog::okButtonClicked") ;

    Hash selectedUserProfileHash ( iController->profileInUse() ) ;
    ProfileComment comment ;

    if ( iSelectedProfile.iIsPrivate == false ) {
        comment.iCommentorNickName = iSelectedProfile.displayName() ;
    }
    comment.iSubject = ui.subjectEdit->text() ;
    comment.iCommentText = ui.messageEdit->toHtml() ;

    comment.iCommentorHash = iSelectedProfile.iFingerPrint ;
    QLOG_STR("New profile comment comment.iCommentorHash = " + comment.iCommentorHash.toString() ) ;
    comment.iTimeOfPublish = QDateTime::currentDateTimeUtc().toTime_t() ;
    comment.iProfileFingerPrint.fromString(reinterpret_cast<const unsigned char *>(ui.commentedProfileEdit->text().toLatin1().constData())) ;
    if ( comment.iProfileFingerPrint == KNullHash ) {
        QMessageBox::about(this, tr("Error"),
                           tr("Commented profile addr is not valid")) ;
    } else {
        QLOG_STR("Profilecomment comment.iProfileFingerPrint = " + comment.iProfileFingerPrint.toString() ) ;
        if ( iReferencesMsg != KNullHash ) {
            comment.iReferences = iReferencesMsg  ;
            comment.iTypeOfObjectReferenced = PrivateMessage ;
        } else if ( iReferencesCa != KNullHash ) {
            comment.iReferences = iReferencesCa  ;
            comment.iTypeOfObjectReferenced = ClassifiedAd ;
        } else {
            comment.iReferences = KNullHash ;
        }
        foreach (const MetadataQueryDialog::MetadataResultSet& attachmentFile , iFilesAboutToBeAttached ) {
            Hash attachmentHash = publishBinaryAttachment(attachmentFile,
                                  false) ;
            if ( attachmentHash != KNullHash ) {
                comment.iAttachedFiles.append(attachmentHash) ;
            }
        }
        // TODO:
        // set iReferences to some meaningful value
        iController->model().lock() ;

        if ( iRecipientsNode == KNullHash ) {
            iRecipientsNode =  AttachmentListDialog::tryFindNodeByProfile(comment.iProfileFingerPrint, *iController) ;
        }

        quint32 dummy  ;
        if (
            iController->model().contentEncryptionModel().PublicKey(iSelectedProfile.iFingerPrint,
                    comment.iKeyOfCommentor,
                    &dummy )) {
            if ( iController->model().profileCommentModel().publishProfileComment(comment) ) {
                iCommentListingModel.newCommentReceived(comment) ;
            }
        } else {
            QMessageBox::about(this, tr("Error"),
                               tr("Recipient encryption key not found from storage")) ;
        }
        iController->model().unlock() ;

        close() ;
        this->deleteLater() ;
    }
Esempio n. 21
0
void Fls_MainFunction(void) {
	/** @req SWS_Fls_00038 */

    static uint32 progressCntr = 0;
	uint32 flashStatus;
	sint32 result;
	uint8 eccError = 0;

	uint32 chunkSize;

	/** @req SWS_Fls_117 */
	VALIDATE_NO_RV(Fls_Global.status != MEMIF_UNINIT,FLS_MAIN_FUNCTION_ID, FLS_E_UNINIT );

	/** @req SWS_Fls_00039 */
	if ( Fls_Global.jobResultType == MEMIF_JOB_PENDING) {
		switch (Fls_Global.jobType) {
		case FLS_JOB_COMPARE:
		    /** @req SWS_Fls_00243 */

			// !req SWS_Fls_00154  Hardware error = FLS_E_COMPARE_FAILED
			// ( we are reading directly from flash so it makes no sense )
		    // Read ECC-error to clear it
		    Mcu_Arc_GetECCError(&eccError); /*lint !e934 Only used in this function  */

		    chunkSize = MIN( Fls_Global.length, Fls_Global.readChunkSize );

		    /** @req SWS_Fls_00244 */
		    /*lint -e{923} flashAddr set by AUTOSAR and it is justified to cast in this case */
			result = (sint32)memcmp((void *)Fls_Global.ramAddr,
					                (void *)Fls_Global.flashAddr, (size_t)chunkSize );

			Fls_Global.ramAddr = &Fls_Global.ramAddr[chunkSize];
			Fls_Global.flashAddr += chunkSize;
			Fls_Global.length -= chunkSize;

			Mcu_Arc_GetECCError(&eccError);  /*lint !e934 Only used in this function  */
			if( eccError > 0u ){
				readFail();
			} else {
				if( 0 != Fls_Global.length ) {
					if (result == 0) {
						Fls_Global.jobResultType = MEMIF_JOB_OK;
					} else {
						/* @req SWS_Fls_00200 */
						Fls_Global.jobResultType = MEMIF_BLOCK_INCONSISTENT;
					}
					Fls_Global.status = MEMIF_IDLE;
					Fls_Global.jobType = FLS_JOB_NONE;
				} else {
					/* Do nothing, wait for next loop */
				}
			}

			break;
		case FLS_JOB_ERASE: {

			flashStatus = Flash_CheckStatus(Fls_Global.config->FlsInfo, (uint32*)Fls_Global.flashAddr, Fls_Global.length ); /*lint !e923 Intended  */

			if (flashStatus == EE_OK ) {
				Fls_Global.jobResultType = MEMIF_JOB_OK;
				Fls_Global.jobType = FLS_JOB_NONE;
				Fls_Global.status = MEMIF_IDLE;
				FEE_JOB_END_NOTIFICATION();
			} else if (flashStatus == EE_INFO_HVOP_INPROGRESS) {
				/* Busy, Do nothing */
			} else {
				// Error
				eraseFail();
			}
			break;
		}
		case FLS_JOB_READ:
			/** @req SWS_Fls_00238 */
			/** @req SWS_Fls_00239 */

			// NOT implemented. Hardware error = FLS_E_READ_FAILED
			// ( we are reading directly from flash so it makes no sense )
			// Read ECC-error to clear it
			Mcu_Arc_GetECCError(&eccError); /*lint !e934 Only used in this function  */


			chunkSize = MIN( Fls_Global.length, Fls_Global.readChunkSize );

			memcpy( (void *)Fls_Global.ramAddr, (void *) Fls_Global.flashAddr, (size_t)chunkSize );  /*lint !e923 Inteded use  */

			Fls_Global.ramAddr += chunkSize; /*lint !e9016 Intended use */
			Fls_Global.flashAddr += chunkSize;
			Fls_Global.length -= chunkSize;

			Mcu_Arc_GetECCError(&eccError);  /*lint !e934 Only used in this function  */
			if( eccError > 0u ){
				readFail();
			} else {
				if( 0 == Fls_Global.length ) {
					Fls_Global.jobResultType = MEMIF_JOB_OK;
					Fls_Global.status = MEMIF_IDLE;
					Fls_Global.jobType = FLS_JOB_NONE;
					FEE_JOB_END_NOTIFICATION();
					LOG_STR("Fls_RP() OK\n");
				}
			}
			break;

		case FLS_JOB_WRITE:
		{
			/* We are writing in chunks. If we want to write 6 chunks in total but
			 * only 2 at a time:
			 *
			 * Call
			 *  #1   The Fls_Write
			 *  #2   Wait for Flash_CheckStatus(), Flash_ProgramPageStart().. function return
			 *      -> 1 verified write, 1 pending
			 *  #3  Wait for Flash_CheckStatus(), Flash_ProgramPageStart()
			 *      Wait for Flash_CheckStatus(), Flash_ProgramPageStart() .. function return
			 *      -> 3 verified writes, 1 pending
			 *  #4  Wait for Flash_CheckStatus(), Flash_ProgramPageStart()
			 *      Wait for Flash_CheckStatus(), Flash_ProgramPageStart() .. function return
			 *      -> 5 verified writes, 1 pending
			 *  #5  Wait for Flash_CheckStatus(), ...function return
			 *      -> 6 verified writes,
			 */

			uint32 bytesLeftToBeWritten = MIN(Fls_Global.flashWriteInfo.chunkSize, Fls_Global.flashWriteInfo.left);

		    do {
				flashStatus = Flash_CheckStatus(
										Fls_Global.config->FlsInfo,
										(uint32 *) Fls_Global.flashWriteInfo.pDest, /*lint !e923 Intended use */
										Fls_Global.flashWriteInfo.pLeft - Fls_Global.flashWriteInfo.left);

				if (flashStatus == EE_OK) {
				    progressCntr = 0;

					LOG_HEX1("Fls_CS() OK ",Fls_Global.flashWriteInfo.pDest);

					if (Fls_Global.flashWriteInfo.left == 0) {
						/* Done! */
						Fls_Global.jobResultType = MEMIF_JOB_OK;
						Fls_Global.status = MEMIF_IDLE;
						Fls_Global.jobType = FLS_JOB_NONE;
						FEE_JOB_END_NOTIFICATION();
						break;
					}

					/* Write more */
					Fls_Global.flashWriteInfo.pDest = Fls_Global.flashWriteInfo.dest;
					Fls_Global.flashWriteInfo.pLeft = Fls_Global.flashWriteInfo.left;

					/* Double word programming */
					LOG_HEX2("Fls_PP() ",Fls_Global.flashWriteInfo.dest," ", Fls_Global.flashWriteInfo.left);

					flashStatus = Flash_ProgramPageStart(
											Fls_Global.config->FlsInfo,
											&Fls_Global.flashWriteInfo.dest,
											&Fls_Global.flashWriteInfo.source,
											&Fls_Global.flashWriteInfo.left, NULL);
					if (flashStatus != EE_OK) {
						writeFail();
						break;  /*lint !e9011 Better readability this way */
					}
					else {
					    uint32 bytesWritten = Fls_Global.flashWriteInfo.pLeft - Fls_Global.flashWriteInfo.left;
					    bytesLeftToBeWritten = (bytesWritten > bytesLeftToBeWritten) ? 0u : (bytesLeftToBeWritten - bytesWritten);
					}

				} else if (flashStatus == EE_INFO_HVOP_INPROGRESS) {
					/* Wait for it */

				    // One return cycle takes approx ~130 instructions.
				    if (MAX_PROGRESS_CNTR < progressCntr) {
				        progressCntr = 0;
				        writeFail();
				        break; /*lint !e9011 Better readability this way */
				    }

				    progressCntr++;

				} else {
				    progressCntr = 0;
					writeFail();
					/* Nothing to do, quit loop */
					break;  /*lint !e9011 Better readability this way */
				}

			} while (bytesLeftToBeWritten > 0 );

			break;
		}
		case FLS_JOB_NONE:
			assert(FALSE);
			break;

		default:
		    break;
		} /* switch */

	}   /* if */
}
void NetworkConnectorEngine::threadIsDeleted() {
    LOG_STR("NetworkConnectorEngine::threadIsDeleted") ;
}
Esempio n. 23
0
CaDbRecord::~CaDbRecord() {
    LOG_STR("CaDbRecord::~CaDbRecord()") ;
}
void host_mass_storage_task(void)
#endif
{
  uint8_t i;
  uint8_t max_lun;
  uint32_t capacity;
  extern volatile uint8_t device_state;
  uint32_t total_capacity;
  uint8_t status = CTRL_GOOD;

#ifdef FREERTOS_USED
  portTickType xLastWakeTime;

  xLastWakeTime = xTaskGetTickCount();
  while (true)
  {
    vTaskDelayUntil(&xLastWakeTime, configTSK_USB_HMS_PERIOD);

#endif  // FREERTOS_USED
    // First, check the host controller is in full operating mode with the
    // B-device attached and enumerated
    if (Is_host_ready())
    {
      // New device connection (executed only once after device connection)
      if (ms_new_device_connected)
      {
        // For all supported interfaces
        for (i = 0; i < Get_nb_supported_interface(); i++)
        {
          // If mass-storage class
          if (Get_class(i) == MS_CLASS)
          {
            total_capacity = 0;

            // Get correct physical pipes associated with IN/OUT endpoints
            if (Is_ep_in(i, 0))
            { // Yes, associate it with the IN pipe
              g_pipe_ms_in = Get_ep_pipe(i, 0);
              g_pipe_ms_out = Get_ep_pipe(i, 1);
            }
            else
            { // No, invert...
              g_pipe_ms_in = Get_ep_pipe(i, 1);
              g_pipe_ms_out = Get_ep_pipe(i, 0);
            }

            ms_new_device_connected = false;
            ms_connected = true;

            // Get the number of LUNs in the connected mass-storage device
            max_lun = host_get_lun();

            // Initialize all USB drives
            for (host_selected_lun = 0; host_selected_lun < max_lun; host_selected_lun++)
            {
              uint32_t retry;
              if ((status = host_ms_inquiry()) != CTRL_GOOD)
                break;
              if ((status = host_ms_request_sense()) != CTRL_GOOD)
                break;
              for (retry = 0; retry < 3; retry++)
              {
                if ((status = host_test_unit_ready(host_selected_lun)) == CTRL_GOOD)
                {
                  if ((status = host_read_capacity(host_selected_lun, &capacity)) == CTRL_GOOD)
                    total_capacity += capacity;
                  break;
                }
              }
            }
            // If busy then restart
            if (status == CTRL_BUSY || status == CTRL_NO_PRESENT)
            {
              ms_connected = false;
              ms_new_device_connected = true;
              return;
            }
            // If failed then report device not supported
            if (status == CTRL_FAIL)
            {
              device_state = DEVICE_ERROR;
              Host_device_class_not_supported_action();
              ms_connected = false;
              return;
            }

#ifdef AI_MAXIMAL_CAPACITY_SUPPORTED_MB
            if (total_capacity > (AI_MAXIMAL_CAPACITY_SUPPORTED_MB*2*1024))
            {
              device_state = DEVICE_ERROR;
              Host_device_class_not_supported_action();
              ms_connected = false;
              return;
            }
#endif

            LOG_STR(log_ms_dev_connected);

            // Notify the Audio Interface of the new connection
            ai_usb_ms_new_connection();
            break;
          }
        }
      }
    }
#ifdef FREERTOS_USED
  }
#endif
}
Esempio n. 25
0
void host_keyboard_hid_task(void)
#endif
{
  uint8_t i;
  uint8_t max_lun;
  uint32_t capacity;

#ifdef FREERTOS_USED
  portTickType xLastWakeTime;

  xLastWakeTime = xTaskGetTickCount();
  while (true)
  {
    vTaskDelayUntil(&xLastWakeTime, configTSK_USB_HHID_KBD_PERIOD);

#endif  // FREERTOS_USED
    // First, check the host controller is in full operating mode with the
    // B-device attached and enumerated
    if (Is_host_ready())
    {
      // Display Start-of-Frame counter on LEDs
      LED_Display_Field(LED_MONO0_GREEN |
                        LED_MONO1_GREEN |
                        LED_MONO2_GREEN |
                        LED_MONO3_GREEN,
                        sof_cnt >> 5);

      // New device connection (executed only once after device connection)
      if (ms_new_device_connected)
      {
        ms_new_device_connected = false;

        // For all supported interfaces
        for (i = 0; i < Get_nb_supported_interface(); i++)
        {
          // If mass-storage class
          if (Get_class(i) == MS_CLASS)
          {
            ms_connected = true;
            LOG_STR(log_ms_dev_connected);

            // Get correct physical pipes associated with IN/OUT endpoints
            if (Is_ep_in(i, 0))
            { // Yes, associate it with the IN pipe
              g_pipe_ms_in = Get_ep_pipe(i, 0);
              g_pipe_ms_out = Get_ep_pipe(i, 1);
            }
            else
            { // No, invert...
              g_pipe_ms_in = Get_ep_pipe(i, 1);
              g_pipe_ms_out = Get_ep_pipe(i, 0);
            }

            // Get the number of LUNs in the connected mass-storage device
            max_lun = host_get_lun();

            // Initialize all USB drives
            for (host_selected_lun = 0; host_selected_lun < max_lun; host_selected_lun++)
            {
              host_ms_inquiry();
              host_read_capacity(host_selected_lun, &capacity);
              host_ms_request_sense();
              for (i = 0; i < 3; i++)
              {
                if (host_test_unit_ready(host_selected_lun) == CTRL_GOOD)
                {
                  host_read_capacity(host_selected_lun, &capacity);
                  break;
                }
              }
            }
            break;
          }
        }
      }
    }
#ifdef FREERTOS_USED
  }
#endif
}