Writing testcase to confirm counter signal values in CAPL - capl

I am writing a basic CAPL test to check if a message counter is counting correctly with each cycle. I am trying the test case in simulated bus now, however whenever I check for the counter signal value using write() function I always get '0'and the signal value check always fails inside the loop. Why can't I see the signal updating in my testmodule at all although in the trace and the graphics it's updating correctly?
Here's the test module code below:
variables
{
float counter1AB;
int values [257];
int count;
long result;
long cntResult;
}
void MainTest()
{
//ChkConfig_Init("user");
TestModuleTitle ("Cyclic time & Process counter check");
TestModuleDescription ("Check the value of messages process counter is changing correctly.");
TestModuleDescription ("Message ID Tested: 0x1AB");
TestModuleDescription ("separate test cases.");
TestGroupBegin("message 0x1AB", "Check the process counter values for message 0x1AB");
TC_MSg_1AB_first_value();
write("signal value is %d", $Sig_cnt);
testGroupEnd();
}
testcase TC_MSg_1AB_first_value()
{
counter1AB=0;
//check message 1AB recieved
result = TestWaitForMessage(Av_VdsToSte1Scnd, 10000);
cntResult = checkSignalMatch(Sig_cnt,counter1AB);
if (result > 0){
testStepPass("1.1","Message 0x1AB recieved for first time");
}
else{
testStepFail("1.1","Message 0x1AB wasn't recieved for first time");
}
if (cntResult > 0){
testStepPass("1.2","Message 0x1AB recieved with counter = %d ",counter1AB);
}
else{
testStepFail("1.2","Message 0x1AB recieved with incorrect counter");
}
//check that we have 255 subsequent transmissions afterwards
for (count=0; count < 255; count++){
result = TestWaitForMessage(0x1AB, 53);
cntResult = checkSignalMatch(Sig_cnt,count+1);
if (result > 0){
testStepPass("1. %d","Message 0x1AB received for the %d th time",count+3,count+2);
}
else{
testStepFail("1.%d","Message 0x1AB wasn't received for the %d th time",count+3,count+2);
}
if (cntResult > 0){
testStepPass("1.%d","Message 0x1AB received with counter = %d ", /*count+4,*/ count+1);
// write("signal value is %d", $Sig_cnt);
}
else{
testStepFail("1.%d","Message 0x1AB received with incorrect counter", count+4);
//write("ExpectedValue= %d",count +1);
}
}
write("signal value is %d", $Sig_cnt);

Related

Generate key for security access using dll file CANOE CAPL

I am trying to generate a key from a seed sent by an ECU using DiagStartGenerateKeyFromSeed but I get a result "buffer too small"
on diagResponse ECU.SecurityAccess_Process
{
long result ;
result = diagGetParameterRaw (this, "securitySeed", gSeedArray, elcount(gSeedArray));
if (result == 0 )
{
write("Seed is (hex) %X %X %X",gSeedArray[0],gSeedArray[1],gSeedArray[2]);
result=DiagStartGenerateKeyFromSeed("ECU",gSeedArray,elcount(gSeedArray),1,"Common","");
if (result == 0)
{
write(" Key computation for security Level 1 was started ") ;
}
else
{
write("Error code %ld during key calculation",result);
if(result==-84)
write("invalid security level");
if(result==-86)
write("buffer too small");
}
}
else
{
write("Could not retrieve parameter");
}
}
Diag_GenerateKeyResult( long result, BYTE computedKey[])
{
int i;
long ret;
char keyBuffer[3], stringBuffer[10];
if(result==0) // if key has been calculated
{
write("callback started ");
// To output the key in one line, a composite string has to be build
snprintf(stringBuffer, elCount(stringBuffer),""); // Clear the string buffer
strncat(stringBuffer, "Key is (hex): ",
elCount(stringBuffer)); // Begin to build composite string
for(i=0;i<elCount(computedKey);i++)
{
snprintf(keyBuffer, elCount(keyBuffer), "%02X ",
computedKey[i]); // Print current key byte into key buffer
strncat(stringBuffer, keyBuffer,
elCount(stringBuffer)); // Add current key byte to the string buffer
}
write(stringBuffer); // Output the string buffer (the key) in one line
}
else
{
write("Error code %ld during key calculation",result);
if(result==-84)
write("invalid security level");
if(result==-86)
write("buffer too small");
}
}
The event OndiagResponse if active once the ECU send the seed
the call back function _Diag_GenerateKeyResult, the DiagStartGenerateKeyFromSeed is correctly working I get " Key computation for security Level 1 was started "

Filtering return on serial port

I have a CO2 sensor on my Arduino Mega and sometimes randomly when I'm reading the CO2 measurement, the sensor will return a "?". The question mark causes my program to crash and return "input string was not in a correct format".
I haven't tried anything because I don't know what approach would be the best for this. The CO2 sensor returns the measurement in the form of "Z 00000" but when this question mark appears it shows that all that returned was a "\n". Currently, I have the program just reading the 5 digits after the Z.
if (returnString != "")
{
val = Convert.ToDouble(returnString.Substring(returnString.LastIndexOf('Z')+ 1));
}
What I expect to return is the digits after Z which works but every so often I will get a random line return which crashes everything.
According to the C# documentation the ToDouble method throws FormatException whenever the input string is invalid. You should catch the exception to avoid further issues.
try {
val = Convert.ToDouble(returnString.Substring(returnString.LastIndexOf('Z')+ 1));
}
catch(FormatException e) {
//If you want to do anything in case of an error
//Otherwise you can leave it blank
}
Also I'd recommend using some sort of statemachine for parsing the data in your case, that could discard all invalid characters. Something like this:
bool z_received = false;
int digits = 0;
int value = 0;
//Called whenever you receive a byte from the serial port
void onCharacter(char input) {
if(input == 'Z') {
z_received = true;
}
else if(z_received && input <= '9' && input >= '0') {
value *= 10;
value += (input - '0');
digits++;
if(digits == 5) {
onData(value);
value = 0;
z_received = false;
digits = 0;
}
}
else {
value = 0;
z_received = false;
digits = 0;
}
}
void onData(int data) {
//do something with the data
}
This is just a mock-up, should work in your case if you can direct the COM port's byte stream into the onCharacter function.

Distance edit array output

I am doing an edit distance with the user input. I am storing my values in array. then the edit distance will compare the user input with my array of strings. I am doing a loop that if the edit distance is more than 2 it will display invalid else valid.
The only problem I've got is that although the program is working out fine, the output is the result of all the '28' strings that I have in my array. I would like to display only invalid or valid once.
Test is my array of strings and user is - String user - the user input.
void testingLD()
{
for (int i=0; i<test.length; i++)
{
if(getLevenshteinDistance(test[i],user) > 2)
{
println ("Invalid re-input");
}
else
{
println ("Valid");
}
}
}
You have your print line functions inside your loop so they get printed once per iteration.
Try this.
void testingLD()
{
boolean isValid = true; // assume true, check each and update
// begin loop
for (int i=0; i<test.length; i++)
{
if(getLevenshteinDistance(test[i],user) > 2)
{
isValid = false;
break; // don't need to test the rest of the loop if we already found a false
}
}
// end loop
if(isValid){
println("Valid");
}else{
println("Invalid re-input");
}
}
Similarly you could count the number of valid int validCount = 0; validCount++ and then display stats about how many were valid, the percentage etc. Or keep an array of the invalid strings and display those as the ones that fail etc!
Wrap up:
When you want to check an entire collection or array for some condition and output one answer make sure to have your output outside of the loop!

libusb data transfer

Hii I have to make a code to read data from usb drive which can be pendrive and later a data acquisition card . i have written this much of code which detects all usb connection n print their info. Altough i don't know how to proceed further . I m also confused as to reading data from say pendrive means as in opening some files or what? Please also tell how to find endpoint of device currently i'm jsut using hit n trial to find it .
PLEASE help me out .I have read whole documentation on synchronous and asynchronous I/O.
enter code here
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <libusb-1.0/libusb.h>
//=========================================================================
// This program detects usb and print out their details
//=========================================================================
int main (int argc, char *argv)
{
libusb_device **devList = NULL;
libusb_device *devPtr = NULL;
libusb_device_handle *devHandle = NULL;
libusb_context *ctx = NULL; //a libusb session
struct libusb_device_descriptor devDesc;
unsigned char strDesc[256];
ssize_t numUsbDevs = 0; // pre-initialized scalars
ssize_t idx = 0;
int retVal = 0;
//========================================================================
// test out the libusb functions
//========================================================================
printf ("*************************\n USB Detection Program:\n*************************\n");
retVal = libusb_init (&ctx);
if(retVal < 0) {
printf ("%d",retVal," Init Error "); //there was an error
return 1;
}
//========================================================================
// Get the list of USB devices visible to the system.
//========================================================================
numUsbDevs = libusb_get_device_list (ctx, &devList);
//========================================================================
// Loop through the list, looking for the device
//========================================================================
while (idx < numUsbDevs)
{
printf ("\n\n[%d]\n", idx+1);
//=====================================================================
// Get next device pointer out of the list, use it to open the device.
//=====================================================================
devPtr = devList[idx];
retVal = libusb_open (devPtr, &devHandle);
if (retVal != LIBUSB_SUCCESS)
break;
//=====================================================================
// Get the device descriptor for this device.
//=====================================================================
retVal = libusb_get_device_descriptor (devPtr, &devDesc);
if (retVal != LIBUSB_SUCCESS)
break;
//=====================================================================
// Get the string associated with iManufacturer index.
//=====================================================================
printf ("iManufacturer = %d", devDesc.iManufacturer);
if (devDesc.iManufacturer > 0)
{
retVal = libusb_get_string_descriptor_ascii
(devHandle, devDesc.iManufacturer, strDesc, 256);
if (retVal < 0)
break;
printf (" string = %s", strDesc);
}
//========================================================================
// Get string associated with iProduct index.
//========================================================================
printf (" \niProduct = %d", devDesc.iProduct);
if (devDesc.iProduct > 0)
{
retVal = libusb_get_string_descriptor_ascii
(devHandle, devDesc.iProduct, strDesc, 256);
if (retVal < 0)
break;
printf (" string = %s", strDesc);
}
//==================================================================
// Get string associated with iSerialNumber index.
//==================================================================
printf (" \niSerialNumber = %d", devDesc.iSerialNumber);
if (devDesc.iSerialNumber > 0)
{
retVal = libusb_get_string_descriptor_ascii
(devHandle, devDesc.iSerialNumber, strDesc, 256);
if (retVal < 0)
break;
printf (" string = %s", strDesc);
}
//==================================================================
// Print product id and Vendor id
//==================================================================
printf (" \nProductid = %d", devDesc.idProduct);
printf (" \nVendorid = %d", devDesc.idVendor);
//========================================================================
// Close and try next one.
//========================================================================
libusb_close (devHandle);
devHandle = NULL;
idx++;
//========================================================================
// Selection of device by user
//========================================================================
if(idx==numUsbDevs)
{ printf("\n\nselect the device : ");
scanf("%d",&idx);
if(idx > numUsbDevs)
{printf("Invalid input, Quitting.............");
break; }
devPtr = devList[idx-1];
retVal = libusb_open (devPtr, &devHandle);
if (retVal != LIBUSB_SUCCESS)
break;
retVal = libusb_get_device_descriptor (devPtr, &devDesc);
if (retVal != LIBUSB_SUCCESS)
break;
printf (" \nProductid = %d", devDesc.idProduct);
printf (" \nVendorid = %d", devDesc.idVendor);
unsigned char data[4] ; //data to read
//data[0]='a';data[1]='b';data[2]='c';data[3]='d'; //some dummy values
int r; //for return values
r = libusb_claim_interface(devHandle, 1); //claim interface 0 (the first) of device
if(r < 0) {
printf("\nCannot Claim Interface");
return 1;
}
printf("\nClaimed Interface");
int actual_length; //used to find out how many bytes were written
r = libusb_bulk_transfer(devHandle,LIBUSB_ENDPOINT_IN, data, 2, &actual_length, 0);
if (r == 0 && actual_length == sizeof(data)) {
// results of the transaction can now be found in the data buffer
// parse them here and report button press
}
else {
error();
}
r = libusb_release_interface(devHandle, 1); //release the claimed interface
if(r!=0) {
printf("\nCannot Release Interface");
return 1;
}
printf("\nReleased Interface");
idx=numUsbDevs +2;
}
} // end of while loop
if (devHandle != NULL)
{
//========================================================================
// Close device if left open due to break out of loop on error.
//========================================================================
libusb_close (devHandle);
}
libusb_exit (ctx); //close the session
printf ("\n*************************\n Done\n*************************\n");
return 0;
}
//==========================================
// EOF
//====================

Receiving order of socket

I am using socket to send data from local machine to remote in TCP, stream mode.
The code in the local side is :
// ----------- Local
send(sd, pData, iSize, 0); // send data
The size of the data is about 1Mb, so socket might divide it to several packets.
While I am recieving the data on remote side, I have to recieve the data separately, and then combine them together.
The code in the remote side is :
// ----------- Remote : Receiving data
int iSizeThis(0);// size of a single separated data
static int iSizeAcc(0);//size of the total data I have already got.
static int iDataSize(0);// size of the original data.
// Get size
if (iDataSize <= 0)
{
if ( (iSizeThis = recv(cli_sd, (char*)&iDataSize, 4, MSG_PEEK)) == 0) {
....
} else if (iSizeThis == SOCKET_ERROR) {
....
} else {
// Allocates memory
if (iDataSize > 0)
pData = realloc(pData, iDataSize);
}
} else if (iSizeAcc < iDataSize){
// Get data.
// The size of the data is about 1Mb, so socket will divide it to several packets.
// I have to recieve the data separately, and then combine them together.
iSizeThis = recv(cli_sd, ((char*)pData) + iSizeAcc, iDataSize - iSizeAcc, 0);
iSizeAcc += iSizeThis;
//{// If I uncomment this block, the recieving order will be reversed. Why?????
// static int i(0);
// std::ostringstream oss;
// oss << i++ << "\n\n";
// oss << "iSizeThis : " << iSizeThis << "\n";
// oss << "iSizeAcc : " << iSizeAcc << "\n";
// oss << "iDataSize : " << iDataSize << "\n";
// ::MessageBoxA(this->GetSafeHwnd(), oss.str().c_str(), "---", 0);
//}
// If all the fragment are combined into pData, the save it to a file.
if (iSizeAcc >= iDataSize){
// Save to file
FILE * pFile;
pFile = fopen ("CCC.dat","wb");
if (pFile != NULL){
fwrite ( ((char*)pData)+4 , 1 , iDataSize-4 , pFile );
fclose (pFile);
}
iSizeAcc = 0;
iDataSize = 0;
}
}
The odd thing is. If I uncomment the message block on remote side, the recieving order will be reversed.
Thus, the result of the remote data is not in a correct order.
Why? (And how could I get the correct order of each fragment?)
Thanks in advance.
While the MessageBoxA function is executing, it pumps messages to your window. Whether or not your thread was expecting them, MessageBoxA dispatched them to you.
Calling MessageBoxA (a blocking, modal dialog) in a receive loop is a fundamentally flawed idea. If you want to see the values, run it in a debugger, print them to a dialog (e.g. a text field), output them to the console or dump them to a file.

Resources