示例#1
0
static co_rc_t coserial_main(int argc, char *argv[])
{
	co_rc_t rc;
	co_command_line_params_t cmdline;
	int unit = 0;
	bool_t unit_specified = PFALSE;
	int instance = 0;
	bool_t instance_specified = PFALSE;
	
	co_debug_start();

	rc = co_cmdline_params_alloc(&argv[1], argc-1, &cmdline);
	if (!CO_OK(rc)) {
		co_terminal_print("coserial: error parsing arguments\n");
		goto out_clean;
	}

	rc = co_cmdline_params_one_arugment_int_parameter(cmdline, "-i", 
							  &instance_specified, &instance);

	if (!CO_OK(rc)) {
		syntax();
		goto out;
	}

	rc = co_cmdline_params_one_arugment_int_parameter(cmdline, "-u", 
							  &unit_specified, &unit);

	if (!CO_OK(rc)) {
		syntax();
		goto out;
	}

	rc = co_cmdline_params_check_for_no_unparsed_parameters(cmdline, PTRUE);
	if (!CO_OK(rc))
		goto out;


	rc = daemon_mode(unit, instance);

out:
	co_cmdline_params_free(cmdline);

out_clean:
	co_debug_end();

	return rc;
}
示例#2
0
文件: main.c 项目: liberalman/mqtt
int main(int argc, char *argv[])
{
    int ret = 0/*, i = 0*/;
    char buf[MAX_BUF]; // 数据缓冲区
    //char error[MAX_ERROR]; // 错误描述缓冲区
    libertymqtt_config config;
    
    #ifndef VERSION
        char VERSION[32];
        snprintf(VERSION, 32, "%s", "0.0");
    #else
        
    #endif
    
    // 输出版本信息
    snprintf(buf, MAX_BUF, "version %s", VERSION);
    _log(DEBUG, "%s\n", buf);

    // 载入配置文件
    ret = _init_conf(&config, argc, argv);
    if (SUCCESS != ret)
        exit(ret);

    // 初始化日志
    _init_log(config.log_file, config.log_type);

    // daemon方式启动
    daemon_mode(&config);

    // 创建socket,监听端口
    libertymqtt_listen(&config.default_listener);
    //for (i = 0; i < config.listener_count; i++){
    //}

    // 主循环
    libertymqtt_main_loop(&config);

    // 退出前不要忘了清理配置、关闭日志等
    _clear_all(&config);
    _log_close();
    return 0;
}
示例#3
0
文件: amd.c 项目: hmatyschok/MeshBSD
int
main(int argc, char *argv[])
{
  char *domdot, *verstr, *vertmp;
  int ppid = 0;
  int error;
  char *progname = NULL;		/* "amd" */
  char hostname[MAXHOSTNAMELEN + 1] = "localhost"; /* Hostname */

  /*
   * Make sure some built-in assumptions are true before we start
   */
  assert(sizeof(nfscookie) >= sizeof(u_int));
  assert(sizeof(int) >= 4);

  /*
   * Set processing status.
   */
  amd_state = Start;

  /*
   * Determine program name
   */
  if (argv[0]) {
    progname = strrchr(argv[0], '/');
    if (progname && progname[1])
      progname++;
    else
      progname = argv[0];
  }
  if (!progname)
    progname = "amd";
  am_set_progname(progname);

  /*
   * Initialize process id.  This is kept
   * cached since it is used for generating
   * and using file handles.
   */
  am_set_mypid();

  /*
   * Get local machine name
   */
  if (gethostname(hostname, sizeof(hostname)) < 0) {
    plog(XLOG_FATAL, "gethostname: %m");
    going_down(1);
  }
  hostname[sizeof(hostname) - 1] = '\0';

  /*
   * Check it makes sense
   */
  if (!*hostname) {
    plog(XLOG_FATAL, "host name is not set");
    going_down(1);
  }

  /*
   * Initialize global options structure.
   */
  init_global_options();

  /*
   * Partially initialize hostd[].  This
   * is completed in get_args().
   */
  if ((domdot = strchr(hostname, '.'))) {
    /*
     * Hostname already contains domainname.
     * Split out hostname and domainname
     * components
     */
    *domdot++ = '\0';
    hostdomain = domdot;
  }
  xstrlcpy(hostd, hostname, sizeof(hostd));
  am_set_hostname(hostname);

  /*
   * Setup signal handlers
   */
  /* SIGINT: trap interrupts for shutdowns */
  setup_sighandler(SIGINT, sigterm);
  /* SIGTERM: trap terminate so we can shutdown cleanly (some chance) */
  setup_sighandler(SIGTERM, sigterm);
  /* SIGHUP: hangups tell us to reload the cache */
  setup_sighandler(SIGHUP, sighup);
  /*
   * SIGCHLD: trap Death-of-a-child.  These allow us to pick up the exit
   * status of backgrounded mounts.  See "sched.c".
   */
  setup_sighandler(SIGCHLD, sigchld);
#ifdef HAVE_SIGACTION
  /* construct global "masked_sigs" used in nfs_start.c */
  sigemptyset(&masked_sigs);
  sigaddset(&masked_sigs, SIGINT);
  sigaddset(&masked_sigs, SIGTERM);
  sigaddset(&masked_sigs, SIGHUP);
  sigaddset(&masked_sigs, SIGCHLD);
#endif /* HAVE_SIGACTION */

  /*
   * Fix-up any umask problems.  Most systems default
   * to 002 which is not too convenient for our purposes
   */
  orig_umask = umask(0);

  /*
   * Figure out primary network name
   */
  getwire(&PrimNetName, &PrimNetNum);

  /*
   * Determine command-line arguments
   */
  get_args(argc, argv);

  /*
   * Log version information.
   */
  vertmp = get_version_string();
  verstr = strtok(vertmp, "\n");
  plog(XLOG_INFO, "AM-UTILS VERSION INFORMATION:");
  while (verstr) {
    plog(XLOG_INFO, "%s", verstr);
    verstr = strtok(NULL, "\n");
  }
  XFREE(vertmp);

  /*
   * Get our own IP address so that we can mount the automounter.  We pass
   * localhost_address which could be used as the default localhost
   * name/address in amu_get_myaddress().
   */
  amu_get_myaddress(&myipaddr, gopt.localhost_address);
  plog(XLOG_INFO, "My ip addr is %s", inet_ntoa(myipaddr));

  /* avoid hanging on other NFS servers if started elsewhere */
  if (chdir("/") < 0)
    plog(XLOG_INFO, "cannot chdir to /: %m");

  /*
   * Now check we are root.
   */
  if (geteuid() != 0) {
    plog(XLOG_FATAL, "Must be root to mount filesystems (euid = %ld)", (long) geteuid());
    going_down(1);
  }

#ifdef HAVE_MAP_NIS
  /*
   * If the domain was specified then bind it here
   * to circumvent any default bindings that may
   * be done in the C library.
   */
  if (gopt.nis_domain && yp_bind(gopt.nis_domain)) {
    plog(XLOG_FATAL, "Can't bind to NIS domain \"%s\"", gopt.nis_domain);
    going_down(1);
  }
#endif /* HAVE_MAP_NIS */

  if (!amuDebug(D_DAEMON))
    ppid = daemon_mode();

  /*
   * Lock process text and data segment in memory.
   */
  if (gopt.flags & CFM_PROCESS_LOCK) {
    do_memory_locking();
  }

  do_mapc_reload = clocktime(NULL) + gopt.map_reload_interval;

  /*
   * Register automounter with system.
   */
  error = mount_automounter(ppid);
  if (error && ppid)
    kill(ppid, SIGALRM);

#ifdef HAVE_FS_AUTOFS
  /*
   * XXX this should be part of going_down(), but I can't move it there
   * because it would be calling non-library code from the library... ugh
   */
  if (amd_use_autofs)
    destroy_autofs_service();
#endif /* HAVE_FS_AUTOFS */

  going_down(error);

  abort();
  return 1; /* should never get here */
}
示例#4
0
/* #########################################################################
Main
######################################################################### */
int main(int argc, char *argv[])
{
	struct sockaddr_in addr;
	int on = 1, disable_control_port = 0;
	pthread_t client, cam, cntrl, mind, uart_control;
	char *dev = "/dev/video0";
	int fps = 5, daemon = 0;


	cd.width = 640;
	cd.height = 480;

	cdata = &cd;
	cd.control_port = htons(8081);
	cd.stream_port = htons(8080);
	while (1) {
		int option_index = 0, c = 0;
		static struct option long_options[] = \
    {
			{"h", no_argument, 0, 0},
			{"help", no_argument, 0, 0},
			{"d", required_argument, 0, 0},
			{"device", required_argument, 0, 0},
			{"r", required_argument, 0, 0},
			{"resolution", required_argument, 0, 0},
			{"f", required_argument, 0, 0},
			{"fps", required_argument, 0, 0},
			{"p", required_argument, 0, 0},
			{"port", required_argument, 0, 0},
			{"v", no_argument, 0, 0},
			{"version", no_argument, 0, 0},
			{"b", no_argument, 0, 0},
			{"background", no_argument, 0, 0},
			{"c", required_argument, 0, 0},
			{"control_port", required_argument, 0, 0},
			{"disable_control", no_argument, 0, 0},
			{"C", no_argument, 0, 0},
			{"calibrate", no_argument, 0, 0},
			{0, 0, 0, 0}
		};

		c = getopt_long_only(argc, argv, "", long_options, &option_index);

		/* no more options to parse */
		if (c == -1) break;

		/* unrecognized option */
		if (c == '?') {
			help(argv[0]);
			return 0;
		}

		switch (option_index) {
			/* h, help */
		case 0:
		case 1:
			help(argv[0]);
			return 0;
			break;

			/* d, device */
		case 2:
		case 3:
			dev = strdup(optarg);
			break;

			/* r, resolution */
		case 4:
		case 5:
			if (strcmp("960x720", optarg) == 0) {
				cd.width = 960;
				cd.height = 720;
			} else if (strcmp("640x480", optarg) == 0) {
				cd.width = 640;
				cd.height = 480;
			} else if (strcmp("320x240", optarg) == 0) {
				cd.width = 320;
				cd.height = 240;
			} else if (strcmp("160x120", optarg) == 0) {
				cd.width = 160;
				cd.height = 120;
			} else {
				fprintf(stderr, "ignoring unsupported resolution\n");
			}
			break;

			/* f, fps */
		case 6:
		case 7:
			fps = atoi(optarg);
			break;

			/* p, port */
		case 8:
		case 9:
			cd.stream_port = htons(atoi(optarg));
			break;

			/* v, version */
		case 10:
		case 11:
			printf("UVC Streamer Version: %s\n" \
               "Compilation Date....: %s\n" \
               "Compilation Time....: %s\n", SOURCE_VERSION, __DATE__, __TIME__);
			return 0;
			break;

			/* v, version */
		case 12:
		case 13:
			daemon = 1;
			break;

			/* c, control_port */
		case 14:
		case 15:
			cd.control_port = htons(atoi(optarg));
			break;
			/* disable_control */
		case 16:
			disable_control_port = 1;
			break;
		case 17:
		case 18:
			disable_control_port = 1;
			break;
		default:
			help(argv[0]);
			return 0;
		}
	}

	/* ignore SIGPIPE (send if transmitting to closed sockets) */
	signal(SIGPIPE, SIG_IGN);
	if (signal(SIGINT, signal_handler) == SIG_ERR) {
		fprintf(stderr, "could not register signal handler\n");
		exit(1);
	}

	/* fork to the background */
	if (daemon) {
		daemon_mode();
	}

	/* allocate webcam datastructure */
	cd.videoIn = (struct vdIn *) calloc(1, sizeof(struct vdIn));

	fprintf(stderr, "Using V4L2 device.....: %s\n", dev);
	fprintf(stderr, "Resolution............: %i x %i\n", cdata->width, cdata->height);
	fprintf(stderr, "frames per second.....: %i\n", fps);
	fprintf(stderr, "TCP port..............: %i\n", ntohs(cd.stream_port));
	if (disable_control_port == 1) {
		fprintf(stderr, "motor control server..: disabled\n");
	} else {
		fprintf(stderr, "motor control TCP port: %i\n", ntohs(cd.control_port));
	}


	/* open video device and prepare data structure */
	cd.video_dev = init_videoIn(cd.videoIn, dev, cd.width, cd.height, fps, V4L2_PIX_FMT_MJPEG, 1);
	if (cd.video_dev < 0) {
		fprintf(stderr, "init_VideoIn failed\n");
		exit(1);
	}

	/* open socket for server */
	sd = socket(PF_INET, SOCK_STREAM, 0);
	if (sd < 0) {
		fprintf(stderr, "socket failed\n");
		exit(1);
	}

	/* ignore "socket already in use" errors */
	if (setsockopt(sd, SOL_SOCKET, SO_REUSEADDR, &on, sizeof(on)) < 0) {
		perror("setsockopt(SO_REUSEADDR) failed");
		exit(1);
	}

	/* configure server address to listen to all local IPs */
	memset(&addr, 0, sizeof(addr));
	addr.sin_family = AF_INET;
	addr.sin_port = cd.stream_port;
	addr.sin_addr.s_addr = htonl(INADDR_ANY);
	if (bind(sd, (struct sockaddr*) &addr, sizeof(addr)) != 0) {
		fprintf(stderr, "bind failed\n");
		perror("Bind");
		exit(1);
	}

	/* start listening on socket */
	if (listen(sd, 10) != 0) {
		fprintf(stderr, "listen failed\n");
		exit(1);
	}

	/* start to read the camera, push picture buffers into global buffer */
	cd.videoIn->tmpbuffer = (unsigned char *) calloc(1, (size_t) cd.videoIn->framesizeIn);
	g_buf = (unsigned char *) calloc(1, (size_t) cd.videoIn->framesizeIn);

	vision_control_init(); //must be first to call;

	pthread_create(&cam, 0, cam_thread, NULL);
	pthread_detach(cam);

	pthread_create(&mind, 0, mind_thread, NULL);
	pthread_detach(mind);

	init_vision();
	init_controller();

	pthread_create(&uart_control, 0, &uart_control_read, NULL);
	pthread_detach(uart_control);

	/* start control server */
	if (disable_control_port == 0) {
		pthread_create(&cntrl, NULL, &uvcstream_control, cdata);
		pthread_detach(cntrl);
	}

	/* create a child for every client that connects */
	while (1) {
		int *pfd = (int *) calloc(1, sizeof(int));
		*pfd = accept(sd, 0, 0);
		pthread_create(&client, NULL, &client_thread, pfd);
		pthread_detach(client);

	}

	return 0;
}
示例#5
0
/******************************************************************************
Description.:
Input Value.:
Return Value:
******************************************************************************/
int main(int argc, char *argv[])
{
  char *input  = "input_uvc.so --resolution 640x480 --fps 5 --device /dev/video0";
  char *output[MAX_OUTPUT_PLUGINS];
  int daemon=0, i;

  output[0] = "output_http.so --port 8080";
  global.outcnt = 0;

  global.control = control;
  global.pidfile = NULL;

  /* parameter parsing */
  while(1) {
    int option_index = 0, c=0;
    static struct option long_options[] = \
    {
      {"h", no_argument, 0, 0},
      {"help", no_argument, 0, 0},
      {"i", required_argument, 0, 0},
      {"input", required_argument, 0, 0},
      {"o", required_argument, 0, 0},
      {"output", required_argument, 0, 0},
      {"v", no_argument, 0, 0},
      {"version", no_argument, 0, 0},
      {"b", no_argument, 0, 0},
      {"background", no_argument, 0, 0},
      {"p", required_argument, 0, 0},
      {"pidfile", required_argument, 0, 0},
      {0, 0, 0, 0}
    };

    c = getopt_long_only(argc, argv, "", long_options, &option_index);

    /* no more options to parse */
    if (c == -1) break;

    /* unrecognized option */
    if(c=='?'){ help(argv[0]); return 0; }

    switch (option_index) {
      /* h, help */
      case 0:
      case 1:
        help(argv[0]);
        return 0;
        break;

      /* i, input */
      case 2:
      case 3:
        input = strdup(optarg);
        break;

      /* o, output */
      case 4:
      case 5:
        output[global.outcnt++] = strdup(optarg);
        break;

      /* v, version */
      case 6:
      case 7:
        printf("MJPG Streamer Version: %s\n" \
               "Compilation Date.....: %s\n" \
               "Compilation Time.....: %s\n", SOURCE_VERSION, __DATE__, __TIME__);
        return 0;
        break;

      /* b, background */
      case 8:
      case 9:
        daemon=1;
        break;

      /* p, pidfile */
      case 10:
      case 11:
        global.pidfile = strdup(optarg);
        break;

      default:
        help(argv[0]);
        return 0;
    }
  }

  openlog("MJPG-streamer ", LOG_PID|LOG_CONS, LOG_USER);
  //openlog("MJPG-streamer ", LOG_PID|LOG_CONS|LOG_PERROR, LOG_USER);
  syslog(LOG_INFO, "starting application");

  /* fork to the background */
  if ( daemon ) {
    LOG("enabling daemon mode");
    daemon_mode();
  }

  /* initialise the global variables */
  global.stop      = 0;
  global.buf       = NULL;
  global.size      = 0;
  global.in.plugin = NULL;

  /* this mutex and the conditional variable are used to synchronize access to the global picture buffer */
  if( pthread_mutex_init(&global.db, NULL) != 0 ) {
    LOG("could not initialize mutex variable\n");
    closelog();
    exit(EXIT_FAILURE);
  }
  if( pthread_cond_init(&global.db_update, NULL) != 0 ) {
    LOG("could not initialize condition variable\n");
    closelog();
    exit(EXIT_FAILURE);
  }

  /* ignore SIGPIPE (send by OS if transmitting to closed TCP sockets) */
  signal(SIGPIPE, SIG_IGN);

  /* register signal handler for <CTRL>+C in order to clean up */
  if (signal(SIGINT, signal_handler) == SIG_ERR) {
    LOG("could not register signal handler\n");
    closelog();
    exit(EXIT_FAILURE);
  }

  /*
   * messages like the following will only be visible on your terminal
   * if not running in daemon mode
   */
  LOG("MJPG Streamer Version.: %s\n", SOURCE_VERSION);

  /* check if at least one output plugin was selected */
  if ( global.outcnt == 0 ) {
    /* no? Then use the default plugin instead */
    global.outcnt = 1;
  }

  /* open input plugin */
  global.in.handle = plugin_load(input, &global.in.plugin);

  global.in.init = dlsym(global.in.handle, "input_init");
  if ( global.in.init == NULL ) {
    LOG("%s\n", dlerror());
    exit(EXIT_FAILURE);
  }
  global.in.stop = dlsym(global.in.handle, "input_stop");
  if ( global.in.stop == NULL ) {
    LOG("%s\n", dlerror());
    exit(EXIT_FAILURE);
  }
  global.in.run = dlsym(global.in.handle, "input_run");
  if ( global.in.run == NULL ) {
    LOG("%s\n", dlerror());
    exit(EXIT_FAILURE);
  }
  /* try to find optional command */
  global.in.cmd = dlsym(global.in.handle, "input_cmd");
  global.in.cmd_new = dlsym(global.in.handle, "input_cmd_new");

  global.in.param.parameter_string = strchr(input, ' ');
  global.in.param.global = &global;

  if ( global.in.init(&global.in.param) ) {
    LOG("input_init() return value signals to exit");
    closelog();
    exit(0);
  }

  /* open output plugin */
  for (i=0; i<global.outcnt; i++) {
    global.out[i].handle = plugin_load(output[i], &global.out[i].plugin);

    global.out[i].init = dlsym(global.out[i].handle, "output_init");
    if ( global.out[i].init == NULL ) {
      LOG("%s\n", dlerror());
      exit(EXIT_FAILURE);
    }
    global.out[i].stop = dlsym(global.out[i].handle, "output_stop");
    if ( global.out[i].stop == NULL ) {
      LOG("%s\n", dlerror());
      exit(EXIT_FAILURE);
    }
    global.out[i].run = dlsym(global.out[i].handle, "output_run");
    if ( global.out[i].run == NULL ) {
      LOG("%s\n", dlerror());
      exit(EXIT_FAILURE);
    }
    /* try to find optional command */
    global.out[i].cmd = dlsym(global.out[i].handle, "output_cmd");

    global.out[i].param.parameter_string = strchr(output[i], ' ');
    global.out[i].param.global = &global;
    global.out[i].param.id = i;
    if ( global.out[i].init(&global.out[i].param) ) {
      LOG("output_init() return value signals to exit");
      closelog();
      exit(0);
    }
  }

  /* start to read the input, push pictures into global buffer */
  DBG("starting input plugin\n");
  syslog(LOG_INFO, "starting input plugin");
  if ( global.in.run() ) {
    LOG("can not run input plugin\n");
    closelog();
    return 1;
  }

  DBG("starting %d output plugin(s)\n", global.outcnt);
  for(i=0; i<global.outcnt; i++) {
    syslog(LOG_INFO, "starting output plugin: %s (ID: %02d)", global.out[i].plugin, global.out[i].param.id);
    global.out[i].run(global.out[i].param.id);
  }

  if (global.pidfile) {
    FILE *fp;
    pid_t mypid = getpid();

    if ((fp=fopen(global.pidfile, "w")) != NULL)
    {
        fprintf(fp, "%d", mypid);
        fclose(fp);
    }
  }

  /* wait for signals */
  pause();

  return 0;
}
示例#6
0
/******************************************************************************
Description.:
Input Value.:
Return Value:
******************************************************************************/
int main(int argc, char *argv[])
{
    //char *input  = "input_uvc.so --resolution 640x480 --fps 5 --device /dev/video0";
    char *input[MAX_INPUT_PLUGINS];
    char *output[MAX_OUTPUT_PLUGINS];
    int daemon = 0, i, j;
    size_t tmp = 0;

    output[0] = "output_http.so --port 8080";
    global.outcnt = 0;
    global.incnt = 0;

    /* parameter parsing */
    while(1) {
        int c = 0;
        static struct option long_options[] = {
            {"help", no_argument, NULL, 'h'},
            {"input", required_argument, NULL, 'i'},
            {"output", required_argument, NULL, 'o'},
            {"version", no_argument, NULL, 'v'},
            {"background", no_argument, NULL, 'b'},
            {NULL, 0, NULL, 0}
        };

        c = getopt_long(argc, argv, "hi:o:vb", long_options, NULL);

        /* no more options to parse */
        if(c == -1) break;

        switch(c) {
        case 'i':
            input[global.incnt++] = strdup(optarg);
            break;

        case 'o':
            output[global.outcnt++] = strdup(optarg);
            break;

        case 'v':
            printf("MJPG Streamer Version: %s\n" \
            "Compilation Date.....: %s\n" \
            "Compilation Time.....: %s\n",
#ifdef SVN_REV
            SVN_REV,
#else
            SOURCE_VERSION,
#endif
            __DATE__, __TIME__);
            return 0;
            break;

        case 'b':
            daemon = 1;
            break;

        case 'h': /* fall through */
        default:
            help(argv[0]);
            exit(EXIT_FAILURE);
        }
    }

    openlog("MJPG-streamer ", LOG_PID | LOG_CONS, LOG_USER);
    //openlog("MJPG-streamer ", LOG_PID|LOG_CONS|LOG_PERROR, LOG_USER);
    syslog(LOG_INFO, "starting application");

    /* fork to the background */
    if(daemon) {
        LOG("enabling daemon mode");
        daemon_mode();
    }

    /* ignore SIGPIPE (send by OS if transmitting to closed TCP sockets) */
    signal(SIGPIPE, SIG_IGN);

    /* register signal handler for <CTRL>+C in order to clean up */
    if(signal(SIGINT, signal_handler) == SIG_ERR) {
        LOG("could not register signal handler\n");
        closelog();
        exit(EXIT_FAILURE);
    }

    /*
     * messages like the following will only be visible on your terminal
     * if not running in daemon mode
     */
#ifdef SVN_REV
    LOG("MJPG Streamer Version: svn rev: %s\n", SVN_REV);
#else
    LOG("MJPG Streamer Version.: %s\n", SOURCE_VERSION);
#endif

    /* check if at least one output plugin was selected */
    if(global.outcnt == 0) {
        /* no? Then use the default plugin instead */
        global.outcnt = 1;
    }

    /* open input plugin */
    for(i = 0; i < global.incnt; i++) {
        /* this mutex and the conditional variable are used to synchronize access to the global picture buffer */
        if(pthread_mutex_init(&global.in[i].db, NULL) != 0) {
            LOG("could not initialize mutex variable\n");
            closelog();
            exit(EXIT_FAILURE);
        }
        if(pthread_cond_init(&global.in[i].db_update, NULL) != 0) {
            LOG("could not initialize condition variable\n");
            closelog();
            exit(EXIT_FAILURE);
        }

        tmp = (size_t)(strchr(input[i], ' ') - input[i]);
        global.in[i].stop      = 0;
        global.in[i].context   = NULL;
        global.in[i].buf       = NULL;
        global.in[i].size      = 0;
        global.in[i].plugin = (tmp > 0) ? strndup(input[i], tmp) : strdup(input[i]);
        global.in[i].handle = dlopen(global.in[i].plugin, RTLD_LAZY);
        if(!global.in[i].handle) {
            LOG("ERROR: could not find input plugin\n");
            LOG("       Perhaps you want to adjust the search path with:\n");
            LOG("       # export LD_LIBRARY_PATH=/path/to/plugin/folder\n");
            LOG("       dlopen: %s\n", dlerror());
            closelog();
            exit(EXIT_FAILURE);
        }
        global.in[i].init = dlsym(global.in[i].handle, "input_init");
        if(global.in[i].init == NULL) {
            LOG("%s\n", dlerror());
            exit(EXIT_FAILURE);
        }
        global.in[i].stop = dlsym(global.in[i].handle, "input_stop");
        if(global.in[i].stop == NULL) {
            LOG("%s\n", dlerror());
            exit(EXIT_FAILURE);
        }
        global.in[i].run = dlsym(global.in[i].handle, "input_run");
        if(global.in[i].run == NULL) {
            LOG("%s\n", dlerror());
            exit(EXIT_FAILURE);
        }
        /* try to find optional command */
        global.in[i].cmd = dlsym(global.in[i].handle, "input_cmd");

        global.in[i].param.parameters = strchr(input[i], ' ');

        for (j = 0; j<MAX_PLUGIN_ARGUMENTS; j++) {
            global.in[i].param.argv[j] = NULL;
        }

        split_parameters(global.in[i].param.parameters, &global.in[i].param.argc, global.in[i].param.argv);
        global.in[i].param.global = &global;
        global.in[i].param.id = i;

        if(global.in[i].init(&global.in[i].param, i)) {
            LOG("input_init() return value signals to exit\n");
            closelog();
            exit(0);
        }
    }

    /* open output plugin */
    for(i = 0; i < global.outcnt; i++) {
        tmp = (size_t)(strchr(output[i], ' ') - output[i]);
        global.out[i].plugin = (tmp > 0) ? strndup(output[i], tmp) : strdup(output[i]);
        global.out[i].handle = dlopen(global.out[i].plugin, RTLD_LAZY);
        if(!global.out[i].handle) {
            LOG("ERROR: could not find output plugin %s\n", global.out[i].plugin);
            LOG("       Perhaps you want to adjust the search path with:\n");
            LOG("       # export LD_LIBRARY_PATH=/path/to/plugin/folder\n");
            LOG("       dlopen: %s\n", dlerror());
            closelog();
            exit(EXIT_FAILURE);
        }
        global.out[i].init = dlsym(global.out[i].handle, "output_init");
        if(global.out[i].init == NULL) {
            LOG("%s\n", dlerror());
            exit(EXIT_FAILURE);
        }
        global.out[i].stop = dlsym(global.out[i].handle, "output_stop");
        if(global.out[i].stop == NULL) {
            LOG("%s\n", dlerror());
            exit(EXIT_FAILURE);
        }
        global.out[i].run = dlsym(global.out[i].handle, "output_run");
        if(global.out[i].run == NULL) {
            LOG("%s\n", dlerror());
            exit(EXIT_FAILURE);
        }

        /* try to find optional command */
        global.out[i].cmd = dlsym(global.out[i].handle, "output_cmd");

        global.out[i].param.parameters = strchr(output[i], ' ');

        for (j = 0; j<MAX_PLUGIN_ARGUMENTS; j++) {
            global.out[i].param.argv[j] = NULL;
        }
        split_parameters(global.out[i].param.parameters, &global.out[i].param.argc, global.out[i].param.argv);

        global.out[i].param.global = &global;
        global.out[i].param.id = i;
        if(global.out[i].init(&global.out[i].param, i)) {
            LOG("output_init() return value signals to exit\n");
            closelog();
            exit(EXIT_FAILURE);
        }
    }

    /* start to read the input, push pictures into global buffer */
    DBG("starting %d input plugin\n", global.incnt);
    for(i = 0; i < global.incnt; i++) {
        syslog(LOG_INFO, "starting input plugin %s", global.in[i].plugin);
        if(global.in[i].run(i)) {
            LOG("can not run input plugin %d: %s\n", i, global.in[i].plugin);
            closelog();
            return 1;
        }
    }

    DBG("starting %d output plugin(s)\n", global.outcnt);
    for(i = 0; i < global.outcnt; i++) {
        syslog(LOG_INFO, "starting output plugin: %s (ID: %02d)", global.out[i].plugin, global.out[i].param.id);
        global.out[i].run(global.out[i].param.id);
    }

    /* wait for signals */
    pause();

    return 0;
}
示例#7
0
文件: main.c 项目: sisoftrg/qico
int main(int argc,char **argv,char **envp)
{
	int c,daemon=-1,rc,sesstype=SESSION_EMSI,line=0,call_flags=0;
	char *hostname=NULL,*str=NULL;
	FTNADDR_T(fa);
#ifndef HAVE_SETPROCTITLE
	setargspace(argc,argv,envp);
#endif
#ifdef HAVE_SETLOCALE
 	setlocale(LC_ALL, "");
#endif
	while((c=getopt(argc, argv, "hI:da:ni:c:tbv"))!=EOF) {
		switch(c) {
		    case 'c':
			daemon=12;
			str=optarg;
			while(str&&*str) {
				switch(toupper(*str)) {
				    case 'N': call_flags=0; break;
				    case 'I': call_flags|=1; break;
				    case 'A': call_flags|=2; break;
				    default:  write_log("unknown call option: %c", *optarg);
					      exit(S_FAILURE);
				}
				str++;
			}
			break;
		    case 'i':
			hostname=optarg;
			break;
		    case 'I':
			configname=optarg;
			break;
		    case 'd':
			daemon=1;
			break;
		    case 'a':
			daemon=0;
			sesstype=SESSION_AUTO;
			if(!strncasecmp(optarg,"**emsi",6)||
			    !strncasecmp(optarg,"auto",4))sesstype=SESSION_EMSI;
#ifdef WITH_BINKP
			if(strncasecmp(optarg,"binkp",5)&&
			    (*optarg!=0x80||!optarg[1]||optarg[2]))break;
			sesstype=SESSION_BINKP;
		    case 'b':
			bink=1;
#endif
			break;
		    case 'n':
			daemon=2;
			break;
		    case 't':
			daemon=3;
			break;
		    case 'v':
			u_vers(progname);
		    default:
			usage(argv[0]);
		}
	}
	if(!hostname&&daemon<0)usage(argv[0]);
	getsysinfo();ssock=lins_sock=uis_sock=-1;
	if(!readconfig(configname)) {
		write_log("there was some errors parsing '%s', aborting",configname);
		exit(S_FAILURE);
	}
	if(!log_init(cfgs(CFG_MASTERLOG),NULL)) {
		write_log("can't open master log '%s'",ccs);
		exit(S_FAILURE);
	}
#ifdef NEED_DEBUG
	parse_log_levels();
	if(facilities_levels['C']>=1)dumpconfig();
#endif
	psubsts=parsesubsts(cfgfasl(CFG_SUBST));
#ifdef NEED_DEBUG
	if(facilities_levels['C']>=1) {
		subst_t *s;
		dialine_t *l;
		for(s=psubsts;s;s=s->next) {
			write_log("subst for %s [%d]",ftnaddrtoa(&s->addr),s->nhids);
			for(l=s->hiddens;l;l=l->next)
				write_log(" * %s,%s,%s,%d,%d",l->phone,l->host,l->timegaps,l->flags,l->num);
		}
	}
#endif
	log_done();
	if(daemon==3)exit(S_OK);
	if(hostname||daemon==12) {
		if(!parseftnaddr(argv[optind],&fa,&DEFADDR,0)) {
			write_log("can't parse address '%s'",argv[optind]);
			exit(S_FAILURE);
		}
		optind++;
	}
	if(hostname) {
		is_ip=1;
		rnode=xcalloc(1,sizeof(ninfo_t));
		xstrcpy(ip_id,"ipline",10);
		rnode->tty=bink?"binkp":"tcpip";
		if(!log_init(cfgs(CFG_LOG),rnode->tty)) {
			write_log("can't open log %s",ccs);
			exit(S_FAILURE);
		}
		signal(SIGINT,sigerr);
		signal(SIGTERM,sigerr);
		signal(SIGSEGV,sigerr);
		signal(SIGPIPE,SIG_IGN);
		IFPerl(perl_init(cfgs(CFG_PERLFILE),0));
		log_callback=NULL;xsend_cb=NULL;
		ssock=cls_conn(CLS_LINE,cfgs(CFG_SERVER),NULL);
		if(ssock<0)write_log("can't connect to server: %s",strerror(errno));
		    else log_callback=vlogs;

		rc=aso_init(cfgs(CFG_ASOOUTBOUND),cfgs(CFG_BSOOUTBOUND),cfgs(CFG_QSTOUTBOUND),cfgal(CFG_ADDRESS)->addr.z);
		if(!rc) {
			write_log("No outbound defined");
			stopit(S_FAILURE);
		}
		rc=do_call(&fa,hostname,NULL);
		aso_done();
		stopit(rc);
	}
	if(daemon==12) {
		if(optind<argc) {
			if(1!=sscanf(argv[optind],"%d",&line)) {
				write_log("can't parse line number '%s'!\n",argv[optind]);
				exit(S_FAILURE);
			}
		} else line = 0;

		log_callback=NULL;xsend_cb=NULL;
		ssock=cls_conn(CLS_LINE,cfgs(CFG_SERVER),NULL);
		if(ssock<0)write_log("can't connect to server: %s",strerror(errno));
		    else log_callback=vlogs;

		rc=aso_init(cfgs(CFG_ASOOUTBOUND),cfgs(CFG_BSOOUTBOUND),cfgs(CFG_QSTOUTBOUND),cfgal(CFG_ADDRESS)->addr.z);
		if(!rc) {
			write_log("No outbound defined");
			cls_close(ssock);
			exit(S_FAILURE);
		}
		if(aso_locknode(&fa,LCK_c)) {
			signal(SIGINT,sigerr);
			signal(SIGTERM,sigerr);
			signal(SIGSEGV,sigerr);
			signal(SIGPIPE,SIG_IGN);
			IFPerl(perl_init(cfgs(CFG_PERLFILE),0));
			rc=force_call(&fa,line,call_flags);
			aso_unlocknode(&fa,LCK_x);
		} else rc=S_FAILURE;
		if(rc&S_MASK)write_log("can't call to %s",ftnaddrtoa(&fa));
		aso_done();
		stopit(rc);
	}
	switch(daemon) {
	    case 1: daemon_mode(); break;
	    case 0: answer_mode(sesstype); break;
	    case 2: compile_nodelists(); break;
	}
	return S_OK;
}
示例#8
0
int main(int argc, char *argv[]) {
	int opt;
	bool daemon = true;

	atexit(close_sockets);
	while ((opt = getopt(argc, argv, "m:vf")) != -1)
		switch (opt) {
		case 'm':
			mux = connect_block(optarg, 5678);
			break;
		case 'v':
			verbose = true;
			daemon = false;
			break;
		case 'f':
			daemon = false;
			break;
		default:
			fatal("Usage: %s: -m mux:port [-v] [-f]\n", argv[0]);
		}
	if (mux < 0)
		mux = connect_block("localhost", 5678);
		
	if (daemon)
		daemon_mode();

	if (!bcm2835_init())
		fatal("initialising bcm2835\n");

	bcm2835_gpio_fsel(pin, BCM2835_GPIO_FSEL_OUTP);

	signal(SIGINT, signal_handler);
	signal(SIGPIPE, SIG_IGN);

	struct timeval last, now;
	last.tv_sec = 0;

	char buf[256];
	for (;;) {
		fd_set rd;
		FD_ZERO(&rd);
		FD_SET(mux, &rd);

		gettimeofday(&now, 0);
		if (now.tv_sec - last.tv_sec > idle_secs)
			bcm2835_gpio_write(pin, LOW);

		struct timeval dt;
		dt.tv_sec = idle_secs;
		dt.tv_usec = 0;
		if (0 > select(mux+1, &rd, 0, 0, &dt))
			fatal("select: %s\n", strerror(errno));

		if (FD_ISSET(mux, &rd)) {
			int n = sock_read_line(mux, buf, sizeof(buf));
			if (verbose)
				printf("%d: %d [%s]\n", mux, n, buf);
			if (n > 0) {
				sensor s;
				s.from_csv(buf);
				if (s.is_wireless()) {
					last.tv_sec = now.tv_sec;
					bcm2835_gpio_write(pin, LOW);
					bcm2835_delay(20);
					bcm2835_gpio_write(pin, HIGH);
				}
			} else if (n == 0)
				fatal("Mux died\n");
		}
	}
}
示例#9
0
文件: receiver.c 项目: yovio/LamPI
int main (int argc, char **argv)
{
	int r_pin = 1;							// This is the Raspberry Programmable Interrupt Number
	int t_pin = 15;							// XXX Txmit pin must be made an option on the commandline
	
	int is_eq;
	int i, j;								// counters
	int binary_length;


		
	// Vars for storing sniffer results
	int address = 0;
	int unit = 0;
	int dimlevel = 0;
	int value;
	
	// Vars for storing commandline options 
    int c;


	int jflg = 0;
    int tflg = 1;							// Standard action is test on commandline, no daemon
	int kflg = 0;							// Kaku remote messages
	int iflg = 0;							// Action remote messages
	int xflg = 0;							// Xclusive, only Kaku, Action and/or other well known defines messages
	int errflg = 0;
	char *hostname = "localhost";
	char *port = PORT;
	
    extern char *optarg;
    extern int optind, optopt;
	
	// Vars for statistics
	unsigned long a_short_cnt, a_short_sum, a_long_cnt, a_long_sum, a_short_min, a_short_max, a_long_min, a_long_max;
	unsigned long p_short_cnt, p_short_sum, p_long_cnt, p_long_sum, p_short_min, p_short_max, p_long_min, p_long_max;
	unsigned long k_short_cnt, k_short_sum, k_long_cnt, k_long_sum,	k_short_min, k_short_max, k_long_min, k_long_max;

	// ------------------------- COMMANDLINE OPTIONS SETTING ----------------------
	// Valid options are:
	// -h <hostname> ; hostname or IP address of the daemon
	// -p <port> ; Portnumber for daemon socket
	// -a ; Catch all, find out the protocol yourself
	// -v ; Verbose, Give detailed messages
	// -d ; Daemon mode, output to daemon over socket connection
	// -i ; Impuls switches such as used for Action remotes
	// -r <pin>; specify receive pin. Default is 1
	// -t <pin>; Specify transmit pin . Default is 15
	// -1 ; At least two equal messages in a row
	// -2 ; Equal to check -c
	// -3 ; Equal to check but now for 3 messages
	// -4 ; Equal to check but now for 4 messages
	// -k ; Show recognized Kaku messages of length 32 and 36 binary bits ONLY
	//
    while ((c = getopt(argc, argv, ":1234adh:ijkl:p:r:t:vx")) != -1) 
	{
        switch(c) {
		case '1':
			cflg=1;
		break;
		case '2':						// Check, we test for at least 2 the same binary codes
			cflg=2;
		break;
		case '3':
			if (dflg>0) errflg++;
			cflg=3;
		break;
		case '4':
			if (dflg>0) errflg++;
			cflg=4;
		break;
		case 'a':
			aflg++;
		break;
        case 'd':						// Daemon mode, use socket communications, wait 1sec in loop and no output
            tflg = 0;
            dflg++;
		break;
		case 'h':						// Socket communication
			if (tflg>0) errflg++;
            else dflg++;				// Need daemon flag too, (implied)
			hostname = optarg;
		break;
		case 'i':						// Impuls switches such as for Action
			iflg = 1;
		break;
		case 'j':						// For test/stdout output only, output a json string
			jflg = 1;
		break;
		case 'k':						// For test, enable kaku output
			if (dflg>0) errflg++;
			else tflg++;
			kflg++;
		break;
		case 'l':						// Low Pass filter setting
			low_pass = atoi(optarg);
			if ((low_pass<20) || (low_pass>pulse_time)) errflg++;
		break;
		case 'p':						// Port number
            port = optarg;
			if (tflg>0) errflg++;
            else dflg++;				// Need daemon flag too, (implied)
        break;
		case 'r':						// Receive pin
            r_pin = atoi(optarg);
		break;
        case 't':						// Transmit pin
			t_pin = atoi(optarg);
		break;
		case 'v':						// Verbose, output long timing/bit strings
			verbose = 1;
		break;
		case 'x':
			xflg++;
		break;
		case ':':       				// -f or -o without operand
			fprintf(stderr,"Option -%c requires an operand\n", optopt);
			errflg++;
		break;
		case '?':
			fprintf(stderr, "Unrecognized option: -%c\n", optopt);
            errflg++;
        }
    }
    if (errflg) {
        fprintf(stderr, "usage: argv[0] (options) \n");
		fprintf(stderr, "\nFor daemon use:\n");
		fprintf(stderr, "-d\t\t; Daemon use, will send received code to daemon on socket\n");
		fprintf(stderr, "\t\t; Daemon use cannot be combined with testing -t\n");
		fprintf(stderr, "\t\t; -v verbose and other settings produce more output in testing mode than in daemon\n");
		fprintf(stderr, "-h hostname\t; Specify the hostname or IP address to connect to. Default is localhost\n");
		fprintf(stderr, "-p port\t\t; Specify the portnumber to connect to. Default is 5000\n");
		fprintf(stderr, "-r pin\t\t; Specify receiver pin for wiringPi. Default is 1\n");
		fprintf(stderr, "-t pin\t\t; Specify trasmitter pin for wiringPi. Default is 15\n");
		fprintf(stderr, "-j\t\t; Json output, will output in json format\n");
		
		fprintf(stderr, "\nFor testing:\n");
		fprintf(stderr, "NOTE: Not using the -d flag implies test/commandline usage\n");
		fprintf(stderr, "\t\t; -v verbose and other settings produce more output in testing mode than in daemon\n");
		fprintf(stderr, "-1\t\t; Check, will check for 1 equal messages in sequence\n");
		fprintf(stderr, "-2\t\t; Check, will check for 2 equal messages in sequence\n");
		fprintf(stderr, "-3\t\t; Check, will check for 3 equal messages in sequence\n");
		fprintf(stderr, "-4\t\t; Check, will check for 4 equal messages in sequence\n");
		fprintf(stderr, "-k\t\t; Show kaku messages and gathers statistic (even is -v not set\n");
		
		fprintf(stderr, "\nOther settings:\n");
		fprintf(stderr, "-a\t\t; Show action/Impuls messages and their statistic (even is -v not set\n");
		fprintf(stderr, "-k\t\t; Show kaku messages and their statistic (even is -v not set\n");
		fprintf(stderr, "-l value\t; Low Pass, number of uSec at minimum that is needed to count as a edge/bit change\n");
		fprintf(stderr, "\t\t; Transmit pin\n");
		fprintf(stderr, "-v\t\t; Verbose, will output more information about the received codes\n");
		fprintf(stderr, "-x\t\t; Xclusive mode, only well known devices\n");
		
        exit (2);
    }

	if (verbose == 1) {
	
		printf("The following options have been set:\n\n");
		printf("-v\t; Verbose option\n");
		
		if (tflg>0) printf("-t\t; Test option\n");
		if (iflg>0) printf("-i\t; Impuls option\n");
		if (kflg>0) printf("-k\t; Kaku option\n");
		if (xflg>0) printf("-x\t; Xclusive (only well known message formats) option\n");
		if (cflg==1) printf("-1\t; Check for 1 same message option\n");
		if (cflg==2) printf("-2\t; Check for 2 additional same messages\n");
		if (cflg==3) printf("-3\t; Check for 3 additional same messages\n");
		if (jflg>0) printf("-j\t; Json option\n");
		if (aflg>0) printf("-a\t; Auto Adapt option (experimental)\n");
		if (dflg>0) {
			printf("-d\t; Daemon option\n");
			printf("Receiver    pin: %d\n",r_pin);
			printf("Transmitter pin: %d\n",t_pin);
			printf("Hostname: %s\n",hostname);
			printf("Port: %s\n",port);
		}
		printf("\n");
	}
	

	
	// ----------------- FOR TEST USE, SET THE VARIABLES -----------------------------
	if ((kflg > 0) || (iflg >0)) {
		a_short_cnt = 0; 	a_short_sum = 0;	a_long_cnt = 0;
		a_long_sum = 0;		a_short_min = 0;	a_short_max = 0;	a_long_min = 0;	a_long_max = 0;
		p_short_cnt = 0;	p_short_sum = 0;	p_long_cnt = 0;
		p_long_sum = 0;		p_short_min = 0;	p_short_max = 0;	p_long_min = 0;	p_long_max = 0;
		k_short_cnt = 0;	k_short_sum = 0;	k_long_cnt = 0;
		k_long_sum = 0;		k_short_min = 0;	k_short_max = 0;	k_long_min = 0;	k_long_max = 0;
	}

	// Catch ALL learning setting
	//	
	if (aflg > 0) {
		pulse_time = P_AUTO;
	}
	else {
		pulse_time = P_KAKU+P_ACTION/2;						// Value in between these two protocols
		pulse_long = 0;
	}
	
	// ------------------ SETUP WIRINGPI --------------------------------------------
	// Now start with setup wiringPI
	//
	
	wiringPiSetup ();
	wiringPiISR (r_pin, INT_EDGE_BOTH, &lampi_interrupt) ;
	


	// -------------------- START THE MAIN LOOP OF THE PROGRAM ------------------------
	// LOOP Forever. for testing purposes (only) not delay, for daemon mode wait every second
	// XXX In daemon mode we can also receive messages every second on the socket if we want
	
	// ---------------------------------------------------------------
	// DAEMON mode communication between two socket connections only
	// When verbose flag is on, the program will output messages

	if (dflg>0) {
	
		daemon_mode(hostname, port);

	}// if dflg


	// ---------------------------------------------------------------------
	// NON DAEMON
	else for (;;)
	{
		// Do we have a complete message!! 
		// stop_ints is set to 1 so we can print message and clean up
		//
		if ( (stop_ints == 1) || ((header > 0) && (footer > 0) && (pulse_long>0)) )
		{
			p_length = p_index;							// Copy the index pos as it may be modded by interrupt handler
			binary_length = 0;
			
			if (p_length <= p_min) {
			
				p_index = 0;
				header = 0;
				footer = 0;
				pulse_long = 0;
				stop_ints = 0;
				continue;
			}
			
			if (!((header > 0) && (footer>0)) ) {
				fprintf(stderr,"Error: stop_ints 1, but no header and/or footer");
			}
			
			// Decode pulse array into bit string based on type of message (length of p_index
			// Is this a Kaku message?
			//
			if (( p_length == 132 ) || (p_length == 148)) {
				
				binary_length = decode_pulse_kaku(pulse_array, binary);
				//printf("Decoding Kaku, length = %d \n",binary_length);
			}
			// Is this an Action/Impuls message? (We count 2 start sync pulses and 2 stop sync)
			else 
			if ( p_length == 52 ) {
				binary_length = decode_pulse_action(pulse_array, binary);
				//printf("Decoding Action, length = %d\n",binary_length);
			}
			
			// Xclusive flag: If the length of the decoded message less than length of 
			// action or kaku message stop further reporting. Good for debugging, not if we are not
			// interested in spurious messages from weather stations, alarm systems and other 433 stuff
			// in the neighbourhood.
			// XXX Careful, the check below is too simple to filter everything. binary_length != 12 or 32 or 36
			
			// If not a well-known message, discard it
			else if (xflg>0) {
				p_index = 0;
				header = 0;
				footer = 0;
				pulse_long = 0;
				stop_ints = 0;
				continue;
			}
			
			// Check? We need at least two identical codes 
			// For -1, One equal binary code extra needed
			// For -2 we will check 2 times
			// For -3 will make this 3 or more times!
			
			if ((cflg>0) && (binary_length > 0))	{
			
				// We check two or more codes with the binary, 
				// much easier than checking all non normalized
				is_eq = 1;
				for (i=0; i < binary_length; i++) { 
				
					if (checks == 0) { 
						chk_array[i] = binary[i]; 			// just copy
					}										
					else if (binary[i] != chk_array[i]) {
						is_eq = 0;
						break;
					}
				}
				if (is_eq == 0)	{							// NOT equal => reset counter and loop
					//printf("Check %d fail bit %d\n",checks,i);
					checks = 0;
					p_index = 0;
					header = 0;
					footer = 0;
					pulse_long = 0;
					stop_ints = 0;
					pulse_time = P_AUTO;				// Mwaaah
					continue;
				}
				else  
				if (checks < cflg) {
					// printf("Check %d success\n",checks);
					checks++;							// One extra check complete								
					p_index = 0;
					header = 0;
					footer = 0;
					pulse_long = 0;
					stop_ints = 0;
					continue;							// break to next loop, no printing further
				}
				
				// If is_eq == 1 and checks == cflg we continue here
				
			}// cflg
			checks = 0;
			
			printf("\n----- Results, checked %d times --------------------------------------------\n",cflg);
			
			if (verbose == 1) {
				printf("Timing code: <");
				for(i=0;i<p_length;i++) {
					printf("%d ",pulse_array[i]);
				}
				printf(">\n");
			}
				
			printf("Binary code: <");
				for(i=0;i<binary_length;i++) {
					printf("%d",binary[i]);
				}
				printf(">\n");
			
			
			//	------------------ PRINTING RESULTS ------------------------------
			// Now we have (optionally) checked the message, this must be a valid code for the remote/handset
			// We can now look at the low and high bits for this transmitter and determine the optimal value
			//
			if (verbose == 1) {
			
				printf("\n\n");

				if(normalize(header) == normalize(pulse_long)) {
					printf("header:\t\t0\n");
				} else {
					printf("header:\t\t%d,\t%d\n",header, normalize(header));
				}
				printf("pulse time:\t%d\n",pulse_time);			// XXX 
				printf("pulse_long:\t%d,\t%d\n",pulse_long, normalize(pulse_long));
				printf("footer:\t\t%d,\t%d\n",footer, normalize(footer));
				printf("p_length:\t%d\n",p_length);
				printf("binary_length:\t%d\n",binary_length);
				printf("stop_ints:\t%d\n",stop_ints);
				printf("\n");
				
				 
			}//if verbose
			
			// QQQ From here on, we work with data that is not influenced by interrupt handler anymore
			
			stop_ints=0;
			
			// If we recognize an impuls/Action message
			//
			if (binary_length == 12 ) {			
				
				address = 0; for (i=0; i<=4; i++) {
					address = address * 2;
					if (binary[i]==1) address += binary[i];
				}
				unit = 0; for (i=5; i<=9; i++) {			// Only the bitposition that is 0 is unit index, others float
					if (binary[i] == 0) {
						unit= i-5;
						continue;
					}
				}
				value = 0;
				if ((binary[10] == 0) && (binary[11]==2)) value = 0;		// Other bits are float
				else
				if ((binary[11] == 0) && (binary[10]==2)) value = 1;
				else 
				//
				// The following escapes below are for Chinese FOB that uses 2 encodings for a float!
				//
				if ((binary[10] == 0) && (binary[11]==3)) { value = 0; unit++; }
				else
				if ((binary[11] == 0) && (binary[10]==3)) { value = 1; unit++; }
				else value=-1;
				
				if ( (tflg>0) && (iflg>0) ) {
				
					p_short_cnt = 0;
					p_short_sum = 0;
					p_long_cnt = 0;
					p_long_sum = 0;
					p_long_min = 0;
					p_long_max = 0;
					p_short_min = 0;
					p_short_max = 0;
					
					// Skip header and footer bits 
					for (i=2; i<p_length-2; i++) {
						j = pulse_array[i];						// Store in tmp variable
						if (j < (2 * pulse_time)) {
							p_short_cnt++;
							p_short_sum += j;
							if ((j<p_short_min) || (p_short_min == 0)) p_short_min=j;
							if (j>p_short_max) p_short_max=j;
						}
						else {
							p_long_cnt++;
							p_long_sum += j;
							if ((j<p_long_min)||(p_long_min == 0)) p_long_min=j;
							if (j>p_long_max) p_long_max=j;
						}
					}
					a_short_cnt += p_short_cnt;
					a_short_sum += p_short_sum;
					a_long_cnt += p_long_cnt;
					a_long_sum += p_long_sum;
					if ((p_short_min < a_short_min) || (a_short_min == 0)) a_short_min=p_short_min;
					if (p_short_max > a_short_max) a_short_max=p_short_max;
					if ((p_long_min <a_long_min)||(a_long_min == 0)) a_long_min =p_long_min;
					if (p_long_max  > a_long_max)  a_long_max =p_long_max;
					
					printf(    "message count :\t\t%d\n", (int) ++socktcnt);
					printf(    "short pulses  :\t\t%d,\t\tthis:\t\t%d\n", (int) a_short_cnt,(int) p_short_cnt);
					if (p_short_cnt >0) 
						printf("short avg time:\t\t%d,\t\tthis:\t\t%d\n", (int)(a_short_sum/a_short_cnt),
																		  (int)(p_short_sum/p_short_cnt));
					else
						printf("short avg time:\t\t0\n");
					printf(    "Minimum short :\t\t%d,\t\tthis:\t\t%d\n", (int) a_short_min,(int) p_short_min);
					printf(    "Maximum short :\t\t%d,\t\tthis:\t\t%d\n", (int) a_short_max,(int) p_short_max);	
						
					printf(    "long  pulses  :\t\t%d,\t\tthis:\t\t%d\n", (int) a_long_cnt,(int) p_long_cnt);
					if (p_long_cnt >0)
						printf("long avg time :\t\t%d,\t\tthis:\t\t%d\n", (int)(a_long_sum/a_long_cnt),
																		  (int)(p_long_sum/p_long_cnt));
					else
						printf("long avg time :\t\t0");
					printf(    "Minimum long  :\t\t%d,\t\tthis:\t\t%d\n", (int) a_long_min,(int) p_long_min);
					printf(    "Maximum long  :\t\t%d,\t\tthis:\t\t%d\n", (int) a_long_max,(int) p_long_max);
				}
				
				printf("Found Action Switch: ");
				printf(" addr: %d, ",address);
				printf(" unit: %d",unit);
				printf(" value: %d ",value);
				printf ("\n------------------------------------------------------------------------\n");
			}
			else
			//
			// If we recognize a kaku command message, print it 
			// 
			if ((binary_length == 32 ) || (binary_length == 36)) {
						
				// bit 0 - 25: First 26 bits are address
				// bit     26: Group Bit
				// bit     27: on/off/dim bit
				// bit 28- 31: Unit Code
				// ** ONLY for dimmer in bit 27 **
				// bit 32- 36: dimmer value
				
				// Gather some more statistics for testing, specific for kaku
				// Use -k flag to gather these statistics. All values remain valid 
				// as long as the program runs
			
				if ( (tflg>0) && (kflg>0) ) {
				
					p_short_cnt = 0;
					p_short_sum = 0;
					p_long_cnt = 0;
					p_long_sum = 0;
					p_long_min = 0;
					p_long_max = 0;
					p_short_min = 0;
					p_short_max = 0;
					
					// Skip header and footer bits 
					for (i=2; i<p_length-1; i++) {
						j = pulse_array[i];
						if (j < (3 * pulse_time)) {
							p_short_cnt++;
							p_short_sum += j;
							if ((j<p_short_min) || (p_short_min == 0)) p_short_min=j;
							if (j>p_short_max) p_short_max=j;
						}
						else {
							p_long_cnt++;
							p_long_sum += j;
							if ((j<p_long_min)||(p_long_min == 0)) p_long_min=j;
							if (j>p_long_max) p_long_max=j;
						}
					}
					k_short_cnt += p_short_cnt;
					k_short_sum += p_short_sum;
					k_long_cnt += p_long_cnt;
					k_long_sum += p_long_sum;
					if ((p_short_min < k_short_min) || (k_short_min == 0)) k_short_min=p_short_min;
					if (p_short_max > k_short_max) k_short_max=p_short_max;
					if ((p_long_min <k_long_min)||(k_long_min == 0)) k_long_min =p_long_min;
					if (p_long_max  > k_long_max)  k_long_max =p_long_max;
					
					printf(    "message count :\t\t%d\n", (int) ++socktcnt);
					printf(    "short pulses  :\t\t%d,\t\tthis:\t\t%d\n", (int) k_short_cnt,(int) p_short_cnt);
					
					printf(    "Minimum short :\t\t%d,\t\tthis:\t\t%d\n", (int) k_short_min,(int) p_short_min);
					if (p_short_cnt >0) 
						printf("short avg time:\t\t%d,\t\tthis:\t\t%d\n", (int)(k_short_sum/k_short_cnt),
																		  (int)(p_short_sum/p_short_cnt));
					else
						printf("short avg time:\t\t0\n");
					printf(    "Maximum short :\t\t%d,\t\tthis:\t\t%d\n", (int) k_short_max,(int) p_short_max);	
					
					printf(    "long  pulses  :\t\t%d,\t\tthis:\t\t%d\n", (int) k_long_cnt,(int) p_long_cnt);
					printf(    "Minimum long  :\t\t%d,\t\tthis:\t\t%d\n", (int) k_long_min,(int) p_long_min);
					if (p_long_cnt >0)
						printf("long avg time :\t\t%d,\t\tthis:\t\t%d\n", (int)(k_long_sum/k_long_cnt),
																		  (int)(p_long_sum/p_long_cnt));
					else
						printf("long avg time :\t\t0");
					printf(    "Maximum long  :\t\t%d,\t\tthis:\t\t%d\n", (int) k_long_max,(int) p_long_max);
				}
			
				//
				// Do other Kaku output
				//
				address = 0; for (i=0; i<=25; i++) address = address * 2 + binary[i];
				unit = 0; for (i=28; i<=31; i++) unit = unit * 2 + binary[i];
									
				if (jflg == 1) {
					printf (" { ");
					printf("\"type\": \"switch\", ");
					printf ("\"address\": \"%d\", ",address);
					printf ("\"group\": \"%d\", ",binary[26]);
					printf ("\"status\": \"%d\", ",binary[27]);
					printf ("\"unit\": \"%d\"",unit);				/* remove trailing comma */
					if (binary_length == 36) {
						dimlevel = 0; for (i=32; i<=35; i++) dimlevel = dimlevel * 2 + binary[i];
						printf (", \"dim\": \"%d\"",dimlevel);		// add separation ","
					}
					printf (" } \n");
				}
				else {
					printf("Found Kaku Switch: ");
					printf(" addr: %d, ",address);
					printf(" group: %d ",binary[26]);
					printf(" on/off: %d ",binary[27]);
					printf(" unit: %d",unit);
					if (binary_length == 36) {
						dimlevel = 0; for (i=32; i<=35; i++) dimlevel = dimlevel * 2 + binary[i];
						printf(" dim: %d",dimlevel);
					}
					printf ("\n-------------------------------------------------------------------\n");
				}
			}
			fflush(stdout);
			
			// Now reset all variables for a next message
			
			header = 0;					// XXX For action stuff, footer is sync pulse (for next message)
			footer = 0;					// So we could copy this footer to new header
			pulse_long = 0;
			p_index = 0;
			stop_ints = 0;				// continue with interrupts
			pulse_time = P_AUTO;
			
		}// if message complete
		
	}// for;;;

	close(sockfd);
	exit (2);
}
示例#10
0
文件: sensor.c 项目: jcdude/LamPI-1.8
/* ********************************************************************
 * MAIN PROGRAM
 *
 * Read the user option of the commandline and either print to stdout
 * or return the value over the socket. 
 *
 * ********************************************************************	*/  
