コード例 #1
0
ファイル: gnokii.c プロジェクト: tal-nino/gnokii
static int parse_options(int argc, char *argv[])
{
	int c;
	int opt_index = -1;
	gn_error rc;

	/* Every option should be in this array. */
	static struct option long_options[] = {
		/* FIXME: these comments are nice, but they would be more useful as docs for the user */
		/* Display usage. */
		{ "help",               optional_argument, NULL, OPT_HELP },

		/* Display version and build information. */
		{ "version",            no_argument,       NULL, OPT_VERSION },

		/* Monitor mode */
		{ "monitor",            optional_argument, NULL, OPT_MONITOR },

		/* Alternate config file location */
		{ "config",             required_argument, NULL, OPT_CONFIGFILE },

		/* Alternate phone section from the config */
		{ "phone",              required_argument, NULL, OPT_CONFIGMODEL },

		/* Get Security Code */
		{ "getsecuritycode",    no_argument,   	   NULL, OPT_GETSECURITYCODE },

		/* Enter Security Code mode */
		{ "entersecuritycode",  required_argument, NULL, OPT_ENTERSECURITYCODE },

		/* Get Security Code status */
		{ "getsecuritycodestatus",  no_argument,   NULL, OPT_GETSECURITYCODESTATUS },

		/* Change Security Code */
		{ "changesecuritycode", required_argument, NULL, OPT_CHANGESECURITYCODE },

		/* Set date and time */
		{ "setdatetime",        optional_argument, NULL, OPT_SETDATETIME },

		/* Get date and time mode */
		{ "getdatetime",        no_argument,       NULL, OPT_GETDATETIME },

		/* Set alarm */
		{ "setalarm",           optional_argument, NULL, OPT_SETALARM },

		/* Get alarm */
		{ "getalarm",           no_argument,       NULL, OPT_GETALARM },

		/* Voice call mode */
		{ "dialvoice",          required_argument, NULL, OPT_DIALVOICE },

		/* Answer the incoming call */
		{ "answercall",         required_argument, NULL, OPT_ANSWERCALL },

		/* Hangup call */
		{ "hangup",             required_argument, NULL, OPT_HANGUP },

		/* Get ToDo note mode */
		{ "gettodo",		required_argument, NULL, OPT_GETTODO },

		/* Write ToDo note mode */
		{ "writetodo",          required_argument, NULL, OPT_WRITETODO },

		/* Delete all ToDo notes mode */
		{ "deletealltodos",     no_argument,       NULL, OPT_DELETEALLTODOS },

		/* Get calendar note mode */
		{ "getcalendarnote",    required_argument, NULL, OPT_GETCALENDARNOTE },

		/* Write calendar note mode */
		{ "writecalendarnote",  required_argument, NULL, OPT_WRITECALENDARNOTE },

		/* Delete calendar note mode */
		{ "deletecalendarnote", required_argument, NULL, OPT_DELCALENDARNOTE },

		/* Get display status mode */
		{ "getdisplaystatus",   no_argument,       NULL, OPT_GETDISPLAYSTATUS },

		/* Get memory mode */
		{ "getphonebook",       required_argument, NULL, OPT_GETPHONEBOOK },

		/* Write phonebook (memory) mode */
		{ "writephonebook",     optional_argument, NULL, OPT_WRITEPHONEBOOK },

		/* Delete phonebook entry from memory mode */
		{ "deletephonebook",    required_argument, NULL, OPT_DELETEPHONEBOOK },

		/* Get speed dial mode */
		{ "getspeeddial",       required_argument, NULL, OPT_GETSPEEDDIAL },

		/* Set speed dial mode */
		{ "setspeeddial",       required_argument, NULL, OPT_SETSPEEDDIAL },

		/* Create SMS folder mode */
		{ "createsmsfolder",    required_argument, NULL, OPT_CREATESMSFOLDER },

		/* Delete SMS folder mode */
		{ "deletesmsfolder",    required_argument, NULL, OPT_DELETESMSFOLDER },

		/* Show SMS folder names and its attributes */
		{ "showsmsfolderstatus",no_argument,       NULL, OPT_SHOWSMSFOLDERSTATUS },

		/* Get SMS message mode */
		{ "getsms",             required_argument, NULL, OPT_GETSMS },

		/* Delete SMS message mode */
		{ "deletesms",          required_argument, NULL, OPT_DELETESMS },

		/* Send SMS message mode */
		{ "sendsms",            required_argument, NULL, OPT_SENDSMS },

		/* Ssve SMS message mode */
		{ "savesms",            optional_argument, NULL, OPT_SAVESMS },

		/* Send logo as SMS message mode */
		{ "sendlogo",           required_argument, NULL, OPT_SENDLOGO },

		/* Send ringtone as SMS message */
		{ "sendringtone",       required_argument, NULL, OPT_SENDRINGTONE },

		/* Get ringtone */
		{ "getringtone",        required_argument, NULL, OPT_GETRINGTONE },

		/* Set ringtone */
		{ "setringtone",        required_argument, NULL, OPT_SETRINGTONE },

		/* Play ringtone */
		{ "playringtone",       required_argument, NULL, OPT_PLAYRINGTONE },

		/* Convert ringtone */
		{ "ringtoneconvert",    required_argument, NULL, OPT_RINGTONECONVERT },

		/* Get list of the ringtones */
		{ "getringtonelist",    no_argument,       NULL, OPT_GETRINGTONELIST },

		/* Delete ringtones */
		{ "deleteringtone",     required_argument, NULL, OPT_DELETERINGTONE },

		/* Get SMS center number mode */
		{ "getsmsc",            optional_argument, NULL, OPT_GETSMSC },

		/* Set SMS center number mode */
		{ "setsmsc",            no_argument,       NULL, OPT_SETSMSC },

		/* For development purposes: run in passive monitoring mode */
		{ "pmon",               no_argument,       NULL, OPT_PMON },

		/* NetMonitor mode */
		{ "netmonitor",         required_argument, NULL, OPT_NETMONITOR },

		/* Identify */
		{ "identify",           no_argument,       NULL, OPT_IDENTIFY },

		/* Send DTMF sequence */
		{ "senddtmf",           required_argument, NULL, OPT_SENDDTMF },

		/* Resets the phone */
		{ "reset",              required_argument, NULL, OPT_RESET },

		/* Set logo */
		{ "setlogo",            required_argument, NULL, OPT_SETLOGO },

		/* Get logo */
		{ "getlogo",            required_argument, NULL, OPT_GETLOGO },

		/* View logo */
		{ "viewlogo",           required_argument, NULL, OPT_VIEWLOGO },

		/* Show profile */
		{ "getprofile",         optional_argument, NULL, OPT_GETPROFILE },

		/* Set profile */
		{ "setprofile",         no_argument,       NULL, OPT_SETPROFILE },

		/* Get the active profile */
		{ "getactiveprofile",   no_argument,       NULL, OPT_GETACTIVEPROFILE },

		/* Set the active profile */
		{ "setactiveprofile",   required_argument, NULL, OPT_SETACTIVEPROFILE },

		/* Show texts from phone's display */
		{ "displayoutput",      no_argument,       NULL, OPT_DISPLAYOUTPUT },

		/* Simulate pressing the keys */
		{ "keysequence",        no_argument,       NULL, OPT_KEYPRESS },

		/* Simulate pressing the keys */
		{ "enterchar",          no_argument,       NULL, OPT_ENTERCHAR },

		/* Divert calls */
		{ "divert",		no_argument,       NULL, OPT_DIVERT },

		/* SMS reader */
		{ "smsreader",          no_argument,       NULL, OPT_SMSREADER },

		/* For development purposes: insert you function calls here */
		{ "foogle",             no_argument,       NULL, OPT_FOOGLE },

		/* Get WAP bookmark */
		{ "getwapbookmark",     required_argument, NULL, OPT_GETWAPBOOKMARK },

		/* Write WAP bookmark */
		{ "writewapbookmark",   required_argument, NULL, OPT_WRITEWAPBOOKMARK },

		/* Delete WAP bookmark */
		{ "deletewapbookmark",  required_argument, NULL, OPT_DELETEWAPBOOKMARK },

		/* Get WAP setting */
		{ "getwapsetting",      required_argument, NULL, OPT_GETWAPSETTING },

		/* Write WAP setting */
		{ "writewapsetting",    no_argument, 	   NULL, OPT_WRITEWAPSETTING },

		/* Activate WAP setting */
		{ "activatewapsetting", required_argument, NULL, OPT_ACTIVATEWAPSETTING },

		/* List GSM networks */
		{ "listnetworks",       no_argument,       NULL, OPT_LISTNETWORKS },

		/* Get network info */
		{ "getnetworkinfo",     no_argument,       NULL, OPT_GETNETWORKINFO },

		/* Get (sim)lock info */
		{ "getlocksinfo",       no_argument,       NULL, OPT_GETLOCKSINFO },

                /* Get file list */
		{ "getfilelist",        required_argument, NULL, OPT_GETFILELIST },

                /* Get file details by id */
		{ "getfiledetailsbyid", optional_argument, NULL, OPT_GETFILEDETAILSBYID },

                /* Get file id */
		{ "getfileid",          required_argument, NULL, OPT_GETFILEID },

                /* Get file */
		{ "getfile",            required_argument, NULL, OPT_GETFILE },

                /* Get file by id */
		{ "getfilebyid",        required_argument, NULL, OPT_GETFILEBYID },

		/* Get all files */
		{ "getallfiles",        required_argument, NULL, OPT_GETALLFILES },

                /* Put a file */
		{ "putfile",            required_argument, NULL, OPT_PUTFILE },

		/* Delete a file */
		{ "deletefile",         required_argument, NULL, OPT_DELETEFILE },

		/* Delete a file by id */
		{ "deletefilebyid",     required_argument, NULL, OPT_DELETEFILEBYID },

		/* Shell like interface */
		{ "shell",              no_argument, NULL, OPT_SHELL },

		/* Get MMS message mode */
		{ "getmms",             required_argument, NULL, OPT_GETMMS },

		/* Delete MMS message mode */
		{ "deletemms",          required_argument, NULL, OPT_DELETEMMS },

		/* Check if the phone responds */
		{ "ping",               no_argument, NULL, OPT_PING },

		{ 0, 0, 0, 0 },
	};

	/* Every command which requires arguments should have an appropriate entry
	   in this array. */
	static struct gnokii_arg_len gals[] = {
		{ OPT_HELP,              1, 100, 0 },
		{ OPT_CONFIGFILE,        1, 100, 0 },
		{ OPT_CONFIGMODEL,       1, 100, 0 },
		{ OPT_ENTERSECURITYCODE, 1, 100, 0 },
		{ OPT_CHANGESECURITYCODE,1, 1, 0 },
		{ OPT_SETDATETIME,       0, 5, 0 },
		{ OPT_SETALARM,          0, 2, 0 },
		{ OPT_DIALVOICE,         1, 1, 0 },
		{ OPT_ANSWERCALL,        1, 1, 0 },
		{ OPT_HANGUP,            1, 1, 0 },
		{ OPT_GETTODO,           1, 3, 0 },
		{ OPT_WRITETODO,         2, 3, 0 },
		{ OPT_GETCALENDARNOTE,   1, 3, 0 },
		{ OPT_WRITECALENDARNOTE, 2, 3, 0 },
		{ OPT_DELCALENDARNOTE,   1, 2, 0 },
		{ OPT_GETPHONEBOOK,      2, 4, 0 },
		{ OPT_WRITEPHONEBOOK,    0, 10, 0 },
		{ OPT_DELETEPHONEBOOK,   2, 3, 0 },
		{ OPT_GETSPEEDDIAL,      1, 1, 0 },
		{ OPT_SETSPEEDDIAL,      3, 3, 0 },
		{ OPT_CREATESMSFOLDER,   1, 1, 0 },
		{ OPT_DELETESMSFOLDER,   1, 1, 0 },
		{ OPT_GETSMS,            2, 6, 0 },
		{ OPT_DELETESMS,         2, 3, 0 },
		{ OPT_SENDSMS,           1, 10, 0 },
		{ OPT_SAVESMS,           0, 12, 0 },
		{ OPT_SENDLOGO,          3, 4, GAL_XOR },
		{ OPT_SENDRINGTONE,      2, 2, 0 },
		{ OPT_GETSMSC,           0, 3, 0 },
		{ OPT_GETWELCOMENOTE,    1, 1, 0 },
		{ OPT_SETWELCOMENOTE,    1, 1, 0 },
		{ OPT_NETMONITOR,        1, 1, 0 },
		{ OPT_SENDDTMF,          1, 1, 0 },
		{ OPT_SETLOGO,           1, 4, 0 },
		{ OPT_GETLOGO,           1, 4, 0 },
		{ OPT_VIEWLOGO,          1, 1, 0 },
		{ OPT_GETRINGTONE,       1, 3, 0 },
		{ OPT_SETRINGTONE,       1, 5, 0 },
		{ OPT_PLAYRINGTONE,      1, 3, 0 },
		{ OPT_RINGTONECONVERT,   2, 2, 0 },
		{ OPT_DELETERINGTONE,    1, 2, 0 },
		{ OPT_RESET,             0, 1, 0 },
		{ OPT_GETPROFILE,        0, 3, 0 },
		{ OPT_SETACTIVEPROFILE,  1, 1, 0 },
		{ OPT_DIVERT,            6, 10, 0 },
		{ OPT_GETWAPBOOKMARK,    1, 1, 0 },
		{ OPT_WRITEWAPBOOKMARK,  2, 2, 0 },
		{ OPT_DELETEWAPBOOKMARK, 1, 1, 0 },
		{ OPT_GETWAPSETTING,     1, 2, 0 },
		{ OPT_ACTIVATEWAPSETTING,1, 1, 0 },
		{ OPT_MONITOR,           0, 1, 0 },
		{ OPT_GETFILELIST,       1, 1, 0 },
		{ OPT_GETFILEDETAILSBYID,0, 1, 0 },
		{ OPT_GETFILEID,         1, 1, 0 },
		{ OPT_GETFILE,           1, 2, 0 },
		{ OPT_GETFILEBYID,       1, 2, 0 },
		{ OPT_GETALLFILES,       1, 1, 0 },
		{ OPT_PUTFILE,           2, 2, 0 },
		{ OPT_DELETEFILE,        1, 1, 0 },
		{ OPT_DELETEFILEBYID,    1, 1, 0 },
		{ OPT_SHELL,             0, 0, 0 },
		{ OPT_GETMMS,            2, 6, 0 },
		{ OPT_DELETEMMS,         2, 3, 0 },
		{ OPT_FOOGLE,            0, 0, 0 },
		{ OPT_PING,              0, 0, 0 },
		{ 0, 0, 0, 0 },
	};

	/* Handle command line arguments.
	 * -c equals to --config
	 * -p equals to --phone
	 */
	c = getopt_long(argc, argv, "c:p:", long_options, &opt_index);

	switch (c) {
	/* No argument given - we should display usage. */
	case -1:
		return usage(stderr, -1, NULL);
	/* First, error conditions */
	case '?':
	case ':':
		/* --shell command does not set argv[0] */
		if (argv[0])
			fprintf(stderr, _("Use '%s --help' for usage information.\n"), argv[0]);
		else
			fprintf(stderr, _("Use '--help' for usage information.\n"));
		return 1;
	/* Then, options with no arguments */
	case OPT_VERSION:
		version();
		return 0;
	/* That's a bit ugly... */
	case 'c':
		c = OPT_CONFIGFILE;
		opt_index = 0;
		break;
	case 'p':
		c = OPT_CONFIGMODEL;
		opt_index = 1;
		break;
	}

	/* We have to build an array of the arguments which will be passed to the
	   functions.  Please note that every text after the --command will be
	   passed as arguments.  A syntax like gnokii --cmd1 args --cmd2 args will
	   not work as expected; instead args --cmd2 args is passed as a
	   parameter. */
	if (checkargs(c, gals, argc, long_options[opt_index].has_arg)) {
		return usage(stderr, -1, NULL);
	}

	/* Other options that do not need initialization */
	switch (c) {
	case OPT_CONFIGFILE:
		if (configfile)
			return usage(stderr, -1, NULL);
		configfile = optarg;
		return parse_options(argc, argv);
	case OPT_CONFIGMODEL:
		if (configmodel)
			return usage(stderr, -1, NULL);
		configmodel = optarg;
		return parse_options(argc, argv);
	case OPT_HELP:
		return usage(stdout, argc, argv);
	case OPT_VIEWLOGO:
		return viewlogo(optarg);
	case OPT_LISTNETWORKS:
		list_gsm_networks();
		return GN_ERR_NONE;
	case OPT_RINGTONECONVERT:
		return ringtoneconvert(argc, argv);
	}

	/* Initialise the code for the GSM interface. */
	if (c != OPT_FOOGLE && state == NULL && businit())
		return -1;

	switch (c) {
	/* Monitoring options */
	case OPT_MONITOR:
		rc = monitormode(argc, argv, data, state);
		break;
	case OPT_GETDISPLAYSTATUS:
		rc = getdisplaystatus(data, state);
		break;
	case OPT_DISPLAYOUTPUT:
		rc = displayoutput(data, state);
		break;
	case OPT_NETMONITOR:
		rc = netmonitor(optarg, data, state);
		break;

	/* SMS options */
	case OPT_SENDSMS:
		rc = sendsms(argc, argv, data, state);
		break;
	case OPT_SAVESMS:
		rc = savesms(argc, argv, data, state);
		break;
	case OPT_GETSMS:
		rc = getsms(argc, argv, data, state);
		break;
	case OPT_DELETESMS:
		rc = deletesms(argc, argv, data, state);
		break;
	case OPT_GETSMSC:
		rc = getsmsc(argc, argv, data, state);
		break;
	case OPT_SETSMSC:
		rc = setsmsc(data, state);
		break;
	case OPT_CREATESMSFOLDER:
		rc = createsmsfolder(optarg, data, state);
		break;
	case OPT_DELETESMSFOLDER:
		rc = deletesmsfolder(optarg, data, state);
		break;
	case OPT_SHOWSMSFOLDERSTATUS:
		rc = showsmsfolderstatus(data, state);
		break;
	case OPT_SMSREADER:
		rc = smsreader(data, state);
		break;

	/* Phonebook options */
	case OPT_GETPHONEBOOK:
		rc = getphonebook(argc, argv, data, state);
		break;
	case OPT_WRITEPHONEBOOK:
		rc = writephonebook(argc, argv, data, state);
		break;
	case OPT_DELETEPHONEBOOK:
		rc = deletephonebook(argc, argv, data, state);
		break;

	/* Calendar options */
	case OPT_GETCALENDARNOTE:
		rc = getcalendarnote(argc, argv, data, state);
		break;
	case OPT_WRITECALENDARNOTE:
		rc = writecalendarnote(argc, argv, data, state);
		break;
	case OPT_DELCALENDARNOTE:
		rc = deletecalendarnote(argc, argv, data, state);
		break;

	/* ToDo options */
	case OPT_GETTODO:
		rc = gettodo(argc, argv, data, state);
		break;
	case OPT_WRITETODO:
		rc = writetodo(argc, argv, data, state);
		break;
	case OPT_DELETEALLTODOS:
		rc = deletealltodos(data, state);
		break;

	/* Dialling and call handling options */
	case OPT_GETSPEEDDIAL:
		rc = getspeeddial(optarg, data, state);
		break;
	case OPT_SETSPEEDDIAL:
		rc = setspeeddial(argv, data, state);
		break;
	case OPT_DIALVOICE:
		rc = dialvoice(optarg, data, state);
		break;
	case OPT_SENDDTMF:
		rc = senddtmf(optarg, data, state);
		break;
	case OPT_ANSWERCALL:
		rc = answercall(optarg, data, state);
		break;
	case OPT_HANGUP:
		rc = hangup(optarg, data, state);
		break;
	case OPT_DIVERT:
		rc = divert(argc, argv, data, state);
		break;

	/* Profile options */
	case OPT_GETPROFILE:
		rc = getprofile(argc, argv, data, state);
		break;
	case OPT_SETPROFILE:
		rc = setprofile(data, state);
		break;
	case OPT_GETACTIVEPROFILE:
		rc = getactiveprofile(data, state);
		break;
	case OPT_SETACTIVEPROFILE:
		rc = setactiveprofile(argc, argv, data, state);
		break;

	/* Phone settings options */
	case OPT_RESET:
		rc = reset(optarg, data, state);
		break;
	case OPT_GETDATETIME:
		rc = getdatetime(data, state);
		break;
	case OPT_SETDATETIME:
		rc = setdatetime(argc, argv, data, state);
		break;
	case OPT_GETALARM:
		rc = getalarm(data, state);
		break;
	case OPT_SETALARM:
		rc = setalarm(argc, argv, data, state);
		break;

	/* WAP options */
	case OPT_GETWAPBOOKMARK:
		rc = getwapbookmark(optarg, data, state);
		break;
	case OPT_WRITEWAPBOOKMARK:
		rc = writewapbookmark(argc, argv, data, state);
		break;
	case OPT_DELETEWAPBOOKMARK:
		rc = deletewapbookmark(optarg, data, state);
		break;
	case OPT_GETWAPSETTING:
		rc = getwapsetting(argc, argv, data, state);
		break;
	case OPT_WRITEWAPSETTING:
		rc = writewapsetting(data, state);
		break;
	case OPT_ACTIVATEWAPSETTING:
		rc = activatewapsetting(optarg, data, state);
		break;

	/* Logo options */
	case OPT_SENDLOGO:
		rc = sendlogo(argc, argv, data, state);
		break;
	case OPT_SETLOGO:
		rc = setlogo(argc, argv, data, state);
		break;
	case OPT_GETLOGO:
		rc = getlogo(argc, argv, data, state);
		break;

	/* Ringtone options */
	case OPT_SENDRINGTONE:
		rc = sendringtone(argc, argv, data, state);
		break;
	case OPT_GETRINGTONE:
		rc = getringtone(argc, argv, data, state);
		break;
	case OPT_SETRINGTONE:
		rc = setringtone(argc, argv, data, state);
		break;
	case OPT_PLAYRINGTONE:
		rc = playringtone(argc, argv, data, state);
		break;
	case OPT_GETRINGTONELIST:
		rc = getringtonelist(data, state);
		break;
	case OPT_DELETERINGTONE:
		rc = deleteringtone(argc, argv, data, state);
		break;

	/* Security options */
	case OPT_IDENTIFY:
		rc = identify(state);
		break;
	case OPT_GETLOCKSINFO:
		rc = getlocksinfo(data, state);
		break;
	case OPT_GETSECURITYCODE:
		rc = getsecuritycode(data, state);
		break;
	case OPT_ENTERSECURITYCODE:
		rc = entersecuritycode(optarg, data, state);
		if (rc == GN_ERR_NONE && optind < argc)
			return parse_options(argc, argv);
		break;
	case OPT_GETSECURITYCODESTATUS:
		rc = getsecuritycodestatus(data, state);
		break;
	case OPT_CHANGESECURITYCODE:
		rc = changesecuritycode(optarg, data, state);
			break;

	/* File options */
	case OPT_GETFILELIST:
		rc = getfilelist(optarg, data, state);
		break;
	case OPT_GETFILEDETAILSBYID:
		rc = getfiledetailsbyid(argc, argv, data, state);
		break;
	case OPT_GETFILEID:
		rc = getfileid(optarg, data, state);
		break;
	case OPT_GETFILE:
		rc = getfile(argc, argv, data, state);
		break;
	case OPT_GETFILEBYID:
		rc = getfilebyid(argc, argv, data, state);
		break;
	case OPT_GETALLFILES:
		rc = getallfiles(optarg, data, state);
		break;
	case OPT_PUTFILE:
		rc = putfile(argc, argv, data, state);
		break;
	case OPT_DELETEFILE:
		rc = deletefile(optarg, data, state);
		break;
	case OPT_DELETEFILEBYID:
		rc = deletefilebyid(optarg, data, state);
		break;

	/* Misc options */
	case OPT_PMON:
		rc = pmon(data, state);
		break;
	case OPT_KEYPRESS:
		rc = presskeysequence(data, state);
		break;
	case OPT_ENTERCHAR:
		rc = enterchar(data, state);
		break;
	case OPT_GETNETWORKINFO:
		rc = getnetworkinfo(data, state);
		break;
	case OPT_SHELL:
		rc = shell(data, state);
		break;
	case OPT_PING:
		rc = ping(data, state);
		break;
#ifndef WIN32
	case OPT_FOOGLE:
		rc = foogle(argc, argv);
		break;
#endif
	/* MMS options */
	case OPT_GETMMS:
		rc = getmms(argc, argv, data, state);
		break;
	case OPT_DELETEMMS:
		rc = deletemms(argc, argv, data, state);
		break;
	default:
		rc = GN_ERR_FAILED;
		fprintf(stderr, _("Unknown option: %d\n"), c);
		break;
	}
	return rc;
}
コード例 #2
0
ファイル: Server.cpp プロジェクト: berendeanicolae/P2P
/**
    @param[out] commands Vector to save the commands that must be executed by Application
    @param[in] timeOut The sleep time in select (100 by default)
*/
int Server::listening(vector<Message> &commands, int timeOut){
    fd_set readfds, writefds, errorfds; //multimile de descriptori de citire, scriere si eroare
    timeval timeout;
    sockaddr_in client = {};

    //creem multimile de descriptori
    FD_ZERO(&readfds);FD_ZERO(&writefds);FD_ZERO(&errorfds);
    FD_SET(0, &readfds); //includem tastatura in readfds
    FD_SET(udpsd, &readfds);

    timeout.tv_sec = timeOut/1000;
    timeout.tv_usec = timeOut%1000;
    select(nfds+1, &readfds, &writefds, &errorfds, &timeout);

    cleanUUIDs();

    /*
      Putem avea ori intrari de la tastatura (0), ori mesaje legate de retea (3), ori bucati de fisiere
    */
    //verificam separat stdin, stdout, stderr
    if (FD_ISSET(0, &readfds)){
        Message msg, comm;
        memset(msgBuffer, 0, sizeof(msgBuffer));
        if (read(0, msgBuffer, sizeof(msgBuffer))<=0){
            perror("[server] Eroare la citirea de la tastatura");
        }
        string input = msgBuffer;
		input.erase(input.end()-1, input.end());
        //input.pop_back(); //stergem caracterul linie noua
        if (input == "quit" || input == "exit"){
            msg.push_back(MSG_quit);
            commands.push_back(msg);
        }
        else if (!input.compare(0, strlen("search"), "search")){
            const char *uuid = getUUID();
            int sd = socket(AF_INET, SOCK_STREAM, 0); //socketul folosit pentru a comunica cu peers ce au fisierul
            sockaddr_in server={};
            server.sin_family = AF_INET;
            server.sin_addr.s_addr = htonl(INADDR_ANY);
            server.sin_port = htons(0);
            bind(sd, (sockaddr*)&server, sizeof(server));
            listen(sd, 5);
            //sockaddr_in tcpserver = {};
            //socklen_t sz = sizeof(tcpserver);

            //calculam expresia regulata
            input.erase(input.begin(), input.begin()+strlen("search"));
            stringStrip(input);
            printf("[Search] %s %s\n", input.c_str(), uuid);
            uuids[uuid] = getTicks();
            comm.push_back(MSG_request);
            comm.push_back(sizeof(sd), &sd);
            commands.push_back(comm);
            //trimit la toti peeri mesajul
            for (list<Peer>::iterator it=peers.begin(); it!=peers.end(); ++it){
                int ip=getIP(sd);
                unsigned short port=getPort(sd);

                msg.clear();
                msg.push_back(MSG_search);
                msg.push_back(40, uuid);
                msg.push_back(sizeof(ip), &ip);
                msg.push_back(sizeof(port), &port);
                msg.push_back(input.size(), input.c_str());

                sendto(udpsd, msg.getMessage(), msg.getSize(), 0, (sockaddr*)&it->address, sizeof(it->address));
            }
        }
        else{
        }
    }
    for (int d=3; d<=nfds; ++d){
        if (FD_ISSET(d, &errorfds)){
        }
        if (FD_ISSET(d, &readfds)){
            if (d==udpsd){
                MSG msgType;
                char ipString[40];
                int port, size;

                socklen_t sock_size = sizeof(client);
                if ((size=recvfrom(d, msgBuffer, 100, 0, (sockaddr*)&client, &sock_size))<=0){
                    printf("Clientul s-a inchis");
                    continue;
                }

                Message msg(size, msgBuffer);
                msg.pop_front(msgType);
                switch (msgType){
                    case MSG_connectAsServer:
                        printf("[server] Connection request P2P_connectAsServer\n");
                        serverPeers.push_back(client);
                    case MSG_connectAsPeer:
                        inet_ntop(client.sin_family, &client.sin_addr.s_addr, ipString, sizeof(ipString));
                        port = client.sin_port;
                        printf("[server] Connection request\n");
                        printf("[server] S-a conectat un peer %s %d\n", ipString, port);
                        peers.push_back(client);
                        sock_size = sizeof(client);
                        msg.clear();
                        msg.push_back(MSG_connectedOK);
                        sendto(udpsd, msg.getMessage(), msg.getSize(), 0, (sockaddr*)&client, sock_size);
                        ///inainte de push verificam sa nu fie in lista (nu e deja peer)
                        printf("[server] Numar total de conexiuni: %lu\n", peers.size());
                        break;
                    case MSG_pong:
                        inet_ntop(client.sin_family, &client.sin_addr.s_addr, ipString, sizeof(ipString));
                        port = client.sin_port;
                        for (list<Peer>::iterator it=peers.begin(); it!=peers.end(); ++it){
                            if (!memcmp(&it->address, &client, sizeof(it->address))){
                                ///client a raspuns la ping
                                printf("[server] Pong from %s %d\n", ipString, port);
                                it->lastPong = getTicks();
                                it->tries = 0;
                                break;
                            }
                        }
                        break;
                    case MSG_search:
                        commands.push_back(msg);
                        for (list<Peer>::iterator it=peers.begin(); it!=peers.end(); ++it){
                            sendto(udpsd, msg.getMessage(), msg.getSize(), 0, (sockaddr*)&it->address, sizeof(it->address));
                        }
                        break;
                    default:
                        printf("[server] Wrong option\n");
                }
            }
            else{
            }
        }
        if (FD_ISSET(d, &writefds)){
        }
    }
    ping();
    return 0; //maybe return value is not needed
}
コード例 #3
0
ファイル: dfs.c プロジェクト: 99years/plan9
/*
 * Rtt_tol is the fractional tollerance for RTT comparisons.
 * If a later (further down the list) host's RTT is less than
 * 1/Rtt_tol better than my current best then I don't bother
 * with it.  This biases me towards entries at the top of the list
 * which Active Directory has already chosen for me and prevents
 * noise in RTTs from pushing me to more distant machines.
 */
