// -------------------------------------------------------------------------- // ARDrone::open(IP address of AR.Drone) // Description : Initialize the AR.Drone. // Return value : SUCCESS: 1 FAILURE: 0 // -------------------------------------------------------------------------- int ARDrone::open(const char *ardrone_addr) { // Initialize FFmpeg av_register_all(); avformat_network_init(); av_log_set_level(AV_LOG_QUIET); // Save IP address strncpy(ip, ardrone_addr, 16); // Get version information if (!getVersionInfo()) return 0; printf("AR.Drone Ver. %d.%d.%d\n", version.major, version.minor, version.revision); //// getVersionInfo() takes too long before realising the drone is not connected //// it call tcp open, which makes a socket and tries to connect to it //// using the connect method, which has too big of a timeout. //// making a smaller, 5 sec timeout before checking the verison to see if drone connected. //// if not, return 0 //if (!version.major) { // // create timeout and wait 5 sec // printf("Waiting for drone to connect...\n"); // msleep(5000); // // check again // if (!version.major) return 0; //} // Initialize AT command if (!initCommand()) return 0; // Initialize Navdata if (!initNavdata()) return 0; // Initialize Video if (!initVideo()) return 0; // Wait for updating state //msleep(500); // Get configurations if (!getConfig()) return 0; // Reset emergency resetWatchDog(); resetEmergency(); return 1; }
///////////////////////////////////////////////// //登录 int login() { command com; initCommand(&com, IPMSG_BR_ENTRY); com.peer.sin_family = AF_INET; com.peer.sin_port = htons(IPMSG_DEFAULT_PORT); if (inet_pton(AF_INET, allHosts, &com.peer.sin_addr)<0) printf("login: Ip error.\n"); strncpy(com.additional, pwd->pw_name, MSGLEN); sendMsg(&com); }
void KisStrokeStrategyUndoCommandBasedTest::testFinishedStroke() { QString result; KUndo2CommandSP initCommand(new TestingUndoCommand(kundo2_noi18n("init"), result)); KUndo2CommandSP dabCommand(new TestingUndoCommand(kundo2_noi18n("dab"), result)); KUndo2CommandSP finishCommand(new TestingUndoCommand(kundo2_noi18n("finish"), result)); KisStrokeStrategy *strategy = new KisStrokeStrategyUndoCommandBased(kundo2_noi18n("test"), false, 0, initCommand, finishCommand); KisStroke stroke(strategy); stroke.addJob( new KisStrokeStrategyUndoCommandBased::Data(dabCommand)); stroke.endStroke(); executeStrokeJobs(&stroke); SCOMPARE(result.trimmed(), "init_redo dab_redo finish_redo"); }
// -------------------------------------------------------------------------- // ARDrone::open(IP address of AR.Drone) // Description : Initialize the AR.Drone. // Return value : SUCCESS: 1 FAILURE: 0 // -------------------------------------------------------------------------- int ARDrone::open(const char *ardrone_addr) { #if _WIN32 // Initialize WSA WSAData wsaData; WSAStartup(MAKEWORD(1,1), &wsaData); #endif // Initialize FFmpeg av_register_all(); avformat_network_init(); av_log_set_level(AV_LOG_QUIET); // Save IP address strncpy(ip, ardrone_addr, 16); // Get version information if (!getVersionInfo()) return 0; printf("AR.Drone Ver. %d.%d.%d\n", version.major, version.minor, version.revision); // Get configurations if (!getConfig()) return 0; // Initialize AT command if (!initCommand()) return 0; // Initialize Navdata if (!initNavdata()) return 0; // Initialize Video if (!initVideo()) return 0; // Wait for updating state msleep(500); // Reset emergency resetWatchDog(); resetEmergency(); return 1; }
int AbstractCommand::init( KCmdLineArgs *parsedArgs ) { parsedArgs->clear(); KCmdLineArgs::reset(); KCmdLineOptions options; setupCommandOptions( options ); KCmdLineArgs::addCmdLineOptions( options ); KCmdLineArgs::addStdCmdLineOptions( KCmdLineArgs::CmdLineArgNone ); KCmdLineArgs *parseCommandArgs = KCmdLineArgs::parsedArgs(); Q_ASSERT( parseCommandArgs != 0 ); const int result = initCommand( parseCommandArgs ); KCmdLineArgs::reset(); KCmdLineArgs::addStdCmdLineOptions( KCmdLineArgs::CmdLineArgNone ); KCmdLineArgs::addCmdLineOptions( options ); return result; }
void KisStrokeStrategyUndoCommandBasedTest::testCancelledStroke() { QString result; KUndo2CommandSP initCommand(new TestingUndoCommand(kundo2_noi18n("init"), result)); KUndo2CommandSP dabCommand(new TestingUndoCommand(kundo2_noi18n("dab"), result)); KUndo2CommandSP finishCommand(new TestingUndoCommand(kundo2_noi18n("finish"), result)); const KoColorSpace *cs = KoColorSpaceRegistry::instance()->rgb8(); KisImageSP image = new KisImage(0, 300, 300, cs, "test", true); KisStrokeStrategy *strategy = new KisStrokeStrategyUndoCommandBased(kundo2_noi18n("test"), false, image->postExecutionUndoAdapter(), initCommand, finishCommand); KisStrokeId id = image->startStroke(strategy); image->addJob(id, new KisStrokeStrategyUndoCommandBased::Data(dabCommand)); QTest::qSleep(500); image->cancelStroke(id); image->waitForDone(); SCOMPARE(result.trimmed(), "init_redo dab_redo dab_undo init_undo"); }
int main(int argc, char *argv[]) { int ret = EXIT_SUCCESS; /* return value */ /* check parameter */ if (argc < 2) { fprintf(stderr, "ERROR: You need to give some command.\n"); showHelp(); return (EXIT_FAILURE); } initSystem(); if (gSystem == SYSTEM_ERROR) { fprintf(stderr, "ERROR: No package-system found (yum, apt).\n"); exit(EXIT_FAILURE); } initCommand(argv[1]); initList(argc - 2, (char **)argv + 2); switch (gCommand) { case COMMAND_HELP: showHelp(); break; case COMMAND_VERSION: showVersion(); break; case COMMAND_INSTALL: if (gList == NULL) { fprintf(stderr, "Error: Need to pass a list of pkgs to install.\n"); showHelp(); ret = EXIT_FAILURE; break; } doInstall(); break; case COMMAND_REMOVE: if (gList == NULL) { fprintf(stderr, "Error: Need to pass a list of pkgs to remove.\n"); showHelp(); ret = EXIT_FAILURE; break; } doRemove(); break; case COMMAND_SEARCH: if (gList == NULL) { fprintf(stderr, "Error: Need to pass a list of pkgs to search.\n"); showHelp(); ret = EXIT_FAILURE; break; } doSearch(); break; case COMMAND_LIST: if (gList == NULL) { fprintf(stderr, "Error: Need to pass a list of pkgs to lisst.\n"); showHelp(); ret = EXIT_FAILURE; break; } doList(); break; case COMMAND_UPDATE: if (gList == NULL) { fprintf(stderr, "Error: Need to pass a list of pkgs to update.\n"); showHelp(); ret = EXIT_FAILURE; break; } doUpdate(); break; default: fprintf(stderr, "ERROR: No such command '%s'. Please use '%s --help'.\n", argv[1], PRG_NAME); ret = EXIT_FAILURE; } destroy(); return (ret); }
//接收文件夹 int getDir(void *option, gsNode *gList) { int sockfd, readBytes, headerSize, fileType, dirDepth=0, tmp; char buf[COMLEN], recvs[RECFRG], hSize[HSIZE], fullPath[2*FILENAME]; filenode *head = (filenode*)option, *cur, fn; command com; struct sockaddr_in peer; long offset=0, fileSize; FILE* recvFile; strncpy(fullPath, gList->targetDir, sizeof(fullPath)); initCommand(&com, IPMSG_GETDIRFILES); //Direcotry snprintf(com.additional, MSGLEN, "%x:%x:%x", gList->packetNo, head->fileNo, offset); sockfd = socket(AF_INET, SOCK_STREAM, 0); bzero(&peer, sizeof(peer)); peer.sin_family = AF_INET; peer.sin_port = htons(IPMSG_DEFAULT_PORT); memcpy(&peer.sin_addr, &gList->peer.sin_addr, sizeof(peer.sin_addr)); if (connect(sockfd, (struct sockaddr*)&peer, sizeof(peer))<0) { printf("File connect error.\n"); return -1; } msgCreater(buf, &com, sizeof(buf)); if (writen(sockfd, buf, strlen(buf)+1)<0) return -1; do { tmp = strlen(fullPath); if (tmp+1>=sizeof(fullPath)) { printf("getDir: target directory is too lang.\n"); return -1; } if (fullPath[tmp-1]!='/') { fullPath[tmp] = '/'; fullPath[tmp+1] = '\0'; } readBytes = readDelimiter(sockfd, hSize, HSIZE, ':'); sscanf(hSize, "%x", &headerSize); if (headerSize<=0 || headerSize<=readBytes || headerSize>RECFRG) //保护、防止溢出 return -1; readn(sockfd, recvs, headerSize-readBytes); recvs[headerSize-readBytes]='\0'; if (parseHeader(&fn, recvs)<0) { printf("getDir: Parse protocol failed.\n"); return -1; } switch (fn.fileType & 0x03) { case IPMSG_FILE_REGULAR: strncat(fullPath, fn.fileName, sizeof(fullPath)-tmp-1); if ((recvFile = fopen(fullPath, "w+")) == NULL) { printf("Open error.\n"); return -1; } sscanf(fn.fileSize, "%x", &fileSize); while (fileSize>0) { readBytes = fileSize < RECFRG ? fileSize:RECFRG; if ((readBytes = readn(sockfd, recvs, readBytes))<0) //RECFRG { printf("File read error.\n"); return -1; } fwrite(recvs, 1, readBytes, recvFile); fileSize -= readBytes; } fclose(recvFile); getParentPath(fullPath, sizeof(fullPath)); break; case IPMSG_FILE_DIR: strncat(fullPath, fn.fileName, sizeof(fullPath)-tmp-1); tmp = strlen(fullPath); if (tmp+1>=sizeof(fullPath)) { printf("getDir: target directory is too lang.\n" "Filename(%s) has been truncated.\n", fn.fileName); fullPath[tmp-1] = '/'; } else { fullPath[tmp] = '/'; fullPath[tmp+1] = '\0'; } if (mkdir(fullPath, S_IRUSR|S_IWUSR|S_IXUSR)) { printf("getDir: mkdir failed.\n"); return -1; } dirDepth++; break; case IPMSG_FILE_RETPARENT: getParentPath(fullPath, sizeof(fullPath)); dirDepth--; break; default: printf("Unsupported file type.\n"); break; } }while(dirDepth>0); //close(sockfd); shutdown(sockfd, SHUT_RDWR); return 0; }
////////////////////////////////////////////////// //聊天 int saySth() { char buf[100]; //临时输入区 char gMsg[MSGLEN]; command com; user *cur=NULL; int remainder; //扩展区剩余空间 int pos; //扩展区的当前输入位置 int who, temp, count; int sended; //标记此包是否已经发过 user *pusers[50]; printf("\n*Talking mode\n" "*Continuous Enter to send msg,\n" "*Ctrl+D to quit conversation.\n"); pthread_mutex_lock(&usrMutex); count = listUsers(pusers, &userList, sizeof(pusers)/sizeof(pusers[0]), 0); // 每个用户都打上use标记? pthread_mutex_unlock(&usrMutex); who = inputNo(1, count, 1, "Please input user No.[1]:"); // 怎么参数里面还有需要打印的字符串 if (who>0) { cur = pusers[who-1]; initCommand(&com, IPMSG_SENDMSG|IPMSG_SENDCHECKOPT); memcpy(&com.peer, &cur->peer, sizeof(com.peer)); remainder = MSGLEN; pos = 0; sended = 1; while(1) { printf("(talking with %s):", cur->name); if (fgets(buf, sizeof(buf), stdin)==NULL) break; if (buf[0] != '\n') { strncpy(com.additional+pos, buf, remainder); temp = strlen(com.additional+pos); pos += temp; remainder -= temp; sended = 0; } if ((buf[0]=='\n') || (remainder<=1)) { if (!sended) { com.packetNo = (unsigned int)time(NULL); sendMsg(&com); sended = 1; printf("Message sent.\n"); } remainder = sizeof(com.additional); // 这里为什么要重新获取缓冲区大小 pos = 0; } } } puts("\nEnd conversation.\n"); pthread_mutex_lock(&usrMutex); unListUsers(pusers, count); // 清楚use标记 pthread_mutex_unlock(&usrMutex); }
int selectFiles() { command com; user *cur=NULL; int who, count, flag, fileType; unsigned int fileNo; char fileName[FILENAME]; struct stat fileAttr; char *strtmp; filenode *fntmp, *head, *tail; gsNode *newTask; user *pusers[50]; printf("\n*Sending mode\n" "*Continuous Enter to send file,\n" "*Ctrl+D to quit.\n"); pthread_mutex_lock(&usrMutex); count = listUsers(pusers, &userList, sizeof(pusers)/sizeof(pusers[0]), 0); pthread_mutex_unlock(&usrMutex); who = inputNo(1, count, 1, "Please input user No.[1]:"); if (who>0) { cur = pusers[who-1]; initCommand(&com, IPMSG_SENDMSG|IPMSG_FILEATTACHOPT); memcpy(&com.peer, &cur->peer, sizeof(com.peer)); printf("To send file to %s(%s).\nPlease select file to send:\n", cur->name, cur->host); newTask = (gsNode*)malloc(sizeof(gsNode)); initGsNode(newTask); newTask->packetNo = com.packetNo; fileNo = 0; head = com.fileList; tail = com.fileList; while (1) { if (fgets(fileName, FILENAME, stdin) == NULL) //取消传输 { free(newTask); newTask = NULL; while (head!=NULL) { tail = head; head = head->next; free(tail); } break; } transfStr(fileName, 0); //去除前后空白字符 if (fileName[0]=='\0') break; if (lstat(fileName, &fileAttr)<0) { printf("Get file attributes error.\n"); continue; } if (S_ISREG(fileAttr.st_mode)) fileType = 1; else if (S_ISDIR(fileAttr.st_mode)) fileType = 2; else { fileType = -1; printf("Unsupported file type.\n"); continue; } if (tail == NULL) head = tail = (filenode*)malloc(sizeof(filenode)); else { tail->next = (filenode*)malloc(sizeof(filenode)); tail = tail->next; } tail->next = NULL; tail->fileNo = fileNo; strncpy(tail->fileName, fileName, sizeof(tail->fileName)); snprintf(tail->fileSize, sizeof(tail->fileSize), "%x", fileAttr.st_size); snprintf(tail->mtime, sizeof(tail->mtime), "%x", fileAttr.st_mtime); tail->fileType = fileType; fileNo++; } // 可以连续发送多个文件? if (head==NULL) { if (newTask!=NULL) free(newTask); } else { newTask->fileList.next = com.fileList = head; pthread_mutex_lock(&sendFMutex); //lock newTask->next = sendFHead.next; sendFHead.next = newTask; pthread_mutex_unlock(&sendFMutex); //unlock if (newTask->fileList.next!=NULL) { sendMsg(&com); //可以放lock外面 printf("\nWaiting to transfer.\n"); } } } pthread_mutex_lock(&usrMutex); unListUsers(pusers, count); pthread_mutex_unlock(&usrMutex); }
int main(int argc, char *argv[], char *env[]) { //flag para laço principal int flag = 1; //comando lido de stdin char cmd[255]; //comando lido command app; initCommand(&app); //struct para manipulação de signals struct sigaction signals; struct jobs *j; struct job *jb; signals.sa_handler = &signalHandler; sigfillset(&signals.sa_mask); signals.sa_flags = 0; sigaction(SIGCHLD, &signals, NULL); sigaction(SIGTSTP, &signals, NULL); sigaction(SIGINT, &signals, NULL); sigaction(SIGTERM, &signals, NULL); //laço principal do { //inicialização do cmd strcpy(cmd, ""); //força a impressão do buffer de saída fflush(stdout); //impressão inicial do terminal printf("AB2> "); //limpeza do stdin __fpurge(stdin); //leitura do comando scanf("%[^\n]", cmd); //comando embutido "quit" ou "exit" if ((!strcmp(cmd, "quit")) || (!strcmp(cmd, "exit"))) { flag = 0; //comando embutido "pwd" } else if (!strcmp(cmd, "pwd")) { printf("%s\n", getcwd(NULL, 0)); //comando embutido "jobs" } else if (!strcmp(cmd, "jobs")) { //remove os 'jobs' terminados da lista cleanJobs(&jobs); if (jobs) { printf("Lista de 'jobs':\n"); j = jobs; while (j) { printf("\t[%d]", j->job.pid); printf("\t%s", (j->job.state == JOB_STOPPED ? "Parado" : (j->job.state == JOB_TERMINATED ? "Terminado" : (j->job.state == JOB_EXEC_FG ? "Executando" : "Executando em plano de fundo")))); printf("\t(%s)\n", j->job.application.input); j = j->next; } } else { printf("Nenhum 'job' na lista\n"); } //comando embutido "job" } else if (!strcmp(cmd, "job")) { printf("job_pid: %d\n", job_pid); //comando embutido "help" } else if (!strcmp(cmd, "help")) { printf("AB2 SHELL HELP\n\n"); printf("Comandos embutidos:\n"); printf(" help: exibe esta lista\n"); printf(" about: exibe o 'about' do shell\n"); printf(" pwd: mostra o diretório corrente\n"); printf(" cd: troca o diretório corrente\n"); printf(" quit: termina o shell\n"); printf(" jobs: lista todos os jobs em background\n"); printf(" bg <PID>: reinicia um job, passando sua execução para background\n"); printf(" fg <PID>: reinicia um job, passando sua execução para foreground\n"); //comando embutido "about" } else if (!strcmp(cmd, "about")) { printf("AB2 SHELL ABOUT\n\n"); printf("Shell criada por:\n"); printf(" André Vinícius Azevedo Aguilar NUSP: 5890160\n"); printf(" Eduardo de Freitas Alberice NUSP: 5890006\n"); printf(" Flávio Heleno Batista NUSP: 5890027\n"); //comandos embutidos com parâmetros ou comandos externos, não vazios } else if (strcmp(cmd, "")) { parseCommand(cmd, &app, env); //comando embutido "cd" if (!strcmp(app.argv[0], "cd")) { if (app.argc) { if (chdir(app.argv[1])) { printf("cd: %s: Diretório não encontrado\n", app.argv[1]); } } //comando embutido "bg" } else if (!strcmp(app.argv[0], "bg")) { if (app.argc == 2) { backgroundJob(atoi(app.argv[1]), &jobs); } else { if (!job_pid) { cleanJobs(&jobs); jb = lastJob(jobs); if (jb) { job_pid = jb->pid; } } if (job_pid) { backgroundJob(job_pid, &jobs); job_pid = 0; } else { printf("Nenhum 'job' ativo\n"); } } //comando embutido "fg" } else if (!strcmp(app.argv[0], "fg")) { if (app.argc == 2) { job_pid = atoi(app.argv[1]); foregroundJob(job_pid, &jobs); } else { if (!job_pid) { cleanJobs(&jobs); jb = lastJob(jobs); if (jb) { job_pid = jb->pid; } } if (job_pid) { foregroundJob(job_pid, &jobs); } else { printf("Nenhum 'job' ativo\n"); } } //comando embutido "kill" } else if (!strcmp(app.argv[0], "kill")) { if (app.argc == 2) { job_pid = atoi(app.argv[1]); terminateJob(job_pid, &jobs); printf("\n[%d]\tterminado\t%s\n", job_pid, ""); job_pid = 0; } else { if (!job_pid) { cleanJobs(&jobs); jb = lastJob(jobs); if (jb) { job_pid = jb->pid; } } if (job_pid) { terminateJob(job_pid, &jobs); printf("\n[%d]\tterminado\t%s\n", job_pid, ""); job_pid = 0; } else { printf("Nenhum 'job' ativo\n"); } } //comandos externos } else { //força a impressão do buffer de saída fflush(stdout); //cria o novo job job_pid = 0; job_pid = createJob(app, &jobs); if (stateJob(job_pid, jobs) == JOB_TERMINATED) { if (resultJob(job_pid, jobs) == JOB_FAILED) { printf("%s: comando não encontrado\n", app.argv[0]); } job_pid = 0; } } freeCommand(&app); } cleanJobs(&jobs); } while (flag); if (jobs) { killJobs(&jobs); cleanJobs(&jobs); } return 0; }