Esempio n. 1
0
/**
 * This program contains integration test for SAPI Tss2_Sys_GetRandom.
 * First, this test is checking the return code to make sure the
 * SAPI is executed correctly(return code should return TPM_RC_SUCCESS).
 * Second, the SAPI is called twice to make sure the return randomBytes
 * are different by comparing the two randomBytes through memcmp.
 * It might not be the best test for random bytes generator but
 * at least this test shows the return randomBytes are differen.
 */
int
test_invoke (TSS2_SYS_CONTEXT *sapi_context)
{
    TSS2_RC rc;
    TPM2B_DIGEST randomBytes1 = { { sizeof (TPM2B_DIGEST) - 2, } };
    TPM2B_DIGEST randomBytes2 = { { sizeof (TPM2B_DIGEST) - 2, } };
    int bytes = 20;

    print_log("GetRandom tests started.");
    rc = Tss2_Sys_GetRandom(sapi_context, 0, bytes, &randomBytes1, 0);
    if (rc != TSS2_RC_SUCCESS)
        print_fail("GetRandom FAILED! Response Code : %x", rc);
    rc = Tss2_Sys_GetRandom(sapi_context, 0, bytes, &randomBytes2, 0);
    if (rc != TSS2_RC_SUCCESS)
        print_fail("GetRandom FAILED! Response Code : %x", rc);
    if(memcmp(&randomBytes1, &randomBytes2, bytes) == 0) {
        print_fail("Comparison FAILED! randomBytes 0x%p & 0x%p are the same.", &randomBytes1, &randomBytes2);
    }
    print_log("GetRandom Test Passed!");
    return 0;
}
Esempio n. 2
0
static int
check_output_line(char *line)
{
	if (strtok(line, " \n") == NULL)
		return -1;

	if (tolower(turn[0]) == 'b') {
		if (strtok(NULL, " \n") == NULL)
			return -1;
	}

	char *move = strtok(NULL, " \n");
	if (move == NULL)
		return -1;

	if (best_move_count > 0) {
		for (unsigned i = 0; i < best_move_count; ++i) {
			if (strcmp(move, best_moves[i]) == 0) {
				print_success(move);
				return 0;
			}
		}
		print_fail(move);
	}
	else if (avoid_move_count > 0) {
		for (unsigned i = 0; i < avoid_move_count; ++i) {
			if (strcmp(move, avoid_moves[i]) == 0) {
				print_fail(move);
				return 0;
			}
		}
		print_success(move);
	}
	else {
		print_success(move);
	}

	return 0;
}
Esempio n. 3
0
int main(int argc, char* argv[]) {
  if (argc > 1) { // If there is a test argument

  }
  else { // Normal mode
    std::cout << "Testing exponential... ";
    if (exponential(2, 1) != 2) {
      print_fail();
      return 0;
    }
    if (exponential(3, 4) != 81) {
      print_fail();
      return 0;
    }
    if (exponential(6, 3) != 216) {
      print_fail();
      return 0;
    }
    print_pass();
  }
  return 0;
}
Esempio n. 4
0
int main(int argc, char **argv)
{
    //TODO: get rid of mem leaks (valgrind)
    uint8_t flags = 0;
    const char *sdcFile = NULL;
    FILE *hdrout = NULL;
    int option;
    while((option = getopt_long(argc, argv, "fvH:Vh", options, 0)) != -1)
    {
        switch(option)
        {
        case '?':
            return EXIT_INVALIDOPT;
        //force
        case 'f':
            flags |= F_FORCE;
            break;
        //verbose
        case 'v':
            flags |= F_VERBOSE;
            break;
        //header output
        case 'H':
            print_status("Opening header sink");
            flags |= F_HEADEROUT;
            hdrout = fopen(optarg, "w");
            if(hdrout == NULL)
            {
                //error opening a file
                print_fail();
                perror(hdrout);
                return errno;
            }
            print_ok();
            break;
        //version
        case 'V':
            print_version();
            return EXIT_SUCCESS;
        //help
        case 'h':
            print_help(PH_LONG,argv[0]);
            return EXIT_SUCCESS;
            break;
        default:
            print_help(PH_SHORT,argv[0]);
            return EXIT_INVALIDOPT;
        }
    }
    if((argc - optind) == 1)
    {
        //parsing argv successful
        sdcFile = argv[optind];
    }
    else
    {
        print_help(PH_SHORT,argv[0]);
        return EXIT_TOOLESS;
    }

    print_status("Opening SDC file");
    int result;
    FILE *in = fopen(sdcFile,"r");
    if(in == NULL)
    {
        //error opening a file
        print_fail();
        perror(sdcFile);
        return errno;
    }
    print_ok();

    //open key file
    void *keyFileName = malloc(strlen(sdcFile)+5);
    sprintf((char*)keyFileName,"%s.key",sdcFile);
    FILE *key = fopen((char*)keyFileName,"r");
    if(key == NULL)
    {
        //error opening a file
        print_fail();
        perror((char*)keyFileName);
        return errno;
    }

    print_status("Verifying keyfile");

    //load keyFileName
    fseek(key,0,SEEK_END);
    int unformattedLength = ftell(key);
    fseek(key,0,SEEK_SET);
    void *unformatted = malloc(unformattedLength+1);
    fread(unformatted,1,unformattedLength,key);
    ((unsigned char *)unformatted)[unformattedLength] = '\0';
    fclose(key);

    //fill unpack structure
    UnpackData unpackData;
    UnpackStatus us = fillUnpackStruct(&unpackData,unformatted);
    switch(us)
    {
    case FUS_OK:
        print_ok();
        break;
    default:
        print_fail();
        fprintf(stderr, "%s: Wrong format of a keyfile!\n", argv[0]);
        return us;
    }

    //load header size
    uint8_t *hdrSizeBuff = (uint8_t*)malloc(4);
    fread(hdrSizeBuff,1,4,in);
    uint32_t headerSize = *(uint32_t*)hdrSizeBuff;
    free(hdrSizeBuff);
    hdrSizeBuff = NULL;

    print_status("Validating SDC header");

    //check header length
    if(headerSize < 0xff)
    {
        //it is not length but signature!
        print_fail();
        fprintf(stderr,
              "%s: Encountered unsupported format! Signature is probably "
              "0x%02x\n", argv[0], headerSize);
      return -1;
    }

    //load and decode header
    Header *header = (Header*)malloc(headerSize);
    DecrError err = loadHeader(in, header, headerSize, &unpackData);
    if(err != DD_OK)
    {
        print_fail();
        fprintf(stderr, "%s: Error when decrypting SDC header (errorcode: %d)\n", argv[0], err);
        return err;
    }

    //check if valid sdc file
    fseeko(in,0,SEEK_END);
    off_t sdcSize = ftello(in);//FIXME: check if still needed
    if((sizeof(Header) + (sizeof(File) * header->headerSize)) > headerSize)
    {
        printf("[ FAIL ]\n");
        fprintf(stderr, "%s: File given is not valid SDC file or decryption key wrong\n", argv[0]);
        if(! (flags & F_FORCE))
            return -1;
    }

    print_ok();

    print_status("Checking file integrity");

    //count crc32
    uLong crc = countCrc(in, headerSize);
    if(flags & F_VERBOSE)
        fprintf(stderr, "%s: crc32: 0x%08lX; orig: 0x%08X\n", argv[0], crc, unpackData.checksum);

    //check if crc is valid
    if(crc != unpackData.checksum)
    {
        print_fail();
        fprintf(
            stderr, "%s: CRC32 of sdc file did not match the one supplied in keyfile (0x%04X expected while have 0x%04lX)\n",
            argv[0], unpackData.checksum, crc
        );
        if(! (flags & F_FORCE))
            return crc;
    }
    else
        print_ok();

    FileUnion *current = header->files;
    off_t filestart = headerSize + 4;
    File *after = &header->files[header->headerSize].file;
    FileName *fn = (FileName*)after;

    print_status("Decoding file name");

    //decode data from header
    uint32_t fnLength = fn->fileNameLength;
    unsigned char *data = (unsigned char*)malloc(getDataOutputSize(fn->fileNameLength) + 1);
    err = decryptData(&fn->fileName, &fnLength, data, unpackData.fileNameKey, 32);
    if(err != DD_OK)
    {
        print_fail();
        fprintf(stderr, "%s: Error while decrypting file name (errorcode: %d)", argv[0], err);
        return err;
    }
    memcpy((void*)&fn->fileName,data, fnLength);

    print_ok();

    // write decrypted header to file
    if(flags & F_HEADEROUT && hdrout)
    {
        fwrite(&headerSize, 4, 1, hdrout);
        fwrite(header, headerSize, 1, hdrout);
        fclose(hdrout);
    }

    // unpack files
    int fileid;
    for(fileid = 0; fileid < header->headerSize; fileid++)
    {
        char *filename = (char*)(&fn->fileName);
        filename += current->file.fileNameOffset;
        uint32_t fn_size = strlen(filename);

        if(flags & F_VERBOSE)
            fprintf(stderr,"File path: %s\n",filename);

        dosPathToUnix(filename);

        void *dirName = malloc(fn_size + 1);
        strcpy((char*)dirName,filename);
        dirName = dirname((char*)dirName);

        char *baseName = basename(filename);

        //get sdc location
        char *sdcDir = (char*)malloc(strlen(sdcFile)+1);
        strcpy(sdcDir,sdcFile);
        sdcDir = dirname(sdcDir);

        print_status("Creating directory structure at '%s'", dirName);

        //create directory according to header
        char *outFile = (char*)malloc(strlen(sdcDir)+strlen((char*)dirName)+2);
        sprintf(outFile,"%s/%s",sdcDir,(char*)dirName);
        int ret = createDir(outFile);
        if(ret != 0)
        {
            print_fail();
            fprintf(stderr,"%s: Directory '%s' creation failed with errno: %d\n",argv[0], outFile,errno);
        }

        print_ok();

        if(flags & F_VERBOSE)
        {
#define TIMESIZE	20
        char crtime[TIMESIZE];
        time_t creation = winTimeToUnix(current->file.creationTime);
        unixTimeToStr(crtime, TIMESIZE, creation);

        char actime[TIMESIZE];
        time_t access = winTimeToUnix(current->file.accessTime);
        unixTimeToStr(actime, TIMESIZE, access);

        char mdtime[TIMESIZE];
        time_t modification = winTimeToUnix(current->file.modificationTime);
        unixTimeToStr(mdtime, TIMESIZE, modification);

        fprintf(stderr, "File has been originally created at %s, last accessed at %s and modified at %s\n", crtime, actime, mdtime);
        }

        print_status("Unpacking '%s'", baseName);

        //open output file
        outFile = (char*)realloc(outFile, strlen(sdcDir)+strlen((char*)dirName)+strlen(baseName)+3);
        sprintf(outFile,"%s/%s/%s",sdcDir,(char*)dirName,baseName);
        FILE *out = fopen(outFile,"w");
        if(out == NULL)
        {
            //error opening a file
            print_fail();
            perror(outFile);
            return errno;
        }

        //memory cleanup
        free(outFile);
        outFile = NULL;
        //free(sdcDir);//FIXME: SIGABRT
        sdcDir = NULL;
        free(dirName);
        dirName = NULL;

        //ensure we are after header
        int r;
        if((r = fseek(in,filestart,SEEK_SET))!=0)
            return r;

        //create inflate struct
        z_stream stream;
        stream.next_in = Z_NULL;
        stream.avail_in = 0;
        stream.zalloc = Z_NULL;
        stream.zfree = Z_NULL;
        stream.opaque = Z_NULL;

        //initialize stream
        r = (int)-1;
        if(header->headerSignature == SIG_ELARGE)
            r = inflateInit(&stream);
        else
            r = inflateInit2_(&stream,-15,ZLIB_VERSION,(int)sizeof(z_stream));
        if(r != Z_OK)
        {
            print_fail();
            fprintf(stderr,"inflateInit failed with errorcode %d (%s)\n",r,stream.msg);
            return r;
        }
        //read from file
        unsigned int bytesToRead;
        if(header->headerSignature == SIG_ELARGE)
        {
            bytesToRead = current->file4gb.compressedSize & 0x3fff;
        }
        else
        {
            bytesToRead = current->file.compressedSize & 0x3fff;
        }
        unsigned char *input = (unsigned char*)malloc(bytesToRead);
        unsigned char *output = (unsigned char*)malloc(0x4000);
        void *tmp = malloc(bytesToRead);

        //determine file size
        unsigned int bytesRemaining = 0;
        if(header->headerSignature == SIG_ELARGE)
            bytesRemaining = current->file4gb.fileSize;
        else
            bytesRemaining = current->file.fileSize;
        double fileSize = bytesRemaining, remaining;
        uint8_t progress = 0;

        if(flags & F_VERBOSE)
            fprintf(stderr,"file size has been set as %u (0x%04X), signature: 0x%02X\n",bytesRemaining,bytesRemaining,header->headerSignature);

        while(bytesRemaining != 0)
        {
            // check progress
            remaining = bytesRemaining;
            if((((fileSize - remaining) / fileSize) * 6) > progress)
            {
                ++progress;
                print_progress(progress);
            }

            result = fread(input+stream.avail_in,1,bytesToRead-stream.avail_in,in);
            if(result == 0 && stream.avail_in == 0)	//stop only if stream iflated whole previous buffer
                return 1;				//still have bytes remaining but container end reached

            //decode
            stream.next_in = (Bytef*)input;
            stream.avail_in += result;
            stream.next_out = (Bytef*)output;
            stream.avail_out = 0x4000;
            stream.total_in = 0;
            stream.total_out = 0;
            r = inflate(&stream,0);
            if(r < Z_OK)
            {
                print_fail();
                fprintf(stderr,"inflate failed with errorcode %d (%s)\n",r,stream.msg);
                return r;
            }

            //XOR
            xorBuffer(unpackData.xorVal % 0x100, output, stream.total_out);

            //write to file
            fwrite(output,1,stream.total_out,out);
            bytesRemaining -= stream.total_out;

            /*
            * tricky part: input buffer hadn't been fully decompressed
            * so we need to copy the rest to TMP and then at the beginning
            * of input buffer so it can be inflated, but before that we need to
            * read the rest of a chunk so its size would be COMPRESSEDSIZE
            */
            memcpy(tmp,stream.next_in,stream.avail_in);
            memcpy(input,tmp,stream.avail_in);
        }

        if(bytesRemaining != 0)
        {
            print_fail();
            fprintf(stderr, "%s: Unexpected end of file!\n", argv[0]);
        }
        else
            print_ok();

        fclose(out);
        free(tmp);
        tmp = NULL;
        free(input);
        input = NULL;
        free(output);
        output = NULL;

        if(header->headerSignature == SIG_ELARGE)
            filestart += current->file4gb.compressedSize;
        else
            filestart += current->file.compressedSize;
        current++;
    }

    free(unpackData.unformatted);
    unpackData.unformatted = NULL;
    unpackData.fileNameKey = NULL;
    unpackData.headerKey = NULL;

    free(header);

    fclose(in);
    return 0;
}
/* Test a composite of a given operation, source, and destination picture.  */
Bool
blend_test(Display *dpy, picture_info *win, picture_info *dst,
	   const int *op, int num_op,
	   const picture_info **src_color, int num_src,
	   const picture_info **dst_color, int num_dst)
{
	color4d expected, tested, tdst;
	char testname[20];
	int i, j, k, y, iter;
	int page, num_pages;

	/* If the window is smaller than the number of sources to test,
	 * we need to break the sources up into pages.
	 *
	 * We however assume that the window will always be wider than num_ops.
	 */
	num_pages = num_src / win_height + 1;

	k = y = 0;
	while (k < num_dst) {
	    XImage *image;
	    int k0 = k, k1 = k;
	    int this_src, rem_src;

	    rem_src = num_src;
	    for (page = 0; page < num_pages; page++) {
		    this_src = rem_src / (num_pages - page);
		    for (iter = 0; iter < pixmap_move_iter; iter++) {
			    k1 = k0;
			    y = 0;
			    while (k1 < num_dst && y + this_src <= win_height) {
				    XRenderComposite(dpy, PictOpSrc,
						     dst_color[k1++]->pict, 0, dst->pict,
						     0, 0,
						     0, 0,
						     0, y,
						     num_op, this_src);
				    for (j = 0; j < this_src; j++) {
					    for (i = 0; i < num_op; i++) {
						    XRenderComposite(dpy, ops[op[i]].op,
								     src_color[j]->pict, 0, dst->pict,
								     0, 0,
								     0, 0,
								     i, y,
								     1, 1);
					    }
					    y++;
				    }
			    }
		    }

		    image = XGetImage(dpy, dst->d,
				      0, 0, num_ops, y,
				      0xffffffff, ZPixmap);
		    copy_pict_to_win(dpy, dst, win, win_width, win_height);

		    y = 0;
		    for (k = k0; k < k1; k++) {
			    XRenderDirectFormat dst_acc;

			    accuracy(&dst_acc,
				     &dst->format->direct,
				     &dst_color[k]->format->direct);

			    tdst = dst_color[k]->color;
			    color_correct(dst, &tdst);

			    for (j = 0; j < this_src; j++) {
				    XRenderDirectFormat acc;

				    accuracy(&acc, &src_color[j]->format->direct, &dst_acc);

				    for (i = 0; i < num_op; i++) {
					    get_pixel_from_image(image, dst, i, y, &tested);

					    do_composite(ops[op[i]].op,
							 &src_color[j]->color,
							 NULL,
							 &tdst,
							 &expected,
							 FALSE);
					    color_correct(dst, &expected);

					    if (eval_diff(&acc, &expected, &tested) > 3.) {
						    char *srcformat;

						    snprintf(testname, 20, "%s blend", ops[op[i]].name);
						    describe_format(&srcformat, NULL, src_color[j]->format);
						    print_fail(testname, &expected, &tested, 0, 0,
							       eval_diff(&acc, &expected, &tested));
						    printf("src color: %.2f %.2f %.2f %.2f (%s)\n"
							   "dst color: %.2f %.2f %.2f %.2f\n",
							   src_color[j]->color.r, src_color[j]->color.g,
							   src_color[j]->color.b, src_color[j]->color.a,
							   srcformat,
							   dst_color[k]->color.r,
							   dst_color[k]->color.g,
							   dst_color[k]->color.b,
							   dst_color[k]->color.a);
						    printf("src: %s, dst: %s\n", src_color[j]->name, dst->name);
						    free(srcformat);
						    return FALSE;
					    }
				    }
				    y++;
			    }
		    }

		    XDestroyImage(image);
		    rem_src -= this_src;
	    }
	}

	return TRUE;
}
Esempio n. 6
0
int main()
{
    bgrt_item_t bgrt_item_1 = BGRT_ITEM_T_INIT( bgrt_item_1 );
    bgrt_item_t bgrt_item_2, bgrt_item_3;
    bgrt_item_t * head;
    int test;

    printf("Test 1: BGRT_ITEM_T_INIT macro: ");
    if( (bgrt_item_1.next != &bgrt_item_1) || (bgrt_item_1.prev != &bgrt_item_1) )
    {
        print_fail();
        return 0;
    }
    else
    {
        print_ok();
    }

    printf("Test 2: bgrt_item_init function: ");
    bgrt_item_init( &bgrt_item_2 );
    bgrt_item_init( &bgrt_item_3 );
    if( (bgrt_item_2.next != &bgrt_item_2) || (bgrt_item_2.prev != &bgrt_item_2) )
    {
        print_fail();
        return 0;
    }
    else
    {
        print_ok();
    }

    printf("Test 3: bgrt_item_insert function: ");
    head = &bgrt_item_1;

    bgrt_item_insert( &bgrt_item_2, head );

    test = (bgrt_item_1.next != &bgrt_item_2) || (bgrt_item_1.prev != &bgrt_item_2);
    test |= (bgrt_item_2.next != &bgrt_item_1) || (bgrt_item_2.prev != &bgrt_item_1);

    bgrt_item_insert( &bgrt_item_3, head );

    test |= (bgrt_item_1.next != &bgrt_item_2) || (bgrt_item_1.prev != &bgrt_item_3);
    test |= (bgrt_item_2.next != &bgrt_item_3) || (bgrt_item_2.prev != &bgrt_item_1);
    test |= (bgrt_item_3.next != &bgrt_item_1) || (bgrt_item_3.prev != &bgrt_item_2);

    if( test )
    {
        print_fail();
        return 0;
    }
    else
    {
        print_ok();
    }

    printf("Test 4: bgrt_item_cut function: ");

    bgrt_item_cut( &bgrt_item_3 );

    test = (bgrt_item_1.next != &bgrt_item_2) || (bgrt_item_1.prev != &bgrt_item_2);
    test |= (bgrt_item_2.next != &bgrt_item_1) || (bgrt_item_2.prev != &bgrt_item_1);

    bgrt_item_cut( &bgrt_item_2 );

    test |= (bgrt_item_1.next != &bgrt_item_1) || (bgrt_item_1.prev != &bgrt_item_1);

    if( test )
    {
        print_fail();
        return 0;
    }
    else
    {
        print_ok();
    }

    return 0;
}
Esempio n. 7
0
int main(int argc, char *argv[])
{
    const char *path_list = getenv("PATH");
    int short_option, long_option, fail_count = 0, path_index;
    int show_dot = 0, show_tilde = 0, tty_only = 0;
    struct option longopts[] = {
        {"version", 0, &long_option, opt_version},
        {"skip-dot", 0, &long_option, opt_skip_dot},
        {"skip-tilde", 0, &long_option, opt_skip_tilde},
        {"show-dot", 0, &long_option, opt_show_dot},
        {"show-tilde", 0, &long_option, opt_show_tilde},
        {"tty-only", 0, &long_option, opt_tty_only},
        {"all", 0, NULL, 'a'},
        {NULL, 0, NULL, 0}
    };

    progname = argv[0];
    while ((short_option = getopt_long(argc, argv, "avV", longopts, NULL)) != -1)
    {
        switch (short_option)
        {
        case 0:
            switch (long_option)
            {
            case opt_version:
                print_version();
                return 0;
            case opt_skip_dot:
                skip_dot = !tty_only;
                break;
            case opt_skip_tilde:
                skip_tilde = !tty_only;
                break;
            case opt_show_dot:
                show_dot = !tty_only;
                break;
#ifndef WIN32
            case opt_show_tilde:
                show_tilde = (!tty_only && geteuid() != 0);
                break;
#endif
            case opt_tty_only:
                tty_only = !isatty(1);
                break;
            }
            break;
        case 'a':
            show_all = 1;
            break;
        case 'v':
        case 'V':
            print_version();
            return 0;
        }
    }

    if (show_dot)
        get_current_working_directory();

    if (show_tilde || skip_tilde)
    {
        const char *h;

        if (!(h = getenv("HOME")))
        {
            fprintf(stderr, "%s: ", progname);
            if (show_tilde)
                fprintf(stderr, "--show-tilde");
            else
                fprintf(stderr, "--skip-tilde");
            fprintf(stderr, ": Environment variable HOME not set\n");
            show_tilde = skip_tilde = 0;
        }
        else
        {
            strncpy(home, h, sizeof(home));
            home[sizeof(home) - 1] = 0;
            homelen = strlen(home);
            if (home[homelen - 1] != DIRSEP && homelen < sizeof(home) - 1)
            {
                strcat(home, "/");
                ++homelen;
            }
        }
    }

    argv += optind;

    if (!*argv)
    {
        print_usage();
        return -1;
    }

    for (; *argv; ++argv)
    {
        char *result = NULL;
        int found_something = 0;

        if (path_list && *path_list != '\0')
        {
            int next;
            path_index = 0;
            do
            {
                next = show_all;
                result = find_command_in_path(*argv, path_list, &path_index);
                if (result)
                {
                    const char *full_path = path_clean_up(result);
                    int in_home = (show_tilde || skip_tilde) && !strncmp(full_path, home, homelen);
                    if (!(skip_tilde && in_home) && show_dot && found_path_starts_with_dot && !strncmp(full_path, cwd, cwdlen))
                    {
                        full_path += cwdlen;
                        fprintf(stdout, "./");
                    }
                    else if (in_home)
                    {
                        if (skip_tilde)
                        {
                            next = 1;
                            continue;
                        }
                        if (show_tilde)
                        {
                            full_path += homelen;
                            fprintf(stdout, "~/");
                        }
                    }
                    fprintf(stdout, "%s\n", full_path);
                    free(result);
                    found_something = 1;
                }
                else
                    break;
            }
            while(next);
        }
        if (!found_something)
        {
            print_fail(absolute_path_given ? strrchr(*argv, DIRSEP) + 1 : *argv, absolute_path_given ? abs_path : path_list);
            ++fail_count;
        }
    }

    return fail_count;
}
Esempio n. 8
0
//=============================================
void gradient_wakeup_timer()
{
  uint8_t next_hop_addr;
  mrfiPacket_t packetToSend;
  switch (gradient_state) {
  //--------------------------------------- transmitter
  case (GRADIENT_IDLE):                                   //wake_up timer
    /* stop preamble sampling */
    wor_stop(IS_SINK_NODE);
    /* stop possible timers */
    stop_timer();
    /* check that there is data to send */
    dataToSend = QgetInUseSlot(OUTQ);
    if (!dataToSend) {
      gradient_end_txrx();
      print_debug("\r\nno data to send",17);
      return;
    }
    /* TODO. check that the medium is free */
    set_timer(UF_PERIOD);                                  //wake_up timer
    /* send first uF */
    gradient_set_state(GRADIENT_TXUF);
    uf_counter = NUMBER_UF-1;
    gradient_build_UF(&packetToSend, uf_counter);
    MRFI_justTransmit(&packetToSend);
    break;
  case (GRADIENT_TXUF):                                   //wake_up timer
    if (uf_counter > 0) {
      uf_counter--;
      /* send uF */
      gradient_build_UF(&packetToSend, uf_counter);
      MRFI_justTransmit(&packetToSend);
    } else {
      stop_timer();
      /* send CW */
      gradient_set_state(GRADIENT_TXCW);
      gradient_build_CW(&packetToSend, CW_LENGTH);
      MRFI_justTransmit(&packetToSend);
      /* wait for ACK */
      gradient_set_state(GRADIENT_RXACK);
      gradient_init_neighbor_table();
      MRFI_RxOn();
      set_timer(CW_LENGTH);
    }
    break;
  case (GRADIENT_RXACK):                                  //wake_up timer
    stop_timer();
    print_neighbor_table(neighbors);
    gradient_update_height();
    print_height(myAddr,myHeight);
    next_hop_addr = gradient_next_hop();
    if (next_hop_addr==0) {
      gradient_end_txrx();
      print_fail("\r\nTX failed: no neighbor",24);
    } else {
      /* send DATA */
      gradient_set_state(GRADIENT_TXDATA);
      //if mine, complete with current neighbor list and empty hop count
      if ( (&(dataToSend->mrfiPkt))->frame[F_SRC]==myAddr) {
        gradient_build_DATA_headers(dataToSend);
      }
      (&(dataToSend->mrfiPkt))->frame[F_DATA_NEXT_HOP]=next_hop_addr;
      MRFI_justTransmit(&(dataToSend->mrfiPkt));
      /* wait for FIN */
      gradient_set_state(GRADIENT_RXFIN);
      MRFI_RxOn();
      set_timer(TIMEOUT_FIN);
    }
    break;
  case (GRADIENT_RXFIN):                                  //wake_up timer
    gradient_end_txrx();
    print_fail("\r\nTX failed: no FIN",19);
    break;
  //--------------------------------------- receiver
  case (GRADIENT_RXUF):                                   //wake_up timer
    stop_timer();
    /* wait for CW */
    gradient_set_state(GRADIENT_RXCW);
    MRFI_RxOn();
    set_timer(TIMEOUT_CW);
    break;
  case (GRADIENT_RXCW):                                   //wake_up timer
    gradient_end_txrx();
    print_fail("\r\nRX failed: no CW",18);
    break;
  case (GRADIENT_BACKOFFACK):                             //wake_up timer
    stop_second_random_timer();
    /* send ACK */
    gradient_set_state(GRADIENT_TXACK);
    gradient_build_ACK(&packetToSend, addr_initiator);
    MRFI_justTransmit(&packetToSend);
    gradient_set_state(GRADIENT_SENTACK);
    MRFI_RxIdle();
    break;
  case (GRADIENT_SENTACK):                                //wake_up timer
    stop_timer();
    /* wait for DATA */
    gradient_set_state(GRADIENT_RXDATA);
    MRFI_RxOn();
    set_timer(TIMEOUT_DATA);
    break;
  case (GRADIENT_RXDATA):                                 //wake_up timer
    gradient_end_txrx();
    print_fail("\r\nRX failed: no DATA",20);
    break;
  case (GRADIENT_TXFIN):                                  //wake_up timer
    stop_timer();
    /* send FIN */
    gradient_build_FIN(&packetToSend, addr_initiator);
    MRFI_justTransmit(&packetToSend);
    print_success("\r\nRX successful",15);
    print_DATA(&lastData, myAddr);
    gradient_end_txrx();
    break;
  }
}
Esempio n. 9
0
int
test_mtd(int argc, char *argv[])
{
	unsigned iterations= 0;

	/* check if microSD card is mounted */
	struct stat buffer;
	if (stat(PARAM_FILE_NAME, &buffer)) {
		warnx("file %s not found, aborting MTD test", PARAM_FILE_NAME);
		print_fail();
		return 1;
	}

	// XXX get real storage space here
	unsigned file_size = 4096;

	/* perform tests for a range of chunk sizes */
	unsigned chunk_sizes[] = {256, 512, 4096};

	for (unsigned c = 0; c < (sizeof(chunk_sizes) / sizeof(chunk_sizes[0])); c++) {

		printf("\n====== FILE TEST: %u bytes chunks ======\n", chunk_sizes[c]);

		uint8_t write_buf[chunk_sizes[c]] __attribute__((aligned(64)));

		/* fill write buffer with known values */
		for (unsigned i = 0; i < sizeof(write_buf); i++) {
			/* this will wrap, but we just need a known value with spacing */
			write_buf[i] = i+11;
		}

		uint8_t read_buf[chunk_sizes[c]] __attribute__((aligned(64)));
		hrt_abstime start, end;

		int fd = open(PARAM_FILE_NAME, O_RDONLY);
		int rret = read(fd, read_buf, chunk_sizes[c]);
		close(fd);
		if (rret <= 0) {
			err(1, "read error");
		}

		fd = open(PARAM_FILE_NAME, O_WRONLY);

		printf("printing 2 percent of the first chunk:\n");
		for (unsigned i = 0; i < sizeof(read_buf) / 50; i++) {
			printf("%02X", read_buf[i]);
		}
		printf("\n");

		iterations = file_size / chunk_sizes[c];

		start = hrt_absolute_time();
		for (unsigned i = 0; i < iterations; i++) {
			int wret = write(fd, write_buf, chunk_sizes[c]);

			if (wret != (int)chunk_sizes[c]) {
				warn("WRITE ERROR!");
				print_fail();
				return 1;
			}

			fsync(fd);

			if (!check_user_abort(fd))
				return OK;

		}
		end = hrt_absolute_time();

		close(fd);
		fd = open(PARAM_FILE_NAME, O_RDONLY);

		/* read back data for validation */
		for (unsigned i = 0; i < iterations; i++) {
			int rret2 = read(fd, read_buf, chunk_sizes[c]);

			if (rret2 != (int)chunk_sizes[c]) {
				warnx("READ ERROR!");
				print_fail();
				return 1;
			}
			
			/* compare value */
			bool compare_ok = true;

			for (unsigned j = 0; j < chunk_sizes[c]; j++) {
				if (read_buf[j] != write_buf[j]) {
					warnx("COMPARISON ERROR: byte %d", j);
					print_fail();
					compare_ok = false;
					break;
				}
			}

			if (!compare_ok) {
				warnx("ABORTING FURTHER COMPARISON DUE TO ERROR");
				print_fail();
				return 1;
			}

			if (!check_user_abort(fd))
				return OK;

		}


		close(fd);

	}

	/* fill the file with 0xFF to make it look new again */
	char ffbuf[64];
	memset(ffbuf, 0xFF, sizeof(ffbuf));
	int fd = open(PARAM_FILE_NAME, O_WRONLY);
	for (unsigned i = 0; i < file_size / sizeof(ffbuf); i++) {
		int ret = write(fd, ffbuf, sizeof(ffbuf));

		if (ret != sizeof(ffbuf)) {
			warnx("ERROR! Could not fill file with 0xFF");
			close(fd);
			print_fail();
			return 1;
		}
	}

	(void)close(fd);
	print_success();

	return 0;
}