RoboCup Real-Time Scheduling Jonas Elmqvist (jonel@ida.liu.se) Mikael Asplund (mikas@ida.liu.se) Calin Curescu Aleksandra Tesanovic Mehdi Amarijoo Real-Time Systems Laboratory Department of Computer and Information Science Linköping University October 2007 Lesson Content Goal of the lab RoboCup physical and simulated scenario Lab environment: platform and software Lab assignments Task scheduling Road-map to successful labs Requirements for passing Resources Practical issues 1 Goal of the Lab to apply scheduling theory to a pseudorealistic setting to learn how to do efficient resource allocation in realtime systems while having fun! Real-time and embedded systems: 1. read sensor values 2. compute control values 3. output result of computation image processing (1) planner (2) actuator (3) What is RoboCup? RoboCup: Robot world Cup framework to foster intelligent robotics research integrates wide range of technologies a soccer game played by robots RoboCup league consists of our lab setup! small-size soccer game played by small robots on a small field ☺ big-size soccer game played by big robots on a big field ☺ more info on RoboCup http://www.robocup.org/ 2 RoboCup Physical Scenario RoboCup Physical Scenario 3 Simulated Scenario Lab Assignments Implement three schedulers cyclic earliest deadline first (EDF) rate monotonic scheduler (RMS) Implement one performance metric deadline miss ratio Develop and test schedulers using the simulated environment 4 Lab Environment: Platform Not many device drivers for real-time Linux Windows and PC provide a nice interface to camera and radio transmitters Programming language Java constraints avoid low-level programming minimize effort to learn a new language ADA has lost popularity in the industry C is too low-level Lab Environment: Software Image Processing Low-Level Controller High-Level Controller Planner Reactor Actuator 5 High-Level Control Planner produces abstract actions based on the image processing information any-time planner executes the plan in six plan steps should restart periodically to make a new plan typically every 1 second High-Level Control Reactor produces low-level actions based on the abstract actions of the planner reevaluates actions in every cycle fairly independent of the planner sends commands to the actuator runs after image processing before actuator 6 Task Scheduling Tasks in the system... ...are image processing (1x) planner (3x) reactor (3x) actuator (1x) ...have precedence constraints (not independent!) ...have temporal attributes (estimated) worst-case execution time period relative deadline Task Temporal Attributes Task name Estimated WCET (µs) Period (µs) Relative deadline (µs) (computation time) Image processing 100000 50000 50000 Planner (all 6 steps) 12000 (2000 per step) 1000000 1000000 Reactor 1000 50000 50000 Actuator 3500 50000 50000 7 Cyclic Scheduling Schedule is a predefined sequence of calls to tasks Consists of major cycle minor cycle Major cycle a whole non-repetitive sequence consists of a number of minor cycles Minor cycle dictated by the clock interrupts major cycle minor cycle interrupts Cyclic Scheduling: your task Make cyclic scheduling for the RoboCup task set Determine the length of the major and minor cycles Determine the number of minor cycles In the minor cycle image processing, reactor, and actuator run to completion planner executes one or more plan steps Restart the planner in an appropriate place in the schedule remember: planner should be restarted every second! keep this in mind when determining the length of the major cycle! 8 Priority Driven Scheduling Scheduler dispatch Tasks in three states ready running suspended Ready Running preempted released Suspended Two type of priority lists maintained by scheduler ready lists sorted according to scheduling policy, e.g., EDF and RMS. suspended lists sorted according to their release times initially all tasks are in the suspended list Priority Driven Scheduling: Your task Write the part of the scheduler code that maintains the priority lists as follows Task is ready to be released should be moved to ready list Tasks in the ready state the task with the highest priority should be executed (by “firing” it) Make sure that the planner is appropriately restarted 9 Priority Driven Scheduling: Your task Running task(s) return on specific yield points can be preempted can miss the deadline scheduler should detect missed deadlines and invoke deadline miss handler getDeadlineMissHandler().handleAsynchEvent() once finished (isfinished=true) task should be suspended new release time and deadline should be set NOTE: you should not have busy loops in the scheduler if there are no task ready to run then scheduler should wait until there are tasks use the sleep() function of the Scheduler Road-map to Success Understand the RoboCup scheduling problem by reading the compendium before the first lab occasion you need this to be able to set-up and run your lab Download studentFiles.exe file download procedure and location of the files is in the compendium extract exe file to your home directory you get code skeletons for two first schedulers (cyclic and EDF) RMS you should implement from scratch Configure the test environment for running the schedulers instructions in the compendium Implement and test you algorithms against another student team against the reference schedulers Join a final demo of some actions taking place in the physical environment (date to be announced) and have some fun! 10 Requirements for Passing Examination consists of two parts practical part theoretical part Practical part demonstration of working solutions of schedulers to the lab assistant Theoretical part extensive discussion with the assistant on the questions from the compendium Words of Wisdom Be prepared to elaborate on all questions from the compendium during the theoretical part of the examination! Answers to preparatory questions should be prepared before the lab! All members of the lab group should be present and actively involved in every segment of the examination! Passiveness in examination could result in extra assignments for passing Do the lab assignments before the deadline: December 6th! 11 Resources TDDB47 web pages address: http://www.ida.liu.se/~TDDB47 all important information and news will be posted there check web regularly for news and important info pay special attention to the first page and the ”Labs” page Compendium contains all the details on the lab exercises contains instructions for setting up and running the lab contains most relevant RoboCup APIs Complete APIs for the RoboCup http://www.ida.liu.se/~m_reap/RoboCup/API or the TDDB47 web pages Practical Isssues Labs are done in PC rooms at IDA Java version used in RoboCup is 1.4.2_05 Available tools for programming Emacs Eclipse Netbeans Working with Emacs (recommended) Start->Programs->GNU Emacs->Emacs Compile in the command prompt with ”javac” See handouts of lesson 2 for more details Eclipse/Netbeans Configuration required 12 Java Basics - for RoboCup Lab Jonas Elmqvist (jonel@ida.liu.se) Mikael Asplund (mikas@ida.liu.se) Calin Curescu Aleksandra Tesanovic Mehdi Amarijoo Real-Time Systems Laboratory Department of Computer and Information Science Linköping University October 2007 This Lesson Gives an introduction to Java language Provides an overview over basic knowledge required by unskilled Java programmers to program the RoboCup lab assignments with success Focuses on specific issues required for programming the RoboCup lab assignments Tailored for students that have some experience with object-oriented programming (e.g., C++) 1 Motivation: RoboCup Lab Lesson Content Java overview and features Control Statements Variables Classes and inheritance Type conversion Operator summary Compiling and running programs Resources 2 Java Programming: an Overview Java Programming Java Platform myScheduler.java myScheduler.class compiler program bytecode Java Virtual Machines interpreter (JVM) interpreter myScheduler.java Java API (+RoboCup API) _______________ JVM Hardware Platform my scheduler Windows my scheduler Java (+RoboCup) Platform Solaris Java Features Object oriented language Interpreted at runtime Garbage collection Java runtime environment deletes objects that are no longer being used different than in C++! automatic deletion of objects=> no deconstructors Strong type checking Exception handling 3 Control Flow statements similar to C and C++! Loops Branching while, do…while , for if…else, switch…case Exceptions try…catch…finally, throw, throws Aborts break, continue, label:, return Scope of these is block dependent Classes public class Scheduler{ public string PolicyName; public Scheduler() {…} public void fireThread(RealtimeThread s){ s.run(); } Variable Constructor CLASS Method } constructor does not have to be specified system uses default constructor default constructor does nothing classes have modifiers public, protected, private a class is an implementation of an interface public static void main(String[] args) interface is Java’s response to multiple inheritance method used for executing a program similar to C++! 4 Variables in Java declaration: type name RLThread newThread can be declared as static class-wide, same value for all instance of the class have modifiers access modifiers: public, protected, private static, final, volatile Class member variable scope class Scheduler{ public string PolicyName; Method Parameter Scope public void fireThread (RealtimeThread s) { ... Local block variable if (..) scope { int i=7; } System.out.println("The value of i = "+i); } are valid within a scope similar to C++! } Error (”i” does not exist out of scope) Variable Types Primitive type byte, short, int, long float, double char, boolean Reference type double missedDeadlines= 0.0; manipulation of the value! similar to C++! RTLThread newThread; reference is a memory manipulation of the address! address (pointer in C++) arrays are objects and are of reference type all objects are manipulated by Java using their references! 5 Object Creation are created from a class (as you know) AbsoluteTime abs= new AbsoluteTime(); class object name allocates space for an object objectReference.variableName used as in C++ constructor manipulate or inspect its variables call its methods remember that objects are of reference type Methods represent the behavior of a class several input one output (return) class Scheduler{ public string PolicyName; public void fireThread(RealtimeThread s){ s.run(); } } modifier output input have parameters and modifiers public, protected, private static, final, synchronized, native OBS! Value of the address is passed if an input parameter is an object ! 6 Example public void tricky(Point arg1, Point arg2) { Point temp = arg1; arg1 = arg2; arg2 = temp; arg2.x = 200; } What is the value of p1.x, p2.x after the following sequence of statements? p1.x = 50; p2.x = 100; tricky(p1,p2); Inheritance public class EarliestDeadlineFirstScheduler extends Scheduler{…} Subclass (EarliestDeadlineFirstScheduler) inherits all members of superclass (Scheduler) Exceptions to inheritance are when members are not accessible (i.e., private) members are explicitly overridden (i.e., redefined) in subclass Constructors are not inherited 7 Type Conversions (Casting) Object casting! Upcast (widening conversion) from subclass to ancestor usually automatic; always safe Downcast (narrowing conversion) from ancestor to subclass checked at runtime for validity if not an instance – an Exception is thrown ”instanceof” operator can be used to check if an object belongs to a class Operators Priority Operators [ ] 1 2 3 () method call . member access ++ pre- or postfix increment -- pre- or postfix decrement + - unary plus, minus ~ bitwise NOT ! boolean (logical) NOT (type) type cast New object creation * / % multiplication, division, remainder + - 4 + 5 6 Operation Associativity Priority array index addition, substraction left signed bit shift left >> signed bit shift right >>> unsigned bit shift right < <= less than, less than or equal to > >= greater than, greater than or equal to Instanceof reference test Operation == equal to != not equal to 7 & bitwise AND & boolean (logical) AND 8 ^ bitwise XOR ^ boolean (logical) XOR 9 right Associativity left left left | bitwise OR | boolean (logical) OR 11 && boolean (logical) AND 12 || boolean (logical) OR left left 13 ? : conditional right = assignment left 14 *= /= += -= %= <<= combinated assignment 10 left left left string concatenation << Operators right >>= >>>= &= ^= |= (operation and assignment) left 8 Code Organization Each class is in its own .java file ClassName has to be the same as FileName in CyclicScheduler.java: public class CyclicScheduler extends BasicScheduler exception is that inner classes contained wihin the class do not have its own .java file Related classes are grouped in packages” in CyclicScheduler.java: similar to namespaces in C++ packages are structured hierarchically each .java file should start with the declaration of the package package rt; import soccorob.rt.*; import soccorob.ai.agent.*; public class CyclicScheduler extends BaseCyclicScheduler { Import allows you to use short names for classes Compiling (*.java Æ *.class) correct compiling depends on setting the CLASSPATH environment variable points to the directories under which the compiler can find classes on which new compiled class depends In Windows: set CLASSPATH=%CLASSPATH%;c:\ programs\Robolab;z:\robolab Class files must respect the package hierarchy class rt.CyclicScheduler should be in CLASSDIR\rt\, where CLASSDIR is contained in CLASSPATH Compiling command example javac [–classpath C:\programs\Robolab] CyclicScheduler.java ”-classpath ...” option can be used instead of the CLASSPATH variable 9 Running the program Result of the compilation is a .class file sorted in the same directory as the source file Can be changed with ”–d DestinationDirectory” command for running the program java myPackage.ClassName Example with this and super this Can be used to access methods or fields Reference to “this ” object can be in a return statement super Only for accessing the parent’s methods or fields public class HelloWorld extends Hello { String msg; public HelloWorld(String message) { super(message); msg = message; } public HelloWorld() { this("hello world"); } public void changeMsg(msg) { this.msg = msg; } public HelloWorld returnMe() { return this; } } 10 Printing Standard I/O: stdin, stdout, stderr defined in java.lang.System object as public static final InputStream in; public static final PrintStream out; Escape codes for unprintable characters: \b - Backspace \t - Tab \n - Newline \f - Form feed Example String mes1 = ”Hello World\nSecond line:”; String mes2 = ”\tValue of ion =” String mes3 = mes1 + mes2; int ion = 3; System.out.println(mes3); System.out.println(mes2 + ion); \r - Carriage return \‘ - Single quote \” - Double quote \\ - A backslash \nnn - The character with octal value nnn ('\012' == '\n') Resources On-line tutorials Help you to learning the Java language Provide explantions for essential Java classes Available at http://java.sun.com/docs/books/tutorial/ 11 THE END RoboCup Example 1 Class Relevant Members HighResolution Time setTime(HighResolutionTi AbsoluteTime me new) ReleaseParamet ..... ers Subclass Relevant members .... PeriodicParameters ... ... AbsoluteTime getStart() RealtimeThread ReleaseParameters getReleaseParameters() .... RLThread .... ThreadNode .... RMThreadNode AbsoluteTime deadline AbsoluteTime nextRelease Assume: RLThread[] threadList=(RLThread[]) getThreads(); threadNode= new RMThreadNode(threadList[i]) ; How can we set the next release time of the threadNode (using setTime). The value of the (old) release time of the thread can be obtained using getRealeseParameters. What should follow? 12 RoboCup Example 1 This statement: threadNode.nextRelease.setTime(((PeriodicParameters)thr eadList[i].getReleaseParameters()).getStart()); ...is equivalent with: AbsoluteTime nextRel = threadNode.nextRelease; RLThread thr = threadList[i]; ReleaseParameters ppo = thr.getReleaseParameters(); PeriodicParameters pp = (PeriodicParameters)ppo; AbsoluteTime sTime = pp.getStart(); nextRel.setTime(sTime); When not sure use ”()” to enforce presedence. Expression between ”()” is always evaluated first! RoboCup Example 2 Class Relevant Members RLThread ThreadNode ThreadNode next ThreadNode previous RLThread thread Subclass Additional members PlannerControl restart() RMThreadNode AbsoluteTime deadline AbsoluteTime nextRelease Assume: RLThread[] threadList=(RLThread[]) getThreads(); threadNode= new RMThreadNode(threadList[i]) ; How can we restart the planner of the threadNode in the list? What should follow? 13 Other examples What is the result of the following statements? System.out.println(”temperature is ”+3+2); System.out.println(”temperature is ”+(3+2)); (PlannerControl)threadList[1].restart(); ((PlannerControl)threadList[1]).restart(); 14