static int
remap(Dfscache *cp, Refer *re)
{
	int n;
	long rtt;
	char *p, *a[4];
	enum {
		Hostname = 1,
		Sharename = 2,
		Pathname = 3,

		Rtt_tol = 10
	};

	if(Debug && strstr(Debug, "dfs") != nil)
		print("	remap %s\n", re->addr);

	for(p = re->addr; *p; p++)
		if(*p == '\\')
			*p = '/';

	if(cp->prox < re->prox){
		if(Debug && strstr(Debug, "dfs") != nil)
			print("	remap %d < %d\n", cp->prox, re->prox);
		return -1;
	}
	if((n = getfields(re->addr, a, sizeof(a), 0, "/")) < 3){
		if(Debug && strstr(Debug, "dfs") != nil)
			print("	remap nfields=%d\n", n);
		return -1;
	}
	if((rtt = ping(a[Hostname], Dfstout)) == -1){
		if(Debug && strstr(Debug, "dfs") != nil)
			print("	remap ping failed\n");
		return -1;
	}
	if(cp->rtt < rtt && (rtt/labs(rtt-cp->rtt)) < Rtt_tol){
		if(Debug && strstr(Debug, "dfs") != nil)
			print("	remap bad ping %ld < %ld && %ld < %d\n",
				cp->rtt, rtt, (rtt/labs(rtt-cp->rtt)), Rtt_tol);
		return -1;
	}

	if(n < 4)
		a[Pathname] = "";
	if(re->ttl == 0)
		re->ttl = 60*5;

	free(cp->host);
	free(cp->share);
	free(cp->path);
	cp->rtt = rtt;
	cp->prox = re->prox;
	cp->expiry = time(nil)+re->ttl;
	cp->host = estrdup9p(a[Hostname]);
	cp->share = estrdup9p(trimshare(a[Sharename]));
	cp->path = estrdup9p(a[Pathname]);
	if(Debug && strstr(Debug, "dfs") != nil)
		print("	remap ping OK prox=%d host=%s share=%s path=%s\n",
			cp->prox, cp->host, cp->share, cp->path);
	return 0;
}
コード例 #4
0
RawBot::msg_vector RawBot::OnError(const jsoncons::json& msg) {
  const auto& data = msg.get("data", jsoncons::json(""));
  std::cout << "Server: Error - " << data.to_string() << std::endl;
  return ping();
}
コード例 #5
0
ファイル: Servotor32.cpp プロジェクト: LingDar/Hexy
void Servotor32::processChar(char inChar){
  switch(inChar){
    case '#':
      servoCounting = true;
      numCount = 0;
      inServo = -1;
      inPos = -1;
      break;
    case 'D':
      printStatus();
      break; 
    case 'P':
      if(servoCounting){
        inServo = tallyCount();
        servoCounting = false;
      }
      posCounting =  true;
      numCount = 0;
      break; 
    case '\r':
    case '\n':
      if(posCounting){
        inPos = tallyCount();
        posCounting = false;
      }
      if((inServo >=0)&&(inServo <=31)&&(((inPos >= 500)&&(inPos <= 2500))||(inPos == -1))){
        changeServo(inServo,inPos);        
        inServo = -1;
        inPos = -1;
      }
      numCount = 0;
      break;
    case 'V':
      Serial.println("SERVOTOR32_v2.0");
      Serial1.println("SERVOTOR32_v2.0");
      break;
    case 'C':
      for(int i=0; i<32; i++){
        changeServo(i, 1500);
      }
      Serial.println("All Centered");
      Serial1.println("All Centered");
      break;
    case 'K':
      for(int i=0; i<32; i++){
        changeServo(i,-1);
      }
      Serial.println("All Turned Off");
      Serial1.println("All Turned Off");
      break;
    case 'L':
      if(servoCounting){
        inServo = tallyCount();
        servoCounting = false;
      }
      changeServo(inServo, -1);
      break;
    case 'Q':
      Serial.print("CM: ");
      Serial.println(ping());
      Serial1.print("CM: ");
      Serial1.println(multiPing(10));
    default:
      if((inChar > 47)&&(inChar < 58)){
        if(numCount<4){
          numString[numCount] = inChar-48;
          numCount++;
        }
      }
      break;
  } 
}
コード例 #6
0
void Framework::loop()
{
	/* main loop variable */
	bool done = false;
	/* used to collect events */
	SDL_Event event;

	/* wait for events */
	while (!done)
	{
		/* handle the events in the queue */
		while (SDL_PollEvent(&event))
		{
			switch(event.type)
			{
			case SDL_MOUSEMOTION:
				/* give away mouse movement with buttons pressed */
				handleMouseMove(event.motion.xrel, event.motion.yrel, event.motion.state);
				break;
			case SDL_MOUSEBUTTONUP:
				/* handle mouse button release for serving */
				if (event.button.button == SDL_BUTTON_LEFT)
					if (!paused) serveBall();
			case SDL_KEYDOWN:
				/* handle key presses */
				handleKeyPress(&event.key.keysym);
				break;
			case SDL_QUIT:
				/* handle quit requests */
				done = true;
				break;
			case SDL_USEREVENT:
				if (((TimerData*)event.user.data1)->timer == NULL)
				{
					/* this means our timer has gone inactive and we are pleased to stop our work! */
				} else {
					((TimerData*)event.user.data1)->receiver->action(((TimerData*)event.user.data1)->event);
				}
				break;
			}
		}
		int tdiff = SDL_GetTicks() - lasttime;
		if (tdiff > timeunit) {
			frames++;
			xdiff += tdiff; // always greater 0 because we decided to let tdiff be greater than timeunit
			if ((xdiff >= 500)&&(xdiff >= timeunit * 25)) {
				output.updateFPS(frames * 1000.0 / xdiff); // There are 1000 ticks / second
				frames = 0;
				xdiff = 0;
				ping();
			}
			lasttime += tdiff;

			// Multiplayer code
			doNetworking();

			// Game status code
			updateGame(tdiff);

			// Rendering code
			drawScene();
		}
	}
}
コード例 #7
0
int main(int argc, char *argv[])
{
    if(argc < 2)
    {
        fprintf(stderr, "Invalid arguments. Usage: %s <interface>\n", argv[0]);
        return -1;
    }
    struct hostent *hname;
    struct sockaddr_in addr;

    int pid;
    struct protoent *proto;
    char ip_prefix[20],ipadd[20];
    //gets ip prefix for e.g. if ip is 172.17.14.10, below function will return 172.17.14.
    getip_prefix(getip(argv[1]),ip_prefix);
    int i,j;

    char str[3];

    //Check for root permissions
    if(getuid()!=0)
    {
        perror("Root permissions are required to run the program\n");
        exit(-1);
    }

    //Creating shared memory for storing the icmp response for the requested ip. Host part of the ip would be used
    //as array index.
    int shmid;
    shmid=shmget(IPC_PRIVATE,255*sizeof(int),0);
    shmarr=(int *)shmat(shmid,NULL,0);

    //fill the array with some value other than 0 as icmp response type which would be stored in the array
    // would be zero.
    initialize(shmarr);

    printf("Scanning online hosts\n");

    for(i=1;i<MAXHOSTS;i++)
    {
        //Will ping all the host ips in different processes to speed up.
        if(fork()==0)
        {
            bzero(ipadd,20);
            bzero(str,3);

            sprintf(str,"%d",i);
            strcpy(ipadd,ip_prefix);

            int t=(int)strlen(ip_prefix);

            //Creating host ip address by appending host part to the ip prefix.
            for(j=0;j<strlen(str);j++)
                ipadd[t+j]=str[j];

            //pid required for icmp id
            pid = getpid();
            proto = getprotobyname("ICMP");
            hname = gethostbyname(ipadd);

            bzero(&addr, sizeof(addr));
            addr.sin_family = (sa_family_t )hname->h_addrtype;
            addr.sin_port = 0;
            addr.sin_addr.s_addr = (in_addr_t )*(long*)hname->h_addr;

            //now ping the host.
            ping(&addr,pid,proto);
            exit(0);
        }
        else
        {
            // if(i%100==0)
            // 	sleep(10);
            continue;
        }
    }
    //make parent sleep
    sleep(10);

    printf("Online hosts\n");
    int ct=0;

    for(i=1;i<MAXHOSTS;i++)
    {
        if(shmarr[i]==0)
        {
            printf("%s%d\n",ip_prefix,i );
            ct++;
        }
    }
    printf("Total %d hosts online\n",ct);

    //wait for all the childs to exit
    wait(0);

    return 0;
}
コード例 #8
0
ファイル: module.c プロジェクト: walgenbach/lustre-release
static int libcfs_ioctl_int(struct cfs_psdev_file *pfile,unsigned long cmd,
                            void *arg, struct libcfs_ioctl_data *data)
{
        int err = -EINVAL;
        ENTRY;

        switch (cmd) {
        case IOC_LIBCFS_CLEAR_DEBUG:
                libcfs_debug_clear_buffer();
                RETURN(0);
        /*
         * case IOC_LIBCFS_PANIC:
         * Handled in arch/cfs_module.c
         */
        case IOC_LIBCFS_MARK_DEBUG:
                if (data->ioc_inlbuf1 == NULL ||
                    data->ioc_inlbuf1[data->ioc_inllen1 - 1] != '\0')
                        RETURN(-EINVAL);
                libcfs_debug_mark_buffer(data->ioc_inlbuf1);
                RETURN(0);
#if LWT_SUPPORT
        case IOC_LIBCFS_LWT_CONTROL:
                err = lwt_control ((data->ioc_flags & 1) != 0, 
                                   (data->ioc_flags & 2) != 0);
                break;

        case IOC_LIBCFS_LWT_SNAPSHOT: {
                cfs_cycles_t   now;
                int            ncpu;
                int            total_size;

                err = lwt_snapshot (&now, &ncpu, &total_size,
                                    data->ioc_pbuf1, data->ioc_plen1);
                data->ioc_u64[0] = now;
                data->ioc_u32[0] = ncpu;
                data->ioc_u32[1] = total_size;

                /* Hedge against broken user/kernel typedefs (e.g. cycles_t) */
                data->ioc_u32[2] = sizeof(lwt_event_t);
                data->ioc_u32[3] = offsetof(lwt_event_t, lwte_where);

                if (err == 0 &&
                    libcfs_ioctl_popdata(arg, data, sizeof (*data)))
                        err = -EFAULT;
                break;
        }

        case IOC_LIBCFS_LWT_LOOKUP_STRING:
                err = lwt_lookup_string (&data->ioc_count, data->ioc_pbuf1,
                                         data->ioc_pbuf2, data->ioc_plen2);
                if (err == 0 &&
                    libcfs_ioctl_popdata(arg, data, sizeof (*data)))
                        err = -EFAULT;
                break;
#endif
        case IOC_LIBCFS_MEMHOG:
                if (pfile->private_data == NULL) {
                        err = -EINVAL;
                } else {
                        kportal_memhog_free(pfile->private_data);
                        /* XXX The ioc_flags is not GFP flags now, need to be fixed */
                        err = kportal_memhog_alloc(pfile->private_data,
                                                   data->ioc_count,
                                                   data->ioc_flags);
                        if (err != 0)
                                kportal_memhog_free(pfile->private_data);
                }
                break;

        case IOC_LIBCFS_PING_TEST: {
		extern void (kping_client)(struct libcfs_ioctl_data *);
		void (*ping)(struct libcfs_ioctl_data *);

		CDEBUG(D_IOCTL, "doing %d pings to nid %s (%s)\n",
		       data->ioc_count, libcfs_nid2str(data->ioc_nid),
		       libcfs_nid2str(data->ioc_nid));
		ping = symbol_get(kping_client);
		if (!ping) {
			CERROR("symbol_get failed\n");
		} else {
			ping(data);
			symbol_put(kping_client);
		}
		RETURN(0);
	}

        default: {
                struct libcfs_ioctl_handler *hand;
                err = -EINVAL;
		down_read(&ioctl_list_sem);
                cfs_list_for_each_entry_typed(hand, &ioctl_list,
                        struct libcfs_ioctl_handler, item) {
                        err = hand->handle_ioctl(cmd, data);
                        if (err != -EINVAL) {
                                if (err == 0)
                                        err = libcfs_ioctl_popdata(arg, 
                                                        data, sizeof (*data));
                                break;
                        }
                }
		up_read(&ioctl_list_sem);
                break;
        }
        }

        RETURN(err);
}
コード例 #9
0
ファイル: WirelessNode_Impl.cpp プロジェクト: crosvera/MSCL
    AutoBalanceResult WirelessNode_Impl::autoBalance(const ChannelMask& mask, float targetPercent)
    {
        Utils::checkBounds_min(targetPercent, 0.0f);
        Utils::checkBounds_max(targetPercent, 100.0f);

        //attempt a few pings first 
        //(legacy (v1) autobalance doesn't have a response packet, so need to check communication)
        uint8 retryCounter = 0;
        bool pingSuccess = false;
        while(!pingSuccess && retryCounter < 3)
        {
            pingSuccess = ping().success();
            retryCounter++;
        }

        if(!pingSuccess)
        {
            throw Error_NodeCommunication(nodeAddress());
        }

        //find the eeprom location that the autobalance will adjust
        //Note: this also verifies that it is supported for this mask
        const EepromLocation& eepromLoc = features().findEeprom(WirelessTypes::chSetting_autoBalance, mask);

        //currently, autobalance is always per channel, so get the channel from the mask
        uint8 channelNumber = mask.lastChEnabled();

        AutoBalanceResult result;

        //perform the autobalance command with the parent base station
        m_baseStation.node_autoBalance(protocol(), m_address, channelNumber, targetPercent, result);

        //clear the cache of the hardware offset eeprom location we adjusted
        eeprom().clearCacheLocation(eepromLoc.location());

        Utils::threadSleep(200);

        //if we used the legacy command, we don't get result info, need to do more work to get it
        if(result.m_errorCode == WirelessTypes::autobalance_legacyNone)
        {
            result.m_errorCode = WirelessTypes::autobalance_maybeInvalid;

            //force the read eeprom retries to a minimum of 3
            uint8 startRetries = m_eepromSettings.numRetries;

            //when this goes out of scope, it will change back the original retries value
            ScopeHelper writebackRetries(std::bind(&WirelessNode_Impl::setReadWriteRetries, this, startRetries));

            //if there are less than 10 retries
            if(startRetries < 10)
            {
                //we want to retry at least a few times
                setReadWriteRetries(10);
            }
            else
            {
                //don't need to write back the retries since we didn't make a change
                writebackRetries.cancel();
            }

            //read the updated hardware offset from the node
            result.m_hardwareOffset = readEeprom(eepromLoc).as_uint16();

            bool readSensorSuccess = false;

            uint8 readSensorTry = 0;
            do
            {
                //perform the read single sensor command
                uint16 sensorVal = 0;
                readSensorSuccess = m_baseStation.node_readSingleSensor(m_address, channelNumber, sensorVal);

                if(readSensorSuccess)
                {
                    //find the max bits value of the node
                    uint32 maxBitsVal = 0;
                    switch(model())
                    {
                        case WirelessModels::node_vLink:
                        case WirelessModels::node_sgLink_rgd:
                        case WirelessModels::node_shmLink:
                            maxBitsVal = 65536;
                            break;

                        default:
                            maxBitsVal = 4096;
                            break;
                    }

                    //calculate and store the percent achieved
                    result.m_percentAchieved = static_cast<float>(sensorVal) / static_cast<float>(maxBitsVal) * 100.0f;
                }

                readSensorTry++;
            }
            while(!readSensorSuccess && readSensorTry <= 3);

            if(readSensorSuccess)
            {
                //mark as questionable if not close enough to the target percentage
                if(std::abs(result.m_percentAchieved - targetPercent) > 5.0)
                {
                    result.m_errorCode = WirelessTypes::autobalance_maybeInvalid;
                }
                else
                {
                    result.m_errorCode = WirelessTypes::autobalance_success;
                }
            }
        }

        return result;
    }
