static void digit_help(char *s, long flag) { long n = atoi(s); if (n < 0 || n > MAX_SECTION+4) pari_err(e_SYNTAX,"no such section in help: ?",s,s); if (n == MAX_SECTION+1) community(); else if (flag & h_LONG) external_help(s,3); else commands(n); return; }
void ScrubbingToolBar::RegenerateTooltips() { #if wxUSE_TOOLTIPS auto fn = [&] (AButton &button, const wxString &label, const wxString &command) { LocalizedCommandNameVector commands( 1u, { label, command } ); ToolBar::SetButtonToolTip(button, commands); }; auto project = GetActiveProject(); if (project) { auto &scrubber = project->GetScrubber(); const auto scrubButton = mButtons[STBScrubID]; const auto seekButton = mButtons[STBSeekID]; wxString label; label = ( scrubber.Scrubs() /* i18n-hint: These commands assist the user in finding a sound by ear. ... "Scrubbing" is variable-speed playback, ... "Seeking" is normal speed playback but with skips */ ? _("Stop Scrubbing") : _("Start Scrubbing") ); fn(*scrubButton, label, wxT("Scrub")); label = ( scrubber.Seeks() /* i18n-hint: These commands assist the user in finding a sound by ear. ... "Scrubbing" is variable-speed playback, ... "Seeking" is normal speed playback but with skips */ ? _("Stop Seeking") : _("Start Seeking") ); fn(*seekButton, label, wxT("Seek")); label = ( project->GetRulerPanel()->ShowingScrubRuler() ? _("Hide Scrub Ruler") : _("Show Scrub Ruler") ); fn(*mButtons[STBRulerID], label, wxT("ToggleScrubRuler")); } #endif }
void customEvent(QEvent *e) { if (e->type() == QEvent::User) { m_noEventSent = true; QVector<Command> commands(0xff); m_receiveQueue->dequeue(commands); foreach (const Command &c, commands) { switch (c.command) { case SetStreamSize: QCOMPARE(c.data.type(), QVariant::Int); if (c.data.toInt() != 0) { m_gotStreamSize = true; if (m_gotSeekable) { m_timer.start(0, this); } } break; case SetSeekable: QCOMPARE(c.data.type(), QVariant::Bool); m_gotSeekable = true; if (m_gotStreamSize) { m_timer.start(0, this); } break; case Write: if (!m_inSeek && !m_inReset) { m_sendQueue->enqueue(EnoughData); ++m_receivedWrites; if (0 == m_receivedWrites % 10000) { qDebug() << "Thread1 received" << m_receivedWrites << "Write commands."; } } break; case EndOfData: QCOMPARE(m_inSeek, 0); QCOMPARE(m_inReset, 0); break; case SeekDone: --m_inSeek; break; case ResetDone: --m_inReset; break; default: qFatal("invalid command %d sent to backend thread", c.command); } } }
/*! Removes the command with \a type and \a syntax. */ void IrcCommandParser::removeCommand(IrcCommand::Type type, const QString& syntax) { Q_D(IrcCommandParser); bool changed = false; QMutableMapIterator<QString, IrcCommandInfo> it(d->commands); while (it.hasNext()) { IrcCommandInfo cmd = it.next().value(); if (cmd.type == type && (syntax.isEmpty() || !syntax.compare(cmd.fullSyntax(), Qt::CaseInsensitive))) { it.remove(); if (!d->commands.contains(cmd.command)) changed = true; } } if (changed) emit commandsChanged(commands()); }
/* * Load a file of user definitions. */ void load(char *name) { FILE *in, *oldin; if ((in = Fopen(name, "r")) == NULL) return; oldin = input; input = in; loading = 1; sourcing = 1; commands(); loading = 0; sourcing = 0; input = oldin; (void)Fclose(in); }
int main(int argc, char **argv) { Aria::init(); ArServerBase robotServer; if (!robotServer.open(5000)) { printf("Could not open robot server port\n"); Aria::exit(1); } ArServerBase clientServer; if (!clientServer.open(7272)) { printf("Could not open robot server port\n"); Aria::exit(1); } ArCentralManager switchManager(&robotServer, &clientServer); switchManager.addForwarderAddedCallback( new ArGlobalFunctor1<ArCentralForwarder *>(&forwarderAdded), 100); switchManager.addForwarderRemovedCallback( new ArGlobalFunctor1<ArCentralForwarder *>(&forwarderRemoved), 100); // Start a small handler to monitor communication between the server and // client. ArServerHandlerCommMonitor commMonitor(&clientServer); ArServerHandlerCommands commands(&clientServer); commands.setPrefix("CentralServer"); ArServerSimpleServerCommands serverCommands(&commands, &clientServer, false); commands.addCommand( "NetworkLogConnections", "Logs the connections to the central server, and to all the forwarded connections", new ArFunctorC<ArCentralManager> (&switchManager, &ArCentralManager::logConnections)); clientServer.runAsync(); robotServer.run(); Aria::exit(0); }
void rop3(int c) { if (iostats() == 0 && c == 'e') edited++; if (c == 'e') { if (wasalt || firstpat) { register line *addr = zero + oldadot; if (addr > dol) addr = dol; if (firstpat) { globp = (*firstpat) ? firstpat : "$"; commands(1,1); firstpat = 0; } else if (addr >= one) { if (inopen) dot = addr; markpr(addr); } else goto other; } else other: if (dol > zero) { if (inopen) dot = one; markpr(one); } if(FIXUNDO) undkind = UNDNONE; if (inopen) { vcline = 0; vreplace(0, EX_LINES, lineDOL()); } } if (laste) { #ifdef VMUNIX tlaste(); #endif laste = 0; ex_sync(); } }
void main(int argc, char *argv[]) { char *p1, *p2; Binit(&bcons, 0, OREAD); notify(notifyf); ARGBEGIN { case 'o': oflag = 1; vflag = 0; break; } ARGEND USED(argc); if(*argv && (strcmp(*argv, "-") == 0)) { argv++; vflag = 0; } if(oflag) { p1 = "/fd/1"; p2 = savedfile; while(*p2++ = *p1++) ; globp = L"a"; } else if(*argv) { p1 = *argv; p2 = savedfile; while(*p2++ = *p1++) if(p2 >= &savedfile[sizeof(savedfile)]) p2--; globp = L"r"; } zero = malloc((nlall+5)*sizeof(int*)); tfname = mktemp("/tmp/eXXXXX"); init(); setjmp(savej); commands(); quit(); }
std::shared_ptr<Chip> IdOnDemandReaderUnit::createChip(std::string type) { std::shared_ptr<Chip> chip; std::shared_ptr<ReaderCardAdapter> rca; if (type == CHIP_GENERICTAG) { chip.reset(new GenericTagIdOnDemandChip()); std::shared_ptr<Commands> commands(new GenericTagIdOnDemandCommands()); commands->setChip(chip); chip->setCommands(commands); rca = getDefaultReaderCardAdapter(); rca->setDataTransport(getDataTransport()); commands->setReaderCardAdapter(rca); } else { chip = ReaderUnit::createChip(type); } return chip; }
CompilationInfoForFile CompilationDatabase::GetCompilationInfoForFile( const std::string &path_to_file ) { ReleaseGil unlock; CompilationInfoForFile info; if ( !is_loaded_ ) return info; lock_guard< mutex > lock( compilation_database_mutex_ ); CompileCommandsWrap commands( clang_CompilationDatabase_getCompileCommands( compilation_database_, path_to_file.c_str() ), clang_CompileCommands_dispose ); uint num_commands = clang_CompileCommands_getSize( commands.get() ); if ( num_commands < 1 ) { return info; } // We always pick the first command offered CXCompileCommand command = clang_CompileCommands_getCommand( commands.get(), 0 ); info.compiler_working_dir_ = CXStringToString( clang_CompileCommand_getDirectory( command ) ); uint num_flags = clang_CompileCommand_getNumArgs( command ); info.compiler_flags_.reserve( num_flags ); for ( uint i = 0; i < num_flags; ++i ) { info.compiler_flags_.push_back( CXStringToString( clang_CompileCommand_getArg( command, i ) ) ); } return info; }
void Arguments::showHelp(int exitCode) { QTextStream out(stdout, QIODevice::WriteOnly); #ifdef UNLZS out << "unlzs [files...] [output directory]\n"; #else out << "lzs [-d] [files...] [output directory]\n"; #endif out << "Options\n"; QMapIterator<QString, QString> it(commands()); while (it.hasNext()) { it.next(); out << "\t" << qPrintable(it.key()) << "\n"; out << "\t" << "\t" << qPrintable(it.value()) << "\n"; } out.flush(); ::exit(exitCode); }
/** * Converts Java String[] to char** and delegates to ExecuteProcess(). */ static pid_t ProcessManager_exec(JNIEnv* env, jclass, jobjectArray javaCommands, jobjectArray javaEnvironment, jstring javaWorkingDirectory, jobject inDescriptor, jobject outDescriptor, jobject errDescriptor, jboolean redirectErrorStream) { ExecStrings commands(env, javaCommands); ExecStrings environment(env, javaEnvironment); // Extract working directory string. const char* workingDirectory = NULL; if (javaWorkingDirectory != NULL) { workingDirectory = env->GetStringUTFChars(javaWorkingDirectory, NULL); } pid_t result = ExecuteProcess(env, commands.get(), environment.get(), workingDirectory, inDescriptor, outDescriptor, errDescriptor, redirectErrorStream); // Clean up working directory string. if (javaWorkingDirectory != NULL) { env->ReleaseStringUTFChars(javaWorkingDirectory, workingDirectory); } return result; }
vector<float> CirclePlanner::get_action() { // ok, we've updated belief. Now pick action float ax = -cos(_bearing_max * M_PI/180.0); float ay = sin(_bearing_max * M_PI/180.0); // prevent circle from switching directions // if dot product is negative from last attempt, direction is different if (ax*last[0] + ay*last[1] < 0.0) { ax = -ax; ay = -ay; } vector<float>commands (3); commands[0] = _uav.max_step * ay; commands[1] = _uav.max_step * ax; commands[2] = 0.0; // preserve current action as last to check for direction last[0] = ax; last[1] = ay; return commands; }
void IMAP::emitResponses() { if ( clientHasBug( NoUnsolicitedResponses ) && commands()->isEmpty() ) return; // first, see if expunges are permitted bool can = false; bool cannot = false; List<Command>::Iterator c( commands() ); while ( c && !cannot ) { // expunges are permitted in idle mode if ( c->state() == Command::Executing && c->name() == "idle" ) can = true; // we cannot send an expunge while a command is being // executed (not without NOTIFY at least...) else if ( c->state() == Command::Executing ) cannot = true; // group 2 contains commands during which we may not send // expunge, group 3 contains all commands that change // flags. else if ( c->group() == 2 || c->group() == 3 ) cannot = true; // if there are MSNs in the pipeline we cannot send // expunge. the copy rule is due to RFC 2180 section // 4.4.1/2 else if ( c->usesMsn() && c->name() != "copy" ) cannot = true; // if another command is finished, we can. else if ( c->state() == Command::Finished && !c->tag().isEmpty() ) can = true; ++c; } if ( cannot ) can = false; bool any = false; Buffer * w = writeBuffer(); List<ImapResponse>::Iterator r( d->responses ); uint n = 0; while ( r ) { if ( !r->meaningful() ) { r->setSent(); } else if ( !r->sent() && ( can || !r->changesMsn() ) ) { EString t = r->text(); if ( !t.isEmpty() ) { w->append( "* ", 2 ); w->append( t ); w->append( "\r\n", 2 ); n++; } r->setSent(); any = true; } if ( r->sent() ) d->responses.take( r ); else ++r; } if ( !any ) return; c = commands()->first(); while ( c ) { c->checkUntaggedResponses(); ++c; } }
int main(int argc, char **argv) { Aria::init(); //ArLog::init(ArLog::StdOut, ArLog::Verbose); // robot ArRobot robot; /// our server ArServerBase server; // set up our parser ArArgumentParser parser(&argc, argv); // set up our simple connector ArSimpleConnector simpleConnector(&parser); // set up a gyro ArAnalogGyro gyro(&robot); // load the default arguments parser.loadDefaultArguments(); // parse the command line... fail and print the help if the parsing fails // or if the help was requested if (!simpleConnector.parseArgs() || !parser.checkHelpAndWarnUnparsed()) { simpleConnector.logOptions(); exit(1); } if (!server.loadUserInfo("userServerTest.userInfo")) { printf("Could not load user info, exiting\n"); exit(1); } server.logUsers(); // first open the server up if (!server.open(7272)) { printf("Could not open server port\n"); exit(1); } // sonar, must be added to the robot ArSonarDevice sonarDev; // add the sonar to the robot robot.addRangeDevice(&sonarDev); ArIRs irs; robot.addRangeDevice(&irs); ArBumpers bumpers; robot.addRangeDevice(&bumpers); // a laser in case one is used ArSick sick(361, 180); // add the laser to the robot robot.addRangeDevice(&sick); // attach stuff to the server ArServerInfoRobot serverInfoRobot(&server, &robot); ArServerInfoSensor serverInfoSensor(&server, &robot); ArServerInfoDrawings drawings(&server); drawings.addRobotsRangeDevices(&robot); // ways of moving the robot ArServerModeStop modeStop(&server, &robot); ArServerModeDrive modeDrive(&server, &robot); ArServerModeRatioDrive modeRatioDrive(&server, &robot); ArServerModeWander modeWander(&server, &robot); modeStop.addAsDefaultMode(); modeStop.activate(); // set up the simple commands ArServerHandlerCommands commands(&server); // add the commands for the microcontroller ArServerSimpleComUC uCCommands(&commands, &robot); // add the commands for logging ArServerSimpleComMovementLogging loggingCommands(&commands, &robot); // add the commands for the gyro ArServerSimpleComGyro gyroCommands(&commands, &robot, &gyro); // add the commands to enable and disable safe driving to the simple commands modeDrive.addControlCommands(&commands); // Forward any video if we have some to forward.. this will forward // from SAV or ACTS, you can find both on our website // http://robots.activmedia.com, ACTS is for color tracking and is // charged for but SAV just does software A/V transmitting and is // free to all our customers... just run ACTS or SAV before you // start this program and this class here will forward video from it // to MobileEyes ArHybridForwarderVideo videoForwarder(&server, "localhost", 7070); // make a camera to use in case we have video ArPTZ *camera = NULL; ArServerHandlerCamera *handlerCamera = NULL; // if we have video then set up a camera if (videoForwarder.isForwardingVideo()) { bool invertedCamera = false; camera = new ArVCC4(&robot, invertedCamera, ArVCC4::COMM_UNKNOWN, true, true); camera->init(); handlerCamera = new ArServerHandlerCamera(&server, &robot, camera); } server.logCommandGroups(); server.logCommandGroupsToFile("userServerTest.commandGroups"); // now let it spin off in its own thread server.runAsync(); // set up the robot for connecting if (!simpleConnector.connectRobot(&robot)) { printf("Could not connect to robot... exiting\n"); Aria::shutdown(); return 1; } // set up the laser before handing it to the laser mode simpleConnector.setupLaser(&sick); robot.enableMotors(); // start the robot running, true so that if we lose connection the run stops robot.runAsync(true); sick.runAsync(); // connect the laser if it was requested if (!simpleConnector.connectLaser(&sick)) { printf("Could not connect to laser... exiting\n"); Aria::shutdown(); return 1; } robot.waitForRunExit(); // now exit Aria::shutdown(); exit(0); }
void f_commands (void) { push_refed_array(commands(current_object)); }
vmain() { register int c, cnt, i; char esave[TUBECOLS]; char *oglobp; char d; line *addr; int ind, nlput; int shouldpo = 0; int onumber, olist, (*OPline)(), (*OPutchar)(); vch_mac = VC_NOTINMAC; /* * If we started as a vi command (on the command line) * then go process initial commands (recover, next or tag). */ if (initev) { oglobp = globp; globp = initev; hadcnt = cnt = 0; i = tchng; addr = dot; goto doinit; } /* * NB: * * The current line is always in the line buffer linebuf, * and the cursor at the position cursor. You should do * a vsave() before moving off the line to make sure the disk * copy is updated if it has changed, and a getDOT() to get * the line back if you mung linebuf. The motion * routines in ex_vwind.c handle most of this. */ for (;;) { /* * Decode a visual command. * First sync the temp file if there has been a reasonable * amount of change. Clear state for decoding of next * command. */ TSYNC(); vglobp = 0; vreg = 0; hold = 0; seenprompt = 1; wcursor = 0; Xhadcnt = hadcnt = 0; Xcnt = cnt = 1; splitw = 0; if (i = holdupd) { if (state == VISUAL) ignore(peekkey()); holdupd = 0; /* if (LINE(0) < ZERO) { vclear(); vcnt = 0; i = 3; } */ if (state != VISUAL) { vcnt = 0; vsave(); vrepaint(cursor); } else if (i == 3) vredraw(WTOP); else vsync(WTOP); vfixcurs(); } /* * Gobble up counts and named buffer specifications. */ for (;;) { looptop: #ifdef MDEBUG if (trace) fprintf(trace, "pc=%c",peekkey()); #endif if (isdigit(peekkey()) && peekkey() != '0') { hadcnt = 1; cnt = vgetcnt(); forbid (cnt <= 0); } if (peekkey() != '"') break; ignore(getkey()), c = getkey(); /* * Buffer names be letters or digits. * But not '0' as that is the source of * an 'empty' named buffer spec in the routine * kshift (see ex_temp.c). */ forbid (c == '0' || !isalpha(c) && !isdigit(c)); vreg = c; } reread: /* * Come to reread from below after some macro expansions. * The call to map allows use of function key pads * by performing a terminal dependent mapping of inputs. */ #ifdef MDEBUG if (trace) fprintf(trace,"pcb=%c,",peekkey()); #endif op = getkey(); maphopcnt = 0; do { /* * Keep mapping the char as long as it changes. * This allows for double mappings, e.g., q to #, * #1 to something else. */ c = op; op = map(c,arrows); #ifdef MDEBUG if (trace) fprintf(trace,"pca=%c,",c); #endif /* * Maybe the mapped to char is a count. If so, we have * to go back to the "for" to interpret it. Likewise * for a buffer name. */ if ((isdigit(c) && c!='0') || c == '"') { ungetkey(c); goto looptop; } if (!value(REMAP)) { c = op; break; } if (++maphopcnt > 256) error("Infinite macro loop"); } while (c != op); /* * Begin to build an image of this command for possible * later repeat in the buffer workcmd. It will be copied * to lastcmd by the routine setLAST * if/when completely specified. */ lastcp = workcmd; if (!vglobp) *lastcp++ = c; /* * First level command decode. */ switch (c) { /* * ^L Clear screen e.g. after transmission error. */ /* * ^R Retype screen, getting rid of @ lines. * If in open, equivalent to ^L. * On terminals where the right arrow key sends * ^L we make ^R act like ^L, since there is no * way to get ^L. These terminals (adm31, tvi) * are intelligent so ^R is useless. Soroc * will probably foul this up, but nobody has * one of them. */ case CTRL(l): case CTRL(r): if (c == CTRL(l) || (KR && *KR==CTRL(l))) { vclear(); vdirty(0, vcnt); } if (state != VISUAL) { /* * Get a clean line, throw away the * memory of what is displayed now, * and move back onto the current line. */ vclean(); vcnt = 0; vmoveto(dot, cursor, 0); continue; } vredraw(WTOP); /* * Weird glitch -- when we enter visual * in a very small window we may end up with * no lines on the screen because the line * at the top is too long. This forces the screen * to be expanded to make room for it (after * we have printed @'s ick showing we goofed). */ if (vcnt == 0) vrepaint(cursor); vfixcurs(); continue; /* * $ Escape just cancels the current command * with a little feedback. */ case ESCAPE: beep(); continue; /* * @ Macros. Bring in the macro and put it * in vmacbuf, point vglobp there and punt. */ case '@': c = getesc(); if (c == 0) continue; if (c == '@') c = lastmac; if (isupper(c)) c = tolower(c); forbid(!islower(c)); lastmac = c; vsave(); CATCH char tmpbuf[BUFSIZ]; regbuf(c,tmpbuf,sizeof(vmacbuf)); macpush(tmpbuf, 1); ONERR lastmac = 0; splitw = 0; getDOT(); vrepaint(cursor); continue; ENDCATCH vmacp = vmacbuf; goto reread; /* * . Repeat the last (modifying) open/visual command. */ case '.': /* * Check that there was a last command, and * take its count and named buffer unless they * were given anew. Special case if last command * referenced a numeric named buffer -- increment * the number and go to a named buffer again. * This allows a sequence like "1pu.u.u... * to successively look for stuff in the kill chain * much as one does in EMACS with C-Y and M-Y. */ forbid (lastcmd[0] == 0); if (hadcnt) lastcnt = cnt; if (vreg) lastreg = vreg; else if (isdigit(lastreg) && lastreg < '9') lastreg++; vreg = lastreg; cnt = lastcnt; hadcnt = lasthad; vglobp = lastcmd; goto reread; /* * ^U Scroll up. A count sticks around for * future scrolls as the scroll amount. * Attempt to hold the indentation from the * top of the screen (in logical lines). * * BUG: A ^U near the bottom of the screen * on a dumb terminal (which can't roll back) * causes the screen to be cleared and then * redrawn almost as it was. In this case * one should simply move the cursor. */ case CTRL(u): if (hadcnt) vSCROLL = cnt; cnt = vSCROLL; if (state == VISUAL) ind = vcline, cnt += ind; else ind = 0; vmoving = 0; vup(cnt, ind, 1); vnline(NOSTR); continue; /* * ^D Scroll down. Like scroll up. */ case CTRL(d): #ifdef TRACE if (trace) fprintf(trace, "before vdown in ^D, dot=%d, wdot=%d, dol=%d\n", lineno(dot), lineno(wdot), lineno(dol)); #endif if (hadcnt) vSCROLL = cnt; cnt = vSCROLL; if (state == VISUAL) ind = vcnt - vcline - 1, cnt += ind; else ind = 0; vmoving = 0; vdown(cnt, ind, 1); #ifdef TRACE if (trace) fprintf(trace, "before vnline in ^D, dot=%d, wdot=%d, dol=%d\n", lineno(dot), lineno(wdot), lineno(dol)); #endif vnline(NOSTR); #ifdef TRACE if (trace) fprintf(trace, "after vnline in ^D, dot=%d, wdot=%d, dol=%d\n", lineno(dot), lineno(wdot), lineno(dol)); #endif continue; /* * ^E Glitch the screen down (one) line. * Cursor left on same line in file. */ case CTRL(e): if (state != VISUAL) continue; if (!hadcnt) cnt = 1; /* Bottom line of file already on screen */ forbid(lineDOL()-lineDOT() <= vcnt-1-vcline); ind = vcnt - vcline - 1 + cnt; vdown(ind, ind, 1); vnline(cursor); continue; /* * ^Y Like ^E but up */ case CTRL(y): if (state != VISUAL) continue; if (!hadcnt) cnt = 1; forbid(lineDOT()-1<=vcline); /* line 1 already there */ ind = vcline + cnt; vup(ind, ind, 1); vnline(cursor); continue; /* * m Mark position in mark register given * by following letter. Return is * accomplished via ' or `; former * to beginning of line where mark * was set, latter to column where marked. */ case 'm': /* * Getesc is generally used when a character * is read as a latter part of a command * to allow one to hit rubout/escape to cancel * what you have typed so far. These characters * are mapped to 0 by the subroutine. */ c = getesc(); if (c == 0) continue; /* * Markreg checks that argument is a letter * and also maps ' and ` to the end of the range * to allow '' or `` to reference the previous * context mark. */ c = markreg(c); forbid (c == 0); vsave(); names[c - 'a'] = (*dot &~ 01); ncols[c - 'a'] = cursor; anymarks = 1; continue; /* * ^F Window forwards, with 2 lines of continuity. * Count repeats. */ case CTRL(f): vsave(); if (vcnt > 2) { addr = dot + (vcnt - vcline) - 2 + (cnt-1)*basWLINES; forbid(addr > dol); dot = addr; vcnt = vcline = 0; } vzop(0, 0, '+'); continue; /* * ^B Window backwards, with 2 lines of continuity. * Inverse of ^F. */ case CTRL(b): vsave(); if (one + vcline != dot && vcnt > 2) { addr = dot - vcline - 2 + (cnt-1)*basWLINES; forbid (addr <= zero); dot = addr; vcnt = vcline = 0; } vzop(0, 0, '^'); continue; /* * z Screen adjustment, taking a following character: * z<CR> current line to top * z<NL> like z<CR> * z- current line to bottom * also z+, z^ like ^F and ^B. * A preceding count is line to use rather * than current line. A count between z and * specifier character changes the screen size * for the redraw. * */ case 'z': if (state == VISUAL) { i = vgetcnt(); if (i > 0) vsetsiz(i); c = getesc(); if (c == 0) continue; } vsave(); vzop(hadcnt, cnt, c); continue; /* * Y Yank lines, abbreviation for y_ or yy. * Yanked lines can be put later if no * changes intervene, or can be put in named * buffers and put anytime in this session. */ case 'Y': ungetkey('_'); c = 'y'; break; /* * J Join lines, 2 by default. Count is number * of lines to join (no join operator sorry.) */ case 'J': forbid (dot == dol); if (cnt == 1) cnt = 2; if (cnt > (i = dol - dot + 1)) cnt = i; vsave(); vmacchng(1); setLAST(); cursor = strend(linebuf); vremote(cnt, join, 0); notenam = "join"; vmoving = 0; killU(); vreplace(vcline, cnt, 1); if (!*cursor && cursor > linebuf) cursor--; if (notecnt == 2) notecnt = 0; vrepaint(cursor); continue; /* * S Substitute text for whole lines, abbrev for c_. * Count is number of lines to change. */ case 'S': ungetkey('_'); c = 'c'; break; /* * O Create a new line above current and accept new * input text, to an escape, there. * A count specifies, for dumb terminals when * slowopen is not set, the number of physical * line space to open on the screen. * * o Like O, but opens lines below. */ case 'O': case 'o': vmacchng(1); voOpen(c, cnt); continue; /* * C Change text to end of line, short for c$. */ case 'C': if (*cursor) { ungetkey('$'), c = 'c'; break; } goto appnd; /* * ~ Switch case of letter under cursor */ case '~': { char mbuf[4]; setLAST(); mbuf[0] = 'r'; mbuf[1] = *cursor; mbuf[2] = cursor[1]==0 ? 0 : ' '; mbuf[3] = 0; if (isalpha(mbuf[1])) mbuf[1] ^= ' '; /* toggle the case */ macpush(mbuf, 1); } continue; /* * A Append at end of line, short for $a. */ case 'A': operate('$', 1); appnd: c = 'a'; /* fall into ... */ /* * a Appends text after cursor. Text can continue * through arbitrary number of lines. */ case 'a': if (*cursor) { if (state == HARDOPEN) putchar(*cursor); cursor++; } goto insrt; /* * I Insert at beginning of whitespace of line, * short for ^i. */ case 'I': operate('^', 1); c = 'i'; /* fall into ... */ /* * R Replace characters, one for one, by input * (logically), like repeated r commands. * * BUG: This is like the typeover mode of many other * editors, and is only rarely useful. Its * implementation is a hack in a low level * routine and it doesn't work very well, e.g. * you can't move around within a R, etc. */ case 'R': /* fall into... */ /* * i Insert text to an escape in the buffer. * Text is arbitrary. This command reminds of * the i command in bare teco. */ case 'i': insrt: /* * Common code for all the insertion commands. * Save for redo, position cursor, prepare for append * at command and in visual undo. Note that nothing * is doomed, unless R when all is, and save the * current line in a the undo temporary buffer. */ vmacchng(1); setLAST(); vcursat(cursor); prepapp(); vnoapp(); doomed = c == 'R' ? 10000 : 0; if(FIXUNDO) vundkind = VCHNG; vmoving = 0; CP(vutmp, linebuf); /* * If this is a repeated command, then suppress * fake insert mode on dumb terminals which looks * ridiculous and wastes lots of time even at 9600B. */ if (vglobp) hold = HOLDQIK; vappend(c, cnt, 0); continue; /* * ^? An attention, normally a ^?, just beeps. * If you are a vi command within ex, then * two ATTN's will drop you back to command mode. */ case ATTN: beep(); if (initev || peekkey() != ATTN) continue; /* fall into... */ /* * ^\ A quit always gets command mode. */ case QUIT: /* * Have to be careful if we were called * g/xxx/vi * since a return will just start up again. * So we simulate an interrupt. */ if (inglobal) onintr(); /* fall into... */ #ifdef notdef /* * q Quit back to command mode, unless called as * vi on command line in which case dont do it */ case 'q': /* quit */ if (initev) { vsave(); CATCH error("Q gets ex command mode, :q leaves vi"); ENDCATCH splitw = 0; getDOT(); vrepaint(cursor); continue; } #endif /* fall into... */ /* * Q Is like q, but always gets to command mode * even if command line invocation was as vi. */ case 'Q': vsave(); /* * If we are in the middle of a macro, throw away * the rest and fix up undo. * This code copied from getbr(). */ if (vmacp) { vmacp = 0; if (inopen == -1) /* don't screw up undo for esc esc */ vundkind = VMANY; inopen = 1; /* restore old setting now that macro done */ } return; /* * ZZ Like :x */ case 'Z': forbid(getkey() != 'Z'); oglobp = globp; globp = "x"; vclrech(0); goto gogo; /* * P Put back text before cursor or before current * line. If text was whole lines goes back * as whole lines. If part of a single line * or parts of whole lines splits up current * line to form many new lines. * May specify a named buffer, or the delete * saving buffers 1-9. * * p Like P but after rather than before. */ case 'P': case 'p': vmoving = 0; #ifdef notdef forbid (!vreg && value(UNDOMACRO) && inopen < 0); #endif /* * If previous delete was partial line, use an * append or insert to put it back so as to * use insert mode on intelligent terminals. */ if (!vreg && DEL[0]) { forbid ((DEL[0] & (QUOTE|TRIM)) == OVERBUF); vglobp = DEL; ungetkey(c == 'p' ? 'a' : 'i'); goto reread; } /* * If a register wasn't specified, then make * sure there is something to put back. */ forbid (!vreg && unddol == dol); /* * If we just did a macro the whole buffer is in * the undo save area. We don't want to put THAT. */ forbid (vundkind == VMANY && undkind==UNDALL); vsave(); vmacchng(1); setLAST(); i = 0; if (vreg && partreg(vreg) || !vreg && pkill[0]) { /* * Restoring multiple lines which were partial * lines; will leave cursor in middle * of line after shoving restored text in to * split the current line. */ i++; if (c == 'p' && *cursor) cursor++; } else { /* * In whole line case, have to back up dot * for P; also want to clear cursor so * cursor will eventually be positioned * at the beginning of the first put line. */ cursor = 0; if (c == 'P') { dot--, vcline--; c = 'p'; } } killU(); /* * The call to putreg can potentially * bomb since there may be nothing in a named buffer. * We thus put a catch in here. If we didn't and * there was an error we would end up in command mode. */ addr = dol; /* old dol */ CATCH vremote(1, vreg ? putreg : put, vreg); ONERR if (vreg == -1) { splitw = 0; if (op == 'P') dot++, vcline++; goto pfixup; } ENDCATCH splitw = 0; nlput = dol - addr + 1; if (!i) { /* * Increment undap1, undap2 to make up * for their incorrect initialization in the * routine vremote before calling put/putreg. */ if (FIXUNDO) undap1++, undap2++; vcline++; nlput--; /* * After a put want current line first line, * and dot was made the last line put in code * run so far. This is why we increment vcline * above and decrease dot here. */ dot -= nlput - 1; } #ifdef TRACE if (trace) fprintf(trace, "vreplace(%d, %d, %d), undap1=%d, undap2=%d, dot=%d\n", vcline, i, nlput, lineno(undap1), lineno(undap2), lineno(dot)); #endif vreplace(vcline, i, nlput); if (state != VISUAL) { /* * Special case in open mode. * Force action on the screen when a single * line is put even if it is identical to * the current line, e.g. on YP; otherwise * you can't tell anything happened. */ vjumpto(dot, cursor, '.'); continue; } pfixup: vrepaint(cursor); vfixcurs(); continue; /* * ^^ Return to previous file. * Like a :e #, and thus can be used after a * "No Write" diagnostic. */ case CTRL(^): forbid (hadcnt); vsave(); ckaw(); oglobp = globp; if (value(AUTOWRITE)) globp = "e! #"; else globp = "e #"; goto gogo; /* * ^] Takes word after cursor as tag, and then does * tag command. Read ``go right to''. */ case CTRL(]): grabtag(); oglobp = globp; globp = "tag"; goto gogo; /* * & Like :& */ case '&': oglobp = globp; globp = "&"; goto gogo; /* * ^G Bring up a status line at the bottom of * the screen, like a :file command. * * BUG: Was ^S but doesn't work in cbreak mode */ case CTRL(g): oglobp = globp; globp = "file"; gogo: addr = dot; vsave(); goto doinit; #ifdef SIGTSTP /* * ^Z: suspend editor session and temporarily return * to shell. Only works with Berkeley/IIASA process * control in kernel. */ case CTRL(z): forbid(dosusp == 0 || !ldisc); vsave(); oglobp = globp; globp = "stop"; goto gogo; #endif /* * : Read a command from the echo area and * execute it in command mode. */ case ':': forbid (hadcnt); vsave(); i = tchng; addr = dot; if (readecho(c)) { esave[0] = 0; goto fixup; } getDOT(); /* * Use the visual undo buffer to store the global * string for command mode, since it is idle right now. */ oglobp = globp; strcpy(vutmp, genbuf+1); globp = vutmp; doinit: esave[0] = 0; fixech(); /* * Have to finagle around not to lose last * character after this command (when run from ex * command mode). This is clumsy. */ d = peekc; ungetchar(0); if (shouldpo) { /* * So after a "Hit return..." ":", we do * another "Hit return..." the next time */ pofix(); shouldpo = 0; } CATCH /* * Save old values of options so we can * notice when they change; switch into * cooked mode so we are interruptible. */ onumber = value(NUMBER); olist = value(LIST); OPline = Pline; OPutchar = Putchar; #ifndef CBREAK vcook(); #endif commands(1, 1); if (dot == zero && dol > zero) dot = one; #ifndef CBREAK vraw(); #endif ONERR #ifndef CBREAK vraw(); #endif copy(esave, vtube[WECHO], TUBECOLS); ENDCATCH fixol(); Pline = OPline; Putchar = OPutchar; ungetchar(d); globp = oglobp; /* * If we ended up with no lines in the buffer, make * a line, and don't consider the buffer changed. */ if (dot == zero) { fixzero(); sync(); } splitw = 0; /* * Special case: did list/number options change? */ if (onumber != value(NUMBER)) setnumb(value(NUMBER)); if (olist != value(LIST)) setlist(value(LIST)); fixup: /* * If a change occurred, other than * a write which clears changes, then * we should allow an undo even if . * didn't move. * * BUG: You can make this wrong by * tricking around with multiple commands * on one line of : escape, and including * a write command there, but its not * worth worrying about. */ if (FIXUNDO && tchng && tchng != i) vundkind = VMANY, cursor = 0; /* * If we are about to do another :, hold off * updating of screen. */ if (vcnt < 0 && Peekkey == ':') { getDOT(); shouldpo = 1; continue; } shouldpo = 0; /* * In the case where the file being edited is * new; e.g. if the initial state hasn't been * saved yet, then do so now. */ if (unddol == truedol) { vundkind = VNONE; Vlines = lineDOL(); if (!inglobal) savevis(); addr = zero; vcnt = 0; if (esave[0] == 0) copy(esave, vtube[WECHO], TUBECOLS); } /* * If the current line moved reset the cursor position. */ if (dot != addr) { vmoving = 0; cursor = 0; } /* * If current line is not on screen or if we are * in open mode and . moved, then redraw. */ i = vcline + (dot - addr); if (i < 0 || i >= vcnt && i >= -vcnt || state != VISUAL && dot != addr) { if (state == CRTOPEN) vup1(); if (vcnt > 0) vcnt = 0; vjumpto(dot, (char *) 0, '.'); } else { /* * Current line IS on screen. * If we did a [Hit return...] then * restore vcnt and clear screen if in visual */ vcline = i; if (vcnt < 0) { vcnt = -vcnt; if (state == VISUAL) vclear(); else if (state == CRTOPEN) { vcnt = 0; } } /* * Limit max value of vcnt based on $ */ i = vcline + lineDOL() - lineDOT() + 1; if (i < vcnt) vcnt = i; /* * Dirty and repaint. */ vdirty(0, LINES); vrepaint(cursor); } /* * If in visual, put back the echo area * if it was clobberred. */ if (state == VISUAL) { int sdc = destcol, sdl = destline; splitw++; vigoto(WECHO, 0); for (i = 0; i < TUBECOLS - 1; i++) { if (esave[i] == 0) break; vputchar(esave[i]); } splitw = 0; vgoto(sdl, sdc); } continue; /* * u undo the last changing command. */ case 'u': vundo(1); continue; /* * U restore current line to initial state. */ case 'U': vUndo(); continue; fonfon: beep(); vmacp = 0; inopen = 1; /* might have been -1 */ continue; } /* * Rest of commands are decoded by the operate * routine. */ operate(c, cnt); } }
// Return commands to restore this breakpoint, using the dummy number // NR. If AS_DUMMY is set, delete the breakpoint immediately in order // to increase the breakpoint number. If ADDR is set, use ADDR as // (fake) address. If COND is set, use COND as (fake) condition. // Return true iff successful. bool BreakPoint::get_state(std::ostream& os, int nr, bool as_dummy, string pos, string cond) { if (pos.empty()) { if (line_nr() > 0) pos = file_name() + ":" + itostring(line_nr()); else pos = string('*') + address(); } if (cond == char(-1)) cond = real_condition(); const string num = "@" + itostring(nr) + "@"; switch (gdb->type()) { case BASH: case GDB: case MAKE: case PYDB: case DBG: { switch (type()) { case BREAKPOINT: { switch (dispo()) { case BPKEEP: case BPDIS: os << "break " << pos << "\n"; break; case BPDEL: os << "tbreak " << pos << "\n"; break; } break; } case WATCHPOINT: { os << gdb->watch_command(expr(), watch_mode()) << "\n"; break; } case TRACEPOINT: case ACTIONPOINT: { // Not handled - FIXME break; } } if (!as_dummy) { // Extra infos if (!enabled() && gdb->has_disable_command()) os << gdb->disable_command(num) << "\n"; int ignore = ignore_count(); if (ignore > 0 && gdb->has_ignore_command()) os << gdb->ignore_command(num, ignore) << "\n"; if (!cond.empty() && gdb->has_condition_command()) os << gdb->condition_command(num, cond) << "\n"; if (commands().size() != 0) { os << "commands " << num << "\n"; for (int i = 0; i < commands().size(); i++) os << commands()[i] << "\n"; os << "end\n"; } } break; } case DBX: { string cond_suffix = ""; if (!cond.empty()) { if (gdb->has_handler_command()) cond_suffix = " -if " + cond; else cond_suffix = " if " + cond; } switch (type()) { case BREAKPOINT: if (!func().empty()) { os << "stop in " << func() << "\n"; } else if (pos.contains('*', 0)) { os << "stop at " << pos.after('*') << cond_suffix << '\n'; } else { os << "file " << pos.before(':') << "\n"; os << "stop at " << pos.after(':') << cond_suffix << "\n"; } break; case WATCHPOINT: os << "stop " << expr() << cond_suffix << '\n'; break; case TRACEPOINT: case ACTIONPOINT: { // Not handled - FIXME break; } } if (!as_dummy) { // Extra infos if (!enabled() && gdb->has_disable_command()) os << gdb->disable_command(num) << "\n"; int ignore = ignore_count(); if (ignore > 0 && gdb->has_ignore_command()) os << gdb->ignore_command(num, ignore) << "\n"; } break; } case JDB: { os << "stop at " << pos << "\n"; break; } case XDB: { string cond_suffix; if (!cond.empty() && !gdb->has_condition_command()) cond_suffix = " {if " + cond + " {} {Q;c}}"; if (pos.contains('*', 0)) os << "ba " << pos.after('*') << cond_suffix << '\n'; else os << "b " << pos << cond_suffix << "\n"; if (!as_dummy) { // Extra infos if (!enabled() && gdb->has_disable_command()) os << gdb->disable_command(num) << "\n"; int ignore = ignore_count(); if (ignore > 0 && gdb->has_ignore_command()) os << gdb->ignore_command(num, ignore) << "\n"; } break; } case PERL: { string cond_suffix; if (!cond.empty()) cond_suffix = " " + cond; os << "f " << pos.before(':') << "\n"; if (type() == BREAKPOINT) os << "b " << pos.after(':') << cond_suffix << "\n"; if (commands().size() != 0) { os << "a " << pos.after(':') << " "; for (int i = 0; i < commands().size(); i++) os << commands()[i] << ";"; os << "\n"; } break; } } if (as_dummy && gdb->has_delete_command()) { // Delete the breakpoint just created os << gdb->delete_command(num) << "\n"; } return true; }
int main(int argc, char** argv) { char* s; NoP(argc); if (s = strrchr(*argv, '/')) s++; else s = *argv; ed.restricted = streq(s, "red"); error_info.id = s; error_info.write = helpwrite; init(); for (;;) { for (;;) { switch (optget(argv, usage)) { case 'O': ed.reflags |= REG_LENIENT; continue; case 'S': ed.reflags &= ~REG_LENIENT; continue; case 'h': ed.help = 1; continue; case 'o': ed.msg = sfstderr; sfstrseek(ed.buffer.file, 0, SEEK_SET); sfputr(ed.buffer.file, "/dev/stdout", 0); continue; case 'p': sfstrseek(ed.buffer.prompt, 0, SEEK_SET); sfputr(ed.buffer.prompt, opt_info.arg, 0); ed.prompt = 1; continue; case 'q': signal(SIGQUIT, SIG_DFL); ed.verbose = 1; continue; case 's': ed.verbose = 0; continue; case '?': ed.help++; error(ERROR_USAGE|4, "%s", opt_info.arg); ed.help--; break; case ':': ed.help++; error(2, "%s", opt_info.arg); ed.help--; continue; } break; } if (!*(argv += opt_info.index) || **argv != '-' || *(*argv + 1)) break; ed.verbose = 0; } if (*argv) { if (*(argv + 1)) error(ERROR_USAGE|4, "%s", optusage(NiL)); sfprintf(ed.buffer.global, "e %s", *argv); if (!(ed.global = sfstruse(ed.buffer.global))) error(ERROR_SYSTEM|3, "out of space"); } edit(); sfdcslow(sfstdin); setjmp(ed.again); commands(); quit(0); exit(0); }
int main(int argc, char **argv) { Aria::init(); ArRobot robot; ArArgumentParser parser(&argc, argv); ArSimpleConnector simpleConnector(&parser); // The base server object, manages all connections to clients. ArServerBase server; // This object simplifies configuration and opening of the ArServerBase // object. ArServerSimpleOpener simpleOpener(&parser); // parse the command line. fail and print the help if the parsing fails // or if the help was requested with -help parser.loadDefaultArguments(); if (!simpleConnector.parseArgs() || !simpleOpener.parseArgs() || !parser.checkHelpAndWarnUnparsed()) { simpleConnector.logOptions(); simpleOpener.logOptions(); exit(1); } // Use the ArSimpleOpener to open the server port if (!simpleOpener.open(&server)) { ArLog::log(ArLog::Terse, "Error: Could not open server on port %d", simpleOpener.getPort()); exit(1); } // // Create services attached to the base server: // // Robot position etc.: ArServerInfoRobot serverInfoRobot(&server, &robot); // Robot control modes (only one mode can be active at once): ArServerModeStop modeStop(&server, &robot); // old ArServerModeDrive modeDrive(&server, &robot); ArServerModeRatioDrive modeRatioDrive(&server, &robot); ArServerModeWander modeWander(&server, &robot); modeStop.addAsDefaultMode(); modeStop.activate(); // This provides a simple way to add new commands. ArServerHandlerCommands commands(&server); // Add our custom command. ArServerHandlerCommands also has other methods // for adding commands taht take different kinds of arguments, or no // arguments. ArGlobalFunctor1<ArArgumentBuilder*> customCommandFunctor(&customCommandHandler); commands.addStringCommand("ExampleCustomCommand", "Example of a custom command. simpleServerExample will print out the text sent with the command.", &customCommandFunctor); // These objects provide various debugging and diagnostic custom commands: ArServerSimpleComUC uCCommands(&commands, &robot); // Get information about the robot ArServerSimpleComMovementLogging loggingCommands(&commands, &robot); // Control logging modeRatioDrive.addControlCommands(&commands); // Drive mode diagnostics // This provides the client (e.g. MobileEyes) with a simple table of string values // (called an InfoGroup). An InfoGroup is kept globally by Aria. // The values in the table sent to clients are retrieved periodically by calling a // functor. ArServerInfoStrings stringInfo(&server); Aria::getInfoGroup()->addAddStringCallback(stringInfo.getAddStringFunctor()); // Here are some example entries in the InfoGroup: Aria::getInfoGroup()->addStringInt( "Motor Packet Count", 10, new ArConstRetFunctorC<int, ArRobot>(&robot, &ArRobot::getMotorPacCount)); // // Connect to the robot: // if (!simpleConnector.connectRobot(&robot)) { printf("Error: Could not connect to robot... exiting\n"); Aria::shutdown(); return 1; } robot.enableMotors(); robot.runAsync(true); // The simple opener might have information to display right before starting // the server thread: simpleOpener.checkAndLog(); // now let the server base run in a new thread, accepting client connections. server.runAsync(); ArLog::log(ArLog::Normal, "Server is now running... Press Ctrl-C to exit."); robot.waitForRunExit(); Aria::shutdown(); exit(0); }
static void vmap_ldinfo (LdInfo *ldi) { struct stat ii, vi; struct vmap *vp; int got_one, retried; int got_exec_file = 0; uint next; int arch64 = ARCH64 (); /* For each *ldi, see if we have a corresponding *vp. If so, update the mapping, and symbol table. If not, add an entry and symbol table. */ do { char *name = LDI_FILENAME (ldi, arch64); char *memb = name + strlen (name) + 1; int fd = LDI_FD (ldi, arch64); retried = 0; if (fstat (fd, &ii) < 0) { /* The kernel sets ld_info to -1, if the process is still using the object, and the object is removed. Keep the symbol info for the removed object and issue a warning. */ warning (_("%s (fd=%d) has disappeared, keeping its symbols"), name, fd); continue; } retry: for (got_one = 0, vp = vmap; vp; vp = vp->nxt) { struct objfile *objfile; /* First try to find a `vp', which is the same as in ldinfo. If not the same, just continue and grep the next `vp'. If same, relocate its tstart, tend, dstart, dend values. If no such `vp' found, get out of this for loop, add this ldi entry as a new vmap (add_vmap) and come back, find its `vp' and so on... */ /* The filenames are not always sufficient to match on. */ if ((name[0] == '/' && strcmp (name, vp->name) != 0) || (memb[0] && strcmp (memb, vp->member) != 0)) continue; /* See if we are referring to the same file. We have to check objfile->obfd, symfile.c:reread_symbols might have updated the obfd after a change. */ objfile = vp->objfile == NULL ? symfile_objfile : vp->objfile; if (objfile == NULL || objfile->obfd == NULL || bfd_stat (objfile->obfd, &vi) < 0) { warning (_("Unable to stat %s, keeping its symbols"), name); continue; } if (ii.st_dev != vi.st_dev || ii.st_ino != vi.st_ino) continue; if (!retried) close (fd); ++got_one; /* Found a corresponding VMAP. Remap! */ vmap_secs (vp, ldi, arch64); /* The objfile is only NULL for the exec file. */ if (vp->objfile == NULL) got_exec_file = 1; /* relocate symbol table(s). */ vmap_symtab (vp); /* Announce new object files. Doing this after symbol relocation makes aix-thread.c's job easier. */ if (vp->objfile) observer_notify_new_objfile (vp->objfile); /* There may be more, so we don't break out of the loop. */ } /* if there was no matching *vp, we must perforce create the sucker(s) */ if (!got_one && !retried) { add_vmap (ldi); ++retried; goto retry; } } while ((next = LDI_NEXT (ldi, arch64)) && (ldi = (void *) (next + (char *) ldi))); /* If we don't find the symfile_objfile anywhere in the ldinfo, it is unlikely that the symbol file is relocated to the proper address. And we might have attached to a process which is running a different copy of the same executable. */ if (symfile_objfile != NULL && !got_exec_file) { warning (_("Symbol file %s\nis not mapped; discarding it.\n\ If in fact that file has symbols which the mapped files listed by\n\ \"info files\" lack, you can load symbols with the \"symbol-file\" or\n\ \"add-symbol-file\" commands (note that you must take care of relocating\n\ symbols to the proper address)."), symfile_objfile->name); free_objfile (symfile_objfile); gdb_assert (symfile_objfile == NULL); }
void global(bool k) { register char *gp; register int c; register line *a1; char globuf[GBSIZE], *Cwas; int lines = lineDOL(); char *oglobp = globp; Cwas = Command; if (inglobal) error("Global within global@not allowed"); markDOT(); setall(); nonzero(); if (skipend()) error("Global needs re|Missing regular expression for global"); c = ex_getchar(); ignore(compile(c, 0)); savere(scanre); gp = globuf; while ((c = ex_getchar()) != '\n') { switch (c) { case EOF: c = '\n'; goto brkwh; case '\\': c = ex_getchar(); switch (c) { case '\\': ungetchar(c); break; case '\n': break; default: *gp++ = '\\'; break; } break; } *gp++ = c; if (gp >= &globuf[GBSIZE - 2]) error("Global command too long"); } brkwh: ungetchar(c); ex_newline(); *gp++ = c; *gp++ = 0; inglobal = 1; for (a1 = one; a1 <= dol; a1++) { *a1 &= ~01; if (a1 >= addr1 && a1 <= addr2 && execute(0, a1) == k) *a1 |= 01; } /* should use gdelete from ed to avoid n**2 here on g/.../d */ saveall(); if (inopen) inopen = -1; for (a1 = one; a1 <= dol; a1++) { if (*a1 & 01) { *a1 &= ~01; dot = a1; globp = globuf; commands(1, 1); a1 = zero; } } globp = oglobp; inglobal = 0; endline = 1; Command = Cwas; netchHAD(lines); setlastchar(EOF); if (inopen) { ungetchar(EOF); inopen = 1; } }
PUBLIC int main(int argc, char *argv[]) { jmp_buf jmpbuf; struct sigaction sa; struct name *to, *cc, *bcc, *smopts; #ifdef MIME_SUPPORT struct name *attach_optargs; struct name *attach_end; #endif char *subject; const char *ef; char nosrc = 0; const char *rc; int Hflag; int i; /* * For portability, call setprogname() early, before * getprogname() is called. */ (void)setprogname(argv[0]); /* * Set up a reasonable environment. * Figure out whether we are being run interactively, * start the SIGCHLD catcher, and so forth. * (Other signals are setup later by sig_setup().) */ (void)sigemptyset(&sa.sa_mask); sa.sa_flags = SA_RESTART; sa.sa_handler = sigchild; (void)sigaction(SIGCHLD, &sa, NULL); if (isatty(0)) assign(ENAME_INTERACTIVE, ""); image = -1; /* * Now, determine how we are being used. * We successively pick off - flags. * If there is anything left, it is the base of the list * of users to mail to. Argp will be set to point to the * first of these users. */ rc = NULL; ef = NULL; to = NULL; cc = NULL; bcc = NULL; smopts = NULL; subject = NULL; Hflag = 0; #ifdef MIME_SUPPORT attach_optargs = NULL; attach_end = NULL; while ((i = getopt(argc, argv, ":~EH:INT:a:b:c:dfinr:s:u:v")) != -1) #else while ((i = getopt(argc, argv, ":~EH:INT:b:c:dfinr:s:u:v")) != -1) #endif { switch (i) { case 'T': /* * Next argument is temp file to write which * articles have been read/deleted for netnews. */ Tflag = optarg; if ((i = creat(Tflag, 0600)) < 0) { warn("%s", Tflag); exit(1); } (void)close(i); break; #ifdef MIME_SUPPORT case 'a': { struct name *np; np = nalloc(optarg, 0); if (attach_end == NULL) attach_optargs = np; else { np->n_blink = attach_end; attach_end->n_flink = np; } attach_end = np; break; } #endif case 'u': /* * Next argument is person to pretend to be. */ myname = optarg; (void)unsetenv("MAIL"); break; case 'i': /* * User wants to ignore interrupts. * Set the variable "ignore" */ assign(ENAME_IGNORE, ""); break; case 'd': debug++; break; case 'r': rc = optarg; break; case 's': /* * Give a subject field for sending from * non terminal */ subject = optarg; break; case 'f': /* * User is specifying file to "edit" with Mail, * as opposed to reading system mailbox. * If no argument is given after -f, we read his * mbox file. * * getopt() can't handle optional arguments, so here * is an ugly hack to get around it. */ if ((argv[optind]) && (argv[optind][0] != '-')) ef = argv[optind++]; else ef = "&"; break; case 'H': /* * Print out the headers and quit. */ Hflag = get_Hflag(argv); break; case 'n': /* * User doesn't want to source /usr/lib/Mail.rc */ nosrc++; break; case 'N': /* * Avoid initial header printing. */ assign(ENAME_NOHEADER, ""); break; case 'v': /* * Send mailer verbose flag */ assign(ENAME_VERBOSE, ""); break; case 'I': case '~': /* * We're interactive */ assign(ENAME_INTERACTIVE, ""); break; case 'c': /* * Get Carbon Copy Recipient list */ cc = cat(cc, lexpand(optarg, GCC)); break; case 'b': /* * Get Blind Carbon Copy Recipient list */ bcc = cat(bcc, lexpand(optarg, GBCC)); break; case 'E': /* * Don't send empty files. */ assign(ENAME_DONTSENDEMPTY, ""); break; case ':': /* * An optarg was expected but not found. */ if (optopt == 'H') { Hflag = get_Hflag(NULL); break; } (void)fprintf(stderr, "%s: option requires an argument -- %c\n", getprogname(), optopt); /* FALLTHROUGH */ case '?': /* * An unknown option flag. We need to do the * error message. */ if (optopt != '?') (void)fprintf(stderr, "%s: unknown option -- %c\n", getprogname(), optopt); usage(); /* print usage message and die */ /*NOTREACHED*/ } } for (i = optind; (argv[i]) && (*argv[i] != '-'); i++) to = cat(to, nalloc(argv[i], GTO)); for (/*EMPTY*/; argv[i]; i++) smopts = cat(smopts, nalloc(argv[i], GSMOPTS)); /* * Check for inconsistent arguments. */ if (to == NULL && (subject != NULL || cc != NULL || bcc != NULL)) errx(EXIT_FAILURE, "You must specify direct recipients with -s, -c, or -b."); if (ef != NULL && to != NULL) { errx(EXIT_FAILURE, "Cannot give -f and people to send to."); } if (Hflag != 0 && to != NULL) errx(EXIT_FAILURE, "Cannot give -H and people to send to."); #ifdef MIME_SUPPORT if (attach_optargs != NULL && to == NULL) errx(EXIT_FAILURE, "Cannot give -a without people to send to."); #endif tinit(); /* must be done before loading the rcfile */ input = stdin; mailmode = Hflag ? mm_hdrsonly : to ? mm_sending : mm_receiving; spreserve(); if (!nosrc) load(_PATH_MASTER_RC); /* * Expand returns a savestr, but load only uses the file name * for fopen, so it's safe to do this. */ if (rc == NULL && (rc = getenv("MAILRC")) == NULL) rc = "~/.mailrc"; load(expand(rc)); setscreensize(); /* do this after loading the rcfile */ #ifdef USE_EDITLINE /* * This is after loading the MAILRC so we can use value(). * Avoid editline in mm_hdrsonly mode or pipelines will screw * up. XXX - there must be a better way! */ if (mailmode != mm_hdrsonly) init_editline(); #endif sig_setup(); switch (mailmode) { case mm_sending: (void)mail(to, cc, bcc, smopts, subject, mime_attach_optargs(attach_optargs)); /* * why wait? */ exit(senderr); break; /* XXX - keep lint happy */ case mm_receiving: case mm_hdrsonly: /* * Ok, we are reading mail. * Decide whether we are editing a mailbox or reading * the system mailbox, and open up the right stuff. */ if (ef == NULL) ef = "%"; if (setfile(ef) < 0) exit(1); /* error already reported */ if (value(ENAME_QUIET) == NULL) (void)printf("Mail version %s. Type ? for help.\n", version); if (mailmode == mm_hdrsonly) show_headers_and_exit(Hflag); /* NORETURN */ announce(); (void)fflush(stdout); if (setjmp(jmpbuf) != 0) { /* Return here if quit() fails below. */ (void)printf("Use 'exit' to quit without saving changes.\n"); } commands(); /* Ignore these signals from now on! */ (void)signal(SIGHUP, SIG_IGN); (void)signal(SIGINT, SIG_IGN); (void)signal(SIGQUIT, SIG_IGN); quit(jmpbuf); break; default: assert(/*CONSTCOND*/0); break; } return 0; }
int main(int argc, char **argv) { // Initialize Aria and Arnl global information Aria::init(); Arnl::init(); // The robot object ArRobot robot; // Parse the command line arguments. ArArgumentParser parser(&argc, argv); // Set up our simpleConnector, to connect to the robot and laser //ArSimpleConnector simpleConnector(&parser); ArRobotConnector robotConnector(&parser, &robot); // Connect to the robot if (!robotConnector.connectRobot()) { ArLog::log(ArLog::Normal, "Error: Could not connect to robot... exiting"); Aria::exit(3); } // Set up where we'll look for files. Arnl::init() set Aria's default // directory to Arnl's default directory; addDirectories() appends this // "examples" directory. char fileDir[1024]; ArUtil::addDirectories(fileDir, sizeof(fileDir), Aria::getDirectory(), "examples"); // To direct log messages to a file, or to change the log level, use these calls: //ArLog::init(ArLog::File, ArLog::Normal, "log.txt", true, true); //ArLog::init(ArLog::File, ArLog::Verbose); // Add a section to the configuration to change ArLog parameters ArLog::addToConfig(Aria::getConfig()); // set up a gyro (if the robot is older and its firmware does not // automatically incorporate gyro corrections, then this object will do it) ArAnalogGyro gyro(&robot); // Our networking server ArServerBase server; // Set up our simpleOpener, used to set up the networking server ArServerSimpleOpener simpleOpener(&parser); // the laser connector ArLaserConnector laserConnector(&parser, &robot, &robotConnector); // Tell the laser connector to always connect the first laser since // this program always requires a laser. parser.addDefaultArgument("-connectLaser"); // Load default arguments for this computer (from /etc/Aria.args, environment // variables, and other places) parser.loadDefaultArguments(); // Parse arguments if (!Aria::parseArgs() || !parser.checkHelpAndWarnUnparsed()) { logOptions(argv[0]); Aria::exit(1); } // This causes Aria::exit(9) to be called if the robot unexpectedly // disconnects ArGlobalFunctor1<int> shutdownFunctor(&Aria::exit, 9); robot.addDisconnectOnErrorCB(&shutdownFunctor); // Create an ArSonarDevice object (ArRangeDevice subclass) and // connect it to the robot. ArSonarDevice sonarDev; robot.addRangeDevice(&sonarDev); // This object will allow robot's movement parameters to be changed through // a Robot Configuration section in the ArConfig global configuration facility. ArRobotConfig robotConfig(&robot); // Include gyro configuration options in the robot configuration section. robotConfig.addAnalogGyro(&gyro); // Start the robot thread. robot.runAsync(true); // connect the laser(s) if it was requested, this adds them to the // robot too, and starts them running in their own threads if (!laserConnector.connectLasers()) { ArLog::log(ArLog::Normal, "Could not connect to all lasers... exiting\n"); Aria::exit(2); } // find the laser we should use for localization and/or mapping, // which will be the first laser robot.lock(); ArLaser *firstLaser = robot.findLaser(1); if (firstLaser == NULL || !firstLaser->isConnected()) { ArLog::log(ArLog::Normal, "Did not have laser 1 or it is not connected, cannot start localization and/or mapping... exiting"); Aria::exit(2); } robot.unlock(); /* Create and set up map object */ // Set up the map object, this will look for files in the examples // directory (unless the file name starts with a /, \, or . // You can take out the 'fileDir' argument to look in the program's current directory // instead. // When a configuration file is loaded into ArConfig later, if it specifies a // map file, then that file will be loaded as the map. ArMap map(fileDir); // set it up to ignore empty file names (otherwise if a configuration omits // the map file, the whole configuration change will fail) map.setIgnoreEmptyFileName(true); // ignore the case, so that if someone is using MobileEyes or // MobilePlanner from Windows and changes the case on a map name, // it will still work. map.setIgnoreCase(true); /* Create localization and path planning threads */ ArPathPlanningTask pathTask(&robot, &sonarDev, &map); ArLog::log(ArLog::Normal, "Creating laser localization task"); // Laser Monte-Carlo Localization ArLocalizationTask locTask(&robot, firstLaser, &map); // Set some options on each laser that the laser connector // connected to. std::map<int, ArLaser *>::iterator laserIt; for (laserIt = robot.getLaserMap()->begin(); laserIt != robot.getLaserMap()->end(); laserIt++) { int laserNum = (*laserIt).first; ArLaser *laser = (*laserIt).second; // Skip lasers that aren't connected if(!laser->isConnected()) continue; // add the disconnectOnError CB to shut things down if the laser // connection is lost laser->addDisconnectOnErrorCB(&shutdownFunctor); // set the number of cumulative readings the laser will take laser->setCumulativeBufferSize(200); // add the lasers to the path planning task pathTask.addRangeDevice(laser, ArPathPlanningTask::BOTH); // set the cumulative clean offset (so that they don't all fire at once) laser->setCumulativeCleanOffset(laserNum * 100); // reset the cumulative clean time (to make the new offset take effect) laser->resetLastCumulativeCleanTime(); // Add the packet count to the Aria info strings (It will be included in // MobileEyes custom details so you can monitor whether the laser data is // being received correctly) std::string laserPacketCountName; laserPacketCountName = laser->getName(); laserPacketCountName += " Packet Count"; Aria::getInfoGroup()->addStringInt( laserPacketCountName.c_str(), 10, new ArRetFunctorC<int, ArLaser>(laser, &ArLaser::getReadingCount)); } // Used for optional multirobot features (see below) (TODO move to multirobot // example?) ArClientSwitchManager clientSwitch(&server, &parser); /* Start the server */ // Open the networking server if (!simpleOpener.open(&server, fileDir, 240)) { ArLog::log(ArLog::Normal, "Error: Could not open server."); exit(2); } /* Create various services that provide network access to clients (such as * MobileEyes), as well as add various additional features to ARNL */ // ARNL can optionally get information about the positions of other robots from a // "central server" (see central server example program), if command // line options specifying the address of the central server was given. // If there is no central server, then the address of each other robot // can instead be given in the configuration, and the multirobot systems // will connect to each robot (or "peer") individually. // TODO move this to multirobot example? bool usingCentralServer = false; if(clientSwitch.getCentralServerHostName() != NULL) usingCentralServer = true; // if we're using the central server then we want to create the // multiRobot central classes if (usingCentralServer) { // Make the handler for multi robot information (this sends the // information to the central server) //ArServerHandlerMultiRobot *handlerMultiRobot = new ArServerHandlerMultiRobot(&server, &robot, &pathTask, &locTask, &map); // Normally each robot, and the central server, must all have // the same map name for the central server to share robot // information. (i.e. they are operating in the same space). // This changes the map name that ArServerHandlerMutliRobot // reports to the central server, in case you want this individual // robot to load a different map file name, but still report // the common map file to the central server. //handlerMultiRobot->overrideMapName("central.map"); // the range device that gets the multi robot information from // the central server and presents it as virtual range readings // to ARNL ArMultiRobotRangeDevice *multiRobotRangeDevice = new ArMultiRobotRangeDevice(&server); robot.addRangeDevice(multiRobotRangeDevice); pathTask.addRangeDevice(multiRobotRangeDevice, ArPathPlanningTask::BOTH); // Set up options for drawing multirobot information in MobileEyes. multiRobotRangeDevice->setCurrentDrawingData( new ArDrawingData("polyDots", ArColor(125, 125, 0), 100, 73, 1000), true); multiRobotRangeDevice->setCumulativeDrawingData( new ArDrawingData("polyDots", ArColor(125, 0, 125), 100, 72, 1000), true); // This sets up the localization to use the known poses of other robots // for its localization in cases where numerous robots crowd out the map. locTask.setMultiRobotCallback(multiRobotRangeDevice->getOtherRobotsCB()); } // if we're not using a central server then create the multirobot peer classes else { // set the path planning so it uses the explicit collision range for how far its planning pathTask.setUseCollisionRangeForPlanningFlag(true); // make our thing that gathers information from the other servers ArServerHandlerMultiRobotPeer *multiRobotPeer = NULL; ArMultiRobotPeerRangeDevice *multiRobotPeerRangeDevice = NULL; multiRobotPeerRangeDevice = new ArMultiRobotPeerRangeDevice(&map); // make our thing that sends information to the other servers multiRobotPeer = new ArServerHandlerMultiRobotPeer(&server, &robot, &pathTask, &locTask); // hook the two together so they both know what priority this robot is multiRobotPeer->setNewPrecedenceCallback( multiRobotPeerRangeDevice->getSetPrecedenceCallback()); // hook the two together so they both know what priority this // robot's fingerprint is multiRobotPeer->setNewFingerprintCallback( multiRobotPeerRangeDevice->getSetFingerprintCallback()); // hook the two together so that the range device can call on the // server handler to change its fingerprint multiRobotPeerRangeDevice->setChangeFingerprintCB( multiRobotPeer->getChangeFingerprintCB()); // then add the robot to the places it needs to be robot.addRangeDevice(multiRobotPeerRangeDevice); pathTask.addRangeDevice(multiRobotPeerRangeDevice, ArPathPlanningTask::BOTH); // Set the range device so that we can see the information its using // to avoid, you can comment these out in order to not see them multiRobotPeerRangeDevice->setCurrentDrawingData( new ArDrawingData("polyDots", ArColor(125, 125, 0), 100, 72, 1000), true); multiRobotPeerRangeDevice->setCumulativeDrawingData( new ArDrawingData("polyDots", ArColor(125, 0, 125), 100, 72, 1000), true); // This sets up the localization to use the known poses of other robots // for its localization in cases where numerous robots crowd out the map. locTask.setMultiRobotCallback( multiRobotPeerRangeDevice->getOtherRobotsCB()); } /* Add additional range devices to the robot and path planning task (so it avoids obstacles detected by these devices) */ // Add IR range device to robot and path planning task (so it avoids obstacles // detected by this device) robot.lock(); ArIRs irs; robot.addRangeDevice(&irs); pathTask.addRangeDevice(&irs, ArPathPlanningTask::CURRENT); // Add bumpers range device to robot and path planning task (so it avoids obstacles // detected by this device) ArBumpers bumpers; robot.addRangeDevice(&bumpers); pathTask.addRangeDevice(&bumpers, ArPathPlanningTask::CURRENT); // Add range device which uses forbidden regions given in the map to give virtual // range device readings to ARNL. (so it avoids obstacles // detected by this device) ArForbiddenRangeDevice forbidden(&map); robot.addRangeDevice(&forbidden); pathTask.addRangeDevice(&forbidden, ArPathPlanningTask::CURRENT); robot.unlock(); // Action to slow down robot when localization score drops but not lost. ArActionSlowDownWhenNotCertain actionSlowDown(&locTask); pathTask.getPathPlanActionGroup()->addAction(&actionSlowDown, 140); // Action to stop the robot when localization is "lost" (score too low) ArActionLost actionLostPath(&locTask, &pathTask); pathTask.getPathPlanActionGroup()->addAction(&actionLostPath, 150); // Arnl uses this object when it must replan its path because its // path is completely blocked. It will use an older history of sensor // readings to replan this new path. This should not be used with SONARNL // since sonar readings are not accurate enough and may prevent the robot // from planning through space that is actually clear. ArGlobalReplanningRangeDevice replanDev(&pathTask); // Service to provide drawings of data in the map display : ArServerInfoDrawings drawings(&server); drawings.addRobotsRangeDevices(&robot); drawings.addRangeDevice(&replanDev); /* Draw a box around the local path planning area use this (You can enable this particular drawing from custom commands which is set up down below in ArServerInfoPath) */ ArDrawingData drawingDataP("polyLine", ArColor(200,200,200), 1, 75); ArFunctor2C<ArPathPlanningTask, ArServerClient *, ArNetPacket *> drawingFunctorP(&pathTask, &ArPathPlanningTask::drawSearchRectangle); drawings.addDrawing(&drawingDataP, "Local Plan Area", &drawingFunctorP); /* Show the sample points used by MCL */ ArDrawingData drawingDataL("polyDots", ArColor(0,255,0), 100, 75); ArFunctor2C<ArLocalizationTask, ArServerClient *, ArNetPacket *> drawingFunctorL(&locTask, &ArLocalizationTask::drawRangePoints); drawings.addDrawing(&drawingDataL, "Localization Points", &drawingFunctorL); // "Custom" commands. You can add your own custom commands here, they will // be available in MobileEyes' custom commands (enable in the toolbar or // access through Robot Tools) ArServerHandlerCommands commands(&server); // These provide various kinds of information to the client: ArServerInfoRobot serverInfoRobot(&server, &robot); ArServerInfoSensor serverInfoSensor(&server, &robot); ArServerInfoPath serverInfoPath(&server, &robot, &pathTask); serverInfoPath.addSearchRectangleDrawing(&drawings); serverInfoPath.addControlCommands(&commands); // Provides localization info and allows the client (MobileEyes) to relocalize at a given // pose: ArServerInfoLocalization serverInfoLocalization(&server, &robot, &locTask); ArServerHandlerLocalization serverLocHandler(&server, &robot, &locTask); // If you're using MobileSim, ArServerHandlerLocalization sends it a command // to move the robot's true pose if you manually do a localization through // MobileEyes. To disable that behavior, use this constructor call instead: // ArServerHandlerLocalization serverLocHandler(&server, &robot, true, false); // The fifth argument determines whether to send the command to MobileSim. // Provide the map to the client (and related controls): ArServerHandlerMap serverMap(&server, &map); // These objects add some simple (custom) commands to 'commands' for testing and debugging: ArServerSimpleComUC uCCommands(&commands, &robot); // Send any command to the microcontroller ArServerSimpleComMovementLogging loggingCommands(&commands, &robot); // configure logging ArServerSimpleComLogRobotConfig configCommands(&commands, &robot); // trigger logging of the robot config parameters // ArServerSimpleServerCommands serverCommands(&commands, &server); // monitor networking behavior (track packets sent etc.) // service that allows the client to monitor the communication link status // between the robot and the client. // ArServerHandlerCommMonitor handlerCommMonitor(&server); // service that allows client to change configuration parameters in ArConfig ArServerHandlerConfig handlerConfig(&server, Aria::getConfig(), Arnl::getTypicalDefaultParamFileName(), Aria::getDirectory()); /* Set up the possible modes for remote control from a client such as * MobileEyes: */ // Mode To go to a goal or other specific point: ArServerModeGoto modeGoto(&server, &robot, &pathTask, &map, locTask.getRobotHome(), locTask.getRobotHomeCallback()); // Mode To stop and remain stopped: ArServerModeStop modeStop(&server, &robot); // Cause the sonar to turn off automatically // when the robot is stopped, and turn it back on when commands to move // are sent. (Note, if using SONARNL to localize, then don't do this // since localization may get lost) ArSonarAutoDisabler sonarAutoDisabler(&robot); // Teleoperation modes To drive by keyboard, joystick, etc: ArServerModeRatioDrive modeRatioDrive(&server, &robot); // ArServerModeDrive modeDrive(&server, &robot); // Older mode for compatability // Prevent normal teleoperation driving if localization is lost using // a high-priority action, which enables itself when the particular mode is // active. // (You have to enter unsafe drive mode to drive when lost.) ArActionLost actionLostRatioDrive(&locTask, &pathTask, &modeRatioDrive); modeRatioDrive.getActionGroup()->addAction(&actionLostRatioDrive, 110); // Add drive mode section to the configuration, and also some custom (simple) commands: modeRatioDrive.addToConfig(Aria::getConfig(), "Teleop settings"); modeRatioDrive.addControlCommands(&commands); // Wander mode (also prevent wandering if lost): ArServerModeWander modeWander(&server, &robot); ArActionLost actionLostWander(&locTask, &pathTask, &modeWander); modeWander.getActionGroup()->addAction(&actionLostWander, 110); // This provides a small table of interesting information for the client // to display to the operator. You can add your own callbacks to show any // data you want. ArServerInfoStrings stringInfo(&server); Aria::getInfoGroup()->addAddStringCallback(stringInfo.getAddStringFunctor()); // Provide a set of informational data (turn on in MobileEyes with // View->Custom Details) Aria::getInfoGroup()->addStringInt( "Motor Packet Count", 10, new ArConstRetFunctorC<int, ArRobot>(&robot, &ArRobot::getMotorPacCount)); Aria::getInfoGroup()->addStringDouble( "Laser Localization Score", 8, new ArRetFunctorC<double, ArLocalizationTask>( &locTask, &ArLocalizationTask::getLocalizationScore), "%.03f"); Aria::getInfoGroup()->addStringInt( "Laser Loc Num Samples", 8, new ArRetFunctorC<int, ArLocalizationTask>( &locTask, &ArLocalizationTask::getCurrentNumSamples), "%4d"); // Display gyro status if gyro is enabled and is being handled by the firmware (gyro types 2, 3, or 4). // (If the firmware detects an error communicating with the gyro or IMU it // returns a flag, and stops using it.) // (This gyro type parameter, and fault flag, are only in ARCOS, not Seekur firmware) if(robot.getOrigRobotConfig() && robot.getOrigRobotConfig()->getGyroType() > 1) { Aria::getInfoGroup()->addStringString( "Gyro/IMU Status", 10, new ArGlobalRetFunctor1<const char*, ArRobot*>(&getGyroStatusString, &robot) ); } // Setup the dock if there is a docking system on board. ArServerModeDock *modeDock = NULL; modeDock = ArServerModeDock::createDock(&server, &robot, &locTask, &pathTask); if (modeDock != NULL) { modeDock->checkDock(); modeDock->addAsDefaultMode(); modeDock->addToConfig(Aria::getConfig()); modeDock->addControlCommands(&commands); } // Make Stop mode the default (If current mode deactivates without entering // a new mode, then Stop Mode will be selected) modeStop.addAsDefaultMode(); // TODO move up near where stop mode is created? /* Services that allow the client to initiate scanning with the laser to create maps in Mapper3 (So not possible with SONARNL): */ ArServerHandlerMapping handlerMapping(&server, &robot, firstLaser, fileDir, "", true); // make laser localization stop while mapping handlerMapping.addMappingStartCallback( new ArFunctor1C<ArLocalizationTask, bool> (&locTask, &ArLocalizationTask::setIdleFlag, true)); // and then make it start again when we're doine handlerMapping.addMappingEndCallback( new ArFunctor1C<ArLocalizationTask, bool> (&locTask, &ArLocalizationTask::setIdleFlag, false)); // Make it so our "lost" actions don't stop us while mapping handlerMapping.addMappingStartCallback(actionLostPath.getDisableCB()); handlerMapping.addMappingStartCallback(actionLostRatioDrive.getDisableCB()); handlerMapping.addMappingStartCallback(actionLostWander.getDisableCB()); // And then let them make us stop as usual when done mapping handlerMapping.addMappingEndCallback(actionLostPath.getEnableCB()); handlerMapping.addMappingEndCallback(actionLostRatioDrive.getEnableCB()); handlerMapping.addMappingEndCallback(actionLostWander.getEnableCB()); // don't let forbidden lines show up as obstacles while mapping // (they'll just interfere with driving while mapping, and localization is off anyway) handlerMapping.addMappingStartCallback(forbidden.getDisableCB()); // let forbidden lines show up as obstacles again as usual after mapping handlerMapping.addMappingEndCallback(forbidden.getEnableCB()); /* // If we are on a simulator, move the robot back to its starting position, // and reset its odometry. // This will allow localizeRobotAtHomeBlocking() below will (probably) work (it // tries current odometry (which will be 0,0,0) and all the map // home points. // (Ignored by a real robot) //robot.com(ArCommands::SIM_RESET); */ // create a pose storage class, this will let the program keep track // of where the robot is between runs... after we try and restore // from this file it will start saving the robot's pose into the // file ArPoseStorage poseStorage(&robot); /// if we could restore the pose from then set the sim there (this /// won't do anything to the real robot)... if we couldn't restore /// the pose then just reset the position of the robot (which again /// won't do anything to the real robot) if (poseStorage.restorePose("robotPose")) serverLocHandler.setSimPose(robot.getPose()); else robot.com(ArCommands::SIM_RESET); /* File transfer services: */ #ifdef WIN32 // Not implemented for Windows yet. ArLog::log(ArLog::Normal, "Note, file upload/download services are not implemented for Windows; not enabling them."); #else // This block will allow you to set up where you get and put files // to/from, just comment them out if you don't want this to happen // /* ArServerFileLister fileLister(&server, fileDir); ArServerFileToClient fileToClient(&server, fileDir); ArServerFileFromClient fileFromClient(&server, fileDir, "/tmp"); ArServerDeleteFileOnServer deleteFileOnServer(&server, fileDir); // */ #endif /* Video image streaming, and camera controls (Requires SAVserver or ACTS) */ // Forward any video if either ACTS or SAV server are running. // You can find out more about SAV and ACTS on our website // http://robots.activmedia.com. ACTS is for color tracking and is // a seperate product. SAV just does software A/V transmitting and is // free to all our customers. Just run ACTS or SAV server before you // start this program and this class here will forward video from the // server to the client. ArHybridForwarderVideo videoForwarder(&server, "localhost", 7070); // make a camera to use in case we have video. the camera collection collects // multiple ptz cameras ArPTZ *camera = NULL; ArServerHandlerCamera *handlerCamera = NULL; ArCameraCollection *cameraCollection = NULL; // if we have video then set up a camera if (videoForwarder.isForwardingVideo()) { cameraCollection = new ArCameraCollection(); cameraCollection->addCamera("Cam1", "PTZ", "Camera", "PTZ"); videoForwarder.setCameraName("Cam1"); videoForwarder.addToCameraCollection(*cameraCollection); camera = new ArVCC4(&robot); //, invertedCamera, ArVCC4::COMM_UNKNOWN, true, true); // To use an RVision SEE camera instead: // camera = new ArRVisionPTZ(&robot); camera->init(); handlerCamera = new ArServerHandlerCamera("Cam1", &server, &robot, camera, cameraCollection); pathTask.addGoalFinishedCB( new ArFunctorC<ArServerHandlerCamera>( handlerCamera, &ArServerHandlerCamera::cameraModeLookAtGoalClearGoal)); } // After all of the cameras / videos have been created and added to the collection, // then start the collection server. // if (cameraCollection != NULL) { new ArServerHandlerCameraCollection(&server, cameraCollection); } /* Load configuration values, map, and begin! */ // When parsing the configuration file, also look at the program's command line options // from the command-line argument parser as well as the configuration file. // (So you can use any argument on the command line, namely -map.) Aria::getConfig()->useArgumentParser(&parser); puts("xxx");puts("aaa"); fflush(stdout); // Read in parameter files. ArLog::log(ArLog::Normal, "Loading config file %s into ArConfig (base directory %s)...", Arnl::getTypicalParamFileName(), Aria::getConfig()->getBaseDirectory()); if (!Aria::getConfig()->parseFile(Arnl::getTypicalParamFileName())) { ArLog::log(ArLog::Normal, "Trouble loading configuration file, exiting"); Aria::exit(5); } // Warn about unknown params. if (!simpleOpener.checkAndLog() || !parser.checkHelpAndWarnUnparsed()) { logOptions(argv[0]); Aria::exit(6); } // Warn if there is no map if (map.getFileName() == NULL || strlen(map.getFileName()) <= 0) { ArLog::log(ArLog::Normal, ""); ArLog::log(ArLog::Normal, "### No map file is set up, you can make a map with the following procedure"); ArLog::log(ArLog::Normal, " 0) You can find this information in README.txt or docs/Mapping.txt"); ArLog::log(ArLog::Normal, " 1) Connect to this server with MobileEyes"); ArLog::log(ArLog::Normal, " 2) Go to Tools->Map Creation->Start Scan"); ArLog::log(ArLog::Normal, " 3) Give the map a name and hit okay"); ArLog::log(ArLog::Normal, " 4) Drive the robot around your space (see docs/Mapping.txt"); ArLog::log(ArLog::Normal, " 5) Go to Tools->Map Creation->Stop Scan"); ArLog::log(ArLog::Normal, " 6) Start up Mapper3"); ArLog::log(ArLog::Normal, " 7) Go to File->Open on Robot"); ArLog::log(ArLog::Normal, " 8) Select the .2d you created"); ArLog::log(ArLog::Normal, " 9) Create a .map"); ArLog::log(ArLog::Normal, " 10) Go to File->Save on Robot"); ArLog::log(ArLog::Normal, " 11) In MobileEyes, go to Tools->Robot Config"); ArLog::log(ArLog::Normal, " 12) Choose the Files section"); ArLog::log(ArLog::Normal, " 13) Enter the path and name of your new .map file for the value of the Map parameter."); ArLog::log(ArLog::Normal, " 14) Press OK and your new map should become the map used"); ArLog::log(ArLog::Normal, ""); } // Print a log message notifying user of the directory for map files ArLog::log(ArLog::Normal, ""); ArLog::log(ArLog::Normal, "Directory for maps and file serving: %s", fileDir); ArLog::log(ArLog::Normal, "See the ARNL README.txt for more information"); ArLog::log(ArLog::Normal, ""); // Do an initial localization of the robot. It tries all the home points // in the map, as well as the robot's current odometric position, as possible // places the robot is likely to be at startup. If successful, it will // also save the position it found to be the best localized position as the // "Home" position, which can be obtained from the localization task (and is // used by the "Go to home" network request). locTask.localizeRobotAtHomeBlocking(); // Let the client switch manager (for multirobot) spin off into its own thread // TODO move to multirobot example? clientSwitch.runAsync(); // Start the networking server's thread server.runAsync(); // Add a key handler so that you can exit by pressing // escape. Note that this key handler, however, prevents this program from // running in the background (e.g. as a system daemon or run from // the shell with "&") -- it will lock up trying to read the keys; // remove this if you wish to be able to run this program in the background. ArKeyHandler *keyHandler; if ((keyHandler = Aria::getKeyHandler()) == NULL) { keyHandler = new ArKeyHandler; Aria::setKeyHandler(keyHandler); robot.lock(); robot.attachKeyHandler(keyHandler); robot.unlock(); puts("Server running. To exit, press escape."); } ArnlASyncTaskExample asyncTaskExample(&pathTask, &robot, &modeGoto, &parser); // Enable the motors and wait until the robot exits (disconnection, etc.) or this program is // canceled. robot.enableMotors(); robot.waitForRunExit(); Aria::exit(0); }
int main(int argc, char **argv) { // mandatory init Aria::init(); //ArLog::init(ArLog::StdOut, ArLog::Verbose); // set up our parser ArArgumentParser parser(&argc, argv); // load the default arguments parser.loadDefaultArguments(); // robot ArRobot robot; // set up our simple connector ArRobotConnector robotConnector(&parser, &robot); // add a gyro, it'll see if it should attach to the robot or not ArAnalogGyro gyro(&robot); // set up the robot for connecting if (!robotConnector.connectRobot()) { printf("Could not connect to robot... exiting\n"); Aria::exit(1); } ArDataLogger dataLogger(&robot, "dataLog.txt"); dataLogger.addToConfig(Aria::getConfig()); // our base server object ArServerBase server; ArLaserConnector laserConnector(&parser, &robot, &robotConnector); ArServerSimpleOpener simpleOpener(&parser); ArClientSwitchManager clientSwitchManager(&server, &parser); // parse the command line... fail and print the help if the parsing fails // or if the help was requested if (!Aria::parseArgs() || !parser.checkHelpAndWarnUnparsed()) { Aria::logOptions(); Aria::exit(1); } // Set up where we'll look for files such as user/password char fileDir[1024]; ArUtil::addDirectories(fileDir, sizeof(fileDir), Aria::getDirectory(), "ArNetworking/examples"); // first open the server up if (!simpleOpener.open(&server, fileDir, 240)) { if (simpleOpener.wasUserFileBad()) printf("Bad user/password/permissions file\n"); else printf("Could not open server port\n"); exit(1); } // Range devices: ArSonarDevice sonarDev; robot.addRangeDevice(&sonarDev); ArIRs irs; robot.addRangeDevice(&irs); ArBumpers bumpers; robot.addRangeDevice(&bumpers); // attach services to the server ArServerInfoRobot serverInfoRobot(&server, &robot); ArServerInfoSensor serverInfoSensor(&server, &robot); ArServerInfoDrawings drawings(&server); // modes for controlling robot movement ArServerModeStop modeStop(&server, &robot); ArServerModeRatioDrive modeRatioDrive(&server, &robot); ArServerModeWander modeWander(&server, &robot); modeStop.addAsDefaultMode(); modeStop.activate(); // set up the simple commands ArServerHandlerCommands commands(&server); ArServerSimpleComUC uCCommands(&commands, &robot); // send commands directly to microcontroller ArServerSimpleComMovementLogging loggingCommands(&commands, &robot); // control debug logging ArServerSimpleComGyro gyroCommands(&commands, &robot, &gyro); // configure gyro ArServerSimpleComLogRobotConfig configCommands(&commands, &robot); // control more debug logging ArServerSimpleServerCommands serverCommands(&commands, &server); // control ArNetworking debug logging ArServerSimpleLogRobotDebugPackets logRobotDebugPackets(&commands, &robot, "."); // debugging tool // ArServerModeDrive is an older drive mode. ArServerModeRatioDrive is newer and generally performs better, // but you can use this for old clients if neccesary. //ArServerModeDrive modeDrive(&server, &robot); //modeDrive.addControlCommands(&commands); // configure the drive modes (e.g. enable/disable safe drive) ArServerHandlerConfig serverHandlerConfig(&server, Aria::getConfig()); // make a config handler ArLog::addToConfig(Aria::getConfig()); // let people configure logging modeRatioDrive.addToConfig(Aria::getConfig(), "Teleop settings"); // able to configure teleop settings modeRatioDrive.addControlCommands(&commands); // Forward video if either ACTS or SAV server are running. // You can find out more about SAV and ACTS on our website // http://robots.activmedia.com. ACTS is for color tracking and is // a separate product. SAV just does software A/V transmitting and is // free to all our customers. Just run ACTS or SAV server before you // start this program and this class here will forward video from the // server to the client. ArHybridForwarderVideo videoForwarder(&server, "localhost", 7070); // Control a pan/tilt/zoom camera, if one is installed, and the video // forwarder was enabled above. ArPTZ *camera = NULL; ArServerHandlerCamera *handlerCamera = NULL; ArCameraCollection *cameraCollection = NULL; if (videoForwarder.isForwardingVideo()) { bool invertedCamera = false; camera = new ArVCC4(&robot, invertedCamera, ArVCC4::COMM_UNKNOWN, true, true); camera->init(); cameraCollection = new ArCameraCollection(); cameraCollection->addCamera("Cam1", "VCC4", "Camera", "VCC4"); handlerCamera = new ArServerHandlerCamera("Cam1", &server, &robot, camera, cameraCollection); } // You can use this class to send a set of arbitrary strings // for MobileEyes to display, this is just a small example ArServerInfoStrings stringInfo(&server); Aria::getInfoGroup()->addAddStringCallback(stringInfo.getAddStringFunctor()); Aria::getInfoGroup()->addStringInt( "Motor Packet Count", 10, new ArConstRetFunctorC<int, ArRobot>(&robot, &ArRobot::getMotorPacCount)); /* Aria::getInfoGroup()->addStringInt( "Laser Packet Count", 10, new ArRetFunctorC<int, ArSick>(&sick, &ArSick::getSickPacCount)); */ // start the robot running, true means that if we lose connection the run thread stops robot.runAsync(true); // connect the laser(s) if it was requested if (!laserConnector.connectLasers()) { printf("Could not connect to lasers... exiting\n"); Aria::exit(2); } drawings.addRobotsRangeDevices(&robot); // log whatever we wanted to before the runAsync simpleOpener.checkAndLog(); // now let it spin off in its own thread server.runAsync(); printf("Server is now running...\n"); // Add a key handler so that you can exit by pressing // escape. Note that a key handler prevents you from running // a program in the background on Linux, since it expects an // active terminal to read keys from; remove this if you want // to run it in the background. ArKeyHandler *keyHandler; if ((keyHandler = Aria::getKeyHandler()) == NULL) { keyHandler = new ArKeyHandler; Aria::setKeyHandler(keyHandler); robot.lock(); robot.attachKeyHandler(keyHandler); robot.unlock(); printf("To exit, press escape.\n"); } // Read in parameter files. std::string configFile = "serverDemoConfig.txt"; Aria::getConfig()->setBaseDirectory("./"); if (Aria::getConfig()->parseFile(configFile.c_str(), true, true)) { ArLog::log(ArLog::Normal, "Loaded config file %s", configFile.c_str()); } else { if (ArUtil::findFile(configFile.c_str())) { ArLog::log(ArLog::Normal, "Trouble loading configuration file %s, continuing", configFile.c_str()); } else { ArLog::log(ArLog::Normal, "No configuration file %s, will try to create if config used", configFile.c_str()); } } clientSwitchManager.runAsync(); robot.lock(); robot.enableMotors(); robot.unlock(); robot.waitForRunExit(); Aria::exit(0); }
// Update breakpoint information bool BreakPoint::update(string& info_output, std::ostream& undo_commands, bool& need_total_undo) { string file = file_name(); BreakPoint new_bp(info_output, arg(), number(), file); bool changed = false; myenabled_changed = false; myposition_changed = false; myfile_changed = false; myaddress_changed = false; need_total_undo = false; const string num = "@" + itostring(number()) + "@"; if (new_bp.number() != number()) { mynumber = new_bp.number(); need_total_undo = changed = true; } if (new_bp.type() != type()) { mytype = new_bp.type(); need_total_undo = changed = myenabled_changed = true; } if (new_bp.dispo() != dispo()) { need_total_undo = changed = myenabled_changed = true; mydispo = new_bp.dispo(); } if (new_bp.watch_mode() != watch_mode()) { need_total_undo = changed = myenabled_changed = true; mywatch_mode = new_bp.watch_mode(); } if (new_bp.myenabled != myenabled) { changed = myenabled_changed = true; myenabled = new_bp.myenabled; if (myenabled) { if (gdb->has_disable_command()) undo_commands << gdb->disable_command(num) << "\n"; else need_total_undo = true; } else { if (gdb->has_enable_command()) undo_commands << gdb->enable_command(num) << "\n"; else need_total_undo = true; } } if (type() == BREAKPOINT) { if (new_bp.address() != address()) { changed = myaddress_changed = true; myaddress = new_bp.address(); } if (new_bp.func() != func()) { changed = myposition_changed = true; myfunc = new_bp.func(); } if (new_bp.file_name() != file_name()) { changed = myposition_changed = myfile_changed = true; myfile_name = new_bp.file_name(); } if (new_bp.line_nr() != line_nr()) { changed = myposition_changed = true; myline_nr = new_bp.line_nr(); } } else if (type() == WATCHPOINT) { if (new_bp.expr() != expr()) { changed = true; myexpr = new_bp.expr(); } } if (new_bp.infos() != infos()) { changed = true; myinfos = new_bp.infos(); } if (new_bp.ignore_count() != ignore_count()) { if (gdb->has_ignore_command()) undo_commands << gdb->ignore_command(num, myignore_count) << "\n"; else need_total_undo = true; changed = myenabled_changed = true; myignore_count = new_bp.ignore_count(); } if (new_bp.mycondition != mycondition) { if (gdb->has_condition_command()) undo_commands << gdb->condition_command(num, condition()) << "\n"; else need_total_undo = true; changed = myenabled_changed = true; mycondition = new_bp.mycondition; } if (!equal(new_bp.commands(), commands())) { if (gdb->type() == GDB || gdb->type() == PYDB || gdb->type() == BASH) { undo_commands << "commands " << num << '\n'; for (int i = 0; i < commands().size(); i++) undo_commands << commands()[i] << '\n'; undo_commands << "end\n"; } changed = myenabled_changed = true; mycommands = new_bp.commands(); } return changed; }
/* * Main procedure. Process arguments and then * transfer control to the main command processing loop * in the routine commands. We are entered as either "ex", "edit" or "vi" * and the distinction is made here. Actually, we are "vi" if * there is a 'v' in our name, and "edit" if there is a 'd' in our * name. For edit we just diddle options; for vi we actually * force an early visual command, setting the external initev so * the q command in visual doesn't give command mode. */ int main(int ac, char **av) { #if 0 char *erpath = EXSTRINGS; #endif register char *cp; register int c; bool recov = 0; bool ivis = any('v', av[0]); bool itag = 0; bool fast = 0; #ifdef TRACE register char *tracef; #endif /* * Immediately grab the tty modes so that we wont * get messed up if an interrupt comes in quickly. */ gTTY(1); normf = tty; #if 0 /* * For debugging take files out of . if name is a.out. * If a 'd' in our name, then set options for edit. */ if (av[0][0] == 'a') erpath += 9; #endif if (ivis) { options[MAGIC].odefault = value(MAGIC) = 0; options[BEAUTIFY].odefault = value(BEAUTIFY) = 1; } else if (any('d', av[0])) { value(OPEN) = 0; value(REPORT) = 1; value(MAGIC) = 0; } /* * Open the error message file. */ draino(); #if 0 erfile = open(erpath, 0); if (erfile < 0) { flush(); exit(1); } #endif pstop(); /* * Initialize interrupt handling. */ oldhup = signal(SIGHUP, SIG_IGN); if (oldhup == SIG_DFL) signal(SIGHUP, onhup); oldquit = signal(SIGQUIT, SIG_IGN); ruptible = signal(SIGINT, SIG_IGN) == SIG_DFL; if (signal(SIGTERM, SIG_IGN) == SIG_DFL) signal(SIGTERM, onhup); /* * Initialize end of core pointers. * Normally we avoid breaking back to fendcore after each * file since this can be expensive (much core-core copying). * If your system can scatter load processes you could do * this as ed does, saving a little core, but it will probably * not often make much difference. */ #ifdef UNIX_SBRK fendcore = (line *) sbrk(0); endcore = fendcore - 2; #else # define LINELIMIT 0x8000 fendcore = malloc(LINELIMIT * sizeof(line *)); endcore = fendcore + LINELIMIT - 1; #endif /* * Process flag arguments. */ ac--, av++; while (ac && av[0][0] == '-') { c = av[0][1]; if (c == 0) { hush = 1; value(AUTOPRINT) = 0; fast++; } else switch (c) { #ifdef TRACE case 'T': if (av[0][2] == 0) tracef = "trace"; else { tracef = tttrace; tracef[8] = av[0][2]; if (tracef[8]) tracef[9] = av[0][3]; else tracef[9] = 0; } trace = fopen(tracef, "w"); if (trace == NULL) ex_printf("Trace create error\n"); setbuf(trace, tracbuf); break; #endif #ifdef LISP case 'l': value(LISP) = 1; value(SHOWMATCH) = 1; break; #endif case 'r': recov++; break; case 't': if (ac > 1 && av[1][0] != '-') { ac--, av++; itag = 1; /* BUG: should check for too long tag. */ CP(lasttag, av[0]); } break; case 'v': globp = ""; ivis = 1; break; default: smerror("Unknown option %s\n", av[0]); break; } ac--, av++; } if (ac && av[0][0] == '+') { firstln = getn(av[0] + 1); if (firstln == 0) firstln = 20000; ac--, av++; } /* * If we are doing a recover and no filename * was given, then execute an exrecover command with * the -r option to type out the list of saved file names. * Otherwise set the remembered file name to the first argument * file name so the "recover" initial command will find it. */ if (recov) { if (ac == 0) { die++; setrupt(); execl(EXRECOVER, "exrecover", "-r", NULL); filioerr(EXRECOVER); exit(1); } CP(savedfile, *av); av++, ac--; } /* * Initialize the argument list. */ argv0 = av; argc0 = ac; args0 = av[0]; erewind(); /* * Initialize a temporary file (buffer) and * set up terminal environment. Read user startup commands. */ init(); if (setexit() == 0) { setrupt(); intty = isatty(0); if (fast || !intty) setterm("dumb"); else { gettmode(); if ((cp = getenv("TERM")) != 0) setterm(cp); if ((cp = getenv("HOME")) != 0) source(strcat(strcpy(genbuf, cp), "/.exrc"), 1); } } /* * Initial processing. Handle tag, recover, and file argument * implied next commands. If going in as 'vi', then don't do * anything, just set initev so we will do it later (from within * visual). */ if (setexit() == 0) { if (recov) globp = "recover"; else if (itag) globp = ivis ? "tag" : "tag|p"; else if (argc) globp = "next"; if (ivis) initev = globp; else if (globp) { inglobal = 1; commands(1, 1); inglobal = 0; } } /* * Vi command... go into visual. * Strange... everything in vi usually happens * before we ever "start". */ if (ivis) { /* * Don't have to be upward compatible with stupidity * of starting editing at line $. */ if (dol > zero) dot = one; globp = "visual"; if (setexit() == 0) commands(1, 1); } /* * Clear out trash in state accumulated by startup, * and then do the main command loop for a normal edit. * If you quit out of a 'vi' command by doing Q or ^\, * you also fall through to here. */ ungetchar(0); globp = 0; initev = 0; setlastchar('\n'); setexit(); commands(0, 0); cleanup(1); return 0; }
// ------------------------------------------------------------------------------ // TOP // ------------------------------------------------------------------------------ int top (int argc, char **argv) { // -------------------------------------------------------------------------- // PARSE THE COMMANDS // -------------------------------------------------------------------------- // Default input arguments char *uart_name = (char*)"/dev/ttyUSB0"; int baudrate = 57600; // do the parse, will throw an int if it fails parse_commandline(argc, argv, uart_name, baudrate); // -------------------------------------------------------------------------- // PORT and THREAD STARTUP // -------------------------------------------------------------------------- /* * Instantiate a serial port object * * This object handles the opening and closing of the offboard computer's * serial port over which it will communicate to an autopilot. It has * methods to read and write a mavlink_message_t object. To help with read * and write in the context of pthreading, it gaurds port operations with a * pthread mutex lock. * */ Serial_Port serial_port(uart_name, baudrate); /* * Instantiate an autopilot interface object * * This starts two threads for read and write over MAVlink. The read thread * listens for any MAVlink message and pushes it to the current_messages * attribute. The write thread at the moment only streams a position target * in the local NED frame (mavlink_set_position_target_local_ned_t), which * is changed by using the method update_setpoint(). Sending these messages * are only half the requirement to get response from the autopilot, a signal * to enter "offboard_control" mode is sent by using the enable_offboard_control() * method. Signal the exit of this mode with disable_offboard_control(). It's * important that one way or another this program signals offboard mode exit, * otherwise the vehicle will go into failsafe. * */ Autopilot_Interface autopilot_interface(&serial_port); /* * Setup interrupt signal handler * * Responds to early exits signaled with Ctrl-C. The handler will command * to exit offboard mode if required, and close threads and the port. * The handler in this example needs references to the above objects. * */ serial_port_quit = &serial_port; autopilot_interface_quit = &autopilot_interface; signal(SIGINT,quit_handler); /* * Start the port and autopilot_interface * This is where the port is opened, and read and write threads are started. */ serial_port.start(); autopilot_interface.start(); // -------------------------------------------------------------------------- // RUN COMMANDS // -------------------------------------------------------------------------- /* * Now we can implement the algorithm we want on top of the autopilot interface */ commands(autopilot_interface); // -------------------------------------------------------------------------- // THREAD and PORT SHUTDOWN // -------------------------------------------------------------------------- /* * Now that we are done we can stop the threads and close the port */ autopilot_interface.stop(); serial_port.stop(); // -------------------------------------------------------------------------- // DONE // -------------------------------------------------------------------------- // woot! return 0; }
hkDemo::Result WorldRayCastMultithreadedDemo::stepDemo() { // const WorldRayCastMultithreadedDemoVariant& variant = g_WorldRayCastMultithreadedDemoVariants[m_variantId]; m_time += m_timestep; // The start point of the ray remains fixed in world space with the destination point of the // ray being varied in both the X and Y directions. This is achieved with simple // sine and cosine functions calls using the current time as the varying parameter: hkReal xDir = 12.0f * hkMath::sin(m_time * 0.3f); hkReal yDir = 12.0f * hkMath::cos(m_time * 0.3f); // For this demo an array of size 1 is sufficient. hkArray<hkpWorldRayCastOutput> resultArray(1); const int numCommands = 1; hkArray<hkpWorldRayCastCommand> commands(numCommands); { hkpWorldRayCastCommand& command = commands[0]; command.m_rayInput.m_from . set(0.0f, 0.0f, 15.0f); command.m_rayInput.m_to . set( xDir, yDir, -15.0f); command.m_rayInput.m_enableShapeCollectionFilter = false; command.m_rayInput.m_filterInfo = 0; command.m_results = resultArray.begin(); command.m_resultsCapacity = 1; command.m_numResultsOut = 0; } // // create the job header // hkpCollisionQueryJobHeader* jobHeader; { jobHeader = hkAllocateChunk<hkpCollisionQueryJobHeader>(1, HK_MEMORY_CLASS_DEMO); } // // setup hkpWorldRayCastJob // m_world->markForRead(); hkpWorldRayCastJob worldRayCastJob(m_world->getCollisionInput(), jobHeader, commands.begin(), numCommands, m_world->m_broadPhase, &m_semaphore); m_world->unmarkForRead(); // // Put the job on the queue, kick-off the PPU/SPU threads and wait for everything to finish. // { m_world->lockReadOnly(); // // Put the raycast job on the job queue. // worldRayCastJob.setRunsOnSpuOrPpu(); m_jobQueue->addJob( worldRayCastJob, hkJobQueue::JOB_LOW_PRIORITY ); m_jobThreadPool->processAllJobs( m_jobQueue ); m_jobThreadPool->waitForCompletion(); // // Wait for the one single job we started to finish. // m_semaphore.acquire(); m_world->unlockReadOnly(); } // // Display results. // if( commands[0].m_numResultsOut > 0 ) { hkVector4 intersectionPointWorld; intersectionPointWorld.setInterpolate4( commands[0].m_rayInput.m_from, commands[0].m_rayInput.m_to, commands[0].m_results->m_hitFraction ); HK_DISPLAY_LINE( commands[0].m_rayInput.m_from, intersectionPointWorld, hkColor::RED); HK_DISPLAY_ARROW( intersectionPointWorld, commands[0].m_results->m_normal, hkColor::CYAN); } else { // Otherwise draw as GREY HK_DISPLAY_LINE(commands[0].m_rayInput.m_from, commands[0].m_rayInput.m_to, hkColor::rgbFromChars(200, 200, 200)); } // // Free temporarily allocated memory. // hkDeallocateChunk(jobHeader, 1, HK_MEMORY_CLASS_DEMO); return hkDefaultPhysicsDemo::stepDemo(); }
int main(int argc, char *argv[]) { int i; signal(SIGINT, SIG_IGN); setbuf(stdin, NULL); // windows only: SYSTEM_INFO sysinfo; std::cout << KENNY_PROG_VERSION << std::endl; #ifdef KENNY_DEBUG_PERFT std::cout << "KENNY_DEBUG_PERFT defined" << std::endl; #endif #ifdef KENNY_DEBUG_MOVES std::cout << "KENNY_DEBUG_MOVES defined" << std::endl; #endif #ifdef KENNY_VERBOSE_EVAL std::cout << "KENNY_VERBOSE_EVAL defined" << std::endl; #endif #ifdef KENNY_DEBUG_EVAL std::cout << "KENNY_DEBUG_EVAL defined" << std::endl; #endif #ifdef KENNY_VERBOSE_SEE std::cout << "KENNY_VERBOSE_SEE defined" << std::endl; #endif #ifdef KENNY_DEBUG_WINBOARD std::cout << "KENNY_DEBUG_WINBOARD defined" << std::endl; #endif #ifdef KENNY_CUSTOM_VALUES std::cout << "KENNY_CUSTOM_VALUES defined" << std::endl; #endif #ifdef KENNY_CUSTOM_POSVALS std::cout << "KENNY_CUSTOM_VALUES defined" << std::endl; #endif #ifdef KENNY_CUSTOM_PSTABLES std::cout << "KENNY_CUSTOM_PSTABLES defined" << std::endl; #endif #ifdef KENNY_CUSTOM_ENDGAME std::cout << "KENNY_CUSTOM_ENDGAME defined" << std::endl; #endif dataInit(); board.init(); // windows only: GetSystemInfo(&sysinfo); if (sysinfo.wProcessorArchitecture == PROCESSOR_ARCHITECTURE_INTEL) std::cout << "Version: X86, "; else if (sysinfo.wProcessorArchitecture == PROCESSOR_ARCHITECTURE_IA64) std::cout << "Version: IA64, "; else if (sysinfo.wProcessorArchitecture == PROCESSOR_ARCHITECTURE_AMD64) std::cout << "Version: X64, "; std::cout << sysinfo.dwNumberOfProcessors << " CPU's (1 CPU used)" << std::endl; std::cout << "Search structure = " << sizeof(board)/1024 << "kB" << std::endl; // read the initialization file: strcpy(PATHNAME, argv[0]); strcpy(INIFILE, "KENNYx.ini"); // default name // check command-line to see if we need to use another ini-file: // usage: "KENNYx.exe i=somefile.ini" for (i = 1; i < argc; i++) { if (!strncmp(argv[i], "i=", 2)) sscanf_s(argv[i]+2,"%s", INIFILE); } readIniFile(); std::cout << "'help' displays a list of commands" << std::endl; commands(); return 0; }