Esempio n. 1
0
static VALUE method_read_counter(VALUE self, long counter) {
    if (check_connection(self)) {
        counter = NUM2INT(counter);
        if (valid_counter(counter)) {
            long data = ReadCounter(counter);
            data = ReadCounter(counter);    // Reads twice, to get around buffering error
            if (data != -1)
                return INT2NUM(data);
        }
        printf("K8055 returned an error.\n");
        return Qfalse;
    }
}
Esempio n. 2
0
// -------------------------------------------------------------------------
// SUBROUTINE - ReadWet
//
// 'temp'  - The temperature from the DS1820 in F
// 'dir'   - The wind direction from 0-15
// 'revol' - The wind speed in revolutions per second
//
// Returns:  TRUE, if the reads were successfull and FALSE if they were not.
//
int ReadWet(int portnum, WeatherStruct *wet, float *temp, int *dir, double *revol)
{
   int ret = TRUE;
   unsigned long start_count=0, end_count=0, start_time, end_time;
   float current_temp;

   // read the current counter
   // use this reference to calculate wind speed later
   if (!ReadCounter(portnum, &wet->ds2423[0], 15, &start_count))
   {
      printf("\nError reading counter, verify device present:%d\n",
              (int)owVerify(portnum, FALSE));
      ret = FALSE;
   }

   // get a time stamp (mS)
   start_time = msGettick();

   // read the temperature and print in F
   if (ReadTemperature(portnum, &wet->ds1820[0],&current_temp))
      *temp = current_temp * 9 / 5 + 32;
   else
   {
      printf("\nError reading temperature, verify device present:%d\n",
              (int)owVerify(portnum, FALSE));
      ret = FALSE;
   }

   // read the wind direction
   *dir = TrueDir(portnum, wet);

   // read the counter again
   if (!ReadCounter(portnum, &wet->ds2423[0], 15, &end_count))
   {
      printf("Error reading counter, verify device present:%d\n",
              (int)owVerify(portnum, FALSE));
      ret = FALSE;
   }

   // get a time stamp (mS)
   end_time = msGettick();

   // calculate the wind speed based on the revolutions per second
   *revol = (((end_count - start_count) * 1000.0) /
              (end_time - start_time)) / 2.0;

   return ret;
}
void GPUParticleSystem::EmitParticles(ID3D11DeviceContext* deviceContext, float dt)
{
	//Set UAVs
	ID3D11UnorderedAccessView* uavs[] = { particlesUAV, particleDeadListUAV };
	UINT initialCounts[] = { (UINT)-1, (UINT)-1 };
	deviceContext->CSSetUnorderedAccessViews(0, ARRAYSIZE(uavs), uavs, initialCounts);

	ID3D11ShaderResourceView* srvs[] = { randomValuesSRV, piRandomValuesSRV };
	deviceContext->CSSetShaderResources(0, ARRAYSIZE(srvs), srvs);

	//Set compute shader
	deviceContext->CSSetShader(emitParticlesCS, nullptr, 0);
	
	ID3D11Buffer* cBuffers[] = { perFrameVariablesBuffer, particleDeadListConstantBuffer, emitterVariablesBuffer, variancesCB };
	deviceContext->CSSetConstantBuffers(0, 4, cBuffers);

	//Set per frame variables such as dt
	PerFrameVariables PF;
	PF.deltaTime = 0.0f;
	PF.elapsedTime = elapsedTime;
	deviceContext->UpdateSubresource(perFrameVariablesBuffer, 0, NULL, &PF, 0, 0);

	//Passes emitter variables over for each emitter
	for (int i = 0; i < emittersParams.size(); ++i)
	{
		// Update the emitter constant buffer
		D3D11_MAPPED_SUBRESOURCE MappedResource;
		deviceContext->Map(emitterVariablesBuffer, 0, D3D11_MAP_WRITE_DISCARD, 0, &MappedResource);
		EmitterParameters* EP = (EmitterParameters*)MappedResource.pData;
		EP->emitterType = emittersParams[i].emitterType;
		
		//Temporary solution for updating emitter position
		tempEmitterPositions[i].x += emittersParams[i].emitterVelocity.x;
		tempEmitterPositions[i].y += emittersParams[i].emitterVelocity.y;
		tempEmitterPositions[i].z += emittersParams[i].emitterVelocity.z;

		EP->emitterPosition.x = emittersParams[i].emitterPosition.x + tempEmitterPositions[i].x;
		EP->emitterPosition.y = emittersParams[i].emitterPosition.y + tempEmitterPositions[i].y;
		EP->emitterPosition.z = emittersParams[i].emitterPosition.z + tempEmitterPositions[i].z;

		EP->emitterVelocity = emittersParams[i].emitterVelocity;
		EP->numToEmitPerFrame = emittersParams[i].numToEmitPerFrame;
		EP->particlePosition = emittersParams[i].particlePosition;
		EP->particleVelocity = emittersParams[i].particleVelocity;
		EP->particleLife = emittersParams[i].particleLife;
		EP->startSize = emittersParams[i].startSize;
		EP->endSize = emittersParams[i].endSize;
		EP->startColour = emittersParams[i].startColour;
		EP->endColour = emittersParams[i].endColour;
		EP->currentColour = emittersParams[i].currentColour;
		EP->currentSize = emittersParams[i].currentSize;

		//Padding numbers so that it is aligned when passed to the gpu (potentially could be used)
		EP->pad = emittersParams[i].pad;
		EP->pad1 = emittersParams[i].pad1;
		EP->pad2 = emittersParams[i].pad2;
		EP->pad3 = emittersParams[i].pad3;
		EP->pad4 = emittersParams[i].pad4;
		EP->pad5 = emittersParams[i].pad5;
		EP->pad6 = emittersParams[i].pad6;
		EP->pad8 = emittersParams[i].pad8;
		deviceContext->Unmap(emitterVariablesBuffer, 0);

		//Map variances to generate numbers in random range
		deviceContext->Map(variancesCB, 0, D3D11_MAP_WRITE_DISCARD, 0, &MappedResource);
		Variances* V = (Variances*)MappedResource.pData;
		V->positionVariance = emittersVars[i].positionVariance;
		V->velocityVariance = emittersVars[i].velocityVariance;
		//V->lifeVariance = emittersVars[i].lifeVariance;

		V->pad = emittersVars[i].pad;
		V->pad1 = emittersVars[i].pad1;
		deviceContext->Unmap(variancesCB, 0);

		deviceContext->CopyStructureCount(particleDeadListConstantBuffer, 0, particleDeadListUAV);

		//Number of particles to emit per frame
		deviceContext->Dispatch(2, 1, 1);
	}

	//Unbind from CS shader so it can be used as a shader resource
	ID3D11UnorderedAccessView* nullUAV = NULL;
	deviceContext->CSSetUnorderedAccessViews(0, 1, &nullUAV, NULL);

	//counter to show number of particles
	int counter = ReadCounter(particleDeadListUAV);
	particleCounter = counter;
}
Esempio n. 4
0
/*
void ReadEIP(PEIP_RECORD pRecord)
{
	W32 high, low, i, top;

	rdmsr(0x1da, low, high);
	top = low;
	
	for(i = 0; i < MAX_EIP_NUM; i++)
	{
		top = (top+i) % MAX_EIP_NUM;
		rdmsr(0x680+top, low, high);
		pRecord->eipFrom[i] = ((W64)high << 32) | low;
		rdmsr(0x6c0+top, low, high);
		pRecord->eipTo[i] = ((W64)high << 32) | low;
	}	
}
*/
int CollectSampling(void)
{
	int cpuId;
	//W32 low, high; 
	SAMPLE_RECORD record;
	PROFILING_RECORD profiling;
	unsigned long irqFlags;
#ifdef DBG	
	W32 i;
#endif
	W64 *pointer;
	
	//if (counterPackage.eipNum > 0)
	//{
	//stop branch recording
//	rdmsr(0x1d9, low, high);
//	low &= 0xfffffffe;
//	wrmsr(0x1d9, low, high);
	//
	//}	
	
	cpuId = smp_processor_id();
#ifdef DBG
	printk("collect sampling on core %d\n", cpuId);
#endif
	StopCounter(&counterPackage);
	//rdtsc(low, high);
	//record.sampleHeader.rdtsc = (((W64)high)<<32) | low;
	record.sampleHeader.rdtsc = __native_read_tsc();
	record.sampleHeader.sampleId = sampleId;
	record.sampleHeader.cpuId = cpuId;
	ReadCounter(&counterPackage, &record);

	
#ifdef DBG	
	pointer = (W64*)(current->thread.sp0);
	printk("a-------------------------------------------------------------\n");
	for(i = 0; i < 8; i++)
	{
		//eipRecord.eipFrom[i] = (*pointer);
		printk("Addr %p: %p\n", pointer, (*pointer));
		pointer--;
		//eipRecord.eipTo[i] = (*pointer);
		printk("Addr %p: %p\n", pointer, (*pointer));
		pointer--;
	}
	printk("b-------------------------------------------------------------\n");
	//printk("rsp: %p\n",curThread.rsp);
	//printk("rsp0: %p\n",curThread.rsp0);
#endif
	if (counterPackage.profiling > 0)
	{
		pointer = (W64*)(current->thread.sp0);
		profiling.pid = (W64)current->pid;
		pointer -= 5;
		profiling.eip = (*pointer);
/*		if(sampleId == 0)
		{
		printk("cpuId: %d eip: %p\n", cpuId, profiling.eip);
		printk("pid: %u\n", profiling.pid);
		}
*/	}
	
	spin_lock_irqsave(&buffer_lock, irqFlags);
#ifdef DBG
	printk("%d cpu get spinlock and write %d bytes to buffer\n", cpuId, sizeof(SAMPLE_HEADER) + sizeof(W64) * counterPackage.usedNum);
#endif	
	AddSampleToBuff(&record, sizeof(SAMPLE_HEADER) + sizeof(W64) * counterPackage.usedNum);
	if (counterPackage.profiling > 0)
	{
		AddSampleToBuff(&profiling, sizeof(PROFILING_RECORD));
	}

	spin_unlock_irqrestore(&buffer_lock, irqFlags);
	
	//start branch recording
	//rdmsr(0x1d9, low, high);
	//low |= 1;
	//wrmsr(0x1d9, low, high);
	//
#ifdef USE_NMI
    WRITEMSR(INS_FIXED_COUNTER, COUNTER_OVERFLOW);
#endif
	
	StartCounter(&counterPackage);
	return 0;
}
Esempio n. 5
0
int main (int argc,char *params[]) 
{
	int i,result[3];
	unsigned char d=0;
	int a1=0,a2=0;
	unsigned short c1=0, c2=0;
	unsigned long int start,mstart=0,lastcall=0;

	start = time_msec();

	/*
		Load parameters
		If parameters are valid continue
	*/
	
	if (read_param(argc,params)) 
	{
		/*
			Initialise USB system
			and enable debug mode
		
		if ( debug ) 
			usb_set_debug(2);
		*/
		/*
			Search the device
		*/
		if ( OpenDevice(ipid)<0 ) {
			printf("Could not open the k8055 (port:%d)\nPlease ensure that the device is correctly connected.\n",ipid);
			return (-1);
			
		} else {

			if ( resetcnt1 )
				ResetCounter(1);
			if ( resetcnt2 )
				ResetCounter(2);	
			if ( dbt1 != -1 )
				SetCounterDebounceTime(1,dbt1);
				
			if ( dbt2 != -1 )
				SetCounterDebounceTime(2,dbt1);
				
			mstart = time_msec(); // Measure start
			for (i=0; i<numread; i++) {
				
				if ( delay ) {
					// Wait until next measure
					while ( time_msec()-mstart < i*delay );
				} 
				ReadAllAnalog(&a1,&a2);
				d=ReadAllDigital();
				c1=ReadCounter(1);
				c2=ReadCounter(2);
				lastcall = time_msec();
				printf("%d;%d;%d;%d;%d;%d\n", (int)(lastcall-start),d, (int)a1, (int)a2,c1,c2 );
			}
			
			if (debug && ((ia1!=-1)||(ia2!=-1)||(id8!=-1))) printf("Set ");
			if (ia1!=-1){ result[0]=OutputAnalogChannel(1,ia1);
			if (debug) printf("analog1:%d ",result[0]);}
			if (ia2!=-1){ result[1]=OutputAnalogChannel(2,ia2);
			if (debug) printf("analog2:%d ",result[1]);}
			if (id8!=-1){ result[2]=WriteAllDigital((long)id8);
			if (debug) printf("digital:%d",result[2]);}
			if (debug) printf("\n");		

			CloseDevice();
		}
	}
	return 0;
}
Esempio n. 6
0
	///
	/// Verifies material consumption.
	//
	int MaterialMonitorSim::UpdateConsumption(unsigned char ucCartridgeNum, unsigned int uiComsumption, unsigned int *uiNewVolume)
	{
		UniqueLock uniqueLock(m_mtx);

		try
		{
			int returnValue = IDTLIB_SUCCESS;
			if (uiNewVolume == NULL)
			{
				returnValue = CONSUMPTION_NULL_PARAMS;
				LOG_EXT(LEVEL_ERROR, "Invalid parameters (error code 0x" << hex << (short)returnValue << ").");
				return returnValue;
			}

			if (!m_bInitialized)
			{
				returnValue = HW_NOT_INITIALIZED;
				LOG_EXT(LEVEL_ERROR, "Hardware not initialized (error code 0x" << hex << (short)returnValue << ").");
				return returnValue;
			}

			int behaviorReturnValue = GetUpdateConsumptionBehavior(ucCartridgeNum, uiComsumption, uiNewVolume);

			LOG_EXT(LEVEL_INFO, "Cartridge #" << (unsigned short)ucCartridgeNum << " material consumption started...");
			if (!IsCartridgeOn(ucCartridgeNum, m_authenticated) ||
				behaviorReturnValue == CARTRIDGE_NOT_AUTHENTICATED)
			{
				returnValue = CARTRIDGE_NOT_AUTHENTICATED;
				LOG_EXT(LEVEL_ERROR, "Cartridge #"<< (unsigned short)ucCartridgeNum << " not authenticated (error code 0x" << hex << (short)returnValue << ").");
				return returnValue;
			}

			LOG_EXT(LEVEL_INFO, "Switching to cartridge #"<< (unsigned short)ucCartridgeNum << "...");
			if (((m_behavior != NULL) && !IsCartridgeOn(ucCartridgeNum, m_behavior->Status)) ||
				behaviorReturnValue == FCB_SELECT_CHANNEL_FAILED)
			{
				returnValue = FCB_SELECT_CHANNEL_FAILED;
				LOG_EXT(LEVEL_ERROR, "Error switching to cartridge #"<< (unsigned short)ucCartridgeNum << " (error code 0x" << hex << (short)returnValue << ").");
				return returnValue;
			}

			LOG_EXT(LEVEL_INFO, "Getting current volume...");
			returnValue = ReadCounter(ucCartridgeNum, uiNewVolume);
			if (returnValue != IDTLIB_SUCCESS)
			{
				if (returnValue == INVALID_VOLUME_SIGNATURE || behaviorReturnValue == INVALID_VOLUME_SIGNATURE)
				{
					LOG_EXT(LEVEL_ERROR, "Error verifying signature (error code 0x" << hex << (short)returnValue << ").");
				}
				else
				{
					LOG_EXT(LEVEL_ERROR, "Error reading counter (error code 0x" << hex << (short)returnValue << ").");
				}

				return returnValue;
			}

			if (*uiNewVolume < uiComsumption || behaviorReturnValue == MATERIAL_OVERCONSUMPTION)
			{
				returnValue = MATERIAL_OVERCONSUMPTION;
				LOG_EXT(LEVEL_ERROR, "Invalid consumption (error code 0x" << hex << (short)returnValue << ").");
				return returnValue;
			}

			returnValue = behaviorReturnValue;
			if (returnValue == IDTLIB_SUCCESS)
			{
				LOG_EXT(LEVEL_INFO, "Decreasing volume by " << uiComsumption << "...");
				*uiNewVolume -= uiComsumption;
				WriteCounter(ucCartridgeNum, *uiNewVolume);
				LOG_EXT(LEVEL_INFO, "Cartridge #" << (unsigned short)ucCartridgeNum << " material consumption ended successfully. Current volume: " << *uiNewVolume << ".");
			}
			else
			{
				LOG_EXT(LEVEL_ERROR, "Error updating consumption (error code 0x" << hex << (short)returnValue << ").");
			}

			return returnValue;
		}
		catch (exception& e)
		{
			LOG_EXT(LEVEL_ERROR, "Exception caught: " << e.what() << ".");
			return EXCEPTION_CAUGHT;
		}
	}
