+ All Categories
Home > Documents > From Control Models to Real-time Code Using Giotto

From Control Models to Real-time Code Using Giotto

Date post: 24-May-2017
Category:
Upload: lgrome73
View: 217 times
Download: 2 times
Share this document with a friend
34
From Control Models to Real-Time Code Using Giotto Thomas A. Henzinger, Christoph M. Kirsch, Marco A.A. Sanvido, and Wolfgang Pree 1
Transcript

FromControlModelsto Real-TimeCodeUsingGiotto

ThomasA. Henzinger, ChristophM. Kirsch,MarcoA.A. Sanvido, andWolfgangPree

1

ThomasA. Henzinger ChristophM. Kirsch MarcoA.A. SanvidoDepartmentof ElectricalEngineeringandComputerSciences

Universityof California, Berkeley, USA{tah,cm,msanvido}@eecs.berkeley.edu

WolfgangPreeSoftwareResearchLaboratoryUniversityof Salzburg, [email protected]

Thisresearchwassupportedin partby theDARPA SECgrantF33615-C-98-3614,theMARCO GSRCgrant98-DT-660,andtheAFOSRMURI grantF49620-00-1-0327.

A preliminaryversionof thispaperappearedas[1].

2

Introduction

We presenta methodology for controlsoftwaredevelopmentbasedon Giotto [2],a domain-specifichigh-level programming languagefor control applications.AGiotto programexplicitly specifiesthe exact real-time interaction of softwarecomponentswith thephysicalworld. TheGiottocompilerautomaticallygeneratestiming codethatensuresthespecifiedbehavior onagivenplatform.

This article illustratesthe Giotto methodology by reimplementing the con-troller for an autonomously flying modelhelicopteroriginally developedat theSwissFederalInstitute of Technology(ETH) Zürich [3]. We demonstratethatGiotto introducesa negligible overhead,andat thesametime increasestherelia-bility andreusabilityof thecontrolsoftware.

Thearticlebeginswith aconceptualoverview of theGiotto methodology. Weexplain how Giotto helpsto automatethecontrolsoftwaredevelopmentprocess,andto improve the quality of the resultingcode. We thenreporton the Giottohelicopterproject. We usethe autopilot softwarefor the helicopterto guideaninformal presentationof the Giotto language,and of the S/G translator, whichextractsaGiottoprogramfrom aGiottocontrolmodelspecifiedin Simulink. Thisis followedby a brief discussionof thecompilation andexecutionof theGiotto-basedcontrol system.Thearticleconcludeswith a summaryof availableGiottoimplementations,andpointersto relatedwork.

More detailson Giotto, aswell asa distribution of the Giotto softwaretoolsusedin thisarticle,canbefoundathttp://www.eecs.berkeley.edu/~fresco/giotto.

The Giotto Methodology

TheGiotto methodology presentsa systematicattemptto decomposethedifficulttaskof controlsystemsdevelopment:domain-specific(control)concernsaresep-aratedfrom platform-specific(implementation)concerns,and time-relatedcon-cernsareseparatedfrom data-related(functionality) concerns.

Separating reactivity from scheduling

Traditionally, acontrolsystemis designedusingtoolsfor mathematicalmodelingandsimulation,suchasMathWorks’ Simulink. Thecontrolmodelis implementedmanuallyor automatically, andthecodeis thentestedandoptimizedfor thegivenplatform until it exhibits satisfactory timing behavior. In the process,the tight

3

correspondencebetweenmodel and codeis often lost. The resultingsoftwareis brittle, difficult to reuseon a differentplatform, anddifficult to enhancewithadditionalfunctionality.

Giotto addressesthis problemby offeringanintermediatelayerof abstractionbetweenthe mathematical modelandthe code. We call this layer an embeddedsoftware model. An embeddedsoftware model specifiesa solution to a givencontrolproblemindependentof anexecutionplatform(i.e.,operatingsystemandhardware),but it is closerto executablecodethana mathematicalmodel. Whiletheentitiesof a mathematicalmodelare,typically, matrices,equations,andper-hapsstatediagrams,theentitiesof asoftwaremodelaredatastructuresandproce-dures.For example,a softwaremodelmayspecifytherepresentationfor storingamatrix,andthealgorithmandprecisionfor evaluatinganequation.

Commonsoftwaremodelsarehigh-level programming languages,but for em-beddedsoftware, the model needsto include constructsfor expressingconcur-rency andtiming. An embeddedsoftwaremodelspecifiesthelogicalconcurrencyandinteractionof softwareprocesses,aswell asthetiming of processinteractionswith thephysicalenvironment.However, anembeddedsoftwaremodelmustnotspecifythephysicaldistributionof thesoftwareprocesses,noraschedulingmech-anism,bothof whichrequireknowledgeabouttheplatform. In Giotto,wespecifywhena sensoris read,which sensorreadingis usedfor computingan actuatorvalue,andwhentheactuatoris set,without specifyingaCPUor apriority for thecomputation.

In short, an embeddedsoftware model separatesthe platform-independentfrom theplatform-dependentissuesin embeddedsoftwaredevelopment.This fa-cilitatescodegenerationby partitioning the taskinto two steps.In thefirst step,calledprogram generation, a given mathematicalmodel is transformed into anembeddedsoftwaremodel(i.e.,ahigh-level embeddedprogram). Thisstepis en-tirely independentof any executionplatform; it specifiesonly the reactivity(i.e.,real-time response)of thesystemrelative to a physicalenvironment. In thesec-ond step,calledcompilation, the softwaremodel is transformedinto executablecodefor a targetplatform. Thisstepmustensuretheschedulability (i.e., real-timeexecution)of the systemin a specificexecutionenvironment. While programgenerationprovidesa fully specifiedalgorithmic solutionto thecontrolproblemathand,compilationis usuallyconcernedalsowith non-reactivepropertiesof thesolution,suchasresourceutilizationandfault tolerance.

Theexplicit useof a softwaremodelduringcodegenerationoffers improvedflexibility in the verification, optimization, integration, and reuseof embeddedcomponents.All of theseactivities areeasierto carry out at the level of an em-

4

beddedsoftwaremodel,ratherthanat thelevel of platform-specificcode.

Separating timing from functionality

Giotto provides an embeddedsoftware model for control applications. Conse-quently, a Giotto-basedsystemsdevelopmentmethodology can separatehigh-level controlconcerns,suchassamplingratesandcontrol laws,which dependonthegivencontrolproblem,from low-level implementation concerns,suchasout-put jitter anddevice drivers,which dependon the chosenplatform. In addition,the Giotto methodology alsoseparatestiming concerns,suchassamplingratesand output jitter, from functionality concerns,suchas control laws and devicedrivers.A Giotto programsupervisestheinteractionbetweensoftwareprocessesandthephysicalworld, but doesnot itself transformdata.All computationis en-capsulatedinsidethesupervisedsoftwareprocesses,which canbewritten in anynon-embeddedprogramming language,suchasC. We refer to a Giotto programasa timingprogram, andto thesupervisedprocessescalledby theGiottoprogramasfunctionality programs.

In this way, Giotto enforcesa programming discipline—thestrict separationof timing andfunctionality— which is often violatedin real-timeprograms, es-peciallywhentheprogramsarehand-optimizedto meettiming constraints.Thisprogrammingdisciplineoffersadditionalbenefitsin theverification,optimization,integration,andreuseof embeddedcomponents.All of theseactivities areeasierto carryout independentlyfor timing andfunctionality programs. Similarly, theseparationof timing andfunctionality further facilitatescodegeneration:thetim-ing (Giotto) programcanbe compiledinto executabletiming code,independentof the compilation of the functionality (e.g.,C) programsinto executablepiecesof functionality code. After linking, the timing codesupervisestheexecutionofthefunctionality code.

It is importantto notethatthisschemeoffersgreatflexibility for thecompiler.A Giottoprogramspecifiesonly thereactivity of thefunctionality programs—i.e.,whenthey areinvoked,andwhentheir outputsareread—but not their schedul-ing. Hence,on thelevel of theGiotto softwaremodel,all functionality programsareatomicexecutionunits, without priorities or internalsynchronizationpoints.In otherwords,the softwareprocessessupervisedby a Giotto programaresub-routines(functions) ratherthancoroutines(threads)[4]. This makesthe Giottosoftwaremodel transparent,andparticularlyattractive for verification [5]. TheGiotto compiler, on theotherhand,is free to producetiming codethatpreemptsfunctionality code,andwill generallydo sofor schedulingandoptimizationpur-

5

Embedded System