int main(int argc, char **argv)  
{  
	int i,c;
	int errflg = 0;
	int repeats = 1;
	int temp = 0;
	int temp_int, temp_frac;				// interger and fracture part for temperature
	
	char *hostname = "localhost";			// Default setting for our host == this host
	char *port = PORT;						// default port, 5000
	char snd_buf[256];
	
    extern char *optarg;
    extern int optind, optopt;

	// ------------------------- COMMANDLINE OPTIONS SETTING ----------------------
	// Valid options are:
	// -h <hostname> ; hostname or IP address of the daemon
	// -p <port> ; Portnumber for daemon socket
	// -v ; Verbose, Give detailed messages
	//
    while ((c = getopt(argc, argv, ":c:dh:p:r:stvx")) != -1) {
        switch(c) {

		case 'c':
			cflg = 1;					// Checks
			checks = atoi(optarg);
		break;
		case 'd':						// Daemon mode, cannot be together with test?
			dflg = 1;
		break;
		case 'h':						// Socket communication
            dflg++;						// Need daemon flag too, (implied)
			hostname = optarg;
		break;
		case 'p':						// Port number
            port = optarg;
           dflg++;						// Need daemon flag too, (implied)
        break;
		case 'r':						// repeats
			repeats = atoi(optarg);
		break;
		case 's':						// Statistics
			sflg = 1;
		break;
		case 't':						// Test Mode, do debugging
			debug=1;
		break;
		case 'v':						// Verbose, output long timing/bit strings
			verbose = 1;
		break;
		case ':':       				// -f or -o without operand
			fprintf(stderr,"Option -%c requires an operand\n", optopt);
			errflg++;
		break;
		case '?':
			fprintf(stderr, "Unrecognized option: -%c\n", optopt);
            errflg++;
        }
    }
	
	// -------------------- PRINT ERROR ---------------------------------------
	// Print error message if parsing the commandline
	// was not successful
	
    if (errflg) {
        fprintf(stderr, "usage: argv[0] (options) \n\n");
		
		fprintf(stderr, "-d\t\t; Daemon mode. Codes received will be sent to another host at port 5000\n");
		fprintf(stderr, "-s\t\t; Statistics, will gather statistics from remote\n");
		fprintf(stderr, "-t\t\t; Test mode, will output received code from remote\n");
		fprintf(stderr, "-v\t\t; Verbose, will output more information about the received codes\n");
        exit (2);
    }
	

	//	------------------ PRINTING Parameters ------------------------------
	//
	if (verbose == 1) {
		printf("The following options have been set:\n\n");
		printf("-v\t; Verbose option\n");
		if (statistics>0)	printf("-s\t; Statistics option\n");
		if (dflg>0)			printf("-d\t; Daemon option\n");
		if (debug)			printf("-t\t; Test and Debug option");
		printf("\n");						 
	}//if verbose
	
	// If we are in daemon mode, initialize sockets etc.
	//
	if (dflg) {
		daemon_mode(hostname, port);
	}
	
	if (sflg) {
		fprintf(stderr,"init statistics\n");
		init_statistics(statistics);			// Make cells 0
	}
	
	chdir (SPATH);
	
	// ------------------------
	// MAIN LOOP
	// 

	if (verbose) printf("\nRepeats: %d::\n",repeats);
	for (i=0; i<repeats; i++)  
	{  
		// For every directory found in SPATH
		DIR *dir;
		struct dirent *ent;
		if ((dir = opendir (SPATH)) != NULL) {
			/* print all the files and directories within directory */
			while ((ent = readdir (dir)) != NULL) {
				if (verbose) printf ("%s\n", ent->d_name);
				// 28 is the prefix for ds18b20
				if (strncmp(ent->d_name,"28",2) == 0)
				{
					temp = ds18b20_read(ent->d_name);
					temp_int = temp/1000;
					temp_frac = temp%1000;
					
					if (dflg) {
					// Daemon, output to socket
						sprintf(snd_buf, 					 "{\"tcnt\":\"%d\",\"action\":\"weather\",\"brand\":\"ds18b20\",\"type\":\"json\",\"address\":\"%s\",\"channel\":\"%d\",\"temperature\":\"%d.%d\",\"humidity\":\"%d\",\"windspeed\":\"%d\",\"winddirection\":\"%d\"}", 
						socktcnt%1000,
						ent->d_name,
						0,
						temp_int,
						temp_frac,
						0,
						0,
						0);
					
						// Do NOT use check_n_write_socket as weather stations will not
						// send too many repeating messages (1 or 2 will come in one trasmission)
						//
						if (write(sockfd, snd_buf, strlen(snd_buf)) == -1) {
							fprintf(stderr,"socket write error\n");
						}	
						socktcnt++;
						delay(200);
						
						if (verbose) printf("Buffer sent to Socket: %s\n",snd_buf);
					}
					else {
					// Commandline
						if (temp > 0) {
							printf("Temperature for dev %s: %d.%d\n",
								ent->d_name, temp/1000,temp%1000);
						}
						else {
							temp = -temp;
							printf("Temperature for dev %s: -%d.%d\n",
								ent->d_name, temp/1000,temp%1000);
						}
					}
				}
			}
			closedir (dir);
		} else {
  			/* could not open directory */
 			 perror ("No such directory ");
			return EXIT_FAILURE;
		}
	}
	delay(1500);
	// Should wait for confirmation of the daemon before closing
	
	exit(EXIT_SUCCESS); 
}  
示例#11
0
/* ********************************************************************
 * MAIN PROGRAM
 *
 * We use HIGE timers in order to see system performance with vmstat
 *
 * ********************************************************************	*/  
