Exemple #1
0
//
// 	Calculate Echo Pulse width (
//	return: centimeter (CM)
//
uint32_t HCSR04::distance(uint32_t timeout) {
	CTick tick;
	CTimeout to;
	to.reset();

	// trigger
	m_trig = HIGH;
	tick.delay(10); // 10us
	m_trig = LOW;

	// wait echo LOW->HIGH
	while (m_echo != HIGH) {
		if (to.isExpired(timeout))
			return 0;
	}

	// wait echo HIGH->LOW
	tick.reset();
	while (m_echo == HIGH) {
		if (to.isExpired(timeout))
			return 0;
	}

	return (tick.elapsed() * 3432 / 20000); // unit (millimeter)
}
Exemple #2
0
void CFan::run() {
	CTimeout tm;			// time count for RPM
	tm.reset();
	while(isAlive()) {		// check thread alive

		//
		// wait for sense pin trigger (interrupt)
		//
		if ( m_sense.wait(FAN_RPM_TIMEOUT) ) {
			if ( m_sense==LOW ) {	// filter noise (for Falling only)
				//
				// RPM calculate
				//
				m_rpmcount++;
				if ( m_rpmcount>=20 ) {
					// Update RPM every 20 counts, increase this for better RPM resolution,
					// decrease for faster update
					m_rpm = (FAN_RPM_RESOLUTION * 1000 * m_rpmcount) / tm.elapsed();
					tm.reset();
					m_rpmcount = 0;

				} // end of if ( m_rpmcount>=20 )
			}

		} else {
			//
			// timeout
			//
			m_ctrl.dutyCycle(0.0f);	// turn off fan
			m_rpm = 0;
		}
	}
}
Exemple #3
0
//
// iProbe run loop
//
void iProbe::run() {
	CTimeout tm;
	CString  msg;
//	uint32_t m_lstCPU = 0;
	uint32_t m_lstNET = 0;
	while(1) {
		tm.wait(1000);
		tm.reset();
		//
		// Make JSON string
		//
		msg = "{";
		msg += "\"cpu\":";
		msg += map(CThread::getIdleTickCount(), 0, 2000, 0, 100);
		msg += ", \"net\":";
		msg += constrain(OFFSET(CSocket::getRxPackageCount(), m_lstNET, MAX_UINT32), 0, 100);
		msg += ", \"mem\":";
		msg += map(heapAvailableSize(), 0, MAX_USERS_MEMORY, 100, 0);
		msg += "}";

		//
		// Send JSON message to All mail receiver
		//
		CMailBox::post(xMAIL_PROBE, msg.getBuffer());

		//
//		m_lstCPU = CThread::getIdleTickCount();
		m_lstNET = CSocket::getRxPackageCount();
	}
}
Exemple #4
0
// ============================ MEMBER FUNCTIONS ===============================
CTimeout* CTimeout::NewL(MTimeoutObserver* aObserver, TInt aPriority)
    {
    CTimeout* self = new (ELeave) CTimeout(aObserver, aPriority);
    CleanupStack::PushL(self);
    self->ConstructL();
    CleanupStack::Pop();
    return self;
    }