Opt

imiz

atio

n/D

ebug

ging

C CompilerCompilation/Linking

Implementation Tools

Program Generation

Real−Time Code

Combined Timing + FunctionalityProgram

(C)

(Simulink)Mathematical Model

Control Problem

RTW Embedded Coder

Modeling Tools

Sim

ulat

ion/

Val

idat

ion

Application

Figure1. The traditional control sys-temsdevelopmentprocess.

Embedded Software Model

Giotto Compiler

Program Generation

Modeling Tools

S/G Translator

Application

S/G

Sim

ulat

or

Control Problem

Mathematical Model(Simulink)

TimingProgram(Giotto)

FunctionalityProgram

(C)

Real−Time Code

Implementation Tools

RTW Embedded Coder

C Compiler

Embedded System

Compilation/Linking

Figure2. TheGiotto-basedcontrolsys-temsdevelopmentprocess.

poses.Thus,on the level of platform code,thepiecesof functionality codethataresupervisedby the timing codeare indeedcoroutines,not subroutines.Thisillustratesstrikingly the main propertyof a goodsoftwaremodel: the softwaremodelshouldemphasizetransparency (simplicity), and thus improve reliabilityandenablereuse,whereasthecompiler shouldemphasizeperformance.

The Giotto tool chain

Fig. 1 shows thecontrolsystemsdevelopmentprocesswithout anembeddedsoft-waremodelthatseparatestiming from functionality; Fig.2 showshow theprocesschangesif Giotto is used.TheGiotto methodologypartitionsthecodegenerationfrom controlmodelsinto four independentphases.Thefour phasesaresupportedby four differenttoolswith thefollowing outputs:

1. Froma givenSimulink model,theSimulinkcodegeneration facilities, e.g.,MathWorks’ Real-Time Workshop(RTW) EmbeddedCoder, generateCprogramsfor thefunctionalentitiesof thedesign,suchascontrol law com-putations.OtherC programsthatimplementfunctionalunits,suchasdevicedrivers,maybetakenfrom libraries.Theindividualfunctionality programs

6

aresequentialandindependent,andtheir executionneedsto besupervisedby a timing program.

2. From the Simulink model,the S/Gtranslatorgeneratesa Giotto program,which specifiesthetiming behavior of a controlsystemin a platform-inde-pendentway. TheGiotto programsupervisestheexecutionof thefunction-ality programsin responseto thebehavior of thephysicalenvironment.

3. Fromthefunctionalityprograms,theCcompilergeneratesexecutablepiecesof codefor achosenplatform.

4. FromtheGiottoprogram,theGiottocompilergeneratesplatform codethat,after linking, supervisesthe executionof functionality codein a way thatguaranteesthereal-timebehavior specifiedby theGiottoprogram.In orderto generatecodewith this property, theGiotto compilerneedsto performaschedulabilityanalysis,andrejectaGiottoprogramif its timing constraintscannotbemeton thetargetplatform.

In thiscode-generationtool chain,therearetwo Giotto-specifictools,namely, theS/GtranslatorandtheGiottocompiler.

In addition, Giotto offers a simulation tool, the S/Gsimulator, which allowsthesimulation of Giottomodelsthatarespecifiedin Simulink. Thebenefitsof us-ing theS/Gsimulator, ratherthanSimulink’s own simulationfacilities,is thattheGiotto tool chainguaranteesthatthereal-timeandfunctionalbehavior of thegen-eratedcodematchesexactly theresultof S/Gsimulation. TheS/Gsimulatorsup-portstherapidprototyping andvalidationof Giotto controlsystemsin Simulink,becausetheGiotto code-generationtoolsarefully compliantwith theS/Gsimu-lationsemantics.

A Giotto-based Autonomous Helicopter System

We illustratetheGiotto methodology by reengineeringanexisting complex con-trol system:the autopilotsoftwareof an autonomously flying modelhelicopter.We startedfrom a systemthatalreadymetthedesiredobjectives:a fully workingsystemwith a well-modularizedsoftwarearchitecture.This madeit easyto iso-late the functionalcomponentsfrom the existing code. A similar reengineeringapproachhasbeenusedto assessthe feasibility of othermethodologies,suchasMetaH,in thecontext of embeddedmissilecontrolsystems[6].

7

Figure3. ThemodelhelicopterandtheOLGA controlsystem(aluminumbox).

The helicopter system

The original helicoptercontrol system[3] wasdevelopedat ETH Zürich aspartof an interdisciplinary projectto build an autonomously flying modelhelicopterfor researchpurposes.Thecontrolsystemhardwareis acustom-craftedcomputerboardwith a single200MHz StrongARMprocessorandspecializedI/O devices.All functionalcomponentsareimplementedin theprogramminglanguageOberon[7], [8] on top of the custom-designedreal-timeoperatingsystemHelyOS [9].Thecontrolsystem(hardware,HelyOS,andautopilot software)is calledOLGA,which standsfor Oberon Language GoesAirborne. OLGA is now sold by we-Control, aspin-off company of ETH Zürich,underthenameof wePilot1000[10].

The completehelicoptersystemconsistsof an aircraft (i.e., the modelheli-copter),theOLGA control system,anda groundsystem.Fig. 3 shows a pictureof the helicopter;Fig. 4 shows the systemstructure. The groundsystem(bot-tom of Fig. 4) supportsmissionplanning,flight commandactivation, andflightmonitoring. Sincethe groundsystemis not relevant for the reimplementationof the OLGA autopilotsoftware,it is not discussedhere. All sensorsandcom-putationalresourcesusedfor flight controlandnavigation areairborne(with theexceptionof a secondaryGPSreceiver usedfor the differentialGPS).The sen-

8

bypass

Remote Control

Helicopter System

Ground System Human Pilot

Computer

(StrongARM)

Receiver

ServosAltimeterCompassRevolution

Acc. sensors

Gyroscopes

Temperature

GPS

GPS

Joystick (PC)Ground Computer

Datalink

Multiplexer

Datalink

Figure4. TheOLGA controlsystemhardwarestructure.

sorsusedon thehelicopterarea GPSreceiver, a compass,a revolution sensor, alaseraltimeter, threeaccelerometers,threegyroscopes,anda temperaturesensor.Theactuatorsaresix servosthatcontrol themainandtail rotor bladesaswell asthethrottle of thetwo-strokecombustionengine.TheOLGA controlsystemgen-eratespulse-width-modulated(PWM) servo commands.Take-off andlandingareunderremotecontrolof ahumanpilot. Thetransitionfrom manualto autonomousflight is donewhenthehelicopteris hovering. In orderto allow a smoothtransi-tion, OLGA tracksthecommandsfrom thehumanpilot and,upontransition,usesthemasthe initial operatingpoint of thecontroller. In caseof anemergency, thehumanpilot is ableto bypassOLGA atany time duringflight.

The complexity of helicopterflight control resultsfrom the numberof dif-ferent sensorsand actuatorsthe control systemhasto handleconcurrently, thedifficulty of flying a helicopter, andthephysical limitationsof thecontrolsystem(electricalconsumption, limitedcomputational resources,vibrations, jitter, etc.).Sincethehelicopteris a dangerousandexpensive platform, a trial-and-errorap-proachcannotbeused.Thecontrolandnavigation algorithms arebasedon hardreal-time assumptionsthathave to beguaranteedunderall circumstancesby theimplementation. In the OLGA control system,the controllerrunsat 40 Hz and

9

datafusion(sensing)at 200Hz. Theworst-caseexecutiontime of thecontrolleranddatafusion implementation is 12 mswithin a singlecontrol cycle of 25 ms,which resultsin a CPUutilization of morethen45%,leaving not muchroomforotheractivitiessuchasbookkeepingandmonitoring.

Researchefforts in unmannedaerialvehicles(UAVs), andmorespecificallyin autonomoushelicopters,have progressively shiftedfocusfrom a purecontrolproblemto an interdisciplinaryproblem,wherethe softwareperformance,relia-bility, andquality hasbecomea majorcritical factor. This is demonstratedby theacademichelicopterprojects[11]–[18]. In [19] anoverview of otherautonomousmodelhelicopterprojectsis given.

The structure of the autopilot software

