コード例 #1
0
ファイル: main.cpp プロジェクト: ageneau/scid
int main(int argc, char * argv[]) {

   // init

   util_init();
   my_random_init(); // for opening book

   printf("Toga II 1.2.1a UCI based on Fruit 2.1 by Thomas Gaksch and Fabien Letouzey. Settings by Dieter Eberle\n");

   // early initialisation (the rest is done after UCI options are parsed in protocol.cpp)

   option_init();

   square_init();
   piece_init();
   pawn_init_bit();
   value_init();
   vector_init();
   attack_init();
   move_do_init();

   random_init();
   hash_init();

   trans_init(Trans);
   book_init();

   // loop

   loop();

   return EXIT_SUCCESS;
}
コード例 #2
0
ファイル: util_map_proc.c プロジェクト: AmesianX/nvml
int
main(int argc, char *argv[])
{
	START(argc, argv, "util_map_proc");

	util_init();

	if (argc < 3)
		UT_FATAL("usage: %s maps_file len [len]...", argv[0]);

	Sfile = argv[1];

	for (int arg = 2; arg < argc; arg++) {
		size_t len = (size_t)strtoull(argv[arg], NULL, 0);

		size_t align = Ut_pagesize;
		if (len >= 2 * GIGABYTE)
			align = GIGABYTE;
		else if (len >= 4 * MEGABYTE)
			align = 2 * MEGABYTE;

		void *h1 =
			util_map_hint_unused((void *)TERABYTE, len, GIGABYTE);
		void *h2 = util_map_hint(len, 0);
		if (h1 != MAP_FAILED && h1 != NULL)
			UT_ASSERTeq((uintptr_t)h1 & (GIGABYTE - 1), 0);
		if (h2 != MAP_FAILED && h2 != NULL)
			UT_ASSERTeq((uintptr_t)h2 & (align - 1), 0);
		UT_OUT("len %zu: %p %p", len, h1, h2);
	}

	DONE(NULL);
}
コード例 #3
0
ファイル: log.c プロジェクト: jithinjosepkl/nvml
static void
log_init(void)
{
	out_init(LOG_PREFIX, LOG_LEVEL_VAR, LOG_FILE_VAR);
	LOG(3, NULL);
	util_init();
}
コード例 #4
0
ファイル: main.cpp プロジェクト: Randl/GambitFruit
int main(int argc, char *argv[]) {

	// init

	util_init();
	my_random_init(); // for opening book

	printf(
		"Gambit Fruit based on Fruit 2.1 and Toga by Ryan Benitez, Thomas Gaksch and Fabien Letouzey\nEdit by Evgeniy Zheltonozhskiy\n");

	// early initialisation (the rest is done after UCI options are parsed in protocol.cpp)

	option_init();

	square_init();
	piece_init();
	pawn_init_bit();
	value_init();
	vector_init();
	attack_init();
	move_do_init();

	random_init();
	hash_init();

	trans_init(Trans);
	book_init();

	// loop
	loop();

	return EXIT_SUCCESS;
}
コード例 #5
0
ファイル: openocd.c プロジェクト: EmuxEvans/openocd
/* normally this is the main() function entry, but if OpenOCD is linked
 * into application, then this fn will not be invoked, but rather that
 * application will have it's own implementation of main(). */
int openocd_main(int argc, char *argv[])
{
	int ret;

	/* initialize commandline interface */
	struct command_context *cmd_ctx;

	cmd_ctx = setup_command_handler(NULL);

	if (util_init(cmd_ctx) != ERROR_OK)
		return EXIT_FAILURE;

	if (ioutil_init(cmd_ctx) != ERROR_OK)
		return EXIT_FAILURE;

	LOG_OUTPUT("For bug reports, read\n\t"
		"http://openocd.sourceforge.net/doc/doxygen/bugs.html"
		"\n");

	command_context_mode(cmd_ctx, COMMAND_CONFIG);
	command_set_output_handler(cmd_ctx, configuration_output_handler, NULL);

	/* Start the executable meat that can evolve into thread in future. */
	ret = openocd_thread(argc, argv, cmd_ctx);

	unregister_all_commands(cmd_ctx, NULL);

	/* free commandline interface */
	command_done(cmd_ctx);

	adapter_quit();

	return ret;
}
コード例 #6
0
ファイル: vmem.c プロジェクト: andreas-bluemle/nvml
/*
 * vmem_init -- initialization for vmem
 *
 * Called automatically by the run-time loader or on the first use of vmem.
 */
void
vmem_init(void)
{
	static bool initialized = false;
	static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
	int oerrno;

	if (initialized)
		return;

	if ((errno = pthread_mutex_lock(&lock)))
		FATAL("!pthread_mutex_lock");

	if (!initialized) {
		out_init(VMEM_LOG_PREFIX, VMEM_LOG_LEVEL_VAR,
				VMEM_LOG_FILE_VAR, VMEM_MAJOR_VERSION,
				VMEM_MINOR_VERSION);
		out_set_vsnprintf_func(je_vmem_navsnprintf);
		LOG(3, NULL);
		util_init();
		Header_size = roundup(sizeof (VMEM), Pagesize);

		/* Set up jemalloc messages to a custom print function */
		je_vmem_malloc_message = print_jemalloc_messages;

		initialized = true;
	}

	oerrno = errno;
	if ((errno = pthread_mutex_unlock(&lock)))
		ERR("!pthread_mutex_unlock");
	errno = oerrno;
}
コード例 #7
0
void Register_libintel_updater(void)
{
	RegisterFunction("flash_ifwi", FlashIfwiFn);
#ifdef TEE_FRAMEWORK
	RegisterFunction("flash_bom_token", FlashBomFn);
#endif	/* TEE_FRAMEWORK */

	RegisterFunction("extract_image", ExtractImageFn);
	RegisterFunction("invalidate_os", InvalidateOsFn);
	RegisterFunction("restore_os", RestoreOsFn);

	RegisterFunction("flash_capsule", FlashCapsuleFn);
	RegisterFunction("flash_esp_update", FlashEspUpdateFn);
	RegisterFunction("flash_ulpmc", FlashUlpmcFn);
	RegisterFunction("flash_partition", FlashPartition);
	RegisterFunction("flash_osiptogpt_partition", FlashOsipToGPTPartition);
	RegisterFunction("flash_image_at_partition", FlashImageAtPartition);
	RegisterFunction("flash_image_at_offset", FlashImageAtOffset);
	RegisterFunction("flash_os_image", FlashOSImage);
	RegisterFunction("write_osip_image", FlashOSImage);
	RegisterFunction("erase_osip", EraseOsipHeader);
	RegisterFunction("restore_os", RestoreOsFn);

	util_init(recovery_error, NULL);
}
コード例 #8
0
ファイル: libpmem.c プロジェクト: Skyprophet/peloton
static void
libpmem_init(void)
{
	out_init(PMEM_LOG_PREFIX, PMEM_LOG_LEVEL_VAR, PMEM_LOG_FILE_VAR,
			PMEM_MAJOR_VERSION, PMEM_MINOR_VERSION);
	LOG(3, NULL);
	util_init();
}
コード例 #9
0
ファイル: librpmem.c プロジェクト: gaoning777/nvml
/*
 * librpmem_init -- load-time initialization for librpmem
 *
 * Called automatically by the run-time loader.
 */
ATTR_CONSTRUCTOR
void
librpmem_init(void)
{
	util_init();
	out_init(RPMEM_LOG_PREFIX, RPMEM_LOG_LEVEL_VAR, RPMEM_LOG_FILE_VAR,
			RPMEM_MAJOR_VERSION, RPMEM_MINOR_VERSION);
	LOG(3, NULL);
}
コード例 #10
0
ファイル: terma.c プロジェクト: halhen/terma
void
init()
{
    setlocale(LC_CTYPE, "");
    util_init();
    x_init();
    term_init(&callbacks);
    shell_fd = sh_init();
}
コード例 #11
0
ファイル: protobuf.c プロジェクト: maniacs-ops/protobuf
static PHP_MINIT_FUNCTION(protobuf) {
  map_field_init(TSRMLS_C);
  repeated_field_init(TSRMLS_C);
  gpb_type_init(TSRMLS_C);
  message_init(TSRMLS_C);
  descriptor_pool_init(TSRMLS_C);
  descriptor_init(TSRMLS_C);
  enum_descriptor_init(TSRMLS_C);
  util_init(TSRMLS_C);
}
コード例 #12
0
ファイル: libpmemobj.c プロジェクト: astroynao/nvml
/*
 * libpmemobj_init -- load-time initialization for obj
 *
 * Called automatically by the run-time loader.
 */