int main(int argc, char **argv)  
{  
	int i,c;
	int errflg = 0;
	int iflg = 0;
	int wflg = 0;							// WIringPI
	int repeats = 1;						// We can repeat readings
	int attempts = 0;						// How many attempts were necessary to be successful
	int fake = 0;
	
    extern char *optarg;
    extern int optind, optopt;
	
	mode = SOCK_STREAM;						// default Socket mode

	// ------------------------- COMMANDLINE OPTIONS SETTING ----------------------
	// Valid options are:
	// -h <hostname> ; hostname or IP address of the daemon
	// -p <port> ; Portnumber for daemon socket
	// -b ; Broadcast mode
	// -v ; Verbose, Give detailed messages
	// -w ; WiringPi mode
	//
    while ((c = getopt(argc, argv, ":bc:dfh:ip:r:stvw")) != -1) {
        switch(c) {
		case 'b':
			mode = SOCK_DGRAM;			// UDP Datagram Mode, broadcastoing
		break;
		case 'c':
			cflg = 1;					// Checks
			checks = atoi(optarg);
		break;
		case 'd':						// Daemon mode, cannot be together with test?
			dflg = 1;
		break;
		case 'f':
			fake = 1;
		break;
		case 'h':						// Socket communication
            dflg++;						// Need daemon flag too, (implied)
			hostname = optarg;
		break;
		case 'i':						// Interrupt (instead of waiting out).
			iflg=1;
			if (wflg) errflg++;
		break;
		case 'p':						// Port number
            port = optarg;
           dflg++;						// Need daemon flag too, (implied)
        break;
		case 'r':						// repeats
			repeats = atoi(optarg);
		break;
		case 's':						// Statistics
			sflg = 1;
		break;
		case 't':						// Test Mode, do debugging
			debug=1;
		break;
		case 'v':						// Verbose, output long timing/bit strings
			verbose = 1;
		break;
		case 'w':						// wiringpi library used
			wflg = 1;
			if (iflg) errflg++;
		break;
		case ':':       				// -f or -o without operand
			fprintf(stderr,"Option -%c requires an operand\n", optopt);
			errflg++;
		break;
		case '?':
			fprintf(stderr, "Unrecognized option: -%c\n", optopt);
            errflg++;
        }
    }
	
	// -------------------- PRINT ERROR ---------------------------------------
	// Print error message if parsing the commandline
	// was not successful
	
    if (errflg) {
        fprintf(stderr, "usage: argv[0] (options) \n\n");
		fprintf(stderr, "-b\t\t; Broadcast mode. Use UDP broadcasting\n");
		fprintf(stderr, "-d\t\t; Daemon mode. Codes received will be sent to another host at port 5000\n");
		fprintf(stderr, "-i\t\t; Interrupt based sensor processing\n");
		fprintf(stderr, "-w\t\t; WiringPI libs used for sensor processing\n");
		fprintf(stderr, "-s\t\t; Statistics, will gather statistics from remote\n");
		fprintf(stderr, "-r\t\t; Repeats, will gather statistics #repeats times\n");
		fprintf(stderr, "-t\t\t; Test mode, will output received code from remote\n");
		fprintf(stderr, "-v\t\t; Verbose, will output more information about the received codes\n");
        exit (2);
    }
	
	// ------------------ SETUP WIRINGPI --------------------------------------------
	// Now start with setup wiringPI
	//
	
	wiringPiSetup();

	//	------------------ PRINTING Parameters ------------------------------
	//
	if (verbose == 1) {
		printf("The following options have been set:\n\n");
		printf("-v\t; Verbose option\n");
		if (statistics>0)	printf("-s\t; Statistics option\n");
		if (dflg>0)			printf("-d\t; Daemon option\n");
		if (iflg>0)			printf("-i\t; Interrupt processing\n");
		if (wflg>0)			printf("-w\t; WIringPI library processing\n");
		if (debug)			printf("-t\t; Test and Debug option\n");
		if (repeats>=1)		printf("-r\t; Repeats: %d\n",repeats);
		if (mode != SOCK_STREAM) printf("-b\t; UDP Broadcasting option\n");
		printf("\n");						 
	}//if verbose
	
	// If we are in daemon mode, initialize sockets etc.
	//
	if (dflg) {
		daemon_mode(hostname, port, mode);
	}
	
	if (sflg) {
		fprintf(stderr,"init statistics\n");
		init_statistics(statistics);			// Make cells 0
	}
	
	// ------------------------
	// MAIN LOOP
	// 
	delay(500);								// Wait 2 secs before starting
	
	// We will initialize the interrupt handler to only react to a falling edge.
	// SO as every bit consists of a high pulse of 50 and a low pulse of either 28 or 75 usec
	// when we measure the falling edge only a 50+28 means a 0 and a 50+75usec flank means 1
	//
	if (iflg) {
		wiringPiISR (DHT22PIN, INT_EDGE_FALLING, &sensor_interrupt);
	}
	
	for (i=0; i<repeats; i++)  
	{  
		if (iflg) {
		// Use an interrupt routing, less resource consuming
			attempts = dht22_read_int(i);
		}
		else if (wflg) {
		// Make use of the special library for these devices in wiringPI
			attempts = dht22_read_wiring(i);
		}
		else if (fake) {
			attempts = 1;
			send_2_server(sockfd, 50, 10);
		}
		else {
		// Use the brute force method and wait all reads out
			attempts = dht22_read_old(i); 
		}
		
		if (attempts <= 100) {
			printf(" It took %d attempts to read\n",attempts);
		}
		else {
			printf(" dht22: Unable to read a value in 100 attempts\n");
		}
		delay(2000);							// wait 2.0 secs
	}
	
	// Close the socket to the daemon
	if (close(sockfd) == -1) {
		perror("Error closing socket to daemon");
	}
	exit(EXIT_SUCCESS); 
}  
示例#12
0
int main(int argc, char *argv[])
{
	int ret, len;
	context *pctx;
	input *in;
	char buf[512];
	int send = 0, backgroud = 0, i;

	for (i = 1; i < argc; i++) {
		if (!strcmp(argv[i], "tcp")) {
			send = 1;
		}
		if (!strcmp(argv[i], "deamon")) {
			backgroud = 1;
		}
	}
	if (backgroud)
		daemon_mode();

	pctx = calloc(1, sizeof(context));
	if (pctx == NULL) {
		DBG("error allocating context\n");
		return -ENOMEM;
	}

	if(signal(SIGINT, fatal_signal) == SIG_ERR) {
		DBG("could not register signal handler\n");
		return -EINVAL;
	}

	// create syslog
	openlog("iMX28-UVC", LOG_PID | LOG_CONS, LOG_USER);


	// get params from flash
	ret = params_load();
	if (ret < 0) {
		fprintf(stderr, "load nvram params failed...\n");
	}

	// open manage serial, 1152008N1
	ret = serial_init(NULL);
	if (ret < 0) {
		fprintf(stderr, "serial_init failed\n");
		free(pctx);
		closelog();
		return -1;
	}

	// register input video stream
	ret = input_init(pctx, UVCDEV);
	if (ret < 0) {
		fprintf(stderr, "input_init failed, exit\n");
		goto exit;
        }

	if (send) {
	    // register output video stream
            ret = output_init("192.168.0.99", 5500);	// tcp
	    if (ret < 0 ) {
		goto exit;
	    }
	}
	ret = input_run(pctx);
	if (ret < 0) {
		goto exit;	
	}

	if (send)
		ret = output_run(pctx->in);

	in = pctx->in;
	while (!stop && in) {
		/* save_jpeg(in->buf, in->size); */
		/* allow others to access the global buffer again */
		/* sys_if_test();	 */
		len = recv_packet(buf, sizeof(buf));
		if (len > 0) {
			hex_dump("SP0 RECV:", buf, len);
			packet_parse(pctx, buf, len);
		} 
	}

	/* wait for signals */
	pause();

	if (send)
		output_stop();
exit:
	if (pctx->in->buf)
		free(pctx->in->buf);
	free(pctx);
	closelog();
	serial_exit();
	DBG("%s:Exit\n", __func__);

	return 0;
}