Theautopilotsoftwarehassix differentmodesof operation(seeFig. 5). In eachmodedifferent tasksareactive. The modesareInit, Idle, Motor, Take-Off, ControlOff, andControlOn. In all modesexceptfor theControlOnmode,thehumanpilot controlstherotorblades,whereastherotorspeedis alwayscontrolledby OLGA. Thefirst threemodesareneededto handletheinitializationprocedurecorrectly. In particular, theMotor modehandlesthe transitionfroma 0 rpm rotor speedto a safespeedof 300 rpm. At this speed,the helicopterisguaranteednot to takeoff, andonly an active commandfrom the groundstationallows thetransition to modeTakeOff. Whenthetakeoff procedureis finished,thehelicopteris in modeControlOff. In this mode,the rotor is at a nominalspeedof 1200rpm and the pilot hasfull control over the rotor blades. At thispoint, thepilot is ableto switch,atany time,to theControlOn mode,activatingtheautopilot. For simplicity, wewill henceforthfocusonly on theControlOffandControlOn modes.

In theControlOff mode,theautopilotsoftwarereadsthecommandsfromthe humanpilot received via the wirelesslink andforwardsthemto the servos.TheControlOff modeconsistsof the200Hz taskADFilter andthe40 HztaskNavPilot. TheADFilter taskdecodesandpreprocessessensorvalues(datafusion). TheNavPilot taskkeepstrack of the positionandvelocity ofthe helicopterusing the preprocesseddatafrom the ADFilter task, and for-wardsthepilot commandsto theservos.TheControlOff modeswitchesto theControlOn modeif thepilot pushesabuttonon theremotecontrol. In additionto the200Hz taskADFilter, theControlOn modehasthe40 Hz taskNav-Control, whichreplacestheNavPilot task.Besideskeepingtrackof positionandvelocity, this taskimplements thecontroller thatstabilizesthehelicopterau-

10

ADFilter

ControlOn

NavControl

TakeOff

ADFilter

NavTakeOff

ADFilter

Mode 4:

200 Hz

40 Hz

200 Hz

40 Hz

200 Hz

40 Hz

200 Hz

40 Hz

200 Hz

40 Hz

200 Hz

40 Hz

isStartMotor

isStopMotor

isInitDone

isEndTakeOff

isControlOff

isControlOn

isStopMotorisS

topM

otor

isRotorUp&isStopMotor

Mode 1:

Mode 6:

Mode 2:

Mode 5:

Mode 3:Init

ADFilter

NavInit

Idle

ADFilter

NavPilot

ADFilter

NavRotorUp

Motor

TakeOff

ControlOff

NavPilot

Figure5. Theoperatingmodesof thehelicoptercontroller.

helicopter controllerhelicopter dynamics

In1In1 Out1 Out1

Figure6. Thehelicoptermodelin Simulink.

tonomously. TheControlOn modeswitchesbackto theControlOff modeif thepilot pushesa take-overbuttonon theremotecontrol.

The Giotto model of the autopilot software in Simulink

A Giottomodelspecifiesthereal-timeinteractionof asetof componentswith thephysicalworld, aswell asthereal-time interaction betweenthecomponents.Allcomponentsof a Giotto modelexecuteperiodically. For this purpose,a Giottomodel hasa parametercalled hyper-period, which is the leastcommonmulti-ple of all componentperiods.Fig. 6 shows theSimulink specificationof a Giottomodelcalledhelicopter controller, whichis connectedto acontinuous-time modelof thehelicopterdynamics.Thedynamicsblock containsonly stan-dardcontinuous-time Simulink blocks.Thecontroller block is a so-calledGiottomodelblock, which exhibits a specialsemanticsdescribedbelow. Thehelicoptercontrollerhasahyper-periodof 25ms.

Fig. 7 shows the contentsof thehelicopter controller block. Theblock labeledADFilter is a Giotto taskblock, which representsa singleGiottotask. A Giotto task is a periodicallyexecutedfunction. TheADFilter block

11

1

Out1

NavPilot OR NavControl

ADFilter

1

In1

In1 Out1

In1 Out1

Figure7. TheGiottohelicoptercontroller in Simulink.

containsonly standarddiscrete-timeSimulink blocksthat implementthe decod-ing andpreprocessingof sensorvalues.Thefunctionality programassociatedwithaGiotto taskblock might beobtainedin anumberof ways.In our casestudy, thefunctionality programis written in Oberonandtakenfrom thelegacy OLGA soft-ware. Alternatively, functionality programsthat implement Giotto task blocksmight behand-writtenor automatically generatedusingSimulink’s codegenera-tion facilities.

The secondblock in the Giotto model is an exampleof a Giotto caseblock,which maycontainmultiple Giotto tasks.Like a taskblock, a Giotto caseblockis invoked periodically. Upon eachinvocation,the caseblock selectsoneof itstasksfor execution.In theexample,thecaseblockcontainstheGiotto taskblocksNavPilot andNavControl. TheNavPilot taskcomputesthe helicopterpositionandvelocity, andreadspilot commandsfrom which it producesthecor-rectservo values.Thusevery time theNavPilot taskexecutes,thehumanpilothasfull control of the helicopter. The NavControl task,by contrast,imple-mentsautonomous flight; it producesthe servo valuesbasedon a control lawcomputation. EachGiottocaseblockhasa frequency, which is givenasanintegervaluerelative to thehyper-periodof theGiotto model. Thecaseblock of theex-amplehasthefrequency 1, thatis, it is invokedwith aperiodof 25ms.Both tasksin the caseblock inherit the frequency. Note that theADFilter taskblock oftheGiotto modelis actuallyanabbreviation for a caseblock containinga singletask.In fact,Giottomodelblockscontainonly caseblocks.Thevirtual caseblockaroundtheADFilter taskhasthe frequency 5, which meansthat the taskrunsfive timesper25ms(i.e.,with aperiodof 5 ms).

Fig. 8 showsthecontentsof thecaseblock. Besidesthetwo taskblocks,thereis a Giotto switch block, labeledisControlOff/On. A Giotto switch block

12

NavControl

OutputPortOut1

11

In1

NavPilot

In1

Out1In1

In1 Out1

Out1In1

In2SelSel

NavPilot

NavControl

isControlOff/On

Action

Action

Figure8. TheGiotto caseblock in Simulink.

maycontainany standarddiscrete-timeSimulink blocksin orderto select,basedon its input values,at mostoneof thetasksfor execution.If no taskis chosenforexecution,thenall previous outputvaluesareheld. TheisControlOff/Onblock readsthepilot commandto switch from manualto autonomousmodeandback,andaccordinglychoosesbetweentheNavPilot taskandtheNavCon-trol task. The switch block is evaluatedoncefor eachinvocationof the sur-rounding caseblockat thebeginningof its period.Thusit is evaluatedonceevery25 ms. The block labeledOutputPort is necessaryonly for multiplexing theoutputsof thetwo tasksinto a singleoutput. Thetasksandtheswitchblock in acaseblock mayonly readfrom theinputsof thecaseblock but not from any taskoutputswithin thatblock. To do this, it is necessaryto establisha feed-backlinkoutsideof thecaseblock from anoutputto aninput.

Generally, a Giotto model may consistof multiple caseblocks that all runconcurrently. More precisely, a setof tasks—at mostoneper caseblock— runconcurrently, andeachsuchcombination of tasksis calleda Giotto mode. Forexample, the ADFilter andNavPilot tasksimplementthe ControlOffmodeof thehelicoptersystem,whereastheADFilter andNavControl tasksimplement the ControlOn mode. Thus any caseswitching during executionimplementsaGiotto modeswitch.

Giotto semantics

Thekey property of theGiottosemanticsis thefixedlogicalexecutiontime(FLET)assumption,which assumesthat the executiontimesassociatedwith all compu-tation andcommunication activities arefixed anddeterminedby the model,not

13

theplatform. In Giotto, thelogical executiontime of a taskis alwaysexactly theperiodof thetask(i.e., theperiodof thesurrounding caseblock), andthelogicalexecutiontimesof all otheractivities (switch blocks,datatransferacrosslinks,etc.) arealwayszero[2]. Notethat theFLET assumptionhasall concurrenttaskexecutionswithin aGiottomoderun logically in parallel.

The logical executiontime of a task is an abstractnotion which is possiblyvery differentfrom theactual,physicalexecutiontime of thetaskon a particularCPU,which mayvary from taskinvocation to taskinvocation.Thepower of theFLET assumptionstemsfrom the fact that logical, not physical executiontimesdeterminewhensensorsareread,whenactuatorsarewritten,andwhendatatrav-els acrosslinks. For example,theADFilter tasklogically executesfor 5 ms,which implies that (1) it readsits input at thebeginningof its period,and(2) itsoutputis not availableto othertasksbefore5 ms,even if theactualexecutionofthe taskon theCPUfinishesearlier. Similarly, thecaseblock with thetwo tasksNavPilot andNavControl logically executesfor exactly25ms.