Exemple #5
0
//
// Main Routine
//
int main(void) {
#ifdef DEBUG
	CSerial ser;		// declare a UART object
	ser.enable();
	CDebug dbg(ser);	// Debug stream use the UART object
	dbg.start();
#endif

	//
	// PWM (Using Timer1)
	//
	hwPWM pwm1(TIMER_1, 5, 6, 7);	// set pwm1 pins on P0.5 (CH1), P0.6 (CH2) and P0.7 (CH3)
	pwm1.period(0.0002);			// period time = 200us
	pwm1.enable();					// enable PWM module

	// update pwm2 channels duty-cycle (can be updated in any-time)
	pwm1.dutycycle(PWM_CH_1, 0.8f);	// CH1 duty-cycle = 80%
	pwm1.dutycycle(PWM_CH_2, 0.6f);	// CH2 duty-cycle = 60%
	pwm1.dutycycle(PWM_CH_3, 0.2f);	// CH3 duty-cycle = 20%

	//
	// PWM (Using Timer2)
	//
	hwPWM pwm2(TIMER_2, LED_PIN_1, LED_PIN_2);		// set pwm2 pins on LED1 (CH1) and LED2
	pwm2.period(0.0005);			// period time = 500us
	pwm2.enable();					// enable PWM module

	// update pwm2 channels duty-cycle (can be updated in any-time)
	pwm2.dutycycle(PWM_CH_1, 0.8f);	// CH1 duty-cycle = 80%
	pwm2.dutycycle(PWM_CH_2, 0.1f);	// CH2 duty-cycle = 10%

	//
	// LED
	//
	CPin led(LED_PIN_0);
	led.output();

	CTimeout tmLED;
	//
    // Enter main loop.
	//
    while(1) {
    	//
    	// FireFly loop
    	//
    	if ( tmLED.isExpired(500) ) {
    		tmLED.reset();
    		led.toggle();
    	}

    }
}
Exemple #6
0
//
// Main Routine
//
int main(void) {
#ifdef DEBUG
	CSerial ser;		// declare a UART object
	ser.enable();
	CDebug dbg(ser);	// Debug stream use the UART object
	dbg.start();
#endif

	//
	// Optional: Enable tickless technology
	//
#ifndef DEBUG
	CPowerSave::tickless(true);
#endif

	//
	// Your setup code here
	//
	CButton btn(BUTTON_PIN_0);

	CBuzzer buz(15);	// buzzer on P0.15
	buz.enable();

	CPin led(LED_PIN_0);
	led.output();

	CTimeout tmLED;

	//
    // Enter main loop.
	//
    while(1) {
    	//
    	// Your loop code here
    	//
    	switch(btn.isPressed()) {
    	case BTN_PRESSED:
    		buz.post(3);	// turn on buzzer x 3
    		break;
    	case BTN_RELEASED:
    		break;
    	case BTN_NOTHING:
    		break;
    	}

    	if ( tmLED.isExpired(500) ) {
    		tmLED.reset();
    		led.toggle();
    	}
    }
}
Exemple #7
0
void SNetStorageObjectRPC::SetExpiration(const CTimeout& ttl)
{
    if (m_State != eReady) {
        NCBI_THROW_FMT(CNetStorageException, eInvalidArg,
                "Cannot set expiration while reading or writing");
    }

    CJsonNode request(x_MkRequest("SETEXPTIME"));

    if (ttl.IsFinite()) {
        request.SetString("TTL", ttl.GetAsTimeSpan().AsString("dTh:m:s"));
    } else {
        request.SetString("TTL", "infinity");
    }

    ExchangeUsingOwnService(request);
}
Exemple #8
0
uint32_t pulseIn(int pin, PIN_LEVEL_T value, uint32_t timeout) {
	CPin p(unoPIN[pin]);
	p.input();
	CTick    tick;
	CTimeout to;

	to.reset();
	while( p!=value ) {
		if ( timeout && to.isExpired(timeout) ) return 0;
	}
	tick.reset();

	while( p==value ) {
		if ( timeout && to.isExpired(timeout) ) return 0;
	}
	return tick.elapsed();
}
Exemple #9
0
/* ==============================================
 main task routine
 ============================================== */