Esempio n. 7
0
	///
	/// Authenticates cartridge.
	///
	int MaterialMonitorSim::AuthenticateCartridge(unsigned char ucCartridgeNum, const unsigned char *aucPubKS, unsigned char *aucIdd, unsigned short *usIddLength, unsigned int *uiCurrentVolume)
	{
		UniqueLock uniqueLock(m_mtx);

		int returnValue = IDTLIB_SUCCESS;
		if (aucPubKS == NULL && m_pubKS == NULL)
		{
			returnValue = INVALID_HOST_KEY;
			LOG_EXT(LEVEL_ERROR, "Invalid host key (error code 0x" << hex << (short)returnValue << ").");
			return returnValue;
		}

		if (aucIdd == NULL || usIddLength == NULL || uiCurrentVolume == NULL)
		{
			returnValue = AUTHENTICATE_NULL_PARAMS;
			LOG_EXT(LEVEL_ERROR, "Invalid parameters (error code 0x" << hex << (short)returnValue << ").");
			return returnValue;
		}

		if (!m_bInitialized)
		{
			returnValue = HW_NOT_INITIALIZED;
			LOG_EXT(LEVEL_ERROR, "Hardware not initialized (error code 0x" << hex << (short)returnValue << ").");
			return returnValue;
		}

		try
		{
			int behaviorReturnValue = GetAuthenticateCartridgeBehavior(ucCartridgeNum, aucPubKS, aucIdd, usIddLength, uiCurrentVolume);

			LOG_EXT(LEVEL_INFO, "Cartridge #" << (unsigned short)ucCartridgeNum << " authentication started:");
			LOG_EXT(LEVEL_INFO, "Switching to cartridge #"<< (unsigned short)ucCartridgeNum << "...");
			if (((m_behavior != NULL) && !IsCartridgeOn(ucCartridgeNum, m_behavior->Status)) ||
				behaviorReturnValue == FCB_SELECT_CHANNEL_FAILED)
			{
				returnValue = FCB_SELECT_CHANNEL_FAILED;
				LOG_EXT(LEVEL_ERROR, "Error switching to cartridge #"<< (unsigned short)ucCartridgeNum << " (error code 0x" << hex << (short)returnValue << ").");
				return returnValue;
			}

			ResetCartridgeInfo(ucCartridgeNum);

			// read certificate file
			LOG_EXT(LEVEL_INFO, "Getting ID certificate...");
			string sCertificateFileName = GetCartridgeFileName(ucCartridgeNum, CERTIFICATE_FILE);

			FILE *pCertificateFile = fopen(sCertificateFileName.c_str(), "rb");
			if (pCertificateFile == NULL || behaviorReturnValue == INVALID_CERTIFICATE_FILE)
			{
				returnValue = INVALID_CERTIFICATE_FILE;
				LOG_EXT(LEVEL_ERROR, "Error getting ID certificate (error code 0x" << hex << (short)returnValue << ").");
				return returnValue;
			}

			fseek(pCertificateFile , 0 , SEEK_END);
			size_t fileSize = (size_t)ftell(pCertificateFile);
			rewind(pCertificateFile);
			fread(aucIdd, sizeof(unsigned char), fileSize, pCertificateFile);

			IDCertificate idc;
			*usIddLength = (unsigned short)idc.Decode(aucIdd) - SIGNATURE_SIZE;

			ECDSA<EC2N, SHA256>::PublicKey* pubKS;
			if (aucPubKS != NULL)
			{
				pubKS = LoadPublicKey(aucPubKS);
				if (pubKS == NULL)
				{
					return INVALID_HOST_KEY;
				}
			}
			else
			{
				pubKS = m_pubKS;
			}

			if (returnValue == INVALID_HOST_KEY || behaviorReturnValue == INVALID_HOST_KEY)
			{
				returnValue = INVALID_HOST_KEY;
				LOG_EXT(LEVEL_ERROR, "Invalid host key (error code 0x" << hex << (short)returnValue << ").");
				return returnValue;
			}

			// verify signature:
			ECDSA<EC2N, SHA256>::Verifier verifier(*pubKS);
			bool ok;
			try
			{
				ok = verifier.VerifyMessage(aucIdd, *usIddLength, aucIdd + *usIddLength, SIGNATURE_SIZE);
			}
			catch (exception& e)
			{
				LOG_EXT(LEVEL_ERROR, "Error verifying ID certificate (error code 0x" << hex << (short)returnValue << "):" << e.what() << ".");
				ok = false;
			}

			if (!ok || behaviorReturnValue == INVALID_CERTIFICATE_SIGNATURE)
			{
				returnValue = INVALID_CERTIFICATE_SIGNATURE;
				LOG_EXT(LEVEL_ERROR, "Error verifying ID certificate (error code 0x" << hex << (short)returnValue << ").");
				return returnValue;
			}

			// read counter
			returnValue = ReadCounter(ucCartridgeNum, uiCurrentVolume);
			if (returnValue != IDTLIB_SUCCESS)
			{
				if (returnValue == INVALID_VOLUME_SIGNATURE || behaviorReturnValue == INVALID_VOLUME_SIGNATURE)
				{
					LOG_EXT(LEVEL_ERROR, "Error verifying signature (error code 0x" << hex << (short)returnValue << ").");
				}
				else
				{
					LOG_EXT(LEVEL_ERROR, "Error reading counter (error code 0x" << hex << (short)returnValue << ").");
				}

				return returnValue;
			}

			returnValue = behaviorReturnValue;
			if (returnValue == IDTLIB_SUCCESS)
			{
				m_authenticated |= (1 << ucCartridgeNum);
				LOG_EXT(LEVEL_INFO, "Cartridge #" << (unsigned short)ucCartridgeNum << " authentication ended successfully. Current volume: " << *uiCurrentVolume << ".");
			}
			else
			{
				LOG_EXT(LEVEL_ERROR, "Error authenticating cartridge (error code 0x" << hex << (short)returnValue << ").");
			}

			return returnValue;
		}
		catch (exception& e)
		{
			LOG_EXT(LEVEL_ERROR, "Exception caught: " << e.what() << ".");
			return EXCEPTION_CAUGHT;
		}
	}