TheFLET hastwo importantconsequences.First,sensorsarereadonly at thebeginningof a task’s period,andactuatorsareupdatedonly at theendof a task’speriod.Thisminimizesjitter. In theexample,thesensorsaresampledby theAD-Filter taskat a frequency of 200 Hz, andthe servos areupdatedby the caseblock at a frequency of 40 Hz, preciselyat theendof eachhyper-period.Second,all inter-taskcommunicationhappensat periodboundaries.This eliminatesraceconditions betweentasks. In the example,the caseblock canonly readthe out-put from theADFilter taskinvocationat theendof theprevioushyper-period,but not from any ADFilter invocation during the currenthyper-period. Con-sequently, while theNavControl taskdoesnot alwaysusethe latestavailabledatafrom ADFilter, theuseddatais independentof varyingexecutiontimesofADFilter invocations,andindependentof theschedulingschemethatchoosesbetweentheNavControl andADFilter taskswhenbotharereadyto beex-ecutedon thesameCPU.We have not encountereda “staledata”problemin thehelicoptercontrolsystem;on thecontrary, this smallpenaltyincurredby theuseof Giotto is morethancompensatedby theimprovedpredictabilityof theoverallsystem.In particular, asa consequenceof theFLET assumption,a Giotto modelis environmentdetermined[20]: for any given behavior of the physical worldseenthroughthesensors,themodelcomputesa uniquetrace,that is, predictableactuatorvaluesat predictabletime instants. In otherwords, the only sourceofnondeterminism in a Giotto systemis thephysicalenvironment. This makesthevalidationof thesystemconsiderablyeasier.

14

Simulating Giotto models in Simulink

To simulateGiotto modelsin Simulink, we have developedthe S/G simulator,which implements the Giotto semantics.In practice,the S/G simulatorreadsaSimulinkspecificationof aGiottomodelandtransformsit into astandarddiscrete-time multi-rateSimulink modelthat makesthe Giotto semantics(i.e., the FLETassumption)explicit in Simulink. ThentheS/GsimulatorusesSimulink’s simu-lation facilities to simulatethe transformedmodel. We refer to simulationof thetransformedmodelasS/Gsimulationof theoriginalGiottomodel.

Fig. 9 shows the resultof S/Gsimulating a stripped-down versionof thehe-licoptercontrollerfor a durationof 140mswith modeswitchesat the50 msand100mstime instants.Thesimulation illustratesonly the timing of the inter-taskcommunicationof the original Giotto modelon trivial data. For simplicity, wehave replacedthe implementation of theADFilter taskwith a pulsegeneratorthattogglestheoutputof thetaskbetween0 and1. Thesimplifiedimplementationof theNavPilot taskreadsthatoutputandadds1; thesimplifiedNavControltaskinsteadadds3. All taskoutputsareinitially 0. In this simplified example,whereno sensorvaluesareread,environmentdeterminednessensuresthat thereis a unique(infinite) traceof the program, i.e., thereareno raceconditions be-tweenthetwo tasks.

Fig. 9 shows theprefixof thetraceup to 140ms.At the5 mstime instant,thefirst invocationof theADFilter taskis finished,andthustheoutputof thetaskchangesfrom 0 to 1. At the10 ms instant,thesecondinvocationis finishedandtheoutputchangesbackto 0, andsoon. Notethat thepulsegeneratorinsidetheADFilter taskimplements a 0/1 toggleindependentof any physicalexecutiontimes: it is the taskblock frequency thatmakesit a 5 mspulsegenerator. At the25msinstant,thefirst invocationof theNavPilot taskis finished.Thistaskwaschosenby the surrounding caseblock to executeat the 0 ms instant. As it readits input alsoat the0 msinstant,its input wasthe initial outputvalue0 from theADFilter task. Thustheoutputof theNavPilot taskat the25 msinstantis0+1,thatis, 1. Thesecondinvocationreads1 from theADFilter task,andthusoutputs2 at the 50 ms instant. Now the caseblock choosestheNavControltask to execute,which reads0 from the ADFilter task. The NavControltaskoutputs0+3, that is, 3, at the 75 ms instant. For its secondinvocation,thetaskreads1 from theADFilter taskandthusoutputs4 at the 100 ms instant.Now thecaseblock again choosestheNavPilot taskto execute,which reads0from theADFilter task.Henceits outputis 1, which is availableat the125msinstant.

15

Figure9. A traceof thesimplifiedGiottohelicoptercontrollerwith modeswitch-ing at50msand100ms.

The time-triggeredsemanticsof Giotto enablesefficient reasoningaboutthetiming behavior of aGiottomodel,in particular, whetherit conformsto thetimingrequirements of the control design. Moreover, Giotto modelsarecompositionalin thesensethatany numberof Giottomodelsmaybeaddedsideby sidewithoutchangingtheir individual semantics.For example,additionalfunctionality canbeaddedto thehelicoptercontroller without changingthereal-timebehavior of thetasksthatpresentlymakeupthecontroller. This,of course,assumestheprovisionof sufficientcomputationalresources,whichis checkedby theGiottocompilerforaspecifiedplatform (seebelow).

From Giotto models to Giotto programs

Thecodegenerationfrom Giotto modelsproceedsin severalsteps(recallFig. 2).First the S/G translator takes a Giotto model block specifiedin Simulink and

16

generatesthe correspondingGiotto programin textual form, which is thenpro-cessedby theGiotto compilerfor schedulabilityanalysisandto generatetimingcode. Here we discussthe Giotto programthat resultsfrom S/G translatingagivenGiottomodelin Simulink; theGiottocompilerwill bediscussedin thenextsection.

A Giottoprogramdefinestheexacttiming andcommunication betweenGiottotasks,andbetweentheprogramandthephysicalenvironment.All communicationhappensexplicitly acrosslinks that connectthe blocks in a Giotto model. Thesourcesanddestinationsof theselinks areimplementedasGiottoports, whicharelocationsin aglobalnamespacethatcarryvalues.TheGiottoportsarepartitionedinto taskinput andtaskoutputports, sensorports, andactuatorports. In Fig. 7,the ADFilter task block hasan incoming link from sensorports to the taskinput ports,andan outgoinglink from the taskoutputports to task input portswithin thecaseblock; thecaseblock hasanoutgoing link from taskoutputportsto actuatorports. Sensorportsarewrittenoutsideof theGiotto model,andreadinside; actuatorports are written inside of the Giotto model, and readoutside.In particular, from theperspective of theGiotto model,it makesno differenceifa sensorport obtainsits valuefrom the physical environment, or from softwareoutsideof theGiottomodel.

A Giotto programneedsto make explicit detailsthat areleft implicit or un-specifiedin theSimulinkspecificationof aGiottomodel,suchasportdeclarationsaswell asdeclarationsof functionality programs for readingandwriting port val-ues.To transportvaluesbetweenportsandto interfacewith thehardware,Giottousestheconceptof drivers.WedistinguishbetweenGiotto link driversandGiottodevicedrivers. (Therearealso initial izationandport drivers, which will bedis-cussedlater.) TheGiotto link driversimplementtheswitchblocksanddatalinksin the Simulink specification of a Giotto model; they canbe further partitionedinto task, actuator, andmodedrivers. The purposeof taskandactuatordriversis to transportvaluesfrom sensorportsandtaskoutputportsto taskinput portsandactuatorports,respectively; amodedriverevaluatesamode-switchconditionand,if it evaluatesto true,transports initial valuesto taskoutputportsof thetar-get mode. A Giotto device driver transports valuesfrom a hardwaredevice or anon-Giotto taskto a Giotto port, or vice versa.For example,a device driver mayreadsensorvaluesandwrite the resultsto a sensorport of the Giotto model; itmaywrite valuesproducedby anasynchronous(event-triggered)taskto a sensorport of theGiotto model;or it mayupdateanactuatorsettingusingthevalueofanactuatorportof theGiottomodel.In additionto transportingdata,driversmayperformsomepreprocessingof thedatasuchastypeconversion.In theSimulink

17

specificationof a Giotto model,taskandactuatordriversexist only implicitly aslinks, modedrivers correspondto switch blocks, and device drivers are absententirely.

The Giotto program for the autopilot software

From a Giotto model block in Simulink, the S/G translatorgeneratesa Giottoprogram, which is a collectionof Giotto modes.EachGiotto modehasa hyper-period,a setof taskinvocationswith specifiedfrequencies,a setof actuatorup-dateswith specifiedfrequencies,anda setof modeswitcheswith specifiedfre-quencies. A task invocation executesthe task driver followed by the task, anactuatorupdateexecutestheactuatordriver, anda modeswitchevaluatesa modedriver, possiblyfollowed by a switch to the target mode. The following exam-pleshowstheGiottoprogramhelicopter controller, whichspecifiestheControlOff andControlOn modesof thecontrolsystem:

mode ControlOff() period 25 {actfreq 1 do ServoUpdate;actfreq 1 do DataPoolUpdate;exitfreq 1 when SwitchOn do ControlOn;taskfreq 5 do ADFilter;taskfreq 1 do NavPilot;}

mode ControlOn() period 25 {actfreq 1 do ServoUpdate;actfreq 1 do DataPoolUpdate;exitfreq 1 when SwitchOff do ControlOff;taskfreq 5 do ADFilter;taskfreq 1 do NavControl;}

The hyper-periodof both modesis 25 ms. The frequenciesof the tasksinvoca-tions, actuatorupdates,and modeswitchesare specifiedrelative to this periodusingthe keywordstaskfreq, actfreq, andexitfreq, respectively. Forexample,theADFilter taskruns in both modesfive timesper 25 ms (i.e., at200 Hz). The helicopterservos andthe datapool,which containsmessagesthataresentto thegroundstation,areupdatedonceevery 25 msby invoking theac-tuatordriversServoUpdate andDataPoolUpdate, respectively. In modeControlOff, a switch to modeControlOn is contemplatedevery 25 ms byexecutingthemodedriverSwitchOn, whichevaluatesamode-switchcondition.

Fig. 10 shows the logical executionof a single hyper-period of the Con-trolOn mode(a possiblephysical executionis shown in Fig. 13 and will be

18

temperature

filter

Giotto tasks Giotto drivers

ADFilter

NavControl Mode switch

Task input

data data

filter

control

Sensor reading

Actuator update

0 5 10 15 20 25 Time(ms)rpm

pilotcompass

lasergps

Tasks/Drivers

�����������������

�����������������

accelerometersgyroscopes

Figure10. The logical executionof the Giotto autopilot programin the Con-trolOn mode.

discussedlater). The logical executionsatisfiesthe FLET assumption:theAD-Filter taskrunsfive timesexactly for 5 ms, whereastheNavControl taskrunsonceexactly for 25 ms. Both tasksrun logically in parallel. All Giotto linkanddevice driversareexecutedin logical zerotime. In practice,link anddevicedriversareboundedcodethatsatisfiesthesynchronyassumption[21] (asdriverscannotdependoneachother, no issuesof fixed-pointsemanticsarisein Giotto).

Inter-taskcommunication,aswell ascommunicationwith theenvironmentoftheGiottoprogram,worksthroughGiottoports.In theGiotto programwedeclareall sensorportsgloballyasfollows:

sensorGPSPort gps uses GPSGet;LaserPort laser uses LaserGet;CompassPort compass uses CompassGet;RPMPort rpm uses RotorGet;ServoPort pilot uses ServoGet;AnalogPort accelerometers uses AccGet;AnalogPort gyroscopes uses GyrosGet;AnalogPort temperature uses TempGet;BoolPort startswitch uses StartSwitchGet;BoolPort stopswitch uses StopSwitchGet;

Besidesa typename,we declarea Giotto device driver for eachsensorport. Forexample,thesensorport gps hasthe typeGPSPort andusesthedevice driver

19

GPSGet to getnew sensorvaluesfrom theGPSdevice. Typesanddevicedriversareimplementedexternallyto Giotto. Herethey areOberontypesandprocedures.In Fig. 10, at the 0 ms instant,the first actionis to readthe latestsensorvaluesby calling the Giotto device drivers for all Giotto sensorports. Subsequently,every 5 ms until the endof the hyper-period, the device driversarecalledonlyfor the sensorportsthat arereadby theADFilter task. Giotto device driversare always called in a time-triggeredfashion. However, somedevices requireimmediateattentionusinganasynchronous(interrupt-driven) task. For example,theGPSGet device driver doesnot accessthe GPSdevice directly, but readsabuffer into which the asynchronoustask(interrupthandler)that is boundto theGPSdevice placesthelatestGPSreadings.Theasynchronoustaskis externaltothe Giotto program. The oppositedirectionfor communicationfrom a port to adevice is donein asimilar way, andwill bediscussedbelow.

At the 0 ms instant, right after executingthe Giotto device drivers for thesensorports,themodedriverSwitchOff is calledto determinewhetheror notto switchinto theControlOff mode.Themodedriver is declaredasfollows:

driver SwitchOff(stopswitch) output () {switch isControlOff(stopswitch)}

Thedriverhasasingleinput,stopswitch, which is asensorportwhoseGiottodevicedriverStopSwitchGet hasjustbeencalled.Thedevicedriver readsthevalueof avariablethatrepresentsthetake-overbutton,whosevalueis transmittedasynchronously(i.e., externally to Giotto) via the wirelesslink from the remotecontrol to theairbornecontrolsystem.Basedon thevalueof thestopswitchport, the Oberonimplementationof theisControlOff predicatereturns trueor false,determiningwhetheror not to switchto theControlOff mode.

Supposethatwe stayin theControlOn mode.Thenext stepis to load thetaskinputportsof theADFilter andNavControl taskswith thelatestvaluesof thesensorandtaskoutputportsto which thetasksareconnected,asspecifiedin thetaskdeclarationsbelow. Beforedeclaringthetasks,all taskoutputportsaredeclaredgloballyasfollows:

outputAnalogPort filter := FilterInit;ServoPort control := ServoInit;DataPoolPort data := DataPoolInit;

Thefilter port will be the only taskoutputport of theADFilter task; thecontrol anddata portswill beusedastaskoutputportsby theNavControl

20

task.Foreachtaskoutputport,in additiontoatypename,aninitializationdriverisspecified,whichis invokedonceatstart-uptimeto initializetheport. Forexample,the task output port filter hasthe type AnalogPort and is initialized bythe driver FilterInit. As usual, the initialization drivers are implementedexternally to Giotto, hereasOberonprocedures.Initial valuesfor all taskoutputportssufficiently describea uniquestartconfigurationof a Giotto program.TheADFilter andNavControl tasksaredeclaredasfollows:

task ADFilter(accelerometers, gyroscopes, tempera-ture, filter)output (filter) {schedule ADFilterImplementation(accelerometers, gyro-

scopes,temperature, fil-

ter, filter)}task NavControl(gps, laser, compass, filter, rpm, pi-lot, data)output (control, data) {schedule NavControlImplementation(gps, laser, compass,

filter, rpm, pilot,control, data)}

The ADFilter task reads from the accelerometers, gyroscopes,temperature, andfilter ports.Thefilter port is alsoataskoutputport,whichmakestheportastatevariableof thetask.Priorto theinvocationof thetask,thevaluesof all four portsarecopiedby the taskdriver for ADFilter to somelocal memory, which is only accessibleto thetaskitself. Thetaskdriver doesnothaveto bedeclaredexplicitly in theGiottoprogram. TheprocedureADFilter-Implementation, whichimplementsthefunctionality of theADFilter task,is externalto Giotto. In our case,it is anOberonprocedurethat is takendirectlyfrom theoriginalOLGA controlsoftware.TheNavControl taskis declaredin asimilarway. Now theGiottoprogramis readyto invoketheADFilter andNav-Control tasks.TheNavControl taskrunslogically for 25 ms; theADFil-ter taskrunslogically concurrently andfinishesafter5 ms. In practice,theout-put ofADFilterImplementation is kept in local memorywhenit becomesavail-able,and loadedinto the taskoutputport filter at the 5 ms instant. This isaccomplishedby an (undeclared)port driver for filter. Port driversareusedto maintainthe FLET assumptionby makingtaskoutputsvisible in taskoutputportsonly at theendof logical taskexecution,whichmaybelaterthantheendof

21

physical taskexecution. Then,still at 5 ms, new sensorvaluesarereadandthetaskinputportsof theADFilter taskareloaded,beforeinvoking thetaskagain.

Thisprocessrepeatsuntil the25mstime instantis reached.At thattime,newvaluesin the control anddata output ports of the NavControl task areavailable. The new values are now transferred by the actuator driversServoUpdate andDataPoolUpdate to the servos anddatapool ac-tuatorports,respectively. Beforedeclaringthe actuatordrivers,we first needtodeclaretheactuatorportsgloballyasfollows:

actuatorServoPort servos uses ServoPut;DataPoolPort datapool uses DataPoolPut;

Besidesa type name,we declarea Giotto device driver for eachactuatorport.For example,the actuatorport servos hasthe typeServoPort andusestheGiotto device driverServoPut to transfernew actuatorvaluesto thehelicopterservos.Again,typesanddevicedriversareimplementedexternallyto Giotto. Be-fore thedevice driversarecalled,theactuatordriversServoUpdate andDat-aPoolUpdate areexecuted.Theactuatordriversaredeclaredasfollows:

driver ServoUpdate(control) output (servos) {call ServoUpdateImplementation(control, servos)}

driver DataPoolUpdate(data) output (datapool) {call DataPoolUpdateImplementation(data, datapool)}

In Fig. 10, at the 25 ms instant after the NavControl taskfinishes, the helicopter servos and datapool are updated byfirst executing the Oberon ServoUpdateImplementation andDataPoolUpdateImplementation, which transportthe valuesfrom thecontrol anddata ports to the servos anddatapool actuatorports, re-spectively. Then, the ServoPut device driver is called, which takes the newvaluefrom theservos portandupdatestheservo devices.TheDataPoolPutdevice driver is alsocalled,but insteadof accessinga device, it puts the valuefrom thedatapool port into a buffer, which getstransmittedover thewirelesslink assoonastheGiotto systembecomesidle. Theactualtransmissionis doneby a background(non-time-critical) taskof theoriginal OLGA controlsoftware.Thebackgroundtaskis externalto theGiotto program.The25 mshyper-periodis now finished.

22

Model

S/GTranslator Coder

Embedded

GiottoProgram

FunctionalityPrograms

CompilerCGiotto

Compiler

SymbolTable Code

FunctionalityE Code

Linker

Embedded Machine + Platform

Legend: Tool Model Software Execution environment

Giotto Simulink

Figure11. TheGiotto tool chainfor codegeneration.

Giotto Compilation and Execution

Beforewe discussthecompilation andexecutionof theGiotto autopilot programon theOLGA hardware,we considertheGiotto tool chainin slightly greaterde-tail, asshown in Fig.11. FromagivenSimulinkmodelthatcontainsGiottomodelblocks, the S/G translatorgeneratesa timing (Giotto) program for the Giottomodelblocks,while we may useMathWorks’ Real-Time WorkshopEmbeddedCoderto generatethe functionality (C) programsthat implementtheGiotto taskandswitch blocks inside the Giotto modelblocks. Functionality(C) programsthat implementthe Giotto drivers needto be provided as well, typically fromdriver libraries.In thenext step,theGiotto compilergeneratestiming codefromthe Giotto program, anda C compiler generatesfunctionality codefrom the Cprograms. The Giotto compiler targetsa virtual machinecalled the EmbeddedMachine [20]. Thecompilergeneratesso-calledE code, which is interpretedbythe EmbeddedMachinein real time. Thereare E codeinstructions to call orschedulethefunctionality code,andto invoke theEmbeddedMachineat specific

23

time instantsor occurrencesof events. In the laststep,beforeE codecanbeex-ecuted,it is linked through a commonsymbol tablewith the functionality codegeneratedby theC compilerfrom thefunctionality programs. Theexecutionenvi-ronmentfor Giotto consistsof animplementation of theEmbeddedMachineanda platform(i.e., operatingsystemandhardware),which includesa schedulerforfunctionality code.

The Giotto compiler

Themaintaskof theGiottocompileris to producetiming (E) codethatis consis-tentwith theFLET assumptionof theGiotto program.To this end,thegeneratedE codemust be shown to be time safe [20] on the chosenplatform, which in-tuitively meansthat all tasksmeetthe logical deadlinesprovided by the Giottosemantics.If the E codeis time safe,thenthe executionbehavior of the Giottocontrolsystem(i.e., timing andfunctionality code)is guaranteedto conformwiththeS/Gsimulation behavior of theoriginalGiottomodel.BecauseGiotto is envi-ronmentdetermined,thisconformanceis precisein bothtiming andfunctionality:for any given sequenceof sensorreadings,the S/G simulationandthe behaviorof the generatedcodeoutputthe samesequenceof actuatorsettings,andupdatetheactuatorsettingsat thesamepointsin time. In otherwords,a Giotto controlsystemexhibits no internalraceconditions,which makesits behavior predictableandverifiable.

TheGiottocompilercheckstimesafetyof theE codeby performing aschedu-lability analysison the Giotto programfor given worst-caseexecutiontimesofthefunctionality code.For single-CPUplatforms, theschedulabilityanalysiscanbe donein polynomial time by checkinga utilization equationfor eachGiottomode[22] (theanalysisis exactunderthe reasonableassumptionthatall modesof the Giotto programcanbe reachedduring program execution;otherwisetheanalysisis conservative). Theschedulabilityanalysisrequiresworst-caseexecu-tion time assumptionsfor C code,which maybeprovidedby non-Giotto-specifictools[23].

Thecode-generationprocessis perhapsbestunderstoodif we considerwhichpartsneedto beredoneif theplatform changes.In orderto run a Giotto controlsystemonanew platform, wemust(1) provideC programsthatimplementGiottodevice driversto interfacethenew hardware;(2) recompilethe functionality (C)programs for thenew platform;(3) have theGiotto compilerredothetime-safetycheckfor thenew worst-caseexecutiontimes;and(4) implement theEmbeddedMachineon thenew platform. In particular, if thenew platformofferssufficient

24

performance,thenthegeneratedtiming (E) codecanberun alsoon thenew plat-form. Indeed,oncethe EmbeddedMachinehasbeenported,the new executionenvironmentcanrunany Giottocontrolsystemthatpassesa time-safetycheck.

The Giotto compiler hasa greatdeal of freedomwhen generatingE code.This is becausea Giotto programdoesnot specifywhere,how, andwhentasksarescheduled.For example,thehelicopter-control programcanbecompiledonplatformswith asingleCPU(by timesharingbetweenthedatafusionandcontroltasks),or on platforms with two CPUs(by parallelism); it canbe compiledonplatforms with preemptive priority scheduling(suchasmostreal-timeoperatingsystems),or onplatformswith time-slicescheduling.Roughly, all theGiottocom-piler needsto ensureis that (1) thesensorsandactuatorsarereadandwritten ascloseaspossibleto thetimesspecifiedby theGiottosemantics,and(2) wheneverin theGiottosemanticsthelogicalcompletionof onetaskprecedestheinvocationof anothertask,thenthe sameprecedenceis preserved during the actualexecu-tion [2]. Thefirst requirementreducesI/O jitter; thefreedomgivenby thesecondrequirementcanbeusedby thecompilerto optimize performance.In particular,aswe will seenext, thehelicoptersystemexecutestwo logically concurrent,log-ically atomic(i.e.,non-preempted)tasksthrough time sharingandpreemption onasingleCPU.

As theGiotto compilermaintainscomplianceof thecodewith thelogical se-mantics,Giotto systemscanbecomposed.Theexisting I/O behavior of a Giottocontrol systemdoesnot changewhennew Giotto tasksareadded,provided thecompilersucceedsin showing thattheresultingE coderemainstime safedespitetheadditional load.

The Giotto-based autopilot control system

The systemarchitectureof the Giotto-basedhelicoptercontrol systemis shownin Fig. 12. Theupperleft portionshows theGiotto programandthecorrespond-ing functionality programs,namely, Oberonimplementationsof theGiottodeviceandlink driversandGiotto tasks.Thenon-Giotto tasksshown in theupperrightportion of Fig. 12 implementasynchronous(event-triggered)tasksor background(non-time-critical) tasks,which areinterfacedto the Giotto systemthrough sen-sor and actuatorports via Giotto device drivers. Asynchronous tasksmust betaken into accountby the schedulabilityanalysisperformed by the Giotto com-piler; backgroundtasksareexecutedonly whentheGiotto systemis idle. In themiddle of Fig. 12, the original OLGA systemsoftware is extendedby an im-plementation of the EmbeddedMachinein the kernel of the HelyOS real-time

25

DeviceGiotto

DriversE Code

GiottoLink Driversand Tasks

AsynchronousTasks Tasks

Background

Giotto Autopilot Program

Actuators SensorsOLGA System

HelyOS Real−Time SystemDrivers

Computer System

Event−Triggered/

EmbeddedMachine

Device

Giotto Control SoftwareNon−Time−Critical Software

Figure12. TheGiotto-basedhelicoptercontrolsystem.

operatingsystem.Theunderlying hardwareis unchanged.Fig. 13 shows theactual,physical executionof theGiotto autopilotprogram

in theControlOn mode,which correspondsto the logical executionshown inFig. 10. Sincethe OLGA hardwarehasa singleCPU to run the Giotto systemaswell asnon-Giotto tasks,at any point in time during the actualexecution,atmostoneof theGiotto or non-Giotto taskscanberunning. This is in contrasttothelogicalexecution,wherethetwo Giotto tasksADFilter andNavControlrun logically in parallel. In orderto checktheschedulabilityof theControlOnmode,the Giotto compiler must verify that on the OLGA CPU, five times theworst-caseexecutiontime of ADFilter, plus the executiontime of NavCon-trol, plus worst-caseassumptionsfor Giotto overhead(i.e., driver execution)and asynchronousnon-Giotto tasksare lessthan the hyper-period of the mode(25ms).

Thescheduleof tasksduringtheactualexecutionis determinedby thegener-atedE codeaswell astheschedulerof theoperatingsystem(OS),which is part

26

of the platform. The E codegovernsthe timing behavior of the Giotto system:it triggerstheimmediate(synchronous)executionof thedrivers,andhandstasksthatarereadyto bescheduledto theOS.TheHelyOSschedulesGiotto tasksus-ing a rate-monotonic scheduler, andrunsbackgroundtaskswhenever the Giottosystemis idle. Thereis a trade-off betweenE codeschedulingandschedulingbytheOS.In thetwo extremecases,theE codemaygive theOSmaximalfreedomby handingover tasksassoonasthey arereadyto bescheduledin conformancewith theGiottosemantics,or it maymake its own schedulingdecisionsandhand,atall times,only oneof thereadytasksto theOS.Many intermediatesolutionsarealsopossible.E codeschedulingis explicit, determinedby theGiotto compiler;schedulingby the OS is implicit, dependingon the schedulingstrategy usedbythe OS.Note,however, thatE codeschedulingis not necessarilystatic,becauseschedulingdecisionsmaydependon thestateof theprogram.E codeis compat-ible with any schedulingstrategy of theOS,but theschedulingstrategy mustbeknown whentheGiotto compilerchecksthegeneratedE codefor time safety.

The top row of Fig. 13 shows the executionof theADFilter taskandthedriversfrom the top row of Fig. 10. Themiddle row shows theexecutionof theNavControl taskandthedriversfrom thebottomrow of Fig. 10. Thebottomrow shows the executionof background(non-time-critical) tasks. At 0 ms, theADFilter taskstartsbeforetheNavControl task,eventhoughbotharereadyaccordingto theGiotto semantics,becauseADFilter runsat a higherrateandthushasa higherpriority. For the samereason,NavControl is preemptedat5 msby thesecondinvocationof ADFilter. Notethatin orderto conformwiththedataflow specifiedby theGiottosemantics,theNavControl taskmustreadthe outputof the last invocation of theADFilter taskfrom the previous con-trol cycle even thoughthe first invocation of ADFilter in the currentcycle isalreadycompletedwhenNavControl starts,andthusa fresheroutputof AD-Filter would be available. The benefitof this strict adherenceto the Giottosemanticsis thatthesameoutputvalue—namelytheoneof definedby theFLETassumption—is usedin all implementations,independentof theschedulingstrat-egy andperformanceof theplatform.

In thehelicoptersystem,in orderto implementtheGiottosemantics,theinputfor theNavControl taskis loadedat0 msandthenbufferedfor 25msuntil theendof the task’s period. Similarly, taskoutputsarebufferedandmadeavailableonly at theendof a taskperiod. Buffering taskinputsandoutputsis a sufficientbut conservative techniqueto implementtheFLET assumptionof theGiotto se-mantics. Other techniquessuchas schedulingwith precedenceconstraintsarepossible[2].

27

Time(ms)

background tasksGiotto drivers Giotto tasks

rpmpilot

compasslaser

gps

Tasks/Drivers

CPU Executing:

������������������������

������������������������

accelerometersgyroscopestemperature

filter

data data

filter

control

0 5 10 15 20 25

Figure13. The actual execution of the Giotto autopilot programin the Con-trolOn modebasedon rate-monotonicscheduling.

Conclusions

Giotto is a domain-specifichigh-level programming language:domain-specific,asit addressesembeddedcontrolapplications;high-level, asit abstractsplatform-dependentimplementation details. Giotto increasesthe transparency of controlsoftware,andautomatesschedulingandoptimizationthrough compilation.

The successfulreengineeringof the OLGA autopilot software using Giottodemonstratesthefeasibility of theGiotto approachfor high-performancecontrolsystems.The Giotto compilerautomatically generatestiming codefor a controlsystemwith multiple modesof operation,multiple levels of taskpriorities, andtime-triggeredaswell asevent-triggeredtaskactivation. Giotto incursan over-headthrough E codeinterpretation, predicatechecksfor modeswitching,andthecopying of ports. Measurementson the helicopterimplementation have shownthatthisoverheadamountsto lessthan2%of a25msperiod.

Giotto-basedcontrolsystemsbenefitfrom thedualseparationof concerns(re-activity vs. scheduling;timing vs. functionality) in many ways. First, andfore-most, the timing behavior of the control systemis guaranteedto conformwiththe simulationbehavior of the correspondingSimulink model. Indeed,for anygivenbehavior of thephysicalenvironment, theresponseof theGiotto systemis

28

unique,andthereforepredictable.Second,thedevelopmenteffort is significantlyreduced,as the tediousprogramming of the timing codeis handedover to theGiotto compiler. Also, theautomationof thetiming codegenerationeliminatesacommonsourceof errors.Third, thehigh degreeof modularizationandsoftwaretransparency facilitatesthe easyexchangeandadditionof functionality, aswellasthe easymodificationof timing requirements.Functionalityprograms canbepackagedassoftwarecomponentsandreused;timing (Giotto) programscanbecomposedwithoutchangingtheir individual behaviors. Fourth,thesystemcanbeportedto all platformsfor whichanimplementation of theEmbeddedMachineisavailable. An implementationof theEmbeddedMachineon top of HelyOSwasaccomplishedin oneweek,andits sourcecodeis only 6 KByte.

Current Giotto implementations

Thereareseveral implementationsof executionenvironments for Giotto besidestheoneusedfor thehelicoptercontrol systemdescribedin this article. Thefirstimplementationof Giotto was a simplified Giotto executionenvironmenton adistributed platform of Lego Mindstorms [24] robots. The robotsuseinfraredtransceivers for communication. Thenwe implementeda full Giotto executionenvironment on a distributedplatform of Intel x86 robotsrunningthe real-timeoperatingsystemVxWorks [25]. The robotsusewirelessEthernetfor commu-nication. We alsowrote a Giotto program that runson five robots,threeLegoMindstorms andtwo x86-basedrobots,to demonstratetheapplicability of Giottofor heterogeneousplatforms.For adiscussionof thiswork, andembeddedcontrolsystemsdevelopmentwith Giotto in general,we referto theearlierreport[26].

Wehave implementedaGiotto-basedautomotiveelectronicthrottlecontrolleron a singleMotorolaMPC 555processorrunningthereal-timeoperatingsystemOSEKWorks [27]. TheGiotto programspecifiesthreetasks:a 1 KHz controllertaskthat implements variousthrottle controllers,a 33 Hz monitor taskthatmon-itors the systemstatus,anda 66 Hz manager taskthat determines,basedon thesystemstatus,which throttle controlleris executedby thecontroller task.

TheBerkeley Aerial Robot(BEAR) helicoptercontrolsystem[16] is alsobe-ing reimplementedin Giotto. In contrastto theOLGA helicoptercontrolsystem,wherethefunctionality programshave beenreusedfrom theoriginal project,thesecondgenerationof theBEAR helicoptercontrolsystemis a completeredesignof thesoftwareimplementation[28].

Except for the one usedin the OLGA helicoptercontrol system(which iswritten in Oberon),all currentversionsof the EmbeddedMachineare written

29

in C andarePOSIX-compliant.Non-real-time implementationsof the Embed-dedMachinearealsoavailablefor Linux andWindows. TheGiotto compileriswrittenin Java. All Giottosoftwaretoolsareavailablefor downloadathttp://www.eecs.berkeley.edu/~fresco/giotto.

Related work

Giottowasoriginally inspiredby thetime-triggeredarchitecture(TTA) [29], whichfirst realizedthetime-triggeredparadigmfor meetinghardreal-timeconstraintsinsafety-criticaldistributedsettings.WhereastheTTA encompassesa hardwarear-chitectureandcommunicationprotocol, Giotto providesa platform-independentprogrammer’s modelfor time-triggeredapplications.

The inter-task communicationsemanticsof Giotto is similar to the MetaHlanguage[30], which is designedfor real-time, distributedavionicsapplications.Giotto canbeviewedascapturinga time-triggeredfragmentof MetaHin anab-stractandformalway. In particular, unlikeMetaH,Giottospecifiesnotonly inter-taskcommunication but alsomodeswitchesin a time-triggeredfashion,and itdoesnot constraintheimplementation to aparticularschedulingscheme.

Many objectivesof Giotto aresharedby the synchronousreactive program-ming languages[21], including Esterel[31], Lustre[32], andSignal[33]. Giottoemphasizestheuseof scheduledcomputation(i.e., theexecutionof tasks,whichconsumenon-negligible amountsof CPU time) at the expenseof synchronouscomputation (i.e., theexecutionof drivers,which areconstrainedto bebounded,independent,non-interactingprocesses).Consequently, while thecompilation ofsynchronousreactive languagesfocuseson fixed-pointanalysis,the compilationof Giotto focusesonschedulabilityanalysis.A moredetailedcomparisonis givenin [34].

Acknowledgments. We thankNiklausWirth andWalterSchaufelbergerfor theiradviceandsupportof thereengineeringeffort of theETH Zürich helicoptercon-trol systemusingGiotto.

References

[1] C.M. Kirsch, M.A.A. Sanvido, T.A. Henzinger, andW. Pree, "A Giotto-basedhelicoptercontrol system," in Proc. SecondInternationalWorkshoponEmbeddedSoftware (EMSOFT), LNCS2491,SpringerVerlag,2002.

30

[2] T.A. Henzinger, B. Horowitz, andC.M. Kirsch, "Giotto: A time-triggeredlanguagefor embeddedprogramming," in Proc. First International Work-shop on EmbeddedSoftware (EMSOFT), LNCS 2211, Springer Verlag,2001,pp.166–184.

[3] J. Chapuis,C. Eck, M. Kottmann,M.A.A. Sanvido, andO. Tanner, "Con-trol of helicopters,"in K. Ågström, P. Albertos, M. Blanke, A. Isidori,W. Schaufelberger, and R. Sanz, editors, Control of Complex Systems,SpringerVerlag,1999,pp.359–392.

[4] N. Wirth, "Tasksversusthreads:An alternative multiprocessingparadigm,"Software-ConceptsandTools, vol. 17,pp.6–12,1996.

[5] T.A. Henzinger, "Masaccio: A formal modelfor embeddedcomponents,"inProc.First IFIP InternationalConferenceonTheoreticalComputerScience,LNCS1872,SpringerVerlag,2000,pp.549–563.

[6] D.J. McConnel,B. Lewis, andL. Gray, "Reengineeringa single-threadedembeddedmissile application onto a parallel processingplatform usingMetaH," Real-TimeSystems, vol. 14,pp.7–20,1998.

[7] N. Wirth, A ComputerSystemfor ModelHelicopterFlight Control; Techni-cal Memo6: TheOberonCompilerfor theStrongARMProcessor, TechnicalReport314,Institute for ComputerSystems,ETH Zürich,1999.

[8] N. Wirth andJ. Gutknecht, Projekt Oberon: TheDesignof an OperatingSystemandCompiler, ACM Press,1992.

[9] M.A.A. Sanvido, A ComputerSystemfor ModelHelicopterFlight Control;Technical Memo3: TheSoftware Core, TechnicalReport317,Institute forComputerSystems,ETH Zürich,1999.

[10] weControlGmbH, wePilot1000[Online].Availableathttp://www.wecontrol.ch.

[11] TheRoboticsInstitute,CarnegieMellon University[Online].Availableathttp://www.cs.cmu.edu/afs/cs/project/chopper/www.

[12] TheUAV Lab,Georgia Instituteof Technology[Online].Availableathttp://controls.ae.gatech.edu/labs/uavrf.

31

[13] Laboratoryfor Information andDecisionSystems,Massachusetts Instituteof Technology, Aerial Robotics[Online].Availableathttp://gewurtz.mit.edu/research/heli.htm.

[14] Robotics ResearchLaboratory, University of SouthernCalifornia, Au-tonomousFlying Vehicles[Online].Availableathttp://www-robotics.usc.edu/~avatar.

[15] MeasurementandControl Laboratory, ETH Zürich, AutonomousHelicopterProject[Online].Availableathttp://www.heli.ethz.ch.

[16] ElectronicResearchLaboratory, Universityof CaliforniaatBerkeley, BEAR:Berkeley Aerial Robot[Online].Availableathttp://robotics.eecs.berkeley.edu/bear.

[17] AerospaceRoboticsLaboratory, StanfordUniversity, TheHummingbird He-licopter [Online].Availableathttp://sun-valley.stanford.edu/~heli.

[18] Institute for TechnicalComputerScience,TechnischeUniversität Berlin,Marvin [Online].Availableathttp://pdv.cs.tu-berlin.de/MARVIN.

[19] C. Eck, Navigation Algorithmswith Applicationsto UnmannedHelicopters,Ph.D.Thesis14402,ComputerScience,ETH Zürich,2001.

[20] T.A. HenzingerandC.M. Kirsch, "The EmbeddedMachine: Predictable,portablereal-time code," in Proc. ACM SIGPLANConferenceon Pro-grammingLanguageDesignandImplementation(PLDI), ACM Press,2002,pp.315–326.

[21] N. Halbwachs, SynchronousProgrammingof ReactiveSystems, Kluwer,1993.

[22] T.A. Henzinger, C.M. Kirsch, R. Majumdar, and S. Matic, "Time-safetycheckingfor embeddedprograms,"in Proc.SecondInternational WorkshoponEmbeddedSoftware (EMSOFT), LNCS2491,SpringerVerlag,2002.

32

[23] C. Ferdinand,R. Heckmann,M. Langenbach,F. Martin, M. Schmidt,H. Theiling, S. Thesing,andR. Wilhelm, "ReliableandpreciseWCET de-terminationfor a real-life processor," in Proc.First InternationalWorkshopon EmbeddedSoftware (EMSOFT), LNCS 2211, SpringerVerlag, 2001,pp.469–485.

[24] Lego, Mindstorms[Online].Availableathttp://mindstorms.lego.com.

[25] WindRiver, VxWorksOperatingSystem[Online].Availableathttp://www.windriver.com/products/html/vxwks5x.html.

[26] T.A. Henzinger, B. Horowitz, and C.M. Kirsch, "Embeddedcontrol sys-temsdevelopmentwith Giotto," in Proc.ACM SIGPLANWorkshoponLan-guages,Compilers,andToolsfor EmbeddedSystems(LCTES), ACM Press,2001,pp.166–184.

[27] WindRiver, OSEKWorks OperatingSystem[Online].Availableathttp://www.windriver.com/products/html/osekworks.html.

[28] B. Horowitz, J.Liebman,C. Ma, J.T. Koo,T.A. Henzinger, A. Sangiovanni-Vincentelli, and S. Sastry, "Embedded-software designand systeminte-gration for rotorcraft UAV using platforms," in Proc. 15th IFAC WorldCongress, Elsevier, 2002.

[29] H. Kopetz,Real-TimeSystems:DesignPrinciplesfor DistributedEmbeddedApplications, Kluwer, 1997.

[30] S. Vestal, "MetaH support for real-time multi-processoravionics," inProc. Fifth InternationalWorkshopon Parallel and DistributedReal-TimeSystems, IEEEComputerSocietyPress,1997,pp.11–21.

[31] G. Berry, "The foundations of Esterel," in G. Plotkin, C. Stirling, andM. Tofte, editors,Proof, Language, and Interaction: Essaysin Honour ofRobinMilner, MIT Press,2000,pp.425–454.

[32] N. Halbwachs,P. Caspi,P. Raymond,and D. Pilaud, "The synchronousdataflow programminglanguageLustre," Proceedingsof theIEEE, vol. 79,pp.1305–1320, 1991.

33

[33] A. Benveniste,P. Le Guernic,andC. Jacquemot,"Synchronousprogram-ming with eventsand relations: The Signal languageand its semantics,"Scienceof ComputerProgramming, vol. 16,pp.103–149,1991.

[34] C.M. Kirsch, "Principles of real-time programming," in Proc. SecondInternational Workshopon EmbeddedSoftware (EMSOFT), LNCS 2491,SpringerVerlag,2002.

34


Recommended