コード例 #10
0
ファイル: parasol.c プロジェクト: elmargb/kentUtils
void parasol(char *command, int argc, char *argv[])
/* parasol - Parasol program - for launching programs in parallel on a computer cluster. */
{
char *subType = argv[0];

hubRudp = rudpMustOpen();
if (sameString(command, "add"))
    {
    if (argc < 1)
        usage();
    if (sameString(subType, "machine"))
	{
	if (argc != 3 && argc != 8)
	    usage();
	addMachine(argc, argv);
	}
    else if (sameString(subType, "job"))
	{
	if (argc < 2)
	    usage();
        addJob(argc-1, argv+1, optionExists("verbose"));
	}
    else if (sameString(subType, "spoke"))
        addSpoke();
    else
        usage();
    }
else if (sameString(command, "clear"))
    {
    if (argc != 1)
	usage();
    if (sameString(subType, "sick"))
	{
        clearSickBatch();
	}
    else
        usage();
    }
else if (sameString(command, "check"))
    {
    if (argc != 1)
	usage();
    if (sameString(subType, "dead"))
	{
        checkDeadNodesASAP();
	}
    else
        usage();
    }
else if (sameString(command, "remove"))
    {
    if (argc < 2)
        usage();
    if (sameString(subType, "machine"))
	{
	if (argc < 3)
	    usage();
        removeMachine(argv[1],argv[2]);
	}
    else if (sameString(subType, "job"))
        removeJob(argv[1]);
    else if (sameString(subType, "jobs"))
        removeUserJobs(argv[1], argc-2, argv+2);
    else
        usage();
    }
else if (sameString(command, "list"))
    {
    if (argc != 1)
        usage();
    if (sameString(subType, "machine") || sameString(subType, "machines"))
        hubCommandAndPrint("listMachines");
    else if (sameString(subType, "job") || sameString(subType, "jobs"))
	{
        if (optionExists("extended"))
	    hubCommandAndPrint("listJobsExtended");
        else
	    hubCommandAndPrint("listJobs");
	}
    else if (sameString(subType, "user") || sameString(subType, "users"))
        hubCommandAndPrint("listUsers");
    else if (sameString(subType, "batch") || sameString(subType, "batches"))
        hubCommandAndPrint("listBatches");
    else if (sameString(subType, "sick"))
        hubCommandAndPrint("listSick");
    else
        usage();
    }
else if (sameString(command, "pstat"))
    {
    pstat();
    }
else if (sameString(command, "pstat2"))
    {
    pstat2();
    }
else if (sameString(command, "plan"))
    {
    hubCommandAndPrint("plan");
    }
else if (sameString(command, "ping"))
    {
    int count = 1;
    if (argc >= 1)
        {
	if (!isdigit(argv[0][0]))
	    usage();
	count = atoi(argv[0]);
	}
    ping(count);
    }
else if (sameString(command, "status"))
    status();
else if (sameString(command, "flushResults"))
    {
    if (argc != 0)
        usage();
    flushResults();
    }
/* Not providing at this time for fear of abuse 
else if (sameString(command, "freeBatch"))
    {
    if (argc != 0)
        usage();
    freeBatch();
    }
*/
else
    usage();
}
コード例 #11
0
ファイル: SRF08.cpp プロジェクト: rafafloripa/OpenDaVINCI
unsigned int SRF08::getDistance(){
	return ping();
}
コード例 #12
0
bool TransportObjectFactory::validateObject(const InetSocketAddress& /*address*/, TcpTransport& transport) {
    return ping(transport) == SUCCESS;
}
コード例 #13
0
void CAdministrationWindow::ping()
{
  ping(mysql());
}
コード例 #14
0
CAdministrationWindow::CAdministrationWindow(QWidget* parent,  CMySQLServer *m)
: CMyWindow(parent, "CAdministrationWindow")
{
  (void)statusBar();

  blocked = false;
  myApp()->incCritical();
  setCaption("[" + m->connectionName() + "] " + trUtf8("Administration Panel"));
  setIcon(getPixmapIcon("applicationIcon"));
  enableMessageWindow(true);  

  if (!m->oneConnection())
  {
    m_mysql = new CMySQLServer(m->connectionName(), messagePanel());
    m_mysql->connect();
    delete_mysql = true;
  }
  else
  {
    m_mysql = m;  //POSIBLE BUG ... need to make m_mysql redirect messages & errors to this->messagePanel() also.  Currently they are in consoleWindow()
    //probably need to disable the timer !
    delete_mysql = false;
  }

  setCentralWidget( new QWidget( this, "qt_central_widget"));
  CAdministrationWindowLayout = new QGridLayout( centralWidget(), 1, 1, 4, 2, "CAdministrationWindowLayout"); 
  
  tabWidget = new QTabWidget( centralWidget(), "tabWidget");  
  
  processList = new CProcessListTable(tabWidget, m_mysql);
  tabWidget->insertTab(processList, getPixmapIcon("showProcessListIcon"), tr("Process List"), SHOW_PROCESSLIST);

  status = new CServerStatusTable(tabWidget, m_mysql);
  tabWidget->insertTab(status, getPixmapIcon("showStatusIcon"), tr("Status"), SHOW_STATUS);

  variables = new CShowServerVariables(tabWidget, m_mysql);
  tabWidget->insertTab(variables, getPixmapIcon("showVariablesIcon"), tr("Variables"), SHOW_VARIABLES);

  save_menu = new QPopupMenu(this);
  connect(save_menu, SIGNAL(activated(int)), this, SLOT(save(int)));
  save_menu->insertItem(getPixmapIcon("showProcessListIcon"), tr("&Process List"), MENU_SAVE_PROCESSLIST);
  save_menu->insertItem(getPixmapIcon("showStatusIcon"), tr("&Status"), MENU_SAVE_STATUS);
  save_menu->insertItem(getPixmapIcon("showVariablesIcon"), tr("&Variables"), MENU_SAVE_VARIABLES);
  save_menu->insertItem(tr("&InnoDB Status"), MENU_SAVE_INNODB_STATUS);

  has_innodb = CInnoDBStatus::hasInnoDB(m_mysql);
  if (has_innodb)
  {
    innoDBStatus = new CInnoDBStatus(tabWidget, m_mysql);
    tabWidget->insertTab(innoDBStatus, tr("InnoDB Status"), SHOW_INNODB_STATUS);    
  }
  else
    save_menu->setItemEnabled(MENU_SAVE_INNODB_STATUS, false);
  
  CAdministrationWindowLayout->addWidget( tabWidget, 0, 0 );

  viewShowMessagesAction = new CAction (tr("Show Messages"), tr("Show &Messages"), Qt::CTRL + Qt::Key_M,
    this, "fileShowMessagesAction", true);
  viewShowMessagesAction->setParentMenuText(tr("View"));
  connect(viewShowMessagesAction, SIGNAL(toggled(bool)), this, SLOT(showMessages(bool)));
  
  CAction * fileCloseAction = new CAction (tr("Close"), getPixmapIcon("closeIcon"),
    tr("&Close"), 0, this, "fileCloseAction");
  fileCloseAction->setParentMenuText(tr("File"));        
  connect(fileCloseAction, SIGNAL(activated()), this, SLOT(close()));


  fileRefreshAction = new CAction (tr("Refresh"), getPixmapIcon("refreshIcon"),
    tr("&Refresh"), Qt::Key_F5, this, "fileRefreshAction");
  fileRefreshAction->setParentMenuText(tr("File"));
  connect(fileRefreshAction, SIGNAL(activated()), this, SLOT(refresh()));


  actionKillProcessAction = new CAction (tr("Kill Process"), getPixmapIcon("killProcessIcon"),
    tr("&Kill Process"), Qt::CTRL + Qt::Key_K, this, "actionKillProcessAction");
  actionKillProcessAction->setParentMenuText(tr("Action"));
  connect(actionKillProcessAction, SIGNAL(activated()), this, SLOT(killProcesses()));

  CAction * actionPingAction = new CAction (tr("Ping"), getPixmapIcon("pingIcon"),
    tr("&Ping"), Qt::CTRL + Qt::Key_P, this, "actionPingAction");
  actionPingAction->setParentMenuText(tr("Action"));
  connect(actionPingAction, SIGNAL(activated()), this, SLOT(ping()));

  CAction * actionShutdownAction = new CAction (tr("Shutdown"), getPixmapIcon("serverShutdownIcon"),
    tr("&Shutdown"), 0, this, "actionShutdownAction");
  actionShutdownAction->setParentMenuText(tr("Action"));
  connect(actionShutdownAction, SIGNAL(activated()), this, SLOT(shutdown()));

  fileTimerAction = new CAction (tr("Start Refresh Timer"), getPixmapIcon("timerIcon"),
    tr("Start Refresh &Timer"), Qt::CTRL + Qt::Key_T, this, "fileTimerAction", true);
  fileTimerAction->setParentMenuText(tr("File"));
  connect(fileTimerAction, SIGNAL(toggled(bool)), this, SLOT(fileTimerActionToggled(bool)));

  QPopupMenu *fileMenu = new QPopupMenu(this);
  QPopupMenu *actionMenu = new QPopupMenu(this);
  QPopupMenu *viewMenu = new QPopupMenu(this);
  connect(viewMenu, SIGNAL(aboutToShow()), this, SLOT(viewMenuAboutToShow()));

  fileMenu->insertItem(getPixmapIcon("saveIcon"), tr("Save"), save_menu);
  fileMenu->insertSeparator();
  fileRefreshAction->addTo(fileMenu);
  fileMenu->insertSeparator();
  fileTimerAction->addTo(fileMenu);
  fileMenu->insertSeparator();
  fileCloseAction->addTo(fileMenu);
  menuBar()->insertItem(tr("&File"), fileMenu);

  viewShowMessagesAction->addTo(viewMenu);
  menuBar()->insertItem(tr("&View"), viewMenu);

  actionKillProcessAction->addTo(actionMenu);

  flush_menu = flushMenu(m_mysql->mysql());
  connect(flush_menu, SIGNAL(activated(int)), this, SLOT(flush(int)));

  actionMenu->insertItem(getPixmapIcon("flushIcon"),tr("Flush"), flush_menu);

  actionPingAction->addTo(actionMenu);
  actionMenu->insertSeparator();
  actionShutdownAction->addTo(actionMenu);
  menuBar()->insertItem(tr("&Action"), actionMenu);

  new CHotKeyEditorMenu(this, menuBar(), "HotKeyEditor");

  QToolBar * actionToolBar = new QToolBar(tr("Action Bar"), this, Top);

  QToolButton * saveTypeButton = new QToolButton(actionToolBar);
  saveTypeButton->setPopup(save_menu);
  saveTypeButton->setPixmap(getPixmapIcon("saveIcon"));
  saveTypeButton->setTextLabel(tr("Save"), true);
  saveTypeButton->setPopupDelay(0);
  actionToolBar->addSeparator();

  actionKillProcessAction->addTo(actionToolBar);
  
  QToolButton * flushTypeButton = new QToolButton(actionToolBar);  
  flushTypeButton->setPopup(flush_menu);
  flushTypeButton->setPixmap(getPixmapIcon("flushIcon"));
  flushTypeButton->setTextLabel(tr("Flush"), true);
  flushTypeButton->setPopupDelay(0);    

  actionPingAction->addTo(actionToolBar);
  actionToolBar->addSeparator();
  actionShutdownAction->addTo(actionToolBar);

  QToolBar * refreshToolBar = new QToolBar(tr("Refresh Bar"), this, Top );  
  fileRefreshAction->addTo(refreshToolBar);  
  refreshToolBar->addSeparator();
 
  QLabel * delayLabel = new QLabel(refreshToolBar, "delayLabel" ); 
  delayLabel->setMinimumSize(QSize(65, 0));
  delayLabel->setText(tr("Refresh Rate (sec)"));
  
  delay = new QSpinBox(refreshToolBar, "delayBox");  
  delay->setMinimumSize(QSize( 50, 0)); 
  delay->setMaxValue(7200);
  delay->setMinValue(1);

  CConfig *cfg = new CConfig();  
  delay->setValue(cfg->readNumberEntry("Refresh Rate", 30));
  status->setTraditionalMode(strtobool(cfg->readStringEntry("Status Traditional Mode", "true")));
  delete cfg;
  status->refresh();  

  fileTimerAction->addTo(refreshToolBar);

  refreshTimer = new QTimer(this);
  connect(refreshTimer, SIGNAL(timeout()), this, SLOT(refresh()));

  connect(tabWidget, SIGNAL(currentChanged (QWidget *)), this, SLOT(tabChanged(QWidget *)));
  myResize(600, 400);
}
コード例 #15
0
quint32 VolumeBarLogic::volume ()
{
    ping ();

    return currentvolume;
}
コード例 #16
0
ファイル: player.c プロジェクト: brabsmit/pianobar
static bool openStream (player_t * const player) {
	assert (player != NULL);
	/* no leak? */
	assert (player->fctx == NULL);

	int ret;

	/* stream setup */
	AVDictionary *options = NULL;
#ifdef HAVE_AV_TIMEOUT
	/* 10 seconds timeout on TCP r/w */
	av_dict_set (&options, "timeout", "10000000", 0);
#else
	/* libav does not support the timeout option above. the workaround stores
	 * the current time with ping() now and then, registers an interrupt
	 * callback (below) and compares saved/current time in this callback. it’s
	 * not bullet-proof, but seems to work fine for av_read_frame. */
	player->fctx = avformat_alloc_context ();
	player->fctx->interrupt_callback.callback = intCb;
	player->fctx->interrupt_callback.opaque = player;
#endif

	assert (player->url != NULL);
	ping ();
	if ((ret = avformat_open_input (&player->fctx, player->url, NULL, &options)) < 0) {
		softfail ("Unable to open audio file");
	}

	ping ();
	if ((ret = avformat_find_stream_info (player->fctx, NULL)) < 0) {
		softfail ("find_stream_info");
	}

	/* ignore all streams, undone for audio stream below */
	for (size_t i = 0; i < player->fctx->nb_streams; i++) {
		player->fctx->streams[i]->discard = AVDISCARD_ALL;
	}

	ping ();
	player->streamIdx = av_find_best_stream (player->fctx, AVMEDIA_TYPE_AUDIO,
			-1, -1, NULL, 0);
	if (player->streamIdx < 0) {
		softfail ("find_best_stream");
	}

	player->st = player->fctx->streams[player->streamIdx];
	AVCodecContext * const cctx = player->st->codec;
	player->st->discard = AVDISCARD_DEFAULT;

	/* decoder setup */
	AVCodec * const decoder = avcodec_find_decoder (cctx->codec_id);
	if (decoder == NULL) {
		softfail ("find_decoder");
	}

	if ((ret = avcodec_open2 (cctx, decoder, NULL)) < 0) {
		softfail ("codec_open2");
	}

	if (player->lastTimestamp > 0) {
		ping ();
		av_seek_frame (player->fctx, player->streamIdx, player->lastTimestamp, 0);
	}

	player->songPlayed = 0;
	player->songDuration = av_q2d (player->st->time_base) *
			(double) player->st->duration;
	player->mode = PLAYER_PLAYING;

	return true;
}
コード例 #17
0
quint32 VolumeBarLogic::maxVolume ()
{
    ping ();

    return currentmax;
}
コード例 #18
0
ファイル: player.c プロジェクト: brabsmit/pianobar
/*	decode and play stream. returns 0 or av error code.
 */