int main(void) {
	pool_memadd((uint32_t) pool, sizeof(pool));

#ifdef DEBUG
	dbg.start();
#endif

	eMBErrorCode eStatus;
//	dbg.waitToDebugMode();

#if MB_TCP_ENABLED == 1
	eStatus = eMBTCPInit( MB_TCP_PORT_USE_DEFAULT );
#endif

	if (eStatus != MB_ENOERR)
		dbg.println("can't initialize modbus stack!");

	/* Enable the Modbus Protocol Stack. */
	eStatus = eMBEnable();
	if (eStatus != MB_ENOERR)
		dbg.println("can't enable modbus stack!");

	// Initialise some registers
	usRegInputBuf[1] = 0x1234;
	usRegInputBuf[2] = 0x5678;
	usRegInputBuf[3] = 0x9abc;

	// debug LED
	CPin led(LED1);
	CTimeout tm;

	// Enter an endless loop
	while (1) {
		if ( tm.read()>0.5 ) {
			led = !led;
			tm.reset();
		}

	    eStatus = eMBPoll(  );

	    /* Here we simply count the number of poll cycles. */
	    usRegInputBuf[0]++;
	}
	return 0;
}
Exemple #10
0
void CButtons::run() {
	CTimeout tm;
	uint32_t newval;
	while(1) {
		newval = m_pins;
		if ( newval != m_flag ) {
			if ( tm.isExpired(10) ) {						// wait for bounce time
				m_down = newval;
				for (int i=0; i<m_pins.count(); i++) {
					if ( bit_chk((m_flag ^ newval), i)  ) {	// is different? Key Even caused...
						if ( bit_chk(newval, i) ) { 		// HIGH is key up
							onKeyUp(i);
						} else {							// LOW is key down
							onKeyDown(i);
						}
					}
				}
				m_flag = newval;
			}
		} else {
			tm.reset();
		}
	}
}
Exemple #11
0
void CButton::run() {
	CTimeout bounce;
	while(1) {
		if ( bit_chk(m_flag, KEY_FLAG_DOWN) ) {
			if ( m_pin==HIGH ){
				if ( bounce.isExpired(10)  ) {
					bit_clr(m_flag, KEY_FLAG_DOWN);
					onKeyUp();		// call virtual function "onKeyUp()"
				}
			} else {
				bounce.reset();
			}
		} else {
			if ( m_pin==LOW ){
				if ( bounce.isExpired(5)  ) {
					bit_set(m_flag, KEY_FLAG_DOWN);
					onKeyDown();	// call virtual function "onKeyDown()"
				}
			} else {
				bounce.reset();
			}
		}
	}
}
TVerdict CIPEventNotifier1Step_ReceiveMFlag::doTestStepL()
	{
    SetTestStepResult(EFail);	
              
    _LIT(KReadingConfig,"CIPEventNotifier1Step_ReceiveMFlag::doTestStepL() reading config..");
	INFO_PRINTF1(KReadingConfig);
	if(!GetBoolFromConfig(ConfigSection(),KTe_IPENMFlagExpectedResultBool,iExpectedMFlagValue) ||
	   !GetStringFromConfig(ConfigSection(),KTe_IPENNetworkInterfacePrefixToMonitor, iNetworkInterfacePrefixToMonitor))
	    {
		User::Leave(KErrNotFound);
		}
		
	_LIT(KShowSettings,"The expected M flag is %d, on 1st interface starting with %S");
	INFO_PRINTF3(KShowSettings,iExpectedMFlagValue,&iNetworkInterfacePrefixToMonitor);
						


	_LIT(KGetIfName,"Getting full interface name..");
	INFO_PRINTF1(KGetIfName);
	TName fullName = GetFullInterfaceNameL(iNetworkInterfacePrefixToMonitor);
	_LIT(KDeclEv,"OK. declaring event..");
	INFO_PRINTF1(KDeclEv);
	NetSubscribe::TEvent event( this, SignalHandler );
	_LIT(KSubscribing,"OK. Subscribing..");
	INFO_PRINTF1(KSubscribing);
	CDhcpSignal::SubscribeL( fullName, IPEvent::EMFlagReceived, event );
	_LIT(KOkWaiting,"OK. Waiting for M flag..");
	INFO_PRINTF1(KOkWaiting);


	CTimeout *timeout = CTimeout::NewLC(this);

	// a Router Advertisement is set to go out every 3 seconds on the test network
	//
	timeout->After(KFiveSecondDelayToCatchRouterAdvertisementEveryThreeSeconds);

	TRAPD(res,CActiveScheduler::Start())
	if(res != KErrNone)
		{
		if(res == KErrTimedOut)
			{
			_LIT(KTimedOut,"Timed out! Subscriber isn't working or network isn't publishing Router Advertisements");
			INFO_PRINTF1(KTimedOut);
			}
		else
			{
			_LIT(KUnexpectedErrCode,"Received unexpected error code: %d");
			INFO_PRINTF2(KUnexpectedErrCode,res);
			}
		SetTestStepResult(EFail);
		}
	
	_LIT(KOkTidyingUp,"OK. Tidying up..");
	INFO_PRINTF1(KOkTidyingUp);

	timeout->Cancel();
	CleanupStack::PopAndDestroy(timeout);
	if (iQuery && iQuery->iHandle)
		{
		CDhcpSignal::UnsubscribeL( event );
		}

	_LIT(KOkDone,"OK. Done.");
	INFO_PRINTF1(KOkDone);
	return TestStepResult();
	}
TVerdict CIPEventNotifier3Step_LinkLocalAddress::doTestStepL()
	{
    SetTestStepResult(EFail);
              
    _LIT(KReadingConfig,"CIPEventNotifier3Step_LinkLocalAddress::doTestStepL() reading config..");
	INFO_PRINTF1(KReadingConfig);
	TPtrC llAddr;
	if(!GetStringFromConfig(ConfigSection(),KTe_IPENAddressToPush, llAddr) ||
	   !GetStringFromConfig(ConfigSection(),KTe_IPENNetworkInterfacePrefixToMonitor, iNetworkInterfacePrefixToMonitor))
	   	{
		User::Leave(KErrNotFound);
		}
		
	_LIT(KAddrToPush,"The address to be pushed is %S");
	INFO_PRINTF2(KAddrToPush, &llAddr);

		
	if ( iLLAddr.Input(llAddr) != KErrNone )
		{
		_LIT(KUnparsable,"Unparsable address in config!");
		INFO_PRINTF1(KUnparsable);
		User::Leave(KErrArgument);
		}

	if(iLLAddr.IsLinkLocal() == false)
		{
		_LIT(KSpecifyLLAddr,"Please specify a linklocal address in config file! (169.254.x.x or fe80:...)!");
		INFO_PRINTF1(KSpecifyLLAddr);
		User::Leave(KErrArgument);
		}


	_LIT(KSubscribing,"Subscribing..");
	INFO_PRINTF1(KSubscribing);
	TName fullName = GetFullInterfaceNameL(iNetworkInterfacePrefixToMonitor);
	NetSubscribe::TEvent event( this, SignalHandler );
	CDhcpSignal::SubscribeL( fullName, IPEvent::ELinklocalAddressKnown,event );
	_LIT(KGettingDetails,"OK. Getting interface details..");
	INFO_PRINTF1(KGettingDetails);


	// Now push the address.. Once we start the scheduler, the subscriber
	//  should pick it up immediately!

	TPckgBuf<TSoInet6InterfaceInfo> originalCfg;

	const TSoInet6InterfaceInfo& originalCfgRef = originalCfg(); (void)originalCfgRef; // for debugging

	GetInterfaceInfoL(fullName,originalCfg);
	
	_LIT(KAddingLL,"OK. Adding a linklocal address..");
	INFO_PRINTF1(KAddingLL);
	
	TInt err;

	TPckgBuf<TSoInet6InterfaceInfo> addConfig(originalCfg());
	
    addConfig().iState    = EIfUp;
    addConfig().iDoState  = ETrue;
    addConfig().iDoId     = ETrue;
    addConfig().iDoPrefix = ETrue;
    addConfig().iAlias    = ETrue; // add another address
    addConfig().iDelete   = EFalse;
	addConfig().iDoAnycast= EFalse;
	addConfig().iDoProxy  = EFalse;
    addConfig().iAddress  = iLLAddr;
	addConfig().iAddress.SetScope(2);

	err = iSocket->SetOpt(KSoInetConfigInterface, KSolInetIfCtrl, addConfig);
	User::LeaveIfError(err);


	_LIT(KWaitingForNotification,"OK. Waiting for notification..");
	INFO_PRINTF1(KWaitingForNotification);
	

	CTimeout* timeout = CTimeout::NewLC(this);

	timeout->After(KTenSecondDADCompletionDelay);

	TRAPD(res,CActiveScheduler::Start())
	if(res != KErrNone)
		{
		if(res == KErrTimedOut)
			{
			_LIT(KTimedOut,"Timed out! Subscriber isn't working");
			INFO_PRINTF1(KTimedOut);
			}
		else
			{
			_LIT(KUnexpectedErrCode,"Received unexpected error code: %d");
			INFO_PRINTF2(KUnexpectedErrCode,res);
			}
		return TestStepResult();
		}


	_LIT(KRestoringAddress,"OK. Removing the address..");
	INFO_PRINTF1(KRestoringAddress);
	
	addConfig().iDelete = ETrue;
	err = iSocket->SetOpt(KSoInetConfigInterface, KSolInetIfCtrl, addConfig);
	User::LeaveIfError(err);

	
	_LIT(KRestoredOk,"Restored OK. Clearing up..");
	INFO_PRINTF1(KRestoredOk);

	
	timeout->Cancel();
	CleanupStack::PopAndDestroy(timeout);
	if (iQuery && iQuery->iHandle)
		{
		CDhcpSignal::UnsubscribeL( event );
		}

	_LIT(KOkDone,"OK. Done.");
	INFO_PRINTF1(KOkDone);
	return TestStepResult();
	}
void CInterProcessLock::Lock(const CTimeout& timeout,
                             const CTimeout& granularity)
{
    CFastMutexGuard LOCK(s_ProcessLock);

    // Check that lock with specified name not already locked
    // in the current process.
    TLocks::iterator it = s_Locks->find(m_SystemName);

    if (m_Handle != kInvalidLockHandle) {
        // The lock is already set in this CInterProcessLock object,
        // just increase reference counter.
        _VERIFY(it != s_Locks->end());
        it->second++;
        return;
    } else {
        if (it != s_Locks->end()) {
            // The lock already exists in the current process.
            // We can use one CInterProcessLock object with
            // multiple Lock() calls, but not with different
            // CInterProcessLock objects. For example, on MS-Windows,
            // we cannot wait on the same mutex in the same thread.
            // So, two different objects can set locks simultaneously.
            // And for OS-compatibility we can do nothing here,
            // except throwing an exception.
            NCBI_THROW(CInterProcessLockException, eMultipleLocks,
                       "Attempt to lock already locked object " \
                       "in the same process");
        }
    }

    // Try to acquire a lock with specified timeout

#if defined(NCBI_OS_UNIX)

    // Open lock file
    mode_t perm = CDirEntry::MakeModeT(
        CDirEntry::fRead | CDirEntry::fWrite /* user */,
        CDirEntry::fRead | CDirEntry::fWrite /* group */,
        0, 0 /* other & special */);
    int fd = open(m_SystemName.c_str(), O_CREAT | O_RDWR, perm);
    if (fd == -1) {
        NCBI_THROW(CInterProcessLockException, eCreateError,
                   string("Error creating lockfile ") + m_SystemName + 
                   ": " + strerror(errno));
    }

    // Try to acquire the lock
    
    int x_errno = 0;
    
    if (timeout.IsInfinite()  ||  timeout.IsDefault()) {
        while ((x_errno = s_UnixLock(fd))) {
            if (errno != EAGAIN)
                break;
        }

    } else {
        unsigned long ms = timeout.GetAsMilliSeconds();
        if ( !ms ) {
            // Timeout == 0
            x_errno = s_UnixLock(fd);
        } else {
            // Timeout > 0
            unsigned long ms_gran;
            if ( granularity.IsInfinite()  ||
                 granularity.IsDefault() ) 
            {
                ms_gran = min(ms/5, (unsigned long)500);
            } else {
                ms_gran = granularity.GetAsMilliSeconds();
            }
            // Try to lock within specified timeout
            for (;;) {
                x_errno = s_UnixLock(fd);
                if ( !x_errno ) {
                    // Successfully locked
                    break;
                }
                if (x_errno != EACCES  &&
                    x_errno != EAGAIN ) {
                    // Error
                    break;
                }
                // Otherwise -- sleep granularity timeout
                unsigned long ms_sleep = ms_gran;
                if (ms_sleep > ms) {
                    ms_sleep = ms;
                }
                if ( !ms_sleep ) {
                     break;
                }
                SleepMilliSec(ms_sleep);
                ms -= ms_sleep;
            }
            // Timeout
            if ( !ms ) {
                close(fd);
                NCBI_THROW(CInterProcessLockException, eLockTimeout,
                           "The lock could not be acquired in the time " \
                           "allotted");
            }
        } // if (!ms)
    } // if (timeout.IsInfinite())
    
    // Error
    if ( x_errno ) {
        close(fd);
        NCBI_THROW(CInterProcessLockException, eLockError,
                   "Error creating lock");
    }
    // Success
    m_Handle = fd;

#elif defined(NCBI_OS_MSWIN)

    HANDLE  handle  = ::CreateMutex(NULL, TRUE, _T_XCSTRING(m_SystemName));
    errno_t errcode = ::GetLastError();
    if (handle == kInvalidLockHandle) {
        switch(errcode) {
            case ERROR_ACCESS_DENIED:
                // Mutex with specified name already exists, 
                // but we don't have enough rights to open it.
                NCBI_THROW(CInterProcessLockException, eLockError,
                           "The lock already exists");
                break;
            case ERROR_INVALID_HANDLE:
                // Some system object with the same name already exists
                NCBI_THROW(CInterProcessLockException, eLockError,
                           "Error creating lock, system object with the same" \
                           "name already exists");
                break;
            default:
                // Unknown error
                NCBI_THROW(CInterProcessLockException, eCreateError,
                           "Error creating lock");
                break;
        }
    } else {
        // Mutex with specified name already exists
        if (errcode == ERROR_ALREADY_EXISTS) {
            // Wait
            DWORD res;
            if (timeout.IsInfinite()  ||  timeout.IsDefault()) {
                res = WaitForSingleObject(handle, INFINITE);
            } else {
                res = WaitForSingleObject(handle, timeout.GetAsMilliSeconds());
            }
            switch(res) {
                case WAIT_OBJECT_0:
                    // The lock has been acquired
                    break;
                case WAIT_TIMEOUT:
                    ::CloseHandle(handle);
                    NCBI_THROW(CInterProcessLockException, eLockTimeout,
                               "The lock could not be acquired in the time " \
                               "allotted");
                    break;
                case WAIT_ABANDONED:
                    // The lock is in abandoned state... Other thread/process
                    // owning it was terminated. We can reuse this mutex, but 
                    // it is better to wait until it will be released by OS.
                    /* FALLTHRU */
                default:
                    ::CloseHandle(handle);
                    NCBI_THROW(CInterProcessLockException, eLockError,
                               "Error creating lock");
                    break;
            }
        }
        m_Handle = handle;
    }
#endif
    // Set reference counter to 1
    (*s_Locks)[m_SystemName] = 1;
}