ATTR_CONSTRUCTOR
void
libpmemobj_init(void)
{
	out_init(PMEMOBJ_LOG_PREFIX, PMEMOBJ_LOG_LEVEL_VAR,
			PMEMOBJ_LOG_FILE_VAR, PMEMOBJ_MAJOR_VERSION,
			PMEMOBJ_MINOR_VERSION);
	LOG(3, NULL);
	util_init();
	obj_init();
}
コード例 #13
0
ファイル: vmem.c プロジェクト: mdalecki/nvml
static void
vmem_init(void)
{
	out_init(LOG_PREFIX, LOG_LEVEL_VAR, LOG_FILE_VAR);
	LOG(3, NULL);
	util_init();
	Header_size = roundup(sizeof (VMEM), Pagesize);

	/* Set up jemalloc to forward messages to a custom print function */
	je_vmem_malloc_message = print_jemalloc_messages;
}
コード例 #14
0
ファイル: rpmem_basic.c プロジェクト: janekmi/nvml
int
main(int argc, char *argv[])
{
	util_init();
	rpmem_fip_probe_get(NULL, NULL);
	START(argc, argv, "rpmem_basic");

	TEST_CASE_PROCESS(argc, argv, test_cases, NTESTS);

	DONE(NULL);
}
コード例 #15
0
int main(int argc, char *argv[])
{
	int i;
	
	util_init();

	cpld_version();
	
//	return *((char *)(map_base+CPLD_VER));	
//	*((char *)(map_base+CONTROL_OFFSET3)) |= ETH_CPU_DIS;	
	util_exit();
}
コード例 #16
0
ファイル: util_poolset.c プロジェクト: dardevelin/nvml
int
main(int argc, char *argv[])
{
	START(argc, argv, "util_poolset");

	out_init(LOG_PREFIX, LOG_LEVEL_VAR, LOG_FILE_VAR,
			MAJOR_VERSION, MINOR_VERSION);
	util_init();

	if (argc < 5)
		UT_FATAL("usage: %s cmd minlen hdrsize [mockopts] setfile ...",
			argv[0]);

	char *fname;
	struct pool_set *set;
	int ret;

	size_t minsize = strtoul(argv[2], &fname, 0);

	for (int arg = 3; arg < argc; arg++) {
		arg += mock_options(argv[arg]);
		fname = argv[arg];

		switch (argv[1][0]) {
		case 'c':
			ret = util_pool_create(&set, fname, 0, minsize,
				SIG, 1, 0, 0, 0);
			if (ret == -1)
				UT_OUT("!%s: util_pool_create", fname);
			else {
				util_poolset_chmod(set, S_IWUSR | S_IRUSR);
				poolset_info(fname, set, 0);
				util_poolset_close(set, 0); /* do not delete */
			}
			break;
		case 'o':
			ret = util_pool_open(&set, fname, 0 /* rdonly */,
				minsize, SIG, 1, 0, 0, 0);
			if (ret == -1)
				UT_OUT("!%s: util_pool_open", fname);
			else {
				poolset_info(fname, set, 1);
				util_poolset_close(set, 0); /* do not delete */
			}
			break;
		}
	}

	out_fini();

	DONE(NULL);
}
コード例 #17
0
ファイル: pmemdetect.c プロジェクト: ChandKV/nvml
int
main(int argc, char *argv[])
{
	int ret;

	if (argc != 2 && argc != 3) {
		fprintf(stderr, "usage: %s [-d] path\n", argv[0]);
		exit(2);
	}

	const char *path = argv[1];
	int dev_dax = 0;

	if (argc == 3 && strcmp(argv[1], "-d") == 0) {
		path = argv[2];
		dev_dax = 1;
	}

	util_init();
	util_mmap_init();

	if (dev_dax)
		ret = is_dev_dax(path);
	else
		ret = is_pmem(path);

	/*
	 * Return 0 if 'path' points to PMEM-aware filesystem or device dax.
	 * Otherwise return 1, if any problem occurred return 2.
	 */
	switch (ret) {
	case 0:
		ret = 1;
		break;
	case 1:
		ret = 0;
		break;
	default:
		ret = 2;
		break;
	}

	return ret;
}
コード例 #18
0
ファイル: info.c プロジェクト: jebtang/nvml
int
pmempool_info_func(char *appname, int argc, char *argv[])
{
	int ret = 0;
	util_init();
	struct pmem_info *pip = pmempool_info_alloc();

	/* read command line arguments */
	if ((ret = parse_args(appname, argc, argv, &pip->args,
					pip->opts)) == 0) {
		/* set some output format values */
		out_set_vlevel(pip->args.vlevel);
		out_set_col_width(pip->args.col_width);

		ret = pmempool_info_file(pip, pip->args.file);
	}

	pmempool_info_free(pip);

	return ret;
}
コード例 #19
0
ファイル: pmempool.c プロジェクト: perone/nvml
int
main(int argc, char *argv[])
{
	int opt;
	int option_index;

	util_init();

	if (argc < 2) {
		print_usage(APPNAME);
		return 0;
	}

	while ((opt = getopt_long(2, argv, "Vh",
			long_options, &option_index)) != -1) {
		switch (opt) {
		case 'V':
			print_version(APPNAME);
			return 0;
		case 'h':
			print_help(APPNAME);
			return 0;
		default:
			print_usage(APPNAME);
			return -1;
		}
	}

	char *cmd_str = argv[optind];

	struct command *cmdp = get_command(cmd_str);

	if (cmdp)
		return cmdp->func(APPNAME, argc - 1, argv + 1);

	outv_err("'%s' -- unknown command\n", cmd_str);

	return -1;
}
コード例 #20
0
ファイル: main.c プロジェクト: wezside/servo-ctc
int main()
{
	init_timer_0();

	init_pin_interrupt(PCINT0);

	init_adc();

	util_init();


	// Outputs
	DDRB |= (1 << PB1);
	DDRB |= (1 << PB3);
	DDRB |= (1 << PB4);

	PORTB &= ~(1 << PB3); // Set LED low
	PORTB &= ~(1 << PB1); // Set Servo pin low

	// Inputs	
	DDRB &= ~(1 << PB0); /* Set PB0 as input */
    PORTB |= (1 << PB0); /* Activate PULL UP resistor */ 


	// Toggle LED
	PORTB ^= (1 << PB3); 
	_delay_ms(1000);
	PORTB ^= (1 << PB3); 	

	// Enable global interrupts
	sei();

	while(1)
	{
		reading = read_analog();
		reading_map = map(reading, 0, 255, 410, 1580, 1) / 1000.0 / 0.01;	
	}
}
コード例 #21
0
ファイル: util_is_poolset.c プロジェクト: dardevelin/nvml
int
main(int argc, char *argv[])
{
	START(argc, argv, "util_is_poolset");

	out_init(LOG_PREFIX, LOG_LEVEL_VAR, LOG_FILE_VAR,
			MAJOR_VERSION, MINOR_VERSION);
	util_init();

	if (argc < 2)
		UT_FATAL("usage: %s file...",
			argv[0]);

	for (int i = 1; i < argc; i++) {
		char *fname = argv[i];
		int is_poolset = util_is_poolset(fname);

		UT_OUT("util_is_poolset(%s): %d", fname, is_poolset);
	}
	out_fini();

	DONE(NULL);
}
コード例 #22
0
ファイル: obj_redo_log.c プロジェクト: AmesianX/nvml
int
main(int argc, char *argv[])
{
	START(argc, argv, "obj_redo_log");
	util_init();

	if (argc < 4)
		FATAL_USAGE();

	PMEMobjpool *pop = pmemobj_open_mock(argv[1]);
	UT_ASSERTne(pop, NULL);

	UT_ASSERTeq(util_is_zeroed((char *)pop->addr + PMEMOBJ_POOL_HDR_SIZE,
			pop->size - PMEMOBJ_POOL_HDR_SIZE), 1);

	char *end = NULL;
	errno = 0;
	size_t redo_size = strtoul(argv[2], &end, 0);
	if (errno || !end || *end != '\0')
		FATAL_USAGE();

	UT_ASSERT(pop->size >= redo_size * sizeof(struct redo_log));

	struct redo_log *redo = (struct redo_log *)pop->addr;

	uint64_t offset;
	uint64_t value;
	int i;
	int ret;
	size_t index;
	for (i = 3; i < argc; i++) {
		char *arg = argv[i];
		UT_ASSERTne(arg, NULL);

		switch (arg[0]) {
		case 's':
			if (sscanf(arg, "s:%ld:0x%lx:0x%lx",
					&index, &offset, &value) != 3)
				FATAL_USAGE();
			UT_OUT("s:%ld:0x%08lx:0x%08lx", index, offset, value);
			redo_log_store(pop, redo, index, offset, value);
			break;
		case 'f':
			if (sscanf(arg, "f:%ld:0x%lx:0x%lx",
					&index, &offset, &value) != 3)
				FATAL_USAGE();
			UT_OUT("f:%ld:0x%08lx:0x%08lx", index, offset, value);
			redo_log_store_last(pop, redo, index, offset,
					value);
			break;
		case 'F':
			if (sscanf(arg, "F:%ld", &index) != 1)
				FATAL_USAGE();
			UT_OUT("F:%ld", index);
			redo_log_set_last(pop, redo, index);
			break;
		case 'r':
			if (sscanf(arg, "r:0x%lx", &offset) != 1)
				FATAL_USAGE();

			uint64_t *valp = (uint64_t *)((uintptr_t)pop->addr
					+ offset);
			UT_OUT("r:0x%08lx:0x%08lx", offset, *valp);
			break;
		case 'e':
			if (sscanf(arg, "e:%ld", &index) != 1)
				FATAL_USAGE();

			struct redo_log *entry = redo + index;

			int flag = (entry->offset & REDO_FINISH_FLAG) ? 1 : 0;
			offset = entry->offset & REDO_FLAG_MASK;
			value = entry->value;

			UT_OUT("e:%ld:0x%08lx:%d:0x%08lx", index, offset,
					flag, value);
			break;
		case 'P':
			redo_log_process(pop, redo, redo_size);
			UT_OUT("P");
			break;
		case 'R':
			redo_log_recover(pop, redo, redo_size);
			UT_OUT("R");
			break;
		case 'C':
			ret = redo_log_check(pop, redo, redo_size);
			UT_OUT("C:%d", ret);
			break;
		default:
			FATAL_USAGE();
		}
	}

	pmemobj_close_mock(pop);

	DONE(NULL);
}
コード例 #23
0
ファイル: rpmemd.c プロジェクト: tomaszkapela/nvml
int
main(int argc, char *argv[])
{
    util_init();

    int send_status = 1;
    int ret = 1;

    struct rpmemd *rpmemd = calloc(1, sizeof(*rpmemd));
    if (!rpmemd) {
        RPMEMD_LOG(ERR, "!calloc");
        goto err_rpmemd;
    }

    rpmemd->obc = rpmemd_obc_init(STDIN_FILENO, STDOUT_FILENO);
    if (!rpmemd->obc) {
        RPMEMD_LOG(ERR, "out-of-band connection intitialization");
        goto err_obc;
    }

    if (rpmemd_log_init(DAEMON_NAME, NULL, 0)) {
        RPMEMD_LOG(ERR, "logging subsystem initialization failed");
        goto err_log_init;
    }

    if (rpmemd_config_read(&rpmemd->config, argc, argv) != 0) {
        RPMEMD_LOG(ERR, "reading configuration failed");
        goto err_config;
    }

    rpmemd_log_close();
    rpmemd_log_level = rpmemd->config.log_level;
    if (rpmemd_log_init(DAEMON_NAME, rpmemd->config.log_file,
                        rpmemd->config.use_syslog)) {
        RPMEMD_LOG(ERR, "logging subsystem initialization"
                   " failed (%s, %d)", rpmemd->config.log_file,
                   rpmemd->config.use_syslog);
        goto err_log_init_config;
    }

    RPMEMD_LOG(INFO, "%s version %s", DAEMON_NAME, SRCVERSION);
    rpmemd->persist = pmem_persist;
    rpmemd->persist_method = rpmemd_get_pm(&rpmemd->config);
    rpmemd->nthreads = rpmemd_get_nthreads();
    if (!rpmemd->nthreads) {
        RPMEMD_LOG(ERR, "invalid number of threads -- '%lu'",
                   rpmemd->nthreads);
        goto err_nthreads;
    }

    rpmemd->db = rpmemd_db_init(rpmemd->config.poolset_dir, 0666);
    if (!rpmemd->db) {
        RPMEMD_LOG(ERR, "!pool set db initialization");
        goto err_db_init;
    }

    if (rpmemd->config.rm_poolset) {
        RPMEMD_LOG(INFO, "removing '%s'",
                   rpmemd->config.rm_poolset);
        if (rpmemd_db_pool_remove(rpmemd->db,
                                  rpmemd->config.rm_poolset,
                                  rpmemd->config.force)) {
            RPMEMD_LOG(ERR, "removing '%s' failed",
                       rpmemd->config.rm_poolset);
        } else {
            RPMEMD_LOG(NOTICE, "removed '%s'",
                       rpmemd->config.rm_poolset);
            ret = 0;
        }
        send_status = 0;
        goto out_rm;
    }

    ret = rpmemd_obc_status(rpmemd->obc, 0);
    if (ret) {
        RPMEMD_LOG(ERR, "writing status failed");
        goto err_status;
    }

    rpmemd_print_info(rpmemd);

    while (!ret) {
        ret = rpmemd_obc_process(rpmemd->obc, &rpmemd_req, rpmemd);
        if (ret) {
            RPMEMD_LOG(ERR, "out-of-band connection"
                       " process failed");
            goto err;
        }

        if (rpmemd->closing)
            break;
    }

    rpmemd_db_fini(rpmemd->db);
    rpmemd_config_free(&rpmemd->config);
    rpmemd_log_close();
    rpmemd_obc_fini(rpmemd->obc);
    free(rpmemd);

    return 0;
err:
    rpmemd_req_cleanup(rpmemd);
err_status:
out_rm:
    rpmemd_db_fini(rpmemd->db);
err_db_init:
err_nthreads:
err_log_init_config:
    rpmemd_config_free(&rpmemd->config);
err_config:
    rpmemd_log_close();
err_log_init:
    if (send_status) {
        if (rpmemd_obc_status(rpmemd->obc, (uint32_t)errno))
            RPMEMD_LOG(ERR, "writing status failed");
    }
    rpmemd_obc_fini(rpmemd->obc);
err_obc:
    free(rpmemd);
err_rpmemd:
    return ret;
}
コード例 #24
0
ファイル: ping_client.c プロジェクト: Floche/nRF905
void ping_client(void)
{
	util_init();

	// Start up
	nRF905_init();

	// Set address of this device
	uint8_t addrRx[] = RXADDR;
	nRF905_setRXAddress(addrRx);

	// Interrupts on
	sei();

	// LED indicator
	DDRC |= _BV(DDC5);
	PORTC |= _BV(PORTC5);

	// Put into receive mode
	nRF905_receive();
	
	uint8_t counter = 0;

	while(1)
	{
		// Make data
		char data[NRF905_MAX_PAYLOAD] = {0};
		sprintf_P(data, PSTR("test %hhu"), counter);
		counter++;

		unsigned long startTime = millis();

		// Set address of device to send to
		uint8_t addr[] = TXADDR;
		nRF905_setTXAddress(addr);

		// Set payload data
		nRF905_setData(data, sizeof(data));

		// Send payload (send fails if other transmissions are going on, keep trying until success)
		while(!nRF905_send());

		// Put into receive mode
		nRF905_receive();

		// Make buffer for reply
		uint8_t buffer[NRF905_MAX_PAYLOAD];
		bool success;

		// Wait for reply with timeout
		unsigned long sendStartTime = millis();
		while(1)
		{
			success = nRF905_getData(buffer, sizeof(buffer));
			if(success)// Got data
				break;

			// Timeout
			if(millis() - sendStartTime > TIMEOUT)
				break;
		}

		// If success toggle LED and send ping time over UART
		if(success)
		{
			unsigned int totalTime = millis() - startTime;
			PORTC ^= _BV(PORTC5);

			printf_P(PSTR("Ping time: %ums\n"), totalTime);

			// Print out ping contents
			printf_P(PSTR("Data from server: "));
			for(uint8_t i=0;i<sizeof(buffer);i++)
				uart_put_nb(buffer[i]);
			puts_P(PSTR(""));
		}
		else
			puts_P(PSTR("Ping timed out"));

		_delay_ms(100);					
	}
}
コード例 #25
0
int main(void)
{
	uint8_t i;
	uint16_t wakeup_sec;
	bool send;

	// delay 1s to avoid further communication with uart or RFM12 when my programmer resets the MC after 500ms...
	_delay_ms(1000);

	util_init();
	
	check_eeprom_compatibility(DEVICETYPE_SOILMOISTUREMETER);
	
	// configure power pin for 74HC14D as output
	sbi(TRIGGERPWR_DDR, TRIGGERPWR_PIN);

	// read packetcounter, increase by cycle and write back
	packetcounter = e2p_generic_get_packetcounter() + PACKET_COUNTER_WRITE_CYCLE;
	e2p_generic_set_packetcounter(packetcounter);

	// read device id
	device_id = e2p_generic_get_deviceid();

	dry_thr = e2p_soilmoisturemeter_get_drythreshold();
	if (dry_thr == 0) // set default value if never initialized
	{
		dry_thr = 40000;
	}

	counter_min = e2p_soilmoisturemeter_get_minval();
	if (counter_min == 0) // set default value if never initialized
	{
		counter_min = 30000;
	}

	avgIntInit = e2p_soilmoisturemeter_get_averagingintervalinit();
	avgInt = e2p_soilmoisturemeter_get_averaginginterval();
	smoothing_percentage = e2p_soilmoisturemeter_get_smoothingpercentage();

	osccal_init();

	uart_init();

	UART_PUTS ("\r\n");
	UART_PUTF4("smarthomatic Soil Moisture Meter v%u.%u.%u (%08lx)\r\n", VERSION_MAJOR, VERSION_MINOR, VERSION_PATCH, VERSION_HASH);
	UART_PUTS("(c) 2014..2015 Uwe Freese, www.smarthomatic.org\r\n");
	osccal_info();
	UART_PUTF ("DeviceID: %u\r\n", device_id);
	UART_PUTF ("PacketCounter: %lu\r\n", packetcounter);
	UART_PUTF ("AveragingInterval for initialization: %u\r\n", avgIntInit);
	UART_PUTF ("AveragingInterval for normal operation: %u\r\n", avgInt);
	UART_PUTF ("Dry threshold: %u\r\n", dry_thr);
	UART_PUTF ("Min value: %u\r\n", counter_min);
	UART_PUTF ("Smoothing percentage: %u\r\n", smoothing_percentage);

	adc_init();

	// init AES key
	e2p_generic_get_aeskey(aes_key);

	// set pull-up for BUTTON_DDR
	sbi(BUTTON_PORT, BUTTON_PIN);
	_delay_ms(10);

	// set DIDR for all ADC channels and AINs, switch off digital input buffers to reduce ADC noise and to save power
	DIDR0 = 63;
	DIDR1 = 3;
	
	// If button pressed at start up, go to sleep for idle power consumption test.
	// Don't communicate with RFM12, which may not have been connected yet.
	if (BUTTON)
	{
		led_blink(50, 50, 20);
		power_down(true);
	}

	led_blink(500, 500, 3);

	rfm12_init();
	wakeup_sec = init_wakeup();

	// init interrupt for button (falling edge)
	sbi(EICRA, ISC11);
	sbi(EIMSK, INT1);
	
	sei();

	for (i = 0; i < SEND_STATUS_TIMES_AT_STARTUP; i++)
	{
		prepare_deviceinfo_status();
		send_prepared_message();
		_delay_ms(800);
		prepare_battery_status();
		send_prepared_message();
		_delay_ms(800);
	}

	while (42)
	{
		if (BUTTON)
		{
			led_blink(100, 0, 1);
			UART_PUTS("Button pressed!\r\n");
			
			uint8_t cnt = 0;
			
			while (BUTTON && (cnt < 250))
			{
				_delay_ms(10);
				cnt++;
			}
			
			if (cnt == 250)
			{
				UART_PUTS("Long press -> initiate measure mode!\r\n");
				
				while (BUTTON)
				{
					led_blink(100, 100, 1);
				}

				init_mode = true;
				wupCnt = 0;
				counter_meas = 0;
				init_wakeup(); // to usually shorter value
				
				UART_PUTS("Button released!\r\n");
				_delay_ms(10);
			}
		}
		else
		{
			send = true;

			//UART_PUTF("version_status_cycle = %u\r\n", version_status_cycle);
		
			if (!measure_humidity())
			{
				if (battery_status_cycle > 0)
					battery_status_cycle--;

				if (version_status_cycle > 0)
					version_status_cycle--;

				if (version_status_cycle == 0)
				{
					version_status_cycle = SEND_VERSION_STATUS_CYCLE;
					prepare_deviceinfo_status();
				}
				else if (battery_status_cycle == 0)
				{
					battery_status_cycle = SEND_BATTERY_STATUS_CYCLE;
					prepare_battery_status();
				}
				else
				{
					send = false;
				}
			}

			if (send)
			{
				send_prepared_message();
			}
		}
		
		power_down(true);
	}
	
	// never called
	// aes256_done(&aes_ctx);
}
コード例 #26
0
int main(void)
{
	uint8_t aes_key_nr;
	uint8_t loop = 0;
	uint8_t loop2 = 0;
	
	// delay 1s to avoid further communication with uart or RFM12 when my programmer resets the MC after 500ms...
	_delay_ms(1000);

	util_init();

	check_eeprom_compatibility(DEVICETYPE_BASESTATION);

	request_queue_init();

	// read packetcounter, increase by cycle and write back
	packetcounter = e2p_generic_get_packetcounter() + PACKET_COUNTER_WRITE_CYCLE;
	e2p_generic_set_packetcounter(packetcounter);

	// read device specific config
	aes_key_count = e2p_basestation_get_aeskeycount();

	device_id = e2p_generic_get_deviceid();

	uart_init();
	UART_PUTS("\r\n");
	UART_PUTF4("smarthomatic Base Station v%u.%u.%u (%08lx)\r\n", VERSION_MAJOR, VERSION_MINOR, VERSION_PATCH, VERSION_HASH);
	UART_PUTS("(c) 2012..2014 Uwe Freese, www.smarthomatic.org\r\n");
	UART_PUTF("Device ID: %u\r\n", device_id);
	UART_PUTF("Packet counter: %lu\r\n", packetcounter);
	UART_PUTF("AES key count: %u\r\n", aes_key_count);
	UART_PUTS("Waiting for incoming data. Press h for help.\r\n\r\n");

	led_blink(500, 500, 3);

	rfm12_init();
	sei();
	
	// ENCODE TEST (Move to unit test some day...)
	/*
	uint8_t testlen = 32;
	uint8_t aes_key_num = 0;
	
	memset(&bufx[0], 0, sizeof(bufx));
	bufx[0] = 0xff;
	bufx[1] = 0xb0;
	bufx[2] = 0xa0;
	bufx[3] = 0x3f;
	bufx[4] = 0x01;
	bufx[5] = 0x70;
	bufx[6] = 0x00;
	bufx[7] = 0x0c;
	bufx[8] = 0xa8;
	bufx[9] = 0x00;
	bufx[10] = 0x20;
	bufx[20] = 0x20;

	eeprom_read_block (aes_key, (uint8_t *)(EEPROM_AESKEYS_BYTE + aes_key_num * 32), 32);
	UART_PUTS("Using AES key ");
	print_bytearray((uint8_t *)aes_key, 32);
	
	UART_PUTS("Before encryption: ");
	print_bytearray(bufx, testlen);
	
	uint8_t aes_byte_count = aes256_encrypt_cbc(bufx, testlen);
	
	UART_PUTF("byte count = %u\r\n", aes_byte_count);
	
	UART_PUTS("After encryption: ");
	print_bytearray(bufx, aes_byte_count);
	
	aes256_decrypt_cbc(bufx, aes_byte_count);
  
	UART_PUTS("After decryption: ");
	print_bytearray(bufx, testlen);
	
	while(1);
	*/

	while (42)
	{
		if (rfm12_rx_status() == STATUS_COMPLETE)
		{
			uint8_t len = rfm12_rx_len();
			
			if ((len == 0) || (len % 16 != 0))
			{
				UART_PUTF("Received garbage (%u bytes not multiple of 16): ", len);
				print_bytearray(bufx, len);
			}
			else // try to decrypt with all keys stored in EEPROM
			{
				bool crcok = false;

				for (aes_key_nr = 0; aes_key_nr < aes_key_count ; aes_key_nr++)
				{
					memcpy(bufx, rfm12_rx_buffer(), len);

					/*if (aes_key_nr == 0)
					{
						UART_PUTS("Before decryption: ");
						print_bytearray(bufx, len);
					}*/
				
					e2p_basestation_get_aeskey(aes_key_nr, aes_key);
					//UART_PUTS("Trying AES key 2 ");
					//print_bytearray((uint8_t *)aes_key, 32);

					aes256_decrypt_cbc(bufx, len);

					//UART_PUTS("Decrypted bytes: ");
					//print_bytearray(bufx, len);
					
					crcok = pkg_header_check_crc32(len);
					
					if (crcok)
					{
						//UART_PUTS("CRC correct, AES key found!\r\n");
						UART_PUTF("Received (AES key %u): ", aes_key_nr);
						print_bytearray(bufx, len);
						
						decode_data(len);
						
						break;
					}
				}
				
				if (!crcok)
				{
					UART_PUTS("Received garbage (CRC wrong after decryption): ");
					memcpy(bufx, rfm12_rx_buffer(), len);
					print_bytearray(bufx, len);
				}
				
				UART_PUTS("\r\n");
			}

			//uart_hexdump((char *)bufcontents, rfm12_rx_len());
			//UART_PUTS("\r\n");

			// tell the implementation that the buffer can be reused for the next data.
			rfm12_rx_clear();
		}

		// send data, if waiting in send buffer
		if (send_data_avail)
		{
			uint8_t i;
			
			// set AES key nr
			aes_key_nr = hex_to_uint8((uint8_t *)cmdbuf, 1);
			//UART_PUTF("AES KEY = %u\r\n", aes_key_nr);

			// init packet buffer
			memset(&bufx[0], 0, sizeof(bufx));

			// set message type
			uint8_t message_type = hex_to_uint8((uint8_t *)cmdbuf, 3);
			pkg_header_set_messagetype(message_type);
			pkg_header_adjust_offset();
			//UART_PUTF("MessageType = %u\r\n", message_type);

			uint8_t string_offset_data = 0;
			
			/*
			UART_PUTS("sKK00RRRRGGMM.............Get\r\n");
			UART_PUTS("sKK01RRRRGGMMDD...........Set\r\n");
			UART_PUTS("sKK02RRRRGGMMDD...........SetGet\r\n");
			UART_PUTS("sKK08GGMMDD...............Status\r\n");
			UART_PUTS("sKK09SSSSPPPPPPEE.........Ack\r\n");
			UART_PUTS("sKK0ASSSSPPPPPPEEGGMMDD...AckStatus\r\n");
			*/
			
			// set header extension fields to the values given as hex string in the user input
			switch (message_type)
			{
				case MESSAGETYPE_GET:
				case MESSAGETYPE_SET:
				case MESSAGETYPE_SETGET:
					pkg_headerext_common_set_receiverid(hex_to_uint16((uint8_t *)cmdbuf, 5));
					pkg_headerext_common_set_messagegroupid(hex_to_uint8((uint8_t *)cmdbuf, 9));
					pkg_headerext_common_set_messageid(hex_to_uint8((uint8_t *)cmdbuf, 11));
					string_offset_data = 12;
					break;
				case MESSAGETYPE_STATUS:
					pkg_headerext_common_set_messagegroupid(hex_to_uint8((uint8_t *)cmdbuf, 5));
					pkg_headerext_common_set_messageid(hex_to_uint8((uint8_t *)cmdbuf, 7));
					string_offset_data = 8;
					break;
				case MESSAGETYPE_ACK:
					pkg_headerext_common_set_acksenderid(hex_to_uint16((uint8_t *)cmdbuf, 5));
					pkg_headerext_common_set_ackpacketcounter(hex_to_uint24((uint8_t *)cmdbuf, 9));
					pkg_headerext_common_set_error(hex_to_uint8((uint8_t *)cmdbuf, 15));
					// fallthrough!
				case MESSAGETYPE_ACKSTATUS:
					pkg_headerext_common_set_messagegroupid(hex_to_uint8((uint8_t *)cmdbuf, 17));
					pkg_headerext_common_set_messageid(hex_to_uint8((uint8_t *)cmdbuf, 19));
					string_offset_data = 20;
					break;
			}

			uint8_t data_len_raw = 0;

			// copy message data, which exists in all packets except in Get and Ack packets
			if ((message_type != MESSAGETYPE_GET) && (message_type != MESSAGETYPE_ACK))
			{
				uint8_t data_len_raw = (strlen(cmdbuf) - 1 - string_offset_data) / 2;
				//UART_PUTF("Data bytes = %u\r\n", data_len_raw);
				
				uint8_t start = __HEADEROFFSETBITS / 8;
				uint8_t shift = __HEADEROFFSETBITS % 8;

				// copy message data, using __HEADEROFFSETBITS value and string_offset_data
				for (i = 0; i < data_len_raw; i++)
				{
					uint8_t val = hex_to_uint8((uint8_t *)cmdbuf, string_offset_data + 2 * i + 1);
					array_write_UIntValue(start + i, shift, 8, val, bufx);
				}
			}
			
			// round packet length to x * 16 bytes
			uint8_t packet_len = ((uint16_t)__HEADEROFFSETBITS + (uint16_t)data_len_raw * 8) / 8;
			packet_len = ((packet_len - 1) / 16 + 1) * 16;

			// send packet which doesn't require an acknowledge immediately
			if ((message_type != MESSAGETYPE_GET) && (message_type != MESSAGETYPE_SET) && (message_type != MESSAGETYPE_SETGET))
			{
				send_packet(aes_key_nr, packet_len);
			}
			else // enqueue request (don't send immediately)
			{
				// header size = 9 bytes!
				if (queue_request(pkg_headerext_common_get_receiverid(), message_type, aes_key_nr, bufx + 9, packet_len - 9))
				{
					UART_PUTF("Request added to queue (%u bytes packet).\r\n", packet_len);
				}
				else
				{
					UART_PUTS("Warning! Request queue full. Packet will not be sent.\r\n");
				}

				print_request_queue();
			}
		
			// clear cmdbuf to receive more input from UART
			send_data_avail = false;

			rfm12_tick();

			led_blink(200, 0, 1);
		}

		// flash LED every second to show the device is alive
		if (loop == 50)
		{
			led_blink(10, 10, 1);
			
			loop = 0;
			
			request_t* request = find_request_to_repeat(packetcounter + 1);

			if (request != 0) // if request to repeat was found in queue
			{
				UART_PUTS("Repeating request.\r\n");					
				send_packet((*request).aes_key, (*request).data_bytes + 9); // header size = 9 bytes!
				print_request_queue();
			}
			
			// Auto-send something for debugging purposes...
			if (loop2 == 50)
			{
				//strcpy(cmdbuf, "s000102828300");
				//send_data_avail = true;
				
				loop2 = 0;
			}
			else
			{
				loop2++;
			}
		}
		else
		{
			_delay_ms(20);
		}

		rfm12_tick();

		loop++;
		
		process_rxbuf();
		
		if (uart_timeout > 0)
		{
			uart_timeout--;
			
			if (uart_timeout == 0)
			{
				UART_PUTS("*** UART user timeout. Input was ignored. ***\r\n");
			}
		}
	}
	
	// never called
	// aes256_done(&aes_ctx);
}
コード例 #27
0
ファイル: shc_dimmer.c プロジェクト: GoHoHa/smarthomatic
int main(void)
{
	uint16_t send_status_timeout = 25;
	uint32_t station_packetcounter;
	uint32_t pos;
	uint8_t button_state = 0;
	uint8_t manual_dim_direction = 0;

	// delay 1s to avoid further communication with uart or RFM12 when my programmer resets the MC after 500ms...
	_delay_ms(1000);

	util_init();
	check_eeprom_compatibility(DEVICE_TYPE_DIMMER);

	osccal_init();
	
	// read packetcounter, increase by cycle and write back
	packetcounter = eeprom_read_dword((uint32_t*)EEPROM_POS_PACKET_COUNTER) + PACKET_COUNTER_WRITE_CYCLE;
	eeprom_write_dword((uint32_t*)EEPROM_POS_PACKET_COUNTER, packetcounter);

	// read device id and write to send buffer
	device_id = eeprom_read_byte((uint8_t*)EEPROM_POS_DEVICE_ID);	
	use_pwm_translation = 1; //eeprom_read_byte((uint8_t*)EEPROM_POS_USE_PWM_TRANSLATION);	
	
	// TODO: read (saved) dimmer state from before the eventual powerloss
	/*for (i = 0; i < SWITCH_COUNT; i++)
	{
		uint16_t u16 = eeprom_read_word((uint16_t*)EEPROM_POS_SWITCH_STATE + i * 2);
		switch_state[i] = (uint8_t)(u16 & 0b1);
		switch_timeout[i] = u16 >> 1;
	}*/
	
	// read last received station packetcounter
	station_packetcounter = eeprom_read_dword((uint32_t*)EEPROM_POS_STATION_PACKET_COUNTER);

	led_blink(200, 200, 5);

#ifdef UART_DEBUG
	uart_init(false);
	UART_PUTS ("\r\n");
	UART_PUTS ("smarthomatic Dimmer V1.0 (c) 2013 Uwe Freese, www.smarthomatic.org\r\n");
	osccal_info();
	UART_PUTF ("Device ID: %u\r\n", device_id);
	UART_PUTF ("Packet counter: %lu\r\n", packetcounter);
	UART_PUTF ("Use PWM translation table: %u\r\n", use_pwm_translation);
	UART_PUTF ("Last received station packet counter: %u\r\n\r\n", station_packetcounter);
#endif

	// init AES key
	eeprom_read_block (aes_key, (uint8_t *)EEPROM_POS_AES_KEY, 32);

	rfm12_init();
	PWM_init();
	io_init();
	setPWMDutyCycle(0);
	timer0_init();

	// DEMO to measure the voltages of different PWM settings to calculate the pwm_lookup table
	/*while (42)
	{
		uint16_t i;
		
		for (i = 0; i <= 1024; i = i + 100)
		{
			UART_PUTF ("PWM value OCR1A: %u\r\n", i);
			OCR1A = i;
			led_blink(500, 6500, 1);
		}
	}*/
	
	// DEMO 0..100..0%, using the pwm_lookup table and the translation table in EEPROM.
	/*while (42)
	{
		float i;
		
		for (i = 0; i <= 100; i = i + 0.05)
		{
			led_blink(10, 10, 1);
			setPWMDutyCycle(i);
		}
		
		for (i = 99.95; i > 0; i = i - 0.05)
		{
			led_blink(10, 10, 1);
			setPWMDutyCycle(i);
		}
	}*/

	// set initial switch state
	/*for (i = 0; i < SWITCH_COUNT; i++)
	{
		switchRelais(i, switch_state[i]);
	}*/

	sei();

	// DEMO 30s
	/*animation_length = 30;
	animation_length = (uint32_t)((float)animation_length * 1000 / ANIMATION_CYCLE_MS);
	start_brightness = 0;
	end_brightness = 255;
	animation_position = 0;*/
	
	while (42)
	{
		if (rfm12_rx_status() == STATUS_COMPLETE)
		{
			uint8_t len = rfm12_rx_len();
			
			if ((len == 0) || (len % 16 != 0))
			{
				UART_PUTF("Received garbage (%u bytes not multiple of 16): ", len);
				printbytearray(bufx, len);
			}
			else // try to decrypt with all keys stored in EEPROM
			{
				memcpy(bufx, rfm12_rx_buffer(), len);
				
				//UART_PUTS("Before decryption: ");
				//printbytearray(bufx, len);
					
				aes256_decrypt_cbc(bufx, len);

				//UART_PUTS("Decrypted bytes: ");
				//printbytearray(bufx, len);

				uint32_t assumed_crc = getBuf32(len - 4);
				uint32_t actual_crc = crc32(bufx, len - 4);
				
				//UART_PUTF("Received CRC32 would be %lx\r\n", assumed_crc);
				//UART_PUTF("Re-calculated CRC32 is  %lx\r\n", actual_crc);
				
				if (assumed_crc != actual_crc)
				{
					UART_PUTS("Received garbage (CRC wrong after decryption).\r\n");
				}
				else
				{
					//UART_PUTS("CRC correct, AES key found!\r\n");
					UART_PUTS("         Received: ");
					printbytearray(bufx, len - 4);
					
					// decode command and react
					uint8_t sender = bufx[0];
					
					UART_PUTF("           Sender: %u\r\n", sender);
					
					if (sender != 0)
					{
						UART_PUTF("Packet not from base station. Ignoring (Sender ID was: %u).\r\n", sender);
					}
					else
					{
						uint32_t packcnt = getBuf32(1);

						UART_PUTF("   Packet Counter: %lu\r\n", packcnt);

						// check received counter
						if (0) //packcnt <= station_packetcounter)
						{
							UART_PUTF2("Received packet counter %lu is lower than last received counter %lu. Ignoring packet.\r\n", packcnt, station_packetcounter);
						}
						else
						{
							// write received counter
							station_packetcounter = packcnt;
							eeprom_write_dword((uint32_t*)EEPROM_POS_STATION_PACKET_COUNTER, station_packetcounter);
							
							// check command ID
							uint8_t cmd = bufx[5];

							UART_PUTF("       Command ID: %u\r\n", cmd);
							
							if (cmd != 141) // ID 141 == Dimmer Request
							{
								UART_PUTF("Received unknown command ID %u. Ignoring packet.\r\n", cmd);
							}
							else
							{
								// check device id
								uint8_t rcv_id = bufx[6];

								UART_PUTF("      Receiver ID: %u\r\n", rcv_id);
								
								if (rcv_id != device_id)
								{
									UART_PUTF("Device ID %u does not match. Ignoring packet.\r\n", rcv_id);
								}
								else
								{
									// read animation mode and parameters
									uint8_t animation_mode = bufx[7] >> 5;
									
									// TODO: Implement support for multiple dimmers (e.g. RGB)
									// uint8_t dimmer_bitmask = bufx[7] & 0b111;
									
									animation_length = getBuf16(8);
									start_brightness = bufx[10];
									end_brightness = bufx[11];

									UART_PUTF("   Animation Mode: %u\r\n", animation_mode); // TODO: Set binary mode like 00010110
									//UART_PUTF("   Dimmer Bitmask: %u\r\n", dimmer_bitmask);
									UART_PUTF("   Animation Time: %us\r\n", animation_length);
									UART_PUTF(" Start Brightness: %u\r\n", start_brightness);
									UART_PUTF("   End Brightness: %u\r\n", end_brightness);
									
									animation_length = (uint32_t)((float)animation_length * 1000 / ANIMATION_CYCLE_MS);
									animation_position = 0;
									
									/* TODO: Write to EEPROM (?)
									// write back switch state to EEPROM
									switch_state[i] = req_state;
									switch_timeout[i] = req_timeout;
									
									eeprom_write_word((uint16_t*)EEPROM_POS_SWITCH_STATE + i * 2, u16);
									
									*/
									
									// send acknowledge
									UART_PUTS("Sending ACK:\r\n");

									// set device ID (base station has ID 0 by definition)
									bufx[0] = device_id;
									
									// update packet counter
									packetcounter++;
									
									if (packetcounter % PACKET_COUNTER_WRITE_CYCLE == 0)
									{
										eeprom_write_dword((uint32_t*)0, packetcounter);
									}

									setBuf32(1, packetcounter);

									// set command ID "Generic Acknowledge"
									bufx[5] = 1;
									
									// set sender ID of request
									bufx[6] = sender;
									
									// set Packet counter of request
									setBuf32(7, station_packetcounter);

									// zero unused bytes
									bufx[11] = 0;
									
									// set CRC32
									uint32_t crc = crc32(bufx, 12);
									setBuf32(12, crc);

									// show info
									UART_PUTF("            CRC32: %lx\r\n", crc);
									uart_putstr("      Unencrypted: ");
									printbytearray(bufx, 16);

									rfm12_sendbuf();
									
									UART_PUTS("   Send encrypted: ");
									printbytearray(bufx, 16);
									UART_PUTS("\r\n");
								
									rfm12_tick();
									
									led_blink(200, 0, 1);
									
									send_status_timeout = 25;
								}
							}
						}
					}
				}
				
			}

			// tell the implementation that the buffer can be reused for the next data.
			rfm12_rx_clear();
		}

		_delay_ms(ANIMATION_UPDATE_MS);
		
		// React on button press.
		// - abort animation
		// - switch off, when brightness > 0
		// - switch on otherwise
		if (!(BUTTON_PORT & (1 << BUTTON_PIN))) // button press
		{
			if (button_state == 0)
			{
				UART_PUTS("Button pressed\r\n");
				animation_length = 0;
				animation_position = 0;
			}
			
			if (button_state < 5)
			{
				button_state++;
			}
			else // manual dimming
			{
				if (manual_dim_direction) // UP
				{
					if (current_brightness < 100)
					{
						current_brightness = (uint8_t)current_brightness / 2 * 2 + 2;
						setPWMDutyCycle(current_brightness);
					}
					else
					{
						UART_PUTS("manual dimming DOWN\r\n");
						manual_dim_direction = 0;
					}
				}
				else // DOWN
				{
					if (current_brightness > 0)
					{
						current_brightness = (((uint8_t)current_brightness - 1) / 2) * 2;
						setPWMDutyCycle(current_brightness);
					}
					else
					{
						UART_PUTS("manual dimming UP\r\n");
						manual_dim_direction = 1;
					}
				}
				
			}
		}
		else if (button_state && (BUTTON_PORT & (1 << BUTTON_PIN))) // button release
		{
			UART_PUTS("Button released\r\n");
			
			if (button_state < 5) // short button press
			{
				if (current_brightness > 0)
				{
					UART_PUTS(" -> 0%\r\n");
					setPWMDutyCycle(0);
				}
				else
				{
					UART_PUTS(" -> 100%\r\n");
					setPWMDutyCycle(100);
				}
			}
			else
			{
				// reverse dim direction
				manual_dim_direction = !manual_dim_direction;
			}
			
			button_state = 0;
		}
				
		// update brightness according animation_position, updated by timer0
		if (animation_length > 0)
		{
			pos = animation_position; // copy value to avoid that it changes in between by timer interrupt
			UART_PUTF2("%lu/%lu, ", pos, animation_length);
			
			if (pos == animation_length)
			{
				UART_PUTF("END Brightness %u%%, ", end_brightness * 100 / 255);
				setPWMDutyCycle((float)end_brightness * 100 / 255);
				animation_length = 0;
				animation_position = 0;
			}
			else
			{			
				float brightness = (start_brightness + ((float)end_brightness - start_brightness) * pos / animation_length) * 100 / 255;
				UART_PUTF("Br.%u%%, ", (uint32_t)(brightness));
				setPWMDutyCycle(brightness);
			}
		}			
		
		// send status from time to time
		if (send_status_timeout == 0)
		{
			send_status_timeout = SEND_STATUS_EVERY_SEC * (1000 / ANIMATION_UPDATE_MS);
			send_dimmer_status();
			led_blink(200, 0, 1);
		}

		rfm12_tick();
		send_status_timeout--;
		checkSwitchOff();
	}
コード例 #28
0
ファイル: leapd.c プロジェクト: sh19910711/leap.js
int main(int argc, char *argv[]) {
/* main
 * The main LEAP program - This performs the display of the
 * title, and processes the command line. Clean termination
 * also should occur here. Everywhere else termination is
 * "unclean", and should return an error status. Define
 * error status' in the dtypes.h file
 */
#ifdef FULL_DEBUG
	/* Test vars */
	char source[50],result[50],*sptr;
#endif
	boolean tdebug=FALSE,ttiming=FALSE,ttimelog=FALSE,tlong=FALSE;
	boolean tquiet=FALSE,ttrace=FALSE,tpad=FALSE,tpjoin=FALSE;
	time_t tp;
	char *s;
	char *argptr;

	/********************************
	 * Startup - Firstly set up the
         * signal handlers
	 ********************************/

	/* Signal Interrupt from the keyboard - the daemon should handle it */
	signal(SIGINT,&signal_handler); 

	/* MSDOS/Windows does not know SIGQUIT/SIGHUP, whereas
	 * these are important in Unix
	 */
#ifndef __MSDOS__

	/* Signal Quit from the keyboard - Ignore it */
	signal(SIGQUIT,SIG_IGN);

	/* Signal Hang up - Handle it */
	signal(SIGHUP,&signal_handler);

#else

#endif

	define_handle(&default_handler,&errorHandler);
	raise_message(EVENT, "%s","Event Handler initialised.");

	define_handle(&default_quiethandler,&messageHandler);
	raise_message(EVENT,"%s","Message Handler initialised.");

	/* Signal Terminate - Handle it */
	signal(SIGTERM,&signal_handler);


	/* Perform some configuration... */
	build_base_dir(LEAP_DEFAULT_DIR);
	
	/* Set the random seed to the time in secs since 01.01.1970
	 * should be random enough!
	 */
	srand(time(NULL));

	s=getenv(LEAP_ENV_DIR);

	strcpy(dbtoopen,"");
	strcpy(activityfile,"");
	strcpy(tempdir,"");
	ACTIVITY_FILE=NULL;

	if (s!=NULL) {
		leap_fprintf(stdout,"Using environment variable %s for path (%s).\n",LEAP_ENV_DIR,s);
		build_base_dir(s);
	}

	/* Process the command line
		Stop if we run out of arguments
		or we get an argument without a dash */

	/* NB. This is based on O'Reilly & Associates "Practical
	  C Programming", by Steve Oualline, 2nd Ed. (pg 178) */

	while ((argc > 1) && (argv[1][0] == '-')) {
		/* 
		 * argv[1][1] is the actual option character
		 */
		if ((argv[1][0]==ARGUMENT_PREFIX) && (argv[1][1]==ARGUMENT_PREFIX)) {
			argptr=&argv[1][2];
		} else {
			argptr=&argv[1][1];
		}
		switch (*argptr) {
		case 'a':
		case 'A':
			if ((strcmp(argptr,"activity-file")==0)||(strcmp(argptr,"activity")==0)||(strlen(argptr)==1)) {
				if (specify(activityfile,argv[2],FILE_PATH_SIZE)){
					argv++;
					argc--;
				} else {
					leap_fprintf(stderr,"No file specified. Using %s\n",LEAP_ACTIVITY_FILE);
					strncpy(activityfile,LEAP_ACTIVITY_FILE,FILE_PATH_SIZE);
				}
				ACTIVITY_FILE=fopen(activityfile,"a");
				if (ACTIVITY_FILE==NULL) {
					leap_fprintf(stderr,"Unable to open activity file for appending.\n");
				} else {
					tp=time(NULL);
					fprintf(ACTIVITY_FILE,"###\n# Activity file STARTED at: %s###\n",ctime(&tp));
					leap_printf("Activity file: %s\n",activityfile);
				}
			}
			break;
			
		case 'b':
		case 'B':
			if (specify(dbtoopen,argv[2],DATABASE_NAME_SIZE)){
				argv++;
				argc--;
			} else {
				raise_message(MESSAGE,"No database specified on command line. %s will be used.",DEFAULT_DB);
			}
			break;

		case 'd':
		case 'D':
			if ((strcmp(argptr,"dir")==0)||(strcmp(argptr,"directory")==0)||(strlen(argptr)==1)) {
				if (argv[2]) {
					build_base_dir(argv[2]);
	
					/* Increment the counts... */
					argv++;
					argc--;
				} else {
					leap_fprintf(stderr,"ERROR: No directory specified after directory flag.\n");
					exit(1);
				}
			} else if (strcmp(argptr,"database")==0) {
				if (specify(dbtoopen,argv[2],DATABASE_NAME_SIZE)){
					argv++;
					argc--;
				}
			} else if (strcmp(argptr,"debug")==0) {
				/* The user wants debug information */
				leap_printf("Debug messages enabled\n");
				tdebug=TRUE;
			}
			break;

		case 'e':
		case 'E':
			if (strlen(argptr)==1) {
				/* The user wants debug information */
				leap_printf("Debug messages enabled\n");
				tdebug=TRUE;
			} else if ((strcmp(argptr,"events")==0)||(strcmp(argptr,"event")==0)) {
				/* User wants event reports */
				define_handle(&default_quiethandler,&eventHandler);
				raise_message(EVENT,"%s","Event Handler initialised.");
			}
			break;
		case 'h':
		case '?':
		case 'H':
			if ((strcmp(argptr,"help")==0)||(strlen(argptr)==1)) {
				/* The user wants some help... */
				print_help();

				/* Exit without an error */
				exit(0);
	
				/* Lint-ified - The break is not reached */
				/* break; */
			}
		case 'i':
		case 'I':
			/* The user wants timing information */
			leap_printf("Timing information enabled\n");
			ttiming=TRUE;
			break;

		case 'l':
		case 'L':
			if ((strcmp(argptr,"time-logging")==0)||(strlen(argptr)==1)) {
				/* Do not fetch the system time in log file */
				leap_printf("Time logging disabled\n");
				ttimelog=FALSE;
			} else if ((strcmp(argptr,"long-commands")==0)||(strcmp(argptr,"long")==0)){
				leap_printf("Long commands enabled\n");
				tlong=TRUE;
			}
			break;
		case 'n':
		case 'N':
			/* Display warranty information */
			do_warranty();
			exit(0);
				
			/* Lint-ified - The break is not reached */
			/* break; */
		case 'o':
		case 'O':
			leap_printf("Long commands enabled\n");
			tlong=TRUE;
			break;
		case 'p':
		case 'P':
			if ((strcmp(argptr,"padding")==0)||(strlen(argptr)==1)) {
				leap_printf("Relation Name Padding enabled\n");
				tpad=TRUE;
			} else if ((strcmp(argptr,"product-join")==0)||(strcmp(argptr,"pjoin")==0)) {
				leap_printf("Product performed in no-condition join\n");
				tpjoin=TRUE;
			} 
			break;
		case 'q':
		case 'Q':
			if ((strcmp(argptr,"quiet")==0)||(strlen(argptr)==1)) {
				tquiet=TRUE;
				BEEP=' ';

				/* Shutdown the message handler */
				define_handle(NULL,&messageHandler);
			}
			break;
		case 'r':
		case 'R':
			if ((strcmp(argptr,"regression")==0)||(strlen(argptr)==1)) {
				/*  What!? This is to disable outputting
 		 		 * items that might cause regression tests
				 * to fail for no good reason, ie. 
				 * temporary relation names which are random,
				 * and will differ between runs.
			     */
				status_regression=TRUE;
				leap_printf("Regression test mode on\n");
			}
			break;
		case 's':
		case 'S':
			if ((strcmp(argptr,"status")==0)||(strlen(argptr)==1)) {
				/* The user wants status messages to be
			   	displayed */
				leap_printf("Status messages enabled\n");
				status=TRUE;
			}
			break;
		case 't':
		case 'T':
			if ((strcmp(argptr,"time")==0)||(strcmp(argptr,"timing")==0)) {
				/* The user wants timing information */
				leap_printf("Timing information enabled\n");
				ttiming=TRUE;
			} else if ((strlen(argptr)==1)||(strcmp(argptr,"trace")==0)||(strcmp(argptr,"tracing")==0)) {
				/* The user wants tracing information */
				leap_printf("Tracing information enabled\n");
				ttrace=TRUE;
			}
			break;
		case 'v':
		case 'V':
			if ((strcmp(argptr,"version")==0)||(strlen(argptr)==1))  {
				/* Print BRIEF version information */
				print_header(TRUE);
				exit(0);
			}
			break;
		case 'w':
		case 'W':
			if ((strcmp(argptr,"warranty")==0)||(strlen(argptr)==1)) {
				do_warranty();
				exit(0);
			}
			break;
		case 'x':
		case 'X':
			if (argv[2]) {
				strncpy(tempdir,argv[2],FILE_PATH_SIZE);
				/* Increment the counts... */
				argv++;
				argc--;
			} else {
				leap_fprintf(stderr,"ERROR: No directory specified after temporary directory flag.\n");
				exit(1);
			}
			break;

			
		default:
			raise_error(ERROR_COMMAND_LINE,NONFATAL,argptr);
		}

		/* Move the argument list up one and the count down one */
		argv++;
		argc--;
	}
	raise_message(EVENT,"%s","Command line processed.");

	/* First things first, report (verbosely) what we are. */
	if ((status_regression!=TRUE) && (tquiet!=TRUE))
		print_header(FALSE);
	
	if ( (status) && (tquiet!=TRUE) ) {
		sprintf(temp_80_chars,"LEAP Base directory set to: %s",LEAP_BASE_DIR);
		leap_printf(temp_80_chars);
	}

	/* Call any initialisation routines... */
	util_init();

	/* This has to be done after the path is read, so that
     * the variable config file is located.
     */
	if (init_variables()!=RETURN_SUCCESS) {
		raise_message(MESSAGE,"Directory specified [%s] not valid. Trying [%s]",LEAP_BASE_DIR,LEAP_TRY_DIR);
		build_base_dir(LEAP_TRY_DIR);
		if (init_variables()!=RETURN_SUCCESS) {
			raise_message(MESSAGE,"[%s] is also not valid - Problems are likely",LEAP_TRY_DIR);
		} else {
			raise_message(MESSAGE,"Variables are now set.");
		}
	}
		

	if (tdebug==TRUE) set_variable(STATUS_DEBUG,STATUS_SETTING_ON);
	if (ttiming==TRUE) set_variable(STATUS_TIMING,STATUS_SETTING_ON);
	if (ttimelog==TRUE) set_variable(STATUS_TIMELOG,STATUS_SETTING_ON);
	if (tlong==FALSE) set_variable(STATUS_LONGLINE,STATUS_SETTING_OFF);
	if (tquiet==TRUE) set_variable(STATUS_QUIET,STATUS_SETTING_ON);
	if (ttrace==TRUE) set_variable(STATUS_TRACE,STATUS_SETTING_ON);
	if (tpad==TRUE) set_variable(STATUS_PADDING,STATUS_SETTING_ON);
	if (tpjoin==TRUE) set_variable(STATUS_PRODUCTJOIN,STATUS_SETTING_ON);

	/* Display some information */
	if (status_quiet!=TRUE) {
		raise_message(MESSAGE,"LEAP is starting...");
	}
	
#ifdef DEBUG
	status_debug=TRUE;
	leap_fprintf(stderr,"DEBUG: LEAP debug mode forced on\n");
#endif

	/* Do the main leap operation */
	(void) do_daemon();
	
	print_shutdown();

	/* Close the various files opened earlier */
	util_close();

	if (status_quiet!=TRUE) {
			/* Inform the user of a clean termination */
			raise_message(MESSAGE,"LEAP Terminated successfully!");
	}

	/* Return success. Elsewhere, non-zero should be returned */
	return(0);
}
コード例 #29
0
ファイル: ab_func_strings.c プロジェクト: osen/cdesktopenv
int 
main (int argc, char *argv[])
{
    STRING	inFilename = NULL;
    FILE	*inFile = NULL;
    FileFuncInfoRec	funcInfo;
    FileFuncInfo	funcs = NULL;
    int			numFuncs = 0;
    int			i = 0;

    /* 
    ** We haven't internationalized this utility program, but it uses
    ** libraries which are I18N-ized.  To resolve this we just set the
    ** message catalog descriptor to -1 here so we get default messages
    ** from library routines.
    */
    Dtb_project_catd = (nl_catd) -1;

    util_init(&argc, &argv);

    if (argc < 2)
    {
	fprintf(stderr, "Usage %s <filename>\n", argv[0]);
	exit(1);
    }

    inFilename = argv[1];
    inFile = util_fopen_locked(inFilename, "r");
    if (inFile == NULL)
    {
	perror(inFilename);
	return -1;
    }

    memset(&funcInfo, 0, sizeof(funcInfo));
    while (get_func(inFile, &funcInfo) >= 0)
    {
        fprintf(stderr, "Function: %s\n", util_strsafe(funcInfo.funcName));

	++numFuncs;
	funcs = (FileFuncInfo)realloc(
			funcs, numFuncs * sizeof(FileFuncInfoRec));
	if (funcs == NULL)
	{
	    fprintf(stderr, "Out of memory!\n");
	    exit(1);
	}
	funcs[numFuncs-1] = funcInfo;
        memset(&funcInfo, 0, sizeof(funcInfo));
    }
    fprintf(stderr, "Functions found in file: %d\n", numFuncs);
    if (numFuncs < 1)
    {
	exit(0);
    }

    for (i = 0; i < numFuncs; ++i)
    {
	write_func_var_decl(stdout, &(funcs[i]));
    }

    abio_puts(stdout, "\n\n\n");

    for (i = 0; i < numFuncs; ++i)
    {
	write_func_as_strings(stdout, &(funcs[i]));
    }


    return 0;
}
コード例 #30
0
ファイル: pmreorder_simple.c プロジェクト: krzycz/nvml
int
main(int argc, char *argv[])
{
	START(argc, argv, "pmreorder_simple");

	util_init();

	if ((argc != 3) || (strchr("gbcm", argv[1][0]) == NULL) ||
			argv[1][1] != '\0')
		UT_FATAL("usage: %s g|b|c|m file", argv[0]);

	int fd = OPEN(argv[2], O_RDWR);
	size_t size;
	/* mmap and register in valgrind pmemcheck */
	void *map = pmem_map_file(argv[2], 0, 0, 0, &size, NULL);
	UT_ASSERTne(map, NULL);

	struct three_field *structp = map;

	char opt = argv[1][0];

	/* clear the struct to get a consistent start state for writing */
	if (strchr("gb", opt))
		pmem_memset_persist(structp, 0, sizeof(*structp));
	else if (strchr("m", opt)) {
		/* set test values to log an inconsistent start state */
		pmem_memset_persist(&structp->flag, 1, sizeof(int));
		pmem_memset_persist(&structp->first_field, 0, sizeof(int) * 2);
		pmem_memset_persist(&structp->third_field, 1, sizeof(int));
		/* clear the struct to get back a consistent start state */
		pmem_memset_persist(structp, 0, sizeof(*structp));
	}

	/* verify that DEFAULT_REORDER restores default engine */
	VALGRIND_EMIT_LOG("PMREORDER_MARKER_CHANGE.BEGIN");

	switch (opt) {
		case 'g':
			write_consistent(structp);
			break;
		case 'b':
			write_inconsistent(structp);
			break;
		case 'm':
			write_consistent(structp);
			break;
		case 'c':
			return check_consistency(structp);
		default:
			UT_FATAL("Unrecognized option %c", opt);
	}
	VALGRIND_EMIT_LOG("PMREORDER_MARKER_CHANGE.END");

	/* check if undefined marker will not cause an issue */
	VALGRIND_EMIT_LOG("PMREORDER_MARKER_UNDEFINED.BEGIN");
	VALGRIND_EMIT_LOG("PMREORDER_MARKER_UNDEFINED.END");

	CLOSE(fd);

	DONE(NULL);
}