static int play (player_t * const player) {
	assert (player != NULL);

	AVPacket pkt;
	av_init_packet (&pkt);
	pkt.data = NULL;
	pkt.size = 0;

	AVFrame *frame = NULL, *filteredFrame = NULL;
	frame = avcodec_alloc_frame ();
	assert (frame != NULL);
	filteredFrame = avcodec_alloc_frame ();
	assert (filteredFrame != NULL);

	while (!player->doQuit) {
		ping ();
		int ret = av_read_frame (player->fctx, &pkt);
		if (ret < 0) {
			av_free_packet (&pkt);
			return ret;
		} else if (pkt.stream_index != player->streamIdx) {
			av_free_packet (&pkt);
			continue;
		}

		AVPacket pkt_orig = pkt;

		/* pausing */
		pthread_mutex_lock (&player->pauseMutex);
		while (true) {
			if (!player->doPause) {
				av_read_play (player->fctx);
				break;
			} else {
				av_read_pause (player->fctx);
			}
			pthread_cond_wait (&player->pauseCond, &player->pauseMutex);
		}
		pthread_mutex_unlock (&player->pauseMutex);

		do {
			int got_frame = 0;

			const int decoded = avcodec_decode_audio4 (player->st->codec,
					frame, &got_frame, &pkt);
			if (decoded < 0) {
				/* skip this one */
				break;
			}

			if (got_frame != 0) {
				/* XXX: suppresses warning from resample filter */
				if (frame->pts == (int64_t) AV_NOPTS_VALUE) {
					frame->pts = 0;
				}
				ret = av_buffersrc_write_frame (player->fabuf, frame);
				assert (ret >= 0);

				while (true) {
					AVFilterBufferRef *audioref = NULL;
#ifdef HAVE_AV_BUFFERSINK_GET_BUFFER_REF
					/* ffmpeg’s compatibility layer is broken in some releases */
					if (av_buffersink_get_buffer_ref (player->fbufsink,
							&audioref, 0) < 0) {
#else
					if (av_buffersink_read (player->fbufsink, &audioref) < 0) {
#endif
						/* try again next frame */
						break;
					}

					ret = avfilter_copy_buf_props (filteredFrame, audioref);
					assert (ret >= 0);

					const int numChannels = av_get_channel_layout_nb_channels (
							filteredFrame->channel_layout);
					const int bps = av_get_bytes_per_sample(filteredFrame->format);
					ao_play (player->aoDev, (char *) filteredFrame->data[0],
							filteredFrame->nb_samples * numChannels * bps);

					avfilter_unref_bufferp (&audioref);
				}
			}

			pkt.data += decoded;
			pkt.size -= decoded;
		} while (pkt.size > 0);

		av_free_packet (&pkt_orig);

		player->songPlayed = av_q2d (player->st->time_base) * (double) pkt.pts;
		player->lastTimestamp = pkt.pts;
	}

	avcodec_free_frame (&filteredFrame);
	avcodec_free_frame (&frame);

	return 0;
}

static void finish (player_t * const player) {
	ao_close (player->aoDev);
	player->aoDev = NULL;
	if (player->fgraph != NULL) {
		avfilter_graph_free (&player->fgraph);
		player->fgraph = NULL;
	}
	if (player->st != NULL && player->st->codec != NULL) {
		avcodec_close (player->st->codec);
		player->st = NULL;
	}
	if (player->fctx != NULL) {
		avformat_close_input (&player->fctx);
	}
}
コード例 #19
0
bool KviKvsProcessAsyncOperation::start()
{
	QStringList args;
	QString szcmd;

	if(m_pData->iFlags & KVI_KVS_PROCESSDESCRIPTOR_NOSHELL)
	{
		args = m_pData->szCommandline.split(" ", QString::SkipEmptyParts);
	}
	else
	{
		QString szShell = m_pData->szShell;
		if(szShell.isEmpty())
		{
#if defined(COMPILE_ON_WINDOWS) || defined(COMPILE_ON_MINGW)
			// [01:26:00] <PragmaOff> btw, what is qt_winunicode ?
			// [01:26:12] <kode54> Qt export specific to win32
			// [01:26:27] <kode54> bool which indicates whether system is Unicode (NT) or not
			// [01:26:58] <kode54> not sure if that's documented, but it is a public export
			//
			// [02:50:21] <kode54> if ( QApplication::winVersion() & Qt::WV_NT_based )
			// [02:50:41] <kode54> I see another implementation using that, maybe it is the official way of detecting that :[
			szShell = !(QSysInfo::WindowsVersion & QSysInfo::WV_DOS_based) ? "cmd.exe /c" : "command.com /c";
// Thnx kode54 :)
#else
			szShell = "sh -c";
#endif
		}
		args = szShell.split(" ", QString::SkipEmptyParts);
		args.append(m_pData->szCommandline);
	}

	m_pProcess = new QProcess(this);

	if(m_pData->iFlags & KVI_KVS_PROCESSDESCRIPTOR_TRIGGERSTDOUT)
	{
		connect(m_pProcess, SIGNAL(readyReadStandardOutput()), this, SLOT(readStdout()));
	}
	else
	{
		m_pProcess->closeReadChannel(QProcess::StandardOutput);
	}

	if(m_pData->iFlags & KVI_KVS_PROCESSDESCRIPTOR_TRIGGERSTDERR)
	{
		connect(m_pProcess, SIGNAL(readyReadStandardError()), this, SLOT(readStderr()));
	}
	else
	{
		m_pProcess->closeReadChannel(QProcess::StandardError);
	}

	connect(m_pProcess, SIGNAL(finished(int)), this, SLOT(processExited(int)));

	if(m_pData->iFlags & KVI_KVS_PROCESSDESCRIPTOR_TRIGGERSTARTED)
	{
		connect(m_pProcess, SIGNAL(started()), this, SLOT(processStarted()));
	}

	szcmd = args.takeFirst();
	m_pProcess->start(szcmd, args);

	if(m_pProcess->state() == QProcess::NotRunning)
	{
		return false;
	}

	if(m_pData->iMaxRunTime > 0)
	{
		m_pRunTimeTimer = new QTimer(this);
		connect(m_pRunTimeTimer, SIGNAL(timeout()), this, SLOT(maxRunTimeExpired()));
		m_pRunTimeTimer->start(m_pData->iMaxRunTime);
	}

	if(m_pData->iPingTimeout > 0)
	{
		m_pPingTimer = new QTimer(this);
		connect(m_pPingTimer, SIGNAL(timeout()), this, SLOT(ping()));
		m_pPingTimer->start(m_pData->iPingTimeout);
	}

	return true;
}
コード例 #20
0
ファイル: main.c プロジェクト: Paolo-Maffei/ninostack
/** 
 * The task for generating button events, also does terminal and ping sending
 */
static void vButtonTask( int8_t *pvParameters )
{
	uint8_t event;
	uint8_t buttons = 0;
	uint8_t s1_count = 0;
	uint8_t s2_count = 0;
	int16_t byte;
	uint8_t i;
	uint8_t channel;

	pvParameters;
	
	N710_BUTTON_INIT();

	vTaskDelay( 200 / portTICK_RATE_MS );
	stack_event = stack_service_init(NULL);	 /* Open socket for stack status message */
	channel = mac_current_channel();
	
	while (1)
	{
		if(gw_assoc_state == 0 && scan_active == 0)
		{
			LED1_OFF();
			scan_active=1;
			scan_start = xTaskGetTickCount();
			gw_discover();
		}		
		/* Sleep for 10 ms or received from UART */
		byte = debug_read_blocking(10 / portTICK_RATE_MS);
		if (byte != -1)
		{
			switch(byte)
			{
				case '1':	/*send a button 1 event*/
					event = 1;
					xQueueSend( button_events, ( void * ) &event,	(portTickType) 0 );
					break;
					
				case '2': /*send a button 2 event*/
					event = 2;
					xQueueSend( button_events, ( void * ) &event,	(portTickType) 0 );
					break;
					
				case '\r':
					debug("\r\n");
					break;

				case 'm':
					{
						sockaddr_t mac;
						
						rf_mac_get(&mac);
						
						debug("MAC: ");
						debug_address(&mac);
						debug("\r\n");
					}
					break;

				case 'p':
					if(ping_active == 0)
					{
						echo_result.count=0;
						if(ping(NULL, &echo_result) == pdTRUE) /* Broadcast */
						{
							ping_start = xTaskGetTickCount();
							ping_active = 2;
							debug("Ping\r\n");
						}
						else
							debug("No buffer.\r\n");
					}
					break;
					
				case 'u':
					if(ping_active == 0)
					{
						echo_result.count=0;
						if(udp_echo(NULL, &echo_result) == pdTRUE)
						{
							ping_start = xTaskGetTickCount();
							ping_active = 1;
							debug("udp echo_req()\r\n");
						}
						else
							debug("No buffer.\r\n");
					}
					break;

				/*case 'C':
					if (channel < 26) channel++;
					channel++;
				case 'c':
					if (channel > 11) channel--;
					mac_set_channel(channel);
					debug("Channel: ");
					debug_int(channel);
					debug("\r\n");
					break;*/
						
				default:
					debug_put(byte);				
			}
		}

		/* Read button (S1 and S2) status */
		if (N710_BUTTON_1 == 1)
		{
			if (s1_count > 5)
			{
				event = 1;
				if (s1_count >= 100) event |= 0x80; /*long keypress*/
				xQueueSend( button_events, ( void * ) &event,	(portTickType) 0 );
			}
			s1_count = 0;
		}
		else
		{
			if (s1_count < 100)
			{
				s1_count++;
			}
		}
		if (N710_BUTTON_2 == 1)
		{
			if (s2_count > 5)
			{
				event = 2;
				if (s2_count >= 100) event |= 0x80;	/*long keypress*/
				xQueueSend( button_events, ( void * ) &event,	(portTickType) 0 );
			}
			s2_count = 0;
		}			
		else
		{
			if (s2_count < 100)
			{
				s2_count++;
			}
		}
		/*LED blinkers*/
		if (led1_count)
		{
			led1_count--;
			LED1_ON();
		}
		else
		{
			LED1_OFF();
		}
		if (led2_count)
		{
			led2_count--;
			LED2_ON();
		}
		else
		{
			LED2_OFF();
		}
		buttons = 0;
		if (LED1())
		{
			buttons |= 1;
		}
		if (LED2())
		{
			buttons |= 2;
		}
		ssi_sensor_update(3, (uint32_t) buttons);

		/* ping response handling */
		if ((xTaskGetTickCount() - ping_start)*portTICK_RATE_MS > 1000 && ping_active)
		{
			debug("Ping timeout.\r\n");
			stop_ping();
			if(echo_result.count)
			{
				debug("Response: \r\n");
				for(i=0; i<echo_result.count; i++)
				{
					debug_address(&(echo_result.result[i].src));
					debug(" ");
					debug_int(echo_result.result[i].rssi);
					debug(" dbm, ");
					debug_int(echo_result.result[i].time);
					debug(" ms\r\n");
					vTaskDelay(4);
				}
				echo_result.count=0;
			}
			else
			{
				debug("No response.\r\n");
			}
			ping_active = 0;
		}
		
		/* stack events */
		if(stack_event)
		{
			buffer_t *buffer = waiting_stack_event(10);
			if(buffer)
			{
				switch (parse_event_message(buffer))
				{
					case BROKEN_LINK:
						buffer->dst_sa.port = datasensor_address.port;
						if(memcmp(&datasensor_address.address, &(buffer->dst_sa.address), 8) == 0)
						{
							gw_assoc_state = 0;
							datasensor_address.addr_type = ADDR_NONE;
							LED1_OFF();
						}
						
						break;
					
					case ROUTER_DISCOVER_RESPONSE:
						scan_active=0;
						if(gw_assoc_state==0)
						{
							memcpy(datasensor_address.address, buffer->src_sa.address, 8);
							datasensor_address.addr_type = buffer->src_sa.addr_type ;
							gw_assoc_state=1;
							LED1_ON();
						}
						break;

					default:

						break;
				}
				if(buffer)
				{
					socket_buffer_free(buffer);
					buffer = 0;
				}
			}
		} /*end stack events*/
		if (scan_active == 1 && (xTaskGetTickCount() - scan_start)*portTICK_RATE_MS > 1000)
		{
			mac_gw_discover();
			scan_start = xTaskGetTickCount();
		}
	} /*end main loop*/
}	
コード例 #21
0
RawBot::msg_vector RawBot::OnTournamentEnd(const jsoncons::json& msg) {
  std::cout << "Server: Tournament end" << std::endl;
  bot_->TournamentEnd();
  return ping();
}
コード例 #22
0
//-------------------------------------------------------------------------------------
bool DBInterfaceMysql::attach(const char* databaseName)
{
    if(!_g_installedWatcher)
    {
        initializeWatcher();
    }

    if(db_port_ == 0)
        db_port_ = 3306;

    if(databaseName != NULL)
        kbe_snprintf(db_name_, MAX_BUF, "%s", databaseName);

    hasLostConnection_ = false;

    try
    {
        pMysql_ = mysql_init(0);
        if(pMysql_ == NULL)
        {
            ERROR_MSG("DBInterfaceMysql::attach: mysql_init is error!\n");
            return false;
        }

        DEBUG_MSG(fmt::format("DBInterfaceMysql::attach: connect: {}:{} starting...\n", db_ip_, db_port_));

        int ntry = 0;

__RECONNECT:
        if(mysql_real_connect(mysql(), db_ip_, db_username_,
                              db_password_, db_name_, db_port_, NULL, 0)) // CLIENT_MULTI_STATEMENTS
        {
            if(mysql_select_db(mysql(), db_name_) != 0)
            {
                ERROR_MSG(fmt::format("DBInterfaceMysql::attach: Could not set active db[{}]\n",
                                      db_name_));

                detach();
                return false;
            }
        }
        else
        {
            if (mysql_errno(pMysql_) == 1049 && ntry++ == 0)
            {
                if (mysql())
                {
                    ::mysql_close(mysql());
                    pMysql_ = NULL;
                }

                pMysql_ = mysql_init(0);
                if (pMysql_ == NULL)
                {
                    ERROR_MSG("DBInterfaceMysql::attach: mysql_init is error!\n");
                    return false;
                }

                if (mysql_real_connect(mysql(), db_ip_, db_username_,
                                       db_password_, NULL, db_port_, NULL, 0)) // CLIENT_MULTI_STATEMENTS
                {
                    this->createDatabaseIfNotExist();
                    if (mysql_select_db(mysql(), db_name_) != 0)
                    {
                        goto __RECONNECT;
                    }
                }
                else
                {
                    goto __RECONNECT;
                }
            }
            else
            {
                ERROR_MSG(fmt::format("DBInterfaceMysql::attach: mysql_errno={}, mysql_error={}\n",
                                      mysql_errno(pMysql_), mysql_error(pMysql_)));

                detach();
                return false;
            }
        }

        if (mysql_set_character_set(mysql(), "utf8") != 0)
        {
            ERROR_MSG("DBInterfaceMysql::attach: Could not set client connection character set to UTF-8\n" );
            return false;
        }

        // 不需要关闭自动提交,底层会START TRANSACTION之后再COMMIT
        // mysql_autocommit(mysql(), 0);

        char characterset_sql[MAX_BUF];
        kbe_snprintf(characterset_sql, MAX_BUF, "ALTER DATABASE CHARACTER SET %s COLLATE %s",
                     characterSet_.c_str(), collation_.c_str());

        query(&characterset_sql[0], strlen(characterset_sql), false);
    }
    catch (std::exception& e)
    {
        ERROR_MSG(fmt::format("DBInterfaceMysql::attach: {}\n", e.what()));
        hasLostConnection_ = true;
        detach();
        return false;
    }

    bool ret = mysql() != NULL && ping();

    if(ret)
    {
        DEBUG_MSG(fmt::format("DBInterfaceMysql::attach: successfully! addr: {}:{}\n", db_ip_, db_port_));
    }

    return ret;
}
コード例 #23
0
RawBot::msg_vector RawBot::OnJoin(const jsoncons::json& msg) {
  std::cout << "Server: Join" << std::endl;
  bot_->JoinedGame();
  return ping();
}
コード例 #24
0
ファイル: twitchBot.c プロジェクト: neuroscr/ayloBot
int main()
{
  //access the simpleIDE terminal
  simpleterm_close();
  //set full-duplex serialization for the terminal
  term = fdserial_open(31, 30, 0, 9600);

  char c;

  //servo_angle(16, gripDegree); //Orient gripper to half open on start
  //pause(3000);

  while (1)
  {
    c = fdserial_rxChar(term); //Get the character entered from the terminal
    if (c != -1)
    {
      //Use the below to see if any key input is being read by the terminal
      // dprint(term, "You typed: %c\n", c);

      //Link key presses to directional commands, and print the command to strings
      if (c == 'f') //press "f" fof forward
      {           
        Drive(ticks, ticks, maxSpeed);
        dprint(term, "ok\n");
      } 
      else if (c == 'b') //press "b" for backward
      { 
        Drive(-ticks, -ticks, maxSpeed);
        dprint(term, "ok\n");
      } 
      else if (c == 'r') //press "r" for right turn
      { 
        Drive(turnTick, -turnTick, maxTurnSpeed);
        dprint(term, "ok\n");
      } 
      else if (c == 'l') //press "l" for left turn
      { 
        Drive(-turnTick, turnTick, maxTurnSpeed);
        dprint(term, "ok\n");
      } 

      //Increasing and Decreasing Drive Speed
      else if (c == 'u') 
      {
        ticks = ticks + 2;
        if (ticks > maxSpeed) //clamp speed so it can't go over the maximum speed
        {
           ticks = maxSpeed;
        }
        dprint(term, "move_speed %d\n", ticks);
      } 
      else if (c == 'd') 
      {
        ticks = ticks - 2;
        if (ticks < minSpeed) //clamp speed so it can't go negative or 0
        {
          ticks = minSpeed;
        }
        dprint(term, "move_speed %d\n", ticks);
      }

      //Increase Turn Speed;
      else if (c == 't') 
      {
        turnTick = turnTick + 1;
        if (turnTick > maxTurnSpeed)
        {
          turnTick = maxTurnSpeed;
        }
        dprint(term, "turn_speed %d\n", turnTick);
      }
      
      //decrease turn speed
      else if (c == 'n')
      {
        turnTick = turnTick - 1;
        if (turnTick < minTurnSpeed)
          {
          turnTick = minTurnSpeed;
          }
        dprint(term, "turn_speed %d\n", turnTick);
      }

      else if (c == 'p') //ping distance
      {
        pingDistance = ping(8);
        dprint(term, "echo %d\n", pingDistance);
        dprint(term, "ok\n");
      }

      else if (c == 'k') // poke
      {
      }
      else if (c == 'o') //open gripper
      {
        gripState = 0;
        gripDegree = -1800;
      }
      else if (c == 'g') //close gripper
      {
        gripState = 1;
        gripDegree = 1800;
      }
    } // End of Read Character Function
  if (gripState != -1) 
  {
    Grip(gripDegree, 2000);
  }
  } // End of While Loop
} //End of Main Loop
コード例 #25
0
	bool push(const T &node)
	{
		if (!node.valid())
			return false;

		bool proceeded = false;
		Lock();
		{
			typename NodeListT::iterator it;
			it = std::find(InternalList.begin(), InternalList.end(), node);

			if (it != InternalList.end()) 
			{
				//既存なら最後尾へ
				T mnode(*it);
				InternalList.erase(it);

				mnode.marge(node);
				mnode.lastlink = time(NULL);
				InternalList.push_back(mnode);
				proceeded = true;
			}
			else if (InternalList.size() < Capacity) 
			{
				//リストに余裕があるなら最後尾に追加
				T newnode(node);
				newnode.lastlink = time(NULL);
                		InternalList.push_back(newnode);
                		proceeded = true;
            		}
#if !USEPING
			else 
			{
				pop_front();
				T newnode(node);
				newnode.lastlink = time(NULL);
				InternalList.push_back(newnode);
                		proceeded = true;
			}
#endif
		}
		Unlock();
		
#if USEPING
		if (proceeded)
		    return true;
		
		//リストの一番上のノード=最古ノードの生存確認
		T head;
		get_front(head);
			bool alive = ping(head);
		
		if (alive) {
		    //最古ノードが生きている:最古ノードを最後尾へ
		    //※対象ノードは追加しない
		    pop_front();
				head.lastlink = time(NULL);
		    Lock();
		    InternalList.push_back(head);
		    Unlock();
		}
		else 
		{
		    //最古ノードが死んでいる:対象ノードを最後尾に追加
		    pop_front();
			T newnode(node);
				newnode.lastlink = time(NULL);
		    Lock();
	    InternalList.push_back(newnode);
	    Unlock();
	}
#endif
	return true;
	};
コード例 #26
0
ファイル: pop_list.c プロジェクト: tommie/xppaut
int two_choice(char *choice1, char *choice2, char *string, char *key, int x,
               int y, Window w, char *title) {
  Window base, c1, c2, wm;
  XEvent ev;
  int not_done = 1;
  int value = 0;
  int l1 = strlen(choice1) * DCURX;
  int l2 = strlen(choice2) * DCURX;
  int lm = strlen(string) * DCURX;
  int tot = lm, xm, x1, x2;

  if (lm < (l1 + l2 + 4 * DCURX))
    tot = (l1 + l2 + 4 * DCURX);
  tot = tot + 6 * DCURX;
  xm = (tot - lm) / 2;
  x1 = (tot - l1 - l2 - 4 * DCURX) / 2;
  x2 = x1 + l1 + 4 * DCURX;
  base = make_plain_window(w, x, y, tot, 5 * DCURY, 4);

  make_icon((char *)alert_bits, alert_width, alert_height, base);

  c1 = make_window(base, x1, 3 * DCURY, l1 + DCURX, DCURY + 4, 1);
  c2 = make_window(base, x2, 3 * DCURY, l2 + DCURX, DCURY + 4, 1);
  XSelectInput(display, c1, BUT_MASK);
  XSelectInput(display, c2, BUT_MASK);

  wm = make_window(base, xm, DCURY / 2, lm + 2, DCURY, 0);

  ping();
  if (w == RootWindow(display, screen)) {
    if (title == NULL) {
      set_window_title(base, "!!!!");
    } else {
      set_window_title(base, title);
    }
  }

  while (not_done) {
    XNextEvent(display, &ev);
    switch (ev.type) {
    case Expose:
    case MapNotify:
      do_expose(ev);
      expose_choice(choice1, choice2, string, c1, c2, wm, ev.xexpose.window);
      break;

    case ButtonPress:
      if (ev.xbutton.window == c1) {
        value = (int)key[0];
        not_done = 0;
      }
      if (ev.xbutton.window == c2) {
        value = (int)key[1];
        not_done = 0;
      }
      break;
    case KeyPress:
      value = get_key_press(&ev);
      not_done = 0;
      break;
    case EnterNotify:
      if (ev.xcrossing.window == c1 || ev.xcrossing.window == c2)
        XSetWindowBorderWidth(display, ev.xcrossing.window, 2);
      XFlush(display);
      break;
    case LeaveNotify:
      if (ev.xcrossing.window == c1 || ev.xcrossing.window == c2)
        XSetWindowBorderWidth(display, ev.xcrossing.window, 1);
      XFlush(display);
      break;
    }
  }
  waitasec(2 * ClickTime);
  XFlush(display);
  XSelectInput(display, c1, EV_MASK);
  XSelectInput(display, c2, EV_MASK);
  XFlush(display);
  XDestroySubwindows(display, base);
  XDestroyWindow(display, base);
  return (value);
}
コード例 #27
0
ファイル: end2end_tests.c プロジェクト: mdsteele/grpc
void grpc_end2end_tests(int argc, char **argv,
                        grpc_end2end_test_config config) {
  int i;

  GPR_ASSERT(g_pre_init_called);

  if (argc <= 1) {
    authority_not_supported(config);
    bad_hostname(config);
    bad_ping(config);
    binary_metadata(config);
    call_creds(config);
    cancel_after_accept(config);
    cancel_after_client_done(config);
    cancel_after_invoke(config);
    cancel_after_round_trip(config);
    cancel_before_invoke(config);
    cancel_in_a_vacuum(config);
    cancel_with_status(config);
    compressed_payload(config);
    connectivity(config);
    default_host(config);
    disappearing_server(config);
    empty_batch(config);
    filter_call_init_fails(config);
    filter_causes_close(config);
    filter_latency(config);
    graceful_server_shutdown(config);
    high_initial_seqno(config);
    hpack_size(config);
    idempotent_request(config);
    invoke_large_request(config);
    keepalive_timeout(config);
    large_metadata(config);
    load_reporting_hook(config);
    max_concurrent_streams(config);
    max_connection_age(config);
    max_connection_idle(config);
    max_message_length(config);
    negative_deadline(config);
    network_status_change(config);
    no_logging(config);
    no_op(config);
    payload(config);
    ping(config);
    ping_pong_streaming(config);
    proxy_auth(config);
    registered_call(config);
    request_with_flags(config);
    request_with_payload(config);
    resource_quota_server(config);
    server_finishes_request(config);
    shutdown_finishes_calls(config);
    shutdown_finishes_tags(config);
    simple_cacheable_request(config);
    simple_delayed_request(config);
    simple_metadata(config);
    simple_request(config);
    streaming_error_response(config);
    trailing_metadata(config);
    workaround_cronet_compression(config);
    write_buffering(config);
    write_buffering_at_end(config);
    return;
  }

  for (i = 1; i < argc; i++) {
    if (0 == strcmp("authority_not_supported", argv[i])) {
      authority_not_supported(config);
      continue;
    }
    if (0 == strcmp("bad_hostname", argv[i])) {
      bad_hostname(config);
      continue;
    }
    if (0 == strcmp("bad_ping", argv[i])) {
      bad_ping(config);
      continue;
    }
    if (0 == strcmp("binary_metadata", argv[i])) {
      binary_metadata(config);
      continue;
    }
    if (0 == strcmp("call_creds", argv[i])) {
      call_creds(config);
      continue;
    }
    if (0 == strcmp("cancel_after_accept", argv[i])) {
      cancel_after_accept(config);
      continue;
    }
    if (0 == strcmp("cancel_after_client_done", argv[i])) {
      cancel_after_client_done(config);
      continue;
    }
    if (0 == strcmp("cancel_after_invoke", argv[i])) {
      cancel_after_invoke(config);
      continue;
    }
    if (0 == strcmp("cancel_after_round_trip", argv[i])) {
      cancel_after_round_trip(config);
      continue;
    }
    if (0 == strcmp("cancel_before_invoke", argv[i])) {
      cancel_before_invoke(config);
      continue;
    }
    if (0 == strcmp("cancel_in_a_vacuum", argv[i])) {
      cancel_in_a_vacuum(config);
      continue;
    }
    if (0 == strcmp("cancel_with_status", argv[i])) {
      cancel_with_status(config);
      continue;
    }
    if (0 == strcmp("compressed_payload", argv[i])) {
      compressed_payload(config);
      continue;
    }
    if (0 == strcmp("connectivity", argv[i])) {
      connectivity(config);
      continue;
    }
    if (0 == strcmp("default_host", argv[i])) {
      default_host(config);
      continue;
    }
    if (0 == strcmp("disappearing_server", argv[i])) {
      disappearing_server(config);
      continue;
    }
    if (0 == strcmp("empty_batch", argv[i])) {
      empty_batch(config);
      continue;
    }
    if (0 == strcmp("filter_call_init_fails", argv[i])) {
      filter_call_init_fails(config);
      continue;
    }
    if (0 == strcmp("filter_causes_close", argv[i])) {
      filter_causes_close(config);
      continue;
    }
    if (0 == strcmp("filter_latency", argv[i])) {
      filter_latency(config);
      continue;
    }
    if (0 == strcmp("graceful_server_shutdown", argv[i])) {
      graceful_server_shutdown(config);
      continue;
    }
    if (0 == strcmp("high_initial_seqno", argv[i])) {
      high_initial_seqno(config);
      continue;
    }
    if (0 == strcmp("hpack_size", argv[i])) {
      hpack_size(config);
      continue;
    }
    if (0 == strcmp("idempotent_request", argv[i])) {
      idempotent_request(config);
      continue;
    }
    if (0 == strcmp("invoke_large_request", argv[i])) {
      invoke_large_request(config);
      continue;
    }
    if (0 == strcmp("keepalive_timeout", argv[i])) {
      keepalive_timeout(config);
      continue;
    }
    if (0 == strcmp("large_metadata", argv[i])) {
      large_metadata(config);
      continue;
    }
    if (0 == strcmp("load_reporting_hook", argv[i])) {
      load_reporting_hook(config);
      continue;
    }
    if (0 == strcmp("max_concurrent_streams", argv[i])) {
      max_concurrent_streams(config);
      continue;
    }
    if (0 == strcmp("max_connection_age", argv[i])) {
      max_connection_age(config);
      continue;
    }
    if (0 == strcmp("max_connection_idle", argv[i])) {
      max_connection_idle(config);
      continue;
    }
    if (0 == strcmp("max_message_length", argv[i])) {
      max_message_length(config);
      continue;
    }
    if (0 == strcmp("negative_deadline", argv[i])) {
      negative_deadline(config);
      continue;
    }
    if (0 == strcmp("network_status_change", argv[i])) {
      network_status_change(config);
      continue;
    }
    if (0 == strcmp("no_logging", argv[i])) {
      no_logging(config);
      continue;
    }
    if (0 == strcmp("no_op", argv[i])) {
      no_op(config);
      continue;
    }
    if (0 == strcmp("payload", argv[i])) {
      payload(config);
      continue;
    }
    if (0 == strcmp("ping", argv[i])) {
      ping(config);
      continue;
    }
    if (0 == strcmp("ping_pong_streaming", argv[i])) {
      ping_pong_streaming(config);
      continue;
    }
    if (0 == strcmp("proxy_auth", argv[i])) {
      proxy_auth(config);
      continue;
    }
    if (0 == strcmp("registered_call", argv[i])) {
      registered_call(config);
      continue;
    }
    if (0 == strcmp("request_with_flags", argv[i])) {
      request_with_flags(config);
      continue;
    }
    if (0 == strcmp("request_with_payload", argv[i])) {
      request_with_payload(config);
      continue;
    }
    if (0 == strcmp("resource_quota_server", argv[i])) {
      resource_quota_server(config);
      continue;
    }
    if (0 == strcmp("server_finishes_request", argv[i])) {
      server_finishes_request(config);
      continue;
    }
    if (0 == strcmp("shutdown_finishes_calls", argv[i])) {
      shutdown_finishes_calls(config);
      continue;
    }
    if (0 == strcmp("shutdown_finishes_tags", argv[i])) {
      shutdown_finishes_tags(config);
      continue;
    }
    if (0 == strcmp("simple_cacheable_request", argv[i])) {
      simple_cacheable_request(config);
      continue;
    }
    if (0 == strcmp("simple_delayed_request", argv[i])) {
      simple_delayed_request(config);
      continue;
    }
    if (0 == strcmp("simple_metadata", argv[i])) {
      simple_metadata(config);
      continue;
    }
    if (0 == strcmp("simple_request", argv[i])) {
      simple_request(config);
      continue;
    }
    if (0 == strcmp("streaming_error_response", argv[i])) {
      streaming_error_response(config);
      continue;
    }
    if (0 == strcmp("trailing_metadata", argv[i])) {
      trailing_metadata(config);
      continue;
    }
    if (0 == strcmp("workaround_cronet_compression", argv[i])) {
      workaround_cronet_compression(config);
      continue;
    }
    if (0 == strcmp("write_buffering", argv[i])) {
      write_buffering(config);
      continue;
    }
    if (0 == strcmp("write_buffering_at_end", argv[i])) {
      write_buffering_at_end(config);
      continue;
    }
    gpr_log(GPR_DEBUG, "not a test: '%s'", argv[i]);
    abort();
  }
}
コード例 #28
0
inline void reduce_on_gpu(InputIterator first,
                          InputIterator last,
                          buffer_iterator<T> result,
                          Function function,
                          command_queue &queue)
{
    const device &device = queue.get_device();
    const context &context = queue.get_context();

    detail::meta_kernel k("reduce");
    k.add_arg<const T*>(memory_object::global_memory, "input");
    k.add_arg<const uint_>("offset");
    k.add_arg<const uint_>("count");
    k.add_arg<T*>(memory_object::global_memory, "output");
    k.add_arg<const uint_>("output_offset");

    k <<
        k.decl<const uint_>("block_offset") << " = get_group_id(0) * VPT * TPB;\n" <<
        "__global const " << type_name<T>() << " *block = input + offset + block_offset;\n" <<
        k.decl<const uint_>("lid") << " = get_local_id(0);\n" <<

        "__local " << type_name<T>() << " scratch[TPB];\n" <<
        // private reduction
        k.decl<T>("sum") << " = 0;\n" <<
        "for(uint i = 0; i < VPT; i++){\n" <<
        "    if(block_offset + lid + i*TPB < count){\n" <<
        "        sum = sum + block[lid+i*TPB]; \n" <<
        "    }\n" <<
        "}\n" <<

        "scratch[lid] = sum;\n";

    // discrimination on vendor name
    if(is_nvidia_device(device))
        k << ReduceBody<T,true>::body();
    else
        k << ReduceBody<T,false>::body();

    k <<
        // write sum to output
         "if(lid == 0){\n" <<
         "    output[output_offset + get_group_id(0)] = scratch[0];\n" <<
         "}\n";

    std::string cache_key = std::string("__boost_reduce_on_gpu_") + type_name<T>();

    // load parameters
    boost::shared_ptr<parameter_cache> parameters =
        detail::parameter_cache::get_global_cache(device);

    uint_ vpt = parameters->get(cache_key, "vpt", 8);
    uint_ tpb = parameters->get(cache_key, "tpb", 128);

    // reduce program compiler flags
    std::stringstream options;
    options << "-DT=" << type_name<T>()
            << " -DVPT=" << vpt
            << " -DTPB=" << tpb;

    // load program
    boost::shared_ptr<program_cache> cache =
        program_cache::get_global_cache(context);

    program reduce_program = cache->get_or_build(
        cache_key, options.str(), k.source(), context
    );

    // create reduce kernel
    kernel reduce_kernel(reduce_program, "reduce");

    size_t count = std::distance(first, last);

    // first pass, reduce from input to ping
    buffer ping(context, std::ceil(float(count) / vpt / tpb) * sizeof(T));
    initial_reduce(first, last, ping, function, reduce_kernel, vpt, tpb, queue);

    // update count after initial reduce
    count = std::ceil(float(count) / vpt / tpb);

    // middle pass(es), reduce between ping and pong
    const buffer *input_buffer = &ping;
    buffer pong(context, count / vpt / tpb * sizeof(T));
    const buffer *output_buffer = &pong;
    if(count > vpt * tpb){
        while(count > vpt * tpb){
            reduce_kernel.set_arg(0, *input_buffer);
            reduce_kernel.set_arg(1, uint_(0));
            reduce_kernel.set_arg(2, uint_(count));
            reduce_kernel.set_arg(3, *output_buffer);
            reduce_kernel.set_arg(4, uint_(0));

            size_t work_size = std::ceil(float(count) / vpt);
            if(work_size % tpb != 0){
                work_size += tpb - work_size % tpb;
            }
            queue.enqueue_1d_range_kernel(reduce_kernel, 0, work_size, tpb);

            std::swap(input_buffer, output_buffer);
            count = std::ceil(float(count) / vpt / tpb);
        }
    }

    // final pass, reduce from ping/pong to result
    reduce_kernel.set_arg(0, *input_buffer);
    reduce_kernel.set_arg(1, uint_(0));
    reduce_kernel.set_arg(2, uint_(count));
    reduce_kernel.set_arg(3, result.get_buffer());
    reduce_kernel.set_arg(4, uint_(result.get_index()));

    queue.enqueue_1d_range_kernel(reduce_kernel, 0, tpb, tpb);
}
コード例 #29
0
void endpoint<connection,config>::ping(connection_hdl hdl, std::string const & payload)
{
    lib::error_code ec;
    ping(hdl,payload,ec);
    if (ec) { throw exception(ec); }
}
コード例 #30
0
ファイル: ClientStub.cpp プロジェクト: tsingcoo/study
 FutureImpl<Void> ClientStub::ping()
 {
     return ping( CallOptions() );
 }