umlpresentation3parts

62
Three Part UML Training Presentation Presented By Robert W. Sharp 2003

Upload: robert-sharp

Post on 14-Aug-2015

258 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: UmlPresentation3Parts

Three Part UML Training Presentation

Presented By

Robert W. Sharp2003

Page 2: UmlPresentation3Parts

Who: Object Management Group (OMG). Grady Booch, Ivar Jacobson, and Jim Rumbaugh original chief methodologists

What: A graphical language for depicting software requirements and design, among other things

Where: http://www.omg.org/spec/UML/

When: This 2003 presentation covers Version 1.5

Why: To standardize best practices modeling techniques

Unified Modeling LanguageIntroduction to the UML

Page 3: UmlPresentation3Parts

•Object-oriented and non-object-oriented software•Analysis of existing software•System & Software Requirements & Design Specification & Documentation

Other kinds of drawings, documents, and artifacts: Pseudo code, memory maps, lifecycle diagrams, tables, GUI concept drawings, text, formal design and requirements documents that contain the UML drawings, tables, etc.

Binary tree used by second source

function

ASYNC_DATA_INFO_STRUCT_T array used by second, third, and

fourth source functions

PCM_WORD_INFO_STRUCT_T array used by third and fourth

source functions

1

2

init()

TIO Input PCM Start Param

TIO Input PCM Data ParamAsynchornous Params

Error Indication Param

Address Range (hex) Size Access(FFFF) 5000 - (FFFF) 5020 32B S/D Card(FFFF) 4000 - (FFFF) 4020 32B TTI Card 4 (432 Test Slot)(FFFF) 3800 - (FFFF) 3820 32B TTI Card 3(FFFF) 3000 - (FFFF) 3020 32B TTI Card 2(FFFF) 2800 - (FFFF) 2820 32B TTI Card 1FFFF 0000 - FFFF FFFF 64K VMEbus A16:D16 Access

FA00 0000 - FFFE FFFF 95.9375M VMEbus A32:D32 Access

(F9)C8 0000 - (F9)CC FFFF 320K MFI Card Accesses(F9)90 0000 - (F9)97 FFFF 512K SCC Card Peripheral SRAM Slave Image(F9)80 0000 - (F9)87 FFFF 512K SCC Card A24 SRAM Slave ImageF900 0000 - F9FF FFFF 16M VMEbus A24:D32 Accesses

F800 0000 - F8FF FFFF 16M VMEbus A24:D16 Access

8000 0000 - 8007 FFFF 512K SCC Card A32 SRAM Slave Image1000 0000 - F7FF FFFF 3.625G VMEbus A32:D32 Access

0F07 F800 - 0F07 FFFF 2K Emulator Scratch Area (RW)(Set in XICE.CFG)

0F07 F7FC Top of Stack on StartupCompiler-generated tagsUninitialized Data

0F01 7C00 50B

0F00 0000 - 0FFF FFFF 16M SRAM IMAGES

UML Use

Page 4: UmlPresentation3Parts

Benefits of Using UML

•You concentrate only on solving the problem at hand, instead of also solving how to express the solution.

• Having a common expression, our designs should be easier to maintain and extend, by ourselves and by others.

• UML is an established standard, we don’t have to invent one ourselves.

• For the things that UML does, it does well.

The benefits of using UML to express requirements and design are the same as using a programming language style guide to express implementation.

Page 5: UmlPresentation3Parts

Static Structure Views:Deployment DiagramComponent DiagramClass Diagram

Behavioral Views:Use CaseSequence DiagramCollaboration DiagramActivity DiagramStatechart Diagram

Viewing Software in Different Ways

Page 6: UmlPresentation3Parts

Node

Represents apiece ofhardware.

Component

Class Name

Attributes

Methods

This is anote.

Package

Groupingmechanism.

Person

Drawing Elements

Activity

S tate N am e

S ta te V ariab les

E vent H and lingA ctivities

Use Case

Interface

Page 7: UmlPresentation3Parts

Element Relationships

Dependency

Association

Generalization

Realization (e.g.,forinterfaces)

End Point (State & Activity)

Start Point (State & Activity)

Relationship (on association)

Composite (Class)

Aggregate (Class), Decision (Activity)

Muliplicity

1 *

{constraint}E vent

<<sterotype>>

Page 8: UmlPresentation3Parts

Deployment Diagrams

Deployment diagrams show the configuration of run-time processing elements and the software components, processes, and objects that execute on them. It is the “Big Picture.”

A node is a run-time physical object that represents a computational resource, generally having at least a memory and often processing capability as well, and upon which components may be deployed.

Page 9: UmlPresentation3Parts

Case Study: Instant

Messaging Application Deployment

Diagram

AIMTransport

MSNMessengerTransport

Yahoo!MessengerTransport

IRCTransport

Jabber user m ust haveaccount on other IMserver in order to usethat server.

Jabber protocolXML

TCP Port 5222

*

Jabber protocolXML

Messages and PresenceNotifications

UNIX Machine

*

OtherTransports

STB

STB JabberUser

STB JabberUser

{ OR }

1 1..3

STB JabberUser's Jabber

Account

Local Jabber User

Rem ote Jabber User

JabberServer

JabberServer

Jabber users exchangepresence info and m essagesbetween them selves. Therem ust not be a firewall to reachrem ote Jabber users.

*

*

Each IM service (A IM, MSN,Yahoo! , Jabber, etc.) onlyexchanges presence info andm essages am ongst users of thatservice.

The num ber of concurrentlocal users is lim ited by thenum ber of possible socketconnections possible on them achine.

ICQ (fully functional), Pager (SNPP),S im plewire W ireless IM , BBS(Maple3, SOB, Maple 2.4x, SNOW ),Groove IM , Magi, O ICQ (China), SMS (inplanning phase), HTTP (to get aroundfirewall), Em ail-to-Jabber (receiving em ailonly), S IP /S IMPLE, GaduGadu (Poland).Som e of these are in planning phase andhave not been im plem ented yet.

STB Jabber User's MSNMessenger Account

MSN Messenger User 0..*

Send/Receive PresenceInfo & Messages

STB Jabber User's Yahoo!Messenger Account

Yahoo! Messenger User 0..*

Send/Receive PresenceInfo & Messages

OtherServers

MSNMessenger

Server

Yahoo!Messenger

Server

ChatServer

Maininstance ofJabber UserDirectory atjabber.org.

STB Jabber User's A IM Account

AIM User

Send/Receive PresenceInfo & Messages

AIMServer

0..*

OLD NEW

Page 10: UmlPresentation3Parts

Component Diagrams

A component diagram shows the dependencies among software

components.

A component represents a modular, deployable, and replaceable part of a system that encapsulates implementation and exposes a set of interfaces. A component may be implemented by one or more artifacts, such as binary, executable, or script files. A component may be deployed on a node.

Page 11: UmlPresentation3Parts

Class Diagrams

Class diagrams show the static structure of the model, in particular, the things that exist (such as classes and types), their internal structure, and their relationships to other things. Class diagrams do not show temporal information, although they may contain things that describe temporal behavior.

An object diagram shows instances compatible with a particular class diagram. It is a “snapshot-in-time” of the running software.

Page 12: UmlPresentation3Parts

Case Study: Video On Demand Application

Page 13: UmlPresentation3Parts

Deployment Diagram

STB

RemoteControl

Keyboard

1

1

1

3

*

Terminal

1

*

HTTPTCPIP

ATM

RTSPServer

Video Server

RAID

RTSPTCPIP

ATM

MPEG2ATM

0..*

1..*

Contains user data:which movies are rented outand their rental periods

Optional

Server

VODServer

DB

Page 14: UmlPresentation3Parts

Component Diagram

VOD Server data

SYS

3

RTSP Sessionand VCR control

VOD MovieManager

Movie Addition & Deletion,Preview Selection, Controlling

Stream Change, MPEG PositionChange, Movie Locked, Ticket

Expired

Initializes VMM, sets MPEG streamposition, gets movie's URI and

RTSP server infoGet/Set Movies' Parameters

TEARDOWN command upon ticket expiration and5 minutes after GUI thread releases movie

Gets all VOD movie rentals'information, browses movie

selections, Initiates movie rental

Ticket Expired, EOS, BOS,error/status notifications

SETUP, TEARDOWN, PLAY,PAUSE, Fast Forward,

Rewind commands

ParentalControl

Uses

Server

VODServer

DB

Video Server

RTSPServer

GUITask

VOD MovieSelection

Application

Focus & KeyInput Events

Replies, Channel Change,Focus Release

Focus & KeyInput Events

Replies, FocusRelease

RTSPClientTask

Preview selection indication, movierental indication

VOD Server data sync request

Error and statusnotifications

Bitmaps

NUses

Gets Password

Flash

Page 15: UmlPresentation3Parts

Class DiagramVOD Movie Manager

- NumMovies: dword- RentalPeriodEndTimer: tAppTmr- VodMoviesInfo: tVodMovieRentalInfo[16]

<<movie & preview addition and deletion functions>>- VmmAddMovie(pMovieInfoArg: const tVodMovieInfo *): bool+ VmmRemoveMovie(Idx: int): void+ VmmSetPreviewData(pPreviewInfoArg: const tVodMovieInfo *): void+ VmmDeletePreview(void): void

<accessor functions>>+ VmmGetNumMovies(void): dword = 0+ VmmGetTitle(MovieId: dword): const char * = NULL+ VmmGetRentEndTime(MovieId: dword): time_t = -1

<<timer related functions>>- StartRentalEndTimer(void): void- VmmCheckForExpiredTickets(TmrId: dword, UserData: dword): void

<<utility functions>>- VodMovieCmp(p1: const tVodMovieInfo *, p2: const tVodMovieRentalInfo *): bool

VOD Movie Manager module internal data, interface, and private functions.

Number of movies rentedTimer used to delete a movie at the end of its rental periodInfo for each movie rented

Page 16: UmlPresentation3Parts

Case Study: MFC/C++ Guitar Composition Application

Page 17: UmlPresentation3Parts

Class Diagram, Document Architecture #1

CDocument

CCompositionLine1..*

CTypedPtrArrayCObject

Handles Undooperations.

1..*CCompositionLine

1

CTypedPtrArray

CGuitarComposerDoc

CTypedPtrArray

CDo

CTypedPtrArray

Handles Redooperations.

{Inner class ofCGuitarComposerDoc}

Page 18: UmlPresentation3Parts

Class Diagram, Document Architecture #2

2..6

CChord

CNote

1

CCompositionLine

CObArray

CKeySignature1

1

1

CObject

CObject

CMeasure0..*

CObject

CTypedPtrArray

CTimingSignature

CObArray

1CTypedPtrArray

CObject

0..*CStroke

CObArray

CTypedPtrArray

Page 19: UmlPresentation3Parts

Class Diagram, View Architecture

CScrollView

CGuitarComposerViewCWnd CWnd

1..* 1..*

11CTypedPtrArray

CObArray

CTypedPtrArray

CObArray

CSignatureLineWnd CStrokeLineWnd

Page 20: UmlPresentation3Parts

Tablature Dialog Box Class Diagram

App CTablatureDialog

SetFingerPosition()

SetPositionIdx()

IncrementPositionIdx

DecrementPositionIdx

Stroke add,delete, modify

Select stroke|| Play[at end

stroke]

Right arrow ||Play[not atend stroke]

Left arrow

CTablatureDialog

- int m_nPositionIdx- tF3GOutputStruct *pF3GOutputStruct

<<Construction>>+ CTablatureDialog(CWnd* pParent = NULL)

<<Destruction>>+ virtual ~CTablatureDialog()

+ void SetFingerPositions(tF3GOutputStruct *pF3GOutputStruct, int nF3GPositionIdx)+ void SetPositionIdx(int nF3GPositionIdx)+ void IncrementPositionIdx(void)+ void DecrementPositionIdx(void)

<<AFX>># virtual void DoDataExchange(CDataExchange* pDX)# afx_msg void OnClose()# afx_msg void OnPaint()

- void PrintFrets(CDC *pDc, int nStartNum)- void DrawFingers(CDC *pDc, int nStartFret)

Modeless dialog window that shows tablature for the selectednote or chord.

Page 21: UmlPresentation3Parts

Static Structure Views:Deployment DiagramComponent DiagramClass Diagram

Behavioral Views:Use CaseSequence DiagramCollaboration DiagramActivity DiagramStatechart Diagram

Viewing Software in Different Ways

Page 22: UmlPresentation3Parts

Use CasesThe purpose of a use case is to define a piece of behavior of an entity without revealing the internal structure of the entity. Each use case specifies a specific way of using the entity; that is, a sequence of actions, including variants, that the entity can perform, interacting with actors of the entity. The complete set of use cases specifies all the different ways to use the entity.

An actor defines a coherent set of roles that users of an entity can play when interacting with the entity. Actors represent both human users and other systems.

A use case can be described in plain text, by activity graphs, by a state machine, by collaboration diagrams, or by other behavior description techniques, such as preconditions and postconditions.

Page 23: UmlPresentation3Parts

Simple Use Case Diagram Example

Telephone Catalog

customer

salesperson

shippingclerk

supervisor

check status

place order

fill order

establishcredit

use case

boundary ofcontainingsystem

association

actor

Page 24: UmlPresentation3Parts

Use Case and Actor Relationships

<<extend>> the salesperson asks for the catalog

place order

requestcatalog

salesperson

1 *

supply customerdata

orderproduct

arrangepayment

<<include>><<include>>

<<include>>

buy a drink

buy a soda

supervisor

salesperson

place order1 *

establishcredit

1 *

Generalization: the arrow points tothe more general actor. Supervisor canplace an order, but a salesperson cannotestablish credit.

Page 25: UmlPresentation3Parts

VOD Use Case Diagram<<use case system>>

VOD

End User

RentMovie

DisplayControls

<<include>>

Fast ForwardMovie

RemoveControls

<<include>> DisplayControls

DisplayControls

<<include>>

PlayMovie

SelectRentedMovie

<<include>>

Page 26: UmlPresentation3Parts

VOD Sample Use CasePlay Movie Scenario

Preconditions: actor has at least one VOD movie currently rented and that can be selected; movie to be played has not yet been selected.

Scenario Steps

1. Actor executes the Select Rented Movie Scenario.

2. Actor presses the remote control’s Select key or the keyboard’s (for stream 1) Enter key to invoke Play functionality. The Movie Information and Selection UI is removed and the VCR Control UI is activated. The movie begins to play.

3. If the user wishes to remove the VCR Controls, the Remove Controls Scenario is followed.

4. Afterwards, if a movie is paused, being fast forwarded, or being rewound, to play the movie the actor uses the Cursor Left and Cursor Right keys to focus the Play button and then presses the Select key (or, equivalently, pressing the “3” key).

Postconditions: VOD movie is playing; VCR controls are displayed and then removed after 2 seconds of user input inactivity.

Exceptions:

If an error occurs with an RTSP request, the VOD System Application displays a message box, with an OK button, indicating the error. Upon selection of the OK button, the Select Rented Movie Scenario is entered.

Page 27: UmlPresentation3Parts

Sequence Diagrams

A sequence diagram shows the explicit sequence of communications between participants and is better for real-time specifications and for complex scenarios. It has two dimensions: one represents time, and the other represents different instances.

Page 28: UmlPresentation3Parts

Example Sequence Diagram

ob1:C1

ob3:C3

ob2:C2

op()

[x>0] foo(x)

[x<0] bar(x)

ob4:C4

doit(z)

doit(w)

Xmore()

X

Legend

Synchronous

Asynchronous

Return from operation

Lifeline

Instancecreated

Instancedestroyed

Selfstimulus

Activation

Stimulus

Page 29: UmlPresentation3Parts

Collaboration Diagrams

A collaboration diagram shows an Interaction organized around the roles in the Interaction and their relationships. It does not show time as a separate dimension, so the sequence of communications and the concurrent threads must be determined using sequence numbers.

Page 30: UmlPresentation3Parts

Case Study: Video On Demand Application

Page 31: UmlPresentation3Parts

Deployment Diagram

STB

RemoteControl

Keyboard

1

1

1

3

*

BDT

1

*

HTTPTCPIP

ATM

RTSPServer

nCUBE's n4 Video Server

VOD moviereferenced by

VPI/VCI

VOD moviereferenced by

BpID

RAID

RTSPTCPIP

ATM

MPEG2ATM

0..*

1..*

There may be morethan one n4 server, each n4

server can have multipleRTSP servers

Contains user data:which movies are rentedout and their rental periods

Optional

Sun Solaris Server

ODAServer

OracleDB

Page 32: UmlPresentation3Parts

Component Diagram

ODA Server data

USH

3

RTSP Sessionand VCR control

VOD MovieManager

Movie Addition & Deletion,Preview Selection, BPID,

Controlling Stream Change,MPEG Position Change, Movie

Locked, Ticket Expired

3

Initializes VMM, sets movie's BPIDand MPEG stream position, gets

movie's URI and RTSP server infoGet/Set Movies' Parameters

TEARDOWN command upon ticket expirationand 5 minutes after GUI thread releases movie

Gets all VOD movie rentals'information, browses movie

selections, Initiates movie rental

The VOD Movie Manager,RTSP Client Task, and thethree VOD GUI Taskscollectively are referred to asthe VOD System Application.

Ticket Expired, EOS, BOS,error/status notifications

SETUP, TEARDOWN,PLAY, PAUSE, Fast

Forward, Rewind commands

ParentalControl

Uses

Sun Solaris Server

ODAServer

OracleDB

nCUBE's n4Video Server

RTSPServer

VOD GUITasks

VOD MovieSelection

Application

Focus & KeyInput Events

Replies, ChannelChange, Focus Release

Focus & KeyInput Events

Replies, FocusRelease

RTSPClientTask

Preview selection indication,movie rental indication

ODA Server data sync request

Error and statusnotifications

3

1

1

Bitmaps

N

3

Uses

StarSight module

VOD SystemApp Startup

Function

Calls VOD Movie Selection Application'sinitialization function, Parental Control'sinitialization function (for each stream), VOD GUItasks' initialization function (for each stream), andRTSP Client's initialization function.

Gets Password

FlashGets Global Lock status

Page 33: UmlPresentation3Parts

VOD Startup Collaboration Diagram

7. Requests VODmovie rentalinformation

3. VodGuiInit()(all 3 streams)

Legend

Synchronous

Asynchronous

8. VOD movierental information

6. OdaRentalSync()

4. RtspClientInit()

VOD MovieSelection

Application

2. PcInit() (allthree streams)

Sun Solaris Server

ODAServer

OracleDB

9. VmmCODatabaseInfo()

5. VmmInit()

10. 0..* VodGuiVmmMovieAdded()

1. WebsterStart(0)

VOD SystemApp Startup

Function

VOD MovieManager

VOD GUITasks

ParentalControl

RTSP ClientTask

Page 34: UmlPresentation3Parts

Movie Preview Collaboration Diagram

4. VmmSetPreviewData()

5.VodGuiRequestFocus

ToWatchPreview()

RTSP ClientTask

2. RequestsPreview Data

1. User selects"PREVIEW" button in ODA

Server's HTML page

3. Preview Data

VOD MovieManager

Sun Solaris Server

ODAServer

OracleDB

VOD GUITasks

USH

VOD MovieSelection

Application

6. RequestApplication Focus

7. Release Application Focus

8. AssignApplication Focus

9. RtspSetup()

Page 35: UmlPresentation3Parts

Design Pattern As A Collaboration Of Classes

abstracthierarchical state

m achine baseclass

concretehierarchical

statem achine

buffer usedto storeevents(m essages)for HSM

utility classused byconcreteHSMs

eventbaseclassevent class

specializedfrom base

event class

CTim erCEQueue

CConcreteHsm

<<abstract>>CHsm

CEvent

CSpecializedEvents

<<pattern>>H ierarch ica l S ta te M ach ine

collaborationnam e

role ofpartic ipant

partic ipant

Page 36: UmlPresentation3Parts

Activity Diagrams

An activity graph focuses on procedural flows driven by internal processing (as opposed to external events). The activity states represent actions or subactivities and the transitions are triggered by the completion of the actions or subactivities.

Page 37: UmlPresentation3Parts

Activity Diagram Example

FindBeverage

Put coffeein filter

Put filter inmachine

Add waterto resevoir

Get cups

Turn onmachine

Brewcoffee

[found coffee]

[no coffee]

Pour coffee

[found cola]

[no cola]

Drink

Get can ofcola

Startpoint

Action stateGuardcondition

Decision

Endpoint

Split

Concurrentpaths

Join

Transition

Page 38: UmlPresentation3Parts

Subactivity States and SignalsHigh-Level Activity

Subactivitystate

turn onmachine

turnOn coffeePot

brew coffee

light goes out

pour coffee

Sending a signal /output event

Receiving a signal /input event

Page 39: UmlPresentation3Parts

Swimlanes

requestservice

pay

Customer Sales

take order

Stockroom

fill order

deliverorder

collectorder

Swimlanes are used to organize responsibility for actions and subactivities.

Page 40: UmlPresentation3Parts

Static Structure Views:Deployment DiagramComponent DiagramClass Diagram

Behavioral Views:Use CaseSequence DiagramCollaboration DiagramActivity DiagramStatechart Diagram

Viewing Software in Different Ways

Page 41: UmlPresentation3Parts

Statechart Diagrams

A statechart diagram describes the behavior of an entity (class, use-case, actor, subsystem, operation, or method) capable of dynamic behavior or an interaction between entities by specifying its response to the receipt of an event. It describes possible sequences of states and actions through which the entity(ies) can proceed during its (their) lifetime as a result of reacting to discrete events.

A state is a condition during the life of an object or an interaction during which it satisfies some condition, performs some action, or waits for some event.

Page 42: UmlPresentation3Parts

Synchronous Sequential Networks (SSN)•Outputs dependent on what has happened in the past (has memory), as well as the instantaneous inputs; associated with a clock•Described by state table or state diagram

Design Procedure 1. Construct state table or state diagram (this is the system, or

application, specification). No general systematic procedure. May be helpful to develop a machine based on a particular input sequence and initial state, then go back and develop next state and output for alternative sequences. Carefully define the information a state represents. Introduce a new state only if

an existing state doesn’t exist that represents the information of this new state. 2. Code the sequential machine3. Design a combinational network to implement the next state and

output functions4. Establish timing (for proper initialization and glitchless output)

q0

q3

IN/OUT0/0

1/3

1/1 0/1

1/2 0/2

q1 q20/1

1/2

In the beginning …

Page 43: UmlPresentation3Parts

SSN Coding

Application EquationsOutputs = f(Current State) Moore MachineOutputs = f(Current State, Inputs) Mealy MachineQ(n+1) = Q(n)

Characteristic Equations of Circuit ElementsQ(n+1) = S + /R Q(n) S-R Flip-FlopQ(n+1) = /K Q(n) + J /Q(n) J-K Flip-FlopQ(n+1) = Q(n) D Flip-Flop

Transition EquationsS[i](n+1) = f[i](Inputs, Current State) S-R Flip-FlopR[i](n+1) = f[i](Inputs, Current State) S-R Flip-FlopJ[i](n+1) = f[i](Inputs, Current State) J-K Flip-FlopK[i](n+1) = f[i](Inputs, Current State) J-K Flip-FlopD[i](n+1) = f[i](Inputs, Current State) D Flip-Flop

Register

Inputs, I

CurrentState, Q(n)

NextState,Q(n+1)

CombinationalNetwork

Outputs, O

Clock, 1Inputs

Outputs

state registerCombinationalNetwork

Q

Q

Inputs and/or Outputs also registered(on different clocking phase than stateregister) so outputs don't "glitch".

Clock, 2

Try to use Grey Code for adjacent states, where only one bit changes in state Q

Page 44: UmlPresentation3Parts

Huffman-Mealy Procedure for State Reduction

1. Combine states that have the same outputs and next states for the same inputs

2. Group states with common outputs

3. Repeatedly break into unique states with the same next state until minimum obtained

a dNext State

IN=0 1 2IN=1 2 2

1

aNext StateIN=0 1IN=1 2

1d

Next StateIN=0 3IN=1 3

2

b c e fNext State

IN=0 1 1 1 1IN=1 2 2 2 2

2

b c e fNext State

IN=0 2 1 2 1IN=1 3 3 3 3

3

aNext StateIN=0 1IN=1 2

1d

Next StateIN=0 3IN=1 3

2b e

Next StateIN=0 2 2IN=1 4 4

3c f

Next StateIN=0 1 1IN=1 3 3

4

Only four uniquestates required.

Q(n)abcdef

Q(n+1)IN=0 IN=1

a bd ca be fd fa e

OUT011011

Q(n)abcd

Q(n+1)IN=0 IN=1

a dd ca bb b

OUT0110

Page 45: UmlPresentation3Parts

Example Finite State Machine (FSM) in VHDLLIBRARY ieee; USE ieee.std_logic_1164.all; entity State_Machine is port (CLK, RDY: in std_logic; P: buffer std_logic; Q: buffer std_logic_vector(1 downto 0)); end State_Machine;

architecture my_SM of State_Machine is begin process (CLK,RDY) begin if (RDY = '0') then P<='0'; Q<="00"; elsif (CLK'event and CLK='0') then case Q is when "00" => P <= '1'; Q <= "01"; when "01" => P <= '1'; Q <= "11"; when "11" => P <= '1'; Q <= "10"; when "10" => P <= '0'; Q <= "10"; when others => P <= '0'; Q <= "01";

end case; end if; end process; end my_SM;

Jump ahead 20 years, and combinational logic and state registers are on “registered” PLDs and FPGAs. State machine is described by a Hardware Description Language (HDL).

Page 46: UmlPresentation3Parts

Example Finite State Machine (FSM) in VerilogModule State_Machine (CLK, RDY, P, Q); input CLK, RDY; output P; output [1:0] Q;

initial Q = 0; always @(negedge CLK) begin: PROCESS if (RDY = ‘0’) then P = 0; Q = 0; else begin case (Q) 0: P = 1; Q = 1; 1: P = 1; Q = 2; 2: P = 1; Q = 3; 3: P = 0; Q = 0; endcase; end; end;endmodule;

Page 47: UmlPresentation3Parts

Software State Machine Implementations

•Non-modal techniques

•Nested switch()

•State table

•State pattern

•Hierarchical

EventProducer

EventQueue

Event Dispatcher(Event Consumer)

EventHandler* *

putevents

into

takeeventsfrom

dispatchevents to

Page 48: UmlPresentation3Parts

Non-Modal Techniques I

•Functions

•Threads

•ProcessesKeypad Handler

GetTime()SET COOKINGTIME Pressed

ENTER pressedStore

cookingtime

Cook()COOK Pressed

STOP pressed || Timeup || Door opened

Get Time

SET COOKINGTIME pressed

ENTERpressed

Cooking

Get Command

Done Error

Time upDooropened

CLEARpressed

CLEARpressed

STOPpressed

COOKpressedand doorclosed

Page 49: UmlPresentation3Parts

Non-Modal Techniques IIUse case: Upon the entity receiving the input pattern “XYZ”, the pattern “ABC” is output by the entity.

•Counters • Loops • Data structures

X

Y

waiting

'X' received

'Y' received

A

entry/ output A;

B

entry/ output B;'Z' received

C

entry/ output C;

[else]

[last 3 characters == "XYZ"]

get input charaacterand put in buffer

n = 0

[n == 1]

[n == 2]

shift out'A'

shift out'B'

shift out'C'

[n == 0]

n++

[else]

Page 50: UmlPresentation3Parts

Nested switch()switch (state) {case state1:

switch (event) {case event1:…; break;case event2:…; break;…

}case state2:

switch (event) {case event1:…; break;case event2:…; break;…

}…}

Page 51: UmlPresentation3Parts

State Tabletypedef enum {e1, e2, …, MAX_EVENT} event;typedef enum {s1, s2, …, MAX_STATE} state;typedef void(*action)(void);void act1(void); void act2(void); …struct { state next; action act;} state_table[MAX_STATE][MAX_EVENTS] =

{{s2, act2}, {s3, act3}, … },{{s10, act10}, {s11, act11}, … },{{s15, act15}, {s15, act15}, … },{{s20, act20}, {s1, act1}, … },

…};

Indexed by state

Indexed by event

Page 52: UmlPresentation3Parts

State Pattern

state pattern

ConcreteStateA

ConcreteStateBContextcurrent_state

provides clientinterface

(accepts events),may determine

next state

defines interface to states,i.e., event handler interface

<<abstract>>State

Handle()

concrete states/definitionof specific behavior, may

determine next state

.

.

.Delegatesevents tocurrent_state.

Page 53: UmlPresentation3Parts

UML Statecharts / State Machines I

top

state variables

entry/ action;exit/ action;eventX/ action;

State Nameevent(param1, param2, ...) [guard] / action1; action2; ...

Starting event, like"Thread starts"

evt(param1, param2)

Initialpseudostate --no eventassociated withtransition.

All state machines have a top state,which cannot be transitioned to andwhose depiction is optional.

another state

entry / actions;exit / actions;event [ guard ] / actions;

state variable 1: int = 0;bBoolVar: bool = true;...

so

event [guard] / actions;

s2

some event

[ some guard ]

[ someother

guard, like"else" ]

s1

Notation toindicate a statehas substates.

Choicepseudostate,alsodepicted asa diamond.

Guardsshould nothave sideeffects.

Finalpseudostate.

terminatoin event

All parts optional

self transition event

Statetransition.

Internaltransitions.

Parameterizedevent("SignalEvent").

Page 54: UmlPresentation3Parts

UML Statecharts II

Orthogonal Region State Machine

State Machine One

S00

State Machine Two

S10events1_to_2

events2_to_1

Being "in astate" is to be inmultiple statessimultaneously.

Time Eventafter(some-period-time)

Change Eventwhen(some-boolean-expression)

Signal Event and Call Eventsignal-name(param1,param2,…)

state orez

after(10 ms) / act();

state eno

when(ready) / do_this()

after(50 ms) when (!ready)

Page 55: UmlPresentation3Parts

UML Statecharts III

s0Shallow historypseudostate -- themost recent directsubstate recentlyactive is transitionedback to.

Deep historypseudostate --the most recentlyactive substate(recursive) istransitioned backto.

s0

s1S2

e1e2

e3

H

H*

Defaultpreviousshallowhistory state.

Default previousdeep history state.

s1

s2

s3

s4

e1

e1

e1

e1

Page 56: UmlPresentation3Parts

UML Statecharts IV

process

setup

A2

B2

A1

B1

cleanup

Name tab

Forkpseudostate

Joinpseudostate

s0 s1

e2[b<0] e1[b<0]

[a<0]

[a = 5]

[a > 7]

s2 s3 s4

Junctionpseudostate

Page 57: UmlPresentation3Parts

Hierarchical State Machine Engine Pattern

abstracthierarchical state

machine baseclass

concretehierarchical

statemachine

buffer usedto storeevents(messages)for HSM

utility classused byconcreteHSMs

eventbaseclassevent class

specializedfrom baseevent class

CTimerCEQueue

CConcreteHsm

<<abstract>>CHsm

CEvent

CSpecializedEvents

<<pattern>>Hierarchical State Machine

Page 58: UmlPresentation3Parts

Hierarchical State Machine Engine Class Diagram

evtmy_queue

0..*

used by statehandlers

CSpecializedEvents

put into andretrieved

from

<<standard signals>>+ EMPTY_SIG: const int = 0+ INIT_SIG: const int = 1+ ENTRY_SIG: const int = 2+ EXIT_SIG: const int = 3+ TERM_SIG: const int = 4+ USER_SIG: const int = 5

<<event ID>>+ sig:int+ hsmp: CHsm*

CEvent

CConcreteHsm

Handler1(event *)Handler2(event *)...

<<abstract>> CHsm

- tid_dispatcher: pthread_t - tid_tmr: pthread_t- my_queue: CQueue - element_size: size_t- my_state: State - my_source: State

# CHsm(initial:State, q_num_entries:unsigned, q_sizeof_entry:size_t, tick_resolution_ms:unsigned = 10, debug_flags:unsigned = 0 )+ virtual ~CHsm()

<<state machine control>># init(target:State):void # tran(target:State): void# dispatch(e: CEvent): void # PseudoState top(const CEvent *): State

<<queue interface>>- get_event(char *msg, unsigned msgLen): void- dispatcher_thread(arg:void *): void *+ post_event(const char *msg, size_t msgLen, unsigned priority): bool

CEQueue

<<queue variables>>- buf: char * - ele_size: size_t- q_cv: pthread_cond_t - q_mutex: pthread_mutex_t- my_start: CEvent * - my_end: CEvent *- my_head: CEvent * - my_tail: CEvent *- my_nmax: unsigned short ...

<<interarrival time analysis variables>>- arrival_time_hsmp: CHsm *- avg_arrival_time_microseconds: unsigned long ...

+ CEQueue(num_elements: unsigned, element_size: size_t, debug_f: unsigned = 0)+ virtual ~CEQueue()+ void get(msg: char *, msgLen: unsigned): void+ putFIFO(msg: char *, msgLen: unsigned): bool+ putLIFO(msg: char *, msgLen: unsigned): bool+ get_avg_interrival_time_microseconds(): unsigned long...

CTimer

- timer_cv: pthread_cond_t- timer_mutex: pthread_mutex_t- head: CTimer* - step_ms: int- time2die: bool- next:CTimer* - evt: CEvent- ctr_ms: int - interval_ms: int

+ CTimer()+ CTimer(step_ms:unsigned)+ virtual ~CTimer()+ fire_in(p:CHsm*, sig:int, ms:int): void+ fire_every(p:CHsm*, sig:int, ms:int): void+ disarm(void): void+ rearm(ms:int): void- arm(hsmp:CHsm*, sig:int, ms:int): void+ tick(arg: void *): void *+ die(void): void+ set_step(ms: int): void

Page 59: UmlPresentation3Parts

Event Queue

An event/message queue is a non-destructive write/destructive read set of memory locations, needed for when the event production rate temporarily exceeds the event consumption rate.

An event queue decouples state machine thread from other threads, producers don’t block waiting for state machine, state machine appears always ready.

Producers add to the queue; state machine takes an event from the queue, and only after completely handling the event does it take another from the queue (Run-To-Completion, RTC, model).

State machine blocks only when waiting for an event. If an exception occurs within a state, have state send state machine an “exception event.” Use timers to send “timeout events” to the state machine. Generally try to handle blocking activities outside of the state machine context, and then send state machine events for it to handle (e.g., “Data read from file” event).

Message Producer Message Consumer

Page 60: UmlPresentation3Parts

Event Queue Sizing I

Empirical Method• Oversize queue• Run application for a while• Examine maximum number of messages in queue at any one time

Constant Pace Burst• Consumer rate, C, constant (in units of messages per unit time)• Production rate, P, constant during a burst of length T (in units of time)• Maximum Length of queue, L = PT – CT = (P – C)T• Emptying time after burst, E = L / C = (P/C – 1) T

Page 61: UmlPresentation3Parts

Event Queue Sizing IIPoisson Distribution Production/Exponential Distribution Consumption

• Average number of message arrivals per time interval = E• Mean interarrival time I = 1 / E• Average message processing time, A I must be greater than A to not overflow• Average message processing time to mean interarrival time, R = A / I• Average length of queue, Lavg = R / (1 – R) = A / (I – A)• Average amount of time message spends in queue, Tavg = A / (1 – R)• Little’s Theorem: Lavg = E * Tavg • Probability of K messages in queue at a given time, P[>=Kenqueued] = RK -- used to determine probability of queue overflowPoisson probability

distribution of message arrival rates for E = 1.P(N) = e-E(EN/N!) for N={0,1,2…}

Exponential probability distribution of message processing times. P(T) = e-T/A/A P(N)

N

Page 62: UmlPresentation3Parts

Event Queue Sizing III

Rules of Thumb• Queue size depends on duration of longest Run-To-Completion (RTC) step: avoid very long RTC steps, the quicker the processing the shorter the queue needs to be.

• Avoid correlated event production, try to spread the event production over many RTC steps.

• The maximum number of queued events is the sum of all events that higher priority threads and ISRs can produce for the state machine thread within the longest RTC step of the state machine thread.

• The higher the priority of the state machine thread, the smaller its event queue needs to be.