Unit_III

44
Unit-III Analysis ,Design concept and principle ANALYSIS MODEL: Analysis model is to provide a description of the required informational,functional and behavioral domains for a computer based system .The model changes dynamically as software engineers learn more about the system to be built.and stakeholders understand about they require.The reason is the analysis model is a instant of requirements at any given time and change it . The analysis model evolves ,certain element become stable providing a foundation for the design tasks.Even so other elements of the model may be more volatile (unstable) ,indicating the customer does not yet fully understand requirements for the system. Analysis Modeling Principles: A large number of developed analysis modeling methods,identified of analysis problems to overcome them vatiety of modeling notations and corresponding sets of heuristics to be used. 1.The information domain of a problem must be represented and understood. 2.The functions that the software performs must be defined. 3.The behavior of the software as a consequence of external events must be represented. 4.The models that depict information function and behavior must be partitiond in a manner that uncovers detail in a layered hierarchy fashion. 5.The analysis task should move from essential information towards implementation detail. Overall Objectives and Philosophy Analysis three primary objectives: 1.To describe what the customer requires. 2.To establish a basis for the creation of a software design. 3.To define a set of requirements that can be validated once the software is built. 69

Transcript of Unit_III

Page 1: Unit_III

Unit-III Analysis Design concept and principle

ANALYSIS MODELAnalysis model is to provide a description of the required informationalfunctional and behavioral domains for a computer based system The model changes dynamically as software engineers learn more about the system to be builtand stakeholders understand about they requireThe reason is the analysis model is a instant of requirements at any given time and change it

The analysis model evolves certain element become stable providing a foundation for the design tasksEven so other elements of the model may be more volatile (unstable) indicating the customer does not yet fully understand requirements for the systemAnalysis Modeling Principles A large number of developed analysis modeling methodsidentified of analysis problems to overcome them vatiety of modeling notations and corresponding sets of heuristics to be used 1The information domain of a problem must be represented and understood2The functions that the software performs must be defined3The behavior of the software as a consequence of external events must be represented4The models that depict information function and behavior must be partitiond in a manner that uncovers detail in a layered hierarchy fashion5The analysis task should move from essential information towards implementation detail

Overall Objectives and Philosophy Analysis three primary objectives1To describe what the customer requires2To establish a basis for the creation of a software design3To define a set of requirements that can be validated once the software is built

The analysis model link the gap between a system-level description that describes overall system functionality as it is achieved by applying softwarehardwaredatahuman and other system elements and a software design model that describes the softwares application architectureuser interface and component level structure

Analysis Rules of ThumbWhen creating the analysis model should be follow the Arlow and Neustadt thumb rules

Systemdescripition

Analysis model

Designmodel

69

The model should focus on requirements that are visible within the problem or business domain (area) The level of abstraction should be relatively high that to explain how the system will work

Each element of the analysis model should add to an overall understanding of software requirements and provide within reach into the information domainfunction and behavior of the system

Delay consideration of infrastructure(communications) and other non-functional models until design Example a database may be required but the classes necessary to implement itthe functions required to access it and database used the behavior (activities)will be displayed only after problem domain analysis has been completed

Minimize Coupling(combination) throughout the systemIt is important to represent relationships between classes and functionsso far if the level of interconnectedness is very high efforts should be made to reduce it

Be certain that the analysis model provides value to all stakeholdersEach stake holders has own use for model Example business stakeholders should use the model to validate requirements designers should use the model as a basis for designQuality assurance people should use the model to help plan acceptance tests

Keep the model as simple as it can be When no new information provide donrsquot add additional diagrams when a simple list will use donrsquot use complete notational (symbol)form

Domain Analysis Firesmith describes domain analysis in the following way Software domain analysis is the identificationanalysis and specification of common requirements from a specific application domain normally for reuse on multiple projects within application domain

Object ndashoriented anlysis is the identification analysis and specification of commonreusable capabilities within a specific application domain in terms of common objectsclassessubassemblies and framework

The goal of domain analysis To find or create those analysis classes and or common functions and features that are applicable and they may be reused

Input and output for domain analysis

The Input and Output for domain analysis diagram shows that source of domain knowledge are analysised try to identify objects that can be reused across the domain

ANALYSIS MODELING APPROACHESStructured analysis

70

The first approach of analysis modeling is structured analysiswhich that mapping data and processes that transfom the data as separate entities

o Data objects define their attribute and relationshipso Process manipulate the data object transform as data flow through the system

such as ERDDFDObject-Oriented analysis The Second approach of analysis modeling called object oriented analysis is to define

all classes and the relationships and behavior associated with them that are relevant to the problem to be solvedUML and Unified process are Object-Oriented

The following of tasks to accomplish the problem1Basic user requirements must be communicated between the customer and the software engineer2Classes must be identified ie defined attributes and methods3A class hierarchy is defined4Object ndash to-object relationships should be represented5Object behavior must be modeled6Tasks 1 through 5 are reapplied iteratively until the model is complete

Elements of the analysis model Analysis model leads to the derivation of each of the modeling elementsThe constructs of models as to showup certain critical features of a system while simultaneously de-emphasizing other aspects of the system

DATA MODELING CONCEPTSAnalysis modeling often begins with data modelingThe software engineer or analyst defines all data objects that are processed within the systemthe relationships between the data objects and other information relevant to the relationshipsTypes of element in Data Modeling Data ObjectsData AttributesRelationshipsCardinality and ModalityData Objects

Scenario-based elementsUse-cases-textUse-case-diagramActivity diagramsSwim lane diagrams

Flow-oriented elementsData flow diagramsControl-flow diagramsProcessing narratives

Class-based elementsClass diagramsAnalysis packagesCRC modelsCollaboration diagrams

Behavioral elementsState diagramsSequence diagrams

71

A data object is defines a composite information(data item) that is processed by software that is it incorporate(join together) collection of individual data items(attributes) and gives the collection of the name of the data object

Therefore ldquowidthrdquo is a single value would not be a valid data objectbut dimension (heightwidth and depth) could defined as an object

It encapsulate data only therefore the data object can be represented as a tablethe heading (column name)in the table is attributes of the object Example object is a car defined in terms of model ID numbeBody typecolor and ownerThe body of the table represents specific instance of the data object ie BMW is an instance of the data object car

Tabular representation of data objects

Data AttributesData attributes define the properties of a data object It follows one of three different characteristics

1)name an instance of the data object2) describe the instance 3)make reference to another instance in antoher table

The attribute as an identifier use as key to find an instance of the data objectvalues for identifiers are unique make reference to the data object

RelationshipsRelationships indicate in which data objects are connected to one another

Relationships between data objectsThe relationships owns and insured to drive define the relevant connections between person and car

Naming attributes descriptive Referential Identifier attributes attributesMake Model ID Body type Color Owner

Ford Tourus Q12A45 hellip Sedon Blue BLFBMW 750il XZ765hellip coupe white IJL

Instance

person car

72

The arrown provide information about the directionality of the relationships and reduce ambiguity or misinterpertations

Cardinality and ModalityThe data model must be capable of representing the number of occurrences of objects in a given relationships

Tillmann define the cardinality of an object or relationship pair in the following manner

Cardinality is the specification of the number of occurrences of one object that can be related to the number of occurrences of another object

Types of Cardinality11 relationship ndashone object can relate to only one other object1N relationship- one object can relate to many objectsMN relationship- some number of occurrences of an object can relate to some other nuber of occurrences of another object

It also defines ldquothe maximum number of objects that can participate in a relationshiprdquo ModalityData model does not yet provide an indication of whether or not a particular data object must participate in the relationshipto specify information the data model adds modality to the object

The modality of relationship is 0 if there is no explicit(direct) need for the relstionship to occur or the relationship is optional

The modality of relationship is 1 if an occurrence of the relationship is mandatory

SCENARIO-BASED MODELINGThe success of a computer-based system or product is measured in many waysuser satisfaction resides(be located) at the top of the list

If software engineers understand how end-users and other actor want to interact with a systemthe software team will be able to properly characterize requirements and build analysis and design models

Therefore analysis modeling with UML begins with the creation of scenarios in the form of Use-casesactivity diagrams and swimlane diagrams

Writing Use- cases A use-case are part of analysis modeling for user interfaces the interaction that occur between producers and consumers of information and the system

The concept of a use-case is easy to understand describe a specific usage scenario in straightforward language from the point of view of a defined actor not only specific person but the actor is device also The following questions that must be answered if use-cases are to provide value as an analysis modeling tool1what to write about

73

2how much to write about it3how detailed to make our description4how to organize the description What to write about itThe first tasks inception and elicitation provide us the information need to begin writing use-cases Requirements gathering meetingsQuality function deployment(QDF)and other reqirement engineering used to identify stakeholdersdefine the scope of the problemspecify overall operational goalsoutline all known functional requirements and describe the objects that will be manipulated by the system

To begin developing a set of use-cases The functions or activites performed by a specific actor are listed These may be obtained from a list of required system functionsthrough conversations with customers or end-users An evaluation of activity diagram developed as part of analysis modeling(requirement modeling) Example The SafeHome home surveillance function(subsystem) discussed in the sidebar identifies the following functions (an abbreviated list) that are performed by the homeowner actor Access camera surveillance via the internet Select camera to view Request thumbnails from all cameras Display camera views in aPc window Control pan and zoom for a specific camera Selectivel y record camera output Replay camera outputThe requirement gathering team develops use-case for each of the functionsFirst use-cases are written in an informal narrative formIf formal writte is requiredthe same use-case is rewritten using a structured format similar to proposed and later reproduced as a sidebarPreliminary use-case diagramWhen scenario is complex diagrammatic representation easy to understanding UML provide use-case diagramming capabilityPreliminary use-case diagram for the (eg)Safehome product each use-case is represented by a oval

Developing an Activity Diagram

74

The UML diagram supplements the use-case by providing a graphical representation of the flow of interaction within a specific scenarioIt is similar to flow chartan activity diagram notation(symbol)

-rounded rectangles to imply a specific system function -arrows to represent flow through the system -decision diamonds to indicate a branching decision -solid horizontal line to indicate that parallel activities are occurring

An activity diagram for the ACS_DCV function( access surveillance ndashdisplay camera view function)

The activity diagram adds additional detail not directly mentioned by the use-caseFor example a user may only attempt to enter userID and password a limited number of timesthis is represented by a decision dicmond below prompt for reentry

Swimlane DiagramsThe UML swimlane diagram is a variation of the activity diagram and allows the modeler to represent the flow of activities by the use-case

75

And at the same time indicate suppose if there multiple actors involved in a specific function in which actor or analysis class has responsibility for the action described by an activity rectangle

Responsibilities are represented as parallel segments that divide the diagram vertically like the lanes in a swimmingpool A UML swimlane diagram for access surveillance ndashdisplay camera view function

The activity diagram is rearranged that activities associated with a particular analysis class inside the swimlane for the classExample The Interface class represents the user interface as seen by the homeownerThe responsibility of the interface is two prompt prompt for reentry and prompt for another view

76

These prompts and the dscision associated with them fall within the Interrface swimlane but arrows from that swimlane back to the Homeowner swimlane where homeowner actions occur

FLOW-ORIENTED MODELING Data flow-oriented modeling is one of the most used analysis notations is a core modeling activity in structured analysis

Elements of flow-oriented modelingCreating a Data flow modelProcessing narratives Creating a Control flow model The Control SpecificationThe Process SpecificationCreating a Data Flow Model

The data flow diagram enables the software engineer at the same time to develop models of the information domain and functional domain

DFD is refined into greater level of detailthe analyst performs an implicit (indirect) functional decomposition of the system

DFD refinement result corresponding refinement data implied in through process in the application

DFD takes an input ndashprocess-output view of a system that is data objects flow into the software are transformed by processing selements and resultant data objects flow out of the software

Data objects represented by labeled arrow and transformations are represented by circles also called bubbles

DFD is presented in hierarchical manner The first data flow model called a level 0 DFD or context diagram represent the

system as a wholeSubsequent data flow diagram providing increase detail with each subsequent level refine context diagram

The guidelines can aid immeasurably during derivation of a DFD 1The level 0 data flow diagram should describe the softwaresystem as a single bubble2primary input and output should be carefully noted3refinement should begin by isolating candidate processesdata objects and data stores to be represented at the next level4all arrows and bubbles should be labeled with meaning ful names5information flow continuity must be maintained from level to level6one bubble at a time should be refined

Context level DFD (level 0 DFD)The primary external entities (boxes) produce information for use by the system and consume information generated by the systemThe labeled arrows represent data objects or in hierarchiesExample Context ndashlevel(level 0) DFD for the security Safe home function

77

User command and data encompasses all configuration commandsall activationdeactivation commands all miscellaneous interactions and all data that are entered to expand a commandProcessing narrative

It is similar to the use-case in style but different in purpose it provides an overall description of the function to be developed It is not a scenario written from one actorrsquos point of view

The level 0 DFD expanded into a level 1 data flow model to proceed A simple even so effective approach is to perform a ldquogrammatical parserdquo on the processing narrative

that describes the context level bubbleThe following processing narrative text with the first occurance of all nouns underlined and the first occurrence of all verbs italicizedExample Safehome processing narrativeThe Safehome security function enables the homeowner to configure the security system when it is installedmonitors all sensors connected to the security and interacts with the homeowner through the Internet a PC or a control panel

Level 1 DFD for Safehome processesReferring to the grammatical parse verbs are represented as bubbles in a subsequent DFDNouns are either external entities (boxes)data or control objects (arrows) or data stored(double lines) that nouns and verbs can be associsated with one anotherFor example each sensor is assigned a number and type are attributes of the data object sensorTherefore by performing a grammatical parse on the processing narrative for a bubble at any DFD level

78

Level 2 DFD The processes represented at DFD level 1 can be further refined into lower levelsThe information flow continuity has been mainted between levels 0 and 1ExampleThe process monitor sensors can be refined into a level 2 DFD

The refinement of DFDs continues until each bubble performs a simple function that would be easily implemented as a program component

Creating A Control Flow Model

79

Control flow modeling used for a large class of applications are ldquodrivenrdquo by events rather than data produce control information rather than reports or displays and process information with heavy concern for time and performance

Already noted that an event or control item is implemented as a Boolean value ie true or false1 or 0 or a discrete list of conditions

The following guidelines to select potential(possible) candidate events-

o List all sensors that are ldquoreadrdquo by the softwareo List all interrupt conditionso List all ldquoswitches ldquothat are actuated by an operatoro List all data conditionso Recalling the nounverb parse that was applied to the processing narrativereview

all ldquocontrol itemsrdquo as possible for control flow inputsoutputso Describe the behavior of a system by identifying its statesidentify how each state

is reached and define the transitions between stateso Focus on possible omissions a very common error in specifying controlfor

example ask ldquoIs there any other way I can get this state or exit from itrdquoThe Control SpecificationThe control specification (CSPEC) represents the behavior of the system in two different ways 1 State diagram 2 Program activationState diagramIt is a sequential specification of behaviorProgram activationIt also contain a program activation table is a combinatorial specification of behavior

The CSPEC describes the behavior of the system but it gives us no information about the inner working of the process that are activated as aresult of this behaviorExampleThe state diagram indicates that the transitions from the idle state can occurTwo transitions occur out of the Monitoring system status state(1)when the system is deactivated a transition occurs back to the idle state(2) when a sensor is triggered a transition to the Acting Alarm state occurs During the review consider all transition and the content of all states

The Process Specification The process specification (PSPEC) is used to describe all flow model processes that

appear at the final level of refinement The content of the process specification can include narrative texta program design

language(PDL) description of the algorithmmathematical equations tablesdiagrams or charts

The PSPEC is a lsquomini specificationrdquofor each transform at the lowest refined level of a DFD that as a guide for design of the software component that will implement the process

Example The password transform represented in the flow model for Safehome the function is perform by PSPEC

80

If the password matches an entry within the table [valid id message=true] is passed to the message and status display functionIf there is no matah [valid id message=false]is passed to the message and status display function

CLASS-BASED MODELING Class-based element of an analysis modelClasses and objectsAttributesOperationsPackagesCRC modelsCollaborations diagram

Identifying Analysis ClassesTo identify classes by examining the pbolem statement or by performing a

ldquogrammatical parserdquo the use-cases or processing narratives developed for the system to be built Classes are determined by underlinining each noun or noun clause and enter it into a simple tableIf the class is required to implement a solution then it is part of the solution space other wise if a class is necessary only to describe a solution it is part of the problem space

The following ways are for Analysis classes to manifest (marked) themselves External entities that produce or consume information to be used by a computer-based

system (eg) devicespeople Things that are part of the information domain for the problem(eg) reports displays

leeterssignals Occurrences or events that occur within the context of system operation(eg)

aproperty transfer or the completion of a series of robot movements Roles played by who interact with the system(eg) manager engineersalesperson Organizational units that are relevant to an application(eg)division groupteam Places that establish the context of the problem and the overall function of the system

(eg) manufacturing floor ) Structures that define a class of objects or related classes of objects (eg)

sensors four-wheeled vehicles or computerBudd suggests taxonomy (classification) of classes that includes producers(sources0 and consumers(sinks) of datadata managerview and helper classes

A class should never have an ldquoimperative procedural namerdquo(eg) an object with the name Imageinersion would making mistake so that inversion of the image the inversion() is an operation that applied to the class image During early stage of modeling analysis class might be defined to the example of Safehome security function performed in a ldquogrammatical parserdquo on a processing narrativeExtracting the nouns each entry in the list a potential object

Coad and Yourdon suggest six selection characteristics that should be used as an analyst considers each potential class for inclusion in the analysis model

1Retained informationThe potential class will be useful during analysis only if information about it must be remembered so that the system can function

81

2Needed servicesThe potential class must have a set of identifiable operations that can change the value of its attributes in some way3Multiple attributesDuring requirement analysis the focus should be on ldquomajor ldquo information a class with a single attribute be useful during design but better to represent ed as an attribute of another class during the analysis activity4Common attributesA set of attributes can be defined for the potential class and these attributes apply to all instances of the class5Common operationsA set of operation can be defined for the potential class and these operations apply to all instances of the class6Essential requirements External entities that appear in the problem space and produce and consume information important to the operation of any solution for the system will almost always be defined as classes in the requirements modelSpecifying AttributesAttributes are the set of data objects that fully define the class within the context of the problemExample

SystemsystemIDverificationPhonenubersystemStatusdelaytimemasterpasswordprogram()display()reset()query()modify()

The shade portion is list of attributes for the system classDefining OperationsIt define the behavior of an object The types of operations are divided into three categories (1)operations that manipulate data egadingdeletingreformattingselecting (2)operations that perform a computation (3)operations that inquire about the state of an object (4)operations that monitor an object for the occurance of a controlling eventThese functions are accomplished by operating on attributes and associationsExample Safehome processing narrative the phrases indicate that a program() operation is encapsulated by the System classClass-Responsibility-Collaborator(CRC) ModelingClass-responsibility-collaborator modeling provides simple means for identifying and organizing the classes that are relevant to system or product requirementsAmbler describes CRC modeling in the following way A CRC model is a collection of standard index cards that represent classesThe cards are divided into three sectionsDESIGN WITHIN THE CONTEXT OF SOFTWARE ENGINEERING

Design Principle1Design should be traceable to the analysis model

82

2Always consider the architecture of the system to be built3Design of data is as important as design of processing functions4Interfaces both internal and external must be designed with care5User interface design should be tuned to the needs of the end-users6Component ndashlevel design should be functionally independent7Components should be loosely coupled to one another and to the environment8Design representation(models) should be easily understandable9The design should be developed iterativelyWith each iteration the designer should stive for greater simplicity

DESIGN PROCESS AND DESIGN QUALITYDesign process

bull Design process is a sequence of steps carried through which the requirements are translated into a system or software model bull Any design may be modeled as a direct graph The graphs are collection of entities with attributes which participate in relationships bull The system should be described at several different levels of abstraction bull Design takes place in overlapping stages bull Various phases of design process are as shown in following

1 In architectural design the subsystem components can be identified2 The abstract specification is used to specify the subsystems3 The interfaces between the subsystems are designed which is called inter face design4 In component design of subsystems components is done5 The data structure is designed to hold the data6 For perfoming the required functionality the appropriate algorithm is de

signed

Software design is an iterative process through which requirements are translated into a design for constructing the software

The design is represented at a high level of abstractiona level that can be directly traced to the specific system objective and more detailed datafunctional and behavioral requirements As design iteraton occur subsequent refinement to design representation at lower levels of abstraction

McGlaughin suggests three characteristics that serve as a guide for the evaluation of a good design Each of these characteristics is a goal of the design process

The design must implement all of the explicit requirements contained in the analysis model and it must accommodate all of the implicit(indirect) requirements desired by the customer

The design must be a readable understandable guide for those who generate code and for those who test and subsequently support the software

The design should provide a complete picture of the software addressing the data functional and behavioral domains from an implementation perspective

83

Quality guidelinesThe following gidelines to evaluate the quality of a design representation

1A design should display an architecture that (a) That has been created using recognizable architectural styles or patterns

(b)That is composed of components that show good design characteristics (c)That can be implemented in an evolutionary style thereby implementing and testing2A design should be modular that is the software should be logically partitioned into elements or subsystems3A design should contain distinct representation of dataarchitectureinterfaces and components4A design should lead to data structures that are appropriate for the classes to be implemented and are drawn from recognizable data patterns5A design should lead to components that show independent functional characteristics6A design should lead to interfaces that reduce the complexity of connections between components and with the external environmemt7A design should be derived using a repeatable method that is driven by information obtained during software requirements analysis8A design should be represented using a notation that effectively communicates its meaning

Quality attributesHewlett Packard deveopled a set of software quality attributes are given as acronym(short form) FURPS to represent a target(goal) for all software design

Functionality Usability Reliability Performance Supportability

FunctionalityIt is assessed by evaluating the feature set and capabilities of the programthe generalization of the functions that are deliveredand the security of the overall systemUsabilityIt is assessed by human factors consistency and documentationReliabilityIt is evaluated by measuring the frequency and severity of failurethe accuracy of output resultsthe mean-time-to-failure(MTTF) the ability to recover from failure and predictability(unavoidability) of the programPerformanceIt is measured by processing speedresponse timeresource consumption throughput and efficiencySupportabilityItcombin the abilitytoxtendtheprogram(extensibility)adaptabilityServiceabilitymainabilitytestabilitycompatibilityconfigurability the ability to organize and control elements of the software congfiguration

Design Principles Davis suggested a set of principles for software design as

bull The design process should not suffer from ldquotunnel visionrdquobull The design should be traceable to the analysis modelbull The design should not reinvent the wheel

84

bull The design should ldquominimize the intellectual distancerdquo between the software and the problem in the real worldbull The design should exhibit uniformity and integrationbull The design should be structured to degrade gentlybull Design is not coding and coding is not designbull The design should be assessed for qualitybull The design should be reviewed to minimize conceptual errors

Design Concept

The software design concept provides a framework for implementing the right software

Following issues are considered while designing the software1Abstraction At each stage of software design process levels of abstractions should be applied to refine the software solutionAt the higher level of abstraction the solution should be stated in broad terms and in the lower level more detailed description of the solution is given While moving through different levels of abstraction the procedural abstraction and data abstraction is created In procedural abstraction it gives the named sequence of instruction in the specific function In data abstracion the collection of data objects is represented Levels of Abstraction Various levels of abstractions are- Level I - This level represents the solution interms of problem environment Level II - This level represents the decomposition of terms that are moved from problem environment but still not at implementation stage Level III - At this level preliminary procedural representation exists All the terminologies at this level are software oriented and implementation modularity begins at the surface Level IV and V - The concepts of stepwise refinement and modularity are

applied at this level2 Modularity

The software is divided into separately named and addressable components that called as modules Creating such models bring the modularity in siftwareMeyer defines five criteria that enable us to evaluate a design method with respect to its ability to define an effective modular systemModular decomposability A design method provides a systematic mechanism for decomposing the problem into sub-problems This reduces the complexity of the problem and the modularity can be achievedModular composability A design method enables existing design components to be assembled into a new systemModular understandability A module can be understood as a standalone unit Then it will be easier to build and easier to changeModular continuity Small changes to the system requirements result in changes to individual modules rather than system- wide changesModular protection An aberrant condition occurs within a module and its effects are constrained within the module3Refinement

Refinement is actually a process of elaborationStepwise refinement is a top-down design strategy proposed by Niklaus WIRTHThe architecture of a program is developed by successively refining levels of procedural detail

85

The process of program refinement is analogues to the process of refinement and partitioning that is used during requirements analysisAbstraction and refinement are complementary concepts The major difference is that - in the abstraction low-level details are suppressedRefinement helps the designer to elaborate low-levels detailsModular Design

Modular design reduces complexity and helps in easier implementation The parallel development of different parts of the system is possible due to modular designWhat is the benefit of modular design Changes made during testing and maintenance becomes manageable and they do not affect other modules Various quality parameters for effective modular design are -1) Functional independance 2) Cohesion 3) Coupling

Functional IndependenceThe functional independence can be achieved be developing the functional modules

with single-minded approachBy using functional independence functions may be compartmentalized and interfaces are simplifiedVarious types of coupling are i) Data coupling - The data coupling is possible by parameter passing or data interactionii) Control coupling - The modules share related control data in control couplingiii) Commom coupling - Content coupling occurs when one module makes use of data or control information maintained in another moduleFan-out Fan-out is a measure of the number of immediate subordinates to a moule The fan-out should be within some limit in the design If fan-out is very high then it indicates that a single module is controlling many other modules Preferably limit fan-out to no more than sevenFan-in

Fan-in indicates how many modules directly control a given module Modules with fan-in must have good cohesion Each interfac to the module must have the same number and types of parametersFactoring

Factoring means separation of function into new modules By applying factoring the size of module is reduced and thereby the complexity of the problem is reduced This also provides duplication of functions in more than one module The effective factoring brings simplification in the implementation of software design DESIGN HEURISTICS

The program structure can be manipulated according the design heuristics as shon below1Evaluate the first iteration of the program structure to reduce the coupling and improve cohesion The module independency can be achieved in the program structure by exploding or imploding the modules Exploding the modules means obtaining two or more modules in the final stage and imploding the modules means combining the result of different modules2Attempt to minimize the structure with high fan-out and strive for fan-in as depth increase At the higher level of program structure the distribution of control should be made Fan-out means number of immediate subordinates to the module Fan-in means number of immediate ancestores the module have

86

3Keep scope of the effect of a module within the scope of control of that module The decisions made in particular module lsquoarsquo should not affect the module rsquo brsquo which lies outside the scope of module lsquoarsquo4Evaluate the module interfaces to reduce complexity and redundancy and improve consistency Mostly the cause of softwatr errors is module interfaces The module interfaces should simply pass the information and should be consistent with the module5Define module whose function is predicatable but avoid modules that are too restrictive The module should be designed with simplified internal processing so that expected data can be produced as a result The modules should not restrict the size of local data structure options with control flow or modes of external interfaces Being module too much restrictive causes large maintenance6Strive for controlled entry modules by avoiding pathological connections Software interfaces should be constrained and controlled so that it will become manageable Pathological connection means many references or branches into the middle of a module

Design ModelThe design model is represented as pyramid The pyramid is a stable object

Representing design model in this way means that the software design should be stableThe design model has braod foundation of data design stable mid-region with architectural and interface design and the sharp point to for component level design

Advantages of horizontal partition1These are easy to test maintain and extend 2They have fewer side effects in change propagation or error propagation

Disadvantages of horizontal partitionMore data has to be passed across module interfaces which complicates the overall

control of program flowVertical partitioning

Vertical partitioning suggests the control and work should be distributed top-down in program structureIn vertical partitioning

Define separate branches of the module hierarchy for each major functionUse control modules to co-ordinate communication between functions

Advantages of vertical partition1These are easy to maintain the changes2 They reduce the change impact and error propagation

DATA DESIGNData design is basically the model of data that is represented at the high level of abstractionThe data design is then progressively refined to create implementation specific representationsVarious elements of data design are

Data object - The data objects are identified and relationship among various data objects can be represented using entity relationship diagrams or data dictionariesDatabases - Using software design model the data models are translated into data structures and databases at the application level

87

Data warehouses - At the business level useful information is identified from various databases and the data warehouses are created For extracting or navigating the useful business information stored in the huge data warehouse then data mining techniques are applied

ARCHITECTURAL DESIGNSoftware architecture The design process for identifying the sub-systems making up a system and the framework for sub-system control and communication is architectural design The output of this design process is a description of the software architecture

Architectural design An early stage of the system design process Represents the link between specification and design processes Often carried out in parallel with some specification activities It involves identifying major system components and their communicationsArchitecture and system characteristics Performancebull Localise critical operations and minimise communications Use large rather than fine-grain components Securitybull Use a layered architecture with critical assets in the inner layers Safetybull Localise safety-critical features in a small number of sub-systems Availabilitybull Include redundant components and mechanisms for fault tolerance Maintainabilitybull Use fine-grain replaceable components

Architectural design decisions Is there a generic application architecture that can be used How will the system be distributed What architectural styles are appropriate What approach will be used to structure the system How will the system be decomposed into modules What control strategy should be used How will the architectural design be evaluated How should the architecture be documentedArchitectural styles The architectural model of a system may conform to a generic architectural model or style An awareness of these styles can simplify the problem of defining system architectures However most large systems are heterogeneous and do not follow a single architectural styleArchitectural models

Used to document an architectural design Static structural model that shows the major system components Dynamic process model that shows the process structure of the system Interface model that defines sub-system interfaces

88

Relationships model such as a data-flow model that shows sub-system relationships Distribution model that shows how sub-systems are distributed across computers

Modular decomposition Another structural level where sub-systems are decomposed into modules Two modular decomposition models coveredbull An object model where the system is decomposed into interacting objectbull A pipeline or data-flow model where the system is decomposed into functional modules which transform inputs to outputs If possible decisions about concurrency should be delayed until modules are implemented

Object models Structure the system into a set of loosely coupled objects with well-defined interfaces Object-oriented decomposition is concerned with identifying object classes their attributes and operations When implemented objects are created from these classes and some control model used to coordinate object operations

Invoice Processing system

Pipeline model advantages Supports transformation reuse Intuitive organisation for stakeholder communication Easy to add new transformations Relatively simple to implement as either a concurrent or sequential system However requires a common format for data transfer along the pipeline and difficult

to support event-based interaction

User interface design

The user interface User interfaces should be designed to match the skills experience and expectations of

its anticipated users System users often judge a system by its interface rather than its functionality A poorly designed interface can cause a user to make catastrophic errors Poor user interface design is the reason why so many software systems are never

usedUser interface Design Principle

89

Design principles User familiaritybull The interface should be based on user-oriented terms and concepts rather than computer concepts For example an office system should use concepts such as letters documents folders etc rather than directories file identifiers etc Consistencybull The system should display an appropriate level of consistency Commands and menus should have the same format command punctuation should be similar etc Minimal surprisebull If a command operates in a known way the user should be able to predict the operation of comparable commandsbull Recoverabilitybull The system should provide some resilience to user errors and allow the user to recover from errors This might include an undo facility confirmation of destructive actions soft deletes etcbull User guidancebull Some user guidance such as help systems on-line manuals etc should be suppliedbull User diversitybull Interaction facilities for different types of user should be supported For example some users have seeing difficulties and so larger text should be available

REAL-TIME SOFTWARE DESIGNReal-time systemsSystems which monitor and control their environmentInevitably associated with hardware devices

bull Sensors Collect data from the system environmentbull Actuators Change (in some way) the systems environment

Time is critical Real-time systems must respond within specified times

Definition A real-time system is a software system where the correct functioning of the

system depends on the results produced by the system and the time at which these results are produced

90

A soft real-time system is a system whose operation is degraded if results are not produced according to the specified timing requirements

A hard real-time system is a system whose operation is incorrect if results are not produced according to the timing specification

StimulusResponse Systems Given a stimulus the system must produce a response within a specified timePeriodic stimuli Stimuli which occur at predictable time intervals

bull For example a temperature sensor may be polled 10 times per secondAperiodic stimuli Stimuli which occur at unpredictable times

bull For example a system power failure may trigger an interrupt which must be processed by the system

Architectural considerations Because of the need to respond to timing demands made by different

stimuliresponses the system architecture must allow for fast switching between stimulus handlers

Timing demands of different stimuli are different so a simple sequential loop is not usually adequate

Real-time systems are therefore usually designed as cooperating processes with a real-time executive controlling these processes

A real-time system model

Real-timecontrol system

ActuatorActuator ActuatorActuator

SensorSensorSensor SensorSensorSensor

Sensoractuator processes

Dataprocessor

Actuatorcontrol

Actuator

Sensorcontrol

Sensor

Stimulus Response

System elementsSensor control processes

bull Collect information from sensors May buffer information collected in response to a sensor stimulus

Data processorbull Carries out processing of collected information and computes the system

responseActuator control processes

91

bull Generates control signals for the actuatorsReal-time programmingHard-real time systems may have to programmed in assembly language to ensure that deadlines are metLanguages such as C allow efficient programs to be written but do not have constructs to support concurrency or shared resource management

Java as a real-time languageJava supports lightweight concurrency (threads and synchronized methods) and can be used for some soft real-time systemsJava 20 is not suitable for hard RT programming but real-time versions of Java are now available that address problems such as

bull Not possible to specify thread execution timebull Different timing in different virtual machinesbull Uncontrollable garbage collectionbull Not possible to discover queue sizes for shared resourcesbull Not possible to access system hardwarebull Not possible to do space or timing analysis

SYSTEM DESIGN Design both the hardware and the software associated with system

Partition functions to either hardware or software Design decisions should be made on the basis on non-functional

system requirements Hardware delivers better performance but potentially longer

development and less scope for changeR-T systems design process

Identify the stimuli to be processed and the required responses to these stimuli For each stimulus and response identify the timing constraints Aggregate the stimulus and response processing into concurrent processes A

process may be associated with each class of stimulus and response Design algorithms to process each class of stimulus and response These must

meet the given timing requirements Design a scheduling system which will ensure that processes are started in time to

meet their deadlines Integrate using a real-time operating system

Timing constraints May require extensive simulation and experiment to ensure that these are met by the systemMay mean that certain design strategies such as object-oriented design cannot be used because of the additional overhead involvedMay mean that low-level programming language features have to be used for performance reasons

Real-time system modellingThe effect of a stimulus in a real-time system may trigger a transition from one state to anotherFinite state machines can be used for modelling real-time systems

92

However FSM models lack structure Even simple systems can have a complex modelThe UML includes notations for defining state machine models

Petrol pump state model

Cardinserted

into reader

Timeout

Resettingdo display CC

error

Initialising

do initialisedisplay

Paying

Stopped

Reading

do get CCdetails

Waiting

do display welcome

dodeliver fuel

do debitCC account

Payment ack

Ready Delivering

update displayNozzle

trigger on

Nozzle trigger off

Nozzle trigger on

Hose inholster

do validatecredit card

Validating

Invalid card

Card removedCard OK

Hose out of holster

Timeout

Real-time operating systems(RTOS)

Real-time operating systems are specialised operating systems which manage the processes in the RTS

Responsible for process management and resource (processor and memory) allocation

May be based on a standard kernel which is used unchanged or modified for a particular application

Do not normally include facilities such as file management

Operating system componentsReal-time clock

bull Provides information for process schedulingInterrupt handler

bull Manages aperiodic requests for serviceScheduler

bull Chooses the next process to be runResource manager

bull Allocates memory and processor resourcesDispatcher

bull Starts process executionNon-stop system components

Configuration manager

93

bull Responsible for the dynamic reconfiguration of the system software and hardware Hardware modules may be replaced and software upgraded without stopping the systems

Fault managerbull Responsible for detecting software and hardware faults and taking appropriate

actions (eg switching to backup disks) to ensure that the system continues in operation

Real-time OS components

Process resourcerequirements

Scheduler

Schedulinginformation

Resourcemanager

Despatcher

Real-timeclock

Processesawaiting

resources

Readylist

Interrupthandler

Availableresource

list

Processorlist

Executing process

Readyprocesses

Releasedresources

Process priority The processing of some types of stimuli must sometimes take priority Interrupt level priority Highest priority which is allocated to processes requiring a

very fast response Clock level priority Allocated to periodic processes Within these further levels of priority may be assigned

Interrupt servicing Control is transferred automatically to a pre-determined memory location This location contains an instruction to jump to

an interrupt service routine Further interrupts are disabled the interrupt

serviced and control returned to the interrupted process

Interrupt service routines must be short simple and fast

Periodic process servicing In most real-time systems there will be several classes of periodic process each with

different periods (the time between executions) execution times and deadlines (the time by which processing must be completed)

The real-time clock ticks periodically and each tick causes an interrupt which schedules the process manager for periodic processes

The process manager selects a process which is ready for execution

Process managementbull Concerned with managing the set of concurrent processes

94

bull Periodic processes are executed at pre-specified time intervalsbull The RTOS uses the real-time clock to determine when to execute a process

taking into accountbull Process period - time between executionsbull Process deadline - the time by which processing must be complete

RTE(Real Time Execution Process) process managementResource manager

Allocate memoryand processor

Scheduler

Choose processfor execution

Despatcher

Start execution on anavailable processor

Process switchingbull The scheduler chooses the next process to be executed by the processor This

depends on a scheduling strategy which may take the process priority into account

bull The resource manager allocates memory and a processor for the process to be executed

bull The dispatcher takes the process from ready list loads it onto a processor and starts execution

Scheduling strategiesNon pre-emptive scheduling

bull Once a process has been scheduled for execution it runs to completion or until it is blocked for some reason (eg waiting for IO)

Pre-emptive schedulingbull The execution of an executing processes may be stopped if a higher priority

process requires serviceScheduling algorithms

bull Round-robinbull Rate monotonicbull Shortest deadline first

Monitoring and control systemsbull Important class of real-time systems bull Continuously check sensors and take actions

depending on sensor valuesbull Monitoring systems examine sensors and

report their resultsbull Control systems take sensor values and control hardware actuators

Generic architecture

95

S1

S2

S3

P (S1)

P (S2)

P (S1)

Monitoringprocesses

Controlprocesses

P (A1)

P (A2)

P (A1)

A1

A2

A3

P (A4) A4

Testingprocess

Control panelprocesses

Burglar alarm systembull A system is required to monitor sensors on doors and windows to detect the

presence of intruders in a buildingbull When a sensor indicates a break-in the system switches on lights around the

area and calls police automaticallybull The system should include provision for operation without a mains power

supply Sensorso Movement detectors window sensors door sensorso 50 window sensors 30 door sensors and 200 movement detectorso Voltage drop sensor Actionso When an intruder is detected police are called automaticallyo Lights are switched on in rooms with active sensorso An audible alarm is switched on

The R-T system design process

bull Identify stimuli and associated responsesbull Define the timing constraints associated with each stimulus and responsebull Allocate system functions to concurrent processesbull Design algorithms for stimulus processing and response generationbull Design a scheduling system which ensures that processes will always be

scheduled to meet their deadlinesStimuli to be processed

Power failurebull Generated aperiodically by a circuit monitor When received the system must

switch to backup power within 50 msIntruder alarm

bull Stimulus generated by system sensors Response is to call the police switch on building lights and the Power failure

bull Generated aperiodically by a circuit monitor When received the system must switch to backup power within 50 ms

bull Intruder alarmbull Stimulus generated by system sensors Response is to call the police switch

on building lights and the audible alarmbull audible alarm

Burglar alarm system processes

96

Lighting controlprocess

Audible alarmprocess

Voice synthesiserprocess

Alarm systemprocess

Power switchprocess

Building monitorprocess

Communicationprocess

Door sensorprocess

Movementdetector process

Window sensorprocess

560 Hz

60 Hz400 Hz 100 Hz

Power failureinterrupt

Alarm system

Building monitor

Alarm system

Alarm system

Alarm system

Detector status Sensor status Sensor status

Room number

Alert message

Room number

Room number

Building_monitor process 1

class BuildingMonitor extends Thread

BuildingSensor win door move

Siren siren = new Siren () Lights lights = new Lights () Synthesizer synthesizer = new Synthesizer () DoorSensors doors = new DoorSensors (30) WindowSensors windows = new WindowSensors (50) MovementSensors movements = new MovementSensors (200) PowerMonitor pm = new PowerMonitor ()

BuildingMonitor() initialise all the sensors and start the processessirenstart () lightsstart () synthesizerstart () windowsstart () doorsstart () movementsstart () pmstart ()

Building monitor process 2public void run () int room = 0 while (true) poll the movement sensors at least twice per second (400 Hz)move = movementsgetVal () poll the window sensors at least twicesecond (100 Hz)win = windowsgetVal () poll the door sensors at least twice per second (60 Hz)door = doorsgetVal ()

97

if (movesensorVal == 1 | doorsensorVal == 1 | winsensorVal == 1) a sensor has indicated an intruder if (movesensorVal == 1) room = moveroom if (doorsensorVal == 1) room = doorroom if (winsensorVal == 1 ) room = winroom lightson (room) sirenon () synthesizeron (room) break Building_monitor process 3 lightsshutdown () sirenshutdown () synthesizershutdown () windowsshutdown () doorsshutdown () movementsshutdown ()

run BuildingMonitor

Control systems

bull A burglar alarm system is primarily a monitoring system It collects data from sensors but no real-time actuator control

bull Control systems are similar but in response to sensor values the system sends control signals to actuators

bull An example of a monitoring and control system is a system that monitors temperature and switches heaters on and off

A temperature control system

Thermostatprocess

Sensorprocess

Furnacecontrol process

Heater controlprocess

500 Hz

500 Hz

Thermostat process500 Hz

Sensorvalues

Switch commandRoom number

DATA ACQUISITION SYSTEMSbull Collect data from sensors for subsequent processing and analysisbull Data collection processes and processing processes may have different periods

and deadlines bull Data collection may be faster than processing eg collecting information about

an explosion bull Circular or ring buffers are a mechanism for smoothing speed differences

The generic Architecture of data acquicition

98

DisplayProcess

dataSensor data

bufferSensorprocess

Sensoridentifier and

value

Sensors (each data flow is a sensor value)

Sensoridentifier and

value

Processdata

Sensor databuffer

Sensorprocess

Sensoridentifier and

value

Sensoridentifier and

value

s1

s2

s3

s4

s5

s6

In data acquisition systemsthe sensor may be generating data quickly and the key problem is to ensure that a sensor is allocated before sensor value changeThe essenitial features of this architecture is each group of sensors has three processes associated with it and convert analogue data to digital values if necessary a buffer process and a process that consumes the data carried out further processing Two groups sensors s1-s3 and s4-s6 on the right side a further procee that diplsys the sensor data Neutron flux data acquisition

Operatordisplay

Fluxprocessing

Flux databuffer

A-Dconvertor

Sensoridentifier and

flux valueProcessedflux level

Neutron flux sensors

bull A system collects data from a set of sensors monitoring the neutron flux from a nuclear reactor

bull Each sensor has a process that converts the analog input flux level into a digita signalIt passes this flux level with sensor identifies to the sensor data buffer the data processing takes the data from this bufferprocesses it and pass it to display process for output on an operator display

A ring buffer

Consumerprocess

Producerprocess

Mutual exclusionbull Producer processes collect data and add it to the buffer Consumer processes

take data from the buffer and make elements availablebull Producer and consumer processes must be mutually excluded from accessing

the same elementThe buffer must stop producer processes adding information to a full buffer and consumer processes trying to take information from an empty buffer

99

Page 2: Unit_III

The model should focus on requirements that are visible within the problem or business domain (area) The level of abstraction should be relatively high that to explain how the system will work

Each element of the analysis model should add to an overall understanding of software requirements and provide within reach into the information domainfunction and behavior of the system

Delay consideration of infrastructure(communications) and other non-functional models until design Example a database may be required but the classes necessary to implement itthe functions required to access it and database used the behavior (activities)will be displayed only after problem domain analysis has been completed

Minimize Coupling(combination) throughout the systemIt is important to represent relationships between classes and functionsso far if the level of interconnectedness is very high efforts should be made to reduce it

Be certain that the analysis model provides value to all stakeholdersEach stake holders has own use for model Example business stakeholders should use the model to validate requirements designers should use the model as a basis for designQuality assurance people should use the model to help plan acceptance tests

Keep the model as simple as it can be When no new information provide donrsquot add additional diagrams when a simple list will use donrsquot use complete notational (symbol)form

Domain Analysis Firesmith describes domain analysis in the following way Software domain analysis is the identificationanalysis and specification of common requirements from a specific application domain normally for reuse on multiple projects within application domain

Object ndashoriented anlysis is the identification analysis and specification of commonreusable capabilities within a specific application domain in terms of common objectsclassessubassemblies and framework

The goal of domain analysis To find or create those analysis classes and or common functions and features that are applicable and they may be reused

Input and output for domain analysis

The Input and Output for domain analysis diagram shows that source of domain knowledge are analysised try to identify objects that can be reused across the domain

ANALYSIS MODELING APPROACHESStructured analysis

70

The first approach of analysis modeling is structured analysiswhich that mapping data and processes that transfom the data as separate entities

o Data objects define their attribute and relationshipso Process manipulate the data object transform as data flow through the system

such as ERDDFDObject-Oriented analysis The Second approach of analysis modeling called object oriented analysis is to define

all classes and the relationships and behavior associated with them that are relevant to the problem to be solvedUML and Unified process are Object-Oriented

The following of tasks to accomplish the problem1Basic user requirements must be communicated between the customer and the software engineer2Classes must be identified ie defined attributes and methods3A class hierarchy is defined4Object ndash to-object relationships should be represented5Object behavior must be modeled6Tasks 1 through 5 are reapplied iteratively until the model is complete

Elements of the analysis model Analysis model leads to the derivation of each of the modeling elementsThe constructs of models as to showup certain critical features of a system while simultaneously de-emphasizing other aspects of the system

DATA MODELING CONCEPTSAnalysis modeling often begins with data modelingThe software engineer or analyst defines all data objects that are processed within the systemthe relationships between the data objects and other information relevant to the relationshipsTypes of element in Data Modeling Data ObjectsData AttributesRelationshipsCardinality and ModalityData Objects

Scenario-based elementsUse-cases-textUse-case-diagramActivity diagramsSwim lane diagrams

Flow-oriented elementsData flow diagramsControl-flow diagramsProcessing narratives

Class-based elementsClass diagramsAnalysis packagesCRC modelsCollaboration diagrams

Behavioral elementsState diagramsSequence diagrams

71

A data object is defines a composite information(data item) that is processed by software that is it incorporate(join together) collection of individual data items(attributes) and gives the collection of the name of the data object

Therefore ldquowidthrdquo is a single value would not be a valid data objectbut dimension (heightwidth and depth) could defined as an object

It encapsulate data only therefore the data object can be represented as a tablethe heading (column name)in the table is attributes of the object Example object is a car defined in terms of model ID numbeBody typecolor and ownerThe body of the table represents specific instance of the data object ie BMW is an instance of the data object car

Tabular representation of data objects

Data AttributesData attributes define the properties of a data object It follows one of three different characteristics

1)name an instance of the data object2) describe the instance 3)make reference to another instance in antoher table

The attribute as an identifier use as key to find an instance of the data objectvalues for identifiers are unique make reference to the data object

RelationshipsRelationships indicate in which data objects are connected to one another

Relationships between data objectsThe relationships owns and insured to drive define the relevant connections between person and car

Naming attributes descriptive Referential Identifier attributes attributesMake Model ID Body type Color Owner

Ford Tourus Q12A45 hellip Sedon Blue BLFBMW 750il XZ765hellip coupe white IJL

Instance

person car

72

The arrown provide information about the directionality of the relationships and reduce ambiguity or misinterpertations

Cardinality and ModalityThe data model must be capable of representing the number of occurrences of objects in a given relationships

Tillmann define the cardinality of an object or relationship pair in the following manner

Cardinality is the specification of the number of occurrences of one object that can be related to the number of occurrences of another object

Types of Cardinality11 relationship ndashone object can relate to only one other object1N relationship- one object can relate to many objectsMN relationship- some number of occurrences of an object can relate to some other nuber of occurrences of another object

It also defines ldquothe maximum number of objects that can participate in a relationshiprdquo ModalityData model does not yet provide an indication of whether or not a particular data object must participate in the relationshipto specify information the data model adds modality to the object

The modality of relationship is 0 if there is no explicit(direct) need for the relstionship to occur or the relationship is optional

The modality of relationship is 1 if an occurrence of the relationship is mandatory

SCENARIO-BASED MODELINGThe success of a computer-based system or product is measured in many waysuser satisfaction resides(be located) at the top of the list

If software engineers understand how end-users and other actor want to interact with a systemthe software team will be able to properly characterize requirements and build analysis and design models

Therefore analysis modeling with UML begins with the creation of scenarios in the form of Use-casesactivity diagrams and swimlane diagrams

Writing Use- cases A use-case are part of analysis modeling for user interfaces the interaction that occur between producers and consumers of information and the system

The concept of a use-case is easy to understand describe a specific usage scenario in straightforward language from the point of view of a defined actor not only specific person but the actor is device also The following questions that must be answered if use-cases are to provide value as an analysis modeling tool1what to write about

73

2how much to write about it3how detailed to make our description4how to organize the description What to write about itThe first tasks inception and elicitation provide us the information need to begin writing use-cases Requirements gathering meetingsQuality function deployment(QDF)and other reqirement engineering used to identify stakeholdersdefine the scope of the problemspecify overall operational goalsoutline all known functional requirements and describe the objects that will be manipulated by the system

To begin developing a set of use-cases The functions or activites performed by a specific actor are listed These may be obtained from a list of required system functionsthrough conversations with customers or end-users An evaluation of activity diagram developed as part of analysis modeling(requirement modeling) Example The SafeHome home surveillance function(subsystem) discussed in the sidebar identifies the following functions (an abbreviated list) that are performed by the homeowner actor Access camera surveillance via the internet Select camera to view Request thumbnails from all cameras Display camera views in aPc window Control pan and zoom for a specific camera Selectivel y record camera output Replay camera outputThe requirement gathering team develops use-case for each of the functionsFirst use-cases are written in an informal narrative formIf formal writte is requiredthe same use-case is rewritten using a structured format similar to proposed and later reproduced as a sidebarPreliminary use-case diagramWhen scenario is complex diagrammatic representation easy to understanding UML provide use-case diagramming capabilityPreliminary use-case diagram for the (eg)Safehome product each use-case is represented by a oval

Developing an Activity Diagram

74

The UML diagram supplements the use-case by providing a graphical representation of the flow of interaction within a specific scenarioIt is similar to flow chartan activity diagram notation(symbol)

-rounded rectangles to imply a specific system function -arrows to represent flow through the system -decision diamonds to indicate a branching decision -solid horizontal line to indicate that parallel activities are occurring

An activity diagram for the ACS_DCV function( access surveillance ndashdisplay camera view function)

The activity diagram adds additional detail not directly mentioned by the use-caseFor example a user may only attempt to enter userID and password a limited number of timesthis is represented by a decision dicmond below prompt for reentry

Swimlane DiagramsThe UML swimlane diagram is a variation of the activity diagram and allows the modeler to represent the flow of activities by the use-case

75

And at the same time indicate suppose if there multiple actors involved in a specific function in which actor or analysis class has responsibility for the action described by an activity rectangle

Responsibilities are represented as parallel segments that divide the diagram vertically like the lanes in a swimmingpool A UML swimlane diagram for access surveillance ndashdisplay camera view function

The activity diagram is rearranged that activities associated with a particular analysis class inside the swimlane for the classExample The Interface class represents the user interface as seen by the homeownerThe responsibility of the interface is two prompt prompt for reentry and prompt for another view

76

These prompts and the dscision associated with them fall within the Interrface swimlane but arrows from that swimlane back to the Homeowner swimlane where homeowner actions occur

FLOW-ORIENTED MODELING Data flow-oriented modeling is one of the most used analysis notations is a core modeling activity in structured analysis

Elements of flow-oriented modelingCreating a Data flow modelProcessing narratives Creating a Control flow model The Control SpecificationThe Process SpecificationCreating a Data Flow Model

The data flow diagram enables the software engineer at the same time to develop models of the information domain and functional domain

DFD is refined into greater level of detailthe analyst performs an implicit (indirect) functional decomposition of the system

DFD refinement result corresponding refinement data implied in through process in the application

DFD takes an input ndashprocess-output view of a system that is data objects flow into the software are transformed by processing selements and resultant data objects flow out of the software

Data objects represented by labeled arrow and transformations are represented by circles also called bubbles

DFD is presented in hierarchical manner The first data flow model called a level 0 DFD or context diagram represent the

system as a wholeSubsequent data flow diagram providing increase detail with each subsequent level refine context diagram

The guidelines can aid immeasurably during derivation of a DFD 1The level 0 data flow diagram should describe the softwaresystem as a single bubble2primary input and output should be carefully noted3refinement should begin by isolating candidate processesdata objects and data stores to be represented at the next level4all arrows and bubbles should be labeled with meaning ful names5information flow continuity must be maintained from level to level6one bubble at a time should be refined

Context level DFD (level 0 DFD)The primary external entities (boxes) produce information for use by the system and consume information generated by the systemThe labeled arrows represent data objects or in hierarchiesExample Context ndashlevel(level 0) DFD for the security Safe home function

77

User command and data encompasses all configuration commandsall activationdeactivation commands all miscellaneous interactions and all data that are entered to expand a commandProcessing narrative

It is similar to the use-case in style but different in purpose it provides an overall description of the function to be developed It is not a scenario written from one actorrsquos point of view

The level 0 DFD expanded into a level 1 data flow model to proceed A simple even so effective approach is to perform a ldquogrammatical parserdquo on the processing narrative

that describes the context level bubbleThe following processing narrative text with the first occurance of all nouns underlined and the first occurrence of all verbs italicizedExample Safehome processing narrativeThe Safehome security function enables the homeowner to configure the security system when it is installedmonitors all sensors connected to the security and interacts with the homeowner through the Internet a PC or a control panel

Level 1 DFD for Safehome processesReferring to the grammatical parse verbs are represented as bubbles in a subsequent DFDNouns are either external entities (boxes)data or control objects (arrows) or data stored(double lines) that nouns and verbs can be associsated with one anotherFor example each sensor is assigned a number and type are attributes of the data object sensorTherefore by performing a grammatical parse on the processing narrative for a bubble at any DFD level

78

Level 2 DFD The processes represented at DFD level 1 can be further refined into lower levelsThe information flow continuity has been mainted between levels 0 and 1ExampleThe process monitor sensors can be refined into a level 2 DFD

The refinement of DFDs continues until each bubble performs a simple function that would be easily implemented as a program component

Creating A Control Flow Model

79

Control flow modeling used for a large class of applications are ldquodrivenrdquo by events rather than data produce control information rather than reports or displays and process information with heavy concern for time and performance

Already noted that an event or control item is implemented as a Boolean value ie true or false1 or 0 or a discrete list of conditions

The following guidelines to select potential(possible) candidate events-

o List all sensors that are ldquoreadrdquo by the softwareo List all interrupt conditionso List all ldquoswitches ldquothat are actuated by an operatoro List all data conditionso Recalling the nounverb parse that was applied to the processing narrativereview

all ldquocontrol itemsrdquo as possible for control flow inputsoutputso Describe the behavior of a system by identifying its statesidentify how each state

is reached and define the transitions between stateso Focus on possible omissions a very common error in specifying controlfor

example ask ldquoIs there any other way I can get this state or exit from itrdquoThe Control SpecificationThe control specification (CSPEC) represents the behavior of the system in two different ways 1 State diagram 2 Program activationState diagramIt is a sequential specification of behaviorProgram activationIt also contain a program activation table is a combinatorial specification of behavior

The CSPEC describes the behavior of the system but it gives us no information about the inner working of the process that are activated as aresult of this behaviorExampleThe state diagram indicates that the transitions from the idle state can occurTwo transitions occur out of the Monitoring system status state(1)when the system is deactivated a transition occurs back to the idle state(2) when a sensor is triggered a transition to the Acting Alarm state occurs During the review consider all transition and the content of all states

The Process Specification The process specification (PSPEC) is used to describe all flow model processes that

appear at the final level of refinement The content of the process specification can include narrative texta program design

language(PDL) description of the algorithmmathematical equations tablesdiagrams or charts

The PSPEC is a lsquomini specificationrdquofor each transform at the lowest refined level of a DFD that as a guide for design of the software component that will implement the process

Example The password transform represented in the flow model for Safehome the function is perform by PSPEC

80

If the password matches an entry within the table [valid id message=true] is passed to the message and status display functionIf there is no matah [valid id message=false]is passed to the message and status display function

CLASS-BASED MODELING Class-based element of an analysis modelClasses and objectsAttributesOperationsPackagesCRC modelsCollaborations diagram

Identifying Analysis ClassesTo identify classes by examining the pbolem statement or by performing a

ldquogrammatical parserdquo the use-cases or processing narratives developed for the system to be built Classes are determined by underlinining each noun or noun clause and enter it into a simple tableIf the class is required to implement a solution then it is part of the solution space other wise if a class is necessary only to describe a solution it is part of the problem space

The following ways are for Analysis classes to manifest (marked) themselves External entities that produce or consume information to be used by a computer-based

system (eg) devicespeople Things that are part of the information domain for the problem(eg) reports displays

leeterssignals Occurrences or events that occur within the context of system operation(eg)

aproperty transfer or the completion of a series of robot movements Roles played by who interact with the system(eg) manager engineersalesperson Organizational units that are relevant to an application(eg)division groupteam Places that establish the context of the problem and the overall function of the system

(eg) manufacturing floor ) Structures that define a class of objects or related classes of objects (eg)

sensors four-wheeled vehicles or computerBudd suggests taxonomy (classification) of classes that includes producers(sources0 and consumers(sinks) of datadata managerview and helper classes

A class should never have an ldquoimperative procedural namerdquo(eg) an object with the name Imageinersion would making mistake so that inversion of the image the inversion() is an operation that applied to the class image During early stage of modeling analysis class might be defined to the example of Safehome security function performed in a ldquogrammatical parserdquo on a processing narrativeExtracting the nouns each entry in the list a potential object

Coad and Yourdon suggest six selection characteristics that should be used as an analyst considers each potential class for inclusion in the analysis model

1Retained informationThe potential class will be useful during analysis only if information about it must be remembered so that the system can function

81

2Needed servicesThe potential class must have a set of identifiable operations that can change the value of its attributes in some way3Multiple attributesDuring requirement analysis the focus should be on ldquomajor ldquo information a class with a single attribute be useful during design but better to represent ed as an attribute of another class during the analysis activity4Common attributesA set of attributes can be defined for the potential class and these attributes apply to all instances of the class5Common operationsA set of operation can be defined for the potential class and these operations apply to all instances of the class6Essential requirements External entities that appear in the problem space and produce and consume information important to the operation of any solution for the system will almost always be defined as classes in the requirements modelSpecifying AttributesAttributes are the set of data objects that fully define the class within the context of the problemExample

SystemsystemIDverificationPhonenubersystemStatusdelaytimemasterpasswordprogram()display()reset()query()modify()

The shade portion is list of attributes for the system classDefining OperationsIt define the behavior of an object The types of operations are divided into three categories (1)operations that manipulate data egadingdeletingreformattingselecting (2)operations that perform a computation (3)operations that inquire about the state of an object (4)operations that monitor an object for the occurance of a controlling eventThese functions are accomplished by operating on attributes and associationsExample Safehome processing narrative the phrases indicate that a program() operation is encapsulated by the System classClass-Responsibility-Collaborator(CRC) ModelingClass-responsibility-collaborator modeling provides simple means for identifying and organizing the classes that are relevant to system or product requirementsAmbler describes CRC modeling in the following way A CRC model is a collection of standard index cards that represent classesThe cards are divided into three sectionsDESIGN WITHIN THE CONTEXT OF SOFTWARE ENGINEERING

Design Principle1Design should be traceable to the analysis model

82

2Always consider the architecture of the system to be built3Design of data is as important as design of processing functions4Interfaces both internal and external must be designed with care5User interface design should be tuned to the needs of the end-users6Component ndashlevel design should be functionally independent7Components should be loosely coupled to one another and to the environment8Design representation(models) should be easily understandable9The design should be developed iterativelyWith each iteration the designer should stive for greater simplicity

DESIGN PROCESS AND DESIGN QUALITYDesign process

bull Design process is a sequence of steps carried through which the requirements are translated into a system or software model bull Any design may be modeled as a direct graph The graphs are collection of entities with attributes which participate in relationships bull The system should be described at several different levels of abstraction bull Design takes place in overlapping stages bull Various phases of design process are as shown in following

1 In architectural design the subsystem components can be identified2 The abstract specification is used to specify the subsystems3 The interfaces between the subsystems are designed which is called inter face design4 In component design of subsystems components is done5 The data structure is designed to hold the data6 For perfoming the required functionality the appropriate algorithm is de

signed

Software design is an iterative process through which requirements are translated into a design for constructing the software

The design is represented at a high level of abstractiona level that can be directly traced to the specific system objective and more detailed datafunctional and behavioral requirements As design iteraton occur subsequent refinement to design representation at lower levels of abstraction

McGlaughin suggests three characteristics that serve as a guide for the evaluation of a good design Each of these characteristics is a goal of the design process

The design must implement all of the explicit requirements contained in the analysis model and it must accommodate all of the implicit(indirect) requirements desired by the customer

The design must be a readable understandable guide for those who generate code and for those who test and subsequently support the software

The design should provide a complete picture of the software addressing the data functional and behavioral domains from an implementation perspective

83

Quality guidelinesThe following gidelines to evaluate the quality of a design representation

1A design should display an architecture that (a) That has been created using recognizable architectural styles or patterns

(b)That is composed of components that show good design characteristics (c)That can be implemented in an evolutionary style thereby implementing and testing2A design should be modular that is the software should be logically partitioned into elements or subsystems3A design should contain distinct representation of dataarchitectureinterfaces and components4A design should lead to data structures that are appropriate for the classes to be implemented and are drawn from recognizable data patterns5A design should lead to components that show independent functional characteristics6A design should lead to interfaces that reduce the complexity of connections between components and with the external environmemt7A design should be derived using a repeatable method that is driven by information obtained during software requirements analysis8A design should be represented using a notation that effectively communicates its meaning

Quality attributesHewlett Packard deveopled a set of software quality attributes are given as acronym(short form) FURPS to represent a target(goal) for all software design

Functionality Usability Reliability Performance Supportability

FunctionalityIt is assessed by evaluating the feature set and capabilities of the programthe generalization of the functions that are deliveredand the security of the overall systemUsabilityIt is assessed by human factors consistency and documentationReliabilityIt is evaluated by measuring the frequency and severity of failurethe accuracy of output resultsthe mean-time-to-failure(MTTF) the ability to recover from failure and predictability(unavoidability) of the programPerformanceIt is measured by processing speedresponse timeresource consumption throughput and efficiencySupportabilityItcombin the abilitytoxtendtheprogram(extensibility)adaptabilityServiceabilitymainabilitytestabilitycompatibilityconfigurability the ability to organize and control elements of the software congfiguration

Design Principles Davis suggested a set of principles for software design as

bull The design process should not suffer from ldquotunnel visionrdquobull The design should be traceable to the analysis modelbull The design should not reinvent the wheel

84

bull The design should ldquominimize the intellectual distancerdquo between the software and the problem in the real worldbull The design should exhibit uniformity and integrationbull The design should be structured to degrade gentlybull Design is not coding and coding is not designbull The design should be assessed for qualitybull The design should be reviewed to minimize conceptual errors

Design Concept

The software design concept provides a framework for implementing the right software

Following issues are considered while designing the software1Abstraction At each stage of software design process levels of abstractions should be applied to refine the software solutionAt the higher level of abstraction the solution should be stated in broad terms and in the lower level more detailed description of the solution is given While moving through different levels of abstraction the procedural abstraction and data abstraction is created In procedural abstraction it gives the named sequence of instruction in the specific function In data abstracion the collection of data objects is represented Levels of Abstraction Various levels of abstractions are- Level I - This level represents the solution interms of problem environment Level II - This level represents the decomposition of terms that are moved from problem environment but still not at implementation stage Level III - At this level preliminary procedural representation exists All the terminologies at this level are software oriented and implementation modularity begins at the surface Level IV and V - The concepts of stepwise refinement and modularity are

applied at this level2 Modularity

The software is divided into separately named and addressable components that called as modules Creating such models bring the modularity in siftwareMeyer defines five criteria that enable us to evaluate a design method with respect to its ability to define an effective modular systemModular decomposability A design method provides a systematic mechanism for decomposing the problem into sub-problems This reduces the complexity of the problem and the modularity can be achievedModular composability A design method enables existing design components to be assembled into a new systemModular understandability A module can be understood as a standalone unit Then it will be easier to build and easier to changeModular continuity Small changes to the system requirements result in changes to individual modules rather than system- wide changesModular protection An aberrant condition occurs within a module and its effects are constrained within the module3Refinement

Refinement is actually a process of elaborationStepwise refinement is a top-down design strategy proposed by Niklaus WIRTHThe architecture of a program is developed by successively refining levels of procedural detail

85

The process of program refinement is analogues to the process of refinement and partitioning that is used during requirements analysisAbstraction and refinement are complementary concepts The major difference is that - in the abstraction low-level details are suppressedRefinement helps the designer to elaborate low-levels detailsModular Design

Modular design reduces complexity and helps in easier implementation The parallel development of different parts of the system is possible due to modular designWhat is the benefit of modular design Changes made during testing and maintenance becomes manageable and they do not affect other modules Various quality parameters for effective modular design are -1) Functional independance 2) Cohesion 3) Coupling

Functional IndependenceThe functional independence can be achieved be developing the functional modules

with single-minded approachBy using functional independence functions may be compartmentalized and interfaces are simplifiedVarious types of coupling are i) Data coupling - The data coupling is possible by parameter passing or data interactionii) Control coupling - The modules share related control data in control couplingiii) Commom coupling - Content coupling occurs when one module makes use of data or control information maintained in another moduleFan-out Fan-out is a measure of the number of immediate subordinates to a moule The fan-out should be within some limit in the design If fan-out is very high then it indicates that a single module is controlling many other modules Preferably limit fan-out to no more than sevenFan-in

Fan-in indicates how many modules directly control a given module Modules with fan-in must have good cohesion Each interfac to the module must have the same number and types of parametersFactoring

Factoring means separation of function into new modules By applying factoring the size of module is reduced and thereby the complexity of the problem is reduced This also provides duplication of functions in more than one module The effective factoring brings simplification in the implementation of software design DESIGN HEURISTICS

The program structure can be manipulated according the design heuristics as shon below1Evaluate the first iteration of the program structure to reduce the coupling and improve cohesion The module independency can be achieved in the program structure by exploding or imploding the modules Exploding the modules means obtaining two or more modules in the final stage and imploding the modules means combining the result of different modules2Attempt to minimize the structure with high fan-out and strive for fan-in as depth increase At the higher level of program structure the distribution of control should be made Fan-out means number of immediate subordinates to the module Fan-in means number of immediate ancestores the module have

86

3Keep scope of the effect of a module within the scope of control of that module The decisions made in particular module lsquoarsquo should not affect the module rsquo brsquo which lies outside the scope of module lsquoarsquo4Evaluate the module interfaces to reduce complexity and redundancy and improve consistency Mostly the cause of softwatr errors is module interfaces The module interfaces should simply pass the information and should be consistent with the module5Define module whose function is predicatable but avoid modules that are too restrictive The module should be designed with simplified internal processing so that expected data can be produced as a result The modules should not restrict the size of local data structure options with control flow or modes of external interfaces Being module too much restrictive causes large maintenance6Strive for controlled entry modules by avoiding pathological connections Software interfaces should be constrained and controlled so that it will become manageable Pathological connection means many references or branches into the middle of a module

Design ModelThe design model is represented as pyramid The pyramid is a stable object

Representing design model in this way means that the software design should be stableThe design model has braod foundation of data design stable mid-region with architectural and interface design and the sharp point to for component level design

Advantages of horizontal partition1These are easy to test maintain and extend 2They have fewer side effects in change propagation or error propagation

Disadvantages of horizontal partitionMore data has to be passed across module interfaces which complicates the overall

control of program flowVertical partitioning

Vertical partitioning suggests the control and work should be distributed top-down in program structureIn vertical partitioning

Define separate branches of the module hierarchy for each major functionUse control modules to co-ordinate communication between functions

Advantages of vertical partition1These are easy to maintain the changes2 They reduce the change impact and error propagation

DATA DESIGNData design is basically the model of data that is represented at the high level of abstractionThe data design is then progressively refined to create implementation specific representationsVarious elements of data design are

Data object - The data objects are identified and relationship among various data objects can be represented using entity relationship diagrams or data dictionariesDatabases - Using software design model the data models are translated into data structures and databases at the application level

87

Data warehouses - At the business level useful information is identified from various databases and the data warehouses are created For extracting or navigating the useful business information stored in the huge data warehouse then data mining techniques are applied

ARCHITECTURAL DESIGNSoftware architecture The design process for identifying the sub-systems making up a system and the framework for sub-system control and communication is architectural design The output of this design process is a description of the software architecture

Architectural design An early stage of the system design process Represents the link between specification and design processes Often carried out in parallel with some specification activities It involves identifying major system components and their communicationsArchitecture and system characteristics Performancebull Localise critical operations and minimise communications Use large rather than fine-grain components Securitybull Use a layered architecture with critical assets in the inner layers Safetybull Localise safety-critical features in a small number of sub-systems Availabilitybull Include redundant components and mechanisms for fault tolerance Maintainabilitybull Use fine-grain replaceable components

Architectural design decisions Is there a generic application architecture that can be used How will the system be distributed What architectural styles are appropriate What approach will be used to structure the system How will the system be decomposed into modules What control strategy should be used How will the architectural design be evaluated How should the architecture be documentedArchitectural styles The architectural model of a system may conform to a generic architectural model or style An awareness of these styles can simplify the problem of defining system architectures However most large systems are heterogeneous and do not follow a single architectural styleArchitectural models

Used to document an architectural design Static structural model that shows the major system components Dynamic process model that shows the process structure of the system Interface model that defines sub-system interfaces

88

Relationships model such as a data-flow model that shows sub-system relationships Distribution model that shows how sub-systems are distributed across computers

Modular decomposition Another structural level where sub-systems are decomposed into modules Two modular decomposition models coveredbull An object model where the system is decomposed into interacting objectbull A pipeline or data-flow model where the system is decomposed into functional modules which transform inputs to outputs If possible decisions about concurrency should be delayed until modules are implemented

Object models Structure the system into a set of loosely coupled objects with well-defined interfaces Object-oriented decomposition is concerned with identifying object classes their attributes and operations When implemented objects are created from these classes and some control model used to coordinate object operations

Invoice Processing system

Pipeline model advantages Supports transformation reuse Intuitive organisation for stakeholder communication Easy to add new transformations Relatively simple to implement as either a concurrent or sequential system However requires a common format for data transfer along the pipeline and difficult

to support event-based interaction

User interface design

The user interface User interfaces should be designed to match the skills experience and expectations of

its anticipated users System users often judge a system by its interface rather than its functionality A poorly designed interface can cause a user to make catastrophic errors Poor user interface design is the reason why so many software systems are never

usedUser interface Design Principle

89

Design principles User familiaritybull The interface should be based on user-oriented terms and concepts rather than computer concepts For example an office system should use concepts such as letters documents folders etc rather than directories file identifiers etc Consistencybull The system should display an appropriate level of consistency Commands and menus should have the same format command punctuation should be similar etc Minimal surprisebull If a command operates in a known way the user should be able to predict the operation of comparable commandsbull Recoverabilitybull The system should provide some resilience to user errors and allow the user to recover from errors This might include an undo facility confirmation of destructive actions soft deletes etcbull User guidancebull Some user guidance such as help systems on-line manuals etc should be suppliedbull User diversitybull Interaction facilities for different types of user should be supported For example some users have seeing difficulties and so larger text should be available

REAL-TIME SOFTWARE DESIGNReal-time systemsSystems which monitor and control their environmentInevitably associated with hardware devices

bull Sensors Collect data from the system environmentbull Actuators Change (in some way) the systems environment

Time is critical Real-time systems must respond within specified times

Definition A real-time system is a software system where the correct functioning of the

system depends on the results produced by the system and the time at which these results are produced

90

A soft real-time system is a system whose operation is degraded if results are not produced according to the specified timing requirements

A hard real-time system is a system whose operation is incorrect if results are not produced according to the timing specification

StimulusResponse Systems Given a stimulus the system must produce a response within a specified timePeriodic stimuli Stimuli which occur at predictable time intervals

bull For example a temperature sensor may be polled 10 times per secondAperiodic stimuli Stimuli which occur at unpredictable times

bull For example a system power failure may trigger an interrupt which must be processed by the system

Architectural considerations Because of the need to respond to timing demands made by different

stimuliresponses the system architecture must allow for fast switching between stimulus handlers

Timing demands of different stimuli are different so a simple sequential loop is not usually adequate

Real-time systems are therefore usually designed as cooperating processes with a real-time executive controlling these processes

A real-time system model

Real-timecontrol system

ActuatorActuator ActuatorActuator

SensorSensorSensor SensorSensorSensor

Sensoractuator processes

Dataprocessor

Actuatorcontrol

Actuator

Sensorcontrol

Sensor

Stimulus Response

System elementsSensor control processes

bull Collect information from sensors May buffer information collected in response to a sensor stimulus

Data processorbull Carries out processing of collected information and computes the system

responseActuator control processes

91

bull Generates control signals for the actuatorsReal-time programmingHard-real time systems may have to programmed in assembly language to ensure that deadlines are metLanguages such as C allow efficient programs to be written but do not have constructs to support concurrency or shared resource management

Java as a real-time languageJava supports lightweight concurrency (threads and synchronized methods) and can be used for some soft real-time systemsJava 20 is not suitable for hard RT programming but real-time versions of Java are now available that address problems such as

bull Not possible to specify thread execution timebull Different timing in different virtual machinesbull Uncontrollable garbage collectionbull Not possible to discover queue sizes for shared resourcesbull Not possible to access system hardwarebull Not possible to do space or timing analysis

SYSTEM DESIGN Design both the hardware and the software associated with system

Partition functions to either hardware or software Design decisions should be made on the basis on non-functional

system requirements Hardware delivers better performance but potentially longer

development and less scope for changeR-T systems design process

Identify the stimuli to be processed and the required responses to these stimuli For each stimulus and response identify the timing constraints Aggregate the stimulus and response processing into concurrent processes A

process may be associated with each class of stimulus and response Design algorithms to process each class of stimulus and response These must

meet the given timing requirements Design a scheduling system which will ensure that processes are started in time to

meet their deadlines Integrate using a real-time operating system

Timing constraints May require extensive simulation and experiment to ensure that these are met by the systemMay mean that certain design strategies such as object-oriented design cannot be used because of the additional overhead involvedMay mean that low-level programming language features have to be used for performance reasons

Real-time system modellingThe effect of a stimulus in a real-time system may trigger a transition from one state to anotherFinite state machines can be used for modelling real-time systems

92

However FSM models lack structure Even simple systems can have a complex modelThe UML includes notations for defining state machine models

Petrol pump state model

Cardinserted

into reader

Timeout

Resettingdo display CC

error

Initialising

do initialisedisplay

Paying

Stopped

Reading

do get CCdetails

Waiting

do display welcome

dodeliver fuel

do debitCC account

Payment ack

Ready Delivering

update displayNozzle

trigger on

Nozzle trigger off

Nozzle trigger on

Hose inholster

do validatecredit card

Validating

Invalid card

Card removedCard OK

Hose out of holster

Timeout

Real-time operating systems(RTOS)

Real-time operating systems are specialised operating systems which manage the processes in the RTS

Responsible for process management and resource (processor and memory) allocation

May be based on a standard kernel which is used unchanged or modified for a particular application

Do not normally include facilities such as file management

Operating system componentsReal-time clock

bull Provides information for process schedulingInterrupt handler

bull Manages aperiodic requests for serviceScheduler

bull Chooses the next process to be runResource manager

bull Allocates memory and processor resourcesDispatcher

bull Starts process executionNon-stop system components

Configuration manager

93

bull Responsible for the dynamic reconfiguration of the system software and hardware Hardware modules may be replaced and software upgraded without stopping the systems

Fault managerbull Responsible for detecting software and hardware faults and taking appropriate

actions (eg switching to backup disks) to ensure that the system continues in operation

Real-time OS components

Process resourcerequirements

Scheduler

Schedulinginformation

Resourcemanager

Despatcher

Real-timeclock

Processesawaiting

resources

Readylist

Interrupthandler

Availableresource

list

Processorlist

Executing process

Readyprocesses

Releasedresources

Process priority The processing of some types of stimuli must sometimes take priority Interrupt level priority Highest priority which is allocated to processes requiring a

very fast response Clock level priority Allocated to periodic processes Within these further levels of priority may be assigned

Interrupt servicing Control is transferred automatically to a pre-determined memory location This location contains an instruction to jump to

an interrupt service routine Further interrupts are disabled the interrupt

serviced and control returned to the interrupted process

Interrupt service routines must be short simple and fast

Periodic process servicing In most real-time systems there will be several classes of periodic process each with

different periods (the time between executions) execution times and deadlines (the time by which processing must be completed)

The real-time clock ticks periodically and each tick causes an interrupt which schedules the process manager for periodic processes

The process manager selects a process which is ready for execution

Process managementbull Concerned with managing the set of concurrent processes

94

bull Periodic processes are executed at pre-specified time intervalsbull The RTOS uses the real-time clock to determine when to execute a process

taking into accountbull Process period - time between executionsbull Process deadline - the time by which processing must be complete

RTE(Real Time Execution Process) process managementResource manager

Allocate memoryand processor

Scheduler

Choose processfor execution

Despatcher

Start execution on anavailable processor

Process switchingbull The scheduler chooses the next process to be executed by the processor This

depends on a scheduling strategy which may take the process priority into account

bull The resource manager allocates memory and a processor for the process to be executed

bull The dispatcher takes the process from ready list loads it onto a processor and starts execution

Scheduling strategiesNon pre-emptive scheduling

bull Once a process has been scheduled for execution it runs to completion or until it is blocked for some reason (eg waiting for IO)

Pre-emptive schedulingbull The execution of an executing processes may be stopped if a higher priority

process requires serviceScheduling algorithms

bull Round-robinbull Rate monotonicbull Shortest deadline first

Monitoring and control systemsbull Important class of real-time systems bull Continuously check sensors and take actions

depending on sensor valuesbull Monitoring systems examine sensors and

report their resultsbull Control systems take sensor values and control hardware actuators

Generic architecture

95

S1

S2

S3

P (S1)

P (S2)

P (S1)

Monitoringprocesses

Controlprocesses

P (A1)

P (A2)

P (A1)

A1

A2

A3

P (A4) A4

Testingprocess

Control panelprocesses

Burglar alarm systembull A system is required to monitor sensors on doors and windows to detect the

presence of intruders in a buildingbull When a sensor indicates a break-in the system switches on lights around the

area and calls police automaticallybull The system should include provision for operation without a mains power

supply Sensorso Movement detectors window sensors door sensorso 50 window sensors 30 door sensors and 200 movement detectorso Voltage drop sensor Actionso When an intruder is detected police are called automaticallyo Lights are switched on in rooms with active sensorso An audible alarm is switched on

The R-T system design process

bull Identify stimuli and associated responsesbull Define the timing constraints associated with each stimulus and responsebull Allocate system functions to concurrent processesbull Design algorithms for stimulus processing and response generationbull Design a scheduling system which ensures that processes will always be

scheduled to meet their deadlinesStimuli to be processed

Power failurebull Generated aperiodically by a circuit monitor When received the system must

switch to backup power within 50 msIntruder alarm

bull Stimulus generated by system sensors Response is to call the police switch on building lights and the Power failure

bull Generated aperiodically by a circuit monitor When received the system must switch to backup power within 50 ms

bull Intruder alarmbull Stimulus generated by system sensors Response is to call the police switch

on building lights and the audible alarmbull audible alarm

Burglar alarm system processes

96

Lighting controlprocess

Audible alarmprocess

Voice synthesiserprocess

Alarm systemprocess

Power switchprocess

Building monitorprocess

Communicationprocess

Door sensorprocess

Movementdetector process

Window sensorprocess

560 Hz

60 Hz400 Hz 100 Hz

Power failureinterrupt

Alarm system

Building monitor

Alarm system

Alarm system

Alarm system

Detector status Sensor status Sensor status

Room number

Alert message

Room number

Room number

Building_monitor process 1

class BuildingMonitor extends Thread

BuildingSensor win door move

Siren siren = new Siren () Lights lights = new Lights () Synthesizer synthesizer = new Synthesizer () DoorSensors doors = new DoorSensors (30) WindowSensors windows = new WindowSensors (50) MovementSensors movements = new MovementSensors (200) PowerMonitor pm = new PowerMonitor ()

BuildingMonitor() initialise all the sensors and start the processessirenstart () lightsstart () synthesizerstart () windowsstart () doorsstart () movementsstart () pmstart ()

Building monitor process 2public void run () int room = 0 while (true) poll the movement sensors at least twice per second (400 Hz)move = movementsgetVal () poll the window sensors at least twicesecond (100 Hz)win = windowsgetVal () poll the door sensors at least twice per second (60 Hz)door = doorsgetVal ()

97

if (movesensorVal == 1 | doorsensorVal == 1 | winsensorVal == 1) a sensor has indicated an intruder if (movesensorVal == 1) room = moveroom if (doorsensorVal == 1) room = doorroom if (winsensorVal == 1 ) room = winroom lightson (room) sirenon () synthesizeron (room) break Building_monitor process 3 lightsshutdown () sirenshutdown () synthesizershutdown () windowsshutdown () doorsshutdown () movementsshutdown ()

run BuildingMonitor

Control systems

bull A burglar alarm system is primarily a monitoring system It collects data from sensors but no real-time actuator control

bull Control systems are similar but in response to sensor values the system sends control signals to actuators

bull An example of a monitoring and control system is a system that monitors temperature and switches heaters on and off

A temperature control system

Thermostatprocess

Sensorprocess

Furnacecontrol process

Heater controlprocess

500 Hz

500 Hz

Thermostat process500 Hz

Sensorvalues

Switch commandRoom number

DATA ACQUISITION SYSTEMSbull Collect data from sensors for subsequent processing and analysisbull Data collection processes and processing processes may have different periods

and deadlines bull Data collection may be faster than processing eg collecting information about

an explosion bull Circular or ring buffers are a mechanism for smoothing speed differences

The generic Architecture of data acquicition

98

DisplayProcess

dataSensor data

bufferSensorprocess

Sensoridentifier and

value

Sensors (each data flow is a sensor value)

Sensoridentifier and

value

Processdata

Sensor databuffer

Sensorprocess

Sensoridentifier and

value

Sensoridentifier and

value

s1

s2

s3

s4

s5

s6

In data acquisition systemsthe sensor may be generating data quickly and the key problem is to ensure that a sensor is allocated before sensor value changeThe essenitial features of this architecture is each group of sensors has three processes associated with it and convert analogue data to digital values if necessary a buffer process and a process that consumes the data carried out further processing Two groups sensors s1-s3 and s4-s6 on the right side a further procee that diplsys the sensor data Neutron flux data acquisition

Operatordisplay

Fluxprocessing

Flux databuffer

A-Dconvertor

Sensoridentifier and

flux valueProcessedflux level

Neutron flux sensors

bull A system collects data from a set of sensors monitoring the neutron flux from a nuclear reactor

bull Each sensor has a process that converts the analog input flux level into a digita signalIt passes this flux level with sensor identifies to the sensor data buffer the data processing takes the data from this bufferprocesses it and pass it to display process for output on an operator display

A ring buffer

Consumerprocess

Producerprocess

Mutual exclusionbull Producer processes collect data and add it to the buffer Consumer processes

take data from the buffer and make elements availablebull Producer and consumer processes must be mutually excluded from accessing

the same elementThe buffer must stop producer processes adding information to a full buffer and consumer processes trying to take information from an empty buffer

99

Page 3: Unit_III

The first approach of analysis modeling is structured analysiswhich that mapping data and processes that transfom the data as separate entities

o Data objects define their attribute and relationshipso Process manipulate the data object transform as data flow through the system

such as ERDDFDObject-Oriented analysis The Second approach of analysis modeling called object oriented analysis is to define

all classes and the relationships and behavior associated with them that are relevant to the problem to be solvedUML and Unified process are Object-Oriented

The following of tasks to accomplish the problem1Basic user requirements must be communicated between the customer and the software engineer2Classes must be identified ie defined attributes and methods3A class hierarchy is defined4Object ndash to-object relationships should be represented5Object behavior must be modeled6Tasks 1 through 5 are reapplied iteratively until the model is complete

Elements of the analysis model Analysis model leads to the derivation of each of the modeling elementsThe constructs of models as to showup certain critical features of a system while simultaneously de-emphasizing other aspects of the system

DATA MODELING CONCEPTSAnalysis modeling often begins with data modelingThe software engineer or analyst defines all data objects that are processed within the systemthe relationships between the data objects and other information relevant to the relationshipsTypes of element in Data Modeling Data ObjectsData AttributesRelationshipsCardinality and ModalityData Objects

Scenario-based elementsUse-cases-textUse-case-diagramActivity diagramsSwim lane diagrams

Flow-oriented elementsData flow diagramsControl-flow diagramsProcessing narratives

Class-based elementsClass diagramsAnalysis packagesCRC modelsCollaboration diagrams

Behavioral elementsState diagramsSequence diagrams

71

A data object is defines a composite information(data item) that is processed by software that is it incorporate(join together) collection of individual data items(attributes) and gives the collection of the name of the data object

Therefore ldquowidthrdquo is a single value would not be a valid data objectbut dimension (heightwidth and depth) could defined as an object

It encapsulate data only therefore the data object can be represented as a tablethe heading (column name)in the table is attributes of the object Example object is a car defined in terms of model ID numbeBody typecolor and ownerThe body of the table represents specific instance of the data object ie BMW is an instance of the data object car

Tabular representation of data objects

Data AttributesData attributes define the properties of a data object It follows one of three different characteristics

1)name an instance of the data object2) describe the instance 3)make reference to another instance in antoher table

The attribute as an identifier use as key to find an instance of the data objectvalues for identifiers are unique make reference to the data object

RelationshipsRelationships indicate in which data objects are connected to one another

Relationships between data objectsThe relationships owns and insured to drive define the relevant connections between person and car

Naming attributes descriptive Referential Identifier attributes attributesMake Model ID Body type Color Owner

Ford Tourus Q12A45 hellip Sedon Blue BLFBMW 750il XZ765hellip coupe white IJL

Instance

person car

72

The arrown provide information about the directionality of the relationships and reduce ambiguity or misinterpertations

Cardinality and ModalityThe data model must be capable of representing the number of occurrences of objects in a given relationships

Tillmann define the cardinality of an object or relationship pair in the following manner

Cardinality is the specification of the number of occurrences of one object that can be related to the number of occurrences of another object

Types of Cardinality11 relationship ndashone object can relate to only one other object1N relationship- one object can relate to many objectsMN relationship- some number of occurrences of an object can relate to some other nuber of occurrences of another object

It also defines ldquothe maximum number of objects that can participate in a relationshiprdquo ModalityData model does not yet provide an indication of whether or not a particular data object must participate in the relationshipto specify information the data model adds modality to the object

The modality of relationship is 0 if there is no explicit(direct) need for the relstionship to occur or the relationship is optional

The modality of relationship is 1 if an occurrence of the relationship is mandatory

SCENARIO-BASED MODELINGThe success of a computer-based system or product is measured in many waysuser satisfaction resides(be located) at the top of the list

If software engineers understand how end-users and other actor want to interact with a systemthe software team will be able to properly characterize requirements and build analysis and design models

Therefore analysis modeling with UML begins with the creation of scenarios in the form of Use-casesactivity diagrams and swimlane diagrams

Writing Use- cases A use-case are part of analysis modeling for user interfaces the interaction that occur between producers and consumers of information and the system

The concept of a use-case is easy to understand describe a specific usage scenario in straightforward language from the point of view of a defined actor not only specific person but the actor is device also The following questions that must be answered if use-cases are to provide value as an analysis modeling tool1what to write about

73

2how much to write about it3how detailed to make our description4how to organize the description What to write about itThe first tasks inception and elicitation provide us the information need to begin writing use-cases Requirements gathering meetingsQuality function deployment(QDF)and other reqirement engineering used to identify stakeholdersdefine the scope of the problemspecify overall operational goalsoutline all known functional requirements and describe the objects that will be manipulated by the system

To begin developing a set of use-cases The functions or activites performed by a specific actor are listed These may be obtained from a list of required system functionsthrough conversations with customers or end-users An evaluation of activity diagram developed as part of analysis modeling(requirement modeling) Example The SafeHome home surveillance function(subsystem) discussed in the sidebar identifies the following functions (an abbreviated list) that are performed by the homeowner actor Access camera surveillance via the internet Select camera to view Request thumbnails from all cameras Display camera views in aPc window Control pan and zoom for a specific camera Selectivel y record camera output Replay camera outputThe requirement gathering team develops use-case for each of the functionsFirst use-cases are written in an informal narrative formIf formal writte is requiredthe same use-case is rewritten using a structured format similar to proposed and later reproduced as a sidebarPreliminary use-case diagramWhen scenario is complex diagrammatic representation easy to understanding UML provide use-case diagramming capabilityPreliminary use-case diagram for the (eg)Safehome product each use-case is represented by a oval

Developing an Activity Diagram

74

The UML diagram supplements the use-case by providing a graphical representation of the flow of interaction within a specific scenarioIt is similar to flow chartan activity diagram notation(symbol)

-rounded rectangles to imply a specific system function -arrows to represent flow through the system -decision diamonds to indicate a branching decision -solid horizontal line to indicate that parallel activities are occurring

An activity diagram for the ACS_DCV function( access surveillance ndashdisplay camera view function)

The activity diagram adds additional detail not directly mentioned by the use-caseFor example a user may only attempt to enter userID and password a limited number of timesthis is represented by a decision dicmond below prompt for reentry

Swimlane DiagramsThe UML swimlane diagram is a variation of the activity diagram and allows the modeler to represent the flow of activities by the use-case

75

And at the same time indicate suppose if there multiple actors involved in a specific function in which actor or analysis class has responsibility for the action described by an activity rectangle

Responsibilities are represented as parallel segments that divide the diagram vertically like the lanes in a swimmingpool A UML swimlane diagram for access surveillance ndashdisplay camera view function

The activity diagram is rearranged that activities associated with a particular analysis class inside the swimlane for the classExample The Interface class represents the user interface as seen by the homeownerThe responsibility of the interface is two prompt prompt for reentry and prompt for another view

76

These prompts and the dscision associated with them fall within the Interrface swimlane but arrows from that swimlane back to the Homeowner swimlane where homeowner actions occur

FLOW-ORIENTED MODELING Data flow-oriented modeling is one of the most used analysis notations is a core modeling activity in structured analysis

Elements of flow-oriented modelingCreating a Data flow modelProcessing narratives Creating a Control flow model The Control SpecificationThe Process SpecificationCreating a Data Flow Model

The data flow diagram enables the software engineer at the same time to develop models of the information domain and functional domain

DFD is refined into greater level of detailthe analyst performs an implicit (indirect) functional decomposition of the system

DFD refinement result corresponding refinement data implied in through process in the application

DFD takes an input ndashprocess-output view of a system that is data objects flow into the software are transformed by processing selements and resultant data objects flow out of the software

Data objects represented by labeled arrow and transformations are represented by circles also called bubbles

DFD is presented in hierarchical manner The first data flow model called a level 0 DFD or context diagram represent the

system as a wholeSubsequent data flow diagram providing increase detail with each subsequent level refine context diagram

The guidelines can aid immeasurably during derivation of a DFD 1The level 0 data flow diagram should describe the softwaresystem as a single bubble2primary input and output should be carefully noted3refinement should begin by isolating candidate processesdata objects and data stores to be represented at the next level4all arrows and bubbles should be labeled with meaning ful names5information flow continuity must be maintained from level to level6one bubble at a time should be refined

Context level DFD (level 0 DFD)The primary external entities (boxes) produce information for use by the system and consume information generated by the systemThe labeled arrows represent data objects or in hierarchiesExample Context ndashlevel(level 0) DFD for the security Safe home function

77

User command and data encompasses all configuration commandsall activationdeactivation commands all miscellaneous interactions and all data that are entered to expand a commandProcessing narrative

It is similar to the use-case in style but different in purpose it provides an overall description of the function to be developed It is not a scenario written from one actorrsquos point of view

The level 0 DFD expanded into a level 1 data flow model to proceed A simple even so effective approach is to perform a ldquogrammatical parserdquo on the processing narrative

that describes the context level bubbleThe following processing narrative text with the first occurance of all nouns underlined and the first occurrence of all verbs italicizedExample Safehome processing narrativeThe Safehome security function enables the homeowner to configure the security system when it is installedmonitors all sensors connected to the security and interacts with the homeowner through the Internet a PC or a control panel

Level 1 DFD for Safehome processesReferring to the grammatical parse verbs are represented as bubbles in a subsequent DFDNouns are either external entities (boxes)data or control objects (arrows) or data stored(double lines) that nouns and verbs can be associsated with one anotherFor example each sensor is assigned a number and type are attributes of the data object sensorTherefore by performing a grammatical parse on the processing narrative for a bubble at any DFD level

78

Level 2 DFD The processes represented at DFD level 1 can be further refined into lower levelsThe information flow continuity has been mainted between levels 0 and 1ExampleThe process monitor sensors can be refined into a level 2 DFD

The refinement of DFDs continues until each bubble performs a simple function that would be easily implemented as a program component

Creating A Control Flow Model

79

Control flow modeling used for a large class of applications are ldquodrivenrdquo by events rather than data produce control information rather than reports or displays and process information with heavy concern for time and performance

Already noted that an event or control item is implemented as a Boolean value ie true or false1 or 0 or a discrete list of conditions

The following guidelines to select potential(possible) candidate events-

o List all sensors that are ldquoreadrdquo by the softwareo List all interrupt conditionso List all ldquoswitches ldquothat are actuated by an operatoro List all data conditionso Recalling the nounverb parse that was applied to the processing narrativereview

all ldquocontrol itemsrdquo as possible for control flow inputsoutputso Describe the behavior of a system by identifying its statesidentify how each state

is reached and define the transitions between stateso Focus on possible omissions a very common error in specifying controlfor

example ask ldquoIs there any other way I can get this state or exit from itrdquoThe Control SpecificationThe control specification (CSPEC) represents the behavior of the system in two different ways 1 State diagram 2 Program activationState diagramIt is a sequential specification of behaviorProgram activationIt also contain a program activation table is a combinatorial specification of behavior

The CSPEC describes the behavior of the system but it gives us no information about the inner working of the process that are activated as aresult of this behaviorExampleThe state diagram indicates that the transitions from the idle state can occurTwo transitions occur out of the Monitoring system status state(1)when the system is deactivated a transition occurs back to the idle state(2) when a sensor is triggered a transition to the Acting Alarm state occurs During the review consider all transition and the content of all states

The Process Specification The process specification (PSPEC) is used to describe all flow model processes that

appear at the final level of refinement The content of the process specification can include narrative texta program design

language(PDL) description of the algorithmmathematical equations tablesdiagrams or charts

The PSPEC is a lsquomini specificationrdquofor each transform at the lowest refined level of a DFD that as a guide for design of the software component that will implement the process

Example The password transform represented in the flow model for Safehome the function is perform by PSPEC

80

If the password matches an entry within the table [valid id message=true] is passed to the message and status display functionIf there is no matah [valid id message=false]is passed to the message and status display function

CLASS-BASED MODELING Class-based element of an analysis modelClasses and objectsAttributesOperationsPackagesCRC modelsCollaborations diagram

Identifying Analysis ClassesTo identify classes by examining the pbolem statement or by performing a

ldquogrammatical parserdquo the use-cases or processing narratives developed for the system to be built Classes are determined by underlinining each noun or noun clause and enter it into a simple tableIf the class is required to implement a solution then it is part of the solution space other wise if a class is necessary only to describe a solution it is part of the problem space

The following ways are for Analysis classes to manifest (marked) themselves External entities that produce or consume information to be used by a computer-based

system (eg) devicespeople Things that are part of the information domain for the problem(eg) reports displays

leeterssignals Occurrences or events that occur within the context of system operation(eg)

aproperty transfer or the completion of a series of robot movements Roles played by who interact with the system(eg) manager engineersalesperson Organizational units that are relevant to an application(eg)division groupteam Places that establish the context of the problem and the overall function of the system

(eg) manufacturing floor ) Structures that define a class of objects or related classes of objects (eg)

sensors four-wheeled vehicles or computerBudd suggests taxonomy (classification) of classes that includes producers(sources0 and consumers(sinks) of datadata managerview and helper classes

A class should never have an ldquoimperative procedural namerdquo(eg) an object with the name Imageinersion would making mistake so that inversion of the image the inversion() is an operation that applied to the class image During early stage of modeling analysis class might be defined to the example of Safehome security function performed in a ldquogrammatical parserdquo on a processing narrativeExtracting the nouns each entry in the list a potential object

Coad and Yourdon suggest six selection characteristics that should be used as an analyst considers each potential class for inclusion in the analysis model

1Retained informationThe potential class will be useful during analysis only if information about it must be remembered so that the system can function

81

2Needed servicesThe potential class must have a set of identifiable operations that can change the value of its attributes in some way3Multiple attributesDuring requirement analysis the focus should be on ldquomajor ldquo information a class with a single attribute be useful during design but better to represent ed as an attribute of another class during the analysis activity4Common attributesA set of attributes can be defined for the potential class and these attributes apply to all instances of the class5Common operationsA set of operation can be defined for the potential class and these operations apply to all instances of the class6Essential requirements External entities that appear in the problem space and produce and consume information important to the operation of any solution for the system will almost always be defined as classes in the requirements modelSpecifying AttributesAttributes are the set of data objects that fully define the class within the context of the problemExample

SystemsystemIDverificationPhonenubersystemStatusdelaytimemasterpasswordprogram()display()reset()query()modify()

The shade portion is list of attributes for the system classDefining OperationsIt define the behavior of an object The types of operations are divided into three categories (1)operations that manipulate data egadingdeletingreformattingselecting (2)operations that perform a computation (3)operations that inquire about the state of an object (4)operations that monitor an object for the occurance of a controlling eventThese functions are accomplished by operating on attributes and associationsExample Safehome processing narrative the phrases indicate that a program() operation is encapsulated by the System classClass-Responsibility-Collaborator(CRC) ModelingClass-responsibility-collaborator modeling provides simple means for identifying and organizing the classes that are relevant to system or product requirementsAmbler describes CRC modeling in the following way A CRC model is a collection of standard index cards that represent classesThe cards are divided into three sectionsDESIGN WITHIN THE CONTEXT OF SOFTWARE ENGINEERING

Design Principle1Design should be traceable to the analysis model

82

2Always consider the architecture of the system to be built3Design of data is as important as design of processing functions4Interfaces both internal and external must be designed with care5User interface design should be tuned to the needs of the end-users6Component ndashlevel design should be functionally independent7Components should be loosely coupled to one another and to the environment8Design representation(models) should be easily understandable9The design should be developed iterativelyWith each iteration the designer should stive for greater simplicity

DESIGN PROCESS AND DESIGN QUALITYDesign process

bull Design process is a sequence of steps carried through which the requirements are translated into a system or software model bull Any design may be modeled as a direct graph The graphs are collection of entities with attributes which participate in relationships bull The system should be described at several different levels of abstraction bull Design takes place in overlapping stages bull Various phases of design process are as shown in following

1 In architectural design the subsystem components can be identified2 The abstract specification is used to specify the subsystems3 The interfaces between the subsystems are designed which is called inter face design4 In component design of subsystems components is done5 The data structure is designed to hold the data6 For perfoming the required functionality the appropriate algorithm is de

signed

Software design is an iterative process through which requirements are translated into a design for constructing the software

The design is represented at a high level of abstractiona level that can be directly traced to the specific system objective and more detailed datafunctional and behavioral requirements As design iteraton occur subsequent refinement to design representation at lower levels of abstraction

McGlaughin suggests three characteristics that serve as a guide for the evaluation of a good design Each of these characteristics is a goal of the design process

The design must implement all of the explicit requirements contained in the analysis model and it must accommodate all of the implicit(indirect) requirements desired by the customer

The design must be a readable understandable guide for those who generate code and for those who test and subsequently support the software

The design should provide a complete picture of the software addressing the data functional and behavioral domains from an implementation perspective

83

Quality guidelinesThe following gidelines to evaluate the quality of a design representation

1A design should display an architecture that (a) That has been created using recognizable architectural styles or patterns

(b)That is composed of components that show good design characteristics (c)That can be implemented in an evolutionary style thereby implementing and testing2A design should be modular that is the software should be logically partitioned into elements or subsystems3A design should contain distinct representation of dataarchitectureinterfaces and components4A design should lead to data structures that are appropriate for the classes to be implemented and are drawn from recognizable data patterns5A design should lead to components that show independent functional characteristics6A design should lead to interfaces that reduce the complexity of connections between components and with the external environmemt7A design should be derived using a repeatable method that is driven by information obtained during software requirements analysis8A design should be represented using a notation that effectively communicates its meaning

Quality attributesHewlett Packard deveopled a set of software quality attributes are given as acronym(short form) FURPS to represent a target(goal) for all software design

Functionality Usability Reliability Performance Supportability

FunctionalityIt is assessed by evaluating the feature set and capabilities of the programthe generalization of the functions that are deliveredand the security of the overall systemUsabilityIt is assessed by human factors consistency and documentationReliabilityIt is evaluated by measuring the frequency and severity of failurethe accuracy of output resultsthe mean-time-to-failure(MTTF) the ability to recover from failure and predictability(unavoidability) of the programPerformanceIt is measured by processing speedresponse timeresource consumption throughput and efficiencySupportabilityItcombin the abilitytoxtendtheprogram(extensibility)adaptabilityServiceabilitymainabilitytestabilitycompatibilityconfigurability the ability to organize and control elements of the software congfiguration

Design Principles Davis suggested a set of principles for software design as

bull The design process should not suffer from ldquotunnel visionrdquobull The design should be traceable to the analysis modelbull The design should not reinvent the wheel

84

bull The design should ldquominimize the intellectual distancerdquo between the software and the problem in the real worldbull The design should exhibit uniformity and integrationbull The design should be structured to degrade gentlybull Design is not coding and coding is not designbull The design should be assessed for qualitybull The design should be reviewed to minimize conceptual errors

Design Concept

The software design concept provides a framework for implementing the right software

Following issues are considered while designing the software1Abstraction At each stage of software design process levels of abstractions should be applied to refine the software solutionAt the higher level of abstraction the solution should be stated in broad terms and in the lower level more detailed description of the solution is given While moving through different levels of abstraction the procedural abstraction and data abstraction is created In procedural abstraction it gives the named sequence of instruction in the specific function In data abstracion the collection of data objects is represented Levels of Abstraction Various levels of abstractions are- Level I - This level represents the solution interms of problem environment Level II - This level represents the decomposition of terms that are moved from problem environment but still not at implementation stage Level III - At this level preliminary procedural representation exists All the terminologies at this level are software oriented and implementation modularity begins at the surface Level IV and V - The concepts of stepwise refinement and modularity are

applied at this level2 Modularity

The software is divided into separately named and addressable components that called as modules Creating such models bring the modularity in siftwareMeyer defines five criteria that enable us to evaluate a design method with respect to its ability to define an effective modular systemModular decomposability A design method provides a systematic mechanism for decomposing the problem into sub-problems This reduces the complexity of the problem and the modularity can be achievedModular composability A design method enables existing design components to be assembled into a new systemModular understandability A module can be understood as a standalone unit Then it will be easier to build and easier to changeModular continuity Small changes to the system requirements result in changes to individual modules rather than system- wide changesModular protection An aberrant condition occurs within a module and its effects are constrained within the module3Refinement

Refinement is actually a process of elaborationStepwise refinement is a top-down design strategy proposed by Niklaus WIRTHThe architecture of a program is developed by successively refining levels of procedural detail

85

The process of program refinement is analogues to the process of refinement and partitioning that is used during requirements analysisAbstraction and refinement are complementary concepts The major difference is that - in the abstraction low-level details are suppressedRefinement helps the designer to elaborate low-levels detailsModular Design

Modular design reduces complexity and helps in easier implementation The parallel development of different parts of the system is possible due to modular designWhat is the benefit of modular design Changes made during testing and maintenance becomes manageable and they do not affect other modules Various quality parameters for effective modular design are -1) Functional independance 2) Cohesion 3) Coupling

Functional IndependenceThe functional independence can be achieved be developing the functional modules

with single-minded approachBy using functional independence functions may be compartmentalized and interfaces are simplifiedVarious types of coupling are i) Data coupling - The data coupling is possible by parameter passing or data interactionii) Control coupling - The modules share related control data in control couplingiii) Commom coupling - Content coupling occurs when one module makes use of data or control information maintained in another moduleFan-out Fan-out is a measure of the number of immediate subordinates to a moule The fan-out should be within some limit in the design If fan-out is very high then it indicates that a single module is controlling many other modules Preferably limit fan-out to no more than sevenFan-in

Fan-in indicates how many modules directly control a given module Modules with fan-in must have good cohesion Each interfac to the module must have the same number and types of parametersFactoring

Factoring means separation of function into new modules By applying factoring the size of module is reduced and thereby the complexity of the problem is reduced This also provides duplication of functions in more than one module The effective factoring brings simplification in the implementation of software design DESIGN HEURISTICS

The program structure can be manipulated according the design heuristics as shon below1Evaluate the first iteration of the program structure to reduce the coupling and improve cohesion The module independency can be achieved in the program structure by exploding or imploding the modules Exploding the modules means obtaining two or more modules in the final stage and imploding the modules means combining the result of different modules2Attempt to minimize the structure with high fan-out and strive for fan-in as depth increase At the higher level of program structure the distribution of control should be made Fan-out means number of immediate subordinates to the module Fan-in means number of immediate ancestores the module have

86

3Keep scope of the effect of a module within the scope of control of that module The decisions made in particular module lsquoarsquo should not affect the module rsquo brsquo which lies outside the scope of module lsquoarsquo4Evaluate the module interfaces to reduce complexity and redundancy and improve consistency Mostly the cause of softwatr errors is module interfaces The module interfaces should simply pass the information and should be consistent with the module5Define module whose function is predicatable but avoid modules that are too restrictive The module should be designed with simplified internal processing so that expected data can be produced as a result The modules should not restrict the size of local data structure options with control flow or modes of external interfaces Being module too much restrictive causes large maintenance6Strive for controlled entry modules by avoiding pathological connections Software interfaces should be constrained and controlled so that it will become manageable Pathological connection means many references or branches into the middle of a module

Design ModelThe design model is represented as pyramid The pyramid is a stable object

Representing design model in this way means that the software design should be stableThe design model has braod foundation of data design stable mid-region with architectural and interface design and the sharp point to for component level design

Advantages of horizontal partition1These are easy to test maintain and extend 2They have fewer side effects in change propagation or error propagation

Disadvantages of horizontal partitionMore data has to be passed across module interfaces which complicates the overall

control of program flowVertical partitioning

Vertical partitioning suggests the control and work should be distributed top-down in program structureIn vertical partitioning

Define separate branches of the module hierarchy for each major functionUse control modules to co-ordinate communication between functions

Advantages of vertical partition1These are easy to maintain the changes2 They reduce the change impact and error propagation

DATA DESIGNData design is basically the model of data that is represented at the high level of abstractionThe data design is then progressively refined to create implementation specific representationsVarious elements of data design are

Data object - The data objects are identified and relationship among various data objects can be represented using entity relationship diagrams or data dictionariesDatabases - Using software design model the data models are translated into data structures and databases at the application level

87

Data warehouses - At the business level useful information is identified from various databases and the data warehouses are created For extracting or navigating the useful business information stored in the huge data warehouse then data mining techniques are applied

ARCHITECTURAL DESIGNSoftware architecture The design process for identifying the sub-systems making up a system and the framework for sub-system control and communication is architectural design The output of this design process is a description of the software architecture

Architectural design An early stage of the system design process Represents the link between specification and design processes Often carried out in parallel with some specification activities It involves identifying major system components and their communicationsArchitecture and system characteristics Performancebull Localise critical operations and minimise communications Use large rather than fine-grain components Securitybull Use a layered architecture with critical assets in the inner layers Safetybull Localise safety-critical features in a small number of sub-systems Availabilitybull Include redundant components and mechanisms for fault tolerance Maintainabilitybull Use fine-grain replaceable components

Architectural design decisions Is there a generic application architecture that can be used How will the system be distributed What architectural styles are appropriate What approach will be used to structure the system How will the system be decomposed into modules What control strategy should be used How will the architectural design be evaluated How should the architecture be documentedArchitectural styles The architectural model of a system may conform to a generic architectural model or style An awareness of these styles can simplify the problem of defining system architectures However most large systems are heterogeneous and do not follow a single architectural styleArchitectural models

Used to document an architectural design Static structural model that shows the major system components Dynamic process model that shows the process structure of the system Interface model that defines sub-system interfaces

88

Relationships model such as a data-flow model that shows sub-system relationships Distribution model that shows how sub-systems are distributed across computers

Modular decomposition Another structural level where sub-systems are decomposed into modules Two modular decomposition models coveredbull An object model where the system is decomposed into interacting objectbull A pipeline or data-flow model where the system is decomposed into functional modules which transform inputs to outputs If possible decisions about concurrency should be delayed until modules are implemented

Object models Structure the system into a set of loosely coupled objects with well-defined interfaces Object-oriented decomposition is concerned with identifying object classes their attributes and operations When implemented objects are created from these classes and some control model used to coordinate object operations

Invoice Processing system

Pipeline model advantages Supports transformation reuse Intuitive organisation for stakeholder communication Easy to add new transformations Relatively simple to implement as either a concurrent or sequential system However requires a common format for data transfer along the pipeline and difficult

to support event-based interaction

User interface design

The user interface User interfaces should be designed to match the skills experience and expectations of

its anticipated users System users often judge a system by its interface rather than its functionality A poorly designed interface can cause a user to make catastrophic errors Poor user interface design is the reason why so many software systems are never

usedUser interface Design Principle

89

Design principles User familiaritybull The interface should be based on user-oriented terms and concepts rather than computer concepts For example an office system should use concepts such as letters documents folders etc rather than directories file identifiers etc Consistencybull The system should display an appropriate level of consistency Commands and menus should have the same format command punctuation should be similar etc Minimal surprisebull If a command operates in a known way the user should be able to predict the operation of comparable commandsbull Recoverabilitybull The system should provide some resilience to user errors and allow the user to recover from errors This might include an undo facility confirmation of destructive actions soft deletes etcbull User guidancebull Some user guidance such as help systems on-line manuals etc should be suppliedbull User diversitybull Interaction facilities for different types of user should be supported For example some users have seeing difficulties and so larger text should be available

REAL-TIME SOFTWARE DESIGNReal-time systemsSystems which monitor and control their environmentInevitably associated with hardware devices

bull Sensors Collect data from the system environmentbull Actuators Change (in some way) the systems environment

Time is critical Real-time systems must respond within specified times

Definition A real-time system is a software system where the correct functioning of the

system depends on the results produced by the system and the time at which these results are produced

90

A soft real-time system is a system whose operation is degraded if results are not produced according to the specified timing requirements

A hard real-time system is a system whose operation is incorrect if results are not produced according to the timing specification

StimulusResponse Systems Given a stimulus the system must produce a response within a specified timePeriodic stimuli Stimuli which occur at predictable time intervals

bull For example a temperature sensor may be polled 10 times per secondAperiodic stimuli Stimuli which occur at unpredictable times

bull For example a system power failure may trigger an interrupt which must be processed by the system

Architectural considerations Because of the need to respond to timing demands made by different

stimuliresponses the system architecture must allow for fast switching between stimulus handlers

Timing demands of different stimuli are different so a simple sequential loop is not usually adequate

Real-time systems are therefore usually designed as cooperating processes with a real-time executive controlling these processes

A real-time system model

Real-timecontrol system

ActuatorActuator ActuatorActuator

SensorSensorSensor SensorSensorSensor

Sensoractuator processes

Dataprocessor

Actuatorcontrol

Actuator

Sensorcontrol

Sensor

Stimulus Response

System elementsSensor control processes

bull Collect information from sensors May buffer information collected in response to a sensor stimulus

Data processorbull Carries out processing of collected information and computes the system

responseActuator control processes

91

bull Generates control signals for the actuatorsReal-time programmingHard-real time systems may have to programmed in assembly language to ensure that deadlines are metLanguages such as C allow efficient programs to be written but do not have constructs to support concurrency or shared resource management

Java as a real-time languageJava supports lightweight concurrency (threads and synchronized methods) and can be used for some soft real-time systemsJava 20 is not suitable for hard RT programming but real-time versions of Java are now available that address problems such as

bull Not possible to specify thread execution timebull Different timing in different virtual machinesbull Uncontrollable garbage collectionbull Not possible to discover queue sizes for shared resourcesbull Not possible to access system hardwarebull Not possible to do space or timing analysis

SYSTEM DESIGN Design both the hardware and the software associated with system

Partition functions to either hardware or software Design decisions should be made on the basis on non-functional

system requirements Hardware delivers better performance but potentially longer

development and less scope for changeR-T systems design process

Identify the stimuli to be processed and the required responses to these stimuli For each stimulus and response identify the timing constraints Aggregate the stimulus and response processing into concurrent processes A

process may be associated with each class of stimulus and response Design algorithms to process each class of stimulus and response These must

meet the given timing requirements Design a scheduling system which will ensure that processes are started in time to

meet their deadlines Integrate using a real-time operating system

Timing constraints May require extensive simulation and experiment to ensure that these are met by the systemMay mean that certain design strategies such as object-oriented design cannot be used because of the additional overhead involvedMay mean that low-level programming language features have to be used for performance reasons

Real-time system modellingThe effect of a stimulus in a real-time system may trigger a transition from one state to anotherFinite state machines can be used for modelling real-time systems

92

However FSM models lack structure Even simple systems can have a complex modelThe UML includes notations for defining state machine models

Petrol pump state model

Cardinserted

into reader

Timeout

Resettingdo display CC

error

Initialising

do initialisedisplay

Paying

Stopped

Reading

do get CCdetails

Waiting

do display welcome

dodeliver fuel

do debitCC account

Payment ack

Ready Delivering

update displayNozzle

trigger on

Nozzle trigger off

Nozzle trigger on

Hose inholster

do validatecredit card

Validating

Invalid card

Card removedCard OK

Hose out of holster

Timeout

Real-time operating systems(RTOS)

Real-time operating systems are specialised operating systems which manage the processes in the RTS

Responsible for process management and resource (processor and memory) allocation

May be based on a standard kernel which is used unchanged or modified for a particular application

Do not normally include facilities such as file management

Operating system componentsReal-time clock

bull Provides information for process schedulingInterrupt handler

bull Manages aperiodic requests for serviceScheduler

bull Chooses the next process to be runResource manager

bull Allocates memory and processor resourcesDispatcher

bull Starts process executionNon-stop system components

Configuration manager

93

bull Responsible for the dynamic reconfiguration of the system software and hardware Hardware modules may be replaced and software upgraded without stopping the systems

Fault managerbull Responsible for detecting software and hardware faults and taking appropriate

actions (eg switching to backup disks) to ensure that the system continues in operation

Real-time OS components

Process resourcerequirements

Scheduler

Schedulinginformation

Resourcemanager

Despatcher

Real-timeclock

Processesawaiting

resources

Readylist

Interrupthandler

Availableresource

list

Processorlist

Executing process

Readyprocesses

Releasedresources

Process priority The processing of some types of stimuli must sometimes take priority Interrupt level priority Highest priority which is allocated to processes requiring a

very fast response Clock level priority Allocated to periodic processes Within these further levels of priority may be assigned

Interrupt servicing Control is transferred automatically to a pre-determined memory location This location contains an instruction to jump to

an interrupt service routine Further interrupts are disabled the interrupt

serviced and control returned to the interrupted process

Interrupt service routines must be short simple and fast

Periodic process servicing In most real-time systems there will be several classes of periodic process each with

different periods (the time between executions) execution times and deadlines (the time by which processing must be completed)

The real-time clock ticks periodically and each tick causes an interrupt which schedules the process manager for periodic processes

The process manager selects a process which is ready for execution

Process managementbull Concerned with managing the set of concurrent processes

94

bull Periodic processes are executed at pre-specified time intervalsbull The RTOS uses the real-time clock to determine when to execute a process

taking into accountbull Process period - time between executionsbull Process deadline - the time by which processing must be complete

RTE(Real Time Execution Process) process managementResource manager

Allocate memoryand processor

Scheduler

Choose processfor execution

Despatcher

Start execution on anavailable processor

Process switchingbull The scheduler chooses the next process to be executed by the processor This

depends on a scheduling strategy which may take the process priority into account

bull The resource manager allocates memory and a processor for the process to be executed

bull The dispatcher takes the process from ready list loads it onto a processor and starts execution

Scheduling strategiesNon pre-emptive scheduling

bull Once a process has been scheduled for execution it runs to completion or until it is blocked for some reason (eg waiting for IO)

Pre-emptive schedulingbull The execution of an executing processes may be stopped if a higher priority

process requires serviceScheduling algorithms

bull Round-robinbull Rate monotonicbull Shortest deadline first

Monitoring and control systemsbull Important class of real-time systems bull Continuously check sensors and take actions

depending on sensor valuesbull Monitoring systems examine sensors and

report their resultsbull Control systems take sensor values and control hardware actuators

Generic architecture

95

S1

S2

S3

P (S1)

P (S2)

P (S1)

Monitoringprocesses

Controlprocesses

P (A1)

P (A2)

P (A1)

A1

A2

A3

P (A4) A4

Testingprocess

Control panelprocesses

Burglar alarm systembull A system is required to monitor sensors on doors and windows to detect the

presence of intruders in a buildingbull When a sensor indicates a break-in the system switches on lights around the

area and calls police automaticallybull The system should include provision for operation without a mains power

supply Sensorso Movement detectors window sensors door sensorso 50 window sensors 30 door sensors and 200 movement detectorso Voltage drop sensor Actionso When an intruder is detected police are called automaticallyo Lights are switched on in rooms with active sensorso An audible alarm is switched on

The R-T system design process

bull Identify stimuli and associated responsesbull Define the timing constraints associated with each stimulus and responsebull Allocate system functions to concurrent processesbull Design algorithms for stimulus processing and response generationbull Design a scheduling system which ensures that processes will always be

scheduled to meet their deadlinesStimuli to be processed

Power failurebull Generated aperiodically by a circuit monitor When received the system must

switch to backup power within 50 msIntruder alarm

bull Stimulus generated by system sensors Response is to call the police switch on building lights and the Power failure

bull Generated aperiodically by a circuit monitor When received the system must switch to backup power within 50 ms

bull Intruder alarmbull Stimulus generated by system sensors Response is to call the police switch

on building lights and the audible alarmbull audible alarm

Burglar alarm system processes

96

Lighting controlprocess

Audible alarmprocess

Voice synthesiserprocess

Alarm systemprocess

Power switchprocess

Building monitorprocess

Communicationprocess

Door sensorprocess

Movementdetector process

Window sensorprocess

560 Hz

60 Hz400 Hz 100 Hz

Power failureinterrupt

Alarm system

Building monitor

Alarm system

Alarm system

Alarm system

Detector status Sensor status Sensor status

Room number

Alert message

Room number

Room number

Building_monitor process 1

class BuildingMonitor extends Thread

BuildingSensor win door move

Siren siren = new Siren () Lights lights = new Lights () Synthesizer synthesizer = new Synthesizer () DoorSensors doors = new DoorSensors (30) WindowSensors windows = new WindowSensors (50) MovementSensors movements = new MovementSensors (200) PowerMonitor pm = new PowerMonitor ()

BuildingMonitor() initialise all the sensors and start the processessirenstart () lightsstart () synthesizerstart () windowsstart () doorsstart () movementsstart () pmstart ()

Building monitor process 2public void run () int room = 0 while (true) poll the movement sensors at least twice per second (400 Hz)move = movementsgetVal () poll the window sensors at least twicesecond (100 Hz)win = windowsgetVal () poll the door sensors at least twice per second (60 Hz)door = doorsgetVal ()

97

if (movesensorVal == 1 | doorsensorVal == 1 | winsensorVal == 1) a sensor has indicated an intruder if (movesensorVal == 1) room = moveroom if (doorsensorVal == 1) room = doorroom if (winsensorVal == 1 ) room = winroom lightson (room) sirenon () synthesizeron (room) break Building_monitor process 3 lightsshutdown () sirenshutdown () synthesizershutdown () windowsshutdown () doorsshutdown () movementsshutdown ()

run BuildingMonitor

Control systems

bull A burglar alarm system is primarily a monitoring system It collects data from sensors but no real-time actuator control

bull Control systems are similar but in response to sensor values the system sends control signals to actuators

bull An example of a monitoring and control system is a system that monitors temperature and switches heaters on and off

A temperature control system

Thermostatprocess

Sensorprocess

Furnacecontrol process

Heater controlprocess

500 Hz

500 Hz

Thermostat process500 Hz

Sensorvalues

Switch commandRoom number

DATA ACQUISITION SYSTEMSbull Collect data from sensors for subsequent processing and analysisbull Data collection processes and processing processes may have different periods

and deadlines bull Data collection may be faster than processing eg collecting information about

an explosion bull Circular or ring buffers are a mechanism for smoothing speed differences

The generic Architecture of data acquicition

98

DisplayProcess

dataSensor data

bufferSensorprocess

Sensoridentifier and

value

Sensors (each data flow is a sensor value)

Sensoridentifier and

value

Processdata

Sensor databuffer

Sensorprocess

Sensoridentifier and

value

Sensoridentifier and

value

s1

s2

s3

s4

s5

s6

In data acquisition systemsthe sensor may be generating data quickly and the key problem is to ensure that a sensor is allocated before sensor value changeThe essenitial features of this architecture is each group of sensors has three processes associated with it and convert analogue data to digital values if necessary a buffer process and a process that consumes the data carried out further processing Two groups sensors s1-s3 and s4-s6 on the right side a further procee that diplsys the sensor data Neutron flux data acquisition

Operatordisplay

Fluxprocessing

Flux databuffer

A-Dconvertor

Sensoridentifier and

flux valueProcessedflux level

Neutron flux sensors

bull A system collects data from a set of sensors monitoring the neutron flux from a nuclear reactor

bull Each sensor has a process that converts the analog input flux level into a digita signalIt passes this flux level with sensor identifies to the sensor data buffer the data processing takes the data from this bufferprocesses it and pass it to display process for output on an operator display

A ring buffer

Consumerprocess

Producerprocess

Mutual exclusionbull Producer processes collect data and add it to the buffer Consumer processes

take data from the buffer and make elements availablebull Producer and consumer processes must be mutually excluded from accessing

the same elementThe buffer must stop producer processes adding information to a full buffer and consumer processes trying to take information from an empty buffer

99

Page 4: Unit_III

A data object is defines a composite information(data item) that is processed by software that is it incorporate(join together) collection of individual data items(attributes) and gives the collection of the name of the data object

Therefore ldquowidthrdquo is a single value would not be a valid data objectbut dimension (heightwidth and depth) could defined as an object

It encapsulate data only therefore the data object can be represented as a tablethe heading (column name)in the table is attributes of the object Example object is a car defined in terms of model ID numbeBody typecolor and ownerThe body of the table represents specific instance of the data object ie BMW is an instance of the data object car

Tabular representation of data objects

Data AttributesData attributes define the properties of a data object It follows one of three different characteristics

1)name an instance of the data object2) describe the instance 3)make reference to another instance in antoher table

The attribute as an identifier use as key to find an instance of the data objectvalues for identifiers are unique make reference to the data object

RelationshipsRelationships indicate in which data objects are connected to one another

Relationships between data objectsThe relationships owns and insured to drive define the relevant connections between person and car

Naming attributes descriptive Referential Identifier attributes attributesMake Model ID Body type Color Owner

Ford Tourus Q12A45 hellip Sedon Blue BLFBMW 750il XZ765hellip coupe white IJL

Instance

person car

72

The arrown provide information about the directionality of the relationships and reduce ambiguity or misinterpertations

Cardinality and ModalityThe data model must be capable of representing the number of occurrences of objects in a given relationships

Tillmann define the cardinality of an object or relationship pair in the following manner

Cardinality is the specification of the number of occurrences of one object that can be related to the number of occurrences of another object

Types of Cardinality11 relationship ndashone object can relate to only one other object1N relationship- one object can relate to many objectsMN relationship- some number of occurrences of an object can relate to some other nuber of occurrences of another object

It also defines ldquothe maximum number of objects that can participate in a relationshiprdquo ModalityData model does not yet provide an indication of whether or not a particular data object must participate in the relationshipto specify information the data model adds modality to the object

The modality of relationship is 0 if there is no explicit(direct) need for the relstionship to occur or the relationship is optional

The modality of relationship is 1 if an occurrence of the relationship is mandatory

SCENARIO-BASED MODELINGThe success of a computer-based system or product is measured in many waysuser satisfaction resides(be located) at the top of the list

If software engineers understand how end-users and other actor want to interact with a systemthe software team will be able to properly characterize requirements and build analysis and design models

Therefore analysis modeling with UML begins with the creation of scenarios in the form of Use-casesactivity diagrams and swimlane diagrams

Writing Use- cases A use-case are part of analysis modeling for user interfaces the interaction that occur between producers and consumers of information and the system

The concept of a use-case is easy to understand describe a specific usage scenario in straightforward language from the point of view of a defined actor not only specific person but the actor is device also The following questions that must be answered if use-cases are to provide value as an analysis modeling tool1what to write about

73

2how much to write about it3how detailed to make our description4how to organize the description What to write about itThe first tasks inception and elicitation provide us the information need to begin writing use-cases Requirements gathering meetingsQuality function deployment(QDF)and other reqirement engineering used to identify stakeholdersdefine the scope of the problemspecify overall operational goalsoutline all known functional requirements and describe the objects that will be manipulated by the system

To begin developing a set of use-cases The functions or activites performed by a specific actor are listed These may be obtained from a list of required system functionsthrough conversations with customers or end-users An evaluation of activity diagram developed as part of analysis modeling(requirement modeling) Example The SafeHome home surveillance function(subsystem) discussed in the sidebar identifies the following functions (an abbreviated list) that are performed by the homeowner actor Access camera surveillance via the internet Select camera to view Request thumbnails from all cameras Display camera views in aPc window Control pan and zoom for a specific camera Selectivel y record camera output Replay camera outputThe requirement gathering team develops use-case for each of the functionsFirst use-cases are written in an informal narrative formIf formal writte is requiredthe same use-case is rewritten using a structured format similar to proposed and later reproduced as a sidebarPreliminary use-case diagramWhen scenario is complex diagrammatic representation easy to understanding UML provide use-case diagramming capabilityPreliminary use-case diagram for the (eg)Safehome product each use-case is represented by a oval

Developing an Activity Diagram

74

The UML diagram supplements the use-case by providing a graphical representation of the flow of interaction within a specific scenarioIt is similar to flow chartan activity diagram notation(symbol)

-rounded rectangles to imply a specific system function -arrows to represent flow through the system -decision diamonds to indicate a branching decision -solid horizontal line to indicate that parallel activities are occurring

An activity diagram for the ACS_DCV function( access surveillance ndashdisplay camera view function)

The activity diagram adds additional detail not directly mentioned by the use-caseFor example a user may only attempt to enter userID and password a limited number of timesthis is represented by a decision dicmond below prompt for reentry

Swimlane DiagramsThe UML swimlane diagram is a variation of the activity diagram and allows the modeler to represent the flow of activities by the use-case

75

And at the same time indicate suppose if there multiple actors involved in a specific function in which actor or analysis class has responsibility for the action described by an activity rectangle

Responsibilities are represented as parallel segments that divide the diagram vertically like the lanes in a swimmingpool A UML swimlane diagram for access surveillance ndashdisplay camera view function

The activity diagram is rearranged that activities associated with a particular analysis class inside the swimlane for the classExample The Interface class represents the user interface as seen by the homeownerThe responsibility of the interface is two prompt prompt for reentry and prompt for another view

76

These prompts and the dscision associated with them fall within the Interrface swimlane but arrows from that swimlane back to the Homeowner swimlane where homeowner actions occur

FLOW-ORIENTED MODELING Data flow-oriented modeling is one of the most used analysis notations is a core modeling activity in structured analysis

Elements of flow-oriented modelingCreating a Data flow modelProcessing narratives Creating a Control flow model The Control SpecificationThe Process SpecificationCreating a Data Flow Model

The data flow diagram enables the software engineer at the same time to develop models of the information domain and functional domain

DFD is refined into greater level of detailthe analyst performs an implicit (indirect) functional decomposition of the system

DFD refinement result corresponding refinement data implied in through process in the application

DFD takes an input ndashprocess-output view of a system that is data objects flow into the software are transformed by processing selements and resultant data objects flow out of the software

Data objects represented by labeled arrow and transformations are represented by circles also called bubbles

DFD is presented in hierarchical manner The first data flow model called a level 0 DFD or context diagram represent the

system as a wholeSubsequent data flow diagram providing increase detail with each subsequent level refine context diagram

The guidelines can aid immeasurably during derivation of a DFD 1The level 0 data flow diagram should describe the softwaresystem as a single bubble2primary input and output should be carefully noted3refinement should begin by isolating candidate processesdata objects and data stores to be represented at the next level4all arrows and bubbles should be labeled with meaning ful names5information flow continuity must be maintained from level to level6one bubble at a time should be refined

Context level DFD (level 0 DFD)The primary external entities (boxes) produce information for use by the system and consume information generated by the systemThe labeled arrows represent data objects or in hierarchiesExample Context ndashlevel(level 0) DFD for the security Safe home function

77

User command and data encompasses all configuration commandsall activationdeactivation commands all miscellaneous interactions and all data that are entered to expand a commandProcessing narrative

It is similar to the use-case in style but different in purpose it provides an overall description of the function to be developed It is not a scenario written from one actorrsquos point of view

The level 0 DFD expanded into a level 1 data flow model to proceed A simple even so effective approach is to perform a ldquogrammatical parserdquo on the processing narrative

that describes the context level bubbleThe following processing narrative text with the first occurance of all nouns underlined and the first occurrence of all verbs italicizedExample Safehome processing narrativeThe Safehome security function enables the homeowner to configure the security system when it is installedmonitors all sensors connected to the security and interacts with the homeowner through the Internet a PC or a control panel

Level 1 DFD for Safehome processesReferring to the grammatical parse verbs are represented as bubbles in a subsequent DFDNouns are either external entities (boxes)data or control objects (arrows) or data stored(double lines) that nouns and verbs can be associsated with one anotherFor example each sensor is assigned a number and type are attributes of the data object sensorTherefore by performing a grammatical parse on the processing narrative for a bubble at any DFD level

78

Level 2 DFD The processes represented at DFD level 1 can be further refined into lower levelsThe information flow continuity has been mainted between levels 0 and 1ExampleThe process monitor sensors can be refined into a level 2 DFD

The refinement of DFDs continues until each bubble performs a simple function that would be easily implemented as a program component

Creating A Control Flow Model

79

Control flow modeling used for a large class of applications are ldquodrivenrdquo by events rather than data produce control information rather than reports or displays and process information with heavy concern for time and performance

Already noted that an event or control item is implemented as a Boolean value ie true or false1 or 0 or a discrete list of conditions

The following guidelines to select potential(possible) candidate events-

o List all sensors that are ldquoreadrdquo by the softwareo List all interrupt conditionso List all ldquoswitches ldquothat are actuated by an operatoro List all data conditionso Recalling the nounverb parse that was applied to the processing narrativereview

all ldquocontrol itemsrdquo as possible for control flow inputsoutputso Describe the behavior of a system by identifying its statesidentify how each state

is reached and define the transitions between stateso Focus on possible omissions a very common error in specifying controlfor

example ask ldquoIs there any other way I can get this state or exit from itrdquoThe Control SpecificationThe control specification (CSPEC) represents the behavior of the system in two different ways 1 State diagram 2 Program activationState diagramIt is a sequential specification of behaviorProgram activationIt also contain a program activation table is a combinatorial specification of behavior

The CSPEC describes the behavior of the system but it gives us no information about the inner working of the process that are activated as aresult of this behaviorExampleThe state diagram indicates that the transitions from the idle state can occurTwo transitions occur out of the Monitoring system status state(1)when the system is deactivated a transition occurs back to the idle state(2) when a sensor is triggered a transition to the Acting Alarm state occurs During the review consider all transition and the content of all states

The Process Specification The process specification (PSPEC) is used to describe all flow model processes that

appear at the final level of refinement The content of the process specification can include narrative texta program design

language(PDL) description of the algorithmmathematical equations tablesdiagrams or charts

The PSPEC is a lsquomini specificationrdquofor each transform at the lowest refined level of a DFD that as a guide for design of the software component that will implement the process

Example The password transform represented in the flow model for Safehome the function is perform by PSPEC

80

If the password matches an entry within the table [valid id message=true] is passed to the message and status display functionIf there is no matah [valid id message=false]is passed to the message and status display function

CLASS-BASED MODELING Class-based element of an analysis modelClasses and objectsAttributesOperationsPackagesCRC modelsCollaborations diagram

Identifying Analysis ClassesTo identify classes by examining the pbolem statement or by performing a

ldquogrammatical parserdquo the use-cases or processing narratives developed for the system to be built Classes are determined by underlinining each noun or noun clause and enter it into a simple tableIf the class is required to implement a solution then it is part of the solution space other wise if a class is necessary only to describe a solution it is part of the problem space

The following ways are for Analysis classes to manifest (marked) themselves External entities that produce or consume information to be used by a computer-based

system (eg) devicespeople Things that are part of the information domain for the problem(eg) reports displays

leeterssignals Occurrences or events that occur within the context of system operation(eg)

aproperty transfer or the completion of a series of robot movements Roles played by who interact with the system(eg) manager engineersalesperson Organizational units that are relevant to an application(eg)division groupteam Places that establish the context of the problem and the overall function of the system

(eg) manufacturing floor ) Structures that define a class of objects or related classes of objects (eg)

sensors four-wheeled vehicles or computerBudd suggests taxonomy (classification) of classes that includes producers(sources0 and consumers(sinks) of datadata managerview and helper classes

A class should never have an ldquoimperative procedural namerdquo(eg) an object with the name Imageinersion would making mistake so that inversion of the image the inversion() is an operation that applied to the class image During early stage of modeling analysis class might be defined to the example of Safehome security function performed in a ldquogrammatical parserdquo on a processing narrativeExtracting the nouns each entry in the list a potential object

Coad and Yourdon suggest six selection characteristics that should be used as an analyst considers each potential class for inclusion in the analysis model

1Retained informationThe potential class will be useful during analysis only if information about it must be remembered so that the system can function

81

2Needed servicesThe potential class must have a set of identifiable operations that can change the value of its attributes in some way3Multiple attributesDuring requirement analysis the focus should be on ldquomajor ldquo information a class with a single attribute be useful during design but better to represent ed as an attribute of another class during the analysis activity4Common attributesA set of attributes can be defined for the potential class and these attributes apply to all instances of the class5Common operationsA set of operation can be defined for the potential class and these operations apply to all instances of the class6Essential requirements External entities that appear in the problem space and produce and consume information important to the operation of any solution for the system will almost always be defined as classes in the requirements modelSpecifying AttributesAttributes are the set of data objects that fully define the class within the context of the problemExample

SystemsystemIDverificationPhonenubersystemStatusdelaytimemasterpasswordprogram()display()reset()query()modify()

The shade portion is list of attributes for the system classDefining OperationsIt define the behavior of an object The types of operations are divided into three categories (1)operations that manipulate data egadingdeletingreformattingselecting (2)operations that perform a computation (3)operations that inquire about the state of an object (4)operations that monitor an object for the occurance of a controlling eventThese functions are accomplished by operating on attributes and associationsExample Safehome processing narrative the phrases indicate that a program() operation is encapsulated by the System classClass-Responsibility-Collaborator(CRC) ModelingClass-responsibility-collaborator modeling provides simple means for identifying and organizing the classes that are relevant to system or product requirementsAmbler describes CRC modeling in the following way A CRC model is a collection of standard index cards that represent classesThe cards are divided into three sectionsDESIGN WITHIN THE CONTEXT OF SOFTWARE ENGINEERING

Design Principle1Design should be traceable to the analysis model

82

2Always consider the architecture of the system to be built3Design of data is as important as design of processing functions4Interfaces both internal and external must be designed with care5User interface design should be tuned to the needs of the end-users6Component ndashlevel design should be functionally independent7Components should be loosely coupled to one another and to the environment8Design representation(models) should be easily understandable9The design should be developed iterativelyWith each iteration the designer should stive for greater simplicity

DESIGN PROCESS AND DESIGN QUALITYDesign process

bull Design process is a sequence of steps carried through which the requirements are translated into a system or software model bull Any design may be modeled as a direct graph The graphs are collection of entities with attributes which participate in relationships bull The system should be described at several different levels of abstraction bull Design takes place in overlapping stages bull Various phases of design process are as shown in following

1 In architectural design the subsystem components can be identified2 The abstract specification is used to specify the subsystems3 The interfaces between the subsystems are designed which is called inter face design4 In component design of subsystems components is done5 The data structure is designed to hold the data6 For perfoming the required functionality the appropriate algorithm is de

signed

Software design is an iterative process through which requirements are translated into a design for constructing the software

The design is represented at a high level of abstractiona level that can be directly traced to the specific system objective and more detailed datafunctional and behavioral requirements As design iteraton occur subsequent refinement to design representation at lower levels of abstraction

McGlaughin suggests three characteristics that serve as a guide for the evaluation of a good design Each of these characteristics is a goal of the design process

The design must implement all of the explicit requirements contained in the analysis model and it must accommodate all of the implicit(indirect) requirements desired by the customer

The design must be a readable understandable guide for those who generate code and for those who test and subsequently support the software

The design should provide a complete picture of the software addressing the data functional and behavioral domains from an implementation perspective

83

Quality guidelinesThe following gidelines to evaluate the quality of a design representation

1A design should display an architecture that (a) That has been created using recognizable architectural styles or patterns

(b)That is composed of components that show good design characteristics (c)That can be implemented in an evolutionary style thereby implementing and testing2A design should be modular that is the software should be logically partitioned into elements or subsystems3A design should contain distinct representation of dataarchitectureinterfaces and components4A design should lead to data structures that are appropriate for the classes to be implemented and are drawn from recognizable data patterns5A design should lead to components that show independent functional characteristics6A design should lead to interfaces that reduce the complexity of connections between components and with the external environmemt7A design should be derived using a repeatable method that is driven by information obtained during software requirements analysis8A design should be represented using a notation that effectively communicates its meaning

Quality attributesHewlett Packard deveopled a set of software quality attributes are given as acronym(short form) FURPS to represent a target(goal) for all software design

Functionality Usability Reliability Performance Supportability

FunctionalityIt is assessed by evaluating the feature set and capabilities of the programthe generalization of the functions that are deliveredand the security of the overall systemUsabilityIt is assessed by human factors consistency and documentationReliabilityIt is evaluated by measuring the frequency and severity of failurethe accuracy of output resultsthe mean-time-to-failure(MTTF) the ability to recover from failure and predictability(unavoidability) of the programPerformanceIt is measured by processing speedresponse timeresource consumption throughput and efficiencySupportabilityItcombin the abilitytoxtendtheprogram(extensibility)adaptabilityServiceabilitymainabilitytestabilitycompatibilityconfigurability the ability to organize and control elements of the software congfiguration

Design Principles Davis suggested a set of principles for software design as

bull The design process should not suffer from ldquotunnel visionrdquobull The design should be traceable to the analysis modelbull The design should not reinvent the wheel

84

bull The design should ldquominimize the intellectual distancerdquo between the software and the problem in the real worldbull The design should exhibit uniformity and integrationbull The design should be structured to degrade gentlybull Design is not coding and coding is not designbull The design should be assessed for qualitybull The design should be reviewed to minimize conceptual errors

Design Concept

The software design concept provides a framework for implementing the right software

Following issues are considered while designing the software1Abstraction At each stage of software design process levels of abstractions should be applied to refine the software solutionAt the higher level of abstraction the solution should be stated in broad terms and in the lower level more detailed description of the solution is given While moving through different levels of abstraction the procedural abstraction and data abstraction is created In procedural abstraction it gives the named sequence of instruction in the specific function In data abstracion the collection of data objects is represented Levels of Abstraction Various levels of abstractions are- Level I - This level represents the solution interms of problem environment Level II - This level represents the decomposition of terms that are moved from problem environment but still not at implementation stage Level III - At this level preliminary procedural representation exists All the terminologies at this level are software oriented and implementation modularity begins at the surface Level IV and V - The concepts of stepwise refinement and modularity are

applied at this level2 Modularity

The software is divided into separately named and addressable components that called as modules Creating such models bring the modularity in siftwareMeyer defines five criteria that enable us to evaluate a design method with respect to its ability to define an effective modular systemModular decomposability A design method provides a systematic mechanism for decomposing the problem into sub-problems This reduces the complexity of the problem and the modularity can be achievedModular composability A design method enables existing design components to be assembled into a new systemModular understandability A module can be understood as a standalone unit Then it will be easier to build and easier to changeModular continuity Small changes to the system requirements result in changes to individual modules rather than system- wide changesModular protection An aberrant condition occurs within a module and its effects are constrained within the module3Refinement

Refinement is actually a process of elaborationStepwise refinement is a top-down design strategy proposed by Niklaus WIRTHThe architecture of a program is developed by successively refining levels of procedural detail

85

The process of program refinement is analogues to the process of refinement and partitioning that is used during requirements analysisAbstraction and refinement are complementary concepts The major difference is that - in the abstraction low-level details are suppressedRefinement helps the designer to elaborate low-levels detailsModular Design

Modular design reduces complexity and helps in easier implementation The parallel development of different parts of the system is possible due to modular designWhat is the benefit of modular design Changes made during testing and maintenance becomes manageable and they do not affect other modules Various quality parameters for effective modular design are -1) Functional independance 2) Cohesion 3) Coupling

Functional IndependenceThe functional independence can be achieved be developing the functional modules

with single-minded approachBy using functional independence functions may be compartmentalized and interfaces are simplifiedVarious types of coupling are i) Data coupling - The data coupling is possible by parameter passing or data interactionii) Control coupling - The modules share related control data in control couplingiii) Commom coupling - Content coupling occurs when one module makes use of data or control information maintained in another moduleFan-out Fan-out is a measure of the number of immediate subordinates to a moule The fan-out should be within some limit in the design If fan-out is very high then it indicates that a single module is controlling many other modules Preferably limit fan-out to no more than sevenFan-in

Fan-in indicates how many modules directly control a given module Modules with fan-in must have good cohesion Each interfac to the module must have the same number and types of parametersFactoring

Factoring means separation of function into new modules By applying factoring the size of module is reduced and thereby the complexity of the problem is reduced This also provides duplication of functions in more than one module The effective factoring brings simplification in the implementation of software design DESIGN HEURISTICS

The program structure can be manipulated according the design heuristics as shon below1Evaluate the first iteration of the program structure to reduce the coupling and improve cohesion The module independency can be achieved in the program structure by exploding or imploding the modules Exploding the modules means obtaining two or more modules in the final stage and imploding the modules means combining the result of different modules2Attempt to minimize the structure with high fan-out and strive for fan-in as depth increase At the higher level of program structure the distribution of control should be made Fan-out means number of immediate subordinates to the module Fan-in means number of immediate ancestores the module have

86

3Keep scope of the effect of a module within the scope of control of that module The decisions made in particular module lsquoarsquo should not affect the module rsquo brsquo which lies outside the scope of module lsquoarsquo4Evaluate the module interfaces to reduce complexity and redundancy and improve consistency Mostly the cause of softwatr errors is module interfaces The module interfaces should simply pass the information and should be consistent with the module5Define module whose function is predicatable but avoid modules that are too restrictive The module should be designed with simplified internal processing so that expected data can be produced as a result The modules should not restrict the size of local data structure options with control flow or modes of external interfaces Being module too much restrictive causes large maintenance6Strive for controlled entry modules by avoiding pathological connections Software interfaces should be constrained and controlled so that it will become manageable Pathological connection means many references or branches into the middle of a module

Design ModelThe design model is represented as pyramid The pyramid is a stable object

Representing design model in this way means that the software design should be stableThe design model has braod foundation of data design stable mid-region with architectural and interface design and the sharp point to for component level design

Advantages of horizontal partition1These are easy to test maintain and extend 2They have fewer side effects in change propagation or error propagation

Disadvantages of horizontal partitionMore data has to be passed across module interfaces which complicates the overall

control of program flowVertical partitioning

Vertical partitioning suggests the control and work should be distributed top-down in program structureIn vertical partitioning

Define separate branches of the module hierarchy for each major functionUse control modules to co-ordinate communication between functions

Advantages of vertical partition1These are easy to maintain the changes2 They reduce the change impact and error propagation

DATA DESIGNData design is basically the model of data that is represented at the high level of abstractionThe data design is then progressively refined to create implementation specific representationsVarious elements of data design are

Data object - The data objects are identified and relationship among various data objects can be represented using entity relationship diagrams or data dictionariesDatabases - Using software design model the data models are translated into data structures and databases at the application level

87

Data warehouses - At the business level useful information is identified from various databases and the data warehouses are created For extracting or navigating the useful business information stored in the huge data warehouse then data mining techniques are applied

ARCHITECTURAL DESIGNSoftware architecture The design process for identifying the sub-systems making up a system and the framework for sub-system control and communication is architectural design The output of this design process is a description of the software architecture

Architectural design An early stage of the system design process Represents the link between specification and design processes Often carried out in parallel with some specification activities It involves identifying major system components and their communicationsArchitecture and system characteristics Performancebull Localise critical operations and minimise communications Use large rather than fine-grain components Securitybull Use a layered architecture with critical assets in the inner layers Safetybull Localise safety-critical features in a small number of sub-systems Availabilitybull Include redundant components and mechanisms for fault tolerance Maintainabilitybull Use fine-grain replaceable components

Architectural design decisions Is there a generic application architecture that can be used How will the system be distributed What architectural styles are appropriate What approach will be used to structure the system How will the system be decomposed into modules What control strategy should be used How will the architectural design be evaluated How should the architecture be documentedArchitectural styles The architectural model of a system may conform to a generic architectural model or style An awareness of these styles can simplify the problem of defining system architectures However most large systems are heterogeneous and do not follow a single architectural styleArchitectural models

Used to document an architectural design Static structural model that shows the major system components Dynamic process model that shows the process structure of the system Interface model that defines sub-system interfaces

88

Relationships model such as a data-flow model that shows sub-system relationships Distribution model that shows how sub-systems are distributed across computers

Modular decomposition Another structural level where sub-systems are decomposed into modules Two modular decomposition models coveredbull An object model where the system is decomposed into interacting objectbull A pipeline or data-flow model where the system is decomposed into functional modules which transform inputs to outputs If possible decisions about concurrency should be delayed until modules are implemented

Object models Structure the system into a set of loosely coupled objects with well-defined interfaces Object-oriented decomposition is concerned with identifying object classes their attributes and operations When implemented objects are created from these classes and some control model used to coordinate object operations

Invoice Processing system

Pipeline model advantages Supports transformation reuse Intuitive organisation for stakeholder communication Easy to add new transformations Relatively simple to implement as either a concurrent or sequential system However requires a common format for data transfer along the pipeline and difficult

to support event-based interaction

User interface design

The user interface User interfaces should be designed to match the skills experience and expectations of

its anticipated users System users often judge a system by its interface rather than its functionality A poorly designed interface can cause a user to make catastrophic errors Poor user interface design is the reason why so many software systems are never

usedUser interface Design Principle

89

Design principles User familiaritybull The interface should be based on user-oriented terms and concepts rather than computer concepts For example an office system should use concepts such as letters documents folders etc rather than directories file identifiers etc Consistencybull The system should display an appropriate level of consistency Commands and menus should have the same format command punctuation should be similar etc Minimal surprisebull If a command operates in a known way the user should be able to predict the operation of comparable commandsbull Recoverabilitybull The system should provide some resilience to user errors and allow the user to recover from errors This might include an undo facility confirmation of destructive actions soft deletes etcbull User guidancebull Some user guidance such as help systems on-line manuals etc should be suppliedbull User diversitybull Interaction facilities for different types of user should be supported For example some users have seeing difficulties and so larger text should be available

REAL-TIME SOFTWARE DESIGNReal-time systemsSystems which monitor and control their environmentInevitably associated with hardware devices

bull Sensors Collect data from the system environmentbull Actuators Change (in some way) the systems environment

Time is critical Real-time systems must respond within specified times

Definition A real-time system is a software system where the correct functioning of the

system depends on the results produced by the system and the time at which these results are produced

90

A soft real-time system is a system whose operation is degraded if results are not produced according to the specified timing requirements

A hard real-time system is a system whose operation is incorrect if results are not produced according to the timing specification

StimulusResponse Systems Given a stimulus the system must produce a response within a specified timePeriodic stimuli Stimuli which occur at predictable time intervals

bull For example a temperature sensor may be polled 10 times per secondAperiodic stimuli Stimuli which occur at unpredictable times

bull For example a system power failure may trigger an interrupt which must be processed by the system

Architectural considerations Because of the need to respond to timing demands made by different

stimuliresponses the system architecture must allow for fast switching between stimulus handlers

Timing demands of different stimuli are different so a simple sequential loop is not usually adequate

Real-time systems are therefore usually designed as cooperating processes with a real-time executive controlling these processes

A real-time system model

Real-timecontrol system

ActuatorActuator ActuatorActuator

SensorSensorSensor SensorSensorSensor

Sensoractuator processes

Dataprocessor

Actuatorcontrol

Actuator

Sensorcontrol

Sensor

Stimulus Response

System elementsSensor control processes

bull Collect information from sensors May buffer information collected in response to a sensor stimulus

Data processorbull Carries out processing of collected information and computes the system

responseActuator control processes

91

bull Generates control signals for the actuatorsReal-time programmingHard-real time systems may have to programmed in assembly language to ensure that deadlines are metLanguages such as C allow efficient programs to be written but do not have constructs to support concurrency or shared resource management

Java as a real-time languageJava supports lightweight concurrency (threads and synchronized methods) and can be used for some soft real-time systemsJava 20 is not suitable for hard RT programming but real-time versions of Java are now available that address problems such as

bull Not possible to specify thread execution timebull Different timing in different virtual machinesbull Uncontrollable garbage collectionbull Not possible to discover queue sizes for shared resourcesbull Not possible to access system hardwarebull Not possible to do space or timing analysis

SYSTEM DESIGN Design both the hardware and the software associated with system

Partition functions to either hardware or software Design decisions should be made on the basis on non-functional

system requirements Hardware delivers better performance but potentially longer

development and less scope for changeR-T systems design process

Identify the stimuli to be processed and the required responses to these stimuli For each stimulus and response identify the timing constraints Aggregate the stimulus and response processing into concurrent processes A

process may be associated with each class of stimulus and response Design algorithms to process each class of stimulus and response These must

meet the given timing requirements Design a scheduling system which will ensure that processes are started in time to

meet their deadlines Integrate using a real-time operating system

Timing constraints May require extensive simulation and experiment to ensure that these are met by the systemMay mean that certain design strategies such as object-oriented design cannot be used because of the additional overhead involvedMay mean that low-level programming language features have to be used for performance reasons

Real-time system modellingThe effect of a stimulus in a real-time system may trigger a transition from one state to anotherFinite state machines can be used for modelling real-time systems

92

However FSM models lack structure Even simple systems can have a complex modelThe UML includes notations for defining state machine models

Petrol pump state model

Cardinserted

into reader

Timeout

Resettingdo display CC

error

Initialising

do initialisedisplay

Paying

Stopped

Reading

do get CCdetails

Waiting

do display welcome

dodeliver fuel

do debitCC account

Payment ack

Ready Delivering

update displayNozzle

trigger on

Nozzle trigger off

Nozzle trigger on

Hose inholster

do validatecredit card

Validating

Invalid card

Card removedCard OK

Hose out of holster

Timeout

Real-time operating systems(RTOS)

Real-time operating systems are specialised operating systems which manage the processes in the RTS

Responsible for process management and resource (processor and memory) allocation

May be based on a standard kernel which is used unchanged or modified for a particular application

Do not normally include facilities such as file management

Operating system componentsReal-time clock

bull Provides information for process schedulingInterrupt handler

bull Manages aperiodic requests for serviceScheduler

bull Chooses the next process to be runResource manager

bull Allocates memory and processor resourcesDispatcher

bull Starts process executionNon-stop system components

Configuration manager

93

bull Responsible for the dynamic reconfiguration of the system software and hardware Hardware modules may be replaced and software upgraded without stopping the systems

Fault managerbull Responsible for detecting software and hardware faults and taking appropriate

actions (eg switching to backup disks) to ensure that the system continues in operation

Real-time OS components

Process resourcerequirements

Scheduler

Schedulinginformation

Resourcemanager

Despatcher

Real-timeclock

Processesawaiting

resources

Readylist

Interrupthandler

Availableresource

list

Processorlist

Executing process

Readyprocesses

Releasedresources

Process priority The processing of some types of stimuli must sometimes take priority Interrupt level priority Highest priority which is allocated to processes requiring a

very fast response Clock level priority Allocated to periodic processes Within these further levels of priority may be assigned

Interrupt servicing Control is transferred automatically to a pre-determined memory location This location contains an instruction to jump to

an interrupt service routine Further interrupts are disabled the interrupt

serviced and control returned to the interrupted process

Interrupt service routines must be short simple and fast

Periodic process servicing In most real-time systems there will be several classes of periodic process each with

different periods (the time between executions) execution times and deadlines (the time by which processing must be completed)

The real-time clock ticks periodically and each tick causes an interrupt which schedules the process manager for periodic processes

The process manager selects a process which is ready for execution

Process managementbull Concerned with managing the set of concurrent processes

94

bull Periodic processes are executed at pre-specified time intervalsbull The RTOS uses the real-time clock to determine when to execute a process

taking into accountbull Process period - time between executionsbull Process deadline - the time by which processing must be complete

RTE(Real Time Execution Process) process managementResource manager

Allocate memoryand processor

Scheduler

Choose processfor execution

Despatcher

Start execution on anavailable processor

Process switchingbull The scheduler chooses the next process to be executed by the processor This

depends on a scheduling strategy which may take the process priority into account

bull The resource manager allocates memory and a processor for the process to be executed

bull The dispatcher takes the process from ready list loads it onto a processor and starts execution

Scheduling strategiesNon pre-emptive scheduling

bull Once a process has been scheduled for execution it runs to completion or until it is blocked for some reason (eg waiting for IO)

Pre-emptive schedulingbull The execution of an executing processes may be stopped if a higher priority

process requires serviceScheduling algorithms

bull Round-robinbull Rate monotonicbull Shortest deadline first

Monitoring and control systemsbull Important class of real-time systems bull Continuously check sensors and take actions

depending on sensor valuesbull Monitoring systems examine sensors and

report their resultsbull Control systems take sensor values and control hardware actuators

Generic architecture

95

S1

S2

S3

P (S1)

P (S2)

P (S1)

Monitoringprocesses

Controlprocesses

P (A1)

P (A2)

P (A1)

A1

A2

A3

P (A4) A4

Testingprocess

Control panelprocesses

Burglar alarm systembull A system is required to monitor sensors on doors and windows to detect the

presence of intruders in a buildingbull When a sensor indicates a break-in the system switches on lights around the

area and calls police automaticallybull The system should include provision for operation without a mains power

supply Sensorso Movement detectors window sensors door sensorso 50 window sensors 30 door sensors and 200 movement detectorso Voltage drop sensor Actionso When an intruder is detected police are called automaticallyo Lights are switched on in rooms with active sensorso An audible alarm is switched on

The R-T system design process

bull Identify stimuli and associated responsesbull Define the timing constraints associated with each stimulus and responsebull Allocate system functions to concurrent processesbull Design algorithms for stimulus processing and response generationbull Design a scheduling system which ensures that processes will always be

scheduled to meet their deadlinesStimuli to be processed

Power failurebull Generated aperiodically by a circuit monitor When received the system must

switch to backup power within 50 msIntruder alarm

bull Stimulus generated by system sensors Response is to call the police switch on building lights and the Power failure

bull Generated aperiodically by a circuit monitor When received the system must switch to backup power within 50 ms

bull Intruder alarmbull Stimulus generated by system sensors Response is to call the police switch

on building lights and the audible alarmbull audible alarm

Burglar alarm system processes

96

Lighting controlprocess

Audible alarmprocess

Voice synthesiserprocess

Alarm systemprocess

Power switchprocess

Building monitorprocess

Communicationprocess

Door sensorprocess

Movementdetector process

Window sensorprocess

560 Hz

60 Hz400 Hz 100 Hz

Power failureinterrupt

Alarm system

Building monitor

Alarm system

Alarm system

Alarm system

Detector status Sensor status Sensor status

Room number

Alert message

Room number

Room number

Building_monitor process 1

class BuildingMonitor extends Thread

BuildingSensor win door move

Siren siren = new Siren () Lights lights = new Lights () Synthesizer synthesizer = new Synthesizer () DoorSensors doors = new DoorSensors (30) WindowSensors windows = new WindowSensors (50) MovementSensors movements = new MovementSensors (200) PowerMonitor pm = new PowerMonitor ()

BuildingMonitor() initialise all the sensors and start the processessirenstart () lightsstart () synthesizerstart () windowsstart () doorsstart () movementsstart () pmstart ()

Building monitor process 2public void run () int room = 0 while (true) poll the movement sensors at least twice per second (400 Hz)move = movementsgetVal () poll the window sensors at least twicesecond (100 Hz)win = windowsgetVal () poll the door sensors at least twice per second (60 Hz)door = doorsgetVal ()

97

if (movesensorVal == 1 | doorsensorVal == 1 | winsensorVal == 1) a sensor has indicated an intruder if (movesensorVal == 1) room = moveroom if (doorsensorVal == 1) room = doorroom if (winsensorVal == 1 ) room = winroom lightson (room) sirenon () synthesizeron (room) break Building_monitor process 3 lightsshutdown () sirenshutdown () synthesizershutdown () windowsshutdown () doorsshutdown () movementsshutdown ()

run BuildingMonitor

Control systems

bull A burglar alarm system is primarily a monitoring system It collects data from sensors but no real-time actuator control

bull Control systems are similar but in response to sensor values the system sends control signals to actuators

bull An example of a monitoring and control system is a system that monitors temperature and switches heaters on and off

A temperature control system

Thermostatprocess

Sensorprocess

Furnacecontrol process

Heater controlprocess

500 Hz

500 Hz

Thermostat process500 Hz

Sensorvalues

Switch commandRoom number

DATA ACQUISITION SYSTEMSbull Collect data from sensors for subsequent processing and analysisbull Data collection processes and processing processes may have different periods

and deadlines bull Data collection may be faster than processing eg collecting information about

an explosion bull Circular or ring buffers are a mechanism for smoothing speed differences

The generic Architecture of data acquicition

98

DisplayProcess

dataSensor data

bufferSensorprocess

Sensoridentifier and

value

Sensors (each data flow is a sensor value)

Sensoridentifier and

value

Processdata

Sensor databuffer

Sensorprocess

Sensoridentifier and

value

Sensoridentifier and

value

s1

s2

s3

s4

s5

s6

In data acquisition systemsthe sensor may be generating data quickly and the key problem is to ensure that a sensor is allocated before sensor value changeThe essenitial features of this architecture is each group of sensors has three processes associated with it and convert analogue data to digital values if necessary a buffer process and a process that consumes the data carried out further processing Two groups sensors s1-s3 and s4-s6 on the right side a further procee that diplsys the sensor data Neutron flux data acquisition

Operatordisplay

Fluxprocessing

Flux databuffer

A-Dconvertor

Sensoridentifier and

flux valueProcessedflux level

Neutron flux sensors

bull A system collects data from a set of sensors monitoring the neutron flux from a nuclear reactor

bull Each sensor has a process that converts the analog input flux level into a digita signalIt passes this flux level with sensor identifies to the sensor data buffer the data processing takes the data from this bufferprocesses it and pass it to display process for output on an operator display

A ring buffer

Consumerprocess

Producerprocess

Mutual exclusionbull Producer processes collect data and add it to the buffer Consumer processes

take data from the buffer and make elements availablebull Producer and consumer processes must be mutually excluded from accessing

the same elementThe buffer must stop producer processes adding information to a full buffer and consumer processes trying to take information from an empty buffer

99

Page 5: Unit_III

The arrown provide information about the directionality of the relationships and reduce ambiguity or misinterpertations

Cardinality and ModalityThe data model must be capable of representing the number of occurrences of objects in a given relationships

Tillmann define the cardinality of an object or relationship pair in the following manner

Cardinality is the specification of the number of occurrences of one object that can be related to the number of occurrences of another object

Types of Cardinality11 relationship ndashone object can relate to only one other object1N relationship- one object can relate to many objectsMN relationship- some number of occurrences of an object can relate to some other nuber of occurrences of another object

It also defines ldquothe maximum number of objects that can participate in a relationshiprdquo ModalityData model does not yet provide an indication of whether or not a particular data object must participate in the relationshipto specify information the data model adds modality to the object

The modality of relationship is 0 if there is no explicit(direct) need for the relstionship to occur or the relationship is optional

The modality of relationship is 1 if an occurrence of the relationship is mandatory

SCENARIO-BASED MODELINGThe success of a computer-based system or product is measured in many waysuser satisfaction resides(be located) at the top of the list

If software engineers understand how end-users and other actor want to interact with a systemthe software team will be able to properly characterize requirements and build analysis and design models

Therefore analysis modeling with UML begins with the creation of scenarios in the form of Use-casesactivity diagrams and swimlane diagrams

Writing Use- cases A use-case are part of analysis modeling for user interfaces the interaction that occur between producers and consumers of information and the system

The concept of a use-case is easy to understand describe a specific usage scenario in straightforward language from the point of view of a defined actor not only specific person but the actor is device also The following questions that must be answered if use-cases are to provide value as an analysis modeling tool1what to write about

73

2how much to write about it3how detailed to make our description4how to organize the description What to write about itThe first tasks inception and elicitation provide us the information need to begin writing use-cases Requirements gathering meetingsQuality function deployment(QDF)and other reqirement engineering used to identify stakeholdersdefine the scope of the problemspecify overall operational goalsoutline all known functional requirements and describe the objects that will be manipulated by the system

To begin developing a set of use-cases The functions or activites performed by a specific actor are listed These may be obtained from a list of required system functionsthrough conversations with customers or end-users An evaluation of activity diagram developed as part of analysis modeling(requirement modeling) Example The SafeHome home surveillance function(subsystem) discussed in the sidebar identifies the following functions (an abbreviated list) that are performed by the homeowner actor Access camera surveillance via the internet Select camera to view Request thumbnails from all cameras Display camera views in aPc window Control pan and zoom for a specific camera Selectivel y record camera output Replay camera outputThe requirement gathering team develops use-case for each of the functionsFirst use-cases are written in an informal narrative formIf formal writte is requiredthe same use-case is rewritten using a structured format similar to proposed and later reproduced as a sidebarPreliminary use-case diagramWhen scenario is complex diagrammatic representation easy to understanding UML provide use-case diagramming capabilityPreliminary use-case diagram for the (eg)Safehome product each use-case is represented by a oval

Developing an Activity Diagram

74

The UML diagram supplements the use-case by providing a graphical representation of the flow of interaction within a specific scenarioIt is similar to flow chartan activity diagram notation(symbol)

-rounded rectangles to imply a specific system function -arrows to represent flow through the system -decision diamonds to indicate a branching decision -solid horizontal line to indicate that parallel activities are occurring

An activity diagram for the ACS_DCV function( access surveillance ndashdisplay camera view function)

The activity diagram adds additional detail not directly mentioned by the use-caseFor example a user may only attempt to enter userID and password a limited number of timesthis is represented by a decision dicmond below prompt for reentry

Swimlane DiagramsThe UML swimlane diagram is a variation of the activity diagram and allows the modeler to represent the flow of activities by the use-case

75

And at the same time indicate suppose if there multiple actors involved in a specific function in which actor or analysis class has responsibility for the action described by an activity rectangle

Responsibilities are represented as parallel segments that divide the diagram vertically like the lanes in a swimmingpool A UML swimlane diagram for access surveillance ndashdisplay camera view function

The activity diagram is rearranged that activities associated with a particular analysis class inside the swimlane for the classExample The Interface class represents the user interface as seen by the homeownerThe responsibility of the interface is two prompt prompt for reentry and prompt for another view

76

These prompts and the dscision associated with them fall within the Interrface swimlane but arrows from that swimlane back to the Homeowner swimlane where homeowner actions occur

FLOW-ORIENTED MODELING Data flow-oriented modeling is one of the most used analysis notations is a core modeling activity in structured analysis

Elements of flow-oriented modelingCreating a Data flow modelProcessing narratives Creating a Control flow model The Control SpecificationThe Process SpecificationCreating a Data Flow Model

The data flow diagram enables the software engineer at the same time to develop models of the information domain and functional domain

DFD is refined into greater level of detailthe analyst performs an implicit (indirect) functional decomposition of the system

DFD refinement result corresponding refinement data implied in through process in the application

DFD takes an input ndashprocess-output view of a system that is data objects flow into the software are transformed by processing selements and resultant data objects flow out of the software

Data objects represented by labeled arrow and transformations are represented by circles also called bubbles

DFD is presented in hierarchical manner The first data flow model called a level 0 DFD or context diagram represent the

system as a wholeSubsequent data flow diagram providing increase detail with each subsequent level refine context diagram

The guidelines can aid immeasurably during derivation of a DFD 1The level 0 data flow diagram should describe the softwaresystem as a single bubble2primary input and output should be carefully noted3refinement should begin by isolating candidate processesdata objects and data stores to be represented at the next level4all arrows and bubbles should be labeled with meaning ful names5information flow continuity must be maintained from level to level6one bubble at a time should be refined

Context level DFD (level 0 DFD)The primary external entities (boxes) produce information for use by the system and consume information generated by the systemThe labeled arrows represent data objects or in hierarchiesExample Context ndashlevel(level 0) DFD for the security Safe home function

77

User command and data encompasses all configuration commandsall activationdeactivation commands all miscellaneous interactions and all data that are entered to expand a commandProcessing narrative

It is similar to the use-case in style but different in purpose it provides an overall description of the function to be developed It is not a scenario written from one actorrsquos point of view

The level 0 DFD expanded into a level 1 data flow model to proceed A simple even so effective approach is to perform a ldquogrammatical parserdquo on the processing narrative

that describes the context level bubbleThe following processing narrative text with the first occurance of all nouns underlined and the first occurrence of all verbs italicizedExample Safehome processing narrativeThe Safehome security function enables the homeowner to configure the security system when it is installedmonitors all sensors connected to the security and interacts with the homeowner through the Internet a PC or a control panel

Level 1 DFD for Safehome processesReferring to the grammatical parse verbs are represented as bubbles in a subsequent DFDNouns are either external entities (boxes)data or control objects (arrows) or data stored(double lines) that nouns and verbs can be associsated with one anotherFor example each sensor is assigned a number and type are attributes of the data object sensorTherefore by performing a grammatical parse on the processing narrative for a bubble at any DFD level

78

Level 2 DFD The processes represented at DFD level 1 can be further refined into lower levelsThe information flow continuity has been mainted between levels 0 and 1ExampleThe process monitor sensors can be refined into a level 2 DFD

The refinement of DFDs continues until each bubble performs a simple function that would be easily implemented as a program component

Creating A Control Flow Model

79

Control flow modeling used for a large class of applications are ldquodrivenrdquo by events rather than data produce control information rather than reports or displays and process information with heavy concern for time and performance

Already noted that an event or control item is implemented as a Boolean value ie true or false1 or 0 or a discrete list of conditions

The following guidelines to select potential(possible) candidate events-

o List all sensors that are ldquoreadrdquo by the softwareo List all interrupt conditionso List all ldquoswitches ldquothat are actuated by an operatoro List all data conditionso Recalling the nounverb parse that was applied to the processing narrativereview

all ldquocontrol itemsrdquo as possible for control flow inputsoutputso Describe the behavior of a system by identifying its statesidentify how each state

is reached and define the transitions between stateso Focus on possible omissions a very common error in specifying controlfor

example ask ldquoIs there any other way I can get this state or exit from itrdquoThe Control SpecificationThe control specification (CSPEC) represents the behavior of the system in two different ways 1 State diagram 2 Program activationState diagramIt is a sequential specification of behaviorProgram activationIt also contain a program activation table is a combinatorial specification of behavior

The CSPEC describes the behavior of the system but it gives us no information about the inner working of the process that are activated as aresult of this behaviorExampleThe state diagram indicates that the transitions from the idle state can occurTwo transitions occur out of the Monitoring system status state(1)when the system is deactivated a transition occurs back to the idle state(2) when a sensor is triggered a transition to the Acting Alarm state occurs During the review consider all transition and the content of all states

The Process Specification The process specification (PSPEC) is used to describe all flow model processes that

appear at the final level of refinement The content of the process specification can include narrative texta program design

language(PDL) description of the algorithmmathematical equations tablesdiagrams or charts

The PSPEC is a lsquomini specificationrdquofor each transform at the lowest refined level of a DFD that as a guide for design of the software component that will implement the process

Example The password transform represented in the flow model for Safehome the function is perform by PSPEC

80

If the password matches an entry within the table [valid id message=true] is passed to the message and status display functionIf there is no matah [valid id message=false]is passed to the message and status display function

CLASS-BASED MODELING Class-based element of an analysis modelClasses and objectsAttributesOperationsPackagesCRC modelsCollaborations diagram

Identifying Analysis ClassesTo identify classes by examining the pbolem statement or by performing a

ldquogrammatical parserdquo the use-cases or processing narratives developed for the system to be built Classes are determined by underlinining each noun or noun clause and enter it into a simple tableIf the class is required to implement a solution then it is part of the solution space other wise if a class is necessary only to describe a solution it is part of the problem space

The following ways are for Analysis classes to manifest (marked) themselves External entities that produce or consume information to be used by a computer-based

system (eg) devicespeople Things that are part of the information domain for the problem(eg) reports displays

leeterssignals Occurrences or events that occur within the context of system operation(eg)

aproperty transfer or the completion of a series of robot movements Roles played by who interact with the system(eg) manager engineersalesperson Organizational units that are relevant to an application(eg)division groupteam Places that establish the context of the problem and the overall function of the system

(eg) manufacturing floor ) Structures that define a class of objects or related classes of objects (eg)

sensors four-wheeled vehicles or computerBudd suggests taxonomy (classification) of classes that includes producers(sources0 and consumers(sinks) of datadata managerview and helper classes

A class should never have an ldquoimperative procedural namerdquo(eg) an object with the name Imageinersion would making mistake so that inversion of the image the inversion() is an operation that applied to the class image During early stage of modeling analysis class might be defined to the example of Safehome security function performed in a ldquogrammatical parserdquo on a processing narrativeExtracting the nouns each entry in the list a potential object

Coad and Yourdon suggest six selection characteristics that should be used as an analyst considers each potential class for inclusion in the analysis model

1Retained informationThe potential class will be useful during analysis only if information about it must be remembered so that the system can function

81

2Needed servicesThe potential class must have a set of identifiable operations that can change the value of its attributes in some way3Multiple attributesDuring requirement analysis the focus should be on ldquomajor ldquo information a class with a single attribute be useful during design but better to represent ed as an attribute of another class during the analysis activity4Common attributesA set of attributes can be defined for the potential class and these attributes apply to all instances of the class5Common operationsA set of operation can be defined for the potential class and these operations apply to all instances of the class6Essential requirements External entities that appear in the problem space and produce and consume information important to the operation of any solution for the system will almost always be defined as classes in the requirements modelSpecifying AttributesAttributes are the set of data objects that fully define the class within the context of the problemExample

SystemsystemIDverificationPhonenubersystemStatusdelaytimemasterpasswordprogram()display()reset()query()modify()

The shade portion is list of attributes for the system classDefining OperationsIt define the behavior of an object The types of operations are divided into three categories (1)operations that manipulate data egadingdeletingreformattingselecting (2)operations that perform a computation (3)operations that inquire about the state of an object (4)operations that monitor an object for the occurance of a controlling eventThese functions are accomplished by operating on attributes and associationsExample Safehome processing narrative the phrases indicate that a program() operation is encapsulated by the System classClass-Responsibility-Collaborator(CRC) ModelingClass-responsibility-collaborator modeling provides simple means for identifying and organizing the classes that are relevant to system or product requirementsAmbler describes CRC modeling in the following way A CRC model is a collection of standard index cards that represent classesThe cards are divided into three sectionsDESIGN WITHIN THE CONTEXT OF SOFTWARE ENGINEERING

Design Principle1Design should be traceable to the analysis model

82

2Always consider the architecture of the system to be built3Design of data is as important as design of processing functions4Interfaces both internal and external must be designed with care5User interface design should be tuned to the needs of the end-users6Component ndashlevel design should be functionally independent7Components should be loosely coupled to one another and to the environment8Design representation(models) should be easily understandable9The design should be developed iterativelyWith each iteration the designer should stive for greater simplicity

DESIGN PROCESS AND DESIGN QUALITYDesign process

bull Design process is a sequence of steps carried through which the requirements are translated into a system or software model bull Any design may be modeled as a direct graph The graphs are collection of entities with attributes which participate in relationships bull The system should be described at several different levels of abstraction bull Design takes place in overlapping stages bull Various phases of design process are as shown in following

1 In architectural design the subsystem components can be identified2 The abstract specification is used to specify the subsystems3 The interfaces between the subsystems are designed which is called inter face design4 In component design of subsystems components is done5 The data structure is designed to hold the data6 For perfoming the required functionality the appropriate algorithm is de

signed

Software design is an iterative process through which requirements are translated into a design for constructing the software

The design is represented at a high level of abstractiona level that can be directly traced to the specific system objective and more detailed datafunctional and behavioral requirements As design iteraton occur subsequent refinement to design representation at lower levels of abstraction

McGlaughin suggests three characteristics that serve as a guide for the evaluation of a good design Each of these characteristics is a goal of the design process

The design must implement all of the explicit requirements contained in the analysis model and it must accommodate all of the implicit(indirect) requirements desired by the customer

The design must be a readable understandable guide for those who generate code and for those who test and subsequently support the software

The design should provide a complete picture of the software addressing the data functional and behavioral domains from an implementation perspective

83

Quality guidelinesThe following gidelines to evaluate the quality of a design representation

1A design should display an architecture that (a) That has been created using recognizable architectural styles or patterns

(b)That is composed of components that show good design characteristics (c)That can be implemented in an evolutionary style thereby implementing and testing2A design should be modular that is the software should be logically partitioned into elements or subsystems3A design should contain distinct representation of dataarchitectureinterfaces and components4A design should lead to data structures that are appropriate for the classes to be implemented and are drawn from recognizable data patterns5A design should lead to components that show independent functional characteristics6A design should lead to interfaces that reduce the complexity of connections between components and with the external environmemt7A design should be derived using a repeatable method that is driven by information obtained during software requirements analysis8A design should be represented using a notation that effectively communicates its meaning

Quality attributesHewlett Packard deveopled a set of software quality attributes are given as acronym(short form) FURPS to represent a target(goal) for all software design

Functionality Usability Reliability Performance Supportability

FunctionalityIt is assessed by evaluating the feature set and capabilities of the programthe generalization of the functions that are deliveredand the security of the overall systemUsabilityIt is assessed by human factors consistency and documentationReliabilityIt is evaluated by measuring the frequency and severity of failurethe accuracy of output resultsthe mean-time-to-failure(MTTF) the ability to recover from failure and predictability(unavoidability) of the programPerformanceIt is measured by processing speedresponse timeresource consumption throughput and efficiencySupportabilityItcombin the abilitytoxtendtheprogram(extensibility)adaptabilityServiceabilitymainabilitytestabilitycompatibilityconfigurability the ability to organize and control elements of the software congfiguration

Design Principles Davis suggested a set of principles for software design as

bull The design process should not suffer from ldquotunnel visionrdquobull The design should be traceable to the analysis modelbull The design should not reinvent the wheel

84

bull The design should ldquominimize the intellectual distancerdquo between the software and the problem in the real worldbull The design should exhibit uniformity and integrationbull The design should be structured to degrade gentlybull Design is not coding and coding is not designbull The design should be assessed for qualitybull The design should be reviewed to minimize conceptual errors

Design Concept

The software design concept provides a framework for implementing the right software

Following issues are considered while designing the software1Abstraction At each stage of software design process levels of abstractions should be applied to refine the software solutionAt the higher level of abstraction the solution should be stated in broad terms and in the lower level more detailed description of the solution is given While moving through different levels of abstraction the procedural abstraction and data abstraction is created In procedural abstraction it gives the named sequence of instruction in the specific function In data abstracion the collection of data objects is represented Levels of Abstraction Various levels of abstractions are- Level I - This level represents the solution interms of problem environment Level II - This level represents the decomposition of terms that are moved from problem environment but still not at implementation stage Level III - At this level preliminary procedural representation exists All the terminologies at this level are software oriented and implementation modularity begins at the surface Level IV and V - The concepts of stepwise refinement and modularity are

applied at this level2 Modularity

The software is divided into separately named and addressable components that called as modules Creating such models bring the modularity in siftwareMeyer defines five criteria that enable us to evaluate a design method with respect to its ability to define an effective modular systemModular decomposability A design method provides a systematic mechanism for decomposing the problem into sub-problems This reduces the complexity of the problem and the modularity can be achievedModular composability A design method enables existing design components to be assembled into a new systemModular understandability A module can be understood as a standalone unit Then it will be easier to build and easier to changeModular continuity Small changes to the system requirements result in changes to individual modules rather than system- wide changesModular protection An aberrant condition occurs within a module and its effects are constrained within the module3Refinement

Refinement is actually a process of elaborationStepwise refinement is a top-down design strategy proposed by Niklaus WIRTHThe architecture of a program is developed by successively refining levels of procedural detail

85

The process of program refinement is analogues to the process of refinement and partitioning that is used during requirements analysisAbstraction and refinement are complementary concepts The major difference is that - in the abstraction low-level details are suppressedRefinement helps the designer to elaborate low-levels detailsModular Design

Modular design reduces complexity and helps in easier implementation The parallel development of different parts of the system is possible due to modular designWhat is the benefit of modular design Changes made during testing and maintenance becomes manageable and they do not affect other modules Various quality parameters for effective modular design are -1) Functional independance 2) Cohesion 3) Coupling

Functional IndependenceThe functional independence can be achieved be developing the functional modules

with single-minded approachBy using functional independence functions may be compartmentalized and interfaces are simplifiedVarious types of coupling are i) Data coupling - The data coupling is possible by parameter passing or data interactionii) Control coupling - The modules share related control data in control couplingiii) Commom coupling - Content coupling occurs when one module makes use of data or control information maintained in another moduleFan-out Fan-out is a measure of the number of immediate subordinates to a moule The fan-out should be within some limit in the design If fan-out is very high then it indicates that a single module is controlling many other modules Preferably limit fan-out to no more than sevenFan-in

Fan-in indicates how many modules directly control a given module Modules with fan-in must have good cohesion Each interfac to the module must have the same number and types of parametersFactoring

Factoring means separation of function into new modules By applying factoring the size of module is reduced and thereby the complexity of the problem is reduced This also provides duplication of functions in more than one module The effective factoring brings simplification in the implementation of software design DESIGN HEURISTICS

The program structure can be manipulated according the design heuristics as shon below1Evaluate the first iteration of the program structure to reduce the coupling and improve cohesion The module independency can be achieved in the program structure by exploding or imploding the modules Exploding the modules means obtaining two or more modules in the final stage and imploding the modules means combining the result of different modules2Attempt to minimize the structure with high fan-out and strive for fan-in as depth increase At the higher level of program structure the distribution of control should be made Fan-out means number of immediate subordinates to the module Fan-in means number of immediate ancestores the module have

86

3Keep scope of the effect of a module within the scope of control of that module The decisions made in particular module lsquoarsquo should not affect the module rsquo brsquo which lies outside the scope of module lsquoarsquo4Evaluate the module interfaces to reduce complexity and redundancy and improve consistency Mostly the cause of softwatr errors is module interfaces The module interfaces should simply pass the information and should be consistent with the module5Define module whose function is predicatable but avoid modules that are too restrictive The module should be designed with simplified internal processing so that expected data can be produced as a result The modules should not restrict the size of local data structure options with control flow or modes of external interfaces Being module too much restrictive causes large maintenance6Strive for controlled entry modules by avoiding pathological connections Software interfaces should be constrained and controlled so that it will become manageable Pathological connection means many references or branches into the middle of a module

Design ModelThe design model is represented as pyramid The pyramid is a stable object

Representing design model in this way means that the software design should be stableThe design model has braod foundation of data design stable mid-region with architectural and interface design and the sharp point to for component level design

Advantages of horizontal partition1These are easy to test maintain and extend 2They have fewer side effects in change propagation or error propagation

Disadvantages of horizontal partitionMore data has to be passed across module interfaces which complicates the overall

control of program flowVertical partitioning

Vertical partitioning suggests the control and work should be distributed top-down in program structureIn vertical partitioning

Define separate branches of the module hierarchy for each major functionUse control modules to co-ordinate communication between functions

Advantages of vertical partition1These are easy to maintain the changes2 They reduce the change impact and error propagation

DATA DESIGNData design is basically the model of data that is represented at the high level of abstractionThe data design is then progressively refined to create implementation specific representationsVarious elements of data design are

Data object - The data objects are identified and relationship among various data objects can be represented using entity relationship diagrams or data dictionariesDatabases - Using software design model the data models are translated into data structures and databases at the application level

87

Data warehouses - At the business level useful information is identified from various databases and the data warehouses are created For extracting or navigating the useful business information stored in the huge data warehouse then data mining techniques are applied

ARCHITECTURAL DESIGNSoftware architecture The design process for identifying the sub-systems making up a system and the framework for sub-system control and communication is architectural design The output of this design process is a description of the software architecture

Architectural design An early stage of the system design process Represents the link between specification and design processes Often carried out in parallel with some specification activities It involves identifying major system components and their communicationsArchitecture and system characteristics Performancebull Localise critical operations and minimise communications Use large rather than fine-grain components Securitybull Use a layered architecture with critical assets in the inner layers Safetybull Localise safety-critical features in a small number of sub-systems Availabilitybull Include redundant components and mechanisms for fault tolerance Maintainabilitybull Use fine-grain replaceable components

Architectural design decisions Is there a generic application architecture that can be used How will the system be distributed What architectural styles are appropriate What approach will be used to structure the system How will the system be decomposed into modules What control strategy should be used How will the architectural design be evaluated How should the architecture be documentedArchitectural styles The architectural model of a system may conform to a generic architectural model or style An awareness of these styles can simplify the problem of defining system architectures However most large systems are heterogeneous and do not follow a single architectural styleArchitectural models

Used to document an architectural design Static structural model that shows the major system components Dynamic process model that shows the process structure of the system Interface model that defines sub-system interfaces

88

Relationships model such as a data-flow model that shows sub-system relationships Distribution model that shows how sub-systems are distributed across computers

Modular decomposition Another structural level where sub-systems are decomposed into modules Two modular decomposition models coveredbull An object model where the system is decomposed into interacting objectbull A pipeline or data-flow model where the system is decomposed into functional modules which transform inputs to outputs If possible decisions about concurrency should be delayed until modules are implemented

Object models Structure the system into a set of loosely coupled objects with well-defined interfaces Object-oriented decomposition is concerned with identifying object classes their attributes and operations When implemented objects are created from these classes and some control model used to coordinate object operations

Invoice Processing system

Pipeline model advantages Supports transformation reuse Intuitive organisation for stakeholder communication Easy to add new transformations Relatively simple to implement as either a concurrent or sequential system However requires a common format for data transfer along the pipeline and difficult

to support event-based interaction

User interface design

The user interface User interfaces should be designed to match the skills experience and expectations of

its anticipated users System users often judge a system by its interface rather than its functionality A poorly designed interface can cause a user to make catastrophic errors Poor user interface design is the reason why so many software systems are never

usedUser interface Design Principle

89

Design principles User familiaritybull The interface should be based on user-oriented terms and concepts rather than computer concepts For example an office system should use concepts such as letters documents folders etc rather than directories file identifiers etc Consistencybull The system should display an appropriate level of consistency Commands and menus should have the same format command punctuation should be similar etc Minimal surprisebull If a command operates in a known way the user should be able to predict the operation of comparable commandsbull Recoverabilitybull The system should provide some resilience to user errors and allow the user to recover from errors This might include an undo facility confirmation of destructive actions soft deletes etcbull User guidancebull Some user guidance such as help systems on-line manuals etc should be suppliedbull User diversitybull Interaction facilities for different types of user should be supported For example some users have seeing difficulties and so larger text should be available

REAL-TIME SOFTWARE DESIGNReal-time systemsSystems which monitor and control their environmentInevitably associated with hardware devices

bull Sensors Collect data from the system environmentbull Actuators Change (in some way) the systems environment

Time is critical Real-time systems must respond within specified times

Definition A real-time system is a software system where the correct functioning of the

system depends on the results produced by the system and the time at which these results are produced

90

A soft real-time system is a system whose operation is degraded if results are not produced according to the specified timing requirements

A hard real-time system is a system whose operation is incorrect if results are not produced according to the timing specification

StimulusResponse Systems Given a stimulus the system must produce a response within a specified timePeriodic stimuli Stimuli which occur at predictable time intervals

bull For example a temperature sensor may be polled 10 times per secondAperiodic stimuli Stimuli which occur at unpredictable times

bull For example a system power failure may trigger an interrupt which must be processed by the system

Architectural considerations Because of the need to respond to timing demands made by different

stimuliresponses the system architecture must allow for fast switching between stimulus handlers

Timing demands of different stimuli are different so a simple sequential loop is not usually adequate

Real-time systems are therefore usually designed as cooperating processes with a real-time executive controlling these processes

A real-time system model

Real-timecontrol system

ActuatorActuator ActuatorActuator

SensorSensorSensor SensorSensorSensor

Sensoractuator processes

Dataprocessor

Actuatorcontrol

Actuator

Sensorcontrol

Sensor

Stimulus Response

System elementsSensor control processes

bull Collect information from sensors May buffer information collected in response to a sensor stimulus

Data processorbull Carries out processing of collected information and computes the system

responseActuator control processes

91

bull Generates control signals for the actuatorsReal-time programmingHard-real time systems may have to programmed in assembly language to ensure that deadlines are metLanguages such as C allow efficient programs to be written but do not have constructs to support concurrency or shared resource management

Java as a real-time languageJava supports lightweight concurrency (threads and synchronized methods) and can be used for some soft real-time systemsJava 20 is not suitable for hard RT programming but real-time versions of Java are now available that address problems such as

bull Not possible to specify thread execution timebull Different timing in different virtual machinesbull Uncontrollable garbage collectionbull Not possible to discover queue sizes for shared resourcesbull Not possible to access system hardwarebull Not possible to do space or timing analysis

SYSTEM DESIGN Design both the hardware and the software associated with system

Partition functions to either hardware or software Design decisions should be made on the basis on non-functional

system requirements Hardware delivers better performance but potentially longer

development and less scope for changeR-T systems design process

Identify the stimuli to be processed and the required responses to these stimuli For each stimulus and response identify the timing constraints Aggregate the stimulus and response processing into concurrent processes A

process may be associated with each class of stimulus and response Design algorithms to process each class of stimulus and response These must

meet the given timing requirements Design a scheduling system which will ensure that processes are started in time to

meet their deadlines Integrate using a real-time operating system

Timing constraints May require extensive simulation and experiment to ensure that these are met by the systemMay mean that certain design strategies such as object-oriented design cannot be used because of the additional overhead involvedMay mean that low-level programming language features have to be used for performance reasons

Real-time system modellingThe effect of a stimulus in a real-time system may trigger a transition from one state to anotherFinite state machines can be used for modelling real-time systems

92

However FSM models lack structure Even simple systems can have a complex modelThe UML includes notations for defining state machine models

Petrol pump state model

Cardinserted

into reader

Timeout

Resettingdo display CC

error

Initialising

do initialisedisplay

Paying

Stopped

Reading

do get CCdetails

Waiting

do display welcome

dodeliver fuel

do debitCC account

Payment ack

Ready Delivering

update displayNozzle

trigger on

Nozzle trigger off

Nozzle trigger on

Hose inholster

do validatecredit card

Validating

Invalid card

Card removedCard OK

Hose out of holster

Timeout

Real-time operating systems(RTOS)

Real-time operating systems are specialised operating systems which manage the processes in the RTS

Responsible for process management and resource (processor and memory) allocation

May be based on a standard kernel which is used unchanged or modified for a particular application

Do not normally include facilities such as file management

Operating system componentsReal-time clock

bull Provides information for process schedulingInterrupt handler

bull Manages aperiodic requests for serviceScheduler

bull Chooses the next process to be runResource manager

bull Allocates memory and processor resourcesDispatcher

bull Starts process executionNon-stop system components

Configuration manager

93

bull Responsible for the dynamic reconfiguration of the system software and hardware Hardware modules may be replaced and software upgraded without stopping the systems

Fault managerbull Responsible for detecting software and hardware faults and taking appropriate

actions (eg switching to backup disks) to ensure that the system continues in operation

Real-time OS components

Process resourcerequirements

Scheduler

Schedulinginformation

Resourcemanager

Despatcher

Real-timeclock

Processesawaiting

resources

Readylist

Interrupthandler

Availableresource

list

Processorlist

Executing process

Readyprocesses

Releasedresources

Process priority The processing of some types of stimuli must sometimes take priority Interrupt level priority Highest priority which is allocated to processes requiring a

very fast response Clock level priority Allocated to periodic processes Within these further levels of priority may be assigned

Interrupt servicing Control is transferred automatically to a pre-determined memory location This location contains an instruction to jump to

an interrupt service routine Further interrupts are disabled the interrupt

serviced and control returned to the interrupted process

Interrupt service routines must be short simple and fast

Periodic process servicing In most real-time systems there will be several classes of periodic process each with

different periods (the time between executions) execution times and deadlines (the time by which processing must be completed)

The real-time clock ticks periodically and each tick causes an interrupt which schedules the process manager for periodic processes

The process manager selects a process which is ready for execution

Process managementbull Concerned with managing the set of concurrent processes

94

bull Periodic processes are executed at pre-specified time intervalsbull The RTOS uses the real-time clock to determine when to execute a process

taking into accountbull Process period - time between executionsbull Process deadline - the time by which processing must be complete

RTE(Real Time Execution Process) process managementResource manager

Allocate memoryand processor

Scheduler

Choose processfor execution

Despatcher

Start execution on anavailable processor

Process switchingbull The scheduler chooses the next process to be executed by the processor This

depends on a scheduling strategy which may take the process priority into account

bull The resource manager allocates memory and a processor for the process to be executed

bull The dispatcher takes the process from ready list loads it onto a processor and starts execution

Scheduling strategiesNon pre-emptive scheduling

bull Once a process has been scheduled for execution it runs to completion or until it is blocked for some reason (eg waiting for IO)

Pre-emptive schedulingbull The execution of an executing processes may be stopped if a higher priority

process requires serviceScheduling algorithms

bull Round-robinbull Rate monotonicbull Shortest deadline first

Monitoring and control systemsbull Important class of real-time systems bull Continuously check sensors and take actions

depending on sensor valuesbull Monitoring systems examine sensors and

report their resultsbull Control systems take sensor values and control hardware actuators

Generic architecture

95

S1

S2

S3

P (S1)

P (S2)

P (S1)

Monitoringprocesses

Controlprocesses

P (A1)

P (A2)

P (A1)

A1

A2

A3

P (A4) A4

Testingprocess

Control panelprocesses

Burglar alarm systembull A system is required to monitor sensors on doors and windows to detect the

presence of intruders in a buildingbull When a sensor indicates a break-in the system switches on lights around the

area and calls police automaticallybull The system should include provision for operation without a mains power

supply Sensorso Movement detectors window sensors door sensorso 50 window sensors 30 door sensors and 200 movement detectorso Voltage drop sensor Actionso When an intruder is detected police are called automaticallyo Lights are switched on in rooms with active sensorso An audible alarm is switched on

The R-T system design process

bull Identify stimuli and associated responsesbull Define the timing constraints associated with each stimulus and responsebull Allocate system functions to concurrent processesbull Design algorithms for stimulus processing and response generationbull Design a scheduling system which ensures that processes will always be

scheduled to meet their deadlinesStimuli to be processed

Power failurebull Generated aperiodically by a circuit monitor When received the system must

switch to backup power within 50 msIntruder alarm

bull Stimulus generated by system sensors Response is to call the police switch on building lights and the Power failure

bull Generated aperiodically by a circuit monitor When received the system must switch to backup power within 50 ms

bull Intruder alarmbull Stimulus generated by system sensors Response is to call the police switch

on building lights and the audible alarmbull audible alarm

Burglar alarm system processes

96

Lighting controlprocess

Audible alarmprocess

Voice synthesiserprocess

Alarm systemprocess

Power switchprocess

Building monitorprocess

Communicationprocess

Door sensorprocess

Movementdetector process

Window sensorprocess

560 Hz

60 Hz400 Hz 100 Hz

Power failureinterrupt

Alarm system

Building monitor

Alarm system

Alarm system

Alarm system

Detector status Sensor status Sensor status

Room number

Alert message

Room number

Room number

Building_monitor process 1

class BuildingMonitor extends Thread

BuildingSensor win door move

Siren siren = new Siren () Lights lights = new Lights () Synthesizer synthesizer = new Synthesizer () DoorSensors doors = new DoorSensors (30) WindowSensors windows = new WindowSensors (50) MovementSensors movements = new MovementSensors (200) PowerMonitor pm = new PowerMonitor ()

BuildingMonitor() initialise all the sensors and start the processessirenstart () lightsstart () synthesizerstart () windowsstart () doorsstart () movementsstart () pmstart ()

Building monitor process 2public void run () int room = 0 while (true) poll the movement sensors at least twice per second (400 Hz)move = movementsgetVal () poll the window sensors at least twicesecond (100 Hz)win = windowsgetVal () poll the door sensors at least twice per second (60 Hz)door = doorsgetVal ()

97

if (movesensorVal == 1 | doorsensorVal == 1 | winsensorVal == 1) a sensor has indicated an intruder if (movesensorVal == 1) room = moveroom if (doorsensorVal == 1) room = doorroom if (winsensorVal == 1 ) room = winroom lightson (room) sirenon () synthesizeron (room) break Building_monitor process 3 lightsshutdown () sirenshutdown () synthesizershutdown () windowsshutdown () doorsshutdown () movementsshutdown ()

run BuildingMonitor

Control systems

bull A burglar alarm system is primarily a monitoring system It collects data from sensors but no real-time actuator control

bull Control systems are similar but in response to sensor values the system sends control signals to actuators

bull An example of a monitoring and control system is a system that monitors temperature and switches heaters on and off

A temperature control system

Thermostatprocess

Sensorprocess

Furnacecontrol process

Heater controlprocess

500 Hz

500 Hz

Thermostat process500 Hz

Sensorvalues

Switch commandRoom number

DATA ACQUISITION SYSTEMSbull Collect data from sensors for subsequent processing and analysisbull Data collection processes and processing processes may have different periods

and deadlines bull Data collection may be faster than processing eg collecting information about

an explosion bull Circular or ring buffers are a mechanism for smoothing speed differences

The generic Architecture of data acquicition

98

DisplayProcess

dataSensor data

bufferSensorprocess

Sensoridentifier and

value

Sensors (each data flow is a sensor value)

Sensoridentifier and

value

Processdata

Sensor databuffer

Sensorprocess

Sensoridentifier and

value

Sensoridentifier and

value

s1

s2

s3

s4

s5

s6

In data acquisition systemsthe sensor may be generating data quickly and the key problem is to ensure that a sensor is allocated before sensor value changeThe essenitial features of this architecture is each group of sensors has three processes associated with it and convert analogue data to digital values if necessary a buffer process and a process that consumes the data carried out further processing Two groups sensors s1-s3 and s4-s6 on the right side a further procee that diplsys the sensor data Neutron flux data acquisition

Operatordisplay

Fluxprocessing

Flux databuffer

A-Dconvertor

Sensoridentifier and

flux valueProcessedflux level

Neutron flux sensors

bull A system collects data from a set of sensors monitoring the neutron flux from a nuclear reactor

bull Each sensor has a process that converts the analog input flux level into a digita signalIt passes this flux level with sensor identifies to the sensor data buffer the data processing takes the data from this bufferprocesses it and pass it to display process for output on an operator display

A ring buffer

Consumerprocess

Producerprocess

Mutual exclusionbull Producer processes collect data and add it to the buffer Consumer processes

take data from the buffer and make elements availablebull Producer and consumer processes must be mutually excluded from accessing

the same elementThe buffer must stop producer processes adding information to a full buffer and consumer processes trying to take information from an empty buffer

99

Page 6: Unit_III

2how much to write about it3how detailed to make our description4how to organize the description What to write about itThe first tasks inception and elicitation provide us the information need to begin writing use-cases Requirements gathering meetingsQuality function deployment(QDF)and other reqirement engineering used to identify stakeholdersdefine the scope of the problemspecify overall operational goalsoutline all known functional requirements and describe the objects that will be manipulated by the system

To begin developing a set of use-cases The functions or activites performed by a specific actor are listed These may be obtained from a list of required system functionsthrough conversations with customers or end-users An evaluation of activity diagram developed as part of analysis modeling(requirement modeling) Example The SafeHome home surveillance function(subsystem) discussed in the sidebar identifies the following functions (an abbreviated list) that are performed by the homeowner actor Access camera surveillance via the internet Select camera to view Request thumbnails from all cameras Display camera views in aPc window Control pan and zoom for a specific camera Selectivel y record camera output Replay camera outputThe requirement gathering team develops use-case for each of the functionsFirst use-cases are written in an informal narrative formIf formal writte is requiredthe same use-case is rewritten using a structured format similar to proposed and later reproduced as a sidebarPreliminary use-case diagramWhen scenario is complex diagrammatic representation easy to understanding UML provide use-case diagramming capabilityPreliminary use-case diagram for the (eg)Safehome product each use-case is represented by a oval

Developing an Activity Diagram

74

The UML diagram supplements the use-case by providing a graphical representation of the flow of interaction within a specific scenarioIt is similar to flow chartan activity diagram notation(symbol)

-rounded rectangles to imply a specific system function -arrows to represent flow through the system -decision diamonds to indicate a branching decision -solid horizontal line to indicate that parallel activities are occurring

An activity diagram for the ACS_DCV function( access surveillance ndashdisplay camera view function)

The activity diagram adds additional detail not directly mentioned by the use-caseFor example a user may only attempt to enter userID and password a limited number of timesthis is represented by a decision dicmond below prompt for reentry

Swimlane DiagramsThe UML swimlane diagram is a variation of the activity diagram and allows the modeler to represent the flow of activities by the use-case

75

And at the same time indicate suppose if there multiple actors involved in a specific function in which actor or analysis class has responsibility for the action described by an activity rectangle

Responsibilities are represented as parallel segments that divide the diagram vertically like the lanes in a swimmingpool A UML swimlane diagram for access surveillance ndashdisplay camera view function

The activity diagram is rearranged that activities associated with a particular analysis class inside the swimlane for the classExample The Interface class represents the user interface as seen by the homeownerThe responsibility of the interface is two prompt prompt for reentry and prompt for another view

76

These prompts and the dscision associated with them fall within the Interrface swimlane but arrows from that swimlane back to the Homeowner swimlane where homeowner actions occur

FLOW-ORIENTED MODELING Data flow-oriented modeling is one of the most used analysis notations is a core modeling activity in structured analysis

Elements of flow-oriented modelingCreating a Data flow modelProcessing narratives Creating a Control flow model The Control SpecificationThe Process SpecificationCreating a Data Flow Model

The data flow diagram enables the software engineer at the same time to develop models of the information domain and functional domain

DFD is refined into greater level of detailthe analyst performs an implicit (indirect) functional decomposition of the system

DFD refinement result corresponding refinement data implied in through process in the application

DFD takes an input ndashprocess-output view of a system that is data objects flow into the software are transformed by processing selements and resultant data objects flow out of the software

Data objects represented by labeled arrow and transformations are represented by circles also called bubbles

DFD is presented in hierarchical manner The first data flow model called a level 0 DFD or context diagram represent the

system as a wholeSubsequent data flow diagram providing increase detail with each subsequent level refine context diagram

The guidelines can aid immeasurably during derivation of a DFD 1The level 0 data flow diagram should describe the softwaresystem as a single bubble2primary input and output should be carefully noted3refinement should begin by isolating candidate processesdata objects and data stores to be represented at the next level4all arrows and bubbles should be labeled with meaning ful names5information flow continuity must be maintained from level to level6one bubble at a time should be refined

Context level DFD (level 0 DFD)The primary external entities (boxes) produce information for use by the system and consume information generated by the systemThe labeled arrows represent data objects or in hierarchiesExample Context ndashlevel(level 0) DFD for the security Safe home function

77

User command and data encompasses all configuration commandsall activationdeactivation commands all miscellaneous interactions and all data that are entered to expand a commandProcessing narrative

It is similar to the use-case in style but different in purpose it provides an overall description of the function to be developed It is not a scenario written from one actorrsquos point of view

The level 0 DFD expanded into a level 1 data flow model to proceed A simple even so effective approach is to perform a ldquogrammatical parserdquo on the processing narrative

that describes the context level bubbleThe following processing narrative text with the first occurance of all nouns underlined and the first occurrence of all verbs italicizedExample Safehome processing narrativeThe Safehome security function enables the homeowner to configure the security system when it is installedmonitors all sensors connected to the security and interacts with the homeowner through the Internet a PC or a control panel

Level 1 DFD for Safehome processesReferring to the grammatical parse verbs are represented as bubbles in a subsequent DFDNouns are either external entities (boxes)data or control objects (arrows) or data stored(double lines) that nouns and verbs can be associsated with one anotherFor example each sensor is assigned a number and type are attributes of the data object sensorTherefore by performing a grammatical parse on the processing narrative for a bubble at any DFD level

78

Level 2 DFD The processes represented at DFD level 1 can be further refined into lower levelsThe information flow continuity has been mainted between levels 0 and 1ExampleThe process monitor sensors can be refined into a level 2 DFD

The refinement of DFDs continues until each bubble performs a simple function that would be easily implemented as a program component

Creating A Control Flow Model

79

Control flow modeling used for a large class of applications are ldquodrivenrdquo by events rather than data produce control information rather than reports or displays and process information with heavy concern for time and performance

Already noted that an event or control item is implemented as a Boolean value ie true or false1 or 0 or a discrete list of conditions

The following guidelines to select potential(possible) candidate events-

o List all sensors that are ldquoreadrdquo by the softwareo List all interrupt conditionso List all ldquoswitches ldquothat are actuated by an operatoro List all data conditionso Recalling the nounverb parse that was applied to the processing narrativereview

all ldquocontrol itemsrdquo as possible for control flow inputsoutputso Describe the behavior of a system by identifying its statesidentify how each state

is reached and define the transitions between stateso Focus on possible omissions a very common error in specifying controlfor

example ask ldquoIs there any other way I can get this state or exit from itrdquoThe Control SpecificationThe control specification (CSPEC) represents the behavior of the system in two different ways 1 State diagram 2 Program activationState diagramIt is a sequential specification of behaviorProgram activationIt also contain a program activation table is a combinatorial specification of behavior

The CSPEC describes the behavior of the system but it gives us no information about the inner working of the process that are activated as aresult of this behaviorExampleThe state diagram indicates that the transitions from the idle state can occurTwo transitions occur out of the Monitoring system status state(1)when the system is deactivated a transition occurs back to the idle state(2) when a sensor is triggered a transition to the Acting Alarm state occurs During the review consider all transition and the content of all states

The Process Specification The process specification (PSPEC) is used to describe all flow model processes that

appear at the final level of refinement The content of the process specification can include narrative texta program design

language(PDL) description of the algorithmmathematical equations tablesdiagrams or charts

The PSPEC is a lsquomini specificationrdquofor each transform at the lowest refined level of a DFD that as a guide for design of the software component that will implement the process

Example The password transform represented in the flow model for Safehome the function is perform by PSPEC

80

If the password matches an entry within the table [valid id message=true] is passed to the message and status display functionIf there is no matah [valid id message=false]is passed to the message and status display function

CLASS-BASED MODELING Class-based element of an analysis modelClasses and objectsAttributesOperationsPackagesCRC modelsCollaborations diagram

Identifying Analysis ClassesTo identify classes by examining the pbolem statement or by performing a

ldquogrammatical parserdquo the use-cases or processing narratives developed for the system to be built Classes are determined by underlinining each noun or noun clause and enter it into a simple tableIf the class is required to implement a solution then it is part of the solution space other wise if a class is necessary only to describe a solution it is part of the problem space

The following ways are for Analysis classes to manifest (marked) themselves External entities that produce or consume information to be used by a computer-based

system (eg) devicespeople Things that are part of the information domain for the problem(eg) reports displays

leeterssignals Occurrences or events that occur within the context of system operation(eg)

aproperty transfer or the completion of a series of robot movements Roles played by who interact with the system(eg) manager engineersalesperson Organizational units that are relevant to an application(eg)division groupteam Places that establish the context of the problem and the overall function of the system

(eg) manufacturing floor ) Structures that define a class of objects or related classes of objects (eg)

sensors four-wheeled vehicles or computerBudd suggests taxonomy (classification) of classes that includes producers(sources0 and consumers(sinks) of datadata managerview and helper classes

A class should never have an ldquoimperative procedural namerdquo(eg) an object with the name Imageinersion would making mistake so that inversion of the image the inversion() is an operation that applied to the class image During early stage of modeling analysis class might be defined to the example of Safehome security function performed in a ldquogrammatical parserdquo on a processing narrativeExtracting the nouns each entry in the list a potential object

Coad and Yourdon suggest six selection characteristics that should be used as an analyst considers each potential class for inclusion in the analysis model

1Retained informationThe potential class will be useful during analysis only if information about it must be remembered so that the system can function

81

2Needed servicesThe potential class must have a set of identifiable operations that can change the value of its attributes in some way3Multiple attributesDuring requirement analysis the focus should be on ldquomajor ldquo information a class with a single attribute be useful during design but better to represent ed as an attribute of another class during the analysis activity4Common attributesA set of attributes can be defined for the potential class and these attributes apply to all instances of the class5Common operationsA set of operation can be defined for the potential class and these operations apply to all instances of the class6Essential requirements External entities that appear in the problem space and produce and consume information important to the operation of any solution for the system will almost always be defined as classes in the requirements modelSpecifying AttributesAttributes are the set of data objects that fully define the class within the context of the problemExample

SystemsystemIDverificationPhonenubersystemStatusdelaytimemasterpasswordprogram()display()reset()query()modify()

The shade portion is list of attributes for the system classDefining OperationsIt define the behavior of an object The types of operations are divided into three categories (1)operations that manipulate data egadingdeletingreformattingselecting (2)operations that perform a computation (3)operations that inquire about the state of an object (4)operations that monitor an object for the occurance of a controlling eventThese functions are accomplished by operating on attributes and associationsExample Safehome processing narrative the phrases indicate that a program() operation is encapsulated by the System classClass-Responsibility-Collaborator(CRC) ModelingClass-responsibility-collaborator modeling provides simple means for identifying and organizing the classes that are relevant to system or product requirementsAmbler describes CRC modeling in the following way A CRC model is a collection of standard index cards that represent classesThe cards are divided into three sectionsDESIGN WITHIN THE CONTEXT OF SOFTWARE ENGINEERING

Design Principle1Design should be traceable to the analysis model

82

2Always consider the architecture of the system to be built3Design of data is as important as design of processing functions4Interfaces both internal and external must be designed with care5User interface design should be tuned to the needs of the end-users6Component ndashlevel design should be functionally independent7Components should be loosely coupled to one another and to the environment8Design representation(models) should be easily understandable9The design should be developed iterativelyWith each iteration the designer should stive for greater simplicity

DESIGN PROCESS AND DESIGN QUALITYDesign process

bull Design process is a sequence of steps carried through which the requirements are translated into a system or software model bull Any design may be modeled as a direct graph The graphs are collection of entities with attributes which participate in relationships bull The system should be described at several different levels of abstraction bull Design takes place in overlapping stages bull Various phases of design process are as shown in following

1 In architectural design the subsystem components can be identified2 The abstract specification is used to specify the subsystems3 The interfaces between the subsystems are designed which is called inter face design4 In component design of subsystems components is done5 The data structure is designed to hold the data6 For perfoming the required functionality the appropriate algorithm is de

signed

Software design is an iterative process through which requirements are translated into a design for constructing the software

The design is represented at a high level of abstractiona level that can be directly traced to the specific system objective and more detailed datafunctional and behavioral requirements As design iteraton occur subsequent refinement to design representation at lower levels of abstraction

McGlaughin suggests three characteristics that serve as a guide for the evaluation of a good design Each of these characteristics is a goal of the design process

The design must implement all of the explicit requirements contained in the analysis model and it must accommodate all of the implicit(indirect) requirements desired by the customer

The design must be a readable understandable guide for those who generate code and for those who test and subsequently support the software

The design should provide a complete picture of the software addressing the data functional and behavioral domains from an implementation perspective

83

Quality guidelinesThe following gidelines to evaluate the quality of a design representation

1A design should display an architecture that (a) That has been created using recognizable architectural styles or patterns

(b)That is composed of components that show good design characteristics (c)That can be implemented in an evolutionary style thereby implementing and testing2A design should be modular that is the software should be logically partitioned into elements or subsystems3A design should contain distinct representation of dataarchitectureinterfaces and components4A design should lead to data structures that are appropriate for the classes to be implemented and are drawn from recognizable data patterns5A design should lead to components that show independent functional characteristics6A design should lead to interfaces that reduce the complexity of connections between components and with the external environmemt7A design should be derived using a repeatable method that is driven by information obtained during software requirements analysis8A design should be represented using a notation that effectively communicates its meaning

Quality attributesHewlett Packard deveopled a set of software quality attributes are given as acronym(short form) FURPS to represent a target(goal) for all software design

Functionality Usability Reliability Performance Supportability

FunctionalityIt is assessed by evaluating the feature set and capabilities of the programthe generalization of the functions that are deliveredand the security of the overall systemUsabilityIt is assessed by human factors consistency and documentationReliabilityIt is evaluated by measuring the frequency and severity of failurethe accuracy of output resultsthe mean-time-to-failure(MTTF) the ability to recover from failure and predictability(unavoidability) of the programPerformanceIt is measured by processing speedresponse timeresource consumption throughput and efficiencySupportabilityItcombin the abilitytoxtendtheprogram(extensibility)adaptabilityServiceabilitymainabilitytestabilitycompatibilityconfigurability the ability to organize and control elements of the software congfiguration

Design Principles Davis suggested a set of principles for software design as

bull The design process should not suffer from ldquotunnel visionrdquobull The design should be traceable to the analysis modelbull The design should not reinvent the wheel

84

bull The design should ldquominimize the intellectual distancerdquo between the software and the problem in the real worldbull The design should exhibit uniformity and integrationbull The design should be structured to degrade gentlybull Design is not coding and coding is not designbull The design should be assessed for qualitybull The design should be reviewed to minimize conceptual errors

Design Concept

The software design concept provides a framework for implementing the right software

Following issues are considered while designing the software1Abstraction At each stage of software design process levels of abstractions should be applied to refine the software solutionAt the higher level of abstraction the solution should be stated in broad terms and in the lower level more detailed description of the solution is given While moving through different levels of abstraction the procedural abstraction and data abstraction is created In procedural abstraction it gives the named sequence of instruction in the specific function In data abstracion the collection of data objects is represented Levels of Abstraction Various levels of abstractions are- Level I - This level represents the solution interms of problem environment Level II - This level represents the decomposition of terms that are moved from problem environment but still not at implementation stage Level III - At this level preliminary procedural representation exists All the terminologies at this level are software oriented and implementation modularity begins at the surface Level IV and V - The concepts of stepwise refinement and modularity are

applied at this level2 Modularity

The software is divided into separately named and addressable components that called as modules Creating such models bring the modularity in siftwareMeyer defines five criteria that enable us to evaluate a design method with respect to its ability to define an effective modular systemModular decomposability A design method provides a systematic mechanism for decomposing the problem into sub-problems This reduces the complexity of the problem and the modularity can be achievedModular composability A design method enables existing design components to be assembled into a new systemModular understandability A module can be understood as a standalone unit Then it will be easier to build and easier to changeModular continuity Small changes to the system requirements result in changes to individual modules rather than system- wide changesModular protection An aberrant condition occurs within a module and its effects are constrained within the module3Refinement

Refinement is actually a process of elaborationStepwise refinement is a top-down design strategy proposed by Niklaus WIRTHThe architecture of a program is developed by successively refining levels of procedural detail

85

The process of program refinement is analogues to the process of refinement and partitioning that is used during requirements analysisAbstraction and refinement are complementary concepts The major difference is that - in the abstraction low-level details are suppressedRefinement helps the designer to elaborate low-levels detailsModular Design

Modular design reduces complexity and helps in easier implementation The parallel development of different parts of the system is possible due to modular designWhat is the benefit of modular design Changes made during testing and maintenance becomes manageable and they do not affect other modules Various quality parameters for effective modular design are -1) Functional independance 2) Cohesion 3) Coupling

Functional IndependenceThe functional independence can be achieved be developing the functional modules

with single-minded approachBy using functional independence functions may be compartmentalized and interfaces are simplifiedVarious types of coupling are i) Data coupling - The data coupling is possible by parameter passing or data interactionii) Control coupling - The modules share related control data in control couplingiii) Commom coupling - Content coupling occurs when one module makes use of data or control information maintained in another moduleFan-out Fan-out is a measure of the number of immediate subordinates to a moule The fan-out should be within some limit in the design If fan-out is very high then it indicates that a single module is controlling many other modules Preferably limit fan-out to no more than sevenFan-in

Fan-in indicates how many modules directly control a given module Modules with fan-in must have good cohesion Each interfac to the module must have the same number and types of parametersFactoring

Factoring means separation of function into new modules By applying factoring the size of module is reduced and thereby the complexity of the problem is reduced This also provides duplication of functions in more than one module The effective factoring brings simplification in the implementation of software design DESIGN HEURISTICS

The program structure can be manipulated according the design heuristics as shon below1Evaluate the first iteration of the program structure to reduce the coupling and improve cohesion The module independency can be achieved in the program structure by exploding or imploding the modules Exploding the modules means obtaining two or more modules in the final stage and imploding the modules means combining the result of different modules2Attempt to minimize the structure with high fan-out and strive for fan-in as depth increase At the higher level of program structure the distribution of control should be made Fan-out means number of immediate subordinates to the module Fan-in means number of immediate ancestores the module have

86

3Keep scope of the effect of a module within the scope of control of that module The decisions made in particular module lsquoarsquo should not affect the module rsquo brsquo which lies outside the scope of module lsquoarsquo4Evaluate the module interfaces to reduce complexity and redundancy and improve consistency Mostly the cause of softwatr errors is module interfaces The module interfaces should simply pass the information and should be consistent with the module5Define module whose function is predicatable but avoid modules that are too restrictive The module should be designed with simplified internal processing so that expected data can be produced as a result The modules should not restrict the size of local data structure options with control flow or modes of external interfaces Being module too much restrictive causes large maintenance6Strive for controlled entry modules by avoiding pathological connections Software interfaces should be constrained and controlled so that it will become manageable Pathological connection means many references or branches into the middle of a module

Design ModelThe design model is represented as pyramid The pyramid is a stable object

Representing design model in this way means that the software design should be stableThe design model has braod foundation of data design stable mid-region with architectural and interface design and the sharp point to for component level design

Advantages of horizontal partition1These are easy to test maintain and extend 2They have fewer side effects in change propagation or error propagation

Disadvantages of horizontal partitionMore data has to be passed across module interfaces which complicates the overall

control of program flowVertical partitioning

Vertical partitioning suggests the control and work should be distributed top-down in program structureIn vertical partitioning

Define separate branches of the module hierarchy for each major functionUse control modules to co-ordinate communication between functions

Advantages of vertical partition1These are easy to maintain the changes2 They reduce the change impact and error propagation

DATA DESIGNData design is basically the model of data that is represented at the high level of abstractionThe data design is then progressively refined to create implementation specific representationsVarious elements of data design are

Data object - The data objects are identified and relationship among various data objects can be represented using entity relationship diagrams or data dictionariesDatabases - Using software design model the data models are translated into data structures and databases at the application level

87

Data warehouses - At the business level useful information is identified from various databases and the data warehouses are created For extracting or navigating the useful business information stored in the huge data warehouse then data mining techniques are applied

ARCHITECTURAL DESIGNSoftware architecture The design process for identifying the sub-systems making up a system and the framework for sub-system control and communication is architectural design The output of this design process is a description of the software architecture

Architectural design An early stage of the system design process Represents the link between specification and design processes Often carried out in parallel with some specification activities It involves identifying major system components and their communicationsArchitecture and system characteristics Performancebull Localise critical operations and minimise communications Use large rather than fine-grain components Securitybull Use a layered architecture with critical assets in the inner layers Safetybull Localise safety-critical features in a small number of sub-systems Availabilitybull Include redundant components and mechanisms for fault tolerance Maintainabilitybull Use fine-grain replaceable components

Architectural design decisions Is there a generic application architecture that can be used How will the system be distributed What architectural styles are appropriate What approach will be used to structure the system How will the system be decomposed into modules What control strategy should be used How will the architectural design be evaluated How should the architecture be documentedArchitectural styles The architectural model of a system may conform to a generic architectural model or style An awareness of these styles can simplify the problem of defining system architectures However most large systems are heterogeneous and do not follow a single architectural styleArchitectural models

Used to document an architectural design Static structural model that shows the major system components Dynamic process model that shows the process structure of the system Interface model that defines sub-system interfaces

88

Relationships model such as a data-flow model that shows sub-system relationships Distribution model that shows how sub-systems are distributed across computers

Modular decomposition Another structural level where sub-systems are decomposed into modules Two modular decomposition models coveredbull An object model where the system is decomposed into interacting objectbull A pipeline or data-flow model where the system is decomposed into functional modules which transform inputs to outputs If possible decisions about concurrency should be delayed until modules are implemented

Object models Structure the system into a set of loosely coupled objects with well-defined interfaces Object-oriented decomposition is concerned with identifying object classes their attributes and operations When implemented objects are created from these classes and some control model used to coordinate object operations

Invoice Processing system

Pipeline model advantages Supports transformation reuse Intuitive organisation for stakeholder communication Easy to add new transformations Relatively simple to implement as either a concurrent or sequential system However requires a common format for data transfer along the pipeline and difficult

to support event-based interaction

User interface design

The user interface User interfaces should be designed to match the skills experience and expectations of

its anticipated users System users often judge a system by its interface rather than its functionality A poorly designed interface can cause a user to make catastrophic errors Poor user interface design is the reason why so many software systems are never

usedUser interface Design Principle

89

Design principles User familiaritybull The interface should be based on user-oriented terms and concepts rather than computer concepts For example an office system should use concepts such as letters documents folders etc rather than directories file identifiers etc Consistencybull The system should display an appropriate level of consistency Commands and menus should have the same format command punctuation should be similar etc Minimal surprisebull If a command operates in a known way the user should be able to predict the operation of comparable commandsbull Recoverabilitybull The system should provide some resilience to user errors and allow the user to recover from errors This might include an undo facility confirmation of destructive actions soft deletes etcbull User guidancebull Some user guidance such as help systems on-line manuals etc should be suppliedbull User diversitybull Interaction facilities for different types of user should be supported For example some users have seeing difficulties and so larger text should be available

REAL-TIME SOFTWARE DESIGNReal-time systemsSystems which monitor and control their environmentInevitably associated with hardware devices

bull Sensors Collect data from the system environmentbull Actuators Change (in some way) the systems environment

Time is critical Real-time systems must respond within specified times

Definition A real-time system is a software system where the correct functioning of the

system depends on the results produced by the system and the time at which these results are produced

90

A soft real-time system is a system whose operation is degraded if results are not produced according to the specified timing requirements

A hard real-time system is a system whose operation is incorrect if results are not produced according to the timing specification

StimulusResponse Systems Given a stimulus the system must produce a response within a specified timePeriodic stimuli Stimuli which occur at predictable time intervals

bull For example a temperature sensor may be polled 10 times per secondAperiodic stimuli Stimuli which occur at unpredictable times

bull For example a system power failure may trigger an interrupt which must be processed by the system

Architectural considerations Because of the need to respond to timing demands made by different

stimuliresponses the system architecture must allow for fast switching between stimulus handlers

Timing demands of different stimuli are different so a simple sequential loop is not usually adequate

Real-time systems are therefore usually designed as cooperating processes with a real-time executive controlling these processes

A real-time system model

Real-timecontrol system

ActuatorActuator ActuatorActuator

SensorSensorSensor SensorSensorSensor

Sensoractuator processes

Dataprocessor

Actuatorcontrol

Actuator

Sensorcontrol

Sensor

Stimulus Response

System elementsSensor control processes

bull Collect information from sensors May buffer information collected in response to a sensor stimulus

Data processorbull Carries out processing of collected information and computes the system

responseActuator control processes

91

bull Generates control signals for the actuatorsReal-time programmingHard-real time systems may have to programmed in assembly language to ensure that deadlines are metLanguages such as C allow efficient programs to be written but do not have constructs to support concurrency or shared resource management

Java as a real-time languageJava supports lightweight concurrency (threads and synchronized methods) and can be used for some soft real-time systemsJava 20 is not suitable for hard RT programming but real-time versions of Java are now available that address problems such as

bull Not possible to specify thread execution timebull Different timing in different virtual machinesbull Uncontrollable garbage collectionbull Not possible to discover queue sizes for shared resourcesbull Not possible to access system hardwarebull Not possible to do space or timing analysis

SYSTEM DESIGN Design both the hardware and the software associated with system

Partition functions to either hardware or software Design decisions should be made on the basis on non-functional

system requirements Hardware delivers better performance but potentially longer

development and less scope for changeR-T systems design process

Identify the stimuli to be processed and the required responses to these stimuli For each stimulus and response identify the timing constraints Aggregate the stimulus and response processing into concurrent processes A

process may be associated with each class of stimulus and response Design algorithms to process each class of stimulus and response These must

meet the given timing requirements Design a scheduling system which will ensure that processes are started in time to

meet their deadlines Integrate using a real-time operating system

Timing constraints May require extensive simulation and experiment to ensure that these are met by the systemMay mean that certain design strategies such as object-oriented design cannot be used because of the additional overhead involvedMay mean that low-level programming language features have to be used for performance reasons

Real-time system modellingThe effect of a stimulus in a real-time system may trigger a transition from one state to anotherFinite state machines can be used for modelling real-time systems

92

However FSM models lack structure Even simple systems can have a complex modelThe UML includes notations for defining state machine models

Petrol pump state model

Cardinserted

into reader

Timeout

Resettingdo display CC

error

Initialising

do initialisedisplay

Paying

Stopped

Reading

do get CCdetails

Waiting

do display welcome

dodeliver fuel

do debitCC account

Payment ack

Ready Delivering

update displayNozzle

trigger on

Nozzle trigger off

Nozzle trigger on

Hose inholster

do validatecredit card

Validating

Invalid card

Card removedCard OK

Hose out of holster

Timeout

Real-time operating systems(RTOS)

Real-time operating systems are specialised operating systems which manage the processes in the RTS

Responsible for process management and resource (processor and memory) allocation

May be based on a standard kernel which is used unchanged or modified for a particular application

Do not normally include facilities such as file management

Operating system componentsReal-time clock

bull Provides information for process schedulingInterrupt handler

bull Manages aperiodic requests for serviceScheduler

bull Chooses the next process to be runResource manager

bull Allocates memory and processor resourcesDispatcher

bull Starts process executionNon-stop system components

Configuration manager

93

bull Responsible for the dynamic reconfiguration of the system software and hardware Hardware modules may be replaced and software upgraded without stopping the systems

Fault managerbull Responsible for detecting software and hardware faults and taking appropriate

actions (eg switching to backup disks) to ensure that the system continues in operation

Real-time OS components

Process resourcerequirements

Scheduler

Schedulinginformation

Resourcemanager

Despatcher

Real-timeclock

Processesawaiting

resources

Readylist

Interrupthandler

Availableresource

list

Processorlist

Executing process

Readyprocesses

Releasedresources

Process priority The processing of some types of stimuli must sometimes take priority Interrupt level priority Highest priority which is allocated to processes requiring a

very fast response Clock level priority Allocated to periodic processes Within these further levels of priority may be assigned

Interrupt servicing Control is transferred automatically to a pre-determined memory location This location contains an instruction to jump to

an interrupt service routine Further interrupts are disabled the interrupt

serviced and control returned to the interrupted process

Interrupt service routines must be short simple and fast

Periodic process servicing In most real-time systems there will be several classes of periodic process each with

different periods (the time between executions) execution times and deadlines (the time by which processing must be completed)

The real-time clock ticks periodically and each tick causes an interrupt which schedules the process manager for periodic processes

The process manager selects a process which is ready for execution

Process managementbull Concerned with managing the set of concurrent processes

94

bull Periodic processes are executed at pre-specified time intervalsbull The RTOS uses the real-time clock to determine when to execute a process

taking into accountbull Process period - time between executionsbull Process deadline - the time by which processing must be complete

RTE(Real Time Execution Process) process managementResource manager

Allocate memoryand processor

Scheduler

Choose processfor execution

Despatcher

Start execution on anavailable processor

Process switchingbull The scheduler chooses the next process to be executed by the processor This

depends on a scheduling strategy which may take the process priority into account

bull The resource manager allocates memory and a processor for the process to be executed

bull The dispatcher takes the process from ready list loads it onto a processor and starts execution

Scheduling strategiesNon pre-emptive scheduling

bull Once a process has been scheduled for execution it runs to completion or until it is blocked for some reason (eg waiting for IO)

Pre-emptive schedulingbull The execution of an executing processes may be stopped if a higher priority

process requires serviceScheduling algorithms

bull Round-robinbull Rate monotonicbull Shortest deadline first

Monitoring and control systemsbull Important class of real-time systems bull Continuously check sensors and take actions

depending on sensor valuesbull Monitoring systems examine sensors and

report their resultsbull Control systems take sensor values and control hardware actuators

Generic architecture

95

S1

S2

S3

P (S1)

P (S2)

P (S1)

Monitoringprocesses

Controlprocesses

P (A1)

P (A2)

P (A1)

A1

A2

A3

P (A4) A4

Testingprocess

Control panelprocesses

Burglar alarm systembull A system is required to monitor sensors on doors and windows to detect the

presence of intruders in a buildingbull When a sensor indicates a break-in the system switches on lights around the

area and calls police automaticallybull The system should include provision for operation without a mains power

supply Sensorso Movement detectors window sensors door sensorso 50 window sensors 30 door sensors and 200 movement detectorso Voltage drop sensor Actionso When an intruder is detected police are called automaticallyo Lights are switched on in rooms with active sensorso An audible alarm is switched on

The R-T system design process

bull Identify stimuli and associated responsesbull Define the timing constraints associated with each stimulus and responsebull Allocate system functions to concurrent processesbull Design algorithms for stimulus processing and response generationbull Design a scheduling system which ensures that processes will always be

scheduled to meet their deadlinesStimuli to be processed

Power failurebull Generated aperiodically by a circuit monitor When received the system must

switch to backup power within 50 msIntruder alarm

bull Stimulus generated by system sensors Response is to call the police switch on building lights and the Power failure

bull Generated aperiodically by a circuit monitor When received the system must switch to backup power within 50 ms

bull Intruder alarmbull Stimulus generated by system sensors Response is to call the police switch

on building lights and the audible alarmbull audible alarm

Burglar alarm system processes

96

Lighting controlprocess

Audible alarmprocess

Voice synthesiserprocess

Alarm systemprocess

Power switchprocess

Building monitorprocess

Communicationprocess

Door sensorprocess

Movementdetector process

Window sensorprocess

560 Hz

60 Hz400 Hz 100 Hz

Power failureinterrupt

Alarm system

Building monitor

Alarm system

Alarm system

Alarm system

Detector status Sensor status Sensor status

Room number

Alert message

Room number

Room number

Building_monitor process 1

class BuildingMonitor extends Thread

BuildingSensor win door move

Siren siren = new Siren () Lights lights = new Lights () Synthesizer synthesizer = new Synthesizer () DoorSensors doors = new DoorSensors (30) WindowSensors windows = new WindowSensors (50) MovementSensors movements = new MovementSensors (200) PowerMonitor pm = new PowerMonitor ()

BuildingMonitor() initialise all the sensors and start the processessirenstart () lightsstart () synthesizerstart () windowsstart () doorsstart () movementsstart () pmstart ()

Building monitor process 2public void run () int room = 0 while (true) poll the movement sensors at least twice per second (400 Hz)move = movementsgetVal () poll the window sensors at least twicesecond (100 Hz)win = windowsgetVal () poll the door sensors at least twice per second (60 Hz)door = doorsgetVal ()

97

if (movesensorVal == 1 | doorsensorVal == 1 | winsensorVal == 1) a sensor has indicated an intruder if (movesensorVal == 1) room = moveroom if (doorsensorVal == 1) room = doorroom if (winsensorVal == 1 ) room = winroom lightson (room) sirenon () synthesizeron (room) break Building_monitor process 3 lightsshutdown () sirenshutdown () synthesizershutdown () windowsshutdown () doorsshutdown () movementsshutdown ()

run BuildingMonitor

Control systems

bull A burglar alarm system is primarily a monitoring system It collects data from sensors but no real-time actuator control

bull Control systems are similar but in response to sensor values the system sends control signals to actuators

bull An example of a monitoring and control system is a system that monitors temperature and switches heaters on and off

A temperature control system

Thermostatprocess

Sensorprocess

Furnacecontrol process

Heater controlprocess

500 Hz

500 Hz

Thermostat process500 Hz

Sensorvalues

Switch commandRoom number

DATA ACQUISITION SYSTEMSbull Collect data from sensors for subsequent processing and analysisbull Data collection processes and processing processes may have different periods

and deadlines bull Data collection may be faster than processing eg collecting information about

an explosion bull Circular or ring buffers are a mechanism for smoothing speed differences

The generic Architecture of data acquicition

98

DisplayProcess

dataSensor data

bufferSensorprocess

Sensoridentifier and

value

Sensors (each data flow is a sensor value)

Sensoridentifier and

value

Processdata

Sensor databuffer

Sensorprocess

Sensoridentifier and

value

Sensoridentifier and

value

s1

s2

s3

s4

s5

s6

In data acquisition systemsthe sensor may be generating data quickly and the key problem is to ensure that a sensor is allocated before sensor value changeThe essenitial features of this architecture is each group of sensors has three processes associated with it and convert analogue data to digital values if necessary a buffer process and a process that consumes the data carried out further processing Two groups sensors s1-s3 and s4-s6 on the right side a further procee that diplsys the sensor data Neutron flux data acquisition

Operatordisplay

Fluxprocessing

Flux databuffer

A-Dconvertor

Sensoridentifier and

flux valueProcessedflux level

Neutron flux sensors

bull A system collects data from a set of sensors monitoring the neutron flux from a nuclear reactor

bull Each sensor has a process that converts the analog input flux level into a digita signalIt passes this flux level with sensor identifies to the sensor data buffer the data processing takes the data from this bufferprocesses it and pass it to display process for output on an operator display

A ring buffer

Consumerprocess

Producerprocess

Mutual exclusionbull Producer processes collect data and add it to the buffer Consumer processes

take data from the buffer and make elements availablebull Producer and consumer processes must be mutually excluded from accessing

the same elementThe buffer must stop producer processes adding information to a full buffer and consumer processes trying to take information from an empty buffer

99

Page 7: Unit_III

The UML diagram supplements the use-case by providing a graphical representation of the flow of interaction within a specific scenarioIt is similar to flow chartan activity diagram notation(symbol)

-rounded rectangles to imply a specific system function -arrows to represent flow through the system -decision diamonds to indicate a branching decision -solid horizontal line to indicate that parallel activities are occurring

An activity diagram for the ACS_DCV function( access surveillance ndashdisplay camera view function)

The activity diagram adds additional detail not directly mentioned by the use-caseFor example a user may only attempt to enter userID and password a limited number of timesthis is represented by a decision dicmond below prompt for reentry

Swimlane DiagramsThe UML swimlane diagram is a variation of the activity diagram and allows the modeler to represent the flow of activities by the use-case

75

And at the same time indicate suppose if there multiple actors involved in a specific function in which actor or analysis class has responsibility for the action described by an activity rectangle

Responsibilities are represented as parallel segments that divide the diagram vertically like the lanes in a swimmingpool A UML swimlane diagram for access surveillance ndashdisplay camera view function

The activity diagram is rearranged that activities associated with a particular analysis class inside the swimlane for the classExample The Interface class represents the user interface as seen by the homeownerThe responsibility of the interface is two prompt prompt for reentry and prompt for another view

76

These prompts and the dscision associated with them fall within the Interrface swimlane but arrows from that swimlane back to the Homeowner swimlane where homeowner actions occur

FLOW-ORIENTED MODELING Data flow-oriented modeling is one of the most used analysis notations is a core modeling activity in structured analysis

Elements of flow-oriented modelingCreating a Data flow modelProcessing narratives Creating a Control flow model The Control SpecificationThe Process SpecificationCreating a Data Flow Model

The data flow diagram enables the software engineer at the same time to develop models of the information domain and functional domain

DFD is refined into greater level of detailthe analyst performs an implicit (indirect) functional decomposition of the system

DFD refinement result corresponding refinement data implied in through process in the application

DFD takes an input ndashprocess-output view of a system that is data objects flow into the software are transformed by processing selements and resultant data objects flow out of the software

Data objects represented by labeled arrow and transformations are represented by circles also called bubbles

DFD is presented in hierarchical manner The first data flow model called a level 0 DFD or context diagram represent the

system as a wholeSubsequent data flow diagram providing increase detail with each subsequent level refine context diagram

The guidelines can aid immeasurably during derivation of a DFD 1The level 0 data flow diagram should describe the softwaresystem as a single bubble2primary input and output should be carefully noted3refinement should begin by isolating candidate processesdata objects and data stores to be represented at the next level4all arrows and bubbles should be labeled with meaning ful names5information flow continuity must be maintained from level to level6one bubble at a time should be refined

Context level DFD (level 0 DFD)The primary external entities (boxes) produce information for use by the system and consume information generated by the systemThe labeled arrows represent data objects or in hierarchiesExample Context ndashlevel(level 0) DFD for the security Safe home function

77

User command and data encompasses all configuration commandsall activationdeactivation commands all miscellaneous interactions and all data that are entered to expand a commandProcessing narrative

It is similar to the use-case in style but different in purpose it provides an overall description of the function to be developed It is not a scenario written from one actorrsquos point of view

The level 0 DFD expanded into a level 1 data flow model to proceed A simple even so effective approach is to perform a ldquogrammatical parserdquo on the processing narrative

that describes the context level bubbleThe following processing narrative text with the first occurance of all nouns underlined and the first occurrence of all verbs italicizedExample Safehome processing narrativeThe Safehome security function enables the homeowner to configure the security system when it is installedmonitors all sensors connected to the security and interacts with the homeowner through the Internet a PC or a control panel

Level 1 DFD for Safehome processesReferring to the grammatical parse verbs are represented as bubbles in a subsequent DFDNouns are either external entities (boxes)data or control objects (arrows) or data stored(double lines) that nouns and verbs can be associsated with one anotherFor example each sensor is assigned a number and type are attributes of the data object sensorTherefore by performing a grammatical parse on the processing narrative for a bubble at any DFD level

78

Level 2 DFD The processes represented at DFD level 1 can be further refined into lower levelsThe information flow continuity has been mainted between levels 0 and 1ExampleThe process monitor sensors can be refined into a level 2 DFD

The refinement of DFDs continues until each bubble performs a simple function that would be easily implemented as a program component

Creating A Control Flow Model

79

Control flow modeling used for a large class of applications are ldquodrivenrdquo by events rather than data produce control information rather than reports or displays and process information with heavy concern for time and performance

Already noted that an event or control item is implemented as a Boolean value ie true or false1 or 0 or a discrete list of conditions

The following guidelines to select potential(possible) candidate events-

o List all sensors that are ldquoreadrdquo by the softwareo List all interrupt conditionso List all ldquoswitches ldquothat are actuated by an operatoro List all data conditionso Recalling the nounverb parse that was applied to the processing narrativereview

all ldquocontrol itemsrdquo as possible for control flow inputsoutputso Describe the behavior of a system by identifying its statesidentify how each state

is reached and define the transitions between stateso Focus on possible omissions a very common error in specifying controlfor

example ask ldquoIs there any other way I can get this state or exit from itrdquoThe Control SpecificationThe control specification (CSPEC) represents the behavior of the system in two different ways 1 State diagram 2 Program activationState diagramIt is a sequential specification of behaviorProgram activationIt also contain a program activation table is a combinatorial specification of behavior

The CSPEC describes the behavior of the system but it gives us no information about the inner working of the process that are activated as aresult of this behaviorExampleThe state diagram indicates that the transitions from the idle state can occurTwo transitions occur out of the Monitoring system status state(1)when the system is deactivated a transition occurs back to the idle state(2) when a sensor is triggered a transition to the Acting Alarm state occurs During the review consider all transition and the content of all states

The Process Specification The process specification (PSPEC) is used to describe all flow model processes that

appear at the final level of refinement The content of the process specification can include narrative texta program design

language(PDL) description of the algorithmmathematical equations tablesdiagrams or charts

The PSPEC is a lsquomini specificationrdquofor each transform at the lowest refined level of a DFD that as a guide for design of the software component that will implement the process

Example The password transform represented in the flow model for Safehome the function is perform by PSPEC

80

If the password matches an entry within the table [valid id message=true] is passed to the message and status display functionIf there is no matah [valid id message=false]is passed to the message and status display function

CLASS-BASED MODELING Class-based element of an analysis modelClasses and objectsAttributesOperationsPackagesCRC modelsCollaborations diagram

Identifying Analysis ClassesTo identify classes by examining the pbolem statement or by performing a

ldquogrammatical parserdquo the use-cases or processing narratives developed for the system to be built Classes are determined by underlinining each noun or noun clause and enter it into a simple tableIf the class is required to implement a solution then it is part of the solution space other wise if a class is necessary only to describe a solution it is part of the problem space

The following ways are for Analysis classes to manifest (marked) themselves External entities that produce or consume information to be used by a computer-based

system (eg) devicespeople Things that are part of the information domain for the problem(eg) reports displays

leeterssignals Occurrences or events that occur within the context of system operation(eg)

aproperty transfer or the completion of a series of robot movements Roles played by who interact with the system(eg) manager engineersalesperson Organizational units that are relevant to an application(eg)division groupteam Places that establish the context of the problem and the overall function of the system

(eg) manufacturing floor ) Structures that define a class of objects or related classes of objects (eg)

sensors four-wheeled vehicles or computerBudd suggests taxonomy (classification) of classes that includes producers(sources0 and consumers(sinks) of datadata managerview and helper classes

A class should never have an ldquoimperative procedural namerdquo(eg) an object with the name Imageinersion would making mistake so that inversion of the image the inversion() is an operation that applied to the class image During early stage of modeling analysis class might be defined to the example of Safehome security function performed in a ldquogrammatical parserdquo on a processing narrativeExtracting the nouns each entry in the list a potential object

Coad and Yourdon suggest six selection characteristics that should be used as an analyst considers each potential class for inclusion in the analysis model

1Retained informationThe potential class will be useful during analysis only if information about it must be remembered so that the system can function

81

2Needed servicesThe potential class must have a set of identifiable operations that can change the value of its attributes in some way3Multiple attributesDuring requirement analysis the focus should be on ldquomajor ldquo information a class with a single attribute be useful during design but better to represent ed as an attribute of another class during the analysis activity4Common attributesA set of attributes can be defined for the potential class and these attributes apply to all instances of the class5Common operationsA set of operation can be defined for the potential class and these operations apply to all instances of the class6Essential requirements External entities that appear in the problem space and produce and consume information important to the operation of any solution for the system will almost always be defined as classes in the requirements modelSpecifying AttributesAttributes are the set of data objects that fully define the class within the context of the problemExample

SystemsystemIDverificationPhonenubersystemStatusdelaytimemasterpasswordprogram()display()reset()query()modify()

The shade portion is list of attributes for the system classDefining OperationsIt define the behavior of an object The types of operations are divided into three categories (1)operations that manipulate data egadingdeletingreformattingselecting (2)operations that perform a computation (3)operations that inquire about the state of an object (4)operations that monitor an object for the occurance of a controlling eventThese functions are accomplished by operating on attributes and associationsExample Safehome processing narrative the phrases indicate that a program() operation is encapsulated by the System classClass-Responsibility-Collaborator(CRC) ModelingClass-responsibility-collaborator modeling provides simple means for identifying and organizing the classes that are relevant to system or product requirementsAmbler describes CRC modeling in the following way A CRC model is a collection of standard index cards that represent classesThe cards are divided into three sectionsDESIGN WITHIN THE CONTEXT OF SOFTWARE ENGINEERING

Design Principle1Design should be traceable to the analysis model

82

2Always consider the architecture of the system to be built3Design of data is as important as design of processing functions4Interfaces both internal and external must be designed with care5User interface design should be tuned to the needs of the end-users6Component ndashlevel design should be functionally independent7Components should be loosely coupled to one another and to the environment8Design representation(models) should be easily understandable9The design should be developed iterativelyWith each iteration the designer should stive for greater simplicity

DESIGN PROCESS AND DESIGN QUALITYDesign process

bull Design process is a sequence of steps carried through which the requirements are translated into a system or software model bull Any design may be modeled as a direct graph The graphs are collection of entities with attributes which participate in relationships bull The system should be described at several different levels of abstraction bull Design takes place in overlapping stages bull Various phases of design process are as shown in following

1 In architectural design the subsystem components can be identified2 The abstract specification is used to specify the subsystems3 The interfaces between the subsystems are designed which is called inter face design4 In component design of subsystems components is done5 The data structure is designed to hold the data6 For perfoming the required functionality the appropriate algorithm is de

signed

Software design is an iterative process through which requirements are translated into a design for constructing the software

The design is represented at a high level of abstractiona level that can be directly traced to the specific system objective and more detailed datafunctional and behavioral requirements As design iteraton occur subsequent refinement to design representation at lower levels of abstraction

McGlaughin suggests three characteristics that serve as a guide for the evaluation of a good design Each of these characteristics is a goal of the design process

The design must implement all of the explicit requirements contained in the analysis model and it must accommodate all of the implicit(indirect) requirements desired by the customer

The design must be a readable understandable guide for those who generate code and for those who test and subsequently support the software

The design should provide a complete picture of the software addressing the data functional and behavioral domains from an implementation perspective

83

Quality guidelinesThe following gidelines to evaluate the quality of a design representation

1A design should display an architecture that (a) That has been created using recognizable architectural styles or patterns

(b)That is composed of components that show good design characteristics (c)That can be implemented in an evolutionary style thereby implementing and testing2A design should be modular that is the software should be logically partitioned into elements or subsystems3A design should contain distinct representation of dataarchitectureinterfaces and components4A design should lead to data structures that are appropriate for the classes to be implemented and are drawn from recognizable data patterns5A design should lead to components that show independent functional characteristics6A design should lead to interfaces that reduce the complexity of connections between components and with the external environmemt7A design should be derived using a repeatable method that is driven by information obtained during software requirements analysis8A design should be represented using a notation that effectively communicates its meaning

Quality attributesHewlett Packard deveopled a set of software quality attributes are given as acronym(short form) FURPS to represent a target(goal) for all software design

Functionality Usability Reliability Performance Supportability

FunctionalityIt is assessed by evaluating the feature set and capabilities of the programthe generalization of the functions that are deliveredand the security of the overall systemUsabilityIt is assessed by human factors consistency and documentationReliabilityIt is evaluated by measuring the frequency and severity of failurethe accuracy of output resultsthe mean-time-to-failure(MTTF) the ability to recover from failure and predictability(unavoidability) of the programPerformanceIt is measured by processing speedresponse timeresource consumption throughput and efficiencySupportabilityItcombin the abilitytoxtendtheprogram(extensibility)adaptabilityServiceabilitymainabilitytestabilitycompatibilityconfigurability the ability to organize and control elements of the software congfiguration

Design Principles Davis suggested a set of principles for software design as

bull The design process should not suffer from ldquotunnel visionrdquobull The design should be traceable to the analysis modelbull The design should not reinvent the wheel

84

bull The design should ldquominimize the intellectual distancerdquo between the software and the problem in the real worldbull The design should exhibit uniformity and integrationbull The design should be structured to degrade gentlybull Design is not coding and coding is not designbull The design should be assessed for qualitybull The design should be reviewed to minimize conceptual errors

Design Concept

The software design concept provides a framework for implementing the right software

Following issues are considered while designing the software1Abstraction At each stage of software design process levels of abstractions should be applied to refine the software solutionAt the higher level of abstraction the solution should be stated in broad terms and in the lower level more detailed description of the solution is given While moving through different levels of abstraction the procedural abstraction and data abstraction is created In procedural abstraction it gives the named sequence of instruction in the specific function In data abstracion the collection of data objects is represented Levels of Abstraction Various levels of abstractions are- Level I - This level represents the solution interms of problem environment Level II - This level represents the decomposition of terms that are moved from problem environment but still not at implementation stage Level III - At this level preliminary procedural representation exists All the terminologies at this level are software oriented and implementation modularity begins at the surface Level IV and V - The concepts of stepwise refinement and modularity are

applied at this level2 Modularity

The software is divided into separately named and addressable components that called as modules Creating such models bring the modularity in siftwareMeyer defines five criteria that enable us to evaluate a design method with respect to its ability to define an effective modular systemModular decomposability A design method provides a systematic mechanism for decomposing the problem into sub-problems This reduces the complexity of the problem and the modularity can be achievedModular composability A design method enables existing design components to be assembled into a new systemModular understandability A module can be understood as a standalone unit Then it will be easier to build and easier to changeModular continuity Small changes to the system requirements result in changes to individual modules rather than system- wide changesModular protection An aberrant condition occurs within a module and its effects are constrained within the module3Refinement

Refinement is actually a process of elaborationStepwise refinement is a top-down design strategy proposed by Niklaus WIRTHThe architecture of a program is developed by successively refining levels of procedural detail

85

The process of program refinement is analogues to the process of refinement and partitioning that is used during requirements analysisAbstraction and refinement are complementary concepts The major difference is that - in the abstraction low-level details are suppressedRefinement helps the designer to elaborate low-levels detailsModular Design

Modular design reduces complexity and helps in easier implementation The parallel development of different parts of the system is possible due to modular designWhat is the benefit of modular design Changes made during testing and maintenance becomes manageable and they do not affect other modules Various quality parameters for effective modular design are -1) Functional independance 2) Cohesion 3) Coupling

Functional IndependenceThe functional independence can be achieved be developing the functional modules

with single-minded approachBy using functional independence functions may be compartmentalized and interfaces are simplifiedVarious types of coupling are i) Data coupling - The data coupling is possible by parameter passing or data interactionii) Control coupling - The modules share related control data in control couplingiii) Commom coupling - Content coupling occurs when one module makes use of data or control information maintained in another moduleFan-out Fan-out is a measure of the number of immediate subordinates to a moule The fan-out should be within some limit in the design If fan-out is very high then it indicates that a single module is controlling many other modules Preferably limit fan-out to no more than sevenFan-in

Fan-in indicates how many modules directly control a given module Modules with fan-in must have good cohesion Each interfac to the module must have the same number and types of parametersFactoring

Factoring means separation of function into new modules By applying factoring the size of module is reduced and thereby the complexity of the problem is reduced This also provides duplication of functions in more than one module The effective factoring brings simplification in the implementation of software design DESIGN HEURISTICS

The program structure can be manipulated according the design heuristics as shon below1Evaluate the first iteration of the program structure to reduce the coupling and improve cohesion The module independency can be achieved in the program structure by exploding or imploding the modules Exploding the modules means obtaining two or more modules in the final stage and imploding the modules means combining the result of different modules2Attempt to minimize the structure with high fan-out and strive for fan-in as depth increase At the higher level of program structure the distribution of control should be made Fan-out means number of immediate subordinates to the module Fan-in means number of immediate ancestores the module have

86

3Keep scope of the effect of a module within the scope of control of that module The decisions made in particular module lsquoarsquo should not affect the module rsquo brsquo which lies outside the scope of module lsquoarsquo4Evaluate the module interfaces to reduce complexity and redundancy and improve consistency Mostly the cause of softwatr errors is module interfaces The module interfaces should simply pass the information and should be consistent with the module5Define module whose function is predicatable but avoid modules that are too restrictive The module should be designed with simplified internal processing so that expected data can be produced as a result The modules should not restrict the size of local data structure options with control flow or modes of external interfaces Being module too much restrictive causes large maintenance6Strive for controlled entry modules by avoiding pathological connections Software interfaces should be constrained and controlled so that it will become manageable Pathological connection means many references or branches into the middle of a module

Design ModelThe design model is represented as pyramid The pyramid is a stable object

Representing design model in this way means that the software design should be stableThe design model has braod foundation of data design stable mid-region with architectural and interface design and the sharp point to for component level design

Advantages of horizontal partition1These are easy to test maintain and extend 2They have fewer side effects in change propagation or error propagation

Disadvantages of horizontal partitionMore data has to be passed across module interfaces which complicates the overall

control of program flowVertical partitioning

Vertical partitioning suggests the control and work should be distributed top-down in program structureIn vertical partitioning

Define separate branches of the module hierarchy for each major functionUse control modules to co-ordinate communication between functions

Advantages of vertical partition1These are easy to maintain the changes2 They reduce the change impact and error propagation

DATA DESIGNData design is basically the model of data that is represented at the high level of abstractionThe data design is then progressively refined to create implementation specific representationsVarious elements of data design are

Data object - The data objects are identified and relationship among various data objects can be represented using entity relationship diagrams or data dictionariesDatabases - Using software design model the data models are translated into data structures and databases at the application level

87

Data warehouses - At the business level useful information is identified from various databases and the data warehouses are created For extracting or navigating the useful business information stored in the huge data warehouse then data mining techniques are applied

ARCHITECTURAL DESIGNSoftware architecture The design process for identifying the sub-systems making up a system and the framework for sub-system control and communication is architectural design The output of this design process is a description of the software architecture

Architectural design An early stage of the system design process Represents the link between specification and design processes Often carried out in parallel with some specification activities It involves identifying major system components and their communicationsArchitecture and system characteristics Performancebull Localise critical operations and minimise communications Use large rather than fine-grain components Securitybull Use a layered architecture with critical assets in the inner layers Safetybull Localise safety-critical features in a small number of sub-systems Availabilitybull Include redundant components and mechanisms for fault tolerance Maintainabilitybull Use fine-grain replaceable components

Architectural design decisions Is there a generic application architecture that can be used How will the system be distributed What architectural styles are appropriate What approach will be used to structure the system How will the system be decomposed into modules What control strategy should be used How will the architectural design be evaluated How should the architecture be documentedArchitectural styles The architectural model of a system may conform to a generic architectural model or style An awareness of these styles can simplify the problem of defining system architectures However most large systems are heterogeneous and do not follow a single architectural styleArchitectural models

Used to document an architectural design Static structural model that shows the major system components Dynamic process model that shows the process structure of the system Interface model that defines sub-system interfaces

88

Relationships model such as a data-flow model that shows sub-system relationships Distribution model that shows how sub-systems are distributed across computers

Modular decomposition Another structural level where sub-systems are decomposed into modules Two modular decomposition models coveredbull An object model where the system is decomposed into interacting objectbull A pipeline or data-flow model where the system is decomposed into functional modules which transform inputs to outputs If possible decisions about concurrency should be delayed until modules are implemented

Object models Structure the system into a set of loosely coupled objects with well-defined interfaces Object-oriented decomposition is concerned with identifying object classes their attributes and operations When implemented objects are created from these classes and some control model used to coordinate object operations

Invoice Processing system

Pipeline model advantages Supports transformation reuse Intuitive organisation for stakeholder communication Easy to add new transformations Relatively simple to implement as either a concurrent or sequential system However requires a common format for data transfer along the pipeline and difficult

to support event-based interaction

User interface design

The user interface User interfaces should be designed to match the skills experience and expectations of

its anticipated users System users often judge a system by its interface rather than its functionality A poorly designed interface can cause a user to make catastrophic errors Poor user interface design is the reason why so many software systems are never

usedUser interface Design Principle

89

Design principles User familiaritybull The interface should be based on user-oriented terms and concepts rather than computer concepts For example an office system should use concepts such as letters documents folders etc rather than directories file identifiers etc Consistencybull The system should display an appropriate level of consistency Commands and menus should have the same format command punctuation should be similar etc Minimal surprisebull If a command operates in a known way the user should be able to predict the operation of comparable commandsbull Recoverabilitybull The system should provide some resilience to user errors and allow the user to recover from errors This might include an undo facility confirmation of destructive actions soft deletes etcbull User guidancebull Some user guidance such as help systems on-line manuals etc should be suppliedbull User diversitybull Interaction facilities for different types of user should be supported For example some users have seeing difficulties and so larger text should be available

REAL-TIME SOFTWARE DESIGNReal-time systemsSystems which monitor and control their environmentInevitably associated with hardware devices

bull Sensors Collect data from the system environmentbull Actuators Change (in some way) the systems environment

Time is critical Real-time systems must respond within specified times

Definition A real-time system is a software system where the correct functioning of the

system depends on the results produced by the system and the time at which these results are produced

90

A soft real-time system is a system whose operation is degraded if results are not produced according to the specified timing requirements

A hard real-time system is a system whose operation is incorrect if results are not produced according to the timing specification

StimulusResponse Systems Given a stimulus the system must produce a response within a specified timePeriodic stimuli Stimuli which occur at predictable time intervals

bull For example a temperature sensor may be polled 10 times per secondAperiodic stimuli Stimuli which occur at unpredictable times

bull For example a system power failure may trigger an interrupt which must be processed by the system

Architectural considerations Because of the need to respond to timing demands made by different

stimuliresponses the system architecture must allow for fast switching between stimulus handlers

Timing demands of different stimuli are different so a simple sequential loop is not usually adequate

Real-time systems are therefore usually designed as cooperating processes with a real-time executive controlling these processes

A real-time system model

Real-timecontrol system

ActuatorActuator ActuatorActuator

SensorSensorSensor SensorSensorSensor

Sensoractuator processes

Dataprocessor

Actuatorcontrol

Actuator

Sensorcontrol

Sensor

Stimulus Response

System elementsSensor control processes

bull Collect information from sensors May buffer information collected in response to a sensor stimulus

Data processorbull Carries out processing of collected information and computes the system

responseActuator control processes

91

bull Generates control signals for the actuatorsReal-time programmingHard-real time systems may have to programmed in assembly language to ensure that deadlines are metLanguages such as C allow efficient programs to be written but do not have constructs to support concurrency or shared resource management

Java as a real-time languageJava supports lightweight concurrency (threads and synchronized methods) and can be used for some soft real-time systemsJava 20 is not suitable for hard RT programming but real-time versions of Java are now available that address problems such as

bull Not possible to specify thread execution timebull Different timing in different virtual machinesbull Uncontrollable garbage collectionbull Not possible to discover queue sizes for shared resourcesbull Not possible to access system hardwarebull Not possible to do space or timing analysis

SYSTEM DESIGN Design both the hardware and the software associated with system

Partition functions to either hardware or software Design decisions should be made on the basis on non-functional

system requirements Hardware delivers better performance but potentially longer

development and less scope for changeR-T systems design process

Identify the stimuli to be processed and the required responses to these stimuli For each stimulus and response identify the timing constraints Aggregate the stimulus and response processing into concurrent processes A

process may be associated with each class of stimulus and response Design algorithms to process each class of stimulus and response These must

meet the given timing requirements Design a scheduling system which will ensure that processes are started in time to

meet their deadlines Integrate using a real-time operating system

Timing constraints May require extensive simulation and experiment to ensure that these are met by the systemMay mean that certain design strategies such as object-oriented design cannot be used because of the additional overhead involvedMay mean that low-level programming language features have to be used for performance reasons

Real-time system modellingThe effect of a stimulus in a real-time system may trigger a transition from one state to anotherFinite state machines can be used for modelling real-time systems

92

However FSM models lack structure Even simple systems can have a complex modelThe UML includes notations for defining state machine models

Petrol pump state model

Cardinserted

into reader

Timeout

Resettingdo display CC

error

Initialising

do initialisedisplay

Paying

Stopped

Reading

do get CCdetails

Waiting

do display welcome

dodeliver fuel

do debitCC account

Payment ack

Ready Delivering

update displayNozzle

trigger on

Nozzle trigger off

Nozzle trigger on

Hose inholster

do validatecredit card

Validating

Invalid card

Card removedCard OK

Hose out of holster

Timeout

Real-time operating systems(RTOS)

Real-time operating systems are specialised operating systems which manage the processes in the RTS

Responsible for process management and resource (processor and memory) allocation

May be based on a standard kernel which is used unchanged or modified for a particular application

Do not normally include facilities such as file management

Operating system componentsReal-time clock

bull Provides information for process schedulingInterrupt handler

bull Manages aperiodic requests for serviceScheduler

bull Chooses the next process to be runResource manager

bull Allocates memory and processor resourcesDispatcher

bull Starts process executionNon-stop system components

Configuration manager

93

bull Responsible for the dynamic reconfiguration of the system software and hardware Hardware modules may be replaced and software upgraded without stopping the systems

Fault managerbull Responsible for detecting software and hardware faults and taking appropriate

actions (eg switching to backup disks) to ensure that the system continues in operation

Real-time OS components

Process resourcerequirements

Scheduler

Schedulinginformation

Resourcemanager

Despatcher

Real-timeclock

Processesawaiting

resources

Readylist

Interrupthandler

Availableresource

list

Processorlist

Executing process

Readyprocesses

Releasedresources

Process priority The processing of some types of stimuli must sometimes take priority Interrupt level priority Highest priority which is allocated to processes requiring a

very fast response Clock level priority Allocated to periodic processes Within these further levels of priority may be assigned

Interrupt servicing Control is transferred automatically to a pre-determined memory location This location contains an instruction to jump to

an interrupt service routine Further interrupts are disabled the interrupt

serviced and control returned to the interrupted process

Interrupt service routines must be short simple and fast

Periodic process servicing In most real-time systems there will be several classes of periodic process each with

different periods (the time between executions) execution times and deadlines (the time by which processing must be completed)

The real-time clock ticks periodically and each tick causes an interrupt which schedules the process manager for periodic processes

The process manager selects a process which is ready for execution

Process managementbull Concerned with managing the set of concurrent processes

94

bull Periodic processes are executed at pre-specified time intervalsbull The RTOS uses the real-time clock to determine when to execute a process

taking into accountbull Process period - time between executionsbull Process deadline - the time by which processing must be complete

RTE(Real Time Execution Process) process managementResource manager

Allocate memoryand processor

Scheduler

Choose processfor execution

Despatcher

Start execution on anavailable processor

Process switchingbull The scheduler chooses the next process to be executed by the processor This

depends on a scheduling strategy which may take the process priority into account

bull The resource manager allocates memory and a processor for the process to be executed

bull The dispatcher takes the process from ready list loads it onto a processor and starts execution

Scheduling strategiesNon pre-emptive scheduling

bull Once a process has been scheduled for execution it runs to completion or until it is blocked for some reason (eg waiting for IO)

Pre-emptive schedulingbull The execution of an executing processes may be stopped if a higher priority

process requires serviceScheduling algorithms

bull Round-robinbull Rate monotonicbull Shortest deadline first

Monitoring and control systemsbull Important class of real-time systems bull Continuously check sensors and take actions

depending on sensor valuesbull Monitoring systems examine sensors and

report their resultsbull Control systems take sensor values and control hardware actuators

Generic architecture

95

S1

S2

S3

P (S1)

P (S2)

P (S1)

Monitoringprocesses

Controlprocesses

P (A1)

P (A2)

P (A1)

A1

A2

A3

P (A4) A4

Testingprocess

Control panelprocesses

Burglar alarm systembull A system is required to monitor sensors on doors and windows to detect the

presence of intruders in a buildingbull When a sensor indicates a break-in the system switches on lights around the

area and calls police automaticallybull The system should include provision for operation without a mains power

supply Sensorso Movement detectors window sensors door sensorso 50 window sensors 30 door sensors and 200 movement detectorso Voltage drop sensor Actionso When an intruder is detected police are called automaticallyo Lights are switched on in rooms with active sensorso An audible alarm is switched on

The R-T system design process

bull Identify stimuli and associated responsesbull Define the timing constraints associated with each stimulus and responsebull Allocate system functions to concurrent processesbull Design algorithms for stimulus processing and response generationbull Design a scheduling system which ensures that processes will always be

scheduled to meet their deadlinesStimuli to be processed

Power failurebull Generated aperiodically by a circuit monitor When received the system must

switch to backup power within 50 msIntruder alarm

bull Stimulus generated by system sensors Response is to call the police switch on building lights and the Power failure

bull Generated aperiodically by a circuit monitor When received the system must switch to backup power within 50 ms

bull Intruder alarmbull Stimulus generated by system sensors Response is to call the police switch

on building lights and the audible alarmbull audible alarm

Burglar alarm system processes

96

Lighting controlprocess

Audible alarmprocess

Voice synthesiserprocess

Alarm systemprocess

Power switchprocess

Building monitorprocess

Communicationprocess

Door sensorprocess

Movementdetector process

Window sensorprocess

560 Hz

60 Hz400 Hz 100 Hz

Power failureinterrupt

Alarm system

Building monitor

Alarm system

Alarm system

Alarm system

Detector status Sensor status Sensor status

Room number

Alert message

Room number

Room number

Building_monitor process 1

class BuildingMonitor extends Thread

BuildingSensor win door move

Siren siren = new Siren () Lights lights = new Lights () Synthesizer synthesizer = new Synthesizer () DoorSensors doors = new DoorSensors (30) WindowSensors windows = new WindowSensors (50) MovementSensors movements = new MovementSensors (200) PowerMonitor pm = new PowerMonitor ()

BuildingMonitor() initialise all the sensors and start the processessirenstart () lightsstart () synthesizerstart () windowsstart () doorsstart () movementsstart () pmstart ()

Building monitor process 2public void run () int room = 0 while (true) poll the movement sensors at least twice per second (400 Hz)move = movementsgetVal () poll the window sensors at least twicesecond (100 Hz)win = windowsgetVal () poll the door sensors at least twice per second (60 Hz)door = doorsgetVal ()

97

if (movesensorVal == 1 | doorsensorVal == 1 | winsensorVal == 1) a sensor has indicated an intruder if (movesensorVal == 1) room = moveroom if (doorsensorVal == 1) room = doorroom if (winsensorVal == 1 ) room = winroom lightson (room) sirenon () synthesizeron (room) break Building_monitor process 3 lightsshutdown () sirenshutdown () synthesizershutdown () windowsshutdown () doorsshutdown () movementsshutdown ()

run BuildingMonitor

Control systems

bull A burglar alarm system is primarily a monitoring system It collects data from sensors but no real-time actuator control

bull Control systems are similar but in response to sensor values the system sends control signals to actuators

bull An example of a monitoring and control system is a system that monitors temperature and switches heaters on and off

A temperature control system

Thermostatprocess

Sensorprocess

Furnacecontrol process

Heater controlprocess

500 Hz

500 Hz

Thermostat process500 Hz

Sensorvalues

Switch commandRoom number

DATA ACQUISITION SYSTEMSbull Collect data from sensors for subsequent processing and analysisbull Data collection processes and processing processes may have different periods

and deadlines bull Data collection may be faster than processing eg collecting information about

an explosion bull Circular or ring buffers are a mechanism for smoothing speed differences

The generic Architecture of data acquicition

98

DisplayProcess

dataSensor data

bufferSensorprocess

Sensoridentifier and

value

Sensors (each data flow is a sensor value)

Sensoridentifier and

value

Processdata

Sensor databuffer

Sensorprocess

Sensoridentifier and

value

Sensoridentifier and

value

s1

s2

s3

s4

s5

s6

In data acquisition systemsthe sensor may be generating data quickly and the key problem is to ensure that a sensor is allocated before sensor value changeThe essenitial features of this architecture is each group of sensors has three processes associated with it and convert analogue data to digital values if necessary a buffer process and a process that consumes the data carried out further processing Two groups sensors s1-s3 and s4-s6 on the right side a further procee that diplsys the sensor data Neutron flux data acquisition

Operatordisplay

Fluxprocessing

Flux databuffer

A-Dconvertor

Sensoridentifier and

flux valueProcessedflux level

Neutron flux sensors

bull A system collects data from a set of sensors monitoring the neutron flux from a nuclear reactor

bull Each sensor has a process that converts the analog input flux level into a digita signalIt passes this flux level with sensor identifies to the sensor data buffer the data processing takes the data from this bufferprocesses it and pass it to display process for output on an operator display

A ring buffer

Consumerprocess

Producerprocess

Mutual exclusionbull Producer processes collect data and add it to the buffer Consumer processes

take data from the buffer and make elements availablebull Producer and consumer processes must be mutually excluded from accessing

the same elementThe buffer must stop producer processes adding information to a full buffer and consumer processes trying to take information from an empty buffer

99

Page 8: Unit_III

And at the same time indicate suppose if there multiple actors involved in a specific function in which actor or analysis class has responsibility for the action described by an activity rectangle

Responsibilities are represented as parallel segments that divide the diagram vertically like the lanes in a swimmingpool A UML swimlane diagram for access surveillance ndashdisplay camera view function

The activity diagram is rearranged that activities associated with a particular analysis class inside the swimlane for the classExample The Interface class represents the user interface as seen by the homeownerThe responsibility of the interface is two prompt prompt for reentry and prompt for another view

76

These prompts and the dscision associated with them fall within the Interrface swimlane but arrows from that swimlane back to the Homeowner swimlane where homeowner actions occur

FLOW-ORIENTED MODELING Data flow-oriented modeling is one of the most used analysis notations is a core modeling activity in structured analysis

Elements of flow-oriented modelingCreating a Data flow modelProcessing narratives Creating a Control flow model The Control SpecificationThe Process SpecificationCreating a Data Flow Model

The data flow diagram enables the software engineer at the same time to develop models of the information domain and functional domain

DFD is refined into greater level of detailthe analyst performs an implicit (indirect) functional decomposition of the system

DFD refinement result corresponding refinement data implied in through process in the application

DFD takes an input ndashprocess-output view of a system that is data objects flow into the software are transformed by processing selements and resultant data objects flow out of the software

Data objects represented by labeled arrow and transformations are represented by circles also called bubbles

DFD is presented in hierarchical manner The first data flow model called a level 0 DFD or context diagram represent the

system as a wholeSubsequent data flow diagram providing increase detail with each subsequent level refine context diagram

The guidelines can aid immeasurably during derivation of a DFD 1The level 0 data flow diagram should describe the softwaresystem as a single bubble2primary input and output should be carefully noted3refinement should begin by isolating candidate processesdata objects and data stores to be represented at the next level4all arrows and bubbles should be labeled with meaning ful names5information flow continuity must be maintained from level to level6one bubble at a time should be refined

Context level DFD (level 0 DFD)The primary external entities (boxes) produce information for use by the system and consume information generated by the systemThe labeled arrows represent data objects or in hierarchiesExample Context ndashlevel(level 0) DFD for the security Safe home function

77

User command and data encompasses all configuration commandsall activationdeactivation commands all miscellaneous interactions and all data that are entered to expand a commandProcessing narrative

It is similar to the use-case in style but different in purpose it provides an overall description of the function to be developed It is not a scenario written from one actorrsquos point of view

The level 0 DFD expanded into a level 1 data flow model to proceed A simple even so effective approach is to perform a ldquogrammatical parserdquo on the processing narrative

that describes the context level bubbleThe following processing narrative text with the first occurance of all nouns underlined and the first occurrence of all verbs italicizedExample Safehome processing narrativeThe Safehome security function enables the homeowner to configure the security system when it is installedmonitors all sensors connected to the security and interacts with the homeowner through the Internet a PC or a control panel

Level 1 DFD for Safehome processesReferring to the grammatical parse verbs are represented as bubbles in a subsequent DFDNouns are either external entities (boxes)data or control objects (arrows) or data stored(double lines) that nouns and verbs can be associsated with one anotherFor example each sensor is assigned a number and type are attributes of the data object sensorTherefore by performing a grammatical parse on the processing narrative for a bubble at any DFD level

78

Level 2 DFD The processes represented at DFD level 1 can be further refined into lower levelsThe information flow continuity has been mainted between levels 0 and 1ExampleThe process monitor sensors can be refined into a level 2 DFD

The refinement of DFDs continues until each bubble performs a simple function that would be easily implemented as a program component

Creating A Control Flow Model

79

Control flow modeling used for a large class of applications are ldquodrivenrdquo by events rather than data produce control information rather than reports or displays and process information with heavy concern for time and performance

Already noted that an event or control item is implemented as a Boolean value ie true or false1 or 0 or a discrete list of conditions

The following guidelines to select potential(possible) candidate events-

o List all sensors that are ldquoreadrdquo by the softwareo List all interrupt conditionso List all ldquoswitches ldquothat are actuated by an operatoro List all data conditionso Recalling the nounverb parse that was applied to the processing narrativereview

all ldquocontrol itemsrdquo as possible for control flow inputsoutputso Describe the behavior of a system by identifying its statesidentify how each state

is reached and define the transitions between stateso Focus on possible omissions a very common error in specifying controlfor

example ask ldquoIs there any other way I can get this state or exit from itrdquoThe Control SpecificationThe control specification (CSPEC) represents the behavior of the system in two different ways 1 State diagram 2 Program activationState diagramIt is a sequential specification of behaviorProgram activationIt also contain a program activation table is a combinatorial specification of behavior

The CSPEC describes the behavior of the system but it gives us no information about the inner working of the process that are activated as aresult of this behaviorExampleThe state diagram indicates that the transitions from the idle state can occurTwo transitions occur out of the Monitoring system status state(1)when the system is deactivated a transition occurs back to the idle state(2) when a sensor is triggered a transition to the Acting Alarm state occurs During the review consider all transition and the content of all states

The Process Specification The process specification (PSPEC) is used to describe all flow model processes that

appear at the final level of refinement The content of the process specification can include narrative texta program design

language(PDL) description of the algorithmmathematical equations tablesdiagrams or charts

The PSPEC is a lsquomini specificationrdquofor each transform at the lowest refined level of a DFD that as a guide for design of the software component that will implement the process

Example The password transform represented in the flow model for Safehome the function is perform by PSPEC

80

If the password matches an entry within the table [valid id message=true] is passed to the message and status display functionIf there is no matah [valid id message=false]is passed to the message and status display function

CLASS-BASED MODELING Class-based element of an analysis modelClasses and objectsAttributesOperationsPackagesCRC modelsCollaborations diagram

Identifying Analysis ClassesTo identify classes by examining the pbolem statement or by performing a

ldquogrammatical parserdquo the use-cases or processing narratives developed for the system to be built Classes are determined by underlinining each noun or noun clause and enter it into a simple tableIf the class is required to implement a solution then it is part of the solution space other wise if a class is necessary only to describe a solution it is part of the problem space

The following ways are for Analysis classes to manifest (marked) themselves External entities that produce or consume information to be used by a computer-based

system (eg) devicespeople Things that are part of the information domain for the problem(eg) reports displays

leeterssignals Occurrences or events that occur within the context of system operation(eg)

aproperty transfer or the completion of a series of robot movements Roles played by who interact with the system(eg) manager engineersalesperson Organizational units that are relevant to an application(eg)division groupteam Places that establish the context of the problem and the overall function of the system

(eg) manufacturing floor ) Structures that define a class of objects or related classes of objects (eg)

sensors four-wheeled vehicles or computerBudd suggests taxonomy (classification) of classes that includes producers(sources0 and consumers(sinks) of datadata managerview and helper classes

A class should never have an ldquoimperative procedural namerdquo(eg) an object with the name Imageinersion would making mistake so that inversion of the image the inversion() is an operation that applied to the class image During early stage of modeling analysis class might be defined to the example of Safehome security function performed in a ldquogrammatical parserdquo on a processing narrativeExtracting the nouns each entry in the list a potential object

Coad and Yourdon suggest six selection characteristics that should be used as an analyst considers each potential class for inclusion in the analysis model

1Retained informationThe potential class will be useful during analysis only if information about it must be remembered so that the system can function

81

2Needed servicesThe potential class must have a set of identifiable operations that can change the value of its attributes in some way3Multiple attributesDuring requirement analysis the focus should be on ldquomajor ldquo information a class with a single attribute be useful during design but better to represent ed as an attribute of another class during the analysis activity4Common attributesA set of attributes can be defined for the potential class and these attributes apply to all instances of the class5Common operationsA set of operation can be defined for the potential class and these operations apply to all instances of the class6Essential requirements External entities that appear in the problem space and produce and consume information important to the operation of any solution for the system will almost always be defined as classes in the requirements modelSpecifying AttributesAttributes are the set of data objects that fully define the class within the context of the problemExample

SystemsystemIDverificationPhonenubersystemStatusdelaytimemasterpasswordprogram()display()reset()query()modify()

The shade portion is list of attributes for the system classDefining OperationsIt define the behavior of an object The types of operations are divided into three categories (1)operations that manipulate data egadingdeletingreformattingselecting (2)operations that perform a computation (3)operations that inquire about the state of an object (4)operations that monitor an object for the occurance of a controlling eventThese functions are accomplished by operating on attributes and associationsExample Safehome processing narrative the phrases indicate that a program() operation is encapsulated by the System classClass-Responsibility-Collaborator(CRC) ModelingClass-responsibility-collaborator modeling provides simple means for identifying and organizing the classes that are relevant to system or product requirementsAmbler describes CRC modeling in the following way A CRC model is a collection of standard index cards that represent classesThe cards are divided into three sectionsDESIGN WITHIN THE CONTEXT OF SOFTWARE ENGINEERING

Design Principle1Design should be traceable to the analysis model

82

2Always consider the architecture of the system to be built3Design of data is as important as design of processing functions4Interfaces both internal and external must be designed with care5User interface design should be tuned to the needs of the end-users6Component ndashlevel design should be functionally independent7Components should be loosely coupled to one another and to the environment8Design representation(models) should be easily understandable9The design should be developed iterativelyWith each iteration the designer should stive for greater simplicity

DESIGN PROCESS AND DESIGN QUALITYDesign process

bull Design process is a sequence of steps carried through which the requirements are translated into a system or software model bull Any design may be modeled as a direct graph The graphs are collection of entities with attributes which participate in relationships bull The system should be described at several different levels of abstraction bull Design takes place in overlapping stages bull Various phases of design process are as shown in following

1 In architectural design the subsystem components can be identified2 The abstract specification is used to specify the subsystems3 The interfaces between the subsystems are designed which is called inter face design4 In component design of subsystems components is done5 The data structure is designed to hold the data6 For perfoming the required functionality the appropriate algorithm is de

signed

Software design is an iterative process through which requirements are translated into a design for constructing the software

The design is represented at a high level of abstractiona level that can be directly traced to the specific system objective and more detailed datafunctional and behavioral requirements As design iteraton occur subsequent refinement to design representation at lower levels of abstraction

McGlaughin suggests three characteristics that serve as a guide for the evaluation of a good design Each of these characteristics is a goal of the design process

The design must implement all of the explicit requirements contained in the analysis model and it must accommodate all of the implicit(indirect) requirements desired by the customer

The design must be a readable understandable guide for those who generate code and for those who test and subsequently support the software

The design should provide a complete picture of the software addressing the data functional and behavioral domains from an implementation perspective

83

Quality guidelinesThe following gidelines to evaluate the quality of a design representation

1A design should display an architecture that (a) That has been created using recognizable architectural styles or patterns

(b)That is composed of components that show good design characteristics (c)That can be implemented in an evolutionary style thereby implementing and testing2A design should be modular that is the software should be logically partitioned into elements or subsystems3A design should contain distinct representation of dataarchitectureinterfaces and components4A design should lead to data structures that are appropriate for the classes to be implemented and are drawn from recognizable data patterns5A design should lead to components that show independent functional characteristics6A design should lead to interfaces that reduce the complexity of connections between components and with the external environmemt7A design should be derived using a repeatable method that is driven by information obtained during software requirements analysis8A design should be represented using a notation that effectively communicates its meaning

Quality attributesHewlett Packard deveopled a set of software quality attributes are given as acronym(short form) FURPS to represent a target(goal) for all software design

Functionality Usability Reliability Performance Supportability

FunctionalityIt is assessed by evaluating the feature set and capabilities of the programthe generalization of the functions that are deliveredand the security of the overall systemUsabilityIt is assessed by human factors consistency and documentationReliabilityIt is evaluated by measuring the frequency and severity of failurethe accuracy of output resultsthe mean-time-to-failure(MTTF) the ability to recover from failure and predictability(unavoidability) of the programPerformanceIt is measured by processing speedresponse timeresource consumption throughput and efficiencySupportabilityItcombin the abilitytoxtendtheprogram(extensibility)adaptabilityServiceabilitymainabilitytestabilitycompatibilityconfigurability the ability to organize and control elements of the software congfiguration

Design Principles Davis suggested a set of principles for software design as

bull The design process should not suffer from ldquotunnel visionrdquobull The design should be traceable to the analysis modelbull The design should not reinvent the wheel

84

bull The design should ldquominimize the intellectual distancerdquo between the software and the problem in the real worldbull The design should exhibit uniformity and integrationbull The design should be structured to degrade gentlybull Design is not coding and coding is not designbull The design should be assessed for qualitybull The design should be reviewed to minimize conceptual errors

Design Concept

The software design concept provides a framework for implementing the right software

Following issues are considered while designing the software1Abstraction At each stage of software design process levels of abstractions should be applied to refine the software solutionAt the higher level of abstraction the solution should be stated in broad terms and in the lower level more detailed description of the solution is given While moving through different levels of abstraction the procedural abstraction and data abstraction is created In procedural abstraction it gives the named sequence of instruction in the specific function In data abstracion the collection of data objects is represented Levels of Abstraction Various levels of abstractions are- Level I - This level represents the solution interms of problem environment Level II - This level represents the decomposition of terms that are moved from problem environment but still not at implementation stage Level III - At this level preliminary procedural representation exists All the terminologies at this level are software oriented and implementation modularity begins at the surface Level IV and V - The concepts of stepwise refinement and modularity are

applied at this level2 Modularity

The software is divided into separately named and addressable components that called as modules Creating such models bring the modularity in siftwareMeyer defines five criteria that enable us to evaluate a design method with respect to its ability to define an effective modular systemModular decomposability A design method provides a systematic mechanism for decomposing the problem into sub-problems This reduces the complexity of the problem and the modularity can be achievedModular composability A design method enables existing design components to be assembled into a new systemModular understandability A module can be understood as a standalone unit Then it will be easier to build and easier to changeModular continuity Small changes to the system requirements result in changes to individual modules rather than system- wide changesModular protection An aberrant condition occurs within a module and its effects are constrained within the module3Refinement

Refinement is actually a process of elaborationStepwise refinement is a top-down design strategy proposed by Niklaus WIRTHThe architecture of a program is developed by successively refining levels of procedural detail

85

The process of program refinement is analogues to the process of refinement and partitioning that is used during requirements analysisAbstraction and refinement are complementary concepts The major difference is that - in the abstraction low-level details are suppressedRefinement helps the designer to elaborate low-levels detailsModular Design

Modular design reduces complexity and helps in easier implementation The parallel development of different parts of the system is possible due to modular designWhat is the benefit of modular design Changes made during testing and maintenance becomes manageable and they do not affect other modules Various quality parameters for effective modular design are -1) Functional independance 2) Cohesion 3) Coupling

Functional IndependenceThe functional independence can be achieved be developing the functional modules

with single-minded approachBy using functional independence functions may be compartmentalized and interfaces are simplifiedVarious types of coupling are i) Data coupling - The data coupling is possible by parameter passing or data interactionii) Control coupling - The modules share related control data in control couplingiii) Commom coupling - Content coupling occurs when one module makes use of data or control information maintained in another moduleFan-out Fan-out is a measure of the number of immediate subordinates to a moule The fan-out should be within some limit in the design If fan-out is very high then it indicates that a single module is controlling many other modules Preferably limit fan-out to no more than sevenFan-in

Fan-in indicates how many modules directly control a given module Modules with fan-in must have good cohesion Each interfac to the module must have the same number and types of parametersFactoring

Factoring means separation of function into new modules By applying factoring the size of module is reduced and thereby the complexity of the problem is reduced This also provides duplication of functions in more than one module The effective factoring brings simplification in the implementation of software design DESIGN HEURISTICS

The program structure can be manipulated according the design heuristics as shon below1Evaluate the first iteration of the program structure to reduce the coupling and improve cohesion The module independency can be achieved in the program structure by exploding or imploding the modules Exploding the modules means obtaining two or more modules in the final stage and imploding the modules means combining the result of different modules2Attempt to minimize the structure with high fan-out and strive for fan-in as depth increase At the higher level of program structure the distribution of control should be made Fan-out means number of immediate subordinates to the module Fan-in means number of immediate ancestores the module have

86

3Keep scope of the effect of a module within the scope of control of that module The decisions made in particular module lsquoarsquo should not affect the module rsquo brsquo which lies outside the scope of module lsquoarsquo4Evaluate the module interfaces to reduce complexity and redundancy and improve consistency Mostly the cause of softwatr errors is module interfaces The module interfaces should simply pass the information and should be consistent with the module5Define module whose function is predicatable but avoid modules that are too restrictive The module should be designed with simplified internal processing so that expected data can be produced as a result The modules should not restrict the size of local data structure options with control flow or modes of external interfaces Being module too much restrictive causes large maintenance6Strive for controlled entry modules by avoiding pathological connections Software interfaces should be constrained and controlled so that it will become manageable Pathological connection means many references or branches into the middle of a module

Design ModelThe design model is represented as pyramid The pyramid is a stable object

Representing design model in this way means that the software design should be stableThe design model has braod foundation of data design stable mid-region with architectural and interface design and the sharp point to for component level design

Advantages of horizontal partition1These are easy to test maintain and extend 2They have fewer side effects in change propagation or error propagation

Disadvantages of horizontal partitionMore data has to be passed across module interfaces which complicates the overall

control of program flowVertical partitioning

Vertical partitioning suggests the control and work should be distributed top-down in program structureIn vertical partitioning

Define separate branches of the module hierarchy for each major functionUse control modules to co-ordinate communication between functions

Advantages of vertical partition1These are easy to maintain the changes2 They reduce the change impact and error propagation

DATA DESIGNData design is basically the model of data that is represented at the high level of abstractionThe data design is then progressively refined to create implementation specific representationsVarious elements of data design are

Data object - The data objects are identified and relationship among various data objects can be represented using entity relationship diagrams or data dictionariesDatabases - Using software design model the data models are translated into data structures and databases at the application level

87

Data warehouses - At the business level useful information is identified from various databases and the data warehouses are created For extracting or navigating the useful business information stored in the huge data warehouse then data mining techniques are applied

ARCHITECTURAL DESIGNSoftware architecture The design process for identifying the sub-systems making up a system and the framework for sub-system control and communication is architectural design The output of this design process is a description of the software architecture

Architectural design An early stage of the system design process Represents the link between specification and design processes Often carried out in parallel with some specification activities It involves identifying major system components and their communicationsArchitecture and system characteristics Performancebull Localise critical operations and minimise communications Use large rather than fine-grain components Securitybull Use a layered architecture with critical assets in the inner layers Safetybull Localise safety-critical features in a small number of sub-systems Availabilitybull Include redundant components and mechanisms for fault tolerance Maintainabilitybull Use fine-grain replaceable components

Architectural design decisions Is there a generic application architecture that can be used How will the system be distributed What architectural styles are appropriate What approach will be used to structure the system How will the system be decomposed into modules What control strategy should be used How will the architectural design be evaluated How should the architecture be documentedArchitectural styles The architectural model of a system may conform to a generic architectural model or style An awareness of these styles can simplify the problem of defining system architectures However most large systems are heterogeneous and do not follow a single architectural styleArchitectural models

Used to document an architectural design Static structural model that shows the major system components Dynamic process model that shows the process structure of the system Interface model that defines sub-system interfaces

88

Relationships model such as a data-flow model that shows sub-system relationships Distribution model that shows how sub-systems are distributed across computers

Modular decomposition Another structural level where sub-systems are decomposed into modules Two modular decomposition models coveredbull An object model where the system is decomposed into interacting objectbull A pipeline or data-flow model where the system is decomposed into functional modules which transform inputs to outputs If possible decisions about concurrency should be delayed until modules are implemented

Object models Structure the system into a set of loosely coupled objects with well-defined interfaces Object-oriented decomposition is concerned with identifying object classes their attributes and operations When implemented objects are created from these classes and some control model used to coordinate object operations

Invoice Processing system

Pipeline model advantages Supports transformation reuse Intuitive organisation for stakeholder communication Easy to add new transformations Relatively simple to implement as either a concurrent or sequential system However requires a common format for data transfer along the pipeline and difficult

to support event-based interaction

User interface design

The user interface User interfaces should be designed to match the skills experience and expectations of

its anticipated users System users often judge a system by its interface rather than its functionality A poorly designed interface can cause a user to make catastrophic errors Poor user interface design is the reason why so many software systems are never

usedUser interface Design Principle

89

Design principles User familiaritybull The interface should be based on user-oriented terms and concepts rather than computer concepts For example an office system should use concepts such as letters documents folders etc rather than directories file identifiers etc Consistencybull The system should display an appropriate level of consistency Commands and menus should have the same format command punctuation should be similar etc Minimal surprisebull If a command operates in a known way the user should be able to predict the operation of comparable commandsbull Recoverabilitybull The system should provide some resilience to user errors and allow the user to recover from errors This might include an undo facility confirmation of destructive actions soft deletes etcbull User guidancebull Some user guidance such as help systems on-line manuals etc should be suppliedbull User diversitybull Interaction facilities for different types of user should be supported For example some users have seeing difficulties and so larger text should be available

REAL-TIME SOFTWARE DESIGNReal-time systemsSystems which monitor and control their environmentInevitably associated with hardware devices

bull Sensors Collect data from the system environmentbull Actuators Change (in some way) the systems environment

Time is critical Real-time systems must respond within specified times

Definition A real-time system is a software system where the correct functioning of the

system depends on the results produced by the system and the time at which these results are produced

90

A soft real-time system is a system whose operation is degraded if results are not produced according to the specified timing requirements

A hard real-time system is a system whose operation is incorrect if results are not produced according to the timing specification

StimulusResponse Systems Given a stimulus the system must produce a response within a specified timePeriodic stimuli Stimuli which occur at predictable time intervals

bull For example a temperature sensor may be polled 10 times per secondAperiodic stimuli Stimuli which occur at unpredictable times

bull For example a system power failure may trigger an interrupt which must be processed by the system

Architectural considerations Because of the need to respond to timing demands made by different

stimuliresponses the system architecture must allow for fast switching between stimulus handlers

Timing demands of different stimuli are different so a simple sequential loop is not usually adequate

Real-time systems are therefore usually designed as cooperating processes with a real-time executive controlling these processes

A real-time system model

Real-timecontrol system

ActuatorActuator ActuatorActuator

SensorSensorSensor SensorSensorSensor

Sensoractuator processes

Dataprocessor

Actuatorcontrol

Actuator

Sensorcontrol

Sensor

Stimulus Response

System elementsSensor control processes

bull Collect information from sensors May buffer information collected in response to a sensor stimulus

Data processorbull Carries out processing of collected information and computes the system

responseActuator control processes

91

bull Generates control signals for the actuatorsReal-time programmingHard-real time systems may have to programmed in assembly language to ensure that deadlines are metLanguages such as C allow efficient programs to be written but do not have constructs to support concurrency or shared resource management

Java as a real-time languageJava supports lightweight concurrency (threads and synchronized methods) and can be used for some soft real-time systemsJava 20 is not suitable for hard RT programming but real-time versions of Java are now available that address problems such as

bull Not possible to specify thread execution timebull Different timing in different virtual machinesbull Uncontrollable garbage collectionbull Not possible to discover queue sizes for shared resourcesbull Not possible to access system hardwarebull Not possible to do space or timing analysis

SYSTEM DESIGN Design both the hardware and the software associated with system

Partition functions to either hardware or software Design decisions should be made on the basis on non-functional

system requirements Hardware delivers better performance but potentially longer

development and less scope for changeR-T systems design process

Identify the stimuli to be processed and the required responses to these stimuli For each stimulus and response identify the timing constraints Aggregate the stimulus and response processing into concurrent processes A

process may be associated with each class of stimulus and response Design algorithms to process each class of stimulus and response These must

meet the given timing requirements Design a scheduling system which will ensure that processes are started in time to

meet their deadlines Integrate using a real-time operating system

Timing constraints May require extensive simulation and experiment to ensure that these are met by the systemMay mean that certain design strategies such as object-oriented design cannot be used because of the additional overhead involvedMay mean that low-level programming language features have to be used for performance reasons

Real-time system modellingThe effect of a stimulus in a real-time system may trigger a transition from one state to anotherFinite state machines can be used for modelling real-time systems

92

However FSM models lack structure Even simple systems can have a complex modelThe UML includes notations for defining state machine models

Petrol pump state model

Cardinserted

into reader

Timeout

Resettingdo display CC

error

Initialising

do initialisedisplay

Paying

Stopped

Reading

do get CCdetails

Waiting

do display welcome

dodeliver fuel

do debitCC account

Payment ack

Ready Delivering

update displayNozzle

trigger on

Nozzle trigger off

Nozzle trigger on

Hose inholster

do validatecredit card

Validating

Invalid card

Card removedCard OK

Hose out of holster

Timeout

Real-time operating systems(RTOS)

Real-time operating systems are specialised operating systems which manage the processes in the RTS

Responsible for process management and resource (processor and memory) allocation

May be based on a standard kernel which is used unchanged or modified for a particular application

Do not normally include facilities such as file management

Operating system componentsReal-time clock

bull Provides information for process schedulingInterrupt handler

bull Manages aperiodic requests for serviceScheduler

bull Chooses the next process to be runResource manager

bull Allocates memory and processor resourcesDispatcher

bull Starts process executionNon-stop system components

Configuration manager

93

bull Responsible for the dynamic reconfiguration of the system software and hardware Hardware modules may be replaced and software upgraded without stopping the systems

Fault managerbull Responsible for detecting software and hardware faults and taking appropriate

actions (eg switching to backup disks) to ensure that the system continues in operation

Real-time OS components

Process resourcerequirements

Scheduler

Schedulinginformation

Resourcemanager

Despatcher

Real-timeclock

Processesawaiting

resources

Readylist

Interrupthandler

Availableresource

list

Processorlist

Executing process

Readyprocesses

Releasedresources

Process priority The processing of some types of stimuli must sometimes take priority Interrupt level priority Highest priority which is allocated to processes requiring a

very fast response Clock level priority Allocated to periodic processes Within these further levels of priority may be assigned

Interrupt servicing Control is transferred automatically to a pre-determined memory location This location contains an instruction to jump to

an interrupt service routine Further interrupts are disabled the interrupt

serviced and control returned to the interrupted process

Interrupt service routines must be short simple and fast

Periodic process servicing In most real-time systems there will be several classes of periodic process each with

different periods (the time between executions) execution times and deadlines (the time by which processing must be completed)

The real-time clock ticks periodically and each tick causes an interrupt which schedules the process manager for periodic processes

The process manager selects a process which is ready for execution

Process managementbull Concerned with managing the set of concurrent processes

94

bull Periodic processes are executed at pre-specified time intervalsbull The RTOS uses the real-time clock to determine when to execute a process

taking into accountbull Process period - time between executionsbull Process deadline - the time by which processing must be complete

RTE(Real Time Execution Process) process managementResource manager

Allocate memoryand processor

Scheduler

Choose processfor execution

Despatcher

Start execution on anavailable processor

Process switchingbull The scheduler chooses the next process to be executed by the processor This

depends on a scheduling strategy which may take the process priority into account

bull The resource manager allocates memory and a processor for the process to be executed

bull The dispatcher takes the process from ready list loads it onto a processor and starts execution

Scheduling strategiesNon pre-emptive scheduling

bull Once a process has been scheduled for execution it runs to completion or until it is blocked for some reason (eg waiting for IO)

Pre-emptive schedulingbull The execution of an executing processes may be stopped if a higher priority

process requires serviceScheduling algorithms

bull Round-robinbull Rate monotonicbull Shortest deadline first

Monitoring and control systemsbull Important class of real-time systems bull Continuously check sensors and take actions

depending on sensor valuesbull Monitoring systems examine sensors and

report their resultsbull Control systems take sensor values and control hardware actuators

Generic architecture

95

S1

S2

S3

P (S1)

P (S2)

P (S1)

Monitoringprocesses

Controlprocesses

P (A1)

P (A2)

P (A1)

A1

A2

A3

P (A4) A4

Testingprocess

Control panelprocesses

Burglar alarm systembull A system is required to monitor sensors on doors and windows to detect the

presence of intruders in a buildingbull When a sensor indicates a break-in the system switches on lights around the

area and calls police automaticallybull The system should include provision for operation without a mains power

supply Sensorso Movement detectors window sensors door sensorso 50 window sensors 30 door sensors and 200 movement detectorso Voltage drop sensor Actionso When an intruder is detected police are called automaticallyo Lights are switched on in rooms with active sensorso An audible alarm is switched on

The R-T system design process

bull Identify stimuli and associated responsesbull Define the timing constraints associated with each stimulus and responsebull Allocate system functions to concurrent processesbull Design algorithms for stimulus processing and response generationbull Design a scheduling system which ensures that processes will always be

scheduled to meet their deadlinesStimuli to be processed

Power failurebull Generated aperiodically by a circuit monitor When received the system must

switch to backup power within 50 msIntruder alarm

bull Stimulus generated by system sensors Response is to call the police switch on building lights and the Power failure

bull Generated aperiodically by a circuit monitor When received the system must switch to backup power within 50 ms

bull Intruder alarmbull Stimulus generated by system sensors Response is to call the police switch

on building lights and the audible alarmbull audible alarm

Burglar alarm system processes

96

Lighting controlprocess

Audible alarmprocess

Voice synthesiserprocess

Alarm systemprocess

Power switchprocess

Building monitorprocess

Communicationprocess

Door sensorprocess

Movementdetector process

Window sensorprocess

560 Hz

60 Hz400 Hz 100 Hz

Power failureinterrupt

Alarm system

Building monitor

Alarm system

Alarm system

Alarm system

Detector status Sensor status Sensor status

Room number

Alert message

Room number

Room number

Building_monitor process 1

class BuildingMonitor extends Thread

BuildingSensor win door move

Siren siren = new Siren () Lights lights = new Lights () Synthesizer synthesizer = new Synthesizer () DoorSensors doors = new DoorSensors (30) WindowSensors windows = new WindowSensors (50) MovementSensors movements = new MovementSensors (200) PowerMonitor pm = new PowerMonitor ()

BuildingMonitor() initialise all the sensors and start the processessirenstart () lightsstart () synthesizerstart () windowsstart () doorsstart () movementsstart () pmstart ()

Building monitor process 2public void run () int room = 0 while (true) poll the movement sensors at least twice per second (400 Hz)move = movementsgetVal () poll the window sensors at least twicesecond (100 Hz)win = windowsgetVal () poll the door sensors at least twice per second (60 Hz)door = doorsgetVal ()

97

if (movesensorVal == 1 | doorsensorVal == 1 | winsensorVal == 1) a sensor has indicated an intruder if (movesensorVal == 1) room = moveroom if (doorsensorVal == 1) room = doorroom if (winsensorVal == 1 ) room = winroom lightson (room) sirenon () synthesizeron (room) break Building_monitor process 3 lightsshutdown () sirenshutdown () synthesizershutdown () windowsshutdown () doorsshutdown () movementsshutdown ()

run BuildingMonitor

Control systems

bull A burglar alarm system is primarily a monitoring system It collects data from sensors but no real-time actuator control

bull Control systems are similar but in response to sensor values the system sends control signals to actuators

bull An example of a monitoring and control system is a system that monitors temperature and switches heaters on and off

A temperature control system

Thermostatprocess

Sensorprocess

Furnacecontrol process

Heater controlprocess

500 Hz

500 Hz

Thermostat process500 Hz

Sensorvalues

Switch commandRoom number

DATA ACQUISITION SYSTEMSbull Collect data from sensors for subsequent processing and analysisbull Data collection processes and processing processes may have different periods

and deadlines bull Data collection may be faster than processing eg collecting information about

an explosion bull Circular or ring buffers are a mechanism for smoothing speed differences

The generic Architecture of data acquicition

98

DisplayProcess

dataSensor data

bufferSensorprocess

Sensoridentifier and

value

Sensors (each data flow is a sensor value)

Sensoridentifier and

value

Processdata

Sensor databuffer

Sensorprocess

Sensoridentifier and

value

Sensoridentifier and

value

s1

s2

s3

s4

s5

s6

In data acquisition systemsthe sensor may be generating data quickly and the key problem is to ensure that a sensor is allocated before sensor value changeThe essenitial features of this architecture is each group of sensors has three processes associated with it and convert analogue data to digital values if necessary a buffer process and a process that consumes the data carried out further processing Two groups sensors s1-s3 and s4-s6 on the right side a further procee that diplsys the sensor data Neutron flux data acquisition

Operatordisplay

Fluxprocessing

Flux databuffer

A-Dconvertor

Sensoridentifier and

flux valueProcessedflux level

Neutron flux sensors

bull A system collects data from a set of sensors monitoring the neutron flux from a nuclear reactor

bull Each sensor has a process that converts the analog input flux level into a digita signalIt passes this flux level with sensor identifies to the sensor data buffer the data processing takes the data from this bufferprocesses it and pass it to display process for output on an operator display

A ring buffer

Consumerprocess

Producerprocess

Mutual exclusionbull Producer processes collect data and add it to the buffer Consumer processes

take data from the buffer and make elements availablebull Producer and consumer processes must be mutually excluded from accessing

the same elementThe buffer must stop producer processes adding information to a full buffer and consumer processes trying to take information from an empty buffer

99

Page 9: Unit_III

These prompts and the dscision associated with them fall within the Interrface swimlane but arrows from that swimlane back to the Homeowner swimlane where homeowner actions occur

FLOW-ORIENTED MODELING Data flow-oriented modeling is one of the most used analysis notations is a core modeling activity in structured analysis

Elements of flow-oriented modelingCreating a Data flow modelProcessing narratives Creating a Control flow model The Control SpecificationThe Process SpecificationCreating a Data Flow Model

The data flow diagram enables the software engineer at the same time to develop models of the information domain and functional domain

DFD is refined into greater level of detailthe analyst performs an implicit (indirect) functional decomposition of the system

DFD refinement result corresponding refinement data implied in through process in the application

DFD takes an input ndashprocess-output view of a system that is data objects flow into the software are transformed by processing selements and resultant data objects flow out of the software

Data objects represented by labeled arrow and transformations are represented by circles also called bubbles

DFD is presented in hierarchical manner The first data flow model called a level 0 DFD or context diagram represent the

system as a wholeSubsequent data flow diagram providing increase detail with each subsequent level refine context diagram

The guidelines can aid immeasurably during derivation of a DFD 1The level 0 data flow diagram should describe the softwaresystem as a single bubble2primary input and output should be carefully noted3refinement should begin by isolating candidate processesdata objects and data stores to be represented at the next level4all arrows and bubbles should be labeled with meaning ful names5information flow continuity must be maintained from level to level6one bubble at a time should be refined

Context level DFD (level 0 DFD)The primary external entities (boxes) produce information for use by the system and consume information generated by the systemThe labeled arrows represent data objects or in hierarchiesExample Context ndashlevel(level 0) DFD for the security Safe home function

77

User command and data encompasses all configuration commandsall activationdeactivation commands all miscellaneous interactions and all data that are entered to expand a commandProcessing narrative

It is similar to the use-case in style but different in purpose it provides an overall description of the function to be developed It is not a scenario written from one actorrsquos point of view

The level 0 DFD expanded into a level 1 data flow model to proceed A simple even so effective approach is to perform a ldquogrammatical parserdquo on the processing narrative

that describes the context level bubbleThe following processing narrative text with the first occurance of all nouns underlined and the first occurrence of all verbs italicizedExample Safehome processing narrativeThe Safehome security function enables the homeowner to configure the security system when it is installedmonitors all sensors connected to the security and interacts with the homeowner through the Internet a PC or a control panel

Level 1 DFD for Safehome processesReferring to the grammatical parse verbs are represented as bubbles in a subsequent DFDNouns are either external entities (boxes)data or control objects (arrows) or data stored(double lines) that nouns and verbs can be associsated with one anotherFor example each sensor is assigned a number and type are attributes of the data object sensorTherefore by performing a grammatical parse on the processing narrative for a bubble at any DFD level

78

Level 2 DFD The processes represented at DFD level 1 can be further refined into lower levelsThe information flow continuity has been mainted between levels 0 and 1ExampleThe process monitor sensors can be refined into a level 2 DFD

The refinement of DFDs continues until each bubble performs a simple function that would be easily implemented as a program component

Creating A Control Flow Model

79

Control flow modeling used for a large class of applications are ldquodrivenrdquo by events rather than data produce control information rather than reports or displays and process information with heavy concern for time and performance

Already noted that an event or control item is implemented as a Boolean value ie true or false1 or 0 or a discrete list of conditions

The following guidelines to select potential(possible) candidate events-

o List all sensors that are ldquoreadrdquo by the softwareo List all interrupt conditionso List all ldquoswitches ldquothat are actuated by an operatoro List all data conditionso Recalling the nounverb parse that was applied to the processing narrativereview

all ldquocontrol itemsrdquo as possible for control flow inputsoutputso Describe the behavior of a system by identifying its statesidentify how each state

is reached and define the transitions between stateso Focus on possible omissions a very common error in specifying controlfor

example ask ldquoIs there any other way I can get this state or exit from itrdquoThe Control SpecificationThe control specification (CSPEC) represents the behavior of the system in two different ways 1 State diagram 2 Program activationState diagramIt is a sequential specification of behaviorProgram activationIt also contain a program activation table is a combinatorial specification of behavior

The CSPEC describes the behavior of the system but it gives us no information about the inner working of the process that are activated as aresult of this behaviorExampleThe state diagram indicates that the transitions from the idle state can occurTwo transitions occur out of the Monitoring system status state(1)when the system is deactivated a transition occurs back to the idle state(2) when a sensor is triggered a transition to the Acting Alarm state occurs During the review consider all transition and the content of all states

The Process Specification The process specification (PSPEC) is used to describe all flow model processes that

appear at the final level of refinement The content of the process specification can include narrative texta program design

language(PDL) description of the algorithmmathematical equations tablesdiagrams or charts

The PSPEC is a lsquomini specificationrdquofor each transform at the lowest refined level of a DFD that as a guide for design of the software component that will implement the process

Example The password transform represented in the flow model for Safehome the function is perform by PSPEC

80

If the password matches an entry within the table [valid id message=true] is passed to the message and status display functionIf there is no matah [valid id message=false]is passed to the message and status display function

CLASS-BASED MODELING Class-based element of an analysis modelClasses and objectsAttributesOperationsPackagesCRC modelsCollaborations diagram

Identifying Analysis ClassesTo identify classes by examining the pbolem statement or by performing a

ldquogrammatical parserdquo the use-cases or processing narratives developed for the system to be built Classes are determined by underlinining each noun or noun clause and enter it into a simple tableIf the class is required to implement a solution then it is part of the solution space other wise if a class is necessary only to describe a solution it is part of the problem space

The following ways are for Analysis classes to manifest (marked) themselves External entities that produce or consume information to be used by a computer-based

system (eg) devicespeople Things that are part of the information domain for the problem(eg) reports displays

leeterssignals Occurrences or events that occur within the context of system operation(eg)

aproperty transfer or the completion of a series of robot movements Roles played by who interact with the system(eg) manager engineersalesperson Organizational units that are relevant to an application(eg)division groupteam Places that establish the context of the problem and the overall function of the system

(eg) manufacturing floor ) Structures that define a class of objects or related classes of objects (eg)

sensors four-wheeled vehicles or computerBudd suggests taxonomy (classification) of classes that includes producers(sources0 and consumers(sinks) of datadata managerview and helper classes

A class should never have an ldquoimperative procedural namerdquo(eg) an object with the name Imageinersion would making mistake so that inversion of the image the inversion() is an operation that applied to the class image During early stage of modeling analysis class might be defined to the example of Safehome security function performed in a ldquogrammatical parserdquo on a processing narrativeExtracting the nouns each entry in the list a potential object

Coad and Yourdon suggest six selection characteristics that should be used as an analyst considers each potential class for inclusion in the analysis model

1Retained informationThe potential class will be useful during analysis only if information about it must be remembered so that the system can function

81

2Needed servicesThe potential class must have a set of identifiable operations that can change the value of its attributes in some way3Multiple attributesDuring requirement analysis the focus should be on ldquomajor ldquo information a class with a single attribute be useful during design but better to represent ed as an attribute of another class during the analysis activity4Common attributesA set of attributes can be defined for the potential class and these attributes apply to all instances of the class5Common operationsA set of operation can be defined for the potential class and these operations apply to all instances of the class6Essential requirements External entities that appear in the problem space and produce and consume information important to the operation of any solution for the system will almost always be defined as classes in the requirements modelSpecifying AttributesAttributes are the set of data objects that fully define the class within the context of the problemExample

SystemsystemIDverificationPhonenubersystemStatusdelaytimemasterpasswordprogram()display()reset()query()modify()

The shade portion is list of attributes for the system classDefining OperationsIt define the behavior of an object The types of operations are divided into three categories (1)operations that manipulate data egadingdeletingreformattingselecting (2)operations that perform a computation (3)operations that inquire about the state of an object (4)operations that monitor an object for the occurance of a controlling eventThese functions are accomplished by operating on attributes and associationsExample Safehome processing narrative the phrases indicate that a program() operation is encapsulated by the System classClass-Responsibility-Collaborator(CRC) ModelingClass-responsibility-collaborator modeling provides simple means for identifying and organizing the classes that are relevant to system or product requirementsAmbler describes CRC modeling in the following way A CRC model is a collection of standard index cards that represent classesThe cards are divided into three sectionsDESIGN WITHIN THE CONTEXT OF SOFTWARE ENGINEERING

Design Principle1Design should be traceable to the analysis model

82

2Always consider the architecture of the system to be built3Design of data is as important as design of processing functions4Interfaces both internal and external must be designed with care5User interface design should be tuned to the needs of the end-users6Component ndashlevel design should be functionally independent7Components should be loosely coupled to one another and to the environment8Design representation(models) should be easily understandable9The design should be developed iterativelyWith each iteration the designer should stive for greater simplicity

DESIGN PROCESS AND DESIGN QUALITYDesign process

bull Design process is a sequence of steps carried through which the requirements are translated into a system or software model bull Any design may be modeled as a direct graph The graphs are collection of entities with attributes which participate in relationships bull The system should be described at several different levels of abstraction bull Design takes place in overlapping stages bull Various phases of design process are as shown in following

1 In architectural design the subsystem components can be identified2 The abstract specification is used to specify the subsystems3 The interfaces between the subsystems are designed which is called inter face design4 In component design of subsystems components is done5 The data structure is designed to hold the data6 For perfoming the required functionality the appropriate algorithm is de

signed

Software design is an iterative process through which requirements are translated into a design for constructing the software

The design is represented at a high level of abstractiona level that can be directly traced to the specific system objective and more detailed datafunctional and behavioral requirements As design iteraton occur subsequent refinement to design representation at lower levels of abstraction

McGlaughin suggests three characteristics that serve as a guide for the evaluation of a good design Each of these characteristics is a goal of the design process

The design must implement all of the explicit requirements contained in the analysis model and it must accommodate all of the implicit(indirect) requirements desired by the customer

The design must be a readable understandable guide for those who generate code and for those who test and subsequently support the software

The design should provide a complete picture of the software addressing the data functional and behavioral domains from an implementation perspective

83

Quality guidelinesThe following gidelines to evaluate the quality of a design representation

1A design should display an architecture that (a) That has been created using recognizable architectural styles or patterns

(b)That is composed of components that show good design characteristics (c)That can be implemented in an evolutionary style thereby implementing and testing2A design should be modular that is the software should be logically partitioned into elements or subsystems3A design should contain distinct representation of dataarchitectureinterfaces and components4A design should lead to data structures that are appropriate for the classes to be implemented and are drawn from recognizable data patterns5A design should lead to components that show independent functional characteristics6A design should lead to interfaces that reduce the complexity of connections between components and with the external environmemt7A design should be derived using a repeatable method that is driven by information obtained during software requirements analysis8A design should be represented using a notation that effectively communicates its meaning

Quality attributesHewlett Packard deveopled a set of software quality attributes are given as acronym(short form) FURPS to represent a target(goal) for all software design

Functionality Usability Reliability Performance Supportability

FunctionalityIt is assessed by evaluating the feature set and capabilities of the programthe generalization of the functions that are deliveredand the security of the overall systemUsabilityIt is assessed by human factors consistency and documentationReliabilityIt is evaluated by measuring the frequency and severity of failurethe accuracy of output resultsthe mean-time-to-failure(MTTF) the ability to recover from failure and predictability(unavoidability) of the programPerformanceIt is measured by processing speedresponse timeresource consumption throughput and efficiencySupportabilityItcombin the abilitytoxtendtheprogram(extensibility)adaptabilityServiceabilitymainabilitytestabilitycompatibilityconfigurability the ability to organize and control elements of the software congfiguration

Design Principles Davis suggested a set of principles for software design as

bull The design process should not suffer from ldquotunnel visionrdquobull The design should be traceable to the analysis modelbull The design should not reinvent the wheel

84

bull The design should ldquominimize the intellectual distancerdquo between the software and the problem in the real worldbull The design should exhibit uniformity and integrationbull The design should be structured to degrade gentlybull Design is not coding and coding is not designbull The design should be assessed for qualitybull The design should be reviewed to minimize conceptual errors

Design Concept

The software design concept provides a framework for implementing the right software

Following issues are considered while designing the software1Abstraction At each stage of software design process levels of abstractions should be applied to refine the software solutionAt the higher level of abstraction the solution should be stated in broad terms and in the lower level more detailed description of the solution is given While moving through different levels of abstraction the procedural abstraction and data abstraction is created In procedural abstraction it gives the named sequence of instruction in the specific function In data abstracion the collection of data objects is represented Levels of Abstraction Various levels of abstractions are- Level I - This level represents the solution interms of problem environment Level II - This level represents the decomposition of terms that are moved from problem environment but still not at implementation stage Level III - At this level preliminary procedural representation exists All the terminologies at this level are software oriented and implementation modularity begins at the surface Level IV and V - The concepts of stepwise refinement and modularity are

applied at this level2 Modularity

The software is divided into separately named and addressable components that called as modules Creating such models bring the modularity in siftwareMeyer defines five criteria that enable us to evaluate a design method with respect to its ability to define an effective modular systemModular decomposability A design method provides a systematic mechanism for decomposing the problem into sub-problems This reduces the complexity of the problem and the modularity can be achievedModular composability A design method enables existing design components to be assembled into a new systemModular understandability A module can be understood as a standalone unit Then it will be easier to build and easier to changeModular continuity Small changes to the system requirements result in changes to individual modules rather than system- wide changesModular protection An aberrant condition occurs within a module and its effects are constrained within the module3Refinement

Refinement is actually a process of elaborationStepwise refinement is a top-down design strategy proposed by Niklaus WIRTHThe architecture of a program is developed by successively refining levels of procedural detail

85

The process of program refinement is analogues to the process of refinement and partitioning that is used during requirements analysisAbstraction and refinement are complementary concepts The major difference is that - in the abstraction low-level details are suppressedRefinement helps the designer to elaborate low-levels detailsModular Design

Modular design reduces complexity and helps in easier implementation The parallel development of different parts of the system is possible due to modular designWhat is the benefit of modular design Changes made during testing and maintenance becomes manageable and they do not affect other modules Various quality parameters for effective modular design are -1) Functional independance 2) Cohesion 3) Coupling

Functional IndependenceThe functional independence can be achieved be developing the functional modules

with single-minded approachBy using functional independence functions may be compartmentalized and interfaces are simplifiedVarious types of coupling are i) Data coupling - The data coupling is possible by parameter passing or data interactionii) Control coupling - The modules share related control data in control couplingiii) Commom coupling - Content coupling occurs when one module makes use of data or control information maintained in another moduleFan-out Fan-out is a measure of the number of immediate subordinates to a moule The fan-out should be within some limit in the design If fan-out is very high then it indicates that a single module is controlling many other modules Preferably limit fan-out to no more than sevenFan-in

Fan-in indicates how many modules directly control a given module Modules with fan-in must have good cohesion Each interfac to the module must have the same number and types of parametersFactoring

Factoring means separation of function into new modules By applying factoring the size of module is reduced and thereby the complexity of the problem is reduced This also provides duplication of functions in more than one module The effective factoring brings simplification in the implementation of software design DESIGN HEURISTICS

The program structure can be manipulated according the design heuristics as shon below1Evaluate the first iteration of the program structure to reduce the coupling and improve cohesion The module independency can be achieved in the program structure by exploding or imploding the modules Exploding the modules means obtaining two or more modules in the final stage and imploding the modules means combining the result of different modules2Attempt to minimize the structure with high fan-out and strive for fan-in as depth increase At the higher level of program structure the distribution of control should be made Fan-out means number of immediate subordinates to the module Fan-in means number of immediate ancestores the module have

86

3Keep scope of the effect of a module within the scope of control of that module The decisions made in particular module lsquoarsquo should not affect the module rsquo brsquo which lies outside the scope of module lsquoarsquo4Evaluate the module interfaces to reduce complexity and redundancy and improve consistency Mostly the cause of softwatr errors is module interfaces The module interfaces should simply pass the information and should be consistent with the module5Define module whose function is predicatable but avoid modules that are too restrictive The module should be designed with simplified internal processing so that expected data can be produced as a result The modules should not restrict the size of local data structure options with control flow or modes of external interfaces Being module too much restrictive causes large maintenance6Strive for controlled entry modules by avoiding pathological connections Software interfaces should be constrained and controlled so that it will become manageable Pathological connection means many references or branches into the middle of a module

Design ModelThe design model is represented as pyramid The pyramid is a stable object

Representing design model in this way means that the software design should be stableThe design model has braod foundation of data design stable mid-region with architectural and interface design and the sharp point to for component level design

Advantages of horizontal partition1These are easy to test maintain and extend 2They have fewer side effects in change propagation or error propagation

Disadvantages of horizontal partitionMore data has to be passed across module interfaces which complicates the overall

control of program flowVertical partitioning

Vertical partitioning suggests the control and work should be distributed top-down in program structureIn vertical partitioning

Define separate branches of the module hierarchy for each major functionUse control modules to co-ordinate communication between functions

Advantages of vertical partition1These are easy to maintain the changes2 They reduce the change impact and error propagation

DATA DESIGNData design is basically the model of data that is represented at the high level of abstractionThe data design is then progressively refined to create implementation specific representationsVarious elements of data design are

Data object - The data objects are identified and relationship among various data objects can be represented using entity relationship diagrams or data dictionariesDatabases - Using software design model the data models are translated into data structures and databases at the application level

87

Data warehouses - At the business level useful information is identified from various databases and the data warehouses are created For extracting or navigating the useful business information stored in the huge data warehouse then data mining techniques are applied

ARCHITECTURAL DESIGNSoftware architecture The design process for identifying the sub-systems making up a system and the framework for sub-system control and communication is architectural design The output of this design process is a description of the software architecture

Architectural design An early stage of the system design process Represents the link between specification and design processes Often carried out in parallel with some specification activities It involves identifying major system components and their communicationsArchitecture and system characteristics Performancebull Localise critical operations and minimise communications Use large rather than fine-grain components Securitybull Use a layered architecture with critical assets in the inner layers Safetybull Localise safety-critical features in a small number of sub-systems Availabilitybull Include redundant components and mechanisms for fault tolerance Maintainabilitybull Use fine-grain replaceable components

Architectural design decisions Is there a generic application architecture that can be used How will the system be distributed What architectural styles are appropriate What approach will be used to structure the system How will the system be decomposed into modules What control strategy should be used How will the architectural design be evaluated How should the architecture be documentedArchitectural styles The architectural model of a system may conform to a generic architectural model or style An awareness of these styles can simplify the problem of defining system architectures However most large systems are heterogeneous and do not follow a single architectural styleArchitectural models

Used to document an architectural design Static structural model that shows the major system components Dynamic process model that shows the process structure of the system Interface model that defines sub-system interfaces

88

Relationships model such as a data-flow model that shows sub-system relationships Distribution model that shows how sub-systems are distributed across computers

Modular decomposition Another structural level where sub-systems are decomposed into modules Two modular decomposition models coveredbull An object model where the system is decomposed into interacting objectbull A pipeline or data-flow model where the system is decomposed into functional modules which transform inputs to outputs If possible decisions about concurrency should be delayed until modules are implemented

Object models Structure the system into a set of loosely coupled objects with well-defined interfaces Object-oriented decomposition is concerned with identifying object classes their attributes and operations When implemented objects are created from these classes and some control model used to coordinate object operations

Invoice Processing system

Pipeline model advantages Supports transformation reuse Intuitive organisation for stakeholder communication Easy to add new transformations Relatively simple to implement as either a concurrent or sequential system However requires a common format for data transfer along the pipeline and difficult

to support event-based interaction

User interface design

The user interface User interfaces should be designed to match the skills experience and expectations of

its anticipated users System users often judge a system by its interface rather than its functionality A poorly designed interface can cause a user to make catastrophic errors Poor user interface design is the reason why so many software systems are never

usedUser interface Design Principle

89

Design principles User familiaritybull The interface should be based on user-oriented terms and concepts rather than computer concepts For example an office system should use concepts such as letters documents folders etc rather than directories file identifiers etc Consistencybull The system should display an appropriate level of consistency Commands and menus should have the same format command punctuation should be similar etc Minimal surprisebull If a command operates in a known way the user should be able to predict the operation of comparable commandsbull Recoverabilitybull The system should provide some resilience to user errors and allow the user to recover from errors This might include an undo facility confirmation of destructive actions soft deletes etcbull User guidancebull Some user guidance such as help systems on-line manuals etc should be suppliedbull User diversitybull Interaction facilities for different types of user should be supported For example some users have seeing difficulties and so larger text should be available

REAL-TIME SOFTWARE DESIGNReal-time systemsSystems which monitor and control their environmentInevitably associated with hardware devices

bull Sensors Collect data from the system environmentbull Actuators Change (in some way) the systems environment

Time is critical Real-time systems must respond within specified times

Definition A real-time system is a software system where the correct functioning of the

system depends on the results produced by the system and the time at which these results are produced

90

A soft real-time system is a system whose operation is degraded if results are not produced according to the specified timing requirements

A hard real-time system is a system whose operation is incorrect if results are not produced according to the timing specification

StimulusResponse Systems Given a stimulus the system must produce a response within a specified timePeriodic stimuli Stimuli which occur at predictable time intervals

bull For example a temperature sensor may be polled 10 times per secondAperiodic stimuli Stimuli which occur at unpredictable times

bull For example a system power failure may trigger an interrupt which must be processed by the system

Architectural considerations Because of the need to respond to timing demands made by different

stimuliresponses the system architecture must allow for fast switching between stimulus handlers

Timing demands of different stimuli are different so a simple sequential loop is not usually adequate

Real-time systems are therefore usually designed as cooperating processes with a real-time executive controlling these processes

A real-time system model

Real-timecontrol system

ActuatorActuator ActuatorActuator

SensorSensorSensor SensorSensorSensor

Sensoractuator processes

Dataprocessor

Actuatorcontrol

Actuator

Sensorcontrol

Sensor

Stimulus Response

System elementsSensor control processes

bull Collect information from sensors May buffer information collected in response to a sensor stimulus

Data processorbull Carries out processing of collected information and computes the system

responseActuator control processes

91

bull Generates control signals for the actuatorsReal-time programmingHard-real time systems may have to programmed in assembly language to ensure that deadlines are metLanguages such as C allow efficient programs to be written but do not have constructs to support concurrency or shared resource management

Java as a real-time languageJava supports lightweight concurrency (threads and synchronized methods) and can be used for some soft real-time systemsJava 20 is not suitable for hard RT programming but real-time versions of Java are now available that address problems such as

bull Not possible to specify thread execution timebull Different timing in different virtual machinesbull Uncontrollable garbage collectionbull Not possible to discover queue sizes for shared resourcesbull Not possible to access system hardwarebull Not possible to do space or timing analysis

SYSTEM DESIGN Design both the hardware and the software associated with system

Partition functions to either hardware or software Design decisions should be made on the basis on non-functional

system requirements Hardware delivers better performance but potentially longer

development and less scope for changeR-T systems design process

Identify the stimuli to be processed and the required responses to these stimuli For each stimulus and response identify the timing constraints Aggregate the stimulus and response processing into concurrent processes A

process may be associated with each class of stimulus and response Design algorithms to process each class of stimulus and response These must

meet the given timing requirements Design a scheduling system which will ensure that processes are started in time to

meet their deadlines Integrate using a real-time operating system

Timing constraints May require extensive simulation and experiment to ensure that these are met by the systemMay mean that certain design strategies such as object-oriented design cannot be used because of the additional overhead involvedMay mean that low-level programming language features have to be used for performance reasons

Real-time system modellingThe effect of a stimulus in a real-time system may trigger a transition from one state to anotherFinite state machines can be used for modelling real-time systems

92

However FSM models lack structure Even simple systems can have a complex modelThe UML includes notations for defining state machine models

Petrol pump state model

Cardinserted

into reader

Timeout

Resettingdo display CC

error

Initialising

do initialisedisplay

Paying

Stopped

Reading

do get CCdetails

Waiting

do display welcome

dodeliver fuel

do debitCC account

Payment ack

Ready Delivering

update displayNozzle

trigger on

Nozzle trigger off

Nozzle trigger on

Hose inholster

do validatecredit card

Validating

Invalid card

Card removedCard OK

Hose out of holster

Timeout

Real-time operating systems(RTOS)

Real-time operating systems are specialised operating systems which manage the processes in the RTS

Responsible for process management and resource (processor and memory) allocation

May be based on a standard kernel which is used unchanged or modified for a particular application

Do not normally include facilities such as file management

Operating system componentsReal-time clock

bull Provides information for process schedulingInterrupt handler

bull Manages aperiodic requests for serviceScheduler

bull Chooses the next process to be runResource manager

bull Allocates memory and processor resourcesDispatcher

bull Starts process executionNon-stop system components

Configuration manager

93

bull Responsible for the dynamic reconfiguration of the system software and hardware Hardware modules may be replaced and software upgraded without stopping the systems

Fault managerbull Responsible for detecting software and hardware faults and taking appropriate

actions (eg switching to backup disks) to ensure that the system continues in operation

Real-time OS components

Process resourcerequirements

Scheduler

Schedulinginformation

Resourcemanager

Despatcher

Real-timeclock

Processesawaiting

resources

Readylist

Interrupthandler

Availableresource

list

Processorlist

Executing process

Readyprocesses

Releasedresources

Process priority The processing of some types of stimuli must sometimes take priority Interrupt level priority Highest priority which is allocated to processes requiring a

very fast response Clock level priority Allocated to periodic processes Within these further levels of priority may be assigned

Interrupt servicing Control is transferred automatically to a pre-determined memory location This location contains an instruction to jump to

an interrupt service routine Further interrupts are disabled the interrupt

serviced and control returned to the interrupted process

Interrupt service routines must be short simple and fast

Periodic process servicing In most real-time systems there will be several classes of periodic process each with

different periods (the time between executions) execution times and deadlines (the time by which processing must be completed)

The real-time clock ticks periodically and each tick causes an interrupt which schedules the process manager for periodic processes

The process manager selects a process which is ready for execution

Process managementbull Concerned with managing the set of concurrent processes

94

bull Periodic processes are executed at pre-specified time intervalsbull The RTOS uses the real-time clock to determine when to execute a process

taking into accountbull Process period - time between executionsbull Process deadline - the time by which processing must be complete

RTE(Real Time Execution Process) process managementResource manager

Allocate memoryand processor

Scheduler

Choose processfor execution

Despatcher

Start execution on anavailable processor

Process switchingbull The scheduler chooses the next process to be executed by the processor This

depends on a scheduling strategy which may take the process priority into account

bull The resource manager allocates memory and a processor for the process to be executed

bull The dispatcher takes the process from ready list loads it onto a processor and starts execution

Scheduling strategiesNon pre-emptive scheduling

bull Once a process has been scheduled for execution it runs to completion or until it is blocked for some reason (eg waiting for IO)

Pre-emptive schedulingbull The execution of an executing processes may be stopped if a higher priority

process requires serviceScheduling algorithms

bull Round-robinbull Rate monotonicbull Shortest deadline first

Monitoring and control systemsbull Important class of real-time systems bull Continuously check sensors and take actions

depending on sensor valuesbull Monitoring systems examine sensors and

report their resultsbull Control systems take sensor values and control hardware actuators

Generic architecture

95

S1

S2

S3

P (S1)

P (S2)

P (S1)

Monitoringprocesses

Controlprocesses

P (A1)

P (A2)

P (A1)

A1

A2

A3

P (A4) A4

Testingprocess

Control panelprocesses

Burglar alarm systembull A system is required to monitor sensors on doors and windows to detect the

presence of intruders in a buildingbull When a sensor indicates a break-in the system switches on lights around the

area and calls police automaticallybull The system should include provision for operation without a mains power

supply Sensorso Movement detectors window sensors door sensorso 50 window sensors 30 door sensors and 200 movement detectorso Voltage drop sensor Actionso When an intruder is detected police are called automaticallyo Lights are switched on in rooms with active sensorso An audible alarm is switched on

The R-T system design process

bull Identify stimuli and associated responsesbull Define the timing constraints associated with each stimulus and responsebull Allocate system functions to concurrent processesbull Design algorithms for stimulus processing and response generationbull Design a scheduling system which ensures that processes will always be

scheduled to meet their deadlinesStimuli to be processed

Power failurebull Generated aperiodically by a circuit monitor When received the system must

switch to backup power within 50 msIntruder alarm

bull Stimulus generated by system sensors Response is to call the police switch on building lights and the Power failure

bull Generated aperiodically by a circuit monitor When received the system must switch to backup power within 50 ms

bull Intruder alarmbull Stimulus generated by system sensors Response is to call the police switch

on building lights and the audible alarmbull audible alarm

Burglar alarm system processes

96

Lighting controlprocess

Audible alarmprocess

Voice synthesiserprocess

Alarm systemprocess

Power switchprocess

Building monitorprocess

Communicationprocess

Door sensorprocess

Movementdetector process

Window sensorprocess

560 Hz

60 Hz400 Hz 100 Hz

Power failureinterrupt

Alarm system

Building monitor

Alarm system

Alarm system

Alarm system

Detector status Sensor status Sensor status

Room number

Alert message

Room number

Room number

Building_monitor process 1

class BuildingMonitor extends Thread

BuildingSensor win door move

Siren siren = new Siren () Lights lights = new Lights () Synthesizer synthesizer = new Synthesizer () DoorSensors doors = new DoorSensors (30) WindowSensors windows = new WindowSensors (50) MovementSensors movements = new MovementSensors (200) PowerMonitor pm = new PowerMonitor ()

BuildingMonitor() initialise all the sensors and start the processessirenstart () lightsstart () synthesizerstart () windowsstart () doorsstart () movementsstart () pmstart ()

Building monitor process 2public void run () int room = 0 while (true) poll the movement sensors at least twice per second (400 Hz)move = movementsgetVal () poll the window sensors at least twicesecond (100 Hz)win = windowsgetVal () poll the door sensors at least twice per second (60 Hz)door = doorsgetVal ()

97

if (movesensorVal == 1 | doorsensorVal == 1 | winsensorVal == 1) a sensor has indicated an intruder if (movesensorVal == 1) room = moveroom if (doorsensorVal == 1) room = doorroom if (winsensorVal == 1 ) room = winroom lightson (room) sirenon () synthesizeron (room) break Building_monitor process 3 lightsshutdown () sirenshutdown () synthesizershutdown () windowsshutdown () doorsshutdown () movementsshutdown ()

run BuildingMonitor

Control systems

bull A burglar alarm system is primarily a monitoring system It collects data from sensors but no real-time actuator control

bull Control systems are similar but in response to sensor values the system sends control signals to actuators

bull An example of a monitoring and control system is a system that monitors temperature and switches heaters on and off

A temperature control system

Thermostatprocess

Sensorprocess

Furnacecontrol process

Heater controlprocess

500 Hz

500 Hz

Thermostat process500 Hz

Sensorvalues

Switch commandRoom number

DATA ACQUISITION SYSTEMSbull Collect data from sensors for subsequent processing and analysisbull Data collection processes and processing processes may have different periods

and deadlines bull Data collection may be faster than processing eg collecting information about

an explosion bull Circular or ring buffers are a mechanism for smoothing speed differences

The generic Architecture of data acquicition

98

DisplayProcess

dataSensor data

bufferSensorprocess

Sensoridentifier and

value

Sensors (each data flow is a sensor value)

Sensoridentifier and

value

Processdata

Sensor databuffer

Sensorprocess

Sensoridentifier and

value

Sensoridentifier and

value

s1

s2

s3

s4

s5

s6

In data acquisition systemsthe sensor may be generating data quickly and the key problem is to ensure that a sensor is allocated before sensor value changeThe essenitial features of this architecture is each group of sensors has three processes associated with it and convert analogue data to digital values if necessary a buffer process and a process that consumes the data carried out further processing Two groups sensors s1-s3 and s4-s6 on the right side a further procee that diplsys the sensor data Neutron flux data acquisition

Operatordisplay

Fluxprocessing

Flux databuffer

A-Dconvertor

Sensoridentifier and

flux valueProcessedflux level

Neutron flux sensors

bull A system collects data from a set of sensors monitoring the neutron flux from a nuclear reactor

bull Each sensor has a process that converts the analog input flux level into a digita signalIt passes this flux level with sensor identifies to the sensor data buffer the data processing takes the data from this bufferprocesses it and pass it to display process for output on an operator display

A ring buffer

Consumerprocess

Producerprocess

Mutual exclusionbull Producer processes collect data and add it to the buffer Consumer processes

take data from the buffer and make elements availablebull Producer and consumer processes must be mutually excluded from accessing

the same elementThe buffer must stop producer processes adding information to a full buffer and consumer processes trying to take information from an empty buffer

99

Page 10: Unit_III

User command and data encompasses all configuration commandsall activationdeactivation commands all miscellaneous interactions and all data that are entered to expand a commandProcessing narrative

It is similar to the use-case in style but different in purpose it provides an overall description of the function to be developed It is not a scenario written from one actorrsquos point of view

The level 0 DFD expanded into a level 1 data flow model to proceed A simple even so effective approach is to perform a ldquogrammatical parserdquo on the processing narrative

that describes the context level bubbleThe following processing narrative text with the first occurance of all nouns underlined and the first occurrence of all verbs italicizedExample Safehome processing narrativeThe Safehome security function enables the homeowner to configure the security system when it is installedmonitors all sensors connected to the security and interacts with the homeowner through the Internet a PC or a control panel

Level 1 DFD for Safehome processesReferring to the grammatical parse verbs are represented as bubbles in a subsequent DFDNouns are either external entities (boxes)data or control objects (arrows) or data stored(double lines) that nouns and verbs can be associsated with one anotherFor example each sensor is assigned a number and type are attributes of the data object sensorTherefore by performing a grammatical parse on the processing narrative for a bubble at any DFD level

78

Level 2 DFD The processes represented at DFD level 1 can be further refined into lower levelsThe information flow continuity has been mainted between levels 0 and 1ExampleThe process monitor sensors can be refined into a level 2 DFD

The refinement of DFDs continues until each bubble performs a simple function that would be easily implemented as a program component

Creating A Control Flow Model

79

Control flow modeling used for a large class of applications are ldquodrivenrdquo by events rather than data produce control information rather than reports or displays and process information with heavy concern for time and performance

Already noted that an event or control item is implemented as a Boolean value ie true or false1 or 0 or a discrete list of conditions

The following guidelines to select potential(possible) candidate events-

o List all sensors that are ldquoreadrdquo by the softwareo List all interrupt conditionso List all ldquoswitches ldquothat are actuated by an operatoro List all data conditionso Recalling the nounverb parse that was applied to the processing narrativereview

all ldquocontrol itemsrdquo as possible for control flow inputsoutputso Describe the behavior of a system by identifying its statesidentify how each state

is reached and define the transitions between stateso Focus on possible omissions a very common error in specifying controlfor

example ask ldquoIs there any other way I can get this state or exit from itrdquoThe Control SpecificationThe control specification (CSPEC) represents the behavior of the system in two different ways 1 State diagram 2 Program activationState diagramIt is a sequential specification of behaviorProgram activationIt also contain a program activation table is a combinatorial specification of behavior

The CSPEC describes the behavior of the system but it gives us no information about the inner working of the process that are activated as aresult of this behaviorExampleThe state diagram indicates that the transitions from the idle state can occurTwo transitions occur out of the Monitoring system status state(1)when the system is deactivated a transition occurs back to the idle state(2) when a sensor is triggered a transition to the Acting Alarm state occurs During the review consider all transition and the content of all states

The Process Specification The process specification (PSPEC) is used to describe all flow model processes that

appear at the final level of refinement The content of the process specification can include narrative texta program design

language(PDL) description of the algorithmmathematical equations tablesdiagrams or charts

The PSPEC is a lsquomini specificationrdquofor each transform at the lowest refined level of a DFD that as a guide for design of the software component that will implement the process

Example The password transform represented in the flow model for Safehome the function is perform by PSPEC

80

If the password matches an entry within the table [valid id message=true] is passed to the message and status display functionIf there is no matah [valid id message=false]is passed to the message and status display function

CLASS-BASED MODELING Class-based element of an analysis modelClasses and objectsAttributesOperationsPackagesCRC modelsCollaborations diagram

Identifying Analysis ClassesTo identify classes by examining the pbolem statement or by performing a

ldquogrammatical parserdquo the use-cases or processing narratives developed for the system to be built Classes are determined by underlinining each noun or noun clause and enter it into a simple tableIf the class is required to implement a solution then it is part of the solution space other wise if a class is necessary only to describe a solution it is part of the problem space

The following ways are for Analysis classes to manifest (marked) themselves External entities that produce or consume information to be used by a computer-based

system (eg) devicespeople Things that are part of the information domain for the problem(eg) reports displays

leeterssignals Occurrences or events that occur within the context of system operation(eg)

aproperty transfer or the completion of a series of robot movements Roles played by who interact with the system(eg) manager engineersalesperson Organizational units that are relevant to an application(eg)division groupteam Places that establish the context of the problem and the overall function of the system

(eg) manufacturing floor ) Structures that define a class of objects or related classes of objects (eg)

sensors four-wheeled vehicles or computerBudd suggests taxonomy (classification) of classes that includes producers(sources0 and consumers(sinks) of datadata managerview and helper classes

A class should never have an ldquoimperative procedural namerdquo(eg) an object with the name Imageinersion would making mistake so that inversion of the image the inversion() is an operation that applied to the class image During early stage of modeling analysis class might be defined to the example of Safehome security function performed in a ldquogrammatical parserdquo on a processing narrativeExtracting the nouns each entry in the list a potential object

Coad and Yourdon suggest six selection characteristics that should be used as an analyst considers each potential class for inclusion in the analysis model

1Retained informationThe potential class will be useful during analysis only if information about it must be remembered so that the system can function

81

2Needed servicesThe potential class must have a set of identifiable operations that can change the value of its attributes in some way3Multiple attributesDuring requirement analysis the focus should be on ldquomajor ldquo information a class with a single attribute be useful during design but better to represent ed as an attribute of another class during the analysis activity4Common attributesA set of attributes can be defined for the potential class and these attributes apply to all instances of the class5Common operationsA set of operation can be defined for the potential class and these operations apply to all instances of the class6Essential requirements External entities that appear in the problem space and produce and consume information important to the operation of any solution for the system will almost always be defined as classes in the requirements modelSpecifying AttributesAttributes are the set of data objects that fully define the class within the context of the problemExample

SystemsystemIDverificationPhonenubersystemStatusdelaytimemasterpasswordprogram()display()reset()query()modify()

The shade portion is list of attributes for the system classDefining OperationsIt define the behavior of an object The types of operations are divided into three categories (1)operations that manipulate data egadingdeletingreformattingselecting (2)operations that perform a computation (3)operations that inquire about the state of an object (4)operations that monitor an object for the occurance of a controlling eventThese functions are accomplished by operating on attributes and associationsExample Safehome processing narrative the phrases indicate that a program() operation is encapsulated by the System classClass-Responsibility-Collaborator(CRC) ModelingClass-responsibility-collaborator modeling provides simple means for identifying and organizing the classes that are relevant to system or product requirementsAmbler describes CRC modeling in the following way A CRC model is a collection of standard index cards that represent classesThe cards are divided into three sectionsDESIGN WITHIN THE CONTEXT OF SOFTWARE ENGINEERING

Design Principle1Design should be traceable to the analysis model

82

2Always consider the architecture of the system to be built3Design of data is as important as design of processing functions4Interfaces both internal and external must be designed with care5User interface design should be tuned to the needs of the end-users6Component ndashlevel design should be functionally independent7Components should be loosely coupled to one another and to the environment8Design representation(models) should be easily understandable9The design should be developed iterativelyWith each iteration the designer should stive for greater simplicity

DESIGN PROCESS AND DESIGN QUALITYDesign process

bull Design process is a sequence of steps carried through which the requirements are translated into a system or software model bull Any design may be modeled as a direct graph The graphs are collection of entities with attributes which participate in relationships bull The system should be described at several different levels of abstraction bull Design takes place in overlapping stages bull Various phases of design process are as shown in following

1 In architectural design the subsystem components can be identified2 The abstract specification is used to specify the subsystems3 The interfaces between the subsystems are designed which is called inter face design4 In component design of subsystems components is done5 The data structure is designed to hold the data6 For perfoming the required functionality the appropriate algorithm is de

signed

Software design is an iterative process through which requirements are translated into a design for constructing the software

The design is represented at a high level of abstractiona level that can be directly traced to the specific system objective and more detailed datafunctional and behavioral requirements As design iteraton occur subsequent refinement to design representation at lower levels of abstraction

McGlaughin suggests three characteristics that serve as a guide for the evaluation of a good design Each of these characteristics is a goal of the design process

The design must implement all of the explicit requirements contained in the analysis model and it must accommodate all of the implicit(indirect) requirements desired by the customer

The design must be a readable understandable guide for those who generate code and for those who test and subsequently support the software

The design should provide a complete picture of the software addressing the data functional and behavioral domains from an implementation perspective

83

Quality guidelinesThe following gidelines to evaluate the quality of a design representation

1A design should display an architecture that (a) That has been created using recognizable architectural styles or patterns

(b)That is composed of components that show good design characteristics (c)That can be implemented in an evolutionary style thereby implementing and testing2A design should be modular that is the software should be logically partitioned into elements or subsystems3A design should contain distinct representation of dataarchitectureinterfaces and components4A design should lead to data structures that are appropriate for the classes to be implemented and are drawn from recognizable data patterns5A design should lead to components that show independent functional characteristics6A design should lead to interfaces that reduce the complexity of connections between components and with the external environmemt7A design should be derived using a repeatable method that is driven by information obtained during software requirements analysis8A design should be represented using a notation that effectively communicates its meaning

Quality attributesHewlett Packard deveopled a set of software quality attributes are given as acronym(short form) FURPS to represent a target(goal) for all software design

Functionality Usability Reliability Performance Supportability

FunctionalityIt is assessed by evaluating the feature set and capabilities of the programthe generalization of the functions that are deliveredand the security of the overall systemUsabilityIt is assessed by human factors consistency and documentationReliabilityIt is evaluated by measuring the frequency and severity of failurethe accuracy of output resultsthe mean-time-to-failure(MTTF) the ability to recover from failure and predictability(unavoidability) of the programPerformanceIt is measured by processing speedresponse timeresource consumption throughput and efficiencySupportabilityItcombin the abilitytoxtendtheprogram(extensibility)adaptabilityServiceabilitymainabilitytestabilitycompatibilityconfigurability the ability to organize and control elements of the software congfiguration

Design Principles Davis suggested a set of principles for software design as

bull The design process should not suffer from ldquotunnel visionrdquobull The design should be traceable to the analysis modelbull The design should not reinvent the wheel

84

bull The design should ldquominimize the intellectual distancerdquo between the software and the problem in the real worldbull The design should exhibit uniformity and integrationbull The design should be structured to degrade gentlybull Design is not coding and coding is not designbull The design should be assessed for qualitybull The design should be reviewed to minimize conceptual errors

Design Concept

The software design concept provides a framework for implementing the right software

Following issues are considered while designing the software1Abstraction At each stage of software design process levels of abstractions should be applied to refine the software solutionAt the higher level of abstraction the solution should be stated in broad terms and in the lower level more detailed description of the solution is given While moving through different levels of abstraction the procedural abstraction and data abstraction is created In procedural abstraction it gives the named sequence of instruction in the specific function In data abstracion the collection of data objects is represented Levels of Abstraction Various levels of abstractions are- Level I - This level represents the solution interms of problem environment Level II - This level represents the decomposition of terms that are moved from problem environment but still not at implementation stage Level III - At this level preliminary procedural representation exists All the terminologies at this level are software oriented and implementation modularity begins at the surface Level IV and V - The concepts of stepwise refinement and modularity are

applied at this level2 Modularity

The software is divided into separately named and addressable components that called as modules Creating such models bring the modularity in siftwareMeyer defines five criteria that enable us to evaluate a design method with respect to its ability to define an effective modular systemModular decomposability A design method provides a systematic mechanism for decomposing the problem into sub-problems This reduces the complexity of the problem and the modularity can be achievedModular composability A design method enables existing design components to be assembled into a new systemModular understandability A module can be understood as a standalone unit Then it will be easier to build and easier to changeModular continuity Small changes to the system requirements result in changes to individual modules rather than system- wide changesModular protection An aberrant condition occurs within a module and its effects are constrained within the module3Refinement

Refinement is actually a process of elaborationStepwise refinement is a top-down design strategy proposed by Niklaus WIRTHThe architecture of a program is developed by successively refining levels of procedural detail

85

The process of program refinement is analogues to the process of refinement and partitioning that is used during requirements analysisAbstraction and refinement are complementary concepts The major difference is that - in the abstraction low-level details are suppressedRefinement helps the designer to elaborate low-levels detailsModular Design

Modular design reduces complexity and helps in easier implementation The parallel development of different parts of the system is possible due to modular designWhat is the benefit of modular design Changes made during testing and maintenance becomes manageable and they do not affect other modules Various quality parameters for effective modular design are -1) Functional independance 2) Cohesion 3) Coupling

Functional IndependenceThe functional independence can be achieved be developing the functional modules

with single-minded approachBy using functional independence functions may be compartmentalized and interfaces are simplifiedVarious types of coupling are i) Data coupling - The data coupling is possible by parameter passing or data interactionii) Control coupling - The modules share related control data in control couplingiii) Commom coupling - Content coupling occurs when one module makes use of data or control information maintained in another moduleFan-out Fan-out is a measure of the number of immediate subordinates to a moule The fan-out should be within some limit in the design If fan-out is very high then it indicates that a single module is controlling many other modules Preferably limit fan-out to no more than sevenFan-in

Fan-in indicates how many modules directly control a given module Modules with fan-in must have good cohesion Each interfac to the module must have the same number and types of parametersFactoring

Factoring means separation of function into new modules By applying factoring the size of module is reduced and thereby the complexity of the problem is reduced This also provides duplication of functions in more than one module The effective factoring brings simplification in the implementation of software design DESIGN HEURISTICS

The program structure can be manipulated according the design heuristics as shon below1Evaluate the first iteration of the program structure to reduce the coupling and improve cohesion The module independency can be achieved in the program structure by exploding or imploding the modules Exploding the modules means obtaining two or more modules in the final stage and imploding the modules means combining the result of different modules2Attempt to minimize the structure with high fan-out and strive for fan-in as depth increase At the higher level of program structure the distribution of control should be made Fan-out means number of immediate subordinates to the module Fan-in means number of immediate ancestores the module have

86

3Keep scope of the effect of a module within the scope of control of that module The decisions made in particular module lsquoarsquo should not affect the module rsquo brsquo which lies outside the scope of module lsquoarsquo4Evaluate the module interfaces to reduce complexity and redundancy and improve consistency Mostly the cause of softwatr errors is module interfaces The module interfaces should simply pass the information and should be consistent with the module5Define module whose function is predicatable but avoid modules that are too restrictive The module should be designed with simplified internal processing so that expected data can be produced as a result The modules should not restrict the size of local data structure options with control flow or modes of external interfaces Being module too much restrictive causes large maintenance6Strive for controlled entry modules by avoiding pathological connections Software interfaces should be constrained and controlled so that it will become manageable Pathological connection means many references or branches into the middle of a module

Design ModelThe design model is represented as pyramid The pyramid is a stable object

Representing design model in this way means that the software design should be stableThe design model has braod foundation of data design stable mid-region with architectural and interface design and the sharp point to for component level design

Advantages of horizontal partition1These are easy to test maintain and extend 2They have fewer side effects in change propagation or error propagation

Disadvantages of horizontal partitionMore data has to be passed across module interfaces which complicates the overall

control of program flowVertical partitioning

Vertical partitioning suggests the control and work should be distributed top-down in program structureIn vertical partitioning

Define separate branches of the module hierarchy for each major functionUse control modules to co-ordinate communication between functions

Advantages of vertical partition1These are easy to maintain the changes2 They reduce the change impact and error propagation

DATA DESIGNData design is basically the model of data that is represented at the high level of abstractionThe data design is then progressively refined to create implementation specific representationsVarious elements of data design are

Data object - The data objects are identified and relationship among various data objects can be represented using entity relationship diagrams or data dictionariesDatabases - Using software design model the data models are translated into data structures and databases at the application level

87

Data warehouses - At the business level useful information is identified from various databases and the data warehouses are created For extracting or navigating the useful business information stored in the huge data warehouse then data mining techniques are applied

ARCHITECTURAL DESIGNSoftware architecture The design process for identifying the sub-systems making up a system and the framework for sub-system control and communication is architectural design The output of this design process is a description of the software architecture

Architectural design An early stage of the system design process Represents the link between specification and design processes Often carried out in parallel with some specification activities It involves identifying major system components and their communicationsArchitecture and system characteristics Performancebull Localise critical operations and minimise communications Use large rather than fine-grain components Securitybull Use a layered architecture with critical assets in the inner layers Safetybull Localise safety-critical features in a small number of sub-systems Availabilitybull Include redundant components and mechanisms for fault tolerance Maintainabilitybull Use fine-grain replaceable components

Architectural design decisions Is there a generic application architecture that can be used How will the system be distributed What architectural styles are appropriate What approach will be used to structure the system How will the system be decomposed into modules What control strategy should be used How will the architectural design be evaluated How should the architecture be documentedArchitectural styles The architectural model of a system may conform to a generic architectural model or style An awareness of these styles can simplify the problem of defining system architectures However most large systems are heterogeneous and do not follow a single architectural styleArchitectural models

Used to document an architectural design Static structural model that shows the major system components Dynamic process model that shows the process structure of the system Interface model that defines sub-system interfaces

88

Relationships model such as a data-flow model that shows sub-system relationships Distribution model that shows how sub-systems are distributed across computers

Modular decomposition Another structural level where sub-systems are decomposed into modules Two modular decomposition models coveredbull An object model where the system is decomposed into interacting objectbull A pipeline or data-flow model where the system is decomposed into functional modules which transform inputs to outputs If possible decisions about concurrency should be delayed until modules are implemented

Object models Structure the system into a set of loosely coupled objects with well-defined interfaces Object-oriented decomposition is concerned with identifying object classes their attributes and operations When implemented objects are created from these classes and some control model used to coordinate object operations

Invoice Processing system

Pipeline model advantages Supports transformation reuse Intuitive organisation for stakeholder communication Easy to add new transformations Relatively simple to implement as either a concurrent or sequential system However requires a common format for data transfer along the pipeline and difficult

to support event-based interaction

User interface design

The user interface User interfaces should be designed to match the skills experience and expectations of

its anticipated users System users often judge a system by its interface rather than its functionality A poorly designed interface can cause a user to make catastrophic errors Poor user interface design is the reason why so many software systems are never

usedUser interface Design Principle

89

Design principles User familiaritybull The interface should be based on user-oriented terms and concepts rather than computer concepts For example an office system should use concepts such as letters documents folders etc rather than directories file identifiers etc Consistencybull The system should display an appropriate level of consistency Commands and menus should have the same format command punctuation should be similar etc Minimal surprisebull If a command operates in a known way the user should be able to predict the operation of comparable commandsbull Recoverabilitybull The system should provide some resilience to user errors and allow the user to recover from errors This might include an undo facility confirmation of destructive actions soft deletes etcbull User guidancebull Some user guidance such as help systems on-line manuals etc should be suppliedbull User diversitybull Interaction facilities for different types of user should be supported For example some users have seeing difficulties and so larger text should be available

REAL-TIME SOFTWARE DESIGNReal-time systemsSystems which monitor and control their environmentInevitably associated with hardware devices

bull Sensors Collect data from the system environmentbull Actuators Change (in some way) the systems environment

Time is critical Real-time systems must respond within specified times

Definition A real-time system is a software system where the correct functioning of the

system depends on the results produced by the system and the time at which these results are produced

90

A soft real-time system is a system whose operation is degraded if results are not produced according to the specified timing requirements

A hard real-time system is a system whose operation is incorrect if results are not produced according to the timing specification

StimulusResponse Systems Given a stimulus the system must produce a response within a specified timePeriodic stimuli Stimuli which occur at predictable time intervals

bull For example a temperature sensor may be polled 10 times per secondAperiodic stimuli Stimuli which occur at unpredictable times

bull For example a system power failure may trigger an interrupt which must be processed by the system

Architectural considerations Because of the need to respond to timing demands made by different

stimuliresponses the system architecture must allow for fast switching between stimulus handlers

Timing demands of different stimuli are different so a simple sequential loop is not usually adequate

Real-time systems are therefore usually designed as cooperating processes with a real-time executive controlling these processes

A real-time system model

Real-timecontrol system

ActuatorActuator ActuatorActuator

SensorSensorSensor SensorSensorSensor

Sensoractuator processes

Dataprocessor

Actuatorcontrol

Actuator

Sensorcontrol

Sensor

Stimulus Response

System elementsSensor control processes

bull Collect information from sensors May buffer information collected in response to a sensor stimulus

Data processorbull Carries out processing of collected information and computes the system

responseActuator control processes

91

bull Generates control signals for the actuatorsReal-time programmingHard-real time systems may have to programmed in assembly language to ensure that deadlines are metLanguages such as C allow efficient programs to be written but do not have constructs to support concurrency or shared resource management

Java as a real-time languageJava supports lightweight concurrency (threads and synchronized methods) and can be used for some soft real-time systemsJava 20 is not suitable for hard RT programming but real-time versions of Java are now available that address problems such as

bull Not possible to specify thread execution timebull Different timing in different virtual machinesbull Uncontrollable garbage collectionbull Not possible to discover queue sizes for shared resourcesbull Not possible to access system hardwarebull Not possible to do space or timing analysis

SYSTEM DESIGN Design both the hardware and the software associated with system

Partition functions to either hardware or software Design decisions should be made on the basis on non-functional

system requirements Hardware delivers better performance but potentially longer

development and less scope for changeR-T systems design process

Identify the stimuli to be processed and the required responses to these stimuli For each stimulus and response identify the timing constraints Aggregate the stimulus and response processing into concurrent processes A

process may be associated with each class of stimulus and response Design algorithms to process each class of stimulus and response These must

meet the given timing requirements Design a scheduling system which will ensure that processes are started in time to

meet their deadlines Integrate using a real-time operating system

Timing constraints May require extensive simulation and experiment to ensure that these are met by the systemMay mean that certain design strategies such as object-oriented design cannot be used because of the additional overhead involvedMay mean that low-level programming language features have to be used for performance reasons

Real-time system modellingThe effect of a stimulus in a real-time system may trigger a transition from one state to anotherFinite state machines can be used for modelling real-time systems

92

However FSM models lack structure Even simple systems can have a complex modelThe UML includes notations for defining state machine models

Petrol pump state model

Cardinserted

into reader

Timeout

Resettingdo display CC

error

Initialising

do initialisedisplay

Paying

Stopped

Reading

do get CCdetails

Waiting

do display welcome

dodeliver fuel

do debitCC account

Payment ack

Ready Delivering

update displayNozzle

trigger on

Nozzle trigger off

Nozzle trigger on

Hose inholster

do validatecredit card

Validating

Invalid card

Card removedCard OK

Hose out of holster

Timeout

Real-time operating systems(RTOS)

Real-time operating systems are specialised operating systems which manage the processes in the RTS

Responsible for process management and resource (processor and memory) allocation

May be based on a standard kernel which is used unchanged or modified for a particular application

Do not normally include facilities such as file management

Operating system componentsReal-time clock

bull Provides information for process schedulingInterrupt handler

bull Manages aperiodic requests for serviceScheduler

bull Chooses the next process to be runResource manager

bull Allocates memory and processor resourcesDispatcher

bull Starts process executionNon-stop system components

Configuration manager

93

bull Responsible for the dynamic reconfiguration of the system software and hardware Hardware modules may be replaced and software upgraded without stopping the systems

Fault managerbull Responsible for detecting software and hardware faults and taking appropriate

actions (eg switching to backup disks) to ensure that the system continues in operation

Real-time OS components

Process resourcerequirements

Scheduler

Schedulinginformation

Resourcemanager

Despatcher

Real-timeclock

Processesawaiting

resources

Readylist

Interrupthandler

Availableresource

list

Processorlist

Executing process

Readyprocesses

Releasedresources

Process priority The processing of some types of stimuli must sometimes take priority Interrupt level priority Highest priority which is allocated to processes requiring a

very fast response Clock level priority Allocated to periodic processes Within these further levels of priority may be assigned

Interrupt servicing Control is transferred automatically to a pre-determined memory location This location contains an instruction to jump to

an interrupt service routine Further interrupts are disabled the interrupt

serviced and control returned to the interrupted process

Interrupt service routines must be short simple and fast

Periodic process servicing In most real-time systems there will be several classes of periodic process each with

different periods (the time between executions) execution times and deadlines (the time by which processing must be completed)

The real-time clock ticks periodically and each tick causes an interrupt which schedules the process manager for periodic processes

The process manager selects a process which is ready for execution

Process managementbull Concerned with managing the set of concurrent processes

94

bull Periodic processes are executed at pre-specified time intervalsbull The RTOS uses the real-time clock to determine when to execute a process

taking into accountbull Process period - time between executionsbull Process deadline - the time by which processing must be complete

RTE(Real Time Execution Process) process managementResource manager

Allocate memoryand processor

Scheduler

Choose processfor execution

Despatcher

Start execution on anavailable processor

Process switchingbull The scheduler chooses the next process to be executed by the processor This

depends on a scheduling strategy which may take the process priority into account

bull The resource manager allocates memory and a processor for the process to be executed

bull The dispatcher takes the process from ready list loads it onto a processor and starts execution

Scheduling strategiesNon pre-emptive scheduling

bull Once a process has been scheduled for execution it runs to completion or until it is blocked for some reason (eg waiting for IO)

Pre-emptive schedulingbull The execution of an executing processes may be stopped if a higher priority

process requires serviceScheduling algorithms

bull Round-robinbull Rate monotonicbull Shortest deadline first

Monitoring and control systemsbull Important class of real-time systems bull Continuously check sensors and take actions

depending on sensor valuesbull Monitoring systems examine sensors and

report their resultsbull Control systems take sensor values and control hardware actuators

Generic architecture

95

S1

S2

S3

P (S1)

P (S2)

P (S1)

Monitoringprocesses

Controlprocesses

P (A1)

P (A2)

P (A1)

A1

A2

A3

P (A4) A4

Testingprocess

Control panelprocesses

Burglar alarm systembull A system is required to monitor sensors on doors and windows to detect the

presence of intruders in a buildingbull When a sensor indicates a break-in the system switches on lights around the

area and calls police automaticallybull The system should include provision for operation without a mains power

supply Sensorso Movement detectors window sensors door sensorso 50 window sensors 30 door sensors and 200 movement detectorso Voltage drop sensor Actionso When an intruder is detected police are called automaticallyo Lights are switched on in rooms with active sensorso An audible alarm is switched on

The R-T system design process

bull Identify stimuli and associated responsesbull Define the timing constraints associated with each stimulus and responsebull Allocate system functions to concurrent processesbull Design algorithms for stimulus processing and response generationbull Design a scheduling system which ensures that processes will always be

scheduled to meet their deadlinesStimuli to be processed

Power failurebull Generated aperiodically by a circuit monitor When received the system must

switch to backup power within 50 msIntruder alarm

bull Stimulus generated by system sensors Response is to call the police switch on building lights and the Power failure

bull Generated aperiodically by a circuit monitor When received the system must switch to backup power within 50 ms

bull Intruder alarmbull Stimulus generated by system sensors Response is to call the police switch

on building lights and the audible alarmbull audible alarm

Burglar alarm system processes

96

Lighting controlprocess

Audible alarmprocess

Voice synthesiserprocess

Alarm systemprocess

Power switchprocess

Building monitorprocess

Communicationprocess

Door sensorprocess

Movementdetector process

Window sensorprocess

560 Hz

60 Hz400 Hz 100 Hz

Power failureinterrupt

Alarm system

Building monitor

Alarm system

Alarm system

Alarm system

Detector status Sensor status Sensor status

Room number

Alert message

Room number

Room number

Building_monitor process 1

class BuildingMonitor extends Thread

BuildingSensor win door move

Siren siren = new Siren () Lights lights = new Lights () Synthesizer synthesizer = new Synthesizer () DoorSensors doors = new DoorSensors (30) WindowSensors windows = new WindowSensors (50) MovementSensors movements = new MovementSensors (200) PowerMonitor pm = new PowerMonitor ()

BuildingMonitor() initialise all the sensors and start the processessirenstart () lightsstart () synthesizerstart () windowsstart () doorsstart () movementsstart () pmstart ()

Building monitor process 2public void run () int room = 0 while (true) poll the movement sensors at least twice per second (400 Hz)move = movementsgetVal () poll the window sensors at least twicesecond (100 Hz)win = windowsgetVal () poll the door sensors at least twice per second (60 Hz)door = doorsgetVal ()

97

if (movesensorVal == 1 | doorsensorVal == 1 | winsensorVal == 1) a sensor has indicated an intruder if (movesensorVal == 1) room = moveroom if (doorsensorVal == 1) room = doorroom if (winsensorVal == 1 ) room = winroom lightson (room) sirenon () synthesizeron (room) break Building_monitor process 3 lightsshutdown () sirenshutdown () synthesizershutdown () windowsshutdown () doorsshutdown () movementsshutdown ()

run BuildingMonitor

Control systems

bull A burglar alarm system is primarily a monitoring system It collects data from sensors but no real-time actuator control

bull Control systems are similar but in response to sensor values the system sends control signals to actuators

bull An example of a monitoring and control system is a system that monitors temperature and switches heaters on and off

A temperature control system

Thermostatprocess

Sensorprocess

Furnacecontrol process

Heater controlprocess

500 Hz

500 Hz

Thermostat process500 Hz

Sensorvalues

Switch commandRoom number

DATA ACQUISITION SYSTEMSbull Collect data from sensors for subsequent processing and analysisbull Data collection processes and processing processes may have different periods

and deadlines bull Data collection may be faster than processing eg collecting information about

an explosion bull Circular or ring buffers are a mechanism for smoothing speed differences

The generic Architecture of data acquicition

98

DisplayProcess

dataSensor data

bufferSensorprocess

Sensoridentifier and

value

Sensors (each data flow is a sensor value)

Sensoridentifier and

value

Processdata

Sensor databuffer

Sensorprocess

Sensoridentifier and

value

Sensoridentifier and

value

s1

s2

s3

s4

s5

s6

In data acquisition systemsthe sensor may be generating data quickly and the key problem is to ensure that a sensor is allocated before sensor value changeThe essenitial features of this architecture is each group of sensors has three processes associated with it and convert analogue data to digital values if necessary a buffer process and a process that consumes the data carried out further processing Two groups sensors s1-s3 and s4-s6 on the right side a further procee that diplsys the sensor data Neutron flux data acquisition

Operatordisplay

Fluxprocessing

Flux databuffer

A-Dconvertor

Sensoridentifier and

flux valueProcessedflux level

Neutron flux sensors

bull A system collects data from a set of sensors monitoring the neutron flux from a nuclear reactor

bull Each sensor has a process that converts the analog input flux level into a digita signalIt passes this flux level with sensor identifies to the sensor data buffer the data processing takes the data from this bufferprocesses it and pass it to display process for output on an operator display

A ring buffer

Consumerprocess

Producerprocess

Mutual exclusionbull Producer processes collect data and add it to the buffer Consumer processes

take data from the buffer and make elements availablebull Producer and consumer processes must be mutually excluded from accessing

the same elementThe buffer must stop producer processes adding information to a full buffer and consumer processes trying to take information from an empty buffer

99

Page 11: Unit_III

Level 2 DFD The processes represented at DFD level 1 can be further refined into lower levelsThe information flow continuity has been mainted between levels 0 and 1ExampleThe process monitor sensors can be refined into a level 2 DFD

The refinement of DFDs continues until each bubble performs a simple function that would be easily implemented as a program component

Creating A Control Flow Model

79

Control flow modeling used for a large class of applications are ldquodrivenrdquo by events rather than data produce control information rather than reports or displays and process information with heavy concern for time and performance

Already noted that an event or control item is implemented as a Boolean value ie true or false1 or 0 or a discrete list of conditions

The following guidelines to select potential(possible) candidate events-

o List all sensors that are ldquoreadrdquo by the softwareo List all interrupt conditionso List all ldquoswitches ldquothat are actuated by an operatoro List all data conditionso Recalling the nounverb parse that was applied to the processing narrativereview

all ldquocontrol itemsrdquo as possible for control flow inputsoutputso Describe the behavior of a system by identifying its statesidentify how each state

is reached and define the transitions between stateso Focus on possible omissions a very common error in specifying controlfor

example ask ldquoIs there any other way I can get this state or exit from itrdquoThe Control SpecificationThe control specification (CSPEC) represents the behavior of the system in two different ways 1 State diagram 2 Program activationState diagramIt is a sequential specification of behaviorProgram activationIt also contain a program activation table is a combinatorial specification of behavior

The CSPEC describes the behavior of the system but it gives us no information about the inner working of the process that are activated as aresult of this behaviorExampleThe state diagram indicates that the transitions from the idle state can occurTwo transitions occur out of the Monitoring system status state(1)when the system is deactivated a transition occurs back to the idle state(2) when a sensor is triggered a transition to the Acting Alarm state occurs During the review consider all transition and the content of all states

The Process Specification The process specification (PSPEC) is used to describe all flow model processes that

appear at the final level of refinement The content of the process specification can include narrative texta program design

language(PDL) description of the algorithmmathematical equations tablesdiagrams or charts

The PSPEC is a lsquomini specificationrdquofor each transform at the lowest refined level of a DFD that as a guide for design of the software component that will implement the process

Example The password transform represented in the flow model for Safehome the function is perform by PSPEC

80

If the password matches an entry within the table [valid id message=true] is passed to the message and status display functionIf there is no matah [valid id message=false]is passed to the message and status display function

CLASS-BASED MODELING Class-based element of an analysis modelClasses and objectsAttributesOperationsPackagesCRC modelsCollaborations diagram

Identifying Analysis ClassesTo identify classes by examining the pbolem statement or by performing a

ldquogrammatical parserdquo the use-cases or processing narratives developed for the system to be built Classes are determined by underlinining each noun or noun clause and enter it into a simple tableIf the class is required to implement a solution then it is part of the solution space other wise if a class is necessary only to describe a solution it is part of the problem space

The following ways are for Analysis classes to manifest (marked) themselves External entities that produce or consume information to be used by a computer-based

system (eg) devicespeople Things that are part of the information domain for the problem(eg) reports displays

leeterssignals Occurrences or events that occur within the context of system operation(eg)

aproperty transfer or the completion of a series of robot movements Roles played by who interact with the system(eg) manager engineersalesperson Organizational units that are relevant to an application(eg)division groupteam Places that establish the context of the problem and the overall function of the system

(eg) manufacturing floor ) Structures that define a class of objects or related classes of objects (eg)

sensors four-wheeled vehicles or computerBudd suggests taxonomy (classification) of classes that includes producers(sources0 and consumers(sinks) of datadata managerview and helper classes

A class should never have an ldquoimperative procedural namerdquo(eg) an object with the name Imageinersion would making mistake so that inversion of the image the inversion() is an operation that applied to the class image During early stage of modeling analysis class might be defined to the example of Safehome security function performed in a ldquogrammatical parserdquo on a processing narrativeExtracting the nouns each entry in the list a potential object

Coad and Yourdon suggest six selection characteristics that should be used as an analyst considers each potential class for inclusion in the analysis model

1Retained informationThe potential class will be useful during analysis only if information about it must be remembered so that the system can function

81

2Needed servicesThe potential class must have a set of identifiable operations that can change the value of its attributes in some way3Multiple attributesDuring requirement analysis the focus should be on ldquomajor ldquo information a class with a single attribute be useful during design but better to represent ed as an attribute of another class during the analysis activity4Common attributesA set of attributes can be defined for the potential class and these attributes apply to all instances of the class5Common operationsA set of operation can be defined for the potential class and these operations apply to all instances of the class6Essential requirements External entities that appear in the problem space and produce and consume information important to the operation of any solution for the system will almost always be defined as classes in the requirements modelSpecifying AttributesAttributes are the set of data objects that fully define the class within the context of the problemExample

SystemsystemIDverificationPhonenubersystemStatusdelaytimemasterpasswordprogram()display()reset()query()modify()

The shade portion is list of attributes for the system classDefining OperationsIt define the behavior of an object The types of operations are divided into three categories (1)operations that manipulate data egadingdeletingreformattingselecting (2)operations that perform a computation (3)operations that inquire about the state of an object (4)operations that monitor an object for the occurance of a controlling eventThese functions are accomplished by operating on attributes and associationsExample Safehome processing narrative the phrases indicate that a program() operation is encapsulated by the System classClass-Responsibility-Collaborator(CRC) ModelingClass-responsibility-collaborator modeling provides simple means for identifying and organizing the classes that are relevant to system or product requirementsAmbler describes CRC modeling in the following way A CRC model is a collection of standard index cards that represent classesThe cards are divided into three sectionsDESIGN WITHIN THE CONTEXT OF SOFTWARE ENGINEERING

Design Principle1Design should be traceable to the analysis model

82

2Always consider the architecture of the system to be built3Design of data is as important as design of processing functions4Interfaces both internal and external must be designed with care5User interface design should be tuned to the needs of the end-users6Component ndashlevel design should be functionally independent7Components should be loosely coupled to one another and to the environment8Design representation(models) should be easily understandable9The design should be developed iterativelyWith each iteration the designer should stive for greater simplicity

DESIGN PROCESS AND DESIGN QUALITYDesign process

bull Design process is a sequence of steps carried through which the requirements are translated into a system or software model bull Any design may be modeled as a direct graph The graphs are collection of entities with attributes which participate in relationships bull The system should be described at several different levels of abstraction bull Design takes place in overlapping stages bull Various phases of design process are as shown in following

1 In architectural design the subsystem components can be identified2 The abstract specification is used to specify the subsystems3 The interfaces between the subsystems are designed which is called inter face design4 In component design of subsystems components is done5 The data structure is designed to hold the data6 For perfoming the required functionality the appropriate algorithm is de

signed

Software design is an iterative process through which requirements are translated into a design for constructing the software

The design is represented at a high level of abstractiona level that can be directly traced to the specific system objective and more detailed datafunctional and behavioral requirements As design iteraton occur subsequent refinement to design representation at lower levels of abstraction

McGlaughin suggests three characteristics that serve as a guide for the evaluation of a good design Each of these characteristics is a goal of the design process

The design must implement all of the explicit requirements contained in the analysis model and it must accommodate all of the implicit(indirect) requirements desired by the customer

The design must be a readable understandable guide for those who generate code and for those who test and subsequently support the software

The design should provide a complete picture of the software addressing the data functional and behavioral domains from an implementation perspective

83

Quality guidelinesThe following gidelines to evaluate the quality of a design representation

1A design should display an architecture that (a) That has been created using recognizable architectural styles or patterns

(b)That is composed of components that show good design characteristics (c)That can be implemented in an evolutionary style thereby implementing and testing2A design should be modular that is the software should be logically partitioned into elements or subsystems3A design should contain distinct representation of dataarchitectureinterfaces and components4A design should lead to data structures that are appropriate for the classes to be implemented and are drawn from recognizable data patterns5A design should lead to components that show independent functional characteristics6A design should lead to interfaces that reduce the complexity of connections between components and with the external environmemt7A design should be derived using a repeatable method that is driven by information obtained during software requirements analysis8A design should be represented using a notation that effectively communicates its meaning

Quality attributesHewlett Packard deveopled a set of software quality attributes are given as acronym(short form) FURPS to represent a target(goal) for all software design

Functionality Usability Reliability Performance Supportability

FunctionalityIt is assessed by evaluating the feature set and capabilities of the programthe generalization of the functions that are deliveredand the security of the overall systemUsabilityIt is assessed by human factors consistency and documentationReliabilityIt is evaluated by measuring the frequency and severity of failurethe accuracy of output resultsthe mean-time-to-failure(MTTF) the ability to recover from failure and predictability(unavoidability) of the programPerformanceIt is measured by processing speedresponse timeresource consumption throughput and efficiencySupportabilityItcombin the abilitytoxtendtheprogram(extensibility)adaptabilityServiceabilitymainabilitytestabilitycompatibilityconfigurability the ability to organize and control elements of the software congfiguration

Design Principles Davis suggested a set of principles for software design as

bull The design process should not suffer from ldquotunnel visionrdquobull The design should be traceable to the analysis modelbull The design should not reinvent the wheel

84

bull The design should ldquominimize the intellectual distancerdquo between the software and the problem in the real worldbull The design should exhibit uniformity and integrationbull The design should be structured to degrade gentlybull Design is not coding and coding is not designbull The design should be assessed for qualitybull The design should be reviewed to minimize conceptual errors

Design Concept

The software design concept provides a framework for implementing the right software

Following issues are considered while designing the software1Abstraction At each stage of software design process levels of abstractions should be applied to refine the software solutionAt the higher level of abstraction the solution should be stated in broad terms and in the lower level more detailed description of the solution is given While moving through different levels of abstraction the procedural abstraction and data abstraction is created In procedural abstraction it gives the named sequence of instruction in the specific function In data abstracion the collection of data objects is represented Levels of Abstraction Various levels of abstractions are- Level I - This level represents the solution interms of problem environment Level II - This level represents the decomposition of terms that are moved from problem environment but still not at implementation stage Level III - At this level preliminary procedural representation exists All the terminologies at this level are software oriented and implementation modularity begins at the surface Level IV and V - The concepts of stepwise refinement and modularity are

applied at this level2 Modularity

The software is divided into separately named and addressable components that called as modules Creating such models bring the modularity in siftwareMeyer defines five criteria that enable us to evaluate a design method with respect to its ability to define an effective modular systemModular decomposability A design method provides a systematic mechanism for decomposing the problem into sub-problems This reduces the complexity of the problem and the modularity can be achievedModular composability A design method enables existing design components to be assembled into a new systemModular understandability A module can be understood as a standalone unit Then it will be easier to build and easier to changeModular continuity Small changes to the system requirements result in changes to individual modules rather than system- wide changesModular protection An aberrant condition occurs within a module and its effects are constrained within the module3Refinement

Refinement is actually a process of elaborationStepwise refinement is a top-down design strategy proposed by Niklaus WIRTHThe architecture of a program is developed by successively refining levels of procedural detail

85

The process of program refinement is analogues to the process of refinement and partitioning that is used during requirements analysisAbstraction and refinement are complementary concepts The major difference is that - in the abstraction low-level details are suppressedRefinement helps the designer to elaborate low-levels detailsModular Design

Modular design reduces complexity and helps in easier implementation The parallel development of different parts of the system is possible due to modular designWhat is the benefit of modular design Changes made during testing and maintenance becomes manageable and they do not affect other modules Various quality parameters for effective modular design are -1) Functional independance 2) Cohesion 3) Coupling

Functional IndependenceThe functional independence can be achieved be developing the functional modules

with single-minded approachBy using functional independence functions may be compartmentalized and interfaces are simplifiedVarious types of coupling are i) Data coupling - The data coupling is possible by parameter passing or data interactionii) Control coupling - The modules share related control data in control couplingiii) Commom coupling - Content coupling occurs when one module makes use of data or control information maintained in another moduleFan-out Fan-out is a measure of the number of immediate subordinates to a moule The fan-out should be within some limit in the design If fan-out is very high then it indicates that a single module is controlling many other modules Preferably limit fan-out to no more than sevenFan-in

Fan-in indicates how many modules directly control a given module Modules with fan-in must have good cohesion Each interfac to the module must have the same number and types of parametersFactoring

Factoring means separation of function into new modules By applying factoring the size of module is reduced and thereby the complexity of the problem is reduced This also provides duplication of functions in more than one module The effective factoring brings simplification in the implementation of software design DESIGN HEURISTICS

The program structure can be manipulated according the design heuristics as shon below1Evaluate the first iteration of the program structure to reduce the coupling and improve cohesion The module independency can be achieved in the program structure by exploding or imploding the modules Exploding the modules means obtaining two or more modules in the final stage and imploding the modules means combining the result of different modules2Attempt to minimize the structure with high fan-out and strive for fan-in as depth increase At the higher level of program structure the distribution of control should be made Fan-out means number of immediate subordinates to the module Fan-in means number of immediate ancestores the module have

86

3Keep scope of the effect of a module within the scope of control of that module The decisions made in particular module lsquoarsquo should not affect the module rsquo brsquo which lies outside the scope of module lsquoarsquo4Evaluate the module interfaces to reduce complexity and redundancy and improve consistency Mostly the cause of softwatr errors is module interfaces The module interfaces should simply pass the information and should be consistent with the module5Define module whose function is predicatable but avoid modules that are too restrictive The module should be designed with simplified internal processing so that expected data can be produced as a result The modules should not restrict the size of local data structure options with control flow or modes of external interfaces Being module too much restrictive causes large maintenance6Strive for controlled entry modules by avoiding pathological connections Software interfaces should be constrained and controlled so that it will become manageable Pathological connection means many references or branches into the middle of a module

Design ModelThe design model is represented as pyramid The pyramid is a stable object

Representing design model in this way means that the software design should be stableThe design model has braod foundation of data design stable mid-region with architectural and interface design and the sharp point to for component level design

Advantages of horizontal partition1These are easy to test maintain and extend 2They have fewer side effects in change propagation or error propagation

Disadvantages of horizontal partitionMore data has to be passed across module interfaces which complicates the overall

control of program flowVertical partitioning

Vertical partitioning suggests the control and work should be distributed top-down in program structureIn vertical partitioning

Define separate branches of the module hierarchy for each major functionUse control modules to co-ordinate communication between functions

Advantages of vertical partition1These are easy to maintain the changes2 They reduce the change impact and error propagation

DATA DESIGNData design is basically the model of data that is represented at the high level of abstractionThe data design is then progressively refined to create implementation specific representationsVarious elements of data design are

Data object - The data objects are identified and relationship among various data objects can be represented using entity relationship diagrams or data dictionariesDatabases - Using software design model the data models are translated into data structures and databases at the application level

87

Data warehouses - At the business level useful information is identified from various databases and the data warehouses are created For extracting or navigating the useful business information stored in the huge data warehouse then data mining techniques are applied

ARCHITECTURAL DESIGNSoftware architecture The design process for identifying the sub-systems making up a system and the framework for sub-system control and communication is architectural design The output of this design process is a description of the software architecture

Architectural design An early stage of the system design process Represents the link between specification and design processes Often carried out in parallel with some specification activities It involves identifying major system components and their communicationsArchitecture and system characteristics Performancebull Localise critical operations and minimise communications Use large rather than fine-grain components Securitybull Use a layered architecture with critical assets in the inner layers Safetybull Localise safety-critical features in a small number of sub-systems Availabilitybull Include redundant components and mechanisms for fault tolerance Maintainabilitybull Use fine-grain replaceable components

Architectural design decisions Is there a generic application architecture that can be used How will the system be distributed What architectural styles are appropriate What approach will be used to structure the system How will the system be decomposed into modules What control strategy should be used How will the architectural design be evaluated How should the architecture be documentedArchitectural styles The architectural model of a system may conform to a generic architectural model or style An awareness of these styles can simplify the problem of defining system architectures However most large systems are heterogeneous and do not follow a single architectural styleArchitectural models

Used to document an architectural design Static structural model that shows the major system components Dynamic process model that shows the process structure of the system Interface model that defines sub-system interfaces

88

Relationships model such as a data-flow model that shows sub-system relationships Distribution model that shows how sub-systems are distributed across computers

Modular decomposition Another structural level where sub-systems are decomposed into modules Two modular decomposition models coveredbull An object model where the system is decomposed into interacting objectbull A pipeline or data-flow model where the system is decomposed into functional modules which transform inputs to outputs If possible decisions about concurrency should be delayed until modules are implemented

Object models Structure the system into a set of loosely coupled objects with well-defined interfaces Object-oriented decomposition is concerned with identifying object classes their attributes and operations When implemented objects are created from these classes and some control model used to coordinate object operations

Invoice Processing system

Pipeline model advantages Supports transformation reuse Intuitive organisation for stakeholder communication Easy to add new transformations Relatively simple to implement as either a concurrent or sequential system However requires a common format for data transfer along the pipeline and difficult

to support event-based interaction

User interface design

The user interface User interfaces should be designed to match the skills experience and expectations of

its anticipated users System users often judge a system by its interface rather than its functionality A poorly designed interface can cause a user to make catastrophic errors Poor user interface design is the reason why so many software systems are never

usedUser interface Design Principle

89

Design principles User familiaritybull The interface should be based on user-oriented terms and concepts rather than computer concepts For example an office system should use concepts such as letters documents folders etc rather than directories file identifiers etc Consistencybull The system should display an appropriate level of consistency Commands and menus should have the same format command punctuation should be similar etc Minimal surprisebull If a command operates in a known way the user should be able to predict the operation of comparable commandsbull Recoverabilitybull The system should provide some resilience to user errors and allow the user to recover from errors This might include an undo facility confirmation of destructive actions soft deletes etcbull User guidancebull Some user guidance such as help systems on-line manuals etc should be suppliedbull User diversitybull Interaction facilities for different types of user should be supported For example some users have seeing difficulties and so larger text should be available

REAL-TIME SOFTWARE DESIGNReal-time systemsSystems which monitor and control their environmentInevitably associated with hardware devices

bull Sensors Collect data from the system environmentbull Actuators Change (in some way) the systems environment

Time is critical Real-time systems must respond within specified times

Definition A real-time system is a software system where the correct functioning of the

system depends on the results produced by the system and the time at which these results are produced

90

A soft real-time system is a system whose operation is degraded if results are not produced according to the specified timing requirements

A hard real-time system is a system whose operation is incorrect if results are not produced according to the timing specification

StimulusResponse Systems Given a stimulus the system must produce a response within a specified timePeriodic stimuli Stimuli which occur at predictable time intervals

bull For example a temperature sensor may be polled 10 times per secondAperiodic stimuli Stimuli which occur at unpredictable times

bull For example a system power failure may trigger an interrupt which must be processed by the system

Architectural considerations Because of the need to respond to timing demands made by different

stimuliresponses the system architecture must allow for fast switching between stimulus handlers

Timing demands of different stimuli are different so a simple sequential loop is not usually adequate

Real-time systems are therefore usually designed as cooperating processes with a real-time executive controlling these processes

A real-time system model

Real-timecontrol system

ActuatorActuator ActuatorActuator

SensorSensorSensor SensorSensorSensor

Sensoractuator processes

Dataprocessor

Actuatorcontrol

Actuator

Sensorcontrol

Sensor

Stimulus Response

System elementsSensor control processes

bull Collect information from sensors May buffer information collected in response to a sensor stimulus

Data processorbull Carries out processing of collected information and computes the system

responseActuator control processes

91

bull Generates control signals for the actuatorsReal-time programmingHard-real time systems may have to programmed in assembly language to ensure that deadlines are metLanguages such as C allow efficient programs to be written but do not have constructs to support concurrency or shared resource management

Java as a real-time languageJava supports lightweight concurrency (threads and synchronized methods) and can be used for some soft real-time systemsJava 20 is not suitable for hard RT programming but real-time versions of Java are now available that address problems such as

bull Not possible to specify thread execution timebull Different timing in different virtual machinesbull Uncontrollable garbage collectionbull Not possible to discover queue sizes for shared resourcesbull Not possible to access system hardwarebull Not possible to do space or timing analysis

SYSTEM DESIGN Design both the hardware and the software associated with system

Partition functions to either hardware or software Design decisions should be made on the basis on non-functional

system requirements Hardware delivers better performance but potentially longer

development and less scope for changeR-T systems design process

Identify the stimuli to be processed and the required responses to these stimuli For each stimulus and response identify the timing constraints Aggregate the stimulus and response processing into concurrent processes A

process may be associated with each class of stimulus and response Design algorithms to process each class of stimulus and response These must

meet the given timing requirements Design a scheduling system which will ensure that processes are started in time to

meet their deadlines Integrate using a real-time operating system

Timing constraints May require extensive simulation and experiment to ensure that these are met by the systemMay mean that certain design strategies such as object-oriented design cannot be used because of the additional overhead involvedMay mean that low-level programming language features have to be used for performance reasons

Real-time system modellingThe effect of a stimulus in a real-time system may trigger a transition from one state to anotherFinite state machines can be used for modelling real-time systems

92

However FSM models lack structure Even simple systems can have a complex modelThe UML includes notations for defining state machine models

Petrol pump state model

Cardinserted

into reader

Timeout

Resettingdo display CC

error

Initialising

do initialisedisplay

Paying

Stopped

Reading

do get CCdetails

Waiting

do display welcome

dodeliver fuel

do debitCC account

Payment ack

Ready Delivering

update displayNozzle

trigger on

Nozzle trigger off

Nozzle trigger on

Hose inholster

do validatecredit card

Validating

Invalid card

Card removedCard OK

Hose out of holster

Timeout

Real-time operating systems(RTOS)

Real-time operating systems are specialised operating systems which manage the processes in the RTS

Responsible for process management and resource (processor and memory) allocation

May be based on a standard kernel which is used unchanged or modified for a particular application

Do not normally include facilities such as file management

Operating system componentsReal-time clock

bull Provides information for process schedulingInterrupt handler

bull Manages aperiodic requests for serviceScheduler

bull Chooses the next process to be runResource manager

bull Allocates memory and processor resourcesDispatcher

bull Starts process executionNon-stop system components

Configuration manager

93

bull Responsible for the dynamic reconfiguration of the system software and hardware Hardware modules may be replaced and software upgraded without stopping the systems

Fault managerbull Responsible for detecting software and hardware faults and taking appropriate

actions (eg switching to backup disks) to ensure that the system continues in operation

Real-time OS components

Process resourcerequirements

Scheduler

Schedulinginformation

Resourcemanager

Despatcher

Real-timeclock

Processesawaiting

resources

Readylist

Interrupthandler

Availableresource

list

Processorlist

Executing process

Readyprocesses

Releasedresources

Process priority The processing of some types of stimuli must sometimes take priority Interrupt level priority Highest priority which is allocated to processes requiring a

very fast response Clock level priority Allocated to periodic processes Within these further levels of priority may be assigned

Interrupt servicing Control is transferred automatically to a pre-determined memory location This location contains an instruction to jump to

an interrupt service routine Further interrupts are disabled the interrupt

serviced and control returned to the interrupted process

Interrupt service routines must be short simple and fast

Periodic process servicing In most real-time systems there will be several classes of periodic process each with

different periods (the time between executions) execution times and deadlines (the time by which processing must be completed)

The real-time clock ticks periodically and each tick causes an interrupt which schedules the process manager for periodic processes

The process manager selects a process which is ready for execution

Process managementbull Concerned with managing the set of concurrent processes

94

bull Periodic processes are executed at pre-specified time intervalsbull The RTOS uses the real-time clock to determine when to execute a process

taking into accountbull Process period - time between executionsbull Process deadline - the time by which processing must be complete

RTE(Real Time Execution Process) process managementResource manager

Allocate memoryand processor

Scheduler

Choose processfor execution

Despatcher

Start execution on anavailable processor

Process switchingbull The scheduler chooses the next process to be executed by the processor This

depends on a scheduling strategy which may take the process priority into account

bull The resource manager allocates memory and a processor for the process to be executed

bull The dispatcher takes the process from ready list loads it onto a processor and starts execution

Scheduling strategiesNon pre-emptive scheduling

bull Once a process has been scheduled for execution it runs to completion or until it is blocked for some reason (eg waiting for IO)

Pre-emptive schedulingbull The execution of an executing processes may be stopped if a higher priority

process requires serviceScheduling algorithms

bull Round-robinbull Rate monotonicbull Shortest deadline first

Monitoring and control systemsbull Important class of real-time systems bull Continuously check sensors and take actions

depending on sensor valuesbull Monitoring systems examine sensors and

report their resultsbull Control systems take sensor values and control hardware actuators

Generic architecture

95

S1

S2

S3

P (S1)

P (S2)

P (S1)

Monitoringprocesses

Controlprocesses

P (A1)

P (A2)

P (A1)

A1

A2

A3

P (A4) A4

Testingprocess

Control panelprocesses

Burglar alarm systembull A system is required to monitor sensors on doors and windows to detect the

presence of intruders in a buildingbull When a sensor indicates a break-in the system switches on lights around the

area and calls police automaticallybull The system should include provision for operation without a mains power

supply Sensorso Movement detectors window sensors door sensorso 50 window sensors 30 door sensors and 200 movement detectorso Voltage drop sensor Actionso When an intruder is detected police are called automaticallyo Lights are switched on in rooms with active sensorso An audible alarm is switched on

The R-T system design process

bull Identify stimuli and associated responsesbull Define the timing constraints associated with each stimulus and responsebull Allocate system functions to concurrent processesbull Design algorithms for stimulus processing and response generationbull Design a scheduling system which ensures that processes will always be

scheduled to meet their deadlinesStimuli to be processed

Power failurebull Generated aperiodically by a circuit monitor When received the system must

switch to backup power within 50 msIntruder alarm

bull Stimulus generated by system sensors Response is to call the police switch on building lights and the Power failure

bull Generated aperiodically by a circuit monitor When received the system must switch to backup power within 50 ms

bull Intruder alarmbull Stimulus generated by system sensors Response is to call the police switch

on building lights and the audible alarmbull audible alarm

Burglar alarm system processes

96

Lighting controlprocess

Audible alarmprocess

Voice synthesiserprocess

Alarm systemprocess

Power switchprocess

Building monitorprocess

Communicationprocess

Door sensorprocess

Movementdetector process

Window sensorprocess

560 Hz

60 Hz400 Hz 100 Hz

Power failureinterrupt

Alarm system

Building monitor

Alarm system

Alarm system

Alarm system

Detector status Sensor status Sensor status

Room number

Alert message

Room number

Room number

Building_monitor process 1

class BuildingMonitor extends Thread

BuildingSensor win door move

Siren siren = new Siren () Lights lights = new Lights () Synthesizer synthesizer = new Synthesizer () DoorSensors doors = new DoorSensors (30) WindowSensors windows = new WindowSensors (50) MovementSensors movements = new MovementSensors (200) PowerMonitor pm = new PowerMonitor ()

BuildingMonitor() initialise all the sensors and start the processessirenstart () lightsstart () synthesizerstart () windowsstart () doorsstart () movementsstart () pmstart ()

Building monitor process 2public void run () int room = 0 while (true) poll the movement sensors at least twice per second (400 Hz)move = movementsgetVal () poll the window sensors at least twicesecond (100 Hz)win = windowsgetVal () poll the door sensors at least twice per second (60 Hz)door = doorsgetVal ()

97

if (movesensorVal == 1 | doorsensorVal == 1 | winsensorVal == 1) a sensor has indicated an intruder if (movesensorVal == 1) room = moveroom if (doorsensorVal == 1) room = doorroom if (winsensorVal == 1 ) room = winroom lightson (room) sirenon () synthesizeron (room) break Building_monitor process 3 lightsshutdown () sirenshutdown () synthesizershutdown () windowsshutdown () doorsshutdown () movementsshutdown ()

run BuildingMonitor

Control systems

bull A burglar alarm system is primarily a monitoring system It collects data from sensors but no real-time actuator control

bull Control systems are similar but in response to sensor values the system sends control signals to actuators

bull An example of a monitoring and control system is a system that monitors temperature and switches heaters on and off

A temperature control system

Thermostatprocess

Sensorprocess

Furnacecontrol process

Heater controlprocess

500 Hz

500 Hz

Thermostat process500 Hz

Sensorvalues

Switch commandRoom number

DATA ACQUISITION SYSTEMSbull Collect data from sensors for subsequent processing and analysisbull Data collection processes and processing processes may have different periods

and deadlines bull Data collection may be faster than processing eg collecting information about

an explosion bull Circular or ring buffers are a mechanism for smoothing speed differences

The generic Architecture of data acquicition

98

DisplayProcess

dataSensor data

bufferSensorprocess

Sensoridentifier and

value

Sensors (each data flow is a sensor value)

Sensoridentifier and

value

Processdata

Sensor databuffer

Sensorprocess

Sensoridentifier and

value

Sensoridentifier and

value

s1

s2

s3

s4

s5

s6

In data acquisition systemsthe sensor may be generating data quickly and the key problem is to ensure that a sensor is allocated before sensor value changeThe essenitial features of this architecture is each group of sensors has three processes associated with it and convert analogue data to digital values if necessary a buffer process and a process that consumes the data carried out further processing Two groups sensors s1-s3 and s4-s6 on the right side a further procee that diplsys the sensor data Neutron flux data acquisition

Operatordisplay

Fluxprocessing

Flux databuffer

A-Dconvertor

Sensoridentifier and

flux valueProcessedflux level

Neutron flux sensors

bull A system collects data from a set of sensors monitoring the neutron flux from a nuclear reactor

bull Each sensor has a process that converts the analog input flux level into a digita signalIt passes this flux level with sensor identifies to the sensor data buffer the data processing takes the data from this bufferprocesses it and pass it to display process for output on an operator display

A ring buffer

Consumerprocess

Producerprocess

Mutual exclusionbull Producer processes collect data and add it to the buffer Consumer processes

take data from the buffer and make elements availablebull Producer and consumer processes must be mutually excluded from accessing

the same elementThe buffer must stop producer processes adding information to a full buffer and consumer processes trying to take information from an empty buffer

99

Page 12: Unit_III

Control flow modeling used for a large class of applications are ldquodrivenrdquo by events rather than data produce control information rather than reports or displays and process information with heavy concern for time and performance

Already noted that an event or control item is implemented as a Boolean value ie true or false1 or 0 or a discrete list of conditions

The following guidelines to select potential(possible) candidate events-

o List all sensors that are ldquoreadrdquo by the softwareo List all interrupt conditionso List all ldquoswitches ldquothat are actuated by an operatoro List all data conditionso Recalling the nounverb parse that was applied to the processing narrativereview

all ldquocontrol itemsrdquo as possible for control flow inputsoutputso Describe the behavior of a system by identifying its statesidentify how each state

is reached and define the transitions between stateso Focus on possible omissions a very common error in specifying controlfor

example ask ldquoIs there any other way I can get this state or exit from itrdquoThe Control SpecificationThe control specification (CSPEC) represents the behavior of the system in two different ways 1 State diagram 2 Program activationState diagramIt is a sequential specification of behaviorProgram activationIt also contain a program activation table is a combinatorial specification of behavior

The CSPEC describes the behavior of the system but it gives us no information about the inner working of the process that are activated as aresult of this behaviorExampleThe state diagram indicates that the transitions from the idle state can occurTwo transitions occur out of the Monitoring system status state(1)when the system is deactivated a transition occurs back to the idle state(2) when a sensor is triggered a transition to the Acting Alarm state occurs During the review consider all transition and the content of all states

The Process Specification The process specification (PSPEC) is used to describe all flow model processes that

appear at the final level of refinement The content of the process specification can include narrative texta program design

language(PDL) description of the algorithmmathematical equations tablesdiagrams or charts

The PSPEC is a lsquomini specificationrdquofor each transform at the lowest refined level of a DFD that as a guide for design of the software component that will implement the process

Example The password transform represented in the flow model for Safehome the function is perform by PSPEC

80

If the password matches an entry within the table [valid id message=true] is passed to the message and status display functionIf there is no matah [valid id message=false]is passed to the message and status display function

CLASS-BASED MODELING Class-based element of an analysis modelClasses and objectsAttributesOperationsPackagesCRC modelsCollaborations diagram

Identifying Analysis ClassesTo identify classes by examining the pbolem statement or by performing a

ldquogrammatical parserdquo the use-cases or processing narratives developed for the system to be built Classes are determined by underlinining each noun or noun clause and enter it into a simple tableIf the class is required to implement a solution then it is part of the solution space other wise if a class is necessary only to describe a solution it is part of the problem space

The following ways are for Analysis classes to manifest (marked) themselves External entities that produce or consume information to be used by a computer-based

system (eg) devicespeople Things that are part of the information domain for the problem(eg) reports displays

leeterssignals Occurrences or events that occur within the context of system operation(eg)

aproperty transfer or the completion of a series of robot movements Roles played by who interact with the system(eg) manager engineersalesperson Organizational units that are relevant to an application(eg)division groupteam Places that establish the context of the problem and the overall function of the system

(eg) manufacturing floor ) Structures that define a class of objects or related classes of objects (eg)

sensors four-wheeled vehicles or computerBudd suggests taxonomy (classification) of classes that includes producers(sources0 and consumers(sinks) of datadata managerview and helper classes

A class should never have an ldquoimperative procedural namerdquo(eg) an object with the name Imageinersion would making mistake so that inversion of the image the inversion() is an operation that applied to the class image During early stage of modeling analysis class might be defined to the example of Safehome security function performed in a ldquogrammatical parserdquo on a processing narrativeExtracting the nouns each entry in the list a potential object

Coad and Yourdon suggest six selection characteristics that should be used as an analyst considers each potential class for inclusion in the analysis model

1Retained informationThe potential class will be useful during analysis only if information about it must be remembered so that the system can function

81

2Needed servicesThe potential class must have a set of identifiable operations that can change the value of its attributes in some way3Multiple attributesDuring requirement analysis the focus should be on ldquomajor ldquo information a class with a single attribute be useful during design but better to represent ed as an attribute of another class during the analysis activity4Common attributesA set of attributes can be defined for the potential class and these attributes apply to all instances of the class5Common operationsA set of operation can be defined for the potential class and these operations apply to all instances of the class6Essential requirements External entities that appear in the problem space and produce and consume information important to the operation of any solution for the system will almost always be defined as classes in the requirements modelSpecifying AttributesAttributes are the set of data objects that fully define the class within the context of the problemExample

SystemsystemIDverificationPhonenubersystemStatusdelaytimemasterpasswordprogram()display()reset()query()modify()

The shade portion is list of attributes for the system classDefining OperationsIt define the behavior of an object The types of operations are divided into three categories (1)operations that manipulate data egadingdeletingreformattingselecting (2)operations that perform a computation (3)operations that inquire about the state of an object (4)operations that monitor an object for the occurance of a controlling eventThese functions are accomplished by operating on attributes and associationsExample Safehome processing narrative the phrases indicate that a program() operation is encapsulated by the System classClass-Responsibility-Collaborator(CRC) ModelingClass-responsibility-collaborator modeling provides simple means for identifying and organizing the classes that are relevant to system or product requirementsAmbler describes CRC modeling in the following way A CRC model is a collection of standard index cards that represent classesThe cards are divided into three sectionsDESIGN WITHIN THE CONTEXT OF SOFTWARE ENGINEERING

Design Principle1Design should be traceable to the analysis model

82

2Always consider the architecture of the system to be built3Design of data is as important as design of processing functions4Interfaces both internal and external must be designed with care5User interface design should be tuned to the needs of the end-users6Component ndashlevel design should be functionally independent7Components should be loosely coupled to one another and to the environment8Design representation(models) should be easily understandable9The design should be developed iterativelyWith each iteration the designer should stive for greater simplicity

DESIGN PROCESS AND DESIGN QUALITYDesign process

bull Design process is a sequence of steps carried through which the requirements are translated into a system or software model bull Any design may be modeled as a direct graph The graphs are collection of entities with attributes which participate in relationships bull The system should be described at several different levels of abstraction bull Design takes place in overlapping stages bull Various phases of design process are as shown in following

1 In architectural design the subsystem components can be identified2 The abstract specification is used to specify the subsystems3 The interfaces between the subsystems are designed which is called inter face design4 In component design of subsystems components is done5 The data structure is designed to hold the data6 For perfoming the required functionality the appropriate algorithm is de

signed

Software design is an iterative process through which requirements are translated into a design for constructing the software

The design is represented at a high level of abstractiona level that can be directly traced to the specific system objective and more detailed datafunctional and behavioral requirements As design iteraton occur subsequent refinement to design representation at lower levels of abstraction

McGlaughin suggests three characteristics that serve as a guide for the evaluation of a good design Each of these characteristics is a goal of the design process

The design must implement all of the explicit requirements contained in the analysis model and it must accommodate all of the implicit(indirect) requirements desired by the customer

The design must be a readable understandable guide for those who generate code and for those who test and subsequently support the software

The design should provide a complete picture of the software addressing the data functional and behavioral domains from an implementation perspective

83

Quality guidelinesThe following gidelines to evaluate the quality of a design representation

1A design should display an architecture that (a) That has been created using recognizable architectural styles or patterns

(b)That is composed of components that show good design characteristics (c)That can be implemented in an evolutionary style thereby implementing and testing2A design should be modular that is the software should be logically partitioned into elements or subsystems3A design should contain distinct representation of dataarchitectureinterfaces and components4A design should lead to data structures that are appropriate for the classes to be implemented and are drawn from recognizable data patterns5A design should lead to components that show independent functional characteristics6A design should lead to interfaces that reduce the complexity of connections between components and with the external environmemt7A design should be derived using a repeatable method that is driven by information obtained during software requirements analysis8A design should be represented using a notation that effectively communicates its meaning

Quality attributesHewlett Packard deveopled a set of software quality attributes are given as acronym(short form) FURPS to represent a target(goal) for all software design

Functionality Usability Reliability Performance Supportability

FunctionalityIt is assessed by evaluating the feature set and capabilities of the programthe generalization of the functions that are deliveredand the security of the overall systemUsabilityIt is assessed by human factors consistency and documentationReliabilityIt is evaluated by measuring the frequency and severity of failurethe accuracy of output resultsthe mean-time-to-failure(MTTF) the ability to recover from failure and predictability(unavoidability) of the programPerformanceIt is measured by processing speedresponse timeresource consumption throughput and efficiencySupportabilityItcombin the abilitytoxtendtheprogram(extensibility)adaptabilityServiceabilitymainabilitytestabilitycompatibilityconfigurability the ability to organize and control elements of the software congfiguration

Design Principles Davis suggested a set of principles for software design as

bull The design process should not suffer from ldquotunnel visionrdquobull The design should be traceable to the analysis modelbull The design should not reinvent the wheel

84

bull The design should ldquominimize the intellectual distancerdquo between the software and the problem in the real worldbull The design should exhibit uniformity and integrationbull The design should be structured to degrade gentlybull Design is not coding and coding is not designbull The design should be assessed for qualitybull The design should be reviewed to minimize conceptual errors

Design Concept

The software design concept provides a framework for implementing the right software

Following issues are considered while designing the software1Abstraction At each stage of software design process levels of abstractions should be applied to refine the software solutionAt the higher level of abstraction the solution should be stated in broad terms and in the lower level more detailed description of the solution is given While moving through different levels of abstraction the procedural abstraction and data abstraction is created In procedural abstraction it gives the named sequence of instruction in the specific function In data abstracion the collection of data objects is represented Levels of Abstraction Various levels of abstractions are- Level I - This level represents the solution interms of problem environment Level II - This level represents the decomposition of terms that are moved from problem environment but still not at implementation stage Level III - At this level preliminary procedural representation exists All the terminologies at this level are software oriented and implementation modularity begins at the surface Level IV and V - The concepts of stepwise refinement and modularity are

applied at this level2 Modularity

The software is divided into separately named and addressable components that called as modules Creating such models bring the modularity in siftwareMeyer defines five criteria that enable us to evaluate a design method with respect to its ability to define an effective modular systemModular decomposability A design method provides a systematic mechanism for decomposing the problem into sub-problems This reduces the complexity of the problem and the modularity can be achievedModular composability A design method enables existing design components to be assembled into a new systemModular understandability A module can be understood as a standalone unit Then it will be easier to build and easier to changeModular continuity Small changes to the system requirements result in changes to individual modules rather than system- wide changesModular protection An aberrant condition occurs within a module and its effects are constrained within the module3Refinement

Refinement is actually a process of elaborationStepwise refinement is a top-down design strategy proposed by Niklaus WIRTHThe architecture of a program is developed by successively refining levels of procedural detail

85

The process of program refinement is analogues to the process of refinement and partitioning that is used during requirements analysisAbstraction and refinement are complementary concepts The major difference is that - in the abstraction low-level details are suppressedRefinement helps the designer to elaborate low-levels detailsModular Design

Modular design reduces complexity and helps in easier implementation The parallel development of different parts of the system is possible due to modular designWhat is the benefit of modular design Changes made during testing and maintenance becomes manageable and they do not affect other modules Various quality parameters for effective modular design are -1) Functional independance 2) Cohesion 3) Coupling

Functional IndependenceThe functional independence can be achieved be developing the functional modules

with single-minded approachBy using functional independence functions may be compartmentalized and interfaces are simplifiedVarious types of coupling are i) Data coupling - The data coupling is possible by parameter passing or data interactionii) Control coupling - The modules share related control data in control couplingiii) Commom coupling - Content coupling occurs when one module makes use of data or control information maintained in another moduleFan-out Fan-out is a measure of the number of immediate subordinates to a moule The fan-out should be within some limit in the design If fan-out is very high then it indicates that a single module is controlling many other modules Preferably limit fan-out to no more than sevenFan-in

Fan-in indicates how many modules directly control a given module Modules with fan-in must have good cohesion Each interfac to the module must have the same number and types of parametersFactoring

Factoring means separation of function into new modules By applying factoring the size of module is reduced and thereby the complexity of the problem is reduced This also provides duplication of functions in more than one module The effective factoring brings simplification in the implementation of software design DESIGN HEURISTICS

The program structure can be manipulated according the design heuristics as shon below1Evaluate the first iteration of the program structure to reduce the coupling and improve cohesion The module independency can be achieved in the program structure by exploding or imploding the modules Exploding the modules means obtaining two or more modules in the final stage and imploding the modules means combining the result of different modules2Attempt to minimize the structure with high fan-out and strive for fan-in as depth increase At the higher level of program structure the distribution of control should be made Fan-out means number of immediate subordinates to the module Fan-in means number of immediate ancestores the module have

86

3Keep scope of the effect of a module within the scope of control of that module The decisions made in particular module lsquoarsquo should not affect the module rsquo brsquo which lies outside the scope of module lsquoarsquo4Evaluate the module interfaces to reduce complexity and redundancy and improve consistency Mostly the cause of softwatr errors is module interfaces The module interfaces should simply pass the information and should be consistent with the module5Define module whose function is predicatable but avoid modules that are too restrictive The module should be designed with simplified internal processing so that expected data can be produced as a result The modules should not restrict the size of local data structure options with control flow or modes of external interfaces Being module too much restrictive causes large maintenance6Strive for controlled entry modules by avoiding pathological connections Software interfaces should be constrained and controlled so that it will become manageable Pathological connection means many references or branches into the middle of a module

Design ModelThe design model is represented as pyramid The pyramid is a stable object

Representing design model in this way means that the software design should be stableThe design model has braod foundation of data design stable mid-region with architectural and interface design and the sharp point to for component level design

Advantages of horizontal partition1These are easy to test maintain and extend 2They have fewer side effects in change propagation or error propagation

Disadvantages of horizontal partitionMore data has to be passed across module interfaces which complicates the overall

control of program flowVertical partitioning

Vertical partitioning suggests the control and work should be distributed top-down in program structureIn vertical partitioning

Define separate branches of the module hierarchy for each major functionUse control modules to co-ordinate communication between functions

Advantages of vertical partition1These are easy to maintain the changes2 They reduce the change impact and error propagation

DATA DESIGNData design is basically the model of data that is represented at the high level of abstractionThe data design is then progressively refined to create implementation specific representationsVarious elements of data design are

Data object - The data objects are identified and relationship among various data objects can be represented using entity relationship diagrams or data dictionariesDatabases - Using software design model the data models are translated into data structures and databases at the application level

87

Data warehouses - At the business level useful information is identified from various databases and the data warehouses are created For extracting or navigating the useful business information stored in the huge data warehouse then data mining techniques are applied

ARCHITECTURAL DESIGNSoftware architecture The design process for identifying the sub-systems making up a system and the framework for sub-system control and communication is architectural design The output of this design process is a description of the software architecture

Architectural design An early stage of the system design process Represents the link between specification and design processes Often carried out in parallel with some specification activities It involves identifying major system components and their communicationsArchitecture and system characteristics Performancebull Localise critical operations and minimise communications Use large rather than fine-grain components Securitybull Use a layered architecture with critical assets in the inner layers Safetybull Localise safety-critical features in a small number of sub-systems Availabilitybull Include redundant components and mechanisms for fault tolerance Maintainabilitybull Use fine-grain replaceable components

Architectural design decisions Is there a generic application architecture that can be used How will the system be distributed What architectural styles are appropriate What approach will be used to structure the system How will the system be decomposed into modules What control strategy should be used How will the architectural design be evaluated How should the architecture be documentedArchitectural styles The architectural model of a system may conform to a generic architectural model or style An awareness of these styles can simplify the problem of defining system architectures However most large systems are heterogeneous and do not follow a single architectural styleArchitectural models

Used to document an architectural design Static structural model that shows the major system components Dynamic process model that shows the process structure of the system Interface model that defines sub-system interfaces

88

Relationships model such as a data-flow model that shows sub-system relationships Distribution model that shows how sub-systems are distributed across computers

Modular decomposition Another structural level where sub-systems are decomposed into modules Two modular decomposition models coveredbull An object model where the system is decomposed into interacting objectbull A pipeline or data-flow model where the system is decomposed into functional modules which transform inputs to outputs If possible decisions about concurrency should be delayed until modules are implemented

Object models Structure the system into a set of loosely coupled objects with well-defined interfaces Object-oriented decomposition is concerned with identifying object classes their attributes and operations When implemented objects are created from these classes and some control model used to coordinate object operations

Invoice Processing system

Pipeline model advantages Supports transformation reuse Intuitive organisation for stakeholder communication Easy to add new transformations Relatively simple to implement as either a concurrent or sequential system However requires a common format for data transfer along the pipeline and difficult

to support event-based interaction

User interface design

The user interface User interfaces should be designed to match the skills experience and expectations of

its anticipated users System users often judge a system by its interface rather than its functionality A poorly designed interface can cause a user to make catastrophic errors Poor user interface design is the reason why so many software systems are never

usedUser interface Design Principle

89

Design principles User familiaritybull The interface should be based on user-oriented terms and concepts rather than computer concepts For example an office system should use concepts such as letters documents folders etc rather than directories file identifiers etc Consistencybull The system should display an appropriate level of consistency Commands and menus should have the same format command punctuation should be similar etc Minimal surprisebull If a command operates in a known way the user should be able to predict the operation of comparable commandsbull Recoverabilitybull The system should provide some resilience to user errors and allow the user to recover from errors This might include an undo facility confirmation of destructive actions soft deletes etcbull User guidancebull Some user guidance such as help systems on-line manuals etc should be suppliedbull User diversitybull Interaction facilities for different types of user should be supported For example some users have seeing difficulties and so larger text should be available

REAL-TIME SOFTWARE DESIGNReal-time systemsSystems which monitor and control their environmentInevitably associated with hardware devices

bull Sensors Collect data from the system environmentbull Actuators Change (in some way) the systems environment

Time is critical Real-time systems must respond within specified times

Definition A real-time system is a software system where the correct functioning of the

system depends on the results produced by the system and the time at which these results are produced

90

A soft real-time system is a system whose operation is degraded if results are not produced according to the specified timing requirements

A hard real-time system is a system whose operation is incorrect if results are not produced according to the timing specification

StimulusResponse Systems Given a stimulus the system must produce a response within a specified timePeriodic stimuli Stimuli which occur at predictable time intervals

bull For example a temperature sensor may be polled 10 times per secondAperiodic stimuli Stimuli which occur at unpredictable times

bull For example a system power failure may trigger an interrupt which must be processed by the system

Architectural considerations Because of the need to respond to timing demands made by different

stimuliresponses the system architecture must allow for fast switching between stimulus handlers

Timing demands of different stimuli are different so a simple sequential loop is not usually adequate

Real-time systems are therefore usually designed as cooperating processes with a real-time executive controlling these processes

A real-time system model

Real-timecontrol system

ActuatorActuator ActuatorActuator

SensorSensorSensor SensorSensorSensor

Sensoractuator processes

Dataprocessor

Actuatorcontrol

Actuator

Sensorcontrol

Sensor

Stimulus Response

System elementsSensor control processes

bull Collect information from sensors May buffer information collected in response to a sensor stimulus

Data processorbull Carries out processing of collected information and computes the system

responseActuator control processes

91

bull Generates control signals for the actuatorsReal-time programmingHard-real time systems may have to programmed in assembly language to ensure that deadlines are metLanguages such as C allow efficient programs to be written but do not have constructs to support concurrency or shared resource management

Java as a real-time languageJava supports lightweight concurrency (threads and synchronized methods) and can be used for some soft real-time systemsJava 20 is not suitable for hard RT programming but real-time versions of Java are now available that address problems such as

bull Not possible to specify thread execution timebull Different timing in different virtual machinesbull Uncontrollable garbage collectionbull Not possible to discover queue sizes for shared resourcesbull Not possible to access system hardwarebull Not possible to do space or timing analysis

SYSTEM DESIGN Design both the hardware and the software associated with system

Partition functions to either hardware or software Design decisions should be made on the basis on non-functional

system requirements Hardware delivers better performance but potentially longer

development and less scope for changeR-T systems design process

Identify the stimuli to be processed and the required responses to these stimuli For each stimulus and response identify the timing constraints Aggregate the stimulus and response processing into concurrent processes A

process may be associated with each class of stimulus and response Design algorithms to process each class of stimulus and response These must

meet the given timing requirements Design a scheduling system which will ensure that processes are started in time to

meet their deadlines Integrate using a real-time operating system

Timing constraints May require extensive simulation and experiment to ensure that these are met by the systemMay mean that certain design strategies such as object-oriented design cannot be used because of the additional overhead involvedMay mean that low-level programming language features have to be used for performance reasons

Real-time system modellingThe effect of a stimulus in a real-time system may trigger a transition from one state to anotherFinite state machines can be used for modelling real-time systems

92

However FSM models lack structure Even simple systems can have a complex modelThe UML includes notations for defining state machine models

Petrol pump state model

Cardinserted

into reader

Timeout

Resettingdo display CC

error

Initialising

do initialisedisplay

Paying

Stopped

Reading

do get CCdetails

Waiting

do display welcome

dodeliver fuel

do debitCC account

Payment ack

Ready Delivering

update displayNozzle

trigger on

Nozzle trigger off

Nozzle trigger on

Hose inholster

do validatecredit card

Validating

Invalid card

Card removedCard OK

Hose out of holster

Timeout

Real-time operating systems(RTOS)

Real-time operating systems are specialised operating systems which manage the processes in the RTS

Responsible for process management and resource (processor and memory) allocation

May be based on a standard kernel which is used unchanged or modified for a particular application

Do not normally include facilities such as file management

Operating system componentsReal-time clock

bull Provides information for process schedulingInterrupt handler

bull Manages aperiodic requests for serviceScheduler

bull Chooses the next process to be runResource manager

bull Allocates memory and processor resourcesDispatcher

bull Starts process executionNon-stop system components

Configuration manager

93

bull Responsible for the dynamic reconfiguration of the system software and hardware Hardware modules may be replaced and software upgraded without stopping the systems

Fault managerbull Responsible for detecting software and hardware faults and taking appropriate

actions (eg switching to backup disks) to ensure that the system continues in operation

Real-time OS components

Process resourcerequirements

Scheduler

Schedulinginformation

Resourcemanager

Despatcher

Real-timeclock

Processesawaiting

resources

Readylist

Interrupthandler

Availableresource

list

Processorlist

Executing process

Readyprocesses

Releasedresources

Process priority The processing of some types of stimuli must sometimes take priority Interrupt level priority Highest priority which is allocated to processes requiring a

very fast response Clock level priority Allocated to periodic processes Within these further levels of priority may be assigned

Interrupt servicing Control is transferred automatically to a pre-determined memory location This location contains an instruction to jump to

an interrupt service routine Further interrupts are disabled the interrupt

serviced and control returned to the interrupted process

Interrupt service routines must be short simple and fast

Periodic process servicing In most real-time systems there will be several classes of periodic process each with

different periods (the time between executions) execution times and deadlines (the time by which processing must be completed)

The real-time clock ticks periodically and each tick causes an interrupt which schedules the process manager for periodic processes

The process manager selects a process which is ready for execution

Process managementbull Concerned with managing the set of concurrent processes

94

bull Periodic processes are executed at pre-specified time intervalsbull The RTOS uses the real-time clock to determine when to execute a process

taking into accountbull Process period - time between executionsbull Process deadline - the time by which processing must be complete

RTE(Real Time Execution Process) process managementResource manager

Allocate memoryand processor

Scheduler

Choose processfor execution

Despatcher

Start execution on anavailable processor

Process switchingbull The scheduler chooses the next process to be executed by the processor This

depends on a scheduling strategy which may take the process priority into account

bull The resource manager allocates memory and a processor for the process to be executed

bull The dispatcher takes the process from ready list loads it onto a processor and starts execution

Scheduling strategiesNon pre-emptive scheduling

bull Once a process has been scheduled for execution it runs to completion or until it is blocked for some reason (eg waiting for IO)

Pre-emptive schedulingbull The execution of an executing processes may be stopped if a higher priority

process requires serviceScheduling algorithms

bull Round-robinbull Rate monotonicbull Shortest deadline first

Monitoring and control systemsbull Important class of real-time systems bull Continuously check sensors and take actions

depending on sensor valuesbull Monitoring systems examine sensors and

report their resultsbull Control systems take sensor values and control hardware actuators

Generic architecture

95

S1

S2

S3

P (S1)

P (S2)

P (S1)

Monitoringprocesses

Controlprocesses

P (A1)

P (A2)

P (A1)

A1

A2

A3

P (A4) A4

Testingprocess

Control panelprocesses

Burglar alarm systembull A system is required to monitor sensors on doors and windows to detect the

presence of intruders in a buildingbull When a sensor indicates a break-in the system switches on lights around the

area and calls police automaticallybull The system should include provision for operation without a mains power

supply Sensorso Movement detectors window sensors door sensorso 50 window sensors 30 door sensors and 200 movement detectorso Voltage drop sensor Actionso When an intruder is detected police are called automaticallyo Lights are switched on in rooms with active sensorso An audible alarm is switched on

The R-T system design process

bull Identify stimuli and associated responsesbull Define the timing constraints associated with each stimulus and responsebull Allocate system functions to concurrent processesbull Design algorithms for stimulus processing and response generationbull Design a scheduling system which ensures that processes will always be

scheduled to meet their deadlinesStimuli to be processed

Power failurebull Generated aperiodically by a circuit monitor When received the system must

switch to backup power within 50 msIntruder alarm

bull Stimulus generated by system sensors Response is to call the police switch on building lights and the Power failure

bull Generated aperiodically by a circuit monitor When received the system must switch to backup power within 50 ms

bull Intruder alarmbull Stimulus generated by system sensors Response is to call the police switch

on building lights and the audible alarmbull audible alarm

Burglar alarm system processes

96

Lighting controlprocess

Audible alarmprocess

Voice synthesiserprocess

Alarm systemprocess

Power switchprocess

Building monitorprocess

Communicationprocess

Door sensorprocess

Movementdetector process

Window sensorprocess

560 Hz

60 Hz400 Hz 100 Hz

Power failureinterrupt

Alarm system

Building monitor

Alarm system

Alarm system

Alarm system

Detector status Sensor status Sensor status

Room number

Alert message

Room number

Room number

Building_monitor process 1

class BuildingMonitor extends Thread

BuildingSensor win door move

Siren siren = new Siren () Lights lights = new Lights () Synthesizer synthesizer = new Synthesizer () DoorSensors doors = new DoorSensors (30) WindowSensors windows = new WindowSensors (50) MovementSensors movements = new MovementSensors (200) PowerMonitor pm = new PowerMonitor ()

BuildingMonitor() initialise all the sensors and start the processessirenstart () lightsstart () synthesizerstart () windowsstart () doorsstart () movementsstart () pmstart ()

Building monitor process 2public void run () int room = 0 while (true) poll the movement sensors at least twice per second (400 Hz)move = movementsgetVal () poll the window sensors at least twicesecond (100 Hz)win = windowsgetVal () poll the door sensors at least twice per second (60 Hz)door = doorsgetVal ()

97

if (movesensorVal == 1 | doorsensorVal == 1 | winsensorVal == 1) a sensor has indicated an intruder if (movesensorVal == 1) room = moveroom if (doorsensorVal == 1) room = doorroom if (winsensorVal == 1 ) room = winroom lightson (room) sirenon () synthesizeron (room) break Building_monitor process 3 lightsshutdown () sirenshutdown () synthesizershutdown () windowsshutdown () doorsshutdown () movementsshutdown ()

run BuildingMonitor

Control systems

bull A burglar alarm system is primarily a monitoring system It collects data from sensors but no real-time actuator control

bull Control systems are similar but in response to sensor values the system sends control signals to actuators

bull An example of a monitoring and control system is a system that monitors temperature and switches heaters on and off

A temperature control system

Thermostatprocess

Sensorprocess

Furnacecontrol process

Heater controlprocess

500 Hz

500 Hz

Thermostat process500 Hz

Sensorvalues

Switch commandRoom number

DATA ACQUISITION SYSTEMSbull Collect data from sensors for subsequent processing and analysisbull Data collection processes and processing processes may have different periods

and deadlines bull Data collection may be faster than processing eg collecting information about

an explosion bull Circular or ring buffers are a mechanism for smoothing speed differences

The generic Architecture of data acquicition

98

DisplayProcess

dataSensor data

bufferSensorprocess

Sensoridentifier and

value

Sensors (each data flow is a sensor value)

Sensoridentifier and

value

Processdata

Sensor databuffer

Sensorprocess

Sensoridentifier and

value

Sensoridentifier and

value

s1

s2

s3

s4

s5

s6

In data acquisition systemsthe sensor may be generating data quickly and the key problem is to ensure that a sensor is allocated before sensor value changeThe essenitial features of this architecture is each group of sensors has three processes associated with it and convert analogue data to digital values if necessary a buffer process and a process that consumes the data carried out further processing Two groups sensors s1-s3 and s4-s6 on the right side a further procee that diplsys the sensor data Neutron flux data acquisition

Operatordisplay

Fluxprocessing

Flux databuffer

A-Dconvertor

Sensoridentifier and

flux valueProcessedflux level

Neutron flux sensors

bull A system collects data from a set of sensors monitoring the neutron flux from a nuclear reactor

bull Each sensor has a process that converts the analog input flux level into a digita signalIt passes this flux level with sensor identifies to the sensor data buffer the data processing takes the data from this bufferprocesses it and pass it to display process for output on an operator display

A ring buffer

Consumerprocess

Producerprocess

Mutual exclusionbull Producer processes collect data and add it to the buffer Consumer processes

take data from the buffer and make elements availablebull Producer and consumer processes must be mutually excluded from accessing

the same elementThe buffer must stop producer processes adding information to a full buffer and consumer processes trying to take information from an empty buffer

99

Page 13: Unit_III

If the password matches an entry within the table [valid id message=true] is passed to the message and status display functionIf there is no matah [valid id message=false]is passed to the message and status display function

CLASS-BASED MODELING Class-based element of an analysis modelClasses and objectsAttributesOperationsPackagesCRC modelsCollaborations diagram

Identifying Analysis ClassesTo identify classes by examining the pbolem statement or by performing a

ldquogrammatical parserdquo the use-cases or processing narratives developed for the system to be built Classes are determined by underlinining each noun or noun clause and enter it into a simple tableIf the class is required to implement a solution then it is part of the solution space other wise if a class is necessary only to describe a solution it is part of the problem space

The following ways are for Analysis classes to manifest (marked) themselves External entities that produce or consume information to be used by a computer-based

system (eg) devicespeople Things that are part of the information domain for the problem(eg) reports displays

leeterssignals Occurrences or events that occur within the context of system operation(eg)

aproperty transfer or the completion of a series of robot movements Roles played by who interact with the system(eg) manager engineersalesperson Organizational units that are relevant to an application(eg)division groupteam Places that establish the context of the problem and the overall function of the system

(eg) manufacturing floor ) Structures that define a class of objects or related classes of objects (eg)

sensors four-wheeled vehicles or computerBudd suggests taxonomy (classification) of classes that includes producers(sources0 and consumers(sinks) of datadata managerview and helper classes

A class should never have an ldquoimperative procedural namerdquo(eg) an object with the name Imageinersion would making mistake so that inversion of the image the inversion() is an operation that applied to the class image During early stage of modeling analysis class might be defined to the example of Safehome security function performed in a ldquogrammatical parserdquo on a processing narrativeExtracting the nouns each entry in the list a potential object

Coad and Yourdon suggest six selection characteristics that should be used as an analyst considers each potential class for inclusion in the analysis model

1Retained informationThe potential class will be useful during analysis only if information about it must be remembered so that the system can function

81

2Needed servicesThe potential class must have a set of identifiable operations that can change the value of its attributes in some way3Multiple attributesDuring requirement analysis the focus should be on ldquomajor ldquo information a class with a single attribute be useful during design but better to represent ed as an attribute of another class during the analysis activity4Common attributesA set of attributes can be defined for the potential class and these attributes apply to all instances of the class5Common operationsA set of operation can be defined for the potential class and these operations apply to all instances of the class6Essential requirements External entities that appear in the problem space and produce and consume information important to the operation of any solution for the system will almost always be defined as classes in the requirements modelSpecifying AttributesAttributes are the set of data objects that fully define the class within the context of the problemExample

SystemsystemIDverificationPhonenubersystemStatusdelaytimemasterpasswordprogram()display()reset()query()modify()

The shade portion is list of attributes for the system classDefining OperationsIt define the behavior of an object The types of operations are divided into three categories (1)operations that manipulate data egadingdeletingreformattingselecting (2)operations that perform a computation (3)operations that inquire about the state of an object (4)operations that monitor an object for the occurance of a controlling eventThese functions are accomplished by operating on attributes and associationsExample Safehome processing narrative the phrases indicate that a program() operation is encapsulated by the System classClass-Responsibility-Collaborator(CRC) ModelingClass-responsibility-collaborator modeling provides simple means for identifying and organizing the classes that are relevant to system or product requirementsAmbler describes CRC modeling in the following way A CRC model is a collection of standard index cards that represent classesThe cards are divided into three sectionsDESIGN WITHIN THE CONTEXT OF SOFTWARE ENGINEERING

Design Principle1Design should be traceable to the analysis model

82

2Always consider the architecture of the system to be built3Design of data is as important as design of processing functions4Interfaces both internal and external must be designed with care5User interface design should be tuned to the needs of the end-users6Component ndashlevel design should be functionally independent7Components should be loosely coupled to one another and to the environment8Design representation(models) should be easily understandable9The design should be developed iterativelyWith each iteration the designer should stive for greater simplicity

DESIGN PROCESS AND DESIGN QUALITYDesign process

bull Design process is a sequence of steps carried through which the requirements are translated into a system or software model bull Any design may be modeled as a direct graph The graphs are collection of entities with attributes which participate in relationships bull The system should be described at several different levels of abstraction bull Design takes place in overlapping stages bull Various phases of design process are as shown in following

1 In architectural design the subsystem components can be identified2 The abstract specification is used to specify the subsystems3 The interfaces between the subsystems are designed which is called inter face design4 In component design of subsystems components is done5 The data structure is designed to hold the data6 For perfoming the required functionality the appropriate algorithm is de

signed

Software design is an iterative process through which requirements are translated into a design for constructing the software

The design is represented at a high level of abstractiona level that can be directly traced to the specific system objective and more detailed datafunctional and behavioral requirements As design iteraton occur subsequent refinement to design representation at lower levels of abstraction

McGlaughin suggests three characteristics that serve as a guide for the evaluation of a good design Each of these characteristics is a goal of the design process

The design must implement all of the explicit requirements contained in the analysis model and it must accommodate all of the implicit(indirect) requirements desired by the customer

The design must be a readable understandable guide for those who generate code and for those who test and subsequently support the software

The design should provide a complete picture of the software addressing the data functional and behavioral domains from an implementation perspective

83

Quality guidelinesThe following gidelines to evaluate the quality of a design representation

1A design should display an architecture that (a) That has been created using recognizable architectural styles or patterns

(b)That is composed of components that show good design characteristics (c)That can be implemented in an evolutionary style thereby implementing and testing2A design should be modular that is the software should be logically partitioned into elements or subsystems3A design should contain distinct representation of dataarchitectureinterfaces and components4A design should lead to data structures that are appropriate for the classes to be implemented and are drawn from recognizable data patterns5A design should lead to components that show independent functional characteristics6A design should lead to interfaces that reduce the complexity of connections between components and with the external environmemt7A design should be derived using a repeatable method that is driven by information obtained during software requirements analysis8A design should be represented using a notation that effectively communicates its meaning

Quality attributesHewlett Packard deveopled a set of software quality attributes are given as acronym(short form) FURPS to represent a target(goal) for all software design

Functionality Usability Reliability Performance Supportability

FunctionalityIt is assessed by evaluating the feature set and capabilities of the programthe generalization of the functions that are deliveredand the security of the overall systemUsabilityIt is assessed by human factors consistency and documentationReliabilityIt is evaluated by measuring the frequency and severity of failurethe accuracy of output resultsthe mean-time-to-failure(MTTF) the ability to recover from failure and predictability(unavoidability) of the programPerformanceIt is measured by processing speedresponse timeresource consumption throughput and efficiencySupportabilityItcombin the abilitytoxtendtheprogram(extensibility)adaptabilityServiceabilitymainabilitytestabilitycompatibilityconfigurability the ability to organize and control elements of the software congfiguration

Design Principles Davis suggested a set of principles for software design as

bull The design process should not suffer from ldquotunnel visionrdquobull The design should be traceable to the analysis modelbull The design should not reinvent the wheel

84

bull The design should ldquominimize the intellectual distancerdquo between the software and the problem in the real worldbull The design should exhibit uniformity and integrationbull The design should be structured to degrade gentlybull Design is not coding and coding is not designbull The design should be assessed for qualitybull The design should be reviewed to minimize conceptual errors

Design Concept

The software design concept provides a framework for implementing the right software

Following issues are considered while designing the software1Abstraction At each stage of software design process levels of abstractions should be applied to refine the software solutionAt the higher level of abstraction the solution should be stated in broad terms and in the lower level more detailed description of the solution is given While moving through different levels of abstraction the procedural abstraction and data abstraction is created In procedural abstraction it gives the named sequence of instruction in the specific function In data abstracion the collection of data objects is represented Levels of Abstraction Various levels of abstractions are- Level I - This level represents the solution interms of problem environment Level II - This level represents the decomposition of terms that are moved from problem environment but still not at implementation stage Level III - At this level preliminary procedural representation exists All the terminologies at this level are software oriented and implementation modularity begins at the surface Level IV and V - The concepts of stepwise refinement and modularity are

applied at this level2 Modularity

The software is divided into separately named and addressable components that called as modules Creating such models bring the modularity in siftwareMeyer defines five criteria that enable us to evaluate a design method with respect to its ability to define an effective modular systemModular decomposability A design method provides a systematic mechanism for decomposing the problem into sub-problems This reduces the complexity of the problem and the modularity can be achievedModular composability A design method enables existing design components to be assembled into a new systemModular understandability A module can be understood as a standalone unit Then it will be easier to build and easier to changeModular continuity Small changes to the system requirements result in changes to individual modules rather than system- wide changesModular protection An aberrant condition occurs within a module and its effects are constrained within the module3Refinement

Refinement is actually a process of elaborationStepwise refinement is a top-down design strategy proposed by Niklaus WIRTHThe architecture of a program is developed by successively refining levels of procedural detail

85

The process of program refinement is analogues to the process of refinement and partitioning that is used during requirements analysisAbstraction and refinement are complementary concepts The major difference is that - in the abstraction low-level details are suppressedRefinement helps the designer to elaborate low-levels detailsModular Design

Modular design reduces complexity and helps in easier implementation The parallel development of different parts of the system is possible due to modular designWhat is the benefit of modular design Changes made during testing and maintenance becomes manageable and they do not affect other modules Various quality parameters for effective modular design are -1) Functional independance 2) Cohesion 3) Coupling

Functional IndependenceThe functional independence can be achieved be developing the functional modules

with single-minded approachBy using functional independence functions may be compartmentalized and interfaces are simplifiedVarious types of coupling are i) Data coupling - The data coupling is possible by parameter passing or data interactionii) Control coupling - The modules share related control data in control couplingiii) Commom coupling - Content coupling occurs when one module makes use of data or control information maintained in another moduleFan-out Fan-out is a measure of the number of immediate subordinates to a moule The fan-out should be within some limit in the design If fan-out is very high then it indicates that a single module is controlling many other modules Preferably limit fan-out to no more than sevenFan-in

Fan-in indicates how many modules directly control a given module Modules with fan-in must have good cohesion Each interfac to the module must have the same number and types of parametersFactoring

Factoring means separation of function into new modules By applying factoring the size of module is reduced and thereby the complexity of the problem is reduced This also provides duplication of functions in more than one module The effective factoring brings simplification in the implementation of software design DESIGN HEURISTICS

The program structure can be manipulated according the design heuristics as shon below1Evaluate the first iteration of the program structure to reduce the coupling and improve cohesion The module independency can be achieved in the program structure by exploding or imploding the modules Exploding the modules means obtaining two or more modules in the final stage and imploding the modules means combining the result of different modules2Attempt to minimize the structure with high fan-out and strive for fan-in as depth increase At the higher level of program structure the distribution of control should be made Fan-out means number of immediate subordinates to the module Fan-in means number of immediate ancestores the module have

86

3Keep scope of the effect of a module within the scope of control of that module The decisions made in particular module lsquoarsquo should not affect the module rsquo brsquo which lies outside the scope of module lsquoarsquo4Evaluate the module interfaces to reduce complexity and redundancy and improve consistency Mostly the cause of softwatr errors is module interfaces The module interfaces should simply pass the information and should be consistent with the module5Define module whose function is predicatable but avoid modules that are too restrictive The module should be designed with simplified internal processing so that expected data can be produced as a result The modules should not restrict the size of local data structure options with control flow or modes of external interfaces Being module too much restrictive causes large maintenance6Strive for controlled entry modules by avoiding pathological connections Software interfaces should be constrained and controlled so that it will become manageable Pathological connection means many references or branches into the middle of a module

Design ModelThe design model is represented as pyramid The pyramid is a stable object

Representing design model in this way means that the software design should be stableThe design model has braod foundation of data design stable mid-region with architectural and interface design and the sharp point to for component level design

Advantages of horizontal partition1These are easy to test maintain and extend 2They have fewer side effects in change propagation or error propagation

Disadvantages of horizontal partitionMore data has to be passed across module interfaces which complicates the overall

control of program flowVertical partitioning

Vertical partitioning suggests the control and work should be distributed top-down in program structureIn vertical partitioning

Define separate branches of the module hierarchy for each major functionUse control modules to co-ordinate communication between functions

Advantages of vertical partition1These are easy to maintain the changes2 They reduce the change impact and error propagation

DATA DESIGNData design is basically the model of data that is represented at the high level of abstractionThe data design is then progressively refined to create implementation specific representationsVarious elements of data design are

Data object - The data objects are identified and relationship among various data objects can be represented using entity relationship diagrams or data dictionariesDatabases - Using software design model the data models are translated into data structures and databases at the application level

87

Data warehouses - At the business level useful information is identified from various databases and the data warehouses are created For extracting or navigating the useful business information stored in the huge data warehouse then data mining techniques are applied

ARCHITECTURAL DESIGNSoftware architecture The design process for identifying the sub-systems making up a system and the framework for sub-system control and communication is architectural design The output of this design process is a description of the software architecture

Architectural design An early stage of the system design process Represents the link between specification and design processes Often carried out in parallel with some specification activities It involves identifying major system components and their communicationsArchitecture and system characteristics Performancebull Localise critical operations and minimise communications Use large rather than fine-grain components Securitybull Use a layered architecture with critical assets in the inner layers Safetybull Localise safety-critical features in a small number of sub-systems Availabilitybull Include redundant components and mechanisms for fault tolerance Maintainabilitybull Use fine-grain replaceable components

Architectural design decisions Is there a generic application architecture that can be used How will the system be distributed What architectural styles are appropriate What approach will be used to structure the system How will the system be decomposed into modules What control strategy should be used How will the architectural design be evaluated How should the architecture be documentedArchitectural styles The architectural model of a system may conform to a generic architectural model or style An awareness of these styles can simplify the problem of defining system architectures However most large systems are heterogeneous and do not follow a single architectural styleArchitectural models

Used to document an architectural design Static structural model that shows the major system components Dynamic process model that shows the process structure of the system Interface model that defines sub-system interfaces

88

Relationships model such as a data-flow model that shows sub-system relationships Distribution model that shows how sub-systems are distributed across computers

Modular decomposition Another structural level where sub-systems are decomposed into modules Two modular decomposition models coveredbull An object model where the system is decomposed into interacting objectbull A pipeline or data-flow model where the system is decomposed into functional modules which transform inputs to outputs If possible decisions about concurrency should be delayed until modules are implemented

Object models Structure the system into a set of loosely coupled objects with well-defined interfaces Object-oriented decomposition is concerned with identifying object classes their attributes and operations When implemented objects are created from these classes and some control model used to coordinate object operations

Invoice Processing system

Pipeline model advantages Supports transformation reuse Intuitive organisation for stakeholder communication Easy to add new transformations Relatively simple to implement as either a concurrent or sequential system However requires a common format for data transfer along the pipeline and difficult

to support event-based interaction

User interface design

The user interface User interfaces should be designed to match the skills experience and expectations of

its anticipated users System users often judge a system by its interface rather than its functionality A poorly designed interface can cause a user to make catastrophic errors Poor user interface design is the reason why so many software systems are never

usedUser interface Design Principle

89

Design principles User familiaritybull The interface should be based on user-oriented terms and concepts rather than computer concepts For example an office system should use concepts such as letters documents folders etc rather than directories file identifiers etc Consistencybull The system should display an appropriate level of consistency Commands and menus should have the same format command punctuation should be similar etc Minimal surprisebull If a command operates in a known way the user should be able to predict the operation of comparable commandsbull Recoverabilitybull The system should provide some resilience to user errors and allow the user to recover from errors This might include an undo facility confirmation of destructive actions soft deletes etcbull User guidancebull Some user guidance such as help systems on-line manuals etc should be suppliedbull User diversitybull Interaction facilities for different types of user should be supported For example some users have seeing difficulties and so larger text should be available

REAL-TIME SOFTWARE DESIGNReal-time systemsSystems which monitor and control their environmentInevitably associated with hardware devices

bull Sensors Collect data from the system environmentbull Actuators Change (in some way) the systems environment

Time is critical Real-time systems must respond within specified times

Definition A real-time system is a software system where the correct functioning of the

system depends on the results produced by the system and the time at which these results are produced

90

A soft real-time system is a system whose operation is degraded if results are not produced according to the specified timing requirements

A hard real-time system is a system whose operation is incorrect if results are not produced according to the timing specification

StimulusResponse Systems Given a stimulus the system must produce a response within a specified timePeriodic stimuli Stimuli which occur at predictable time intervals

bull For example a temperature sensor may be polled 10 times per secondAperiodic stimuli Stimuli which occur at unpredictable times

bull For example a system power failure may trigger an interrupt which must be processed by the system

Architectural considerations Because of the need to respond to timing demands made by different

stimuliresponses the system architecture must allow for fast switching between stimulus handlers

Timing demands of different stimuli are different so a simple sequential loop is not usually adequate

Real-time systems are therefore usually designed as cooperating processes with a real-time executive controlling these processes

A real-time system model

Real-timecontrol system

ActuatorActuator ActuatorActuator

SensorSensorSensor SensorSensorSensor

Sensoractuator processes

Dataprocessor

Actuatorcontrol

Actuator

Sensorcontrol

Sensor

Stimulus Response

System elementsSensor control processes

bull Collect information from sensors May buffer information collected in response to a sensor stimulus

Data processorbull Carries out processing of collected information and computes the system

responseActuator control processes

91

bull Generates control signals for the actuatorsReal-time programmingHard-real time systems may have to programmed in assembly language to ensure that deadlines are metLanguages such as C allow efficient programs to be written but do not have constructs to support concurrency or shared resource management

Java as a real-time languageJava supports lightweight concurrency (threads and synchronized methods) and can be used for some soft real-time systemsJava 20 is not suitable for hard RT programming but real-time versions of Java are now available that address problems such as

bull Not possible to specify thread execution timebull Different timing in different virtual machinesbull Uncontrollable garbage collectionbull Not possible to discover queue sizes for shared resourcesbull Not possible to access system hardwarebull Not possible to do space or timing analysis

SYSTEM DESIGN Design both the hardware and the software associated with system

Partition functions to either hardware or software Design decisions should be made on the basis on non-functional

system requirements Hardware delivers better performance but potentially longer

development and less scope for changeR-T systems design process

Identify the stimuli to be processed and the required responses to these stimuli For each stimulus and response identify the timing constraints Aggregate the stimulus and response processing into concurrent processes A

process may be associated with each class of stimulus and response Design algorithms to process each class of stimulus and response These must

meet the given timing requirements Design a scheduling system which will ensure that processes are started in time to

meet their deadlines Integrate using a real-time operating system

Timing constraints May require extensive simulation and experiment to ensure that these are met by the systemMay mean that certain design strategies such as object-oriented design cannot be used because of the additional overhead involvedMay mean that low-level programming language features have to be used for performance reasons

Real-time system modellingThe effect of a stimulus in a real-time system may trigger a transition from one state to anotherFinite state machines can be used for modelling real-time systems

92

However FSM models lack structure Even simple systems can have a complex modelThe UML includes notations for defining state machine models

Petrol pump state model

Cardinserted

into reader

Timeout

Resettingdo display CC

error

Initialising

do initialisedisplay

Paying

Stopped

Reading

do get CCdetails

Waiting

do display welcome

dodeliver fuel

do debitCC account

Payment ack

Ready Delivering

update displayNozzle

trigger on

Nozzle trigger off

Nozzle trigger on

Hose inholster

do validatecredit card

Validating

Invalid card

Card removedCard OK

Hose out of holster

Timeout

Real-time operating systems(RTOS)

Real-time operating systems are specialised operating systems which manage the processes in the RTS

Responsible for process management and resource (processor and memory) allocation

May be based on a standard kernel which is used unchanged or modified for a particular application

Do not normally include facilities such as file management

Operating system componentsReal-time clock

bull Provides information for process schedulingInterrupt handler

bull Manages aperiodic requests for serviceScheduler

bull Chooses the next process to be runResource manager

bull Allocates memory and processor resourcesDispatcher

bull Starts process executionNon-stop system components

Configuration manager

93

bull Responsible for the dynamic reconfiguration of the system software and hardware Hardware modules may be replaced and software upgraded without stopping the systems

Fault managerbull Responsible for detecting software and hardware faults and taking appropriate

actions (eg switching to backup disks) to ensure that the system continues in operation

Real-time OS components

Process resourcerequirements

Scheduler

Schedulinginformation

Resourcemanager

Despatcher

Real-timeclock

Processesawaiting

resources

Readylist

Interrupthandler

Availableresource

list

Processorlist

Executing process

Readyprocesses

Releasedresources

Process priority The processing of some types of stimuli must sometimes take priority Interrupt level priority Highest priority which is allocated to processes requiring a

very fast response Clock level priority Allocated to periodic processes Within these further levels of priority may be assigned

Interrupt servicing Control is transferred automatically to a pre-determined memory location This location contains an instruction to jump to

an interrupt service routine Further interrupts are disabled the interrupt

serviced and control returned to the interrupted process

Interrupt service routines must be short simple and fast

Periodic process servicing In most real-time systems there will be several classes of periodic process each with

different periods (the time between executions) execution times and deadlines (the time by which processing must be completed)

The real-time clock ticks periodically and each tick causes an interrupt which schedules the process manager for periodic processes

The process manager selects a process which is ready for execution

Process managementbull Concerned with managing the set of concurrent processes

94

bull Periodic processes are executed at pre-specified time intervalsbull The RTOS uses the real-time clock to determine when to execute a process

taking into accountbull Process period - time between executionsbull Process deadline - the time by which processing must be complete

RTE(Real Time Execution Process) process managementResource manager

Allocate memoryand processor

Scheduler

Choose processfor execution

Despatcher

Start execution on anavailable processor

Process switchingbull The scheduler chooses the next process to be executed by the processor This

depends on a scheduling strategy which may take the process priority into account

bull The resource manager allocates memory and a processor for the process to be executed

bull The dispatcher takes the process from ready list loads it onto a processor and starts execution

Scheduling strategiesNon pre-emptive scheduling

bull Once a process has been scheduled for execution it runs to completion or until it is blocked for some reason (eg waiting for IO)

Pre-emptive schedulingbull The execution of an executing processes may be stopped if a higher priority

process requires serviceScheduling algorithms

bull Round-robinbull Rate monotonicbull Shortest deadline first

Monitoring and control systemsbull Important class of real-time systems bull Continuously check sensors and take actions

depending on sensor valuesbull Monitoring systems examine sensors and

report their resultsbull Control systems take sensor values and control hardware actuators

Generic architecture

95

S1

S2

S3

P (S1)

P (S2)

P (S1)

Monitoringprocesses

Controlprocesses

P (A1)

P (A2)

P (A1)

A1

A2

A3

P (A4) A4

Testingprocess

Control panelprocesses

Burglar alarm systembull A system is required to monitor sensors on doors and windows to detect the

presence of intruders in a buildingbull When a sensor indicates a break-in the system switches on lights around the

area and calls police automaticallybull The system should include provision for operation without a mains power

supply Sensorso Movement detectors window sensors door sensorso 50 window sensors 30 door sensors and 200 movement detectorso Voltage drop sensor Actionso When an intruder is detected police are called automaticallyo Lights are switched on in rooms with active sensorso An audible alarm is switched on

The R-T system design process

bull Identify stimuli and associated responsesbull Define the timing constraints associated with each stimulus and responsebull Allocate system functions to concurrent processesbull Design algorithms for stimulus processing and response generationbull Design a scheduling system which ensures that processes will always be

scheduled to meet their deadlinesStimuli to be processed

Power failurebull Generated aperiodically by a circuit monitor When received the system must

switch to backup power within 50 msIntruder alarm

bull Stimulus generated by system sensors Response is to call the police switch on building lights and the Power failure

bull Generated aperiodically by a circuit monitor When received the system must switch to backup power within 50 ms

bull Intruder alarmbull Stimulus generated by system sensors Response is to call the police switch

on building lights and the audible alarmbull audible alarm

Burglar alarm system processes

96

Lighting controlprocess

Audible alarmprocess

Voice synthesiserprocess

Alarm systemprocess

Power switchprocess

Building monitorprocess

Communicationprocess

Door sensorprocess

Movementdetector process

Window sensorprocess

560 Hz

60 Hz400 Hz 100 Hz

Power failureinterrupt

Alarm system

Building monitor

Alarm system

Alarm system

Alarm system

Detector status Sensor status Sensor status

Room number

Alert message

Room number

Room number

Building_monitor process 1

class BuildingMonitor extends Thread

BuildingSensor win door move

Siren siren = new Siren () Lights lights = new Lights () Synthesizer synthesizer = new Synthesizer () DoorSensors doors = new DoorSensors (30) WindowSensors windows = new WindowSensors (50) MovementSensors movements = new MovementSensors (200) PowerMonitor pm = new PowerMonitor ()

BuildingMonitor() initialise all the sensors and start the processessirenstart () lightsstart () synthesizerstart () windowsstart () doorsstart () movementsstart () pmstart ()

Building monitor process 2public void run () int room = 0 while (true) poll the movement sensors at least twice per second (400 Hz)move = movementsgetVal () poll the window sensors at least twicesecond (100 Hz)win = windowsgetVal () poll the door sensors at least twice per second (60 Hz)door = doorsgetVal ()

97

if (movesensorVal == 1 | doorsensorVal == 1 | winsensorVal == 1) a sensor has indicated an intruder if (movesensorVal == 1) room = moveroom if (doorsensorVal == 1) room = doorroom if (winsensorVal == 1 ) room = winroom lightson (room) sirenon () synthesizeron (room) break Building_monitor process 3 lightsshutdown () sirenshutdown () synthesizershutdown () windowsshutdown () doorsshutdown () movementsshutdown ()

run BuildingMonitor

Control systems

bull A burglar alarm system is primarily a monitoring system It collects data from sensors but no real-time actuator control

bull Control systems are similar but in response to sensor values the system sends control signals to actuators

bull An example of a monitoring and control system is a system that monitors temperature and switches heaters on and off

A temperature control system

Thermostatprocess

Sensorprocess

Furnacecontrol process

Heater controlprocess

500 Hz

500 Hz

Thermostat process500 Hz

Sensorvalues

Switch commandRoom number

DATA ACQUISITION SYSTEMSbull Collect data from sensors for subsequent processing and analysisbull Data collection processes and processing processes may have different periods

and deadlines bull Data collection may be faster than processing eg collecting information about

an explosion bull Circular or ring buffers are a mechanism for smoothing speed differences

The generic Architecture of data acquicition

98

DisplayProcess

dataSensor data

bufferSensorprocess

Sensoridentifier and

value

Sensors (each data flow is a sensor value)

Sensoridentifier and

value

Processdata

Sensor databuffer

Sensorprocess

Sensoridentifier and

value

Sensoridentifier and

value

s1

s2

s3

s4

s5

s6

In data acquisition systemsthe sensor may be generating data quickly and the key problem is to ensure that a sensor is allocated before sensor value changeThe essenitial features of this architecture is each group of sensors has three processes associated with it and convert analogue data to digital values if necessary a buffer process and a process that consumes the data carried out further processing Two groups sensors s1-s3 and s4-s6 on the right side a further procee that diplsys the sensor data Neutron flux data acquisition

Operatordisplay

Fluxprocessing

Flux databuffer

A-Dconvertor

Sensoridentifier and

flux valueProcessedflux level

Neutron flux sensors

bull A system collects data from a set of sensors monitoring the neutron flux from a nuclear reactor

bull Each sensor has a process that converts the analog input flux level into a digita signalIt passes this flux level with sensor identifies to the sensor data buffer the data processing takes the data from this bufferprocesses it and pass it to display process for output on an operator display

A ring buffer

Consumerprocess

Producerprocess

Mutual exclusionbull Producer processes collect data and add it to the buffer Consumer processes

take data from the buffer and make elements availablebull Producer and consumer processes must be mutually excluded from accessing

the same elementThe buffer must stop producer processes adding information to a full buffer and consumer processes trying to take information from an empty buffer

99

Page 14: Unit_III

2Needed servicesThe potential class must have a set of identifiable operations that can change the value of its attributes in some way3Multiple attributesDuring requirement analysis the focus should be on ldquomajor ldquo information a class with a single attribute be useful during design but better to represent ed as an attribute of another class during the analysis activity4Common attributesA set of attributes can be defined for the potential class and these attributes apply to all instances of the class5Common operationsA set of operation can be defined for the potential class and these operations apply to all instances of the class6Essential requirements External entities that appear in the problem space and produce and consume information important to the operation of any solution for the system will almost always be defined as classes in the requirements modelSpecifying AttributesAttributes are the set of data objects that fully define the class within the context of the problemExample

SystemsystemIDverificationPhonenubersystemStatusdelaytimemasterpasswordprogram()display()reset()query()modify()

The shade portion is list of attributes for the system classDefining OperationsIt define the behavior of an object The types of operations are divided into three categories (1)operations that manipulate data egadingdeletingreformattingselecting (2)operations that perform a computation (3)operations that inquire about the state of an object (4)operations that monitor an object for the occurance of a controlling eventThese functions are accomplished by operating on attributes and associationsExample Safehome processing narrative the phrases indicate that a program() operation is encapsulated by the System classClass-Responsibility-Collaborator(CRC) ModelingClass-responsibility-collaborator modeling provides simple means for identifying and organizing the classes that are relevant to system or product requirementsAmbler describes CRC modeling in the following way A CRC model is a collection of standard index cards that represent classesThe cards are divided into three sectionsDESIGN WITHIN THE CONTEXT OF SOFTWARE ENGINEERING

Design Principle1Design should be traceable to the analysis model

82

2Always consider the architecture of the system to be built3Design of data is as important as design of processing functions4Interfaces both internal and external must be designed with care5User interface design should be tuned to the needs of the end-users6Component ndashlevel design should be functionally independent7Components should be loosely coupled to one another and to the environment8Design representation(models) should be easily understandable9The design should be developed iterativelyWith each iteration the designer should stive for greater simplicity

DESIGN PROCESS AND DESIGN QUALITYDesign process

bull Design process is a sequence of steps carried through which the requirements are translated into a system or software model bull Any design may be modeled as a direct graph The graphs are collection of entities with attributes which participate in relationships bull The system should be described at several different levels of abstraction bull Design takes place in overlapping stages bull Various phases of design process are as shown in following

1 In architectural design the subsystem components can be identified2 The abstract specification is used to specify the subsystems3 The interfaces between the subsystems are designed which is called inter face design4 In component design of subsystems components is done5 The data structure is designed to hold the data6 For perfoming the required functionality the appropriate algorithm is de

signed

Software design is an iterative process through which requirements are translated into a design for constructing the software

The design is represented at a high level of abstractiona level that can be directly traced to the specific system objective and more detailed datafunctional and behavioral requirements As design iteraton occur subsequent refinement to design representation at lower levels of abstraction

McGlaughin suggests three characteristics that serve as a guide for the evaluation of a good design Each of these characteristics is a goal of the design process

The design must implement all of the explicit requirements contained in the analysis model and it must accommodate all of the implicit(indirect) requirements desired by the customer

The design must be a readable understandable guide for those who generate code and for those who test and subsequently support the software

The design should provide a complete picture of the software addressing the data functional and behavioral domains from an implementation perspective

83

Quality guidelinesThe following gidelines to evaluate the quality of a design representation

1A design should display an architecture that (a) That has been created using recognizable architectural styles or patterns

(b)That is composed of components that show good design characteristics (c)That can be implemented in an evolutionary style thereby implementing and testing2A design should be modular that is the software should be logically partitioned into elements or subsystems3A design should contain distinct representation of dataarchitectureinterfaces and components4A design should lead to data structures that are appropriate for the classes to be implemented and are drawn from recognizable data patterns5A design should lead to components that show independent functional characteristics6A design should lead to interfaces that reduce the complexity of connections between components and with the external environmemt7A design should be derived using a repeatable method that is driven by information obtained during software requirements analysis8A design should be represented using a notation that effectively communicates its meaning

Quality attributesHewlett Packard deveopled a set of software quality attributes are given as acronym(short form) FURPS to represent a target(goal) for all software design

Functionality Usability Reliability Performance Supportability

FunctionalityIt is assessed by evaluating the feature set and capabilities of the programthe generalization of the functions that are deliveredand the security of the overall systemUsabilityIt is assessed by human factors consistency and documentationReliabilityIt is evaluated by measuring the frequency and severity of failurethe accuracy of output resultsthe mean-time-to-failure(MTTF) the ability to recover from failure and predictability(unavoidability) of the programPerformanceIt is measured by processing speedresponse timeresource consumption throughput and efficiencySupportabilityItcombin the abilitytoxtendtheprogram(extensibility)adaptabilityServiceabilitymainabilitytestabilitycompatibilityconfigurability the ability to organize and control elements of the software congfiguration

Design Principles Davis suggested a set of principles for software design as

bull The design process should not suffer from ldquotunnel visionrdquobull The design should be traceable to the analysis modelbull The design should not reinvent the wheel

84

bull The design should ldquominimize the intellectual distancerdquo between the software and the problem in the real worldbull The design should exhibit uniformity and integrationbull The design should be structured to degrade gentlybull Design is not coding and coding is not designbull The design should be assessed for qualitybull The design should be reviewed to minimize conceptual errors

Design Concept

The software design concept provides a framework for implementing the right software

Following issues are considered while designing the software1Abstraction At each stage of software design process levels of abstractions should be applied to refine the software solutionAt the higher level of abstraction the solution should be stated in broad terms and in the lower level more detailed description of the solution is given While moving through different levels of abstraction the procedural abstraction and data abstraction is created In procedural abstraction it gives the named sequence of instruction in the specific function In data abstracion the collection of data objects is represented Levels of Abstraction Various levels of abstractions are- Level I - This level represents the solution interms of problem environment Level II - This level represents the decomposition of terms that are moved from problem environment but still not at implementation stage Level III - At this level preliminary procedural representation exists All the terminologies at this level are software oriented and implementation modularity begins at the surface Level IV and V - The concepts of stepwise refinement and modularity are

applied at this level2 Modularity

The software is divided into separately named and addressable components that called as modules Creating such models bring the modularity in siftwareMeyer defines five criteria that enable us to evaluate a design method with respect to its ability to define an effective modular systemModular decomposability A design method provides a systematic mechanism for decomposing the problem into sub-problems This reduces the complexity of the problem and the modularity can be achievedModular composability A design method enables existing design components to be assembled into a new systemModular understandability A module can be understood as a standalone unit Then it will be easier to build and easier to changeModular continuity Small changes to the system requirements result in changes to individual modules rather than system- wide changesModular protection An aberrant condition occurs within a module and its effects are constrained within the module3Refinement

Refinement is actually a process of elaborationStepwise refinement is a top-down design strategy proposed by Niklaus WIRTHThe architecture of a program is developed by successively refining levels of procedural detail

85

The process of program refinement is analogues to the process of refinement and partitioning that is used during requirements analysisAbstraction and refinement are complementary concepts The major difference is that - in the abstraction low-level details are suppressedRefinement helps the designer to elaborate low-levels detailsModular Design

Modular design reduces complexity and helps in easier implementation The parallel development of different parts of the system is possible due to modular designWhat is the benefit of modular design Changes made during testing and maintenance becomes manageable and they do not affect other modules Various quality parameters for effective modular design are -1) Functional independance 2) Cohesion 3) Coupling

Functional IndependenceThe functional independence can be achieved be developing the functional modules

with single-minded approachBy using functional independence functions may be compartmentalized and interfaces are simplifiedVarious types of coupling are i) Data coupling - The data coupling is possible by parameter passing or data interactionii) Control coupling - The modules share related control data in control couplingiii) Commom coupling - Content coupling occurs when one module makes use of data or control information maintained in another moduleFan-out Fan-out is a measure of the number of immediate subordinates to a moule The fan-out should be within some limit in the design If fan-out is very high then it indicates that a single module is controlling many other modules Preferably limit fan-out to no more than sevenFan-in

Fan-in indicates how many modules directly control a given module Modules with fan-in must have good cohesion Each interfac to the module must have the same number and types of parametersFactoring

Factoring means separation of function into new modules By applying factoring the size of module is reduced and thereby the complexity of the problem is reduced This also provides duplication of functions in more than one module The effective factoring brings simplification in the implementation of software design DESIGN HEURISTICS

The program structure can be manipulated according the design heuristics as shon below1Evaluate the first iteration of the program structure to reduce the coupling and improve cohesion The module independency can be achieved in the program structure by exploding or imploding the modules Exploding the modules means obtaining two or more modules in the final stage and imploding the modules means combining the result of different modules2Attempt to minimize the structure with high fan-out and strive for fan-in as depth increase At the higher level of program structure the distribution of control should be made Fan-out means number of immediate subordinates to the module Fan-in means number of immediate ancestores the module have

86

3Keep scope of the effect of a module within the scope of control of that module The decisions made in particular module lsquoarsquo should not affect the module rsquo brsquo which lies outside the scope of module lsquoarsquo4Evaluate the module interfaces to reduce complexity and redundancy and improve consistency Mostly the cause of softwatr errors is module interfaces The module interfaces should simply pass the information and should be consistent with the module5Define module whose function is predicatable but avoid modules that are too restrictive The module should be designed with simplified internal processing so that expected data can be produced as a result The modules should not restrict the size of local data structure options with control flow or modes of external interfaces Being module too much restrictive causes large maintenance6Strive for controlled entry modules by avoiding pathological connections Software interfaces should be constrained and controlled so that it will become manageable Pathological connection means many references or branches into the middle of a module

Design ModelThe design model is represented as pyramid The pyramid is a stable object

Representing design model in this way means that the software design should be stableThe design model has braod foundation of data design stable mid-region with architectural and interface design and the sharp point to for component level design

Advantages of horizontal partition1These are easy to test maintain and extend 2They have fewer side effects in change propagation or error propagation

Disadvantages of horizontal partitionMore data has to be passed across module interfaces which complicates the overall

control of program flowVertical partitioning

Vertical partitioning suggests the control and work should be distributed top-down in program structureIn vertical partitioning

Define separate branches of the module hierarchy for each major functionUse control modules to co-ordinate communication between functions

Advantages of vertical partition1These are easy to maintain the changes2 They reduce the change impact and error propagation

DATA DESIGNData design is basically the model of data that is represented at the high level of abstractionThe data design is then progressively refined to create implementation specific representationsVarious elements of data design are

Data object - The data objects are identified and relationship among various data objects can be represented using entity relationship diagrams or data dictionariesDatabases - Using software design model the data models are translated into data structures and databases at the application level

87

Data warehouses - At the business level useful information is identified from various databases and the data warehouses are created For extracting or navigating the useful business information stored in the huge data warehouse then data mining techniques are applied

ARCHITECTURAL DESIGNSoftware architecture The design process for identifying the sub-systems making up a system and the framework for sub-system control and communication is architectural design The output of this design process is a description of the software architecture

Architectural design An early stage of the system design process Represents the link between specification and design processes Often carried out in parallel with some specification activities It involves identifying major system components and their communicationsArchitecture and system characteristics Performancebull Localise critical operations and minimise communications Use large rather than fine-grain components Securitybull Use a layered architecture with critical assets in the inner layers Safetybull Localise safety-critical features in a small number of sub-systems Availabilitybull Include redundant components and mechanisms for fault tolerance Maintainabilitybull Use fine-grain replaceable components

Architectural design decisions Is there a generic application architecture that can be used How will the system be distributed What architectural styles are appropriate What approach will be used to structure the system How will the system be decomposed into modules What control strategy should be used How will the architectural design be evaluated How should the architecture be documentedArchitectural styles The architectural model of a system may conform to a generic architectural model or style An awareness of these styles can simplify the problem of defining system architectures However most large systems are heterogeneous and do not follow a single architectural styleArchitectural models

Used to document an architectural design Static structural model that shows the major system components Dynamic process model that shows the process structure of the system Interface model that defines sub-system interfaces

88

Relationships model such as a data-flow model that shows sub-system relationships Distribution model that shows how sub-systems are distributed across computers

Modular decomposition Another structural level where sub-systems are decomposed into modules Two modular decomposition models coveredbull An object model where the system is decomposed into interacting objectbull A pipeline or data-flow model where the system is decomposed into functional modules which transform inputs to outputs If possible decisions about concurrency should be delayed until modules are implemented

Object models Structure the system into a set of loosely coupled objects with well-defined interfaces Object-oriented decomposition is concerned with identifying object classes their attributes and operations When implemented objects are created from these classes and some control model used to coordinate object operations

Invoice Processing system

Pipeline model advantages Supports transformation reuse Intuitive organisation for stakeholder communication Easy to add new transformations Relatively simple to implement as either a concurrent or sequential system However requires a common format for data transfer along the pipeline and difficult

to support event-based interaction

User interface design

The user interface User interfaces should be designed to match the skills experience and expectations of

its anticipated users System users often judge a system by its interface rather than its functionality A poorly designed interface can cause a user to make catastrophic errors Poor user interface design is the reason why so many software systems are never

usedUser interface Design Principle

89

Design principles User familiaritybull The interface should be based on user-oriented terms and concepts rather than computer concepts For example an office system should use concepts such as letters documents folders etc rather than directories file identifiers etc Consistencybull The system should display an appropriate level of consistency Commands and menus should have the same format command punctuation should be similar etc Minimal surprisebull If a command operates in a known way the user should be able to predict the operation of comparable commandsbull Recoverabilitybull The system should provide some resilience to user errors and allow the user to recover from errors This might include an undo facility confirmation of destructive actions soft deletes etcbull User guidancebull Some user guidance such as help systems on-line manuals etc should be suppliedbull User diversitybull Interaction facilities for different types of user should be supported For example some users have seeing difficulties and so larger text should be available

REAL-TIME SOFTWARE DESIGNReal-time systemsSystems which monitor and control their environmentInevitably associated with hardware devices

bull Sensors Collect data from the system environmentbull Actuators Change (in some way) the systems environment

Time is critical Real-time systems must respond within specified times

Definition A real-time system is a software system where the correct functioning of the

system depends on the results produced by the system and the time at which these results are produced

90

A soft real-time system is a system whose operation is degraded if results are not produced according to the specified timing requirements

A hard real-time system is a system whose operation is incorrect if results are not produced according to the timing specification

StimulusResponse Systems Given a stimulus the system must produce a response within a specified timePeriodic stimuli Stimuli which occur at predictable time intervals

bull For example a temperature sensor may be polled 10 times per secondAperiodic stimuli Stimuli which occur at unpredictable times

bull For example a system power failure may trigger an interrupt which must be processed by the system

Architectural considerations Because of the need to respond to timing demands made by different

stimuliresponses the system architecture must allow for fast switching between stimulus handlers

Timing demands of different stimuli are different so a simple sequential loop is not usually adequate

Real-time systems are therefore usually designed as cooperating processes with a real-time executive controlling these processes

A real-time system model

Real-timecontrol system

ActuatorActuator ActuatorActuator

SensorSensorSensor SensorSensorSensor

Sensoractuator processes

Dataprocessor

Actuatorcontrol

Actuator

Sensorcontrol

Sensor

Stimulus Response

System elementsSensor control processes

bull Collect information from sensors May buffer information collected in response to a sensor stimulus

Data processorbull Carries out processing of collected information and computes the system

responseActuator control processes

91

bull Generates control signals for the actuatorsReal-time programmingHard-real time systems may have to programmed in assembly language to ensure that deadlines are metLanguages such as C allow efficient programs to be written but do not have constructs to support concurrency or shared resource management

Java as a real-time languageJava supports lightweight concurrency (threads and synchronized methods) and can be used for some soft real-time systemsJava 20 is not suitable for hard RT programming but real-time versions of Java are now available that address problems such as

bull Not possible to specify thread execution timebull Different timing in different virtual machinesbull Uncontrollable garbage collectionbull Not possible to discover queue sizes for shared resourcesbull Not possible to access system hardwarebull Not possible to do space or timing analysis

SYSTEM DESIGN Design both the hardware and the software associated with system

Partition functions to either hardware or software Design decisions should be made on the basis on non-functional

system requirements Hardware delivers better performance but potentially longer

development and less scope for changeR-T systems design process

Identify the stimuli to be processed and the required responses to these stimuli For each stimulus and response identify the timing constraints Aggregate the stimulus and response processing into concurrent processes A

process may be associated with each class of stimulus and response Design algorithms to process each class of stimulus and response These must

meet the given timing requirements Design a scheduling system which will ensure that processes are started in time to

meet their deadlines Integrate using a real-time operating system

Timing constraints May require extensive simulation and experiment to ensure that these are met by the systemMay mean that certain design strategies such as object-oriented design cannot be used because of the additional overhead involvedMay mean that low-level programming language features have to be used for performance reasons

Real-time system modellingThe effect of a stimulus in a real-time system may trigger a transition from one state to anotherFinite state machines can be used for modelling real-time systems

92

However FSM models lack structure Even simple systems can have a complex modelThe UML includes notations for defining state machine models

Petrol pump state model

Cardinserted

into reader

Timeout

Resettingdo display CC

error

Initialising

do initialisedisplay

Paying

Stopped

Reading

do get CCdetails

Waiting

do display welcome

dodeliver fuel

do debitCC account

Payment ack

Ready Delivering

update displayNozzle

trigger on

Nozzle trigger off

Nozzle trigger on

Hose inholster

do validatecredit card

Validating

Invalid card

Card removedCard OK

Hose out of holster

Timeout

Real-time operating systems(RTOS)

Real-time operating systems are specialised operating systems which manage the processes in the RTS

Responsible for process management and resource (processor and memory) allocation

May be based on a standard kernel which is used unchanged or modified for a particular application

Do not normally include facilities such as file management

Operating system componentsReal-time clock

bull Provides information for process schedulingInterrupt handler

bull Manages aperiodic requests for serviceScheduler

bull Chooses the next process to be runResource manager

bull Allocates memory and processor resourcesDispatcher

bull Starts process executionNon-stop system components

Configuration manager

93

bull Responsible for the dynamic reconfiguration of the system software and hardware Hardware modules may be replaced and software upgraded without stopping the systems

Fault managerbull Responsible for detecting software and hardware faults and taking appropriate

actions (eg switching to backup disks) to ensure that the system continues in operation

Real-time OS components

Process resourcerequirements

Scheduler

Schedulinginformation

Resourcemanager

Despatcher

Real-timeclock

Processesawaiting

resources

Readylist

Interrupthandler

Availableresource

list

Processorlist

Executing process

Readyprocesses

Releasedresources

Process priority The processing of some types of stimuli must sometimes take priority Interrupt level priority Highest priority which is allocated to processes requiring a

very fast response Clock level priority Allocated to periodic processes Within these further levels of priority may be assigned

Interrupt servicing Control is transferred automatically to a pre-determined memory location This location contains an instruction to jump to

an interrupt service routine Further interrupts are disabled the interrupt

serviced and control returned to the interrupted process

Interrupt service routines must be short simple and fast

Periodic process servicing In most real-time systems there will be several classes of periodic process each with

different periods (the time between executions) execution times and deadlines (the time by which processing must be completed)

The real-time clock ticks periodically and each tick causes an interrupt which schedules the process manager for periodic processes

The process manager selects a process which is ready for execution

Process managementbull Concerned with managing the set of concurrent processes

94

bull Periodic processes are executed at pre-specified time intervalsbull The RTOS uses the real-time clock to determine when to execute a process

taking into accountbull Process period - time between executionsbull Process deadline - the time by which processing must be complete

RTE(Real Time Execution Process) process managementResource manager

Allocate memoryand processor

Scheduler

Choose processfor execution

Despatcher

Start execution on anavailable processor

Process switchingbull The scheduler chooses the next process to be executed by the processor This

depends on a scheduling strategy which may take the process priority into account

bull The resource manager allocates memory and a processor for the process to be executed

bull The dispatcher takes the process from ready list loads it onto a processor and starts execution

Scheduling strategiesNon pre-emptive scheduling

bull Once a process has been scheduled for execution it runs to completion or until it is blocked for some reason (eg waiting for IO)

Pre-emptive schedulingbull The execution of an executing processes may be stopped if a higher priority

process requires serviceScheduling algorithms

bull Round-robinbull Rate monotonicbull Shortest deadline first

Monitoring and control systemsbull Important class of real-time systems bull Continuously check sensors and take actions

depending on sensor valuesbull Monitoring systems examine sensors and

report their resultsbull Control systems take sensor values and control hardware actuators

Generic architecture

95

S1

S2

S3

P (S1)

P (S2)

P (S1)

Monitoringprocesses

Controlprocesses

P (A1)

P (A2)

P (A1)

A1

A2

A3

P (A4) A4

Testingprocess

Control panelprocesses

Burglar alarm systembull A system is required to monitor sensors on doors and windows to detect the

presence of intruders in a buildingbull When a sensor indicates a break-in the system switches on lights around the

area and calls police automaticallybull The system should include provision for operation without a mains power

supply Sensorso Movement detectors window sensors door sensorso 50 window sensors 30 door sensors and 200 movement detectorso Voltage drop sensor Actionso When an intruder is detected police are called automaticallyo Lights are switched on in rooms with active sensorso An audible alarm is switched on

The R-T system design process

bull Identify stimuli and associated responsesbull Define the timing constraints associated with each stimulus and responsebull Allocate system functions to concurrent processesbull Design algorithms for stimulus processing and response generationbull Design a scheduling system which ensures that processes will always be

scheduled to meet their deadlinesStimuli to be processed

Power failurebull Generated aperiodically by a circuit monitor When received the system must

switch to backup power within 50 msIntruder alarm

bull Stimulus generated by system sensors Response is to call the police switch on building lights and the Power failure

bull Generated aperiodically by a circuit monitor When received the system must switch to backup power within 50 ms

bull Intruder alarmbull Stimulus generated by system sensors Response is to call the police switch

on building lights and the audible alarmbull audible alarm

Burglar alarm system processes

96

Lighting controlprocess

Audible alarmprocess

Voice synthesiserprocess

Alarm systemprocess

Power switchprocess

Building monitorprocess

Communicationprocess

Door sensorprocess

Movementdetector process

Window sensorprocess

560 Hz

60 Hz400 Hz 100 Hz

Power failureinterrupt

Alarm system

Building monitor

Alarm system

Alarm system

Alarm system

Detector status Sensor status Sensor status

Room number

Alert message

Room number

Room number

Building_monitor process 1

class BuildingMonitor extends Thread

BuildingSensor win door move

Siren siren = new Siren () Lights lights = new Lights () Synthesizer synthesizer = new Synthesizer () DoorSensors doors = new DoorSensors (30) WindowSensors windows = new WindowSensors (50) MovementSensors movements = new MovementSensors (200) PowerMonitor pm = new PowerMonitor ()

BuildingMonitor() initialise all the sensors and start the processessirenstart () lightsstart () synthesizerstart () windowsstart () doorsstart () movementsstart () pmstart ()

Building monitor process 2public void run () int room = 0 while (true) poll the movement sensors at least twice per second (400 Hz)move = movementsgetVal () poll the window sensors at least twicesecond (100 Hz)win = windowsgetVal () poll the door sensors at least twice per second (60 Hz)door = doorsgetVal ()

97

if (movesensorVal == 1 | doorsensorVal == 1 | winsensorVal == 1) a sensor has indicated an intruder if (movesensorVal == 1) room = moveroom if (doorsensorVal == 1) room = doorroom if (winsensorVal == 1 ) room = winroom lightson (room) sirenon () synthesizeron (room) break Building_monitor process 3 lightsshutdown () sirenshutdown () synthesizershutdown () windowsshutdown () doorsshutdown () movementsshutdown ()

run BuildingMonitor

Control systems

bull A burglar alarm system is primarily a monitoring system It collects data from sensors but no real-time actuator control

bull Control systems are similar but in response to sensor values the system sends control signals to actuators

bull An example of a monitoring and control system is a system that monitors temperature and switches heaters on and off

A temperature control system

Thermostatprocess

Sensorprocess

Furnacecontrol process

Heater controlprocess

500 Hz

500 Hz

Thermostat process500 Hz

Sensorvalues

Switch commandRoom number

DATA ACQUISITION SYSTEMSbull Collect data from sensors for subsequent processing and analysisbull Data collection processes and processing processes may have different periods

and deadlines bull Data collection may be faster than processing eg collecting information about

an explosion bull Circular or ring buffers are a mechanism for smoothing speed differences

The generic Architecture of data acquicition

98

DisplayProcess

dataSensor data

bufferSensorprocess

Sensoridentifier and

value

Sensors (each data flow is a sensor value)

Sensoridentifier and

value

Processdata

Sensor databuffer

Sensorprocess

Sensoridentifier and

value

Sensoridentifier and

value

s1

s2

s3

s4

s5

s6

In data acquisition systemsthe sensor may be generating data quickly and the key problem is to ensure that a sensor is allocated before sensor value changeThe essenitial features of this architecture is each group of sensors has three processes associated with it and convert analogue data to digital values if necessary a buffer process and a process that consumes the data carried out further processing Two groups sensors s1-s3 and s4-s6 on the right side a further procee that diplsys the sensor data Neutron flux data acquisition

Operatordisplay

Fluxprocessing

Flux databuffer

A-Dconvertor

Sensoridentifier and

flux valueProcessedflux level

Neutron flux sensors

bull A system collects data from a set of sensors monitoring the neutron flux from a nuclear reactor

bull Each sensor has a process that converts the analog input flux level into a digita signalIt passes this flux level with sensor identifies to the sensor data buffer the data processing takes the data from this bufferprocesses it and pass it to display process for output on an operator display

A ring buffer

Consumerprocess

Producerprocess

Mutual exclusionbull Producer processes collect data and add it to the buffer Consumer processes

take data from the buffer and make elements availablebull Producer and consumer processes must be mutually excluded from accessing

the same elementThe buffer must stop producer processes adding information to a full buffer and consumer processes trying to take information from an empty buffer

99

Page 15: Unit_III

2Always consider the architecture of the system to be built3Design of data is as important as design of processing functions4Interfaces both internal and external must be designed with care5User interface design should be tuned to the needs of the end-users6Component ndashlevel design should be functionally independent7Components should be loosely coupled to one another and to the environment8Design representation(models) should be easily understandable9The design should be developed iterativelyWith each iteration the designer should stive for greater simplicity

DESIGN PROCESS AND DESIGN QUALITYDesign process

bull Design process is a sequence of steps carried through which the requirements are translated into a system or software model bull Any design may be modeled as a direct graph The graphs are collection of entities with attributes which participate in relationships bull The system should be described at several different levels of abstraction bull Design takes place in overlapping stages bull Various phases of design process are as shown in following

1 In architectural design the subsystem components can be identified2 The abstract specification is used to specify the subsystems3 The interfaces between the subsystems are designed which is called inter face design4 In component design of subsystems components is done5 The data structure is designed to hold the data6 For perfoming the required functionality the appropriate algorithm is de

signed

Software design is an iterative process through which requirements are translated into a design for constructing the software

The design is represented at a high level of abstractiona level that can be directly traced to the specific system objective and more detailed datafunctional and behavioral requirements As design iteraton occur subsequent refinement to design representation at lower levels of abstraction

McGlaughin suggests three characteristics that serve as a guide for the evaluation of a good design Each of these characteristics is a goal of the design process

The design must implement all of the explicit requirements contained in the analysis model and it must accommodate all of the implicit(indirect) requirements desired by the customer

The design must be a readable understandable guide for those who generate code and for those who test and subsequently support the software

The design should provide a complete picture of the software addressing the data functional and behavioral domains from an implementation perspective

83

Quality guidelinesThe following gidelines to evaluate the quality of a design representation

1A design should display an architecture that (a) That has been created using recognizable architectural styles or patterns

(b)That is composed of components that show good design characteristics (c)That can be implemented in an evolutionary style thereby implementing and testing2A design should be modular that is the software should be logically partitioned into elements or subsystems3A design should contain distinct representation of dataarchitectureinterfaces and components4A design should lead to data structures that are appropriate for the classes to be implemented and are drawn from recognizable data patterns5A design should lead to components that show independent functional characteristics6A design should lead to interfaces that reduce the complexity of connections between components and with the external environmemt7A design should be derived using a repeatable method that is driven by information obtained during software requirements analysis8A design should be represented using a notation that effectively communicates its meaning

Quality attributesHewlett Packard deveopled a set of software quality attributes are given as acronym(short form) FURPS to represent a target(goal) for all software design

Functionality Usability Reliability Performance Supportability

FunctionalityIt is assessed by evaluating the feature set and capabilities of the programthe generalization of the functions that are deliveredand the security of the overall systemUsabilityIt is assessed by human factors consistency and documentationReliabilityIt is evaluated by measuring the frequency and severity of failurethe accuracy of output resultsthe mean-time-to-failure(MTTF) the ability to recover from failure and predictability(unavoidability) of the programPerformanceIt is measured by processing speedresponse timeresource consumption throughput and efficiencySupportabilityItcombin the abilitytoxtendtheprogram(extensibility)adaptabilityServiceabilitymainabilitytestabilitycompatibilityconfigurability the ability to organize and control elements of the software congfiguration

Design Principles Davis suggested a set of principles for software design as

bull The design process should not suffer from ldquotunnel visionrdquobull The design should be traceable to the analysis modelbull The design should not reinvent the wheel

84

bull The design should ldquominimize the intellectual distancerdquo between the software and the problem in the real worldbull The design should exhibit uniformity and integrationbull The design should be structured to degrade gentlybull Design is not coding and coding is not designbull The design should be assessed for qualitybull The design should be reviewed to minimize conceptual errors

Design Concept

The software design concept provides a framework for implementing the right software

Following issues are considered while designing the software1Abstraction At each stage of software design process levels of abstractions should be applied to refine the software solutionAt the higher level of abstraction the solution should be stated in broad terms and in the lower level more detailed description of the solution is given While moving through different levels of abstraction the procedural abstraction and data abstraction is created In procedural abstraction it gives the named sequence of instruction in the specific function In data abstracion the collection of data objects is represented Levels of Abstraction Various levels of abstractions are- Level I - This level represents the solution interms of problem environment Level II - This level represents the decomposition of terms that are moved from problem environment but still not at implementation stage Level III - At this level preliminary procedural representation exists All the terminologies at this level are software oriented and implementation modularity begins at the surface Level IV and V - The concepts of stepwise refinement and modularity are

applied at this level2 Modularity

The software is divided into separately named and addressable components that called as modules Creating such models bring the modularity in siftwareMeyer defines five criteria that enable us to evaluate a design method with respect to its ability to define an effective modular systemModular decomposability A design method provides a systematic mechanism for decomposing the problem into sub-problems This reduces the complexity of the problem and the modularity can be achievedModular composability A design method enables existing design components to be assembled into a new systemModular understandability A module can be understood as a standalone unit Then it will be easier to build and easier to changeModular continuity Small changes to the system requirements result in changes to individual modules rather than system- wide changesModular protection An aberrant condition occurs within a module and its effects are constrained within the module3Refinement

Refinement is actually a process of elaborationStepwise refinement is a top-down design strategy proposed by Niklaus WIRTHThe architecture of a program is developed by successively refining levels of procedural detail

85

The process of program refinement is analogues to the process of refinement and partitioning that is used during requirements analysisAbstraction and refinement are complementary concepts The major difference is that - in the abstraction low-level details are suppressedRefinement helps the designer to elaborate low-levels detailsModular Design

Modular design reduces complexity and helps in easier implementation The parallel development of different parts of the system is possible due to modular designWhat is the benefit of modular design Changes made during testing and maintenance becomes manageable and they do not affect other modules Various quality parameters for effective modular design are -1) Functional independance 2) Cohesion 3) Coupling

Functional IndependenceThe functional independence can be achieved be developing the functional modules

with single-minded approachBy using functional independence functions may be compartmentalized and interfaces are simplifiedVarious types of coupling are i) Data coupling - The data coupling is possible by parameter passing or data interactionii) Control coupling - The modules share related control data in control couplingiii) Commom coupling - Content coupling occurs when one module makes use of data or control information maintained in another moduleFan-out Fan-out is a measure of the number of immediate subordinates to a moule The fan-out should be within some limit in the design If fan-out is very high then it indicates that a single module is controlling many other modules Preferably limit fan-out to no more than sevenFan-in

Fan-in indicates how many modules directly control a given module Modules with fan-in must have good cohesion Each interfac to the module must have the same number and types of parametersFactoring

Factoring means separation of function into new modules By applying factoring the size of module is reduced and thereby the complexity of the problem is reduced This also provides duplication of functions in more than one module The effective factoring brings simplification in the implementation of software design DESIGN HEURISTICS

The program structure can be manipulated according the design heuristics as shon below1Evaluate the first iteration of the program structure to reduce the coupling and improve cohesion The module independency can be achieved in the program structure by exploding or imploding the modules Exploding the modules means obtaining two or more modules in the final stage and imploding the modules means combining the result of different modules2Attempt to minimize the structure with high fan-out and strive for fan-in as depth increase At the higher level of program structure the distribution of control should be made Fan-out means number of immediate subordinates to the module Fan-in means number of immediate ancestores the module have

86

3Keep scope of the effect of a module within the scope of control of that module The decisions made in particular module lsquoarsquo should not affect the module rsquo brsquo which lies outside the scope of module lsquoarsquo4Evaluate the module interfaces to reduce complexity and redundancy and improve consistency Mostly the cause of softwatr errors is module interfaces The module interfaces should simply pass the information and should be consistent with the module5Define module whose function is predicatable but avoid modules that are too restrictive The module should be designed with simplified internal processing so that expected data can be produced as a result The modules should not restrict the size of local data structure options with control flow or modes of external interfaces Being module too much restrictive causes large maintenance6Strive for controlled entry modules by avoiding pathological connections Software interfaces should be constrained and controlled so that it will become manageable Pathological connection means many references or branches into the middle of a module

Design ModelThe design model is represented as pyramid The pyramid is a stable object

Representing design model in this way means that the software design should be stableThe design model has braod foundation of data design stable mid-region with architectural and interface design and the sharp point to for component level design

Advantages of horizontal partition1These are easy to test maintain and extend 2They have fewer side effects in change propagation or error propagation

Disadvantages of horizontal partitionMore data has to be passed across module interfaces which complicates the overall

control of program flowVertical partitioning

Vertical partitioning suggests the control and work should be distributed top-down in program structureIn vertical partitioning

Define separate branches of the module hierarchy for each major functionUse control modules to co-ordinate communication between functions

Advantages of vertical partition1These are easy to maintain the changes2 They reduce the change impact and error propagation

DATA DESIGNData design is basically the model of data that is represented at the high level of abstractionThe data design is then progressively refined to create implementation specific representationsVarious elements of data design are

Data object - The data objects are identified and relationship among various data objects can be represented using entity relationship diagrams or data dictionariesDatabases - Using software design model the data models are translated into data structures and databases at the application level

87

Data warehouses - At the business level useful information is identified from various databases and the data warehouses are created For extracting or navigating the useful business information stored in the huge data warehouse then data mining techniques are applied

ARCHITECTURAL DESIGNSoftware architecture The design process for identifying the sub-systems making up a system and the framework for sub-system control and communication is architectural design The output of this design process is a description of the software architecture

Architectural design An early stage of the system design process Represents the link between specification and design processes Often carried out in parallel with some specification activities It involves identifying major system components and their communicationsArchitecture and system characteristics Performancebull Localise critical operations and minimise communications Use large rather than fine-grain components Securitybull Use a layered architecture with critical assets in the inner layers Safetybull Localise safety-critical features in a small number of sub-systems Availabilitybull Include redundant components and mechanisms for fault tolerance Maintainabilitybull Use fine-grain replaceable components

Architectural design decisions Is there a generic application architecture that can be used How will the system be distributed What architectural styles are appropriate What approach will be used to structure the system How will the system be decomposed into modules What control strategy should be used How will the architectural design be evaluated How should the architecture be documentedArchitectural styles The architectural model of a system may conform to a generic architectural model or style An awareness of these styles can simplify the problem of defining system architectures However most large systems are heterogeneous and do not follow a single architectural styleArchitectural models

Used to document an architectural design Static structural model that shows the major system components Dynamic process model that shows the process structure of the system Interface model that defines sub-system interfaces

88

Relationships model such as a data-flow model that shows sub-system relationships Distribution model that shows how sub-systems are distributed across computers

Modular decomposition Another structural level where sub-systems are decomposed into modules Two modular decomposition models coveredbull An object model where the system is decomposed into interacting objectbull A pipeline or data-flow model where the system is decomposed into functional modules which transform inputs to outputs If possible decisions about concurrency should be delayed until modules are implemented

Object models Structure the system into a set of loosely coupled objects with well-defined interfaces Object-oriented decomposition is concerned with identifying object classes their attributes and operations When implemented objects are created from these classes and some control model used to coordinate object operations

Invoice Processing system

Pipeline model advantages Supports transformation reuse Intuitive organisation for stakeholder communication Easy to add new transformations Relatively simple to implement as either a concurrent or sequential system However requires a common format for data transfer along the pipeline and difficult

to support event-based interaction

User interface design

The user interface User interfaces should be designed to match the skills experience and expectations of

its anticipated users System users often judge a system by its interface rather than its functionality A poorly designed interface can cause a user to make catastrophic errors Poor user interface design is the reason why so many software systems are never

usedUser interface Design Principle

89

Design principles User familiaritybull The interface should be based on user-oriented terms and concepts rather than computer concepts For example an office system should use concepts such as letters documents folders etc rather than directories file identifiers etc Consistencybull The system should display an appropriate level of consistency Commands and menus should have the same format command punctuation should be similar etc Minimal surprisebull If a command operates in a known way the user should be able to predict the operation of comparable commandsbull Recoverabilitybull The system should provide some resilience to user errors and allow the user to recover from errors This might include an undo facility confirmation of destructive actions soft deletes etcbull User guidancebull Some user guidance such as help systems on-line manuals etc should be suppliedbull User diversitybull Interaction facilities for different types of user should be supported For example some users have seeing difficulties and so larger text should be available

REAL-TIME SOFTWARE DESIGNReal-time systemsSystems which monitor and control their environmentInevitably associated with hardware devices

bull Sensors Collect data from the system environmentbull Actuators Change (in some way) the systems environment

Time is critical Real-time systems must respond within specified times

Definition A real-time system is a software system where the correct functioning of the

system depends on the results produced by the system and the time at which these results are produced

90

A soft real-time system is a system whose operation is degraded if results are not produced according to the specified timing requirements

A hard real-time system is a system whose operation is incorrect if results are not produced according to the timing specification

StimulusResponse Systems Given a stimulus the system must produce a response within a specified timePeriodic stimuli Stimuli which occur at predictable time intervals

bull For example a temperature sensor may be polled 10 times per secondAperiodic stimuli Stimuli which occur at unpredictable times

bull For example a system power failure may trigger an interrupt which must be processed by the system

Architectural considerations Because of the need to respond to timing demands made by different

stimuliresponses the system architecture must allow for fast switching between stimulus handlers

Timing demands of different stimuli are different so a simple sequential loop is not usually adequate

Real-time systems are therefore usually designed as cooperating processes with a real-time executive controlling these processes

A real-time system model

Real-timecontrol system

ActuatorActuator ActuatorActuator

SensorSensorSensor SensorSensorSensor

Sensoractuator processes

Dataprocessor

Actuatorcontrol

Actuator

Sensorcontrol

Sensor

Stimulus Response

System elementsSensor control processes

bull Collect information from sensors May buffer information collected in response to a sensor stimulus

Data processorbull Carries out processing of collected information and computes the system

responseActuator control processes

91

bull Generates control signals for the actuatorsReal-time programmingHard-real time systems may have to programmed in assembly language to ensure that deadlines are metLanguages such as C allow efficient programs to be written but do not have constructs to support concurrency or shared resource management

Java as a real-time languageJava supports lightweight concurrency (threads and synchronized methods) and can be used for some soft real-time systemsJava 20 is not suitable for hard RT programming but real-time versions of Java are now available that address problems such as

bull Not possible to specify thread execution timebull Different timing in different virtual machinesbull Uncontrollable garbage collectionbull Not possible to discover queue sizes for shared resourcesbull Not possible to access system hardwarebull Not possible to do space or timing analysis

SYSTEM DESIGN Design both the hardware and the software associated with system

Partition functions to either hardware or software Design decisions should be made on the basis on non-functional

system requirements Hardware delivers better performance but potentially longer

development and less scope for changeR-T systems design process

Identify the stimuli to be processed and the required responses to these stimuli For each stimulus and response identify the timing constraints Aggregate the stimulus and response processing into concurrent processes A

process may be associated with each class of stimulus and response Design algorithms to process each class of stimulus and response These must

meet the given timing requirements Design a scheduling system which will ensure that processes are started in time to

meet their deadlines Integrate using a real-time operating system

Timing constraints May require extensive simulation and experiment to ensure that these are met by the systemMay mean that certain design strategies such as object-oriented design cannot be used because of the additional overhead involvedMay mean that low-level programming language features have to be used for performance reasons

Real-time system modellingThe effect of a stimulus in a real-time system may trigger a transition from one state to anotherFinite state machines can be used for modelling real-time systems

92

However FSM models lack structure Even simple systems can have a complex modelThe UML includes notations for defining state machine models

Petrol pump state model

Cardinserted

into reader

Timeout

Resettingdo display CC

error

Initialising

do initialisedisplay

Paying

Stopped

Reading

do get CCdetails

Waiting

do display welcome

dodeliver fuel

do debitCC account

Payment ack

Ready Delivering

update displayNozzle

trigger on

Nozzle trigger off

Nozzle trigger on

Hose inholster

do validatecredit card

Validating

Invalid card

Card removedCard OK

Hose out of holster

Timeout

Real-time operating systems(RTOS)

Real-time operating systems are specialised operating systems which manage the processes in the RTS

Responsible for process management and resource (processor and memory) allocation

May be based on a standard kernel which is used unchanged or modified for a particular application

Do not normally include facilities such as file management

Operating system componentsReal-time clock

bull Provides information for process schedulingInterrupt handler

bull Manages aperiodic requests for serviceScheduler

bull Chooses the next process to be runResource manager

bull Allocates memory and processor resourcesDispatcher

bull Starts process executionNon-stop system components

Configuration manager

93

bull Responsible for the dynamic reconfiguration of the system software and hardware Hardware modules may be replaced and software upgraded without stopping the systems

Fault managerbull Responsible for detecting software and hardware faults and taking appropriate

actions (eg switching to backup disks) to ensure that the system continues in operation

Real-time OS components

Process resourcerequirements

Scheduler

Schedulinginformation

Resourcemanager

Despatcher

Real-timeclock

Processesawaiting

resources

Readylist

Interrupthandler

Availableresource

list

Processorlist

Executing process

Readyprocesses

Releasedresources

Process priority The processing of some types of stimuli must sometimes take priority Interrupt level priority Highest priority which is allocated to processes requiring a

very fast response Clock level priority Allocated to periodic processes Within these further levels of priority may be assigned

Interrupt servicing Control is transferred automatically to a pre-determined memory location This location contains an instruction to jump to

an interrupt service routine Further interrupts are disabled the interrupt

serviced and control returned to the interrupted process

Interrupt service routines must be short simple and fast

Periodic process servicing In most real-time systems there will be several classes of periodic process each with

different periods (the time between executions) execution times and deadlines (the time by which processing must be completed)

The real-time clock ticks periodically and each tick causes an interrupt which schedules the process manager for periodic processes

The process manager selects a process which is ready for execution

Process managementbull Concerned with managing the set of concurrent processes

94

bull Periodic processes are executed at pre-specified time intervalsbull The RTOS uses the real-time clock to determine when to execute a process

taking into accountbull Process period - time between executionsbull Process deadline - the time by which processing must be complete

RTE(Real Time Execution Process) process managementResource manager

Allocate memoryand processor

Scheduler

Choose processfor execution

Despatcher

Start execution on anavailable processor

Process switchingbull The scheduler chooses the next process to be executed by the processor This

depends on a scheduling strategy which may take the process priority into account

bull The resource manager allocates memory and a processor for the process to be executed

bull The dispatcher takes the process from ready list loads it onto a processor and starts execution

Scheduling strategiesNon pre-emptive scheduling

bull Once a process has been scheduled for execution it runs to completion or until it is blocked for some reason (eg waiting for IO)

Pre-emptive schedulingbull The execution of an executing processes may be stopped if a higher priority

process requires serviceScheduling algorithms

bull Round-robinbull Rate monotonicbull Shortest deadline first

Monitoring and control systemsbull Important class of real-time systems bull Continuously check sensors and take actions

depending on sensor valuesbull Monitoring systems examine sensors and

report their resultsbull Control systems take sensor values and control hardware actuators

Generic architecture

95

S1

S2

S3

P (S1)

P (S2)

P (S1)

Monitoringprocesses

Controlprocesses

P (A1)

P (A2)

P (A1)

A1

A2

A3

P (A4) A4

Testingprocess

Control panelprocesses

Burglar alarm systembull A system is required to monitor sensors on doors and windows to detect the

presence of intruders in a buildingbull When a sensor indicates a break-in the system switches on lights around the

area and calls police automaticallybull The system should include provision for operation without a mains power

supply Sensorso Movement detectors window sensors door sensorso 50 window sensors 30 door sensors and 200 movement detectorso Voltage drop sensor Actionso When an intruder is detected police are called automaticallyo Lights are switched on in rooms with active sensorso An audible alarm is switched on

The R-T system design process

bull Identify stimuli and associated responsesbull Define the timing constraints associated with each stimulus and responsebull Allocate system functions to concurrent processesbull Design algorithms for stimulus processing and response generationbull Design a scheduling system which ensures that processes will always be

scheduled to meet their deadlinesStimuli to be processed

Power failurebull Generated aperiodically by a circuit monitor When received the system must

switch to backup power within 50 msIntruder alarm

bull Stimulus generated by system sensors Response is to call the police switch on building lights and the Power failure

bull Generated aperiodically by a circuit monitor When received the system must switch to backup power within 50 ms

bull Intruder alarmbull Stimulus generated by system sensors Response is to call the police switch

on building lights and the audible alarmbull audible alarm

Burglar alarm system processes

96

Lighting controlprocess

Audible alarmprocess

Voice synthesiserprocess

Alarm systemprocess

Power switchprocess

Building monitorprocess

Communicationprocess

Door sensorprocess

Movementdetector process

Window sensorprocess

560 Hz

60 Hz400 Hz 100 Hz

Power failureinterrupt

Alarm system

Building monitor

Alarm system

Alarm system

Alarm system

Detector status Sensor status Sensor status

Room number

Alert message

Room number

Room number

Building_monitor process 1

class BuildingMonitor extends Thread

BuildingSensor win door move

Siren siren = new Siren () Lights lights = new Lights () Synthesizer synthesizer = new Synthesizer () DoorSensors doors = new DoorSensors (30) WindowSensors windows = new WindowSensors (50) MovementSensors movements = new MovementSensors (200) PowerMonitor pm = new PowerMonitor ()

BuildingMonitor() initialise all the sensors and start the processessirenstart () lightsstart () synthesizerstart () windowsstart () doorsstart () movementsstart () pmstart ()

Building monitor process 2public void run () int room = 0 while (true) poll the movement sensors at least twice per second (400 Hz)move = movementsgetVal () poll the window sensors at least twicesecond (100 Hz)win = windowsgetVal () poll the door sensors at least twice per second (60 Hz)door = doorsgetVal ()

97

if (movesensorVal == 1 | doorsensorVal == 1 | winsensorVal == 1) a sensor has indicated an intruder if (movesensorVal == 1) room = moveroom if (doorsensorVal == 1) room = doorroom if (winsensorVal == 1 ) room = winroom lightson (room) sirenon () synthesizeron (room) break Building_monitor process 3 lightsshutdown () sirenshutdown () synthesizershutdown () windowsshutdown () doorsshutdown () movementsshutdown ()

run BuildingMonitor

Control systems

bull A burglar alarm system is primarily a monitoring system It collects data from sensors but no real-time actuator control

bull Control systems are similar but in response to sensor values the system sends control signals to actuators

bull An example of a monitoring and control system is a system that monitors temperature and switches heaters on and off

A temperature control system

Thermostatprocess

Sensorprocess

Furnacecontrol process

Heater controlprocess

500 Hz

500 Hz

Thermostat process500 Hz

Sensorvalues

Switch commandRoom number

DATA ACQUISITION SYSTEMSbull Collect data from sensors for subsequent processing and analysisbull Data collection processes and processing processes may have different periods

and deadlines bull Data collection may be faster than processing eg collecting information about

an explosion bull Circular or ring buffers are a mechanism for smoothing speed differences

The generic Architecture of data acquicition

98

DisplayProcess

dataSensor data

bufferSensorprocess

Sensoridentifier and

value

Sensors (each data flow is a sensor value)

Sensoridentifier and

value

Processdata

Sensor databuffer

Sensorprocess

Sensoridentifier and

value

Sensoridentifier and

value

s1

s2

s3

s4

s5

s6

In data acquisition systemsthe sensor may be generating data quickly and the key problem is to ensure that a sensor is allocated before sensor value changeThe essenitial features of this architecture is each group of sensors has three processes associated with it and convert analogue data to digital values if necessary a buffer process and a process that consumes the data carried out further processing Two groups sensors s1-s3 and s4-s6 on the right side a further procee that diplsys the sensor data Neutron flux data acquisition

Operatordisplay

Fluxprocessing

Flux databuffer

A-Dconvertor

Sensoridentifier and

flux valueProcessedflux level

Neutron flux sensors

bull A system collects data from a set of sensors monitoring the neutron flux from a nuclear reactor

bull Each sensor has a process that converts the analog input flux level into a digita signalIt passes this flux level with sensor identifies to the sensor data buffer the data processing takes the data from this bufferprocesses it and pass it to display process for output on an operator display

A ring buffer

Consumerprocess

Producerprocess

Mutual exclusionbull Producer processes collect data and add it to the buffer Consumer processes

take data from the buffer and make elements availablebull Producer and consumer processes must be mutually excluded from accessing

the same elementThe buffer must stop producer processes adding information to a full buffer and consumer processes trying to take information from an empty buffer

99

Page 16: Unit_III

Quality guidelinesThe following gidelines to evaluate the quality of a design representation

1A design should display an architecture that (a) That has been created using recognizable architectural styles or patterns

(b)That is composed of components that show good design characteristics (c)That can be implemented in an evolutionary style thereby implementing and testing2A design should be modular that is the software should be logically partitioned into elements or subsystems3A design should contain distinct representation of dataarchitectureinterfaces and components4A design should lead to data structures that are appropriate for the classes to be implemented and are drawn from recognizable data patterns5A design should lead to components that show independent functional characteristics6A design should lead to interfaces that reduce the complexity of connections between components and with the external environmemt7A design should be derived using a repeatable method that is driven by information obtained during software requirements analysis8A design should be represented using a notation that effectively communicates its meaning

Quality attributesHewlett Packard deveopled a set of software quality attributes are given as acronym(short form) FURPS to represent a target(goal) for all software design

Functionality Usability Reliability Performance Supportability

FunctionalityIt is assessed by evaluating the feature set and capabilities of the programthe generalization of the functions that are deliveredand the security of the overall systemUsabilityIt is assessed by human factors consistency and documentationReliabilityIt is evaluated by measuring the frequency and severity of failurethe accuracy of output resultsthe mean-time-to-failure(MTTF) the ability to recover from failure and predictability(unavoidability) of the programPerformanceIt is measured by processing speedresponse timeresource consumption throughput and efficiencySupportabilityItcombin the abilitytoxtendtheprogram(extensibility)adaptabilityServiceabilitymainabilitytestabilitycompatibilityconfigurability the ability to organize and control elements of the software congfiguration

Design Principles Davis suggested a set of principles for software design as

bull The design process should not suffer from ldquotunnel visionrdquobull The design should be traceable to the analysis modelbull The design should not reinvent the wheel

84

bull The design should ldquominimize the intellectual distancerdquo between the software and the problem in the real worldbull The design should exhibit uniformity and integrationbull The design should be structured to degrade gentlybull Design is not coding and coding is not designbull The design should be assessed for qualitybull The design should be reviewed to minimize conceptual errors

Design Concept

The software design concept provides a framework for implementing the right software

Following issues are considered while designing the software1Abstraction At each stage of software design process levels of abstractions should be applied to refine the software solutionAt the higher level of abstraction the solution should be stated in broad terms and in the lower level more detailed description of the solution is given While moving through different levels of abstraction the procedural abstraction and data abstraction is created In procedural abstraction it gives the named sequence of instruction in the specific function In data abstracion the collection of data objects is represented Levels of Abstraction Various levels of abstractions are- Level I - This level represents the solution interms of problem environment Level II - This level represents the decomposition of terms that are moved from problem environment but still not at implementation stage Level III - At this level preliminary procedural representation exists All the terminologies at this level are software oriented and implementation modularity begins at the surface Level IV and V - The concepts of stepwise refinement and modularity are

applied at this level2 Modularity

The software is divided into separately named and addressable components that called as modules Creating such models bring the modularity in siftwareMeyer defines five criteria that enable us to evaluate a design method with respect to its ability to define an effective modular systemModular decomposability A design method provides a systematic mechanism for decomposing the problem into sub-problems This reduces the complexity of the problem and the modularity can be achievedModular composability A design method enables existing design components to be assembled into a new systemModular understandability A module can be understood as a standalone unit Then it will be easier to build and easier to changeModular continuity Small changes to the system requirements result in changes to individual modules rather than system- wide changesModular protection An aberrant condition occurs within a module and its effects are constrained within the module3Refinement

Refinement is actually a process of elaborationStepwise refinement is a top-down design strategy proposed by Niklaus WIRTHThe architecture of a program is developed by successively refining levels of procedural detail

85

The process of program refinement is analogues to the process of refinement and partitioning that is used during requirements analysisAbstraction and refinement are complementary concepts The major difference is that - in the abstraction low-level details are suppressedRefinement helps the designer to elaborate low-levels detailsModular Design

Modular design reduces complexity and helps in easier implementation The parallel development of different parts of the system is possible due to modular designWhat is the benefit of modular design Changes made during testing and maintenance becomes manageable and they do not affect other modules Various quality parameters for effective modular design are -1) Functional independance 2) Cohesion 3) Coupling

Functional IndependenceThe functional independence can be achieved be developing the functional modules

with single-minded approachBy using functional independence functions may be compartmentalized and interfaces are simplifiedVarious types of coupling are i) Data coupling - The data coupling is possible by parameter passing or data interactionii) Control coupling - The modules share related control data in control couplingiii) Commom coupling - Content coupling occurs when one module makes use of data or control information maintained in another moduleFan-out Fan-out is a measure of the number of immediate subordinates to a moule The fan-out should be within some limit in the design If fan-out is very high then it indicates that a single module is controlling many other modules Preferably limit fan-out to no more than sevenFan-in

Fan-in indicates how many modules directly control a given module Modules with fan-in must have good cohesion Each interfac to the module must have the same number and types of parametersFactoring

Factoring means separation of function into new modules By applying factoring the size of module is reduced and thereby the complexity of the problem is reduced This also provides duplication of functions in more than one module The effective factoring brings simplification in the implementation of software design DESIGN HEURISTICS

The program structure can be manipulated according the design heuristics as shon below1Evaluate the first iteration of the program structure to reduce the coupling and improve cohesion The module independency can be achieved in the program structure by exploding or imploding the modules Exploding the modules means obtaining two or more modules in the final stage and imploding the modules means combining the result of different modules2Attempt to minimize the structure with high fan-out and strive for fan-in as depth increase At the higher level of program structure the distribution of control should be made Fan-out means number of immediate subordinates to the module Fan-in means number of immediate ancestores the module have

86

3Keep scope of the effect of a module within the scope of control of that module The decisions made in particular module lsquoarsquo should not affect the module rsquo brsquo which lies outside the scope of module lsquoarsquo4Evaluate the module interfaces to reduce complexity and redundancy and improve consistency Mostly the cause of softwatr errors is module interfaces The module interfaces should simply pass the information and should be consistent with the module5Define module whose function is predicatable but avoid modules that are too restrictive The module should be designed with simplified internal processing so that expected data can be produced as a result The modules should not restrict the size of local data structure options with control flow or modes of external interfaces Being module too much restrictive causes large maintenance6Strive for controlled entry modules by avoiding pathological connections Software interfaces should be constrained and controlled so that it will become manageable Pathological connection means many references or branches into the middle of a module

Design ModelThe design model is represented as pyramid The pyramid is a stable object

Representing design model in this way means that the software design should be stableThe design model has braod foundation of data design stable mid-region with architectural and interface design and the sharp point to for component level design

Advantages of horizontal partition1These are easy to test maintain and extend 2They have fewer side effects in change propagation or error propagation

Disadvantages of horizontal partitionMore data has to be passed across module interfaces which complicates the overall

control of program flowVertical partitioning

Vertical partitioning suggests the control and work should be distributed top-down in program structureIn vertical partitioning

Define separate branches of the module hierarchy for each major functionUse control modules to co-ordinate communication between functions

Advantages of vertical partition1These are easy to maintain the changes2 They reduce the change impact and error propagation

DATA DESIGNData design is basically the model of data that is represented at the high level of abstractionThe data design is then progressively refined to create implementation specific representationsVarious elements of data design are

Data object - The data objects are identified and relationship among various data objects can be represented using entity relationship diagrams or data dictionariesDatabases - Using software design model the data models are translated into data structures and databases at the application level

87

Data warehouses - At the business level useful information is identified from various databases and the data warehouses are created For extracting or navigating the useful business information stored in the huge data warehouse then data mining techniques are applied

ARCHITECTURAL DESIGNSoftware architecture The design process for identifying the sub-systems making up a system and the framework for sub-system control and communication is architectural design The output of this design process is a description of the software architecture

Architectural design An early stage of the system design process Represents the link between specification and design processes Often carried out in parallel with some specification activities It involves identifying major system components and their communicationsArchitecture and system characteristics Performancebull Localise critical operations and minimise communications Use large rather than fine-grain components Securitybull Use a layered architecture with critical assets in the inner layers Safetybull Localise safety-critical features in a small number of sub-systems Availabilitybull Include redundant components and mechanisms for fault tolerance Maintainabilitybull Use fine-grain replaceable components

Architectural design decisions Is there a generic application architecture that can be used How will the system be distributed What architectural styles are appropriate What approach will be used to structure the system How will the system be decomposed into modules What control strategy should be used How will the architectural design be evaluated How should the architecture be documentedArchitectural styles The architectural model of a system may conform to a generic architectural model or style An awareness of these styles can simplify the problem of defining system architectures However most large systems are heterogeneous and do not follow a single architectural styleArchitectural models

Used to document an architectural design Static structural model that shows the major system components Dynamic process model that shows the process structure of the system Interface model that defines sub-system interfaces

88

Relationships model such as a data-flow model that shows sub-system relationships Distribution model that shows how sub-systems are distributed across computers

Modular decomposition Another structural level where sub-systems are decomposed into modules Two modular decomposition models coveredbull An object model where the system is decomposed into interacting objectbull A pipeline or data-flow model where the system is decomposed into functional modules which transform inputs to outputs If possible decisions about concurrency should be delayed until modules are implemented

Object models Structure the system into a set of loosely coupled objects with well-defined interfaces Object-oriented decomposition is concerned with identifying object classes their attributes and operations When implemented objects are created from these classes and some control model used to coordinate object operations

Invoice Processing system

Pipeline model advantages Supports transformation reuse Intuitive organisation for stakeholder communication Easy to add new transformations Relatively simple to implement as either a concurrent or sequential system However requires a common format for data transfer along the pipeline and difficult

to support event-based interaction

User interface design

The user interface User interfaces should be designed to match the skills experience and expectations of

its anticipated users System users often judge a system by its interface rather than its functionality A poorly designed interface can cause a user to make catastrophic errors Poor user interface design is the reason why so many software systems are never

usedUser interface Design Principle

89

Design principles User familiaritybull The interface should be based on user-oriented terms and concepts rather than computer concepts For example an office system should use concepts such as letters documents folders etc rather than directories file identifiers etc Consistencybull The system should display an appropriate level of consistency Commands and menus should have the same format command punctuation should be similar etc Minimal surprisebull If a command operates in a known way the user should be able to predict the operation of comparable commandsbull Recoverabilitybull The system should provide some resilience to user errors and allow the user to recover from errors This might include an undo facility confirmation of destructive actions soft deletes etcbull User guidancebull Some user guidance such as help systems on-line manuals etc should be suppliedbull User diversitybull Interaction facilities for different types of user should be supported For example some users have seeing difficulties and so larger text should be available

REAL-TIME SOFTWARE DESIGNReal-time systemsSystems which monitor and control their environmentInevitably associated with hardware devices

bull Sensors Collect data from the system environmentbull Actuators Change (in some way) the systems environment

Time is critical Real-time systems must respond within specified times

Definition A real-time system is a software system where the correct functioning of the

system depends on the results produced by the system and the time at which these results are produced

90

A soft real-time system is a system whose operation is degraded if results are not produced according to the specified timing requirements

A hard real-time system is a system whose operation is incorrect if results are not produced according to the timing specification

StimulusResponse Systems Given a stimulus the system must produce a response within a specified timePeriodic stimuli Stimuli which occur at predictable time intervals

bull For example a temperature sensor may be polled 10 times per secondAperiodic stimuli Stimuli which occur at unpredictable times

bull For example a system power failure may trigger an interrupt which must be processed by the system

Architectural considerations Because of the need to respond to timing demands made by different

stimuliresponses the system architecture must allow for fast switching between stimulus handlers

Timing demands of different stimuli are different so a simple sequential loop is not usually adequate

Real-time systems are therefore usually designed as cooperating processes with a real-time executive controlling these processes

A real-time system model

Real-timecontrol system

ActuatorActuator ActuatorActuator

SensorSensorSensor SensorSensorSensor

Sensoractuator processes

Dataprocessor

Actuatorcontrol

Actuator

Sensorcontrol

Sensor

Stimulus Response

System elementsSensor control processes

bull Collect information from sensors May buffer information collected in response to a sensor stimulus

Data processorbull Carries out processing of collected information and computes the system

responseActuator control processes

91

bull Generates control signals for the actuatorsReal-time programmingHard-real time systems may have to programmed in assembly language to ensure that deadlines are metLanguages such as C allow efficient programs to be written but do not have constructs to support concurrency or shared resource management

Java as a real-time languageJava supports lightweight concurrency (threads and synchronized methods) and can be used for some soft real-time systemsJava 20 is not suitable for hard RT programming but real-time versions of Java are now available that address problems such as

bull Not possible to specify thread execution timebull Different timing in different virtual machinesbull Uncontrollable garbage collectionbull Not possible to discover queue sizes for shared resourcesbull Not possible to access system hardwarebull Not possible to do space or timing analysis

SYSTEM DESIGN Design both the hardware and the software associated with system

Partition functions to either hardware or software Design decisions should be made on the basis on non-functional

system requirements Hardware delivers better performance but potentially longer

development and less scope for changeR-T systems design process

Identify the stimuli to be processed and the required responses to these stimuli For each stimulus and response identify the timing constraints Aggregate the stimulus and response processing into concurrent processes A

process may be associated with each class of stimulus and response Design algorithms to process each class of stimulus and response These must

meet the given timing requirements Design a scheduling system which will ensure that processes are started in time to

meet their deadlines Integrate using a real-time operating system

Timing constraints May require extensive simulation and experiment to ensure that these are met by the systemMay mean that certain design strategies such as object-oriented design cannot be used because of the additional overhead involvedMay mean that low-level programming language features have to be used for performance reasons

Real-time system modellingThe effect of a stimulus in a real-time system may trigger a transition from one state to anotherFinite state machines can be used for modelling real-time systems

92

However FSM models lack structure Even simple systems can have a complex modelThe UML includes notations for defining state machine models

Petrol pump state model

Cardinserted

into reader

Timeout

Resettingdo display CC

error

Initialising

do initialisedisplay

Paying

Stopped

Reading

do get CCdetails

Waiting

do display welcome

dodeliver fuel

do debitCC account

Payment ack

Ready Delivering

update displayNozzle

trigger on

Nozzle trigger off

Nozzle trigger on

Hose inholster

do validatecredit card

Validating

Invalid card

Card removedCard OK

Hose out of holster

Timeout

Real-time operating systems(RTOS)

Real-time operating systems are specialised operating systems which manage the processes in the RTS

Responsible for process management and resource (processor and memory) allocation

May be based on a standard kernel which is used unchanged or modified for a particular application

Do not normally include facilities such as file management

Operating system componentsReal-time clock

bull Provides information for process schedulingInterrupt handler

bull Manages aperiodic requests for serviceScheduler

bull Chooses the next process to be runResource manager

bull Allocates memory and processor resourcesDispatcher

bull Starts process executionNon-stop system components

Configuration manager

93

bull Responsible for the dynamic reconfiguration of the system software and hardware Hardware modules may be replaced and software upgraded without stopping the systems

Fault managerbull Responsible for detecting software and hardware faults and taking appropriate

actions (eg switching to backup disks) to ensure that the system continues in operation

Real-time OS components

Process resourcerequirements

Scheduler

Schedulinginformation

Resourcemanager

Despatcher

Real-timeclock

Processesawaiting

resources

Readylist

Interrupthandler

Availableresource

list

Processorlist

Executing process

Readyprocesses

Releasedresources

Process priority The processing of some types of stimuli must sometimes take priority Interrupt level priority Highest priority which is allocated to processes requiring a

very fast response Clock level priority Allocated to periodic processes Within these further levels of priority may be assigned

Interrupt servicing Control is transferred automatically to a pre-determined memory location This location contains an instruction to jump to

an interrupt service routine Further interrupts are disabled the interrupt

serviced and control returned to the interrupted process

Interrupt service routines must be short simple and fast

Periodic process servicing In most real-time systems there will be several classes of periodic process each with

different periods (the time between executions) execution times and deadlines (the time by which processing must be completed)

The real-time clock ticks periodically and each tick causes an interrupt which schedules the process manager for periodic processes

The process manager selects a process which is ready for execution

Process managementbull Concerned with managing the set of concurrent processes

94

bull Periodic processes are executed at pre-specified time intervalsbull The RTOS uses the real-time clock to determine when to execute a process

taking into accountbull Process period - time between executionsbull Process deadline - the time by which processing must be complete

RTE(Real Time Execution Process) process managementResource manager

Allocate memoryand processor

Scheduler

Choose processfor execution

Despatcher

Start execution on anavailable processor

Process switchingbull The scheduler chooses the next process to be executed by the processor This

depends on a scheduling strategy which may take the process priority into account

bull The resource manager allocates memory and a processor for the process to be executed

bull The dispatcher takes the process from ready list loads it onto a processor and starts execution

Scheduling strategiesNon pre-emptive scheduling

bull Once a process has been scheduled for execution it runs to completion or until it is blocked for some reason (eg waiting for IO)

Pre-emptive schedulingbull The execution of an executing processes may be stopped if a higher priority

process requires serviceScheduling algorithms

bull Round-robinbull Rate monotonicbull Shortest deadline first

Monitoring and control systemsbull Important class of real-time systems bull Continuously check sensors and take actions

depending on sensor valuesbull Monitoring systems examine sensors and

report their resultsbull Control systems take sensor values and control hardware actuators

Generic architecture

95

S1

S2

S3

P (S1)

P (S2)

P (S1)

Monitoringprocesses

Controlprocesses

P (A1)

P (A2)

P (A1)

A1

A2

A3

P (A4) A4

Testingprocess

Control panelprocesses

Burglar alarm systembull A system is required to monitor sensors on doors and windows to detect the

presence of intruders in a buildingbull When a sensor indicates a break-in the system switches on lights around the

area and calls police automaticallybull The system should include provision for operation without a mains power

supply Sensorso Movement detectors window sensors door sensorso 50 window sensors 30 door sensors and 200 movement detectorso Voltage drop sensor Actionso When an intruder is detected police are called automaticallyo Lights are switched on in rooms with active sensorso An audible alarm is switched on

The R-T system design process

bull Identify stimuli and associated responsesbull Define the timing constraints associated with each stimulus and responsebull Allocate system functions to concurrent processesbull Design algorithms for stimulus processing and response generationbull Design a scheduling system which ensures that processes will always be

scheduled to meet their deadlinesStimuli to be processed

Power failurebull Generated aperiodically by a circuit monitor When received the system must

switch to backup power within 50 msIntruder alarm

bull Stimulus generated by system sensors Response is to call the police switch on building lights and the Power failure

bull Generated aperiodically by a circuit monitor When received the system must switch to backup power within 50 ms

bull Intruder alarmbull Stimulus generated by system sensors Response is to call the police switch

on building lights and the audible alarmbull audible alarm

Burglar alarm system processes

96

Lighting controlprocess

Audible alarmprocess

Voice synthesiserprocess

Alarm systemprocess

Power switchprocess

Building monitorprocess

Communicationprocess

Door sensorprocess

Movementdetector process

Window sensorprocess

560 Hz

60 Hz400 Hz 100 Hz

Power failureinterrupt

Alarm system

Building monitor

Alarm system

Alarm system

Alarm system

Detector status Sensor status Sensor status

Room number

Alert message

Room number

Room number

Building_monitor process 1

class BuildingMonitor extends Thread

BuildingSensor win door move

Siren siren = new Siren () Lights lights = new Lights () Synthesizer synthesizer = new Synthesizer () DoorSensors doors = new DoorSensors (30) WindowSensors windows = new WindowSensors (50) MovementSensors movements = new MovementSensors (200) PowerMonitor pm = new PowerMonitor ()

BuildingMonitor() initialise all the sensors and start the processessirenstart () lightsstart () synthesizerstart () windowsstart () doorsstart () movementsstart () pmstart ()

Building monitor process 2public void run () int room = 0 while (true) poll the movement sensors at least twice per second (400 Hz)move = movementsgetVal () poll the window sensors at least twicesecond (100 Hz)win = windowsgetVal () poll the door sensors at least twice per second (60 Hz)door = doorsgetVal ()

97

if (movesensorVal == 1 | doorsensorVal == 1 | winsensorVal == 1) a sensor has indicated an intruder if (movesensorVal == 1) room = moveroom if (doorsensorVal == 1) room = doorroom if (winsensorVal == 1 ) room = winroom lightson (room) sirenon () synthesizeron (room) break Building_monitor process 3 lightsshutdown () sirenshutdown () synthesizershutdown () windowsshutdown () doorsshutdown () movementsshutdown ()

run BuildingMonitor

Control systems

bull A burglar alarm system is primarily a monitoring system It collects data from sensors but no real-time actuator control

bull Control systems are similar but in response to sensor values the system sends control signals to actuators

bull An example of a monitoring and control system is a system that monitors temperature and switches heaters on and off

A temperature control system

Thermostatprocess

Sensorprocess

Furnacecontrol process

Heater controlprocess

500 Hz

500 Hz

Thermostat process500 Hz

Sensorvalues

Switch commandRoom number

DATA ACQUISITION SYSTEMSbull Collect data from sensors for subsequent processing and analysisbull Data collection processes and processing processes may have different periods

and deadlines bull Data collection may be faster than processing eg collecting information about

an explosion bull Circular or ring buffers are a mechanism for smoothing speed differences

The generic Architecture of data acquicition

98

DisplayProcess

dataSensor data

bufferSensorprocess

Sensoridentifier and

value

Sensors (each data flow is a sensor value)

Sensoridentifier and

value

Processdata

Sensor databuffer

Sensorprocess

Sensoridentifier and

value

Sensoridentifier and

value

s1

s2

s3

s4

s5

s6

In data acquisition systemsthe sensor may be generating data quickly and the key problem is to ensure that a sensor is allocated before sensor value changeThe essenitial features of this architecture is each group of sensors has three processes associated with it and convert analogue data to digital values if necessary a buffer process and a process that consumes the data carried out further processing Two groups sensors s1-s3 and s4-s6 on the right side a further procee that diplsys the sensor data Neutron flux data acquisition

Operatordisplay

Fluxprocessing

Flux databuffer

A-Dconvertor

Sensoridentifier and

flux valueProcessedflux level

Neutron flux sensors

bull A system collects data from a set of sensors monitoring the neutron flux from a nuclear reactor

bull Each sensor has a process that converts the analog input flux level into a digita signalIt passes this flux level with sensor identifies to the sensor data buffer the data processing takes the data from this bufferprocesses it and pass it to display process for output on an operator display

A ring buffer

Consumerprocess

Producerprocess

Mutual exclusionbull Producer processes collect data and add it to the buffer Consumer processes

take data from the buffer and make elements availablebull Producer and consumer processes must be mutually excluded from accessing

the same elementThe buffer must stop producer processes adding information to a full buffer and consumer processes trying to take information from an empty buffer

99

Page 17: Unit_III

bull The design should ldquominimize the intellectual distancerdquo between the software and the problem in the real worldbull The design should exhibit uniformity and integrationbull The design should be structured to degrade gentlybull Design is not coding and coding is not designbull The design should be assessed for qualitybull The design should be reviewed to minimize conceptual errors

Design Concept

The software design concept provides a framework for implementing the right software

Following issues are considered while designing the software1Abstraction At each stage of software design process levels of abstractions should be applied to refine the software solutionAt the higher level of abstraction the solution should be stated in broad terms and in the lower level more detailed description of the solution is given While moving through different levels of abstraction the procedural abstraction and data abstraction is created In procedural abstraction it gives the named sequence of instruction in the specific function In data abstracion the collection of data objects is represented Levels of Abstraction Various levels of abstractions are- Level I - This level represents the solution interms of problem environment Level II - This level represents the decomposition of terms that are moved from problem environment but still not at implementation stage Level III - At this level preliminary procedural representation exists All the terminologies at this level are software oriented and implementation modularity begins at the surface Level IV and V - The concepts of stepwise refinement and modularity are

applied at this level2 Modularity

The software is divided into separately named and addressable components that called as modules Creating such models bring the modularity in siftwareMeyer defines five criteria that enable us to evaluate a design method with respect to its ability to define an effective modular systemModular decomposability A design method provides a systematic mechanism for decomposing the problem into sub-problems This reduces the complexity of the problem and the modularity can be achievedModular composability A design method enables existing design components to be assembled into a new systemModular understandability A module can be understood as a standalone unit Then it will be easier to build and easier to changeModular continuity Small changes to the system requirements result in changes to individual modules rather than system- wide changesModular protection An aberrant condition occurs within a module and its effects are constrained within the module3Refinement

Refinement is actually a process of elaborationStepwise refinement is a top-down design strategy proposed by Niklaus WIRTHThe architecture of a program is developed by successively refining levels of procedural detail

85

The process of program refinement is analogues to the process of refinement and partitioning that is used during requirements analysisAbstraction and refinement are complementary concepts The major difference is that - in the abstraction low-level details are suppressedRefinement helps the designer to elaborate low-levels detailsModular Design

Modular design reduces complexity and helps in easier implementation The parallel development of different parts of the system is possible due to modular designWhat is the benefit of modular design Changes made during testing and maintenance becomes manageable and they do not affect other modules Various quality parameters for effective modular design are -1) Functional independance 2) Cohesion 3) Coupling

Functional IndependenceThe functional independence can be achieved be developing the functional modules

with single-minded approachBy using functional independence functions may be compartmentalized and interfaces are simplifiedVarious types of coupling are i) Data coupling - The data coupling is possible by parameter passing or data interactionii) Control coupling - The modules share related control data in control couplingiii) Commom coupling - Content coupling occurs when one module makes use of data or control information maintained in another moduleFan-out Fan-out is a measure of the number of immediate subordinates to a moule The fan-out should be within some limit in the design If fan-out is very high then it indicates that a single module is controlling many other modules Preferably limit fan-out to no more than sevenFan-in

Fan-in indicates how many modules directly control a given module Modules with fan-in must have good cohesion Each interfac to the module must have the same number and types of parametersFactoring

Factoring means separation of function into new modules By applying factoring the size of module is reduced and thereby the complexity of the problem is reduced This also provides duplication of functions in more than one module The effective factoring brings simplification in the implementation of software design DESIGN HEURISTICS

The program structure can be manipulated according the design heuristics as shon below1Evaluate the first iteration of the program structure to reduce the coupling and improve cohesion The module independency can be achieved in the program structure by exploding or imploding the modules Exploding the modules means obtaining two or more modules in the final stage and imploding the modules means combining the result of different modules2Attempt to minimize the structure with high fan-out and strive for fan-in as depth increase At the higher level of program structure the distribution of control should be made Fan-out means number of immediate subordinates to the module Fan-in means number of immediate ancestores the module have

86

3Keep scope of the effect of a module within the scope of control of that module The decisions made in particular module lsquoarsquo should not affect the module rsquo brsquo which lies outside the scope of module lsquoarsquo4Evaluate the module interfaces to reduce complexity and redundancy and improve consistency Mostly the cause of softwatr errors is module interfaces The module interfaces should simply pass the information and should be consistent with the module5Define module whose function is predicatable but avoid modules that are too restrictive The module should be designed with simplified internal processing so that expected data can be produced as a result The modules should not restrict the size of local data structure options with control flow or modes of external interfaces Being module too much restrictive causes large maintenance6Strive for controlled entry modules by avoiding pathological connections Software interfaces should be constrained and controlled so that it will become manageable Pathological connection means many references or branches into the middle of a module

Design ModelThe design model is represented as pyramid The pyramid is a stable object

Representing design model in this way means that the software design should be stableThe design model has braod foundation of data design stable mid-region with architectural and interface design and the sharp point to for component level design

Advantages of horizontal partition1These are easy to test maintain and extend 2They have fewer side effects in change propagation or error propagation

Disadvantages of horizontal partitionMore data has to be passed across module interfaces which complicates the overall

control of program flowVertical partitioning

Vertical partitioning suggests the control and work should be distributed top-down in program structureIn vertical partitioning

Define separate branches of the module hierarchy for each major functionUse control modules to co-ordinate communication between functions

Advantages of vertical partition1These are easy to maintain the changes2 They reduce the change impact and error propagation

DATA DESIGNData design is basically the model of data that is represented at the high level of abstractionThe data design is then progressively refined to create implementation specific representationsVarious elements of data design are

Data object - The data objects are identified and relationship among various data objects can be represented using entity relationship diagrams or data dictionariesDatabases - Using software design model the data models are translated into data structures and databases at the application level

87

Data warehouses - At the business level useful information is identified from various databases and the data warehouses are created For extracting or navigating the useful business information stored in the huge data warehouse then data mining techniques are applied

ARCHITECTURAL DESIGNSoftware architecture The design process for identifying the sub-systems making up a system and the framework for sub-system control and communication is architectural design The output of this design process is a description of the software architecture

Architectural design An early stage of the system design process Represents the link between specification and design processes Often carried out in parallel with some specification activities It involves identifying major system components and their communicationsArchitecture and system characteristics Performancebull Localise critical operations and minimise communications Use large rather than fine-grain components Securitybull Use a layered architecture with critical assets in the inner layers Safetybull Localise safety-critical features in a small number of sub-systems Availabilitybull Include redundant components and mechanisms for fault tolerance Maintainabilitybull Use fine-grain replaceable components

Architectural design decisions Is there a generic application architecture that can be used How will the system be distributed What architectural styles are appropriate What approach will be used to structure the system How will the system be decomposed into modules What control strategy should be used How will the architectural design be evaluated How should the architecture be documentedArchitectural styles The architectural model of a system may conform to a generic architectural model or style An awareness of these styles can simplify the problem of defining system architectures However most large systems are heterogeneous and do not follow a single architectural styleArchitectural models

Used to document an architectural design Static structural model that shows the major system components Dynamic process model that shows the process structure of the system Interface model that defines sub-system interfaces

88

Relationships model such as a data-flow model that shows sub-system relationships Distribution model that shows how sub-systems are distributed across computers

Modular decomposition Another structural level where sub-systems are decomposed into modules Two modular decomposition models coveredbull An object model where the system is decomposed into interacting objectbull A pipeline or data-flow model where the system is decomposed into functional modules which transform inputs to outputs If possible decisions about concurrency should be delayed until modules are implemented

Object models Structure the system into a set of loosely coupled objects with well-defined interfaces Object-oriented decomposition is concerned with identifying object classes their attributes and operations When implemented objects are created from these classes and some control model used to coordinate object operations

Invoice Processing system

Pipeline model advantages Supports transformation reuse Intuitive organisation for stakeholder communication Easy to add new transformations Relatively simple to implement as either a concurrent or sequential system However requires a common format for data transfer along the pipeline and difficult

to support event-based interaction

User interface design

The user interface User interfaces should be designed to match the skills experience and expectations of

its anticipated users System users often judge a system by its interface rather than its functionality A poorly designed interface can cause a user to make catastrophic errors Poor user interface design is the reason why so many software systems are never

usedUser interface Design Principle

89

Design principles User familiaritybull The interface should be based on user-oriented terms and concepts rather than computer concepts For example an office system should use concepts such as letters documents folders etc rather than directories file identifiers etc Consistencybull The system should display an appropriate level of consistency Commands and menus should have the same format command punctuation should be similar etc Minimal surprisebull If a command operates in a known way the user should be able to predict the operation of comparable commandsbull Recoverabilitybull The system should provide some resilience to user errors and allow the user to recover from errors This might include an undo facility confirmation of destructive actions soft deletes etcbull User guidancebull Some user guidance such as help systems on-line manuals etc should be suppliedbull User diversitybull Interaction facilities for different types of user should be supported For example some users have seeing difficulties and so larger text should be available

REAL-TIME SOFTWARE DESIGNReal-time systemsSystems which monitor and control their environmentInevitably associated with hardware devices

bull Sensors Collect data from the system environmentbull Actuators Change (in some way) the systems environment

Time is critical Real-time systems must respond within specified times

Definition A real-time system is a software system where the correct functioning of the

system depends on the results produced by the system and the time at which these results are produced

90

A soft real-time system is a system whose operation is degraded if results are not produced according to the specified timing requirements

A hard real-time system is a system whose operation is incorrect if results are not produced according to the timing specification

StimulusResponse Systems Given a stimulus the system must produce a response within a specified timePeriodic stimuli Stimuli which occur at predictable time intervals

bull For example a temperature sensor may be polled 10 times per secondAperiodic stimuli Stimuli which occur at unpredictable times

bull For example a system power failure may trigger an interrupt which must be processed by the system

Architectural considerations Because of the need to respond to timing demands made by different

stimuliresponses the system architecture must allow for fast switching between stimulus handlers

Timing demands of different stimuli are different so a simple sequential loop is not usually adequate

Real-time systems are therefore usually designed as cooperating processes with a real-time executive controlling these processes

A real-time system model

Real-timecontrol system

ActuatorActuator ActuatorActuator

SensorSensorSensor SensorSensorSensor

Sensoractuator processes

Dataprocessor

Actuatorcontrol

Actuator

Sensorcontrol

Sensor

Stimulus Response

System elementsSensor control processes

bull Collect information from sensors May buffer information collected in response to a sensor stimulus

Data processorbull Carries out processing of collected information and computes the system

responseActuator control processes

91

bull Generates control signals for the actuatorsReal-time programmingHard-real time systems may have to programmed in assembly language to ensure that deadlines are metLanguages such as C allow efficient programs to be written but do not have constructs to support concurrency or shared resource management

Java as a real-time languageJava supports lightweight concurrency (threads and synchronized methods) and can be used for some soft real-time systemsJava 20 is not suitable for hard RT programming but real-time versions of Java are now available that address problems such as

bull Not possible to specify thread execution timebull Different timing in different virtual machinesbull Uncontrollable garbage collectionbull Not possible to discover queue sizes for shared resourcesbull Not possible to access system hardwarebull Not possible to do space or timing analysis

SYSTEM DESIGN Design both the hardware and the software associated with system

Partition functions to either hardware or software Design decisions should be made on the basis on non-functional

system requirements Hardware delivers better performance but potentially longer

development and less scope for changeR-T systems design process

Identify the stimuli to be processed and the required responses to these stimuli For each stimulus and response identify the timing constraints Aggregate the stimulus and response processing into concurrent processes A

process may be associated with each class of stimulus and response Design algorithms to process each class of stimulus and response These must

meet the given timing requirements Design a scheduling system which will ensure that processes are started in time to

meet their deadlines Integrate using a real-time operating system

Timing constraints May require extensive simulation and experiment to ensure that these are met by the systemMay mean that certain design strategies such as object-oriented design cannot be used because of the additional overhead involvedMay mean that low-level programming language features have to be used for performance reasons

Real-time system modellingThe effect of a stimulus in a real-time system may trigger a transition from one state to anotherFinite state machines can be used for modelling real-time systems

92

However FSM models lack structure Even simple systems can have a complex modelThe UML includes notations for defining state machine models

Petrol pump state model

Cardinserted

into reader

Timeout

Resettingdo display CC

error

Initialising

do initialisedisplay

Paying

Stopped

Reading

do get CCdetails

Waiting

do display welcome

dodeliver fuel

do debitCC account

Payment ack

Ready Delivering

update displayNozzle

trigger on

Nozzle trigger off

Nozzle trigger on

Hose inholster

do validatecredit card

Validating

Invalid card

Card removedCard OK

Hose out of holster

Timeout

Real-time operating systems(RTOS)

Real-time operating systems are specialised operating systems which manage the processes in the RTS

Responsible for process management and resource (processor and memory) allocation

May be based on a standard kernel which is used unchanged or modified for a particular application

Do not normally include facilities such as file management

Operating system componentsReal-time clock

bull Provides information for process schedulingInterrupt handler

bull Manages aperiodic requests for serviceScheduler

bull Chooses the next process to be runResource manager

bull Allocates memory and processor resourcesDispatcher

bull Starts process executionNon-stop system components

Configuration manager

93

bull Responsible for the dynamic reconfiguration of the system software and hardware Hardware modules may be replaced and software upgraded without stopping the systems

Fault managerbull Responsible for detecting software and hardware faults and taking appropriate

actions (eg switching to backup disks) to ensure that the system continues in operation

Real-time OS components

Process resourcerequirements

Scheduler

Schedulinginformation

Resourcemanager

Despatcher

Real-timeclock

Processesawaiting

resources

Readylist

Interrupthandler

Availableresource

list

Processorlist

Executing process

Readyprocesses

Releasedresources

Process priority The processing of some types of stimuli must sometimes take priority Interrupt level priority Highest priority which is allocated to processes requiring a

very fast response Clock level priority Allocated to periodic processes Within these further levels of priority may be assigned

Interrupt servicing Control is transferred automatically to a pre-determined memory location This location contains an instruction to jump to

an interrupt service routine Further interrupts are disabled the interrupt

serviced and control returned to the interrupted process

Interrupt service routines must be short simple and fast

Periodic process servicing In most real-time systems there will be several classes of periodic process each with

different periods (the time between executions) execution times and deadlines (the time by which processing must be completed)

The real-time clock ticks periodically and each tick causes an interrupt which schedules the process manager for periodic processes

The process manager selects a process which is ready for execution

Process managementbull Concerned with managing the set of concurrent processes

94

bull Periodic processes are executed at pre-specified time intervalsbull The RTOS uses the real-time clock to determine when to execute a process

taking into accountbull Process period - time between executionsbull Process deadline - the time by which processing must be complete

RTE(Real Time Execution Process) process managementResource manager

Allocate memoryand processor

Scheduler

Choose processfor execution

Despatcher

Start execution on anavailable processor

Process switchingbull The scheduler chooses the next process to be executed by the processor This

depends on a scheduling strategy which may take the process priority into account

bull The resource manager allocates memory and a processor for the process to be executed

bull The dispatcher takes the process from ready list loads it onto a processor and starts execution

Scheduling strategiesNon pre-emptive scheduling

bull Once a process has been scheduled for execution it runs to completion or until it is blocked for some reason (eg waiting for IO)

Pre-emptive schedulingbull The execution of an executing processes may be stopped if a higher priority

process requires serviceScheduling algorithms

bull Round-robinbull Rate monotonicbull Shortest deadline first

Monitoring and control systemsbull Important class of real-time systems bull Continuously check sensors and take actions

depending on sensor valuesbull Monitoring systems examine sensors and

report their resultsbull Control systems take sensor values and control hardware actuators

Generic architecture

95

S1

S2

S3

P (S1)

P (S2)

P (S1)

Monitoringprocesses

Controlprocesses

P (A1)

P (A2)

P (A1)

A1

A2

A3

P (A4) A4

Testingprocess

Control panelprocesses

Burglar alarm systembull A system is required to monitor sensors on doors and windows to detect the

presence of intruders in a buildingbull When a sensor indicates a break-in the system switches on lights around the

area and calls police automaticallybull The system should include provision for operation without a mains power

supply Sensorso Movement detectors window sensors door sensorso 50 window sensors 30 door sensors and 200 movement detectorso Voltage drop sensor Actionso When an intruder is detected police are called automaticallyo Lights are switched on in rooms with active sensorso An audible alarm is switched on

The R-T system design process

bull Identify stimuli and associated responsesbull Define the timing constraints associated with each stimulus and responsebull Allocate system functions to concurrent processesbull Design algorithms for stimulus processing and response generationbull Design a scheduling system which ensures that processes will always be

scheduled to meet their deadlinesStimuli to be processed

Power failurebull Generated aperiodically by a circuit monitor When received the system must

switch to backup power within 50 msIntruder alarm

bull Stimulus generated by system sensors Response is to call the police switch on building lights and the Power failure

bull Generated aperiodically by a circuit monitor When received the system must switch to backup power within 50 ms

bull Intruder alarmbull Stimulus generated by system sensors Response is to call the police switch

on building lights and the audible alarmbull audible alarm

Burglar alarm system processes

96

Lighting controlprocess

Audible alarmprocess

Voice synthesiserprocess

Alarm systemprocess

Power switchprocess

Building monitorprocess

Communicationprocess

Door sensorprocess

Movementdetector process

Window sensorprocess

560 Hz

60 Hz400 Hz 100 Hz

Power failureinterrupt

Alarm system

Building monitor

Alarm system

Alarm system

Alarm system

Detector status Sensor status Sensor status

Room number

Alert message

Room number

Room number

Building_monitor process 1

class BuildingMonitor extends Thread

BuildingSensor win door move

Siren siren = new Siren () Lights lights = new Lights () Synthesizer synthesizer = new Synthesizer () DoorSensors doors = new DoorSensors (30) WindowSensors windows = new WindowSensors (50) MovementSensors movements = new MovementSensors (200) PowerMonitor pm = new PowerMonitor ()

BuildingMonitor() initialise all the sensors and start the processessirenstart () lightsstart () synthesizerstart () windowsstart () doorsstart () movementsstart () pmstart ()

Building monitor process 2public void run () int room = 0 while (true) poll the movement sensors at least twice per second (400 Hz)move = movementsgetVal () poll the window sensors at least twicesecond (100 Hz)win = windowsgetVal () poll the door sensors at least twice per second (60 Hz)door = doorsgetVal ()

97

if (movesensorVal == 1 | doorsensorVal == 1 | winsensorVal == 1) a sensor has indicated an intruder if (movesensorVal == 1) room = moveroom if (doorsensorVal == 1) room = doorroom if (winsensorVal == 1 ) room = winroom lightson (room) sirenon () synthesizeron (room) break Building_monitor process 3 lightsshutdown () sirenshutdown () synthesizershutdown () windowsshutdown () doorsshutdown () movementsshutdown ()

run BuildingMonitor

Control systems

bull A burglar alarm system is primarily a monitoring system It collects data from sensors but no real-time actuator control

bull Control systems are similar but in response to sensor values the system sends control signals to actuators

bull An example of a monitoring and control system is a system that monitors temperature and switches heaters on and off

A temperature control system

Thermostatprocess

Sensorprocess

Furnacecontrol process

Heater controlprocess

500 Hz

500 Hz

Thermostat process500 Hz

Sensorvalues

Switch commandRoom number

DATA ACQUISITION SYSTEMSbull Collect data from sensors for subsequent processing and analysisbull Data collection processes and processing processes may have different periods

and deadlines bull Data collection may be faster than processing eg collecting information about

an explosion bull Circular or ring buffers are a mechanism for smoothing speed differences

The generic Architecture of data acquicition

98

DisplayProcess

dataSensor data

bufferSensorprocess

Sensoridentifier and

value

Sensors (each data flow is a sensor value)

Sensoridentifier and

value

Processdata

Sensor databuffer

Sensorprocess

Sensoridentifier and

value

Sensoridentifier and

value

s1

s2

s3

s4

s5

s6

In data acquisition systemsthe sensor may be generating data quickly and the key problem is to ensure that a sensor is allocated before sensor value changeThe essenitial features of this architecture is each group of sensors has three processes associated with it and convert analogue data to digital values if necessary a buffer process and a process that consumes the data carried out further processing Two groups sensors s1-s3 and s4-s6 on the right side a further procee that diplsys the sensor data Neutron flux data acquisition

Operatordisplay

Fluxprocessing

Flux databuffer

A-Dconvertor

Sensoridentifier and

flux valueProcessedflux level

Neutron flux sensors

bull A system collects data from a set of sensors monitoring the neutron flux from a nuclear reactor

bull Each sensor has a process that converts the analog input flux level into a digita signalIt passes this flux level with sensor identifies to the sensor data buffer the data processing takes the data from this bufferprocesses it and pass it to display process for output on an operator display

A ring buffer

Consumerprocess

Producerprocess

Mutual exclusionbull Producer processes collect data and add it to the buffer Consumer processes

take data from the buffer and make elements availablebull Producer and consumer processes must be mutually excluded from accessing

the same elementThe buffer must stop producer processes adding information to a full buffer and consumer processes trying to take information from an empty buffer

99

Page 18: Unit_III

The process of program refinement is analogues to the process of refinement and partitioning that is used during requirements analysisAbstraction and refinement are complementary concepts The major difference is that - in the abstraction low-level details are suppressedRefinement helps the designer to elaborate low-levels detailsModular Design

Modular design reduces complexity and helps in easier implementation The parallel development of different parts of the system is possible due to modular designWhat is the benefit of modular design Changes made during testing and maintenance becomes manageable and they do not affect other modules Various quality parameters for effective modular design are -1) Functional independance 2) Cohesion 3) Coupling

Functional IndependenceThe functional independence can be achieved be developing the functional modules

with single-minded approachBy using functional independence functions may be compartmentalized and interfaces are simplifiedVarious types of coupling are i) Data coupling - The data coupling is possible by parameter passing or data interactionii) Control coupling - The modules share related control data in control couplingiii) Commom coupling - Content coupling occurs when one module makes use of data or control information maintained in another moduleFan-out Fan-out is a measure of the number of immediate subordinates to a moule The fan-out should be within some limit in the design If fan-out is very high then it indicates that a single module is controlling many other modules Preferably limit fan-out to no more than sevenFan-in

Fan-in indicates how many modules directly control a given module Modules with fan-in must have good cohesion Each interfac to the module must have the same number and types of parametersFactoring

Factoring means separation of function into new modules By applying factoring the size of module is reduced and thereby the complexity of the problem is reduced This also provides duplication of functions in more than one module The effective factoring brings simplification in the implementation of software design DESIGN HEURISTICS

The program structure can be manipulated according the design heuristics as shon below1Evaluate the first iteration of the program structure to reduce the coupling and improve cohesion The module independency can be achieved in the program structure by exploding or imploding the modules Exploding the modules means obtaining two or more modules in the final stage and imploding the modules means combining the result of different modules2Attempt to minimize the structure with high fan-out and strive for fan-in as depth increase At the higher level of program structure the distribution of control should be made Fan-out means number of immediate subordinates to the module Fan-in means number of immediate ancestores the module have

86

3Keep scope of the effect of a module within the scope of control of that module The decisions made in particular module lsquoarsquo should not affect the module rsquo brsquo which lies outside the scope of module lsquoarsquo4Evaluate the module interfaces to reduce complexity and redundancy and improve consistency Mostly the cause of softwatr errors is module interfaces The module interfaces should simply pass the information and should be consistent with the module5Define module whose function is predicatable but avoid modules that are too restrictive The module should be designed with simplified internal processing so that expected data can be produced as a result The modules should not restrict the size of local data structure options with control flow or modes of external interfaces Being module too much restrictive causes large maintenance6Strive for controlled entry modules by avoiding pathological connections Software interfaces should be constrained and controlled so that it will become manageable Pathological connection means many references or branches into the middle of a module

Design ModelThe design model is represented as pyramid The pyramid is a stable object

Representing design model in this way means that the software design should be stableThe design model has braod foundation of data design stable mid-region with architectural and interface design and the sharp point to for component level design

Advantages of horizontal partition1These are easy to test maintain and extend 2They have fewer side effects in change propagation or error propagation

Disadvantages of horizontal partitionMore data has to be passed across module interfaces which complicates the overall

control of program flowVertical partitioning

Vertical partitioning suggests the control and work should be distributed top-down in program structureIn vertical partitioning

Define separate branches of the module hierarchy for each major functionUse control modules to co-ordinate communication between functions

Advantages of vertical partition1These are easy to maintain the changes2 They reduce the change impact and error propagation

DATA DESIGNData design is basically the model of data that is represented at the high level of abstractionThe data design is then progressively refined to create implementation specific representationsVarious elements of data design are

Data object - The data objects are identified and relationship among various data objects can be represented using entity relationship diagrams or data dictionariesDatabases - Using software design model the data models are translated into data structures and databases at the application level

87

Data warehouses - At the business level useful information is identified from various databases and the data warehouses are created For extracting or navigating the useful business information stored in the huge data warehouse then data mining techniques are applied

ARCHITECTURAL DESIGNSoftware architecture The design process for identifying the sub-systems making up a system and the framework for sub-system control and communication is architectural design The output of this design process is a description of the software architecture

Architectural design An early stage of the system design process Represents the link between specification and design processes Often carried out in parallel with some specification activities It involves identifying major system components and their communicationsArchitecture and system characteristics Performancebull Localise critical operations and minimise communications Use large rather than fine-grain components Securitybull Use a layered architecture with critical assets in the inner layers Safetybull Localise safety-critical features in a small number of sub-systems Availabilitybull Include redundant components and mechanisms for fault tolerance Maintainabilitybull Use fine-grain replaceable components

Architectural design decisions Is there a generic application architecture that can be used How will the system be distributed What architectural styles are appropriate What approach will be used to structure the system How will the system be decomposed into modules What control strategy should be used How will the architectural design be evaluated How should the architecture be documentedArchitectural styles The architectural model of a system may conform to a generic architectural model or style An awareness of these styles can simplify the problem of defining system architectures However most large systems are heterogeneous and do not follow a single architectural styleArchitectural models

Used to document an architectural design Static structural model that shows the major system components Dynamic process model that shows the process structure of the system Interface model that defines sub-system interfaces

88

Relationships model such as a data-flow model that shows sub-system relationships Distribution model that shows how sub-systems are distributed across computers

Modular decomposition Another structural level where sub-systems are decomposed into modules Two modular decomposition models coveredbull An object model where the system is decomposed into interacting objectbull A pipeline or data-flow model where the system is decomposed into functional modules which transform inputs to outputs If possible decisions about concurrency should be delayed until modules are implemented

Object models Structure the system into a set of loosely coupled objects with well-defined interfaces Object-oriented decomposition is concerned with identifying object classes their attributes and operations When implemented objects are created from these classes and some control model used to coordinate object operations

Invoice Processing system

Pipeline model advantages Supports transformation reuse Intuitive organisation for stakeholder communication Easy to add new transformations Relatively simple to implement as either a concurrent or sequential system However requires a common format for data transfer along the pipeline and difficult

to support event-based interaction

User interface design

The user interface User interfaces should be designed to match the skills experience and expectations of

its anticipated users System users often judge a system by its interface rather than its functionality A poorly designed interface can cause a user to make catastrophic errors Poor user interface design is the reason why so many software systems are never

usedUser interface Design Principle

89

Design principles User familiaritybull The interface should be based on user-oriented terms and concepts rather than computer concepts For example an office system should use concepts such as letters documents folders etc rather than directories file identifiers etc Consistencybull The system should display an appropriate level of consistency Commands and menus should have the same format command punctuation should be similar etc Minimal surprisebull If a command operates in a known way the user should be able to predict the operation of comparable commandsbull Recoverabilitybull The system should provide some resilience to user errors and allow the user to recover from errors This might include an undo facility confirmation of destructive actions soft deletes etcbull User guidancebull Some user guidance such as help systems on-line manuals etc should be suppliedbull User diversitybull Interaction facilities for different types of user should be supported For example some users have seeing difficulties and so larger text should be available

REAL-TIME SOFTWARE DESIGNReal-time systemsSystems which monitor and control their environmentInevitably associated with hardware devices

bull Sensors Collect data from the system environmentbull Actuators Change (in some way) the systems environment

Time is critical Real-time systems must respond within specified times

Definition A real-time system is a software system where the correct functioning of the

system depends on the results produced by the system and the time at which these results are produced

90

A soft real-time system is a system whose operation is degraded if results are not produced according to the specified timing requirements

A hard real-time system is a system whose operation is incorrect if results are not produced according to the timing specification

StimulusResponse Systems Given a stimulus the system must produce a response within a specified timePeriodic stimuli Stimuli which occur at predictable time intervals

bull For example a temperature sensor may be polled 10 times per secondAperiodic stimuli Stimuli which occur at unpredictable times

bull For example a system power failure may trigger an interrupt which must be processed by the system

Architectural considerations Because of the need to respond to timing demands made by different

stimuliresponses the system architecture must allow for fast switching between stimulus handlers

Timing demands of different stimuli are different so a simple sequential loop is not usually adequate

Real-time systems are therefore usually designed as cooperating processes with a real-time executive controlling these processes

A real-time system model

Real-timecontrol system

ActuatorActuator ActuatorActuator

SensorSensorSensor SensorSensorSensor

Sensoractuator processes

Dataprocessor

Actuatorcontrol

Actuator

Sensorcontrol

Sensor

Stimulus Response

System elementsSensor control processes

bull Collect information from sensors May buffer information collected in response to a sensor stimulus

Data processorbull Carries out processing of collected information and computes the system

responseActuator control processes

91

bull Generates control signals for the actuatorsReal-time programmingHard-real time systems may have to programmed in assembly language to ensure that deadlines are metLanguages such as C allow efficient programs to be written but do not have constructs to support concurrency or shared resource management

Java as a real-time languageJava supports lightweight concurrency (threads and synchronized methods) and can be used for some soft real-time systemsJava 20 is not suitable for hard RT programming but real-time versions of Java are now available that address problems such as

bull Not possible to specify thread execution timebull Different timing in different virtual machinesbull Uncontrollable garbage collectionbull Not possible to discover queue sizes for shared resourcesbull Not possible to access system hardwarebull Not possible to do space or timing analysis

SYSTEM DESIGN Design both the hardware and the software associated with system

Partition functions to either hardware or software Design decisions should be made on the basis on non-functional

system requirements Hardware delivers better performance but potentially longer

development and less scope for changeR-T systems design process

Identify the stimuli to be processed and the required responses to these stimuli For each stimulus and response identify the timing constraints Aggregate the stimulus and response processing into concurrent processes A

process may be associated with each class of stimulus and response Design algorithms to process each class of stimulus and response These must

meet the given timing requirements Design a scheduling system which will ensure that processes are started in time to

meet their deadlines Integrate using a real-time operating system

Timing constraints May require extensive simulation and experiment to ensure that these are met by the systemMay mean that certain design strategies such as object-oriented design cannot be used because of the additional overhead involvedMay mean that low-level programming language features have to be used for performance reasons

Real-time system modellingThe effect of a stimulus in a real-time system may trigger a transition from one state to anotherFinite state machines can be used for modelling real-time systems

92

However FSM models lack structure Even simple systems can have a complex modelThe UML includes notations for defining state machine models

Petrol pump state model

Cardinserted

into reader

Timeout

Resettingdo display CC

error

Initialising

do initialisedisplay

Paying

Stopped

Reading

do get CCdetails

Waiting

do display welcome

dodeliver fuel

do debitCC account

Payment ack

Ready Delivering

update displayNozzle

trigger on

Nozzle trigger off

Nozzle trigger on

Hose inholster

do validatecredit card

Validating

Invalid card

Card removedCard OK

Hose out of holster

Timeout

Real-time operating systems(RTOS)

Real-time operating systems are specialised operating systems which manage the processes in the RTS

Responsible for process management and resource (processor and memory) allocation

May be based on a standard kernel which is used unchanged or modified for a particular application

Do not normally include facilities such as file management

Operating system componentsReal-time clock

bull Provides information for process schedulingInterrupt handler

bull Manages aperiodic requests for serviceScheduler

bull Chooses the next process to be runResource manager

bull Allocates memory and processor resourcesDispatcher

bull Starts process executionNon-stop system components

Configuration manager

93

bull Responsible for the dynamic reconfiguration of the system software and hardware Hardware modules may be replaced and software upgraded without stopping the systems

Fault managerbull Responsible for detecting software and hardware faults and taking appropriate

actions (eg switching to backup disks) to ensure that the system continues in operation

Real-time OS components

Process resourcerequirements

Scheduler

Schedulinginformation

Resourcemanager

Despatcher

Real-timeclock

Processesawaiting

resources

Readylist

Interrupthandler

Availableresource

list

Processorlist

Executing process

Readyprocesses

Releasedresources

Process priority The processing of some types of stimuli must sometimes take priority Interrupt level priority Highest priority which is allocated to processes requiring a

very fast response Clock level priority Allocated to periodic processes Within these further levels of priority may be assigned

Interrupt servicing Control is transferred automatically to a pre-determined memory location This location contains an instruction to jump to

an interrupt service routine Further interrupts are disabled the interrupt

serviced and control returned to the interrupted process

Interrupt service routines must be short simple and fast

Periodic process servicing In most real-time systems there will be several classes of periodic process each with

different periods (the time between executions) execution times and deadlines (the time by which processing must be completed)

The real-time clock ticks periodically and each tick causes an interrupt which schedules the process manager for periodic processes

The process manager selects a process which is ready for execution

Process managementbull Concerned with managing the set of concurrent processes

94

bull Periodic processes are executed at pre-specified time intervalsbull The RTOS uses the real-time clock to determine when to execute a process

taking into accountbull Process period - time between executionsbull Process deadline - the time by which processing must be complete

RTE(Real Time Execution Process) process managementResource manager

Allocate memoryand processor

Scheduler

Choose processfor execution

Despatcher

Start execution on anavailable processor

Process switchingbull The scheduler chooses the next process to be executed by the processor This

depends on a scheduling strategy which may take the process priority into account

bull The resource manager allocates memory and a processor for the process to be executed

bull The dispatcher takes the process from ready list loads it onto a processor and starts execution

Scheduling strategiesNon pre-emptive scheduling

bull Once a process has been scheduled for execution it runs to completion or until it is blocked for some reason (eg waiting for IO)

Pre-emptive schedulingbull The execution of an executing processes may be stopped if a higher priority

process requires serviceScheduling algorithms

bull Round-robinbull Rate monotonicbull Shortest deadline first

Monitoring and control systemsbull Important class of real-time systems bull Continuously check sensors and take actions

depending on sensor valuesbull Monitoring systems examine sensors and

report their resultsbull Control systems take sensor values and control hardware actuators

Generic architecture

95

S1

S2

S3

P (S1)

P (S2)

P (S1)

Monitoringprocesses

Controlprocesses

P (A1)

P (A2)

P (A1)

A1

A2

A3

P (A4) A4

Testingprocess

Control panelprocesses

Burglar alarm systembull A system is required to monitor sensors on doors and windows to detect the

presence of intruders in a buildingbull When a sensor indicates a break-in the system switches on lights around the

area and calls police automaticallybull The system should include provision for operation without a mains power

supply Sensorso Movement detectors window sensors door sensorso 50 window sensors 30 door sensors and 200 movement detectorso Voltage drop sensor Actionso When an intruder is detected police are called automaticallyo Lights are switched on in rooms with active sensorso An audible alarm is switched on

The R-T system design process

bull Identify stimuli and associated responsesbull Define the timing constraints associated with each stimulus and responsebull Allocate system functions to concurrent processesbull Design algorithms for stimulus processing and response generationbull Design a scheduling system which ensures that processes will always be

scheduled to meet their deadlinesStimuli to be processed

Power failurebull Generated aperiodically by a circuit monitor When received the system must

switch to backup power within 50 msIntruder alarm

bull Stimulus generated by system sensors Response is to call the police switch on building lights and the Power failure

bull Generated aperiodically by a circuit monitor When received the system must switch to backup power within 50 ms

bull Intruder alarmbull Stimulus generated by system sensors Response is to call the police switch

on building lights and the audible alarmbull audible alarm

Burglar alarm system processes

96

Lighting controlprocess

Audible alarmprocess

Voice synthesiserprocess

Alarm systemprocess

Power switchprocess

Building monitorprocess

Communicationprocess

Door sensorprocess

Movementdetector process

Window sensorprocess

560 Hz

60 Hz400 Hz 100 Hz

Power failureinterrupt

Alarm system

Building monitor

Alarm system

Alarm system

Alarm system

Detector status Sensor status Sensor status

Room number

Alert message

Room number

Room number

Building_monitor process 1

class BuildingMonitor extends Thread

BuildingSensor win door move

Siren siren = new Siren () Lights lights = new Lights () Synthesizer synthesizer = new Synthesizer () DoorSensors doors = new DoorSensors (30) WindowSensors windows = new WindowSensors (50) MovementSensors movements = new MovementSensors (200) PowerMonitor pm = new PowerMonitor ()

BuildingMonitor() initialise all the sensors and start the processessirenstart () lightsstart () synthesizerstart () windowsstart () doorsstart () movementsstart () pmstart ()

Building monitor process 2public void run () int room = 0 while (true) poll the movement sensors at least twice per second (400 Hz)move = movementsgetVal () poll the window sensors at least twicesecond (100 Hz)win = windowsgetVal () poll the door sensors at least twice per second (60 Hz)door = doorsgetVal ()

97

if (movesensorVal == 1 | doorsensorVal == 1 | winsensorVal == 1) a sensor has indicated an intruder if (movesensorVal == 1) room = moveroom if (doorsensorVal == 1) room = doorroom if (winsensorVal == 1 ) room = winroom lightson (room) sirenon () synthesizeron (room) break Building_monitor process 3 lightsshutdown () sirenshutdown () synthesizershutdown () windowsshutdown () doorsshutdown () movementsshutdown ()

run BuildingMonitor

Control systems

bull A burglar alarm system is primarily a monitoring system It collects data from sensors but no real-time actuator control

bull Control systems are similar but in response to sensor values the system sends control signals to actuators

bull An example of a monitoring and control system is a system that monitors temperature and switches heaters on and off

A temperature control system

Thermostatprocess

Sensorprocess

Furnacecontrol process

Heater controlprocess

500 Hz

500 Hz

Thermostat process500 Hz

Sensorvalues

Switch commandRoom number

DATA ACQUISITION SYSTEMSbull Collect data from sensors for subsequent processing and analysisbull Data collection processes and processing processes may have different periods

and deadlines bull Data collection may be faster than processing eg collecting information about

an explosion bull Circular or ring buffers are a mechanism for smoothing speed differences

The generic Architecture of data acquicition

98

DisplayProcess

dataSensor data

bufferSensorprocess

Sensoridentifier and

value

Sensors (each data flow is a sensor value)

Sensoridentifier and

value

Processdata

Sensor databuffer

Sensorprocess

Sensoridentifier and

value

Sensoridentifier and

value

s1

s2

s3

s4

s5

s6

In data acquisition systemsthe sensor may be generating data quickly and the key problem is to ensure that a sensor is allocated before sensor value changeThe essenitial features of this architecture is each group of sensors has three processes associated with it and convert analogue data to digital values if necessary a buffer process and a process that consumes the data carried out further processing Two groups sensors s1-s3 and s4-s6 on the right side a further procee that diplsys the sensor data Neutron flux data acquisition

Operatordisplay

Fluxprocessing

Flux databuffer

A-Dconvertor

Sensoridentifier and

flux valueProcessedflux level

Neutron flux sensors

bull A system collects data from a set of sensors monitoring the neutron flux from a nuclear reactor

bull Each sensor has a process that converts the analog input flux level into a digita signalIt passes this flux level with sensor identifies to the sensor data buffer the data processing takes the data from this bufferprocesses it and pass it to display process for output on an operator display

A ring buffer

Consumerprocess

Producerprocess

Mutual exclusionbull Producer processes collect data and add it to the buffer Consumer processes

take data from the buffer and make elements availablebull Producer and consumer processes must be mutually excluded from accessing

the same elementThe buffer must stop producer processes adding information to a full buffer and consumer processes trying to take information from an empty buffer

99

Page 19: Unit_III

3Keep scope of the effect of a module within the scope of control of that module The decisions made in particular module lsquoarsquo should not affect the module rsquo brsquo which lies outside the scope of module lsquoarsquo4Evaluate the module interfaces to reduce complexity and redundancy and improve consistency Mostly the cause of softwatr errors is module interfaces The module interfaces should simply pass the information and should be consistent with the module5Define module whose function is predicatable but avoid modules that are too restrictive The module should be designed with simplified internal processing so that expected data can be produced as a result The modules should not restrict the size of local data structure options with control flow or modes of external interfaces Being module too much restrictive causes large maintenance6Strive for controlled entry modules by avoiding pathological connections Software interfaces should be constrained and controlled so that it will become manageable Pathological connection means many references or branches into the middle of a module

Design ModelThe design model is represented as pyramid The pyramid is a stable object

Representing design model in this way means that the software design should be stableThe design model has braod foundation of data design stable mid-region with architectural and interface design and the sharp point to for component level design

Advantages of horizontal partition1These are easy to test maintain and extend 2They have fewer side effects in change propagation or error propagation

Disadvantages of horizontal partitionMore data has to be passed across module interfaces which complicates the overall

control of program flowVertical partitioning

Vertical partitioning suggests the control and work should be distributed top-down in program structureIn vertical partitioning

Define separate branches of the module hierarchy for each major functionUse control modules to co-ordinate communication between functions

Advantages of vertical partition1These are easy to maintain the changes2 They reduce the change impact and error propagation

DATA DESIGNData design is basically the model of data that is represented at the high level of abstractionThe data design is then progressively refined to create implementation specific representationsVarious elements of data design are

Data object - The data objects are identified and relationship among various data objects can be represented using entity relationship diagrams or data dictionariesDatabases - Using software design model the data models are translated into data structures and databases at the application level

87

Data warehouses - At the business level useful information is identified from various databases and the data warehouses are created For extracting or navigating the useful business information stored in the huge data warehouse then data mining techniques are applied

ARCHITECTURAL DESIGNSoftware architecture The design process for identifying the sub-systems making up a system and the framework for sub-system control and communication is architectural design The output of this design process is a description of the software architecture

Architectural design An early stage of the system design process Represents the link between specification and design processes Often carried out in parallel with some specification activities It involves identifying major system components and their communicationsArchitecture and system characteristics Performancebull Localise critical operations and minimise communications Use large rather than fine-grain components Securitybull Use a layered architecture with critical assets in the inner layers Safetybull Localise safety-critical features in a small number of sub-systems Availabilitybull Include redundant components and mechanisms for fault tolerance Maintainabilitybull Use fine-grain replaceable components

Architectural design decisions Is there a generic application architecture that can be used How will the system be distributed What architectural styles are appropriate What approach will be used to structure the system How will the system be decomposed into modules What control strategy should be used How will the architectural design be evaluated How should the architecture be documentedArchitectural styles The architectural model of a system may conform to a generic architectural model or style An awareness of these styles can simplify the problem of defining system architectures However most large systems are heterogeneous and do not follow a single architectural styleArchitectural models

Used to document an architectural design Static structural model that shows the major system components Dynamic process model that shows the process structure of the system Interface model that defines sub-system interfaces

88

Relationships model such as a data-flow model that shows sub-system relationships Distribution model that shows how sub-systems are distributed across computers

Modular decomposition Another structural level where sub-systems are decomposed into modules Two modular decomposition models coveredbull An object model where the system is decomposed into interacting objectbull A pipeline or data-flow model where the system is decomposed into functional modules which transform inputs to outputs If possible decisions about concurrency should be delayed until modules are implemented

Object models Structure the system into a set of loosely coupled objects with well-defined interfaces Object-oriented decomposition is concerned with identifying object classes their attributes and operations When implemented objects are created from these classes and some control model used to coordinate object operations

Invoice Processing system

Pipeline model advantages Supports transformation reuse Intuitive organisation for stakeholder communication Easy to add new transformations Relatively simple to implement as either a concurrent or sequential system However requires a common format for data transfer along the pipeline and difficult

to support event-based interaction

User interface design

The user interface User interfaces should be designed to match the skills experience and expectations of

its anticipated users System users often judge a system by its interface rather than its functionality A poorly designed interface can cause a user to make catastrophic errors Poor user interface design is the reason why so many software systems are never

usedUser interface Design Principle

89

Design principles User familiaritybull The interface should be based on user-oriented terms and concepts rather than computer concepts For example an office system should use concepts such as letters documents folders etc rather than directories file identifiers etc Consistencybull The system should display an appropriate level of consistency Commands and menus should have the same format command punctuation should be similar etc Minimal surprisebull If a command operates in a known way the user should be able to predict the operation of comparable commandsbull Recoverabilitybull The system should provide some resilience to user errors and allow the user to recover from errors This might include an undo facility confirmation of destructive actions soft deletes etcbull User guidancebull Some user guidance such as help systems on-line manuals etc should be suppliedbull User diversitybull Interaction facilities for different types of user should be supported For example some users have seeing difficulties and so larger text should be available

REAL-TIME SOFTWARE DESIGNReal-time systemsSystems which monitor and control their environmentInevitably associated with hardware devices

bull Sensors Collect data from the system environmentbull Actuators Change (in some way) the systems environment

Time is critical Real-time systems must respond within specified times

Definition A real-time system is a software system where the correct functioning of the

system depends on the results produced by the system and the time at which these results are produced

90

A soft real-time system is a system whose operation is degraded if results are not produced according to the specified timing requirements

A hard real-time system is a system whose operation is incorrect if results are not produced according to the timing specification

StimulusResponse Systems Given a stimulus the system must produce a response within a specified timePeriodic stimuli Stimuli which occur at predictable time intervals

bull For example a temperature sensor may be polled 10 times per secondAperiodic stimuli Stimuli which occur at unpredictable times

bull For example a system power failure may trigger an interrupt which must be processed by the system

Architectural considerations Because of the need to respond to timing demands made by different

stimuliresponses the system architecture must allow for fast switching between stimulus handlers

Timing demands of different stimuli are different so a simple sequential loop is not usually adequate

Real-time systems are therefore usually designed as cooperating processes with a real-time executive controlling these processes

A real-time system model

Real-timecontrol system

ActuatorActuator ActuatorActuator

SensorSensorSensor SensorSensorSensor

Sensoractuator processes

Dataprocessor

Actuatorcontrol

Actuator

Sensorcontrol

Sensor

Stimulus Response

System elementsSensor control processes

bull Collect information from sensors May buffer information collected in response to a sensor stimulus

Data processorbull Carries out processing of collected information and computes the system

responseActuator control processes

91

bull Generates control signals for the actuatorsReal-time programmingHard-real time systems may have to programmed in assembly language to ensure that deadlines are metLanguages such as C allow efficient programs to be written but do not have constructs to support concurrency or shared resource management

Java as a real-time languageJava supports lightweight concurrency (threads and synchronized methods) and can be used for some soft real-time systemsJava 20 is not suitable for hard RT programming but real-time versions of Java are now available that address problems such as

bull Not possible to specify thread execution timebull Different timing in different virtual machinesbull Uncontrollable garbage collectionbull Not possible to discover queue sizes for shared resourcesbull Not possible to access system hardwarebull Not possible to do space or timing analysis

SYSTEM DESIGN Design both the hardware and the software associated with system

Partition functions to either hardware or software Design decisions should be made on the basis on non-functional

system requirements Hardware delivers better performance but potentially longer

development and less scope for changeR-T systems design process

Identify the stimuli to be processed and the required responses to these stimuli For each stimulus and response identify the timing constraints Aggregate the stimulus and response processing into concurrent processes A

process may be associated with each class of stimulus and response Design algorithms to process each class of stimulus and response These must

meet the given timing requirements Design a scheduling system which will ensure that processes are started in time to

meet their deadlines Integrate using a real-time operating system

Timing constraints May require extensive simulation and experiment to ensure that these are met by the systemMay mean that certain design strategies such as object-oriented design cannot be used because of the additional overhead involvedMay mean that low-level programming language features have to be used for performance reasons

Real-time system modellingThe effect of a stimulus in a real-time system may trigger a transition from one state to anotherFinite state machines can be used for modelling real-time systems

92

However FSM models lack structure Even simple systems can have a complex modelThe UML includes notations for defining state machine models

Petrol pump state model

Cardinserted

into reader

Timeout

Resettingdo display CC

error

Initialising

do initialisedisplay

Paying

Stopped

Reading

do get CCdetails

Waiting

do display welcome

dodeliver fuel

do debitCC account

Payment ack

Ready Delivering

update displayNozzle

trigger on

Nozzle trigger off

Nozzle trigger on

Hose inholster

do validatecredit card

Validating

Invalid card

Card removedCard OK

Hose out of holster

Timeout

Real-time operating systems(RTOS)

Real-time operating systems are specialised operating systems which manage the processes in the RTS

Responsible for process management and resource (processor and memory) allocation

May be based on a standard kernel which is used unchanged or modified for a particular application

Do not normally include facilities such as file management

Operating system componentsReal-time clock

bull Provides information for process schedulingInterrupt handler

bull Manages aperiodic requests for serviceScheduler

bull Chooses the next process to be runResource manager

bull Allocates memory and processor resourcesDispatcher

bull Starts process executionNon-stop system components

Configuration manager

93

bull Responsible for the dynamic reconfiguration of the system software and hardware Hardware modules may be replaced and software upgraded without stopping the systems

Fault managerbull Responsible for detecting software and hardware faults and taking appropriate

actions (eg switching to backup disks) to ensure that the system continues in operation

Real-time OS components

Process resourcerequirements

Scheduler

Schedulinginformation

Resourcemanager

Despatcher

Real-timeclock

Processesawaiting

resources

Readylist

Interrupthandler

Availableresource

list

Processorlist

Executing process

Readyprocesses

Releasedresources

Process priority The processing of some types of stimuli must sometimes take priority Interrupt level priority Highest priority which is allocated to processes requiring a

very fast response Clock level priority Allocated to periodic processes Within these further levels of priority may be assigned

Interrupt servicing Control is transferred automatically to a pre-determined memory location This location contains an instruction to jump to

an interrupt service routine Further interrupts are disabled the interrupt

serviced and control returned to the interrupted process

Interrupt service routines must be short simple and fast

Periodic process servicing In most real-time systems there will be several classes of periodic process each with

different periods (the time between executions) execution times and deadlines (the time by which processing must be completed)

The real-time clock ticks periodically and each tick causes an interrupt which schedules the process manager for periodic processes

The process manager selects a process which is ready for execution

Process managementbull Concerned with managing the set of concurrent processes

94

bull Periodic processes are executed at pre-specified time intervalsbull The RTOS uses the real-time clock to determine when to execute a process

taking into accountbull Process period - time between executionsbull Process deadline - the time by which processing must be complete

RTE(Real Time Execution Process) process managementResource manager

Allocate memoryand processor

Scheduler

Choose processfor execution

Despatcher

Start execution on anavailable processor

Process switchingbull The scheduler chooses the next process to be executed by the processor This

depends on a scheduling strategy which may take the process priority into account

bull The resource manager allocates memory and a processor for the process to be executed

bull The dispatcher takes the process from ready list loads it onto a processor and starts execution

Scheduling strategiesNon pre-emptive scheduling

bull Once a process has been scheduled for execution it runs to completion or until it is blocked for some reason (eg waiting for IO)

Pre-emptive schedulingbull The execution of an executing processes may be stopped if a higher priority

process requires serviceScheduling algorithms

bull Round-robinbull Rate monotonicbull Shortest deadline first

Monitoring and control systemsbull Important class of real-time systems bull Continuously check sensors and take actions

depending on sensor valuesbull Monitoring systems examine sensors and

report their resultsbull Control systems take sensor values and control hardware actuators

Generic architecture

95

S1

S2

S3

P (S1)

P (S2)

P (S1)

Monitoringprocesses

Controlprocesses

P (A1)

P (A2)

P (A1)

A1

A2

A3

P (A4) A4

Testingprocess

Control panelprocesses

Burglar alarm systembull A system is required to monitor sensors on doors and windows to detect the

presence of intruders in a buildingbull When a sensor indicates a break-in the system switches on lights around the

area and calls police automaticallybull The system should include provision for operation without a mains power

supply Sensorso Movement detectors window sensors door sensorso 50 window sensors 30 door sensors and 200 movement detectorso Voltage drop sensor Actionso When an intruder is detected police are called automaticallyo Lights are switched on in rooms with active sensorso An audible alarm is switched on

The R-T system design process

bull Identify stimuli and associated responsesbull Define the timing constraints associated with each stimulus and responsebull Allocate system functions to concurrent processesbull Design algorithms for stimulus processing and response generationbull Design a scheduling system which ensures that processes will always be

scheduled to meet their deadlinesStimuli to be processed

Power failurebull Generated aperiodically by a circuit monitor When received the system must

switch to backup power within 50 msIntruder alarm

bull Stimulus generated by system sensors Response is to call the police switch on building lights and the Power failure

bull Generated aperiodically by a circuit monitor When received the system must switch to backup power within 50 ms

bull Intruder alarmbull Stimulus generated by system sensors Response is to call the police switch

on building lights and the audible alarmbull audible alarm

Burglar alarm system processes

96

Lighting controlprocess

Audible alarmprocess

Voice synthesiserprocess

Alarm systemprocess

Power switchprocess

Building monitorprocess

Communicationprocess

Door sensorprocess

Movementdetector process

Window sensorprocess

560 Hz

60 Hz400 Hz 100 Hz

Power failureinterrupt

Alarm system

Building monitor

Alarm system

Alarm system

Alarm system

Detector status Sensor status Sensor status

Room number

Alert message

Room number

Room number

Building_monitor process 1

class BuildingMonitor extends Thread

BuildingSensor win door move

Siren siren = new Siren () Lights lights = new Lights () Synthesizer synthesizer = new Synthesizer () DoorSensors doors = new DoorSensors (30) WindowSensors windows = new WindowSensors (50) MovementSensors movements = new MovementSensors (200) PowerMonitor pm = new PowerMonitor ()

BuildingMonitor() initialise all the sensors and start the processessirenstart () lightsstart () synthesizerstart () windowsstart () doorsstart () movementsstart () pmstart ()

Building monitor process 2public void run () int room = 0 while (true) poll the movement sensors at least twice per second (400 Hz)move = movementsgetVal () poll the window sensors at least twicesecond (100 Hz)win = windowsgetVal () poll the door sensors at least twice per second (60 Hz)door = doorsgetVal ()

97

if (movesensorVal == 1 | doorsensorVal == 1 | winsensorVal == 1) a sensor has indicated an intruder if (movesensorVal == 1) room = moveroom if (doorsensorVal == 1) room = doorroom if (winsensorVal == 1 ) room = winroom lightson (room) sirenon () synthesizeron (room) break Building_monitor process 3 lightsshutdown () sirenshutdown () synthesizershutdown () windowsshutdown () doorsshutdown () movementsshutdown ()

run BuildingMonitor

Control systems

bull A burglar alarm system is primarily a monitoring system It collects data from sensors but no real-time actuator control

bull Control systems are similar but in response to sensor values the system sends control signals to actuators

bull An example of a monitoring and control system is a system that monitors temperature and switches heaters on and off

A temperature control system

Thermostatprocess

Sensorprocess

Furnacecontrol process

Heater controlprocess

500 Hz

500 Hz

Thermostat process500 Hz

Sensorvalues

Switch commandRoom number

DATA ACQUISITION SYSTEMSbull Collect data from sensors for subsequent processing and analysisbull Data collection processes and processing processes may have different periods

and deadlines bull Data collection may be faster than processing eg collecting information about

an explosion bull Circular or ring buffers are a mechanism for smoothing speed differences

The generic Architecture of data acquicition

98

DisplayProcess

dataSensor data

bufferSensorprocess

Sensoridentifier and

value

Sensors (each data flow is a sensor value)

Sensoridentifier and

value

Processdata

Sensor databuffer

Sensorprocess

Sensoridentifier and

value

Sensoridentifier and

value

s1

s2

s3

s4

s5

s6

In data acquisition systemsthe sensor may be generating data quickly and the key problem is to ensure that a sensor is allocated before sensor value changeThe essenitial features of this architecture is each group of sensors has three processes associated with it and convert analogue data to digital values if necessary a buffer process and a process that consumes the data carried out further processing Two groups sensors s1-s3 and s4-s6 on the right side a further procee that diplsys the sensor data Neutron flux data acquisition

Operatordisplay

Fluxprocessing

Flux databuffer

A-Dconvertor

Sensoridentifier and

flux valueProcessedflux level

Neutron flux sensors

bull A system collects data from a set of sensors monitoring the neutron flux from a nuclear reactor

bull Each sensor has a process that converts the analog input flux level into a digita signalIt passes this flux level with sensor identifies to the sensor data buffer the data processing takes the data from this bufferprocesses it and pass it to display process for output on an operator display

A ring buffer

Consumerprocess

Producerprocess

Mutual exclusionbull Producer processes collect data and add it to the buffer Consumer processes

take data from the buffer and make elements availablebull Producer and consumer processes must be mutually excluded from accessing

the same elementThe buffer must stop producer processes adding information to a full buffer and consumer processes trying to take information from an empty buffer

99

Page 20: Unit_III

Data warehouses - At the business level useful information is identified from various databases and the data warehouses are created For extracting or navigating the useful business information stored in the huge data warehouse then data mining techniques are applied

ARCHITECTURAL DESIGNSoftware architecture The design process for identifying the sub-systems making up a system and the framework for sub-system control and communication is architectural design The output of this design process is a description of the software architecture

Architectural design An early stage of the system design process Represents the link between specification and design processes Often carried out in parallel with some specification activities It involves identifying major system components and their communicationsArchitecture and system characteristics Performancebull Localise critical operations and minimise communications Use large rather than fine-grain components Securitybull Use a layered architecture with critical assets in the inner layers Safetybull Localise safety-critical features in a small number of sub-systems Availabilitybull Include redundant components and mechanisms for fault tolerance Maintainabilitybull Use fine-grain replaceable components

Architectural design decisions Is there a generic application architecture that can be used How will the system be distributed What architectural styles are appropriate What approach will be used to structure the system How will the system be decomposed into modules What control strategy should be used How will the architectural design be evaluated How should the architecture be documentedArchitectural styles The architectural model of a system may conform to a generic architectural model or style An awareness of these styles can simplify the problem of defining system architectures However most large systems are heterogeneous and do not follow a single architectural styleArchitectural models

Used to document an architectural design Static structural model that shows the major system components Dynamic process model that shows the process structure of the system Interface model that defines sub-system interfaces

88

Relationships model such as a data-flow model that shows sub-system relationships Distribution model that shows how sub-systems are distributed across computers

Modular decomposition Another structural level where sub-systems are decomposed into modules Two modular decomposition models coveredbull An object model where the system is decomposed into interacting objectbull A pipeline or data-flow model where the system is decomposed into functional modules which transform inputs to outputs If possible decisions about concurrency should be delayed until modules are implemented

Object models Structure the system into a set of loosely coupled objects with well-defined interfaces Object-oriented decomposition is concerned with identifying object classes their attributes and operations When implemented objects are created from these classes and some control model used to coordinate object operations

Invoice Processing system

Pipeline model advantages Supports transformation reuse Intuitive organisation for stakeholder communication Easy to add new transformations Relatively simple to implement as either a concurrent or sequential system However requires a common format for data transfer along the pipeline and difficult

to support event-based interaction

User interface design

The user interface User interfaces should be designed to match the skills experience and expectations of

its anticipated users System users often judge a system by its interface rather than its functionality A poorly designed interface can cause a user to make catastrophic errors Poor user interface design is the reason why so many software systems are never

usedUser interface Design Principle

89

Design principles User familiaritybull The interface should be based on user-oriented terms and concepts rather than computer concepts For example an office system should use concepts such as letters documents folders etc rather than directories file identifiers etc Consistencybull The system should display an appropriate level of consistency Commands and menus should have the same format command punctuation should be similar etc Minimal surprisebull If a command operates in a known way the user should be able to predict the operation of comparable commandsbull Recoverabilitybull The system should provide some resilience to user errors and allow the user to recover from errors This might include an undo facility confirmation of destructive actions soft deletes etcbull User guidancebull Some user guidance such as help systems on-line manuals etc should be suppliedbull User diversitybull Interaction facilities for different types of user should be supported For example some users have seeing difficulties and so larger text should be available

REAL-TIME SOFTWARE DESIGNReal-time systemsSystems which monitor and control their environmentInevitably associated with hardware devices

bull Sensors Collect data from the system environmentbull Actuators Change (in some way) the systems environment

Time is critical Real-time systems must respond within specified times

Definition A real-time system is a software system where the correct functioning of the

system depends on the results produced by the system and the time at which these results are produced

90

A soft real-time system is a system whose operation is degraded if results are not produced according to the specified timing requirements

A hard real-time system is a system whose operation is incorrect if results are not produced according to the timing specification

StimulusResponse Systems Given a stimulus the system must produce a response within a specified timePeriodic stimuli Stimuli which occur at predictable time intervals

bull For example a temperature sensor may be polled 10 times per secondAperiodic stimuli Stimuli which occur at unpredictable times

bull For example a system power failure may trigger an interrupt which must be processed by the system

Architectural considerations Because of the need to respond to timing demands made by different

stimuliresponses the system architecture must allow for fast switching between stimulus handlers

Timing demands of different stimuli are different so a simple sequential loop is not usually adequate

Real-time systems are therefore usually designed as cooperating processes with a real-time executive controlling these processes

A real-time system model

Real-timecontrol system

ActuatorActuator ActuatorActuator

SensorSensorSensor SensorSensorSensor

Sensoractuator processes

Dataprocessor

Actuatorcontrol

Actuator

Sensorcontrol

Sensor

Stimulus Response

System elementsSensor control processes

bull Collect information from sensors May buffer information collected in response to a sensor stimulus

Data processorbull Carries out processing of collected information and computes the system

responseActuator control processes

91

bull Generates control signals for the actuatorsReal-time programmingHard-real time systems may have to programmed in assembly language to ensure that deadlines are metLanguages such as C allow efficient programs to be written but do not have constructs to support concurrency or shared resource management

Java as a real-time languageJava supports lightweight concurrency (threads and synchronized methods) and can be used for some soft real-time systemsJava 20 is not suitable for hard RT programming but real-time versions of Java are now available that address problems such as

bull Not possible to specify thread execution timebull Different timing in different virtual machinesbull Uncontrollable garbage collectionbull Not possible to discover queue sizes for shared resourcesbull Not possible to access system hardwarebull Not possible to do space or timing analysis

SYSTEM DESIGN Design both the hardware and the software associated with system

Partition functions to either hardware or software Design decisions should be made on the basis on non-functional

system requirements Hardware delivers better performance but potentially longer

development and less scope for changeR-T systems design process

Identify the stimuli to be processed and the required responses to these stimuli For each stimulus and response identify the timing constraints Aggregate the stimulus and response processing into concurrent processes A

process may be associated with each class of stimulus and response Design algorithms to process each class of stimulus and response These must

meet the given timing requirements Design a scheduling system which will ensure that processes are started in time to

meet their deadlines Integrate using a real-time operating system

Timing constraints May require extensive simulation and experiment to ensure that these are met by the systemMay mean that certain design strategies such as object-oriented design cannot be used because of the additional overhead involvedMay mean that low-level programming language features have to be used for performance reasons

Real-time system modellingThe effect of a stimulus in a real-time system may trigger a transition from one state to anotherFinite state machines can be used for modelling real-time systems

92

However FSM models lack structure Even simple systems can have a complex modelThe UML includes notations for defining state machine models

Petrol pump state model

Cardinserted

into reader

Timeout

Resettingdo display CC

error

Initialising

do initialisedisplay

Paying

Stopped

Reading

do get CCdetails

Waiting

do display welcome

dodeliver fuel

do debitCC account

Payment ack

Ready Delivering

update displayNozzle

trigger on

Nozzle trigger off

Nozzle trigger on

Hose inholster

do validatecredit card

Validating

Invalid card

Card removedCard OK

Hose out of holster

Timeout

Real-time operating systems(RTOS)

Real-time operating systems are specialised operating systems which manage the processes in the RTS

Responsible for process management and resource (processor and memory) allocation

May be based on a standard kernel which is used unchanged or modified for a particular application

Do not normally include facilities such as file management

Operating system componentsReal-time clock

bull Provides information for process schedulingInterrupt handler

bull Manages aperiodic requests for serviceScheduler

bull Chooses the next process to be runResource manager

bull Allocates memory and processor resourcesDispatcher

bull Starts process executionNon-stop system components

Configuration manager

93

bull Responsible for the dynamic reconfiguration of the system software and hardware Hardware modules may be replaced and software upgraded without stopping the systems

Fault managerbull Responsible for detecting software and hardware faults and taking appropriate

actions (eg switching to backup disks) to ensure that the system continues in operation

Real-time OS components

Process resourcerequirements

Scheduler

Schedulinginformation

Resourcemanager

Despatcher

Real-timeclock

Processesawaiting

resources

Readylist

Interrupthandler

Availableresource

list

Processorlist

Executing process

Readyprocesses

Releasedresources

Process priority The processing of some types of stimuli must sometimes take priority Interrupt level priority Highest priority which is allocated to processes requiring a

very fast response Clock level priority Allocated to periodic processes Within these further levels of priority may be assigned

Interrupt servicing Control is transferred automatically to a pre-determined memory location This location contains an instruction to jump to

an interrupt service routine Further interrupts are disabled the interrupt

serviced and control returned to the interrupted process

Interrupt service routines must be short simple and fast

Periodic process servicing In most real-time systems there will be several classes of periodic process each with

different periods (the time between executions) execution times and deadlines (the time by which processing must be completed)

The real-time clock ticks periodically and each tick causes an interrupt which schedules the process manager for periodic processes

The process manager selects a process which is ready for execution

Process managementbull Concerned with managing the set of concurrent processes

94

bull Periodic processes are executed at pre-specified time intervalsbull The RTOS uses the real-time clock to determine when to execute a process

taking into accountbull Process period - time between executionsbull Process deadline - the time by which processing must be complete

RTE(Real Time Execution Process) process managementResource manager

Allocate memoryand processor

Scheduler

Choose processfor execution

Despatcher

Start execution on anavailable processor

Process switchingbull The scheduler chooses the next process to be executed by the processor This

depends on a scheduling strategy which may take the process priority into account

bull The resource manager allocates memory and a processor for the process to be executed

bull The dispatcher takes the process from ready list loads it onto a processor and starts execution

Scheduling strategiesNon pre-emptive scheduling

bull Once a process has been scheduled for execution it runs to completion or until it is blocked for some reason (eg waiting for IO)

Pre-emptive schedulingbull The execution of an executing processes may be stopped if a higher priority

process requires serviceScheduling algorithms

bull Round-robinbull Rate monotonicbull Shortest deadline first

Monitoring and control systemsbull Important class of real-time systems bull Continuously check sensors and take actions

depending on sensor valuesbull Monitoring systems examine sensors and

report their resultsbull Control systems take sensor values and control hardware actuators

Generic architecture

95

S1

S2

S3

P (S1)

P (S2)

P (S1)

Monitoringprocesses

Controlprocesses

P (A1)

P (A2)

P (A1)

A1

A2

A3

P (A4) A4

Testingprocess

Control panelprocesses

Burglar alarm systembull A system is required to monitor sensors on doors and windows to detect the

presence of intruders in a buildingbull When a sensor indicates a break-in the system switches on lights around the

area and calls police automaticallybull The system should include provision for operation without a mains power

supply Sensorso Movement detectors window sensors door sensorso 50 window sensors 30 door sensors and 200 movement detectorso Voltage drop sensor Actionso When an intruder is detected police are called automaticallyo Lights are switched on in rooms with active sensorso An audible alarm is switched on

The R-T system design process

bull Identify stimuli and associated responsesbull Define the timing constraints associated with each stimulus and responsebull Allocate system functions to concurrent processesbull Design algorithms for stimulus processing and response generationbull Design a scheduling system which ensures that processes will always be

scheduled to meet their deadlinesStimuli to be processed

Power failurebull Generated aperiodically by a circuit monitor When received the system must

switch to backup power within 50 msIntruder alarm

bull Stimulus generated by system sensors Response is to call the police switch on building lights and the Power failure

bull Generated aperiodically by a circuit monitor When received the system must switch to backup power within 50 ms

bull Intruder alarmbull Stimulus generated by system sensors Response is to call the police switch

on building lights and the audible alarmbull audible alarm

Burglar alarm system processes

96

Lighting controlprocess

Audible alarmprocess

Voice synthesiserprocess

Alarm systemprocess

Power switchprocess

Building monitorprocess

Communicationprocess

Door sensorprocess

Movementdetector process

Window sensorprocess

560 Hz

60 Hz400 Hz 100 Hz

Power failureinterrupt

Alarm system

Building monitor

Alarm system

Alarm system

Alarm system

Detector status Sensor status Sensor status

Room number

Alert message

Room number

Room number

Building_monitor process 1

class BuildingMonitor extends Thread

BuildingSensor win door move

Siren siren = new Siren () Lights lights = new Lights () Synthesizer synthesizer = new Synthesizer () DoorSensors doors = new DoorSensors (30) WindowSensors windows = new WindowSensors (50) MovementSensors movements = new MovementSensors (200) PowerMonitor pm = new PowerMonitor ()

BuildingMonitor() initialise all the sensors and start the processessirenstart () lightsstart () synthesizerstart () windowsstart () doorsstart () movementsstart () pmstart ()

Building monitor process 2public void run () int room = 0 while (true) poll the movement sensors at least twice per second (400 Hz)move = movementsgetVal () poll the window sensors at least twicesecond (100 Hz)win = windowsgetVal () poll the door sensors at least twice per second (60 Hz)door = doorsgetVal ()

97

if (movesensorVal == 1 | doorsensorVal == 1 | winsensorVal == 1) a sensor has indicated an intruder if (movesensorVal == 1) room = moveroom if (doorsensorVal == 1) room = doorroom if (winsensorVal == 1 ) room = winroom lightson (room) sirenon () synthesizeron (room) break Building_monitor process 3 lightsshutdown () sirenshutdown () synthesizershutdown () windowsshutdown () doorsshutdown () movementsshutdown ()

run BuildingMonitor

Control systems

bull A burglar alarm system is primarily a monitoring system It collects data from sensors but no real-time actuator control

bull Control systems are similar but in response to sensor values the system sends control signals to actuators

bull An example of a monitoring and control system is a system that monitors temperature and switches heaters on and off

A temperature control system

Thermostatprocess

Sensorprocess

Furnacecontrol process

Heater controlprocess

500 Hz

500 Hz

Thermostat process500 Hz

Sensorvalues

Switch commandRoom number

DATA ACQUISITION SYSTEMSbull Collect data from sensors for subsequent processing and analysisbull Data collection processes and processing processes may have different periods

and deadlines bull Data collection may be faster than processing eg collecting information about

an explosion bull Circular or ring buffers are a mechanism for smoothing speed differences

The generic Architecture of data acquicition

98

DisplayProcess

dataSensor data

bufferSensorprocess

Sensoridentifier and

value

Sensors (each data flow is a sensor value)

Sensoridentifier and

value

Processdata

Sensor databuffer

Sensorprocess

Sensoridentifier and

value

Sensoridentifier and

value

s1

s2

s3

s4

s5

s6

In data acquisition systemsthe sensor may be generating data quickly and the key problem is to ensure that a sensor is allocated before sensor value changeThe essenitial features of this architecture is each group of sensors has three processes associated with it and convert analogue data to digital values if necessary a buffer process and a process that consumes the data carried out further processing Two groups sensors s1-s3 and s4-s6 on the right side a further procee that diplsys the sensor data Neutron flux data acquisition

Operatordisplay

Fluxprocessing

Flux databuffer

A-Dconvertor

Sensoridentifier and

flux valueProcessedflux level

Neutron flux sensors

bull A system collects data from a set of sensors monitoring the neutron flux from a nuclear reactor

bull Each sensor has a process that converts the analog input flux level into a digita signalIt passes this flux level with sensor identifies to the sensor data buffer the data processing takes the data from this bufferprocesses it and pass it to display process for output on an operator display

A ring buffer

Consumerprocess

Producerprocess

Mutual exclusionbull Producer processes collect data and add it to the buffer Consumer processes

take data from the buffer and make elements availablebull Producer and consumer processes must be mutually excluded from accessing

the same elementThe buffer must stop producer processes adding information to a full buffer and consumer processes trying to take information from an empty buffer

99

Page 21: Unit_III

Relationships model such as a data-flow model that shows sub-system relationships Distribution model that shows how sub-systems are distributed across computers

Modular decomposition Another structural level where sub-systems are decomposed into modules Two modular decomposition models coveredbull An object model where the system is decomposed into interacting objectbull A pipeline or data-flow model where the system is decomposed into functional modules which transform inputs to outputs If possible decisions about concurrency should be delayed until modules are implemented

Object models Structure the system into a set of loosely coupled objects with well-defined interfaces Object-oriented decomposition is concerned with identifying object classes their attributes and operations When implemented objects are created from these classes and some control model used to coordinate object operations

Invoice Processing system

Pipeline model advantages Supports transformation reuse Intuitive organisation for stakeholder communication Easy to add new transformations Relatively simple to implement as either a concurrent or sequential system However requires a common format for data transfer along the pipeline and difficult

to support event-based interaction

User interface design

The user interface User interfaces should be designed to match the skills experience and expectations of

its anticipated users System users often judge a system by its interface rather than its functionality A poorly designed interface can cause a user to make catastrophic errors Poor user interface design is the reason why so many software systems are never

usedUser interface Design Principle

89

Design principles User familiaritybull The interface should be based on user-oriented terms and concepts rather than computer concepts For example an office system should use concepts such as letters documents folders etc rather than directories file identifiers etc Consistencybull The system should display an appropriate level of consistency Commands and menus should have the same format command punctuation should be similar etc Minimal surprisebull If a command operates in a known way the user should be able to predict the operation of comparable commandsbull Recoverabilitybull The system should provide some resilience to user errors and allow the user to recover from errors This might include an undo facility confirmation of destructive actions soft deletes etcbull User guidancebull Some user guidance such as help systems on-line manuals etc should be suppliedbull User diversitybull Interaction facilities for different types of user should be supported For example some users have seeing difficulties and so larger text should be available

REAL-TIME SOFTWARE DESIGNReal-time systemsSystems which monitor and control their environmentInevitably associated with hardware devices

bull Sensors Collect data from the system environmentbull Actuators Change (in some way) the systems environment

Time is critical Real-time systems must respond within specified times

Definition A real-time system is a software system where the correct functioning of the

system depends on the results produced by the system and the time at which these results are produced

90

A soft real-time system is a system whose operation is degraded if results are not produced according to the specified timing requirements

A hard real-time system is a system whose operation is incorrect if results are not produced according to the timing specification

StimulusResponse Systems Given a stimulus the system must produce a response within a specified timePeriodic stimuli Stimuli which occur at predictable time intervals

bull For example a temperature sensor may be polled 10 times per secondAperiodic stimuli Stimuli which occur at unpredictable times

bull For example a system power failure may trigger an interrupt which must be processed by the system

Architectural considerations Because of the need to respond to timing demands made by different

stimuliresponses the system architecture must allow for fast switching between stimulus handlers

Timing demands of different stimuli are different so a simple sequential loop is not usually adequate

Real-time systems are therefore usually designed as cooperating processes with a real-time executive controlling these processes

A real-time system model

Real-timecontrol system

ActuatorActuator ActuatorActuator

SensorSensorSensor SensorSensorSensor

Sensoractuator processes

Dataprocessor

Actuatorcontrol

Actuator

Sensorcontrol

Sensor

Stimulus Response

System elementsSensor control processes

bull Collect information from sensors May buffer information collected in response to a sensor stimulus

Data processorbull Carries out processing of collected information and computes the system

responseActuator control processes

91

bull Generates control signals for the actuatorsReal-time programmingHard-real time systems may have to programmed in assembly language to ensure that deadlines are metLanguages such as C allow efficient programs to be written but do not have constructs to support concurrency or shared resource management

Java as a real-time languageJava supports lightweight concurrency (threads and synchronized methods) and can be used for some soft real-time systemsJava 20 is not suitable for hard RT programming but real-time versions of Java are now available that address problems such as

bull Not possible to specify thread execution timebull Different timing in different virtual machinesbull Uncontrollable garbage collectionbull Not possible to discover queue sizes for shared resourcesbull Not possible to access system hardwarebull Not possible to do space or timing analysis

SYSTEM DESIGN Design both the hardware and the software associated with system

Partition functions to either hardware or software Design decisions should be made on the basis on non-functional

system requirements Hardware delivers better performance but potentially longer

development and less scope for changeR-T systems design process

Identify the stimuli to be processed and the required responses to these stimuli For each stimulus and response identify the timing constraints Aggregate the stimulus and response processing into concurrent processes A

process may be associated with each class of stimulus and response Design algorithms to process each class of stimulus and response These must

meet the given timing requirements Design a scheduling system which will ensure that processes are started in time to

meet their deadlines Integrate using a real-time operating system

Timing constraints May require extensive simulation and experiment to ensure that these are met by the systemMay mean that certain design strategies such as object-oriented design cannot be used because of the additional overhead involvedMay mean that low-level programming language features have to be used for performance reasons

Real-time system modellingThe effect of a stimulus in a real-time system may trigger a transition from one state to anotherFinite state machines can be used for modelling real-time systems

92

However FSM models lack structure Even simple systems can have a complex modelThe UML includes notations for defining state machine models

Petrol pump state model

Cardinserted

into reader

Timeout

Resettingdo display CC

error

Initialising

do initialisedisplay

Paying

Stopped

Reading

do get CCdetails

Waiting

do display welcome

dodeliver fuel

do debitCC account

Payment ack

Ready Delivering

update displayNozzle

trigger on

Nozzle trigger off

Nozzle trigger on

Hose inholster

do validatecredit card

Validating

Invalid card

Card removedCard OK

Hose out of holster

Timeout

Real-time operating systems(RTOS)

Real-time operating systems are specialised operating systems which manage the processes in the RTS

Responsible for process management and resource (processor and memory) allocation

May be based on a standard kernel which is used unchanged or modified for a particular application

Do not normally include facilities such as file management

Operating system componentsReal-time clock

bull Provides information for process schedulingInterrupt handler

bull Manages aperiodic requests for serviceScheduler

bull Chooses the next process to be runResource manager

bull Allocates memory and processor resourcesDispatcher

bull Starts process executionNon-stop system components

Configuration manager

93

bull Responsible for the dynamic reconfiguration of the system software and hardware Hardware modules may be replaced and software upgraded without stopping the systems

Fault managerbull Responsible for detecting software and hardware faults and taking appropriate

actions (eg switching to backup disks) to ensure that the system continues in operation

Real-time OS components

Process resourcerequirements

Scheduler

Schedulinginformation

Resourcemanager

Despatcher

Real-timeclock

Processesawaiting

resources

Readylist

Interrupthandler

Availableresource

list

Processorlist

Executing process

Readyprocesses

Releasedresources

Process priority The processing of some types of stimuli must sometimes take priority Interrupt level priority Highest priority which is allocated to processes requiring a

very fast response Clock level priority Allocated to periodic processes Within these further levels of priority may be assigned

Interrupt servicing Control is transferred automatically to a pre-determined memory location This location contains an instruction to jump to

an interrupt service routine Further interrupts are disabled the interrupt

serviced and control returned to the interrupted process

Interrupt service routines must be short simple and fast

Periodic process servicing In most real-time systems there will be several classes of periodic process each with

different periods (the time between executions) execution times and deadlines (the time by which processing must be completed)

The real-time clock ticks periodically and each tick causes an interrupt which schedules the process manager for periodic processes

The process manager selects a process which is ready for execution

Process managementbull Concerned with managing the set of concurrent processes

94

bull Periodic processes are executed at pre-specified time intervalsbull The RTOS uses the real-time clock to determine when to execute a process

taking into accountbull Process period - time between executionsbull Process deadline - the time by which processing must be complete

RTE(Real Time Execution Process) process managementResource manager

Allocate memoryand processor

Scheduler

Choose processfor execution

Despatcher

Start execution on anavailable processor

Process switchingbull The scheduler chooses the next process to be executed by the processor This

depends on a scheduling strategy which may take the process priority into account

bull The resource manager allocates memory and a processor for the process to be executed

bull The dispatcher takes the process from ready list loads it onto a processor and starts execution

Scheduling strategiesNon pre-emptive scheduling

bull Once a process has been scheduled for execution it runs to completion or until it is blocked for some reason (eg waiting for IO)

Pre-emptive schedulingbull The execution of an executing processes may be stopped if a higher priority

process requires serviceScheduling algorithms

bull Round-robinbull Rate monotonicbull Shortest deadline first

Monitoring and control systemsbull Important class of real-time systems bull Continuously check sensors and take actions

depending on sensor valuesbull Monitoring systems examine sensors and

report their resultsbull Control systems take sensor values and control hardware actuators

Generic architecture

95

S1

S2

S3

P (S1)

P (S2)

P (S1)

Monitoringprocesses

Controlprocesses

P (A1)

P (A2)

P (A1)

A1

A2

A3

P (A4) A4

Testingprocess

Control panelprocesses

Burglar alarm systembull A system is required to monitor sensors on doors and windows to detect the

presence of intruders in a buildingbull When a sensor indicates a break-in the system switches on lights around the

area and calls police automaticallybull The system should include provision for operation without a mains power

supply Sensorso Movement detectors window sensors door sensorso 50 window sensors 30 door sensors and 200 movement detectorso Voltage drop sensor Actionso When an intruder is detected police are called automaticallyo Lights are switched on in rooms with active sensorso An audible alarm is switched on

The R-T system design process

bull Identify stimuli and associated responsesbull Define the timing constraints associated with each stimulus and responsebull Allocate system functions to concurrent processesbull Design algorithms for stimulus processing and response generationbull Design a scheduling system which ensures that processes will always be

scheduled to meet their deadlinesStimuli to be processed

Power failurebull Generated aperiodically by a circuit monitor When received the system must

switch to backup power within 50 msIntruder alarm

bull Stimulus generated by system sensors Response is to call the police switch on building lights and the Power failure

bull Generated aperiodically by a circuit monitor When received the system must switch to backup power within 50 ms

bull Intruder alarmbull Stimulus generated by system sensors Response is to call the police switch

on building lights and the audible alarmbull audible alarm

Burglar alarm system processes

96

Lighting controlprocess

Audible alarmprocess

Voice synthesiserprocess

Alarm systemprocess

Power switchprocess

Building monitorprocess

Communicationprocess

Door sensorprocess

Movementdetector process

Window sensorprocess

560 Hz

60 Hz400 Hz 100 Hz

Power failureinterrupt

Alarm system

Building monitor

Alarm system

Alarm system

Alarm system

Detector status Sensor status Sensor status

Room number

Alert message

Room number

Room number

Building_monitor process 1

class BuildingMonitor extends Thread

BuildingSensor win door move

Siren siren = new Siren () Lights lights = new Lights () Synthesizer synthesizer = new Synthesizer () DoorSensors doors = new DoorSensors (30) WindowSensors windows = new WindowSensors (50) MovementSensors movements = new MovementSensors (200) PowerMonitor pm = new PowerMonitor ()

BuildingMonitor() initialise all the sensors and start the processessirenstart () lightsstart () synthesizerstart () windowsstart () doorsstart () movementsstart () pmstart ()

Building monitor process 2public void run () int room = 0 while (true) poll the movement sensors at least twice per second (400 Hz)move = movementsgetVal () poll the window sensors at least twicesecond (100 Hz)win = windowsgetVal () poll the door sensors at least twice per second (60 Hz)door = doorsgetVal ()

97

if (movesensorVal == 1 | doorsensorVal == 1 | winsensorVal == 1) a sensor has indicated an intruder if (movesensorVal == 1) room = moveroom if (doorsensorVal == 1) room = doorroom if (winsensorVal == 1 ) room = winroom lightson (room) sirenon () synthesizeron (room) break Building_monitor process 3 lightsshutdown () sirenshutdown () synthesizershutdown () windowsshutdown () doorsshutdown () movementsshutdown ()

run BuildingMonitor

Control systems

bull A burglar alarm system is primarily a monitoring system It collects data from sensors but no real-time actuator control

bull Control systems are similar but in response to sensor values the system sends control signals to actuators

bull An example of a monitoring and control system is a system that monitors temperature and switches heaters on and off

A temperature control system

Thermostatprocess

Sensorprocess

Furnacecontrol process

Heater controlprocess

500 Hz

500 Hz

Thermostat process500 Hz

Sensorvalues

Switch commandRoom number

DATA ACQUISITION SYSTEMSbull Collect data from sensors for subsequent processing and analysisbull Data collection processes and processing processes may have different periods

and deadlines bull Data collection may be faster than processing eg collecting information about

an explosion bull Circular or ring buffers are a mechanism for smoothing speed differences

The generic Architecture of data acquicition

98

DisplayProcess

dataSensor data

bufferSensorprocess

Sensoridentifier and

value

Sensors (each data flow is a sensor value)

Sensoridentifier and

value

Processdata

Sensor databuffer

Sensorprocess

Sensoridentifier and

value

Sensoridentifier and

value

s1

s2

s3

s4

s5

s6

In data acquisition systemsthe sensor may be generating data quickly and the key problem is to ensure that a sensor is allocated before sensor value changeThe essenitial features of this architecture is each group of sensors has three processes associated with it and convert analogue data to digital values if necessary a buffer process and a process that consumes the data carried out further processing Two groups sensors s1-s3 and s4-s6 on the right side a further procee that diplsys the sensor data Neutron flux data acquisition

Operatordisplay

Fluxprocessing

Flux databuffer

A-Dconvertor

Sensoridentifier and

flux valueProcessedflux level

Neutron flux sensors

bull A system collects data from a set of sensors monitoring the neutron flux from a nuclear reactor

bull Each sensor has a process that converts the analog input flux level into a digita signalIt passes this flux level with sensor identifies to the sensor data buffer the data processing takes the data from this bufferprocesses it and pass it to display process for output on an operator display

A ring buffer

Consumerprocess

Producerprocess

Mutual exclusionbull Producer processes collect data and add it to the buffer Consumer processes

take data from the buffer and make elements availablebull Producer and consumer processes must be mutually excluded from accessing

the same elementThe buffer must stop producer processes adding information to a full buffer and consumer processes trying to take information from an empty buffer

99

Page 22: Unit_III

Design principles User familiaritybull The interface should be based on user-oriented terms and concepts rather than computer concepts For example an office system should use concepts such as letters documents folders etc rather than directories file identifiers etc Consistencybull The system should display an appropriate level of consistency Commands and menus should have the same format command punctuation should be similar etc Minimal surprisebull If a command operates in a known way the user should be able to predict the operation of comparable commandsbull Recoverabilitybull The system should provide some resilience to user errors and allow the user to recover from errors This might include an undo facility confirmation of destructive actions soft deletes etcbull User guidancebull Some user guidance such as help systems on-line manuals etc should be suppliedbull User diversitybull Interaction facilities for different types of user should be supported For example some users have seeing difficulties and so larger text should be available

REAL-TIME SOFTWARE DESIGNReal-time systemsSystems which monitor and control their environmentInevitably associated with hardware devices

bull Sensors Collect data from the system environmentbull Actuators Change (in some way) the systems environment

Time is critical Real-time systems must respond within specified times

Definition A real-time system is a software system where the correct functioning of the

system depends on the results produced by the system and the time at which these results are produced

90

A soft real-time system is a system whose operation is degraded if results are not produced according to the specified timing requirements

A hard real-time system is a system whose operation is incorrect if results are not produced according to the timing specification

StimulusResponse Systems Given a stimulus the system must produce a response within a specified timePeriodic stimuli Stimuli which occur at predictable time intervals

bull For example a temperature sensor may be polled 10 times per secondAperiodic stimuli Stimuli which occur at unpredictable times

bull For example a system power failure may trigger an interrupt which must be processed by the system

Architectural considerations Because of the need to respond to timing demands made by different

stimuliresponses the system architecture must allow for fast switching between stimulus handlers

Timing demands of different stimuli are different so a simple sequential loop is not usually adequate

Real-time systems are therefore usually designed as cooperating processes with a real-time executive controlling these processes

A real-time system model

Real-timecontrol system

ActuatorActuator ActuatorActuator

SensorSensorSensor SensorSensorSensor

Sensoractuator processes

Dataprocessor

Actuatorcontrol

Actuator

Sensorcontrol

Sensor

Stimulus Response

System elementsSensor control processes

bull Collect information from sensors May buffer information collected in response to a sensor stimulus

Data processorbull Carries out processing of collected information and computes the system

responseActuator control processes

91

bull Generates control signals for the actuatorsReal-time programmingHard-real time systems may have to programmed in assembly language to ensure that deadlines are metLanguages such as C allow efficient programs to be written but do not have constructs to support concurrency or shared resource management

Java as a real-time languageJava supports lightweight concurrency (threads and synchronized methods) and can be used for some soft real-time systemsJava 20 is not suitable for hard RT programming but real-time versions of Java are now available that address problems such as

bull Not possible to specify thread execution timebull Different timing in different virtual machinesbull Uncontrollable garbage collectionbull Not possible to discover queue sizes for shared resourcesbull Not possible to access system hardwarebull Not possible to do space or timing analysis

SYSTEM DESIGN Design both the hardware and the software associated with system

Partition functions to either hardware or software Design decisions should be made on the basis on non-functional

system requirements Hardware delivers better performance but potentially longer

development and less scope for changeR-T systems design process

Identify the stimuli to be processed and the required responses to these stimuli For each stimulus and response identify the timing constraints Aggregate the stimulus and response processing into concurrent processes A

process may be associated with each class of stimulus and response Design algorithms to process each class of stimulus and response These must

meet the given timing requirements Design a scheduling system which will ensure that processes are started in time to

meet their deadlines Integrate using a real-time operating system

Timing constraints May require extensive simulation and experiment to ensure that these are met by the systemMay mean that certain design strategies such as object-oriented design cannot be used because of the additional overhead involvedMay mean that low-level programming language features have to be used for performance reasons

Real-time system modellingThe effect of a stimulus in a real-time system may trigger a transition from one state to anotherFinite state machines can be used for modelling real-time systems

92

However FSM models lack structure Even simple systems can have a complex modelThe UML includes notations for defining state machine models

Petrol pump state model

Cardinserted

into reader

Timeout

Resettingdo display CC

error

Initialising

do initialisedisplay

Paying

Stopped

Reading

do get CCdetails

Waiting

do display welcome

dodeliver fuel

do debitCC account

Payment ack

Ready Delivering

update displayNozzle

trigger on

Nozzle trigger off

Nozzle trigger on

Hose inholster

do validatecredit card

Validating

Invalid card

Card removedCard OK

Hose out of holster

Timeout

Real-time operating systems(RTOS)

Real-time operating systems are specialised operating systems which manage the processes in the RTS

Responsible for process management and resource (processor and memory) allocation

May be based on a standard kernel which is used unchanged or modified for a particular application

Do not normally include facilities such as file management

Operating system componentsReal-time clock

bull Provides information for process schedulingInterrupt handler

bull Manages aperiodic requests for serviceScheduler

bull Chooses the next process to be runResource manager

bull Allocates memory and processor resourcesDispatcher

bull Starts process executionNon-stop system components

Configuration manager

93

bull Responsible for the dynamic reconfiguration of the system software and hardware Hardware modules may be replaced and software upgraded without stopping the systems

Fault managerbull Responsible for detecting software and hardware faults and taking appropriate

actions (eg switching to backup disks) to ensure that the system continues in operation

Real-time OS components

Process resourcerequirements

Scheduler

Schedulinginformation

Resourcemanager

Despatcher

Real-timeclock

Processesawaiting

resources

Readylist

Interrupthandler

Availableresource

list

Processorlist

Executing process

Readyprocesses

Releasedresources

Process priority The processing of some types of stimuli must sometimes take priority Interrupt level priority Highest priority which is allocated to processes requiring a

very fast response Clock level priority Allocated to periodic processes Within these further levels of priority may be assigned

Interrupt servicing Control is transferred automatically to a pre-determined memory location This location contains an instruction to jump to

an interrupt service routine Further interrupts are disabled the interrupt

serviced and control returned to the interrupted process

Interrupt service routines must be short simple and fast

Periodic process servicing In most real-time systems there will be several classes of periodic process each with

different periods (the time between executions) execution times and deadlines (the time by which processing must be completed)

The real-time clock ticks periodically and each tick causes an interrupt which schedules the process manager for periodic processes

The process manager selects a process which is ready for execution

Process managementbull Concerned with managing the set of concurrent processes

94

bull Periodic processes are executed at pre-specified time intervalsbull The RTOS uses the real-time clock to determine when to execute a process

taking into accountbull Process period - time between executionsbull Process deadline - the time by which processing must be complete

RTE(Real Time Execution Process) process managementResource manager

Allocate memoryand processor

Scheduler

Choose processfor execution

Despatcher

Start execution on anavailable processor

Process switchingbull The scheduler chooses the next process to be executed by the processor This

depends on a scheduling strategy which may take the process priority into account

bull The resource manager allocates memory and a processor for the process to be executed

bull The dispatcher takes the process from ready list loads it onto a processor and starts execution

Scheduling strategiesNon pre-emptive scheduling

bull Once a process has been scheduled for execution it runs to completion or until it is blocked for some reason (eg waiting for IO)

Pre-emptive schedulingbull The execution of an executing processes may be stopped if a higher priority

process requires serviceScheduling algorithms

bull Round-robinbull Rate monotonicbull Shortest deadline first

Monitoring and control systemsbull Important class of real-time systems bull Continuously check sensors and take actions

depending on sensor valuesbull Monitoring systems examine sensors and

report their resultsbull Control systems take sensor values and control hardware actuators

Generic architecture

95

S1

S2

S3

P (S1)

P (S2)

P (S1)

Monitoringprocesses

Controlprocesses

P (A1)

P (A2)

P (A1)

A1

A2

A3

P (A4) A4

Testingprocess

Control panelprocesses

Burglar alarm systembull A system is required to monitor sensors on doors and windows to detect the

presence of intruders in a buildingbull When a sensor indicates a break-in the system switches on lights around the

area and calls police automaticallybull The system should include provision for operation without a mains power

supply Sensorso Movement detectors window sensors door sensorso 50 window sensors 30 door sensors and 200 movement detectorso Voltage drop sensor Actionso When an intruder is detected police are called automaticallyo Lights are switched on in rooms with active sensorso An audible alarm is switched on

The R-T system design process

bull Identify stimuli and associated responsesbull Define the timing constraints associated with each stimulus and responsebull Allocate system functions to concurrent processesbull Design algorithms for stimulus processing and response generationbull Design a scheduling system which ensures that processes will always be

scheduled to meet their deadlinesStimuli to be processed

Power failurebull Generated aperiodically by a circuit monitor When received the system must

switch to backup power within 50 msIntruder alarm

bull Stimulus generated by system sensors Response is to call the police switch on building lights and the Power failure

bull Generated aperiodically by a circuit monitor When received the system must switch to backup power within 50 ms

bull Intruder alarmbull Stimulus generated by system sensors Response is to call the police switch

on building lights and the audible alarmbull audible alarm

Burglar alarm system processes

96

Lighting controlprocess

Audible alarmprocess

Voice synthesiserprocess

Alarm systemprocess

Power switchprocess

Building monitorprocess

Communicationprocess

Door sensorprocess

Movementdetector process

Window sensorprocess

560 Hz

60 Hz400 Hz 100 Hz

Power failureinterrupt

Alarm system

Building monitor

Alarm system

Alarm system

Alarm system

Detector status Sensor status Sensor status

Room number

Alert message

Room number

Room number

Building_monitor process 1

class BuildingMonitor extends Thread

BuildingSensor win door move

Siren siren = new Siren () Lights lights = new Lights () Synthesizer synthesizer = new Synthesizer () DoorSensors doors = new DoorSensors (30) WindowSensors windows = new WindowSensors (50) MovementSensors movements = new MovementSensors (200) PowerMonitor pm = new PowerMonitor ()

BuildingMonitor() initialise all the sensors and start the processessirenstart () lightsstart () synthesizerstart () windowsstart () doorsstart () movementsstart () pmstart ()

Building monitor process 2public void run () int room = 0 while (true) poll the movement sensors at least twice per second (400 Hz)move = movementsgetVal () poll the window sensors at least twicesecond (100 Hz)win = windowsgetVal () poll the door sensors at least twice per second (60 Hz)door = doorsgetVal ()

97

if (movesensorVal == 1 | doorsensorVal == 1 | winsensorVal == 1) a sensor has indicated an intruder if (movesensorVal == 1) room = moveroom if (doorsensorVal == 1) room = doorroom if (winsensorVal == 1 ) room = winroom lightson (room) sirenon () synthesizeron (room) break Building_monitor process 3 lightsshutdown () sirenshutdown () synthesizershutdown () windowsshutdown () doorsshutdown () movementsshutdown ()

run BuildingMonitor

Control systems

bull A burglar alarm system is primarily a monitoring system It collects data from sensors but no real-time actuator control

bull Control systems are similar but in response to sensor values the system sends control signals to actuators

bull An example of a monitoring and control system is a system that monitors temperature and switches heaters on and off

A temperature control system

Thermostatprocess

Sensorprocess

Furnacecontrol process

Heater controlprocess

500 Hz

500 Hz

Thermostat process500 Hz

Sensorvalues

Switch commandRoom number

DATA ACQUISITION SYSTEMSbull Collect data from sensors for subsequent processing and analysisbull Data collection processes and processing processes may have different periods

and deadlines bull Data collection may be faster than processing eg collecting information about

an explosion bull Circular or ring buffers are a mechanism for smoothing speed differences

The generic Architecture of data acquicition

98

DisplayProcess

dataSensor data

bufferSensorprocess

Sensoridentifier and

value

Sensors (each data flow is a sensor value)

Sensoridentifier and

value

Processdata

Sensor databuffer

Sensorprocess

Sensoridentifier and

value

Sensoridentifier and

value

s1

s2

s3

s4

s5

s6

In data acquisition systemsthe sensor may be generating data quickly and the key problem is to ensure that a sensor is allocated before sensor value changeThe essenitial features of this architecture is each group of sensors has three processes associated with it and convert analogue data to digital values if necessary a buffer process and a process that consumes the data carried out further processing Two groups sensors s1-s3 and s4-s6 on the right side a further procee that diplsys the sensor data Neutron flux data acquisition

Operatordisplay

Fluxprocessing

Flux databuffer

A-Dconvertor

Sensoridentifier and

flux valueProcessedflux level

Neutron flux sensors

bull A system collects data from a set of sensors monitoring the neutron flux from a nuclear reactor

bull Each sensor has a process that converts the analog input flux level into a digita signalIt passes this flux level with sensor identifies to the sensor data buffer the data processing takes the data from this bufferprocesses it and pass it to display process for output on an operator display

A ring buffer

Consumerprocess

Producerprocess

Mutual exclusionbull Producer processes collect data and add it to the buffer Consumer processes

take data from the buffer and make elements availablebull Producer and consumer processes must be mutually excluded from accessing

the same elementThe buffer must stop producer processes adding information to a full buffer and consumer processes trying to take information from an empty buffer

99

Page 23: Unit_III

A soft real-time system is a system whose operation is degraded if results are not produced according to the specified timing requirements

A hard real-time system is a system whose operation is incorrect if results are not produced according to the timing specification

StimulusResponse Systems Given a stimulus the system must produce a response within a specified timePeriodic stimuli Stimuli which occur at predictable time intervals

bull For example a temperature sensor may be polled 10 times per secondAperiodic stimuli Stimuli which occur at unpredictable times

bull For example a system power failure may trigger an interrupt which must be processed by the system

Architectural considerations Because of the need to respond to timing demands made by different

stimuliresponses the system architecture must allow for fast switching between stimulus handlers

Timing demands of different stimuli are different so a simple sequential loop is not usually adequate

Real-time systems are therefore usually designed as cooperating processes with a real-time executive controlling these processes

A real-time system model

Real-timecontrol system

ActuatorActuator ActuatorActuator

SensorSensorSensor SensorSensorSensor

Sensoractuator processes

Dataprocessor

Actuatorcontrol

Actuator

Sensorcontrol

Sensor

Stimulus Response

System elementsSensor control processes

bull Collect information from sensors May buffer information collected in response to a sensor stimulus

Data processorbull Carries out processing of collected information and computes the system

responseActuator control processes

91

bull Generates control signals for the actuatorsReal-time programmingHard-real time systems may have to programmed in assembly language to ensure that deadlines are metLanguages such as C allow efficient programs to be written but do not have constructs to support concurrency or shared resource management

Java as a real-time languageJava supports lightweight concurrency (threads and synchronized methods) and can be used for some soft real-time systemsJava 20 is not suitable for hard RT programming but real-time versions of Java are now available that address problems such as

bull Not possible to specify thread execution timebull Different timing in different virtual machinesbull Uncontrollable garbage collectionbull Not possible to discover queue sizes for shared resourcesbull Not possible to access system hardwarebull Not possible to do space or timing analysis

SYSTEM DESIGN Design both the hardware and the software associated with system

Partition functions to either hardware or software Design decisions should be made on the basis on non-functional

system requirements Hardware delivers better performance but potentially longer

development and less scope for changeR-T systems design process

Identify the stimuli to be processed and the required responses to these stimuli For each stimulus and response identify the timing constraints Aggregate the stimulus and response processing into concurrent processes A

process may be associated with each class of stimulus and response Design algorithms to process each class of stimulus and response These must

meet the given timing requirements Design a scheduling system which will ensure that processes are started in time to

meet their deadlines Integrate using a real-time operating system

Timing constraints May require extensive simulation and experiment to ensure that these are met by the systemMay mean that certain design strategies such as object-oriented design cannot be used because of the additional overhead involvedMay mean that low-level programming language features have to be used for performance reasons

Real-time system modellingThe effect of a stimulus in a real-time system may trigger a transition from one state to anotherFinite state machines can be used for modelling real-time systems

92

However FSM models lack structure Even simple systems can have a complex modelThe UML includes notations for defining state machine models

Petrol pump state model

Cardinserted

into reader

Timeout

Resettingdo display CC

error

Initialising

do initialisedisplay

Paying

Stopped

Reading

do get CCdetails

Waiting

do display welcome

dodeliver fuel

do debitCC account

Payment ack

Ready Delivering

update displayNozzle

trigger on

Nozzle trigger off

Nozzle trigger on

Hose inholster

do validatecredit card

Validating

Invalid card

Card removedCard OK

Hose out of holster

Timeout

Real-time operating systems(RTOS)

Real-time operating systems are specialised operating systems which manage the processes in the RTS

Responsible for process management and resource (processor and memory) allocation

May be based on a standard kernel which is used unchanged or modified for a particular application

Do not normally include facilities such as file management

Operating system componentsReal-time clock

bull Provides information for process schedulingInterrupt handler

bull Manages aperiodic requests for serviceScheduler

bull Chooses the next process to be runResource manager

bull Allocates memory and processor resourcesDispatcher

bull Starts process executionNon-stop system components

Configuration manager

93

bull Responsible for the dynamic reconfiguration of the system software and hardware Hardware modules may be replaced and software upgraded without stopping the systems

Fault managerbull Responsible for detecting software and hardware faults and taking appropriate

actions (eg switching to backup disks) to ensure that the system continues in operation

Real-time OS components

Process resourcerequirements

Scheduler

Schedulinginformation

Resourcemanager

Despatcher

Real-timeclock

Processesawaiting

resources

Readylist

Interrupthandler

Availableresource

list

Processorlist

Executing process

Readyprocesses

Releasedresources

Process priority The processing of some types of stimuli must sometimes take priority Interrupt level priority Highest priority which is allocated to processes requiring a

very fast response Clock level priority Allocated to periodic processes Within these further levels of priority may be assigned

Interrupt servicing Control is transferred automatically to a pre-determined memory location This location contains an instruction to jump to

an interrupt service routine Further interrupts are disabled the interrupt

serviced and control returned to the interrupted process

Interrupt service routines must be short simple and fast

Periodic process servicing In most real-time systems there will be several classes of periodic process each with

different periods (the time between executions) execution times and deadlines (the time by which processing must be completed)

The real-time clock ticks periodically and each tick causes an interrupt which schedules the process manager for periodic processes

The process manager selects a process which is ready for execution

Process managementbull Concerned with managing the set of concurrent processes

94

bull Periodic processes are executed at pre-specified time intervalsbull The RTOS uses the real-time clock to determine when to execute a process

taking into accountbull Process period - time between executionsbull Process deadline - the time by which processing must be complete

RTE(Real Time Execution Process) process managementResource manager

Allocate memoryand processor

Scheduler

Choose processfor execution

Despatcher

Start execution on anavailable processor

Process switchingbull The scheduler chooses the next process to be executed by the processor This

depends on a scheduling strategy which may take the process priority into account

bull The resource manager allocates memory and a processor for the process to be executed

bull The dispatcher takes the process from ready list loads it onto a processor and starts execution

Scheduling strategiesNon pre-emptive scheduling

bull Once a process has been scheduled for execution it runs to completion or until it is blocked for some reason (eg waiting for IO)

Pre-emptive schedulingbull The execution of an executing processes may be stopped if a higher priority

process requires serviceScheduling algorithms

bull Round-robinbull Rate monotonicbull Shortest deadline first

Monitoring and control systemsbull Important class of real-time systems bull Continuously check sensors and take actions

depending on sensor valuesbull Monitoring systems examine sensors and

report their resultsbull Control systems take sensor values and control hardware actuators

Generic architecture

95

S1

S2

S3

P (S1)

P (S2)

P (S1)

Monitoringprocesses

Controlprocesses

P (A1)

P (A2)

P (A1)

A1

A2

A3

P (A4) A4

Testingprocess

Control panelprocesses

Burglar alarm systembull A system is required to monitor sensors on doors and windows to detect the

presence of intruders in a buildingbull When a sensor indicates a break-in the system switches on lights around the

area and calls police automaticallybull The system should include provision for operation without a mains power

supply Sensorso Movement detectors window sensors door sensorso 50 window sensors 30 door sensors and 200 movement detectorso Voltage drop sensor Actionso When an intruder is detected police are called automaticallyo Lights are switched on in rooms with active sensorso An audible alarm is switched on

The R-T system design process

bull Identify stimuli and associated responsesbull Define the timing constraints associated with each stimulus and responsebull Allocate system functions to concurrent processesbull Design algorithms for stimulus processing and response generationbull Design a scheduling system which ensures that processes will always be

scheduled to meet their deadlinesStimuli to be processed

Power failurebull Generated aperiodically by a circuit monitor When received the system must

switch to backup power within 50 msIntruder alarm

bull Stimulus generated by system sensors Response is to call the police switch on building lights and the Power failure

bull Generated aperiodically by a circuit monitor When received the system must switch to backup power within 50 ms

bull Intruder alarmbull Stimulus generated by system sensors Response is to call the police switch

on building lights and the audible alarmbull audible alarm

Burglar alarm system processes

96

Lighting controlprocess

Audible alarmprocess

Voice synthesiserprocess

Alarm systemprocess

Power switchprocess

Building monitorprocess

Communicationprocess

Door sensorprocess

Movementdetector process

Window sensorprocess

560 Hz

60 Hz400 Hz 100 Hz

Power failureinterrupt

Alarm system

Building monitor

Alarm system

Alarm system

Alarm system

Detector status Sensor status Sensor status

Room number

Alert message

Room number

Room number

Building_monitor process 1

class BuildingMonitor extends Thread

BuildingSensor win door move

Siren siren = new Siren () Lights lights = new Lights () Synthesizer synthesizer = new Synthesizer () DoorSensors doors = new DoorSensors (30) WindowSensors windows = new WindowSensors (50) MovementSensors movements = new MovementSensors (200) PowerMonitor pm = new PowerMonitor ()

BuildingMonitor() initialise all the sensors and start the processessirenstart () lightsstart () synthesizerstart () windowsstart () doorsstart () movementsstart () pmstart ()

Building monitor process 2public void run () int room = 0 while (true) poll the movement sensors at least twice per second (400 Hz)move = movementsgetVal () poll the window sensors at least twicesecond (100 Hz)win = windowsgetVal () poll the door sensors at least twice per second (60 Hz)door = doorsgetVal ()

97

if (movesensorVal == 1 | doorsensorVal == 1 | winsensorVal == 1) a sensor has indicated an intruder if (movesensorVal == 1) room = moveroom if (doorsensorVal == 1) room = doorroom if (winsensorVal == 1 ) room = winroom lightson (room) sirenon () synthesizeron (room) break Building_monitor process 3 lightsshutdown () sirenshutdown () synthesizershutdown () windowsshutdown () doorsshutdown () movementsshutdown ()

run BuildingMonitor

Control systems

bull A burglar alarm system is primarily a monitoring system It collects data from sensors but no real-time actuator control

bull Control systems are similar but in response to sensor values the system sends control signals to actuators

bull An example of a monitoring and control system is a system that monitors temperature and switches heaters on and off

A temperature control system

Thermostatprocess

Sensorprocess

Furnacecontrol process

Heater controlprocess

500 Hz

500 Hz

Thermostat process500 Hz

Sensorvalues

Switch commandRoom number

DATA ACQUISITION SYSTEMSbull Collect data from sensors for subsequent processing and analysisbull Data collection processes and processing processes may have different periods

and deadlines bull Data collection may be faster than processing eg collecting information about

an explosion bull Circular or ring buffers are a mechanism for smoothing speed differences

The generic Architecture of data acquicition

98

DisplayProcess

dataSensor data

bufferSensorprocess

Sensoridentifier and

value

Sensors (each data flow is a sensor value)

Sensoridentifier and

value

Processdata

Sensor databuffer

Sensorprocess

Sensoridentifier and

value

Sensoridentifier and

value

s1

s2

s3

s4

s5

s6

In data acquisition systemsthe sensor may be generating data quickly and the key problem is to ensure that a sensor is allocated before sensor value changeThe essenitial features of this architecture is each group of sensors has three processes associated with it and convert analogue data to digital values if necessary a buffer process and a process that consumes the data carried out further processing Two groups sensors s1-s3 and s4-s6 on the right side a further procee that diplsys the sensor data Neutron flux data acquisition

Operatordisplay

Fluxprocessing

Flux databuffer

A-Dconvertor

Sensoridentifier and

flux valueProcessedflux level

Neutron flux sensors

bull A system collects data from a set of sensors monitoring the neutron flux from a nuclear reactor

bull Each sensor has a process that converts the analog input flux level into a digita signalIt passes this flux level with sensor identifies to the sensor data buffer the data processing takes the data from this bufferprocesses it and pass it to display process for output on an operator display

A ring buffer

Consumerprocess

Producerprocess

Mutual exclusionbull Producer processes collect data and add it to the buffer Consumer processes

take data from the buffer and make elements availablebull Producer and consumer processes must be mutually excluded from accessing

the same elementThe buffer must stop producer processes adding information to a full buffer and consumer processes trying to take information from an empty buffer

99

Page 24: Unit_III

bull Generates control signals for the actuatorsReal-time programmingHard-real time systems may have to programmed in assembly language to ensure that deadlines are metLanguages such as C allow efficient programs to be written but do not have constructs to support concurrency or shared resource management

Java as a real-time languageJava supports lightweight concurrency (threads and synchronized methods) and can be used for some soft real-time systemsJava 20 is not suitable for hard RT programming but real-time versions of Java are now available that address problems such as

bull Not possible to specify thread execution timebull Different timing in different virtual machinesbull Uncontrollable garbage collectionbull Not possible to discover queue sizes for shared resourcesbull Not possible to access system hardwarebull Not possible to do space or timing analysis

SYSTEM DESIGN Design both the hardware and the software associated with system

Partition functions to either hardware or software Design decisions should be made on the basis on non-functional

system requirements Hardware delivers better performance but potentially longer

development and less scope for changeR-T systems design process

Identify the stimuli to be processed and the required responses to these stimuli For each stimulus and response identify the timing constraints Aggregate the stimulus and response processing into concurrent processes A

process may be associated with each class of stimulus and response Design algorithms to process each class of stimulus and response These must

meet the given timing requirements Design a scheduling system which will ensure that processes are started in time to

meet their deadlines Integrate using a real-time operating system

Timing constraints May require extensive simulation and experiment to ensure that these are met by the systemMay mean that certain design strategies such as object-oriented design cannot be used because of the additional overhead involvedMay mean that low-level programming language features have to be used for performance reasons

Real-time system modellingThe effect of a stimulus in a real-time system may trigger a transition from one state to anotherFinite state machines can be used for modelling real-time systems

92

However FSM models lack structure Even simple systems can have a complex modelThe UML includes notations for defining state machine models

Petrol pump state model

Cardinserted

into reader

Timeout

Resettingdo display CC

error

Initialising

do initialisedisplay

Paying

Stopped

Reading

do get CCdetails

Waiting

do display welcome

dodeliver fuel

do debitCC account

Payment ack

Ready Delivering

update displayNozzle

trigger on

Nozzle trigger off

Nozzle trigger on

Hose inholster

do validatecredit card

Validating

Invalid card

Card removedCard OK

Hose out of holster

Timeout

Real-time operating systems(RTOS)

Real-time operating systems are specialised operating systems which manage the processes in the RTS

Responsible for process management and resource (processor and memory) allocation

May be based on a standard kernel which is used unchanged or modified for a particular application

Do not normally include facilities such as file management

Operating system componentsReal-time clock

bull Provides information for process schedulingInterrupt handler

bull Manages aperiodic requests for serviceScheduler

bull Chooses the next process to be runResource manager

bull Allocates memory and processor resourcesDispatcher

bull Starts process executionNon-stop system components

Configuration manager

93

bull Responsible for the dynamic reconfiguration of the system software and hardware Hardware modules may be replaced and software upgraded without stopping the systems

Fault managerbull Responsible for detecting software and hardware faults and taking appropriate

actions (eg switching to backup disks) to ensure that the system continues in operation

Real-time OS components

Process resourcerequirements

Scheduler

Schedulinginformation

Resourcemanager

Despatcher

Real-timeclock

Processesawaiting

resources

Readylist

Interrupthandler

Availableresource

list

Processorlist

Executing process

Readyprocesses

Releasedresources

Process priority The processing of some types of stimuli must sometimes take priority Interrupt level priority Highest priority which is allocated to processes requiring a

very fast response Clock level priority Allocated to periodic processes Within these further levels of priority may be assigned

Interrupt servicing Control is transferred automatically to a pre-determined memory location This location contains an instruction to jump to

an interrupt service routine Further interrupts are disabled the interrupt

serviced and control returned to the interrupted process

Interrupt service routines must be short simple and fast

Periodic process servicing In most real-time systems there will be several classes of periodic process each with

different periods (the time between executions) execution times and deadlines (the time by which processing must be completed)

The real-time clock ticks periodically and each tick causes an interrupt which schedules the process manager for periodic processes

The process manager selects a process which is ready for execution

Process managementbull Concerned with managing the set of concurrent processes

94

bull Periodic processes are executed at pre-specified time intervalsbull The RTOS uses the real-time clock to determine when to execute a process

taking into accountbull Process period - time between executionsbull Process deadline - the time by which processing must be complete

RTE(Real Time Execution Process) process managementResource manager

Allocate memoryand processor

Scheduler

Choose processfor execution

Despatcher

Start execution on anavailable processor

Process switchingbull The scheduler chooses the next process to be executed by the processor This

depends on a scheduling strategy which may take the process priority into account

bull The resource manager allocates memory and a processor for the process to be executed

bull The dispatcher takes the process from ready list loads it onto a processor and starts execution

Scheduling strategiesNon pre-emptive scheduling

bull Once a process has been scheduled for execution it runs to completion or until it is blocked for some reason (eg waiting for IO)

Pre-emptive schedulingbull The execution of an executing processes may be stopped if a higher priority

process requires serviceScheduling algorithms

bull Round-robinbull Rate monotonicbull Shortest deadline first

Monitoring and control systemsbull Important class of real-time systems bull Continuously check sensors and take actions

depending on sensor valuesbull Monitoring systems examine sensors and

report their resultsbull Control systems take sensor values and control hardware actuators

Generic architecture

95

S1

S2

S3

P (S1)

P (S2)

P (S1)

Monitoringprocesses

Controlprocesses

P (A1)

P (A2)

P (A1)

A1

A2

A3

P (A4) A4

Testingprocess

Control panelprocesses

Burglar alarm systembull A system is required to monitor sensors on doors and windows to detect the

presence of intruders in a buildingbull When a sensor indicates a break-in the system switches on lights around the

area and calls police automaticallybull The system should include provision for operation without a mains power

supply Sensorso Movement detectors window sensors door sensorso 50 window sensors 30 door sensors and 200 movement detectorso Voltage drop sensor Actionso When an intruder is detected police are called automaticallyo Lights are switched on in rooms with active sensorso An audible alarm is switched on

The R-T system design process

bull Identify stimuli and associated responsesbull Define the timing constraints associated with each stimulus and responsebull Allocate system functions to concurrent processesbull Design algorithms for stimulus processing and response generationbull Design a scheduling system which ensures that processes will always be

scheduled to meet their deadlinesStimuli to be processed

Power failurebull Generated aperiodically by a circuit monitor When received the system must

switch to backup power within 50 msIntruder alarm

bull Stimulus generated by system sensors Response is to call the police switch on building lights and the Power failure

bull Generated aperiodically by a circuit monitor When received the system must switch to backup power within 50 ms

bull Intruder alarmbull Stimulus generated by system sensors Response is to call the police switch

on building lights and the audible alarmbull audible alarm

Burglar alarm system processes

96

Lighting controlprocess

Audible alarmprocess

Voice synthesiserprocess

Alarm systemprocess

Power switchprocess

Building monitorprocess

Communicationprocess

Door sensorprocess

Movementdetector process

Window sensorprocess

560 Hz

60 Hz400 Hz 100 Hz

Power failureinterrupt

Alarm system

Building monitor

Alarm system

Alarm system

Alarm system

Detector status Sensor status Sensor status

Room number

Alert message

Room number

Room number

Building_monitor process 1

class BuildingMonitor extends Thread

BuildingSensor win door move

Siren siren = new Siren () Lights lights = new Lights () Synthesizer synthesizer = new Synthesizer () DoorSensors doors = new DoorSensors (30) WindowSensors windows = new WindowSensors (50) MovementSensors movements = new MovementSensors (200) PowerMonitor pm = new PowerMonitor ()

BuildingMonitor() initialise all the sensors and start the processessirenstart () lightsstart () synthesizerstart () windowsstart () doorsstart () movementsstart () pmstart ()

Building monitor process 2public void run () int room = 0 while (true) poll the movement sensors at least twice per second (400 Hz)move = movementsgetVal () poll the window sensors at least twicesecond (100 Hz)win = windowsgetVal () poll the door sensors at least twice per second (60 Hz)door = doorsgetVal ()

97

if (movesensorVal == 1 | doorsensorVal == 1 | winsensorVal == 1) a sensor has indicated an intruder if (movesensorVal == 1) room = moveroom if (doorsensorVal == 1) room = doorroom if (winsensorVal == 1 ) room = winroom lightson (room) sirenon () synthesizeron (room) break Building_monitor process 3 lightsshutdown () sirenshutdown () synthesizershutdown () windowsshutdown () doorsshutdown () movementsshutdown ()

run BuildingMonitor

Control systems

bull A burglar alarm system is primarily a monitoring system It collects data from sensors but no real-time actuator control

bull Control systems are similar but in response to sensor values the system sends control signals to actuators

bull An example of a monitoring and control system is a system that monitors temperature and switches heaters on and off

A temperature control system

Thermostatprocess

Sensorprocess

Furnacecontrol process

Heater controlprocess

500 Hz

500 Hz

Thermostat process500 Hz

Sensorvalues

Switch commandRoom number

DATA ACQUISITION SYSTEMSbull Collect data from sensors for subsequent processing and analysisbull Data collection processes and processing processes may have different periods

and deadlines bull Data collection may be faster than processing eg collecting information about

an explosion bull Circular or ring buffers are a mechanism for smoothing speed differences

The generic Architecture of data acquicition

98

DisplayProcess

dataSensor data

bufferSensorprocess

Sensoridentifier and

value

Sensors (each data flow is a sensor value)

Sensoridentifier and

value

Processdata

Sensor databuffer

Sensorprocess

Sensoridentifier and

value

Sensoridentifier and

value

s1

s2

s3

s4

s5

s6

In data acquisition systemsthe sensor may be generating data quickly and the key problem is to ensure that a sensor is allocated before sensor value changeThe essenitial features of this architecture is each group of sensors has three processes associated with it and convert analogue data to digital values if necessary a buffer process and a process that consumes the data carried out further processing Two groups sensors s1-s3 and s4-s6 on the right side a further procee that diplsys the sensor data Neutron flux data acquisition

Operatordisplay

Fluxprocessing

Flux databuffer

A-Dconvertor

Sensoridentifier and

flux valueProcessedflux level

Neutron flux sensors

bull A system collects data from a set of sensors monitoring the neutron flux from a nuclear reactor

bull Each sensor has a process that converts the analog input flux level into a digita signalIt passes this flux level with sensor identifies to the sensor data buffer the data processing takes the data from this bufferprocesses it and pass it to display process for output on an operator display

A ring buffer

Consumerprocess

Producerprocess

Mutual exclusionbull Producer processes collect data and add it to the buffer Consumer processes

take data from the buffer and make elements availablebull Producer and consumer processes must be mutually excluded from accessing

the same elementThe buffer must stop producer processes adding information to a full buffer and consumer processes trying to take information from an empty buffer

99

Page 25: Unit_III

However FSM models lack structure Even simple systems can have a complex modelThe UML includes notations for defining state machine models

Petrol pump state model

Cardinserted

into reader

Timeout

Resettingdo display CC

error

Initialising

do initialisedisplay

Paying

Stopped

Reading

do get CCdetails

Waiting

do display welcome

dodeliver fuel

do debitCC account

Payment ack

Ready Delivering

update displayNozzle

trigger on

Nozzle trigger off

Nozzle trigger on

Hose inholster

do validatecredit card

Validating

Invalid card

Card removedCard OK

Hose out of holster

Timeout

Real-time operating systems(RTOS)

Real-time operating systems are specialised operating systems which manage the processes in the RTS

Responsible for process management and resource (processor and memory) allocation

May be based on a standard kernel which is used unchanged or modified for a particular application

Do not normally include facilities such as file management

Operating system componentsReal-time clock

bull Provides information for process schedulingInterrupt handler

bull Manages aperiodic requests for serviceScheduler

bull Chooses the next process to be runResource manager

bull Allocates memory and processor resourcesDispatcher

bull Starts process executionNon-stop system components

Configuration manager

93

bull Responsible for the dynamic reconfiguration of the system software and hardware Hardware modules may be replaced and software upgraded without stopping the systems

Fault managerbull Responsible for detecting software and hardware faults and taking appropriate

actions (eg switching to backup disks) to ensure that the system continues in operation

Real-time OS components

Process resourcerequirements

Scheduler

Schedulinginformation

Resourcemanager

Despatcher

Real-timeclock

Processesawaiting

resources

Readylist

Interrupthandler

Availableresource

list

Processorlist

Executing process

Readyprocesses

Releasedresources

Process priority The processing of some types of stimuli must sometimes take priority Interrupt level priority Highest priority which is allocated to processes requiring a

very fast response Clock level priority Allocated to periodic processes Within these further levels of priority may be assigned

Interrupt servicing Control is transferred automatically to a pre-determined memory location This location contains an instruction to jump to

an interrupt service routine Further interrupts are disabled the interrupt

serviced and control returned to the interrupted process

Interrupt service routines must be short simple and fast

Periodic process servicing In most real-time systems there will be several classes of periodic process each with

different periods (the time between executions) execution times and deadlines (the time by which processing must be completed)

The real-time clock ticks periodically and each tick causes an interrupt which schedules the process manager for periodic processes

The process manager selects a process which is ready for execution

Process managementbull Concerned with managing the set of concurrent processes

94

bull Periodic processes are executed at pre-specified time intervalsbull The RTOS uses the real-time clock to determine when to execute a process

taking into accountbull Process period - time between executionsbull Process deadline - the time by which processing must be complete

RTE(Real Time Execution Process) process managementResource manager

Allocate memoryand processor

Scheduler

Choose processfor execution

Despatcher

Start execution on anavailable processor

Process switchingbull The scheduler chooses the next process to be executed by the processor This

depends on a scheduling strategy which may take the process priority into account

bull The resource manager allocates memory and a processor for the process to be executed

bull The dispatcher takes the process from ready list loads it onto a processor and starts execution

Scheduling strategiesNon pre-emptive scheduling

bull Once a process has been scheduled for execution it runs to completion or until it is blocked for some reason (eg waiting for IO)

Pre-emptive schedulingbull The execution of an executing processes may be stopped if a higher priority

process requires serviceScheduling algorithms

bull Round-robinbull Rate monotonicbull Shortest deadline first

Monitoring and control systemsbull Important class of real-time systems bull Continuously check sensors and take actions

depending on sensor valuesbull Monitoring systems examine sensors and

report their resultsbull Control systems take sensor values and control hardware actuators

Generic architecture

95

S1

S2

S3

P (S1)

P (S2)

P (S1)

Monitoringprocesses

Controlprocesses

P (A1)

P (A2)

P (A1)

A1

A2

A3

P (A4) A4

Testingprocess

Control panelprocesses

Burglar alarm systembull A system is required to monitor sensors on doors and windows to detect the

presence of intruders in a buildingbull When a sensor indicates a break-in the system switches on lights around the

area and calls police automaticallybull The system should include provision for operation without a mains power

supply Sensorso Movement detectors window sensors door sensorso 50 window sensors 30 door sensors and 200 movement detectorso Voltage drop sensor Actionso When an intruder is detected police are called automaticallyo Lights are switched on in rooms with active sensorso An audible alarm is switched on

The R-T system design process

bull Identify stimuli and associated responsesbull Define the timing constraints associated with each stimulus and responsebull Allocate system functions to concurrent processesbull Design algorithms for stimulus processing and response generationbull Design a scheduling system which ensures that processes will always be

scheduled to meet their deadlinesStimuli to be processed

Power failurebull Generated aperiodically by a circuit monitor When received the system must

switch to backup power within 50 msIntruder alarm

bull Stimulus generated by system sensors Response is to call the police switch on building lights and the Power failure

bull Generated aperiodically by a circuit monitor When received the system must switch to backup power within 50 ms

bull Intruder alarmbull Stimulus generated by system sensors Response is to call the police switch

on building lights and the audible alarmbull audible alarm

Burglar alarm system processes

96

Lighting controlprocess

Audible alarmprocess

Voice synthesiserprocess

Alarm systemprocess

Power switchprocess

Building monitorprocess

Communicationprocess

Door sensorprocess

Movementdetector process

Window sensorprocess

560 Hz

60 Hz400 Hz 100 Hz

Power failureinterrupt

Alarm system

Building monitor

Alarm system

Alarm system

Alarm system

Detector status Sensor status Sensor status

Room number

Alert message

Room number

Room number

Building_monitor process 1

class BuildingMonitor extends Thread

BuildingSensor win door move

Siren siren = new Siren () Lights lights = new Lights () Synthesizer synthesizer = new Synthesizer () DoorSensors doors = new DoorSensors (30) WindowSensors windows = new WindowSensors (50) MovementSensors movements = new MovementSensors (200) PowerMonitor pm = new PowerMonitor ()

BuildingMonitor() initialise all the sensors and start the processessirenstart () lightsstart () synthesizerstart () windowsstart () doorsstart () movementsstart () pmstart ()

Building monitor process 2public void run () int room = 0 while (true) poll the movement sensors at least twice per second (400 Hz)move = movementsgetVal () poll the window sensors at least twicesecond (100 Hz)win = windowsgetVal () poll the door sensors at least twice per second (60 Hz)door = doorsgetVal ()

97

if (movesensorVal == 1 | doorsensorVal == 1 | winsensorVal == 1) a sensor has indicated an intruder if (movesensorVal == 1) room = moveroom if (doorsensorVal == 1) room = doorroom if (winsensorVal == 1 ) room = winroom lightson (room) sirenon () synthesizeron (room) break Building_monitor process 3 lightsshutdown () sirenshutdown () synthesizershutdown () windowsshutdown () doorsshutdown () movementsshutdown ()

run BuildingMonitor

Control systems

bull A burglar alarm system is primarily a monitoring system It collects data from sensors but no real-time actuator control

bull Control systems are similar but in response to sensor values the system sends control signals to actuators

bull An example of a monitoring and control system is a system that monitors temperature and switches heaters on and off

A temperature control system

Thermostatprocess

Sensorprocess

Furnacecontrol process

Heater controlprocess

500 Hz

500 Hz

Thermostat process500 Hz

Sensorvalues

Switch commandRoom number

DATA ACQUISITION SYSTEMSbull Collect data from sensors for subsequent processing and analysisbull Data collection processes and processing processes may have different periods

and deadlines bull Data collection may be faster than processing eg collecting information about

an explosion bull Circular or ring buffers are a mechanism for smoothing speed differences

The generic Architecture of data acquicition

98

DisplayProcess

dataSensor data

bufferSensorprocess

Sensoridentifier and

value

Sensors (each data flow is a sensor value)

Sensoridentifier and

value

Processdata

Sensor databuffer

Sensorprocess

Sensoridentifier and

value

Sensoridentifier and

value

s1

s2

s3

s4

s5

s6

In data acquisition systemsthe sensor may be generating data quickly and the key problem is to ensure that a sensor is allocated before sensor value changeThe essenitial features of this architecture is each group of sensors has three processes associated with it and convert analogue data to digital values if necessary a buffer process and a process that consumes the data carried out further processing Two groups sensors s1-s3 and s4-s6 on the right side a further procee that diplsys the sensor data Neutron flux data acquisition

Operatordisplay

Fluxprocessing

Flux databuffer

A-Dconvertor

Sensoridentifier and

flux valueProcessedflux level

Neutron flux sensors

bull A system collects data from a set of sensors monitoring the neutron flux from a nuclear reactor

bull Each sensor has a process that converts the analog input flux level into a digita signalIt passes this flux level with sensor identifies to the sensor data buffer the data processing takes the data from this bufferprocesses it and pass it to display process for output on an operator display

A ring buffer

Consumerprocess

Producerprocess

Mutual exclusionbull Producer processes collect data and add it to the buffer Consumer processes

take data from the buffer and make elements availablebull Producer and consumer processes must be mutually excluded from accessing

the same elementThe buffer must stop producer processes adding information to a full buffer and consumer processes trying to take information from an empty buffer

99

Page 26: Unit_III

bull Responsible for the dynamic reconfiguration of the system software and hardware Hardware modules may be replaced and software upgraded without stopping the systems

Fault managerbull Responsible for detecting software and hardware faults and taking appropriate

actions (eg switching to backup disks) to ensure that the system continues in operation

Real-time OS components

Process resourcerequirements

Scheduler

Schedulinginformation

Resourcemanager

Despatcher

Real-timeclock

Processesawaiting

resources

Readylist

Interrupthandler

Availableresource

list

Processorlist

Executing process

Readyprocesses

Releasedresources

Process priority The processing of some types of stimuli must sometimes take priority Interrupt level priority Highest priority which is allocated to processes requiring a

very fast response Clock level priority Allocated to periodic processes Within these further levels of priority may be assigned

Interrupt servicing Control is transferred automatically to a pre-determined memory location This location contains an instruction to jump to

an interrupt service routine Further interrupts are disabled the interrupt

serviced and control returned to the interrupted process

Interrupt service routines must be short simple and fast

Periodic process servicing In most real-time systems there will be several classes of periodic process each with

different periods (the time between executions) execution times and deadlines (the time by which processing must be completed)

The real-time clock ticks periodically and each tick causes an interrupt which schedules the process manager for periodic processes

The process manager selects a process which is ready for execution

Process managementbull Concerned with managing the set of concurrent processes

94

bull Periodic processes are executed at pre-specified time intervalsbull The RTOS uses the real-time clock to determine when to execute a process

taking into accountbull Process period - time between executionsbull Process deadline - the time by which processing must be complete

RTE(Real Time Execution Process) process managementResource manager

Allocate memoryand processor

Scheduler

Choose processfor execution

Despatcher

Start execution on anavailable processor

Process switchingbull The scheduler chooses the next process to be executed by the processor This

depends on a scheduling strategy which may take the process priority into account

bull The resource manager allocates memory and a processor for the process to be executed

bull The dispatcher takes the process from ready list loads it onto a processor and starts execution

Scheduling strategiesNon pre-emptive scheduling

bull Once a process has been scheduled for execution it runs to completion or until it is blocked for some reason (eg waiting for IO)

Pre-emptive schedulingbull The execution of an executing processes may be stopped if a higher priority

process requires serviceScheduling algorithms

bull Round-robinbull Rate monotonicbull Shortest deadline first

Monitoring and control systemsbull Important class of real-time systems bull Continuously check sensors and take actions

depending on sensor valuesbull Monitoring systems examine sensors and

report their resultsbull Control systems take sensor values and control hardware actuators

Generic architecture

95

S1

S2

S3

P (S1)

P (S2)

P (S1)

Monitoringprocesses

Controlprocesses

P (A1)

P (A2)

P (A1)

A1

A2

A3

P (A4) A4

Testingprocess

Control panelprocesses

Burglar alarm systembull A system is required to monitor sensors on doors and windows to detect the

presence of intruders in a buildingbull When a sensor indicates a break-in the system switches on lights around the

area and calls police automaticallybull The system should include provision for operation without a mains power

supply Sensorso Movement detectors window sensors door sensorso 50 window sensors 30 door sensors and 200 movement detectorso Voltage drop sensor Actionso When an intruder is detected police are called automaticallyo Lights are switched on in rooms with active sensorso An audible alarm is switched on

The R-T system design process

bull Identify stimuli and associated responsesbull Define the timing constraints associated with each stimulus and responsebull Allocate system functions to concurrent processesbull Design algorithms for stimulus processing and response generationbull Design a scheduling system which ensures that processes will always be

scheduled to meet their deadlinesStimuli to be processed

Power failurebull Generated aperiodically by a circuit monitor When received the system must

switch to backup power within 50 msIntruder alarm

bull Stimulus generated by system sensors Response is to call the police switch on building lights and the Power failure

bull Generated aperiodically by a circuit monitor When received the system must switch to backup power within 50 ms

bull Intruder alarmbull Stimulus generated by system sensors Response is to call the police switch

on building lights and the audible alarmbull audible alarm

Burglar alarm system processes

96

Lighting controlprocess

Audible alarmprocess

Voice synthesiserprocess

Alarm systemprocess

Power switchprocess

Building monitorprocess

Communicationprocess

Door sensorprocess

Movementdetector process

Window sensorprocess

560 Hz

60 Hz400 Hz 100 Hz

Power failureinterrupt

Alarm system

Building monitor

Alarm system

Alarm system

Alarm system

Detector status Sensor status Sensor status

Room number

Alert message

Room number

Room number

Building_monitor process 1

class BuildingMonitor extends Thread

BuildingSensor win door move

Siren siren = new Siren () Lights lights = new Lights () Synthesizer synthesizer = new Synthesizer () DoorSensors doors = new DoorSensors (30) WindowSensors windows = new WindowSensors (50) MovementSensors movements = new MovementSensors (200) PowerMonitor pm = new PowerMonitor ()

BuildingMonitor() initialise all the sensors and start the processessirenstart () lightsstart () synthesizerstart () windowsstart () doorsstart () movementsstart () pmstart ()

Building monitor process 2public void run () int room = 0 while (true) poll the movement sensors at least twice per second (400 Hz)move = movementsgetVal () poll the window sensors at least twicesecond (100 Hz)win = windowsgetVal () poll the door sensors at least twice per second (60 Hz)door = doorsgetVal ()

97

if (movesensorVal == 1 | doorsensorVal == 1 | winsensorVal == 1) a sensor has indicated an intruder if (movesensorVal == 1) room = moveroom if (doorsensorVal == 1) room = doorroom if (winsensorVal == 1 ) room = winroom lightson (room) sirenon () synthesizeron (room) break Building_monitor process 3 lightsshutdown () sirenshutdown () synthesizershutdown () windowsshutdown () doorsshutdown () movementsshutdown ()

run BuildingMonitor

Control systems

bull A burglar alarm system is primarily a monitoring system It collects data from sensors but no real-time actuator control

bull Control systems are similar but in response to sensor values the system sends control signals to actuators

bull An example of a monitoring and control system is a system that monitors temperature and switches heaters on and off

A temperature control system

Thermostatprocess

Sensorprocess

Furnacecontrol process

Heater controlprocess

500 Hz

500 Hz

Thermostat process500 Hz

Sensorvalues

Switch commandRoom number

DATA ACQUISITION SYSTEMSbull Collect data from sensors for subsequent processing and analysisbull Data collection processes and processing processes may have different periods

and deadlines bull Data collection may be faster than processing eg collecting information about

an explosion bull Circular or ring buffers are a mechanism for smoothing speed differences

The generic Architecture of data acquicition

98

DisplayProcess

dataSensor data

bufferSensorprocess

Sensoridentifier and

value

Sensors (each data flow is a sensor value)

Sensoridentifier and

value

Processdata

Sensor databuffer

Sensorprocess

Sensoridentifier and

value

Sensoridentifier and

value

s1

s2

s3

s4

s5

s6

In data acquisition systemsthe sensor may be generating data quickly and the key problem is to ensure that a sensor is allocated before sensor value changeThe essenitial features of this architecture is each group of sensors has three processes associated with it and convert analogue data to digital values if necessary a buffer process and a process that consumes the data carried out further processing Two groups sensors s1-s3 and s4-s6 on the right side a further procee that diplsys the sensor data Neutron flux data acquisition

Operatordisplay

Fluxprocessing

Flux databuffer

A-Dconvertor

Sensoridentifier and

flux valueProcessedflux level

Neutron flux sensors

bull A system collects data from a set of sensors monitoring the neutron flux from a nuclear reactor

bull Each sensor has a process that converts the analog input flux level into a digita signalIt passes this flux level with sensor identifies to the sensor data buffer the data processing takes the data from this bufferprocesses it and pass it to display process for output on an operator display

A ring buffer

Consumerprocess

Producerprocess

Mutual exclusionbull Producer processes collect data and add it to the buffer Consumer processes

take data from the buffer and make elements availablebull Producer and consumer processes must be mutually excluded from accessing

the same elementThe buffer must stop producer processes adding information to a full buffer and consumer processes trying to take information from an empty buffer

99

Page 27: Unit_III

bull Periodic processes are executed at pre-specified time intervalsbull The RTOS uses the real-time clock to determine when to execute a process

taking into accountbull Process period - time between executionsbull Process deadline - the time by which processing must be complete

RTE(Real Time Execution Process) process managementResource manager

Allocate memoryand processor

Scheduler

Choose processfor execution

Despatcher

Start execution on anavailable processor

Process switchingbull The scheduler chooses the next process to be executed by the processor This

depends on a scheduling strategy which may take the process priority into account

bull The resource manager allocates memory and a processor for the process to be executed

bull The dispatcher takes the process from ready list loads it onto a processor and starts execution

Scheduling strategiesNon pre-emptive scheduling

bull Once a process has been scheduled for execution it runs to completion or until it is blocked for some reason (eg waiting for IO)

Pre-emptive schedulingbull The execution of an executing processes may be stopped if a higher priority

process requires serviceScheduling algorithms

bull Round-robinbull Rate monotonicbull Shortest deadline first

Monitoring and control systemsbull Important class of real-time systems bull Continuously check sensors and take actions

depending on sensor valuesbull Monitoring systems examine sensors and

report their resultsbull Control systems take sensor values and control hardware actuators

Generic architecture

95

S1

S2

S3

P (S1)

P (S2)

P (S1)

Monitoringprocesses

Controlprocesses

P (A1)

P (A2)

P (A1)

A1

A2

A3

P (A4) A4

Testingprocess

Control panelprocesses

Burglar alarm systembull A system is required to monitor sensors on doors and windows to detect the

presence of intruders in a buildingbull When a sensor indicates a break-in the system switches on lights around the

area and calls police automaticallybull The system should include provision for operation without a mains power

supply Sensorso Movement detectors window sensors door sensorso 50 window sensors 30 door sensors and 200 movement detectorso Voltage drop sensor Actionso When an intruder is detected police are called automaticallyo Lights are switched on in rooms with active sensorso An audible alarm is switched on

The R-T system design process

bull Identify stimuli and associated responsesbull Define the timing constraints associated with each stimulus and responsebull Allocate system functions to concurrent processesbull Design algorithms for stimulus processing and response generationbull Design a scheduling system which ensures that processes will always be

scheduled to meet their deadlinesStimuli to be processed

Power failurebull Generated aperiodically by a circuit monitor When received the system must

switch to backup power within 50 msIntruder alarm

bull Stimulus generated by system sensors Response is to call the police switch on building lights and the Power failure

bull Generated aperiodically by a circuit monitor When received the system must switch to backup power within 50 ms

bull Intruder alarmbull Stimulus generated by system sensors Response is to call the police switch

on building lights and the audible alarmbull audible alarm

Burglar alarm system processes

96

Lighting controlprocess

Audible alarmprocess

Voice synthesiserprocess

Alarm systemprocess

Power switchprocess

Building monitorprocess

Communicationprocess

Door sensorprocess

Movementdetector process

Window sensorprocess

560 Hz

60 Hz400 Hz 100 Hz

Power failureinterrupt

Alarm system

Building monitor

Alarm system

Alarm system

Alarm system

Detector status Sensor status Sensor status

Room number

Alert message

Room number

Room number

Building_monitor process 1

class BuildingMonitor extends Thread

BuildingSensor win door move

Siren siren = new Siren () Lights lights = new Lights () Synthesizer synthesizer = new Synthesizer () DoorSensors doors = new DoorSensors (30) WindowSensors windows = new WindowSensors (50) MovementSensors movements = new MovementSensors (200) PowerMonitor pm = new PowerMonitor ()

BuildingMonitor() initialise all the sensors and start the processessirenstart () lightsstart () synthesizerstart () windowsstart () doorsstart () movementsstart () pmstart ()

Building monitor process 2public void run () int room = 0 while (true) poll the movement sensors at least twice per second (400 Hz)move = movementsgetVal () poll the window sensors at least twicesecond (100 Hz)win = windowsgetVal () poll the door sensors at least twice per second (60 Hz)door = doorsgetVal ()

97

if (movesensorVal == 1 | doorsensorVal == 1 | winsensorVal == 1) a sensor has indicated an intruder if (movesensorVal == 1) room = moveroom if (doorsensorVal == 1) room = doorroom if (winsensorVal == 1 ) room = winroom lightson (room) sirenon () synthesizeron (room) break Building_monitor process 3 lightsshutdown () sirenshutdown () synthesizershutdown () windowsshutdown () doorsshutdown () movementsshutdown ()

run BuildingMonitor

Control systems

bull A burglar alarm system is primarily a monitoring system It collects data from sensors but no real-time actuator control

bull Control systems are similar but in response to sensor values the system sends control signals to actuators

bull An example of a monitoring and control system is a system that monitors temperature and switches heaters on and off

A temperature control system

Thermostatprocess

Sensorprocess

Furnacecontrol process

Heater controlprocess

500 Hz

500 Hz

Thermostat process500 Hz

Sensorvalues

Switch commandRoom number

DATA ACQUISITION SYSTEMSbull Collect data from sensors for subsequent processing and analysisbull Data collection processes and processing processes may have different periods

and deadlines bull Data collection may be faster than processing eg collecting information about

an explosion bull Circular or ring buffers are a mechanism for smoothing speed differences

The generic Architecture of data acquicition

98

DisplayProcess

dataSensor data

bufferSensorprocess

Sensoridentifier and

value

Sensors (each data flow is a sensor value)

Sensoridentifier and

value

Processdata

Sensor databuffer

Sensorprocess

Sensoridentifier and

value

Sensoridentifier and

value

s1

s2

s3

s4

s5

s6

In data acquisition systemsthe sensor may be generating data quickly and the key problem is to ensure that a sensor is allocated before sensor value changeThe essenitial features of this architecture is each group of sensors has three processes associated with it and convert analogue data to digital values if necessary a buffer process and a process that consumes the data carried out further processing Two groups sensors s1-s3 and s4-s6 on the right side a further procee that diplsys the sensor data Neutron flux data acquisition

Operatordisplay

Fluxprocessing

Flux databuffer

A-Dconvertor

Sensoridentifier and

flux valueProcessedflux level

Neutron flux sensors

bull A system collects data from a set of sensors monitoring the neutron flux from a nuclear reactor

bull Each sensor has a process that converts the analog input flux level into a digita signalIt passes this flux level with sensor identifies to the sensor data buffer the data processing takes the data from this bufferprocesses it and pass it to display process for output on an operator display

A ring buffer

Consumerprocess

Producerprocess

Mutual exclusionbull Producer processes collect data and add it to the buffer Consumer processes

take data from the buffer and make elements availablebull Producer and consumer processes must be mutually excluded from accessing

the same elementThe buffer must stop producer processes adding information to a full buffer and consumer processes trying to take information from an empty buffer

99

Page 28: Unit_III

S1

S2

S3

P (S1)

P (S2)

P (S1)

Monitoringprocesses

Controlprocesses

P (A1)

P (A2)

P (A1)

A1

A2

A3

P (A4) A4

Testingprocess

Control panelprocesses

Burglar alarm systembull A system is required to monitor sensors on doors and windows to detect the

presence of intruders in a buildingbull When a sensor indicates a break-in the system switches on lights around the

area and calls police automaticallybull The system should include provision for operation without a mains power

supply Sensorso Movement detectors window sensors door sensorso 50 window sensors 30 door sensors and 200 movement detectorso Voltage drop sensor Actionso When an intruder is detected police are called automaticallyo Lights are switched on in rooms with active sensorso An audible alarm is switched on

The R-T system design process

bull Identify stimuli and associated responsesbull Define the timing constraints associated with each stimulus and responsebull Allocate system functions to concurrent processesbull Design algorithms for stimulus processing and response generationbull Design a scheduling system which ensures that processes will always be

scheduled to meet their deadlinesStimuli to be processed

Power failurebull Generated aperiodically by a circuit monitor When received the system must

switch to backup power within 50 msIntruder alarm

bull Stimulus generated by system sensors Response is to call the police switch on building lights and the Power failure

bull Generated aperiodically by a circuit monitor When received the system must switch to backup power within 50 ms

bull Intruder alarmbull Stimulus generated by system sensors Response is to call the police switch

on building lights and the audible alarmbull audible alarm

Burglar alarm system processes

96

Lighting controlprocess

Audible alarmprocess

Voice synthesiserprocess

Alarm systemprocess

Power switchprocess

Building monitorprocess

Communicationprocess

Door sensorprocess

Movementdetector process

Window sensorprocess

560 Hz

60 Hz400 Hz 100 Hz

Power failureinterrupt

Alarm system

Building monitor

Alarm system

Alarm system

Alarm system

Detector status Sensor status Sensor status

Room number

Alert message

Room number

Room number

Building_monitor process 1

class BuildingMonitor extends Thread

BuildingSensor win door move

Siren siren = new Siren () Lights lights = new Lights () Synthesizer synthesizer = new Synthesizer () DoorSensors doors = new DoorSensors (30) WindowSensors windows = new WindowSensors (50) MovementSensors movements = new MovementSensors (200) PowerMonitor pm = new PowerMonitor ()

BuildingMonitor() initialise all the sensors and start the processessirenstart () lightsstart () synthesizerstart () windowsstart () doorsstart () movementsstart () pmstart ()

Building monitor process 2public void run () int room = 0 while (true) poll the movement sensors at least twice per second (400 Hz)move = movementsgetVal () poll the window sensors at least twicesecond (100 Hz)win = windowsgetVal () poll the door sensors at least twice per second (60 Hz)door = doorsgetVal ()

97

if (movesensorVal == 1 | doorsensorVal == 1 | winsensorVal == 1) a sensor has indicated an intruder if (movesensorVal == 1) room = moveroom if (doorsensorVal == 1) room = doorroom if (winsensorVal == 1 ) room = winroom lightson (room) sirenon () synthesizeron (room) break Building_monitor process 3 lightsshutdown () sirenshutdown () synthesizershutdown () windowsshutdown () doorsshutdown () movementsshutdown ()

run BuildingMonitor

Control systems

bull A burglar alarm system is primarily a monitoring system It collects data from sensors but no real-time actuator control

bull Control systems are similar but in response to sensor values the system sends control signals to actuators

bull An example of a monitoring and control system is a system that monitors temperature and switches heaters on and off

A temperature control system

Thermostatprocess

Sensorprocess

Furnacecontrol process

Heater controlprocess

500 Hz

500 Hz

Thermostat process500 Hz

Sensorvalues

Switch commandRoom number

DATA ACQUISITION SYSTEMSbull Collect data from sensors for subsequent processing and analysisbull Data collection processes and processing processes may have different periods

and deadlines bull Data collection may be faster than processing eg collecting information about

an explosion bull Circular or ring buffers are a mechanism for smoothing speed differences

The generic Architecture of data acquicition

98

DisplayProcess

dataSensor data

bufferSensorprocess

Sensoridentifier and

value

Sensors (each data flow is a sensor value)

Sensoridentifier and

value

Processdata

Sensor databuffer

Sensorprocess

Sensoridentifier and

value

Sensoridentifier and

value

s1

s2

s3

s4

s5

s6

In data acquisition systemsthe sensor may be generating data quickly and the key problem is to ensure that a sensor is allocated before sensor value changeThe essenitial features of this architecture is each group of sensors has three processes associated with it and convert analogue data to digital values if necessary a buffer process and a process that consumes the data carried out further processing Two groups sensors s1-s3 and s4-s6 on the right side a further procee that diplsys the sensor data Neutron flux data acquisition

Operatordisplay

Fluxprocessing

Flux databuffer

A-Dconvertor

Sensoridentifier and

flux valueProcessedflux level

Neutron flux sensors

bull A system collects data from a set of sensors monitoring the neutron flux from a nuclear reactor

bull Each sensor has a process that converts the analog input flux level into a digita signalIt passes this flux level with sensor identifies to the sensor data buffer the data processing takes the data from this bufferprocesses it and pass it to display process for output on an operator display

A ring buffer

Consumerprocess

Producerprocess

Mutual exclusionbull Producer processes collect data and add it to the buffer Consumer processes

take data from the buffer and make elements availablebull Producer and consumer processes must be mutually excluded from accessing

the same elementThe buffer must stop producer processes adding information to a full buffer and consumer processes trying to take information from an empty buffer

99

Page 29: Unit_III

Lighting controlprocess

Audible alarmprocess

Voice synthesiserprocess

Alarm systemprocess

Power switchprocess

Building monitorprocess

Communicationprocess

Door sensorprocess

Movementdetector process

Window sensorprocess

560 Hz

60 Hz400 Hz 100 Hz

Power failureinterrupt

Alarm system

Building monitor

Alarm system

Alarm system

Alarm system

Detector status Sensor status Sensor status

Room number

Alert message

Room number

Room number

Building_monitor process 1

class BuildingMonitor extends Thread

BuildingSensor win door move

Siren siren = new Siren () Lights lights = new Lights () Synthesizer synthesizer = new Synthesizer () DoorSensors doors = new DoorSensors (30) WindowSensors windows = new WindowSensors (50) MovementSensors movements = new MovementSensors (200) PowerMonitor pm = new PowerMonitor ()

BuildingMonitor() initialise all the sensors and start the processessirenstart () lightsstart () synthesizerstart () windowsstart () doorsstart () movementsstart () pmstart ()

Building monitor process 2public void run () int room = 0 while (true) poll the movement sensors at least twice per second (400 Hz)move = movementsgetVal () poll the window sensors at least twicesecond (100 Hz)win = windowsgetVal () poll the door sensors at least twice per second (60 Hz)door = doorsgetVal ()

97

if (movesensorVal == 1 | doorsensorVal == 1 | winsensorVal == 1) a sensor has indicated an intruder if (movesensorVal == 1) room = moveroom if (doorsensorVal == 1) room = doorroom if (winsensorVal == 1 ) room = winroom lightson (room) sirenon () synthesizeron (room) break Building_monitor process 3 lightsshutdown () sirenshutdown () synthesizershutdown () windowsshutdown () doorsshutdown () movementsshutdown ()

run BuildingMonitor

Control systems

bull A burglar alarm system is primarily a monitoring system It collects data from sensors but no real-time actuator control

bull Control systems are similar but in response to sensor values the system sends control signals to actuators

bull An example of a monitoring and control system is a system that monitors temperature and switches heaters on and off

A temperature control system

Thermostatprocess

Sensorprocess

Furnacecontrol process

Heater controlprocess

500 Hz

500 Hz

Thermostat process500 Hz

Sensorvalues

Switch commandRoom number

DATA ACQUISITION SYSTEMSbull Collect data from sensors for subsequent processing and analysisbull Data collection processes and processing processes may have different periods

and deadlines bull Data collection may be faster than processing eg collecting information about

an explosion bull Circular or ring buffers are a mechanism for smoothing speed differences

The generic Architecture of data acquicition

98

DisplayProcess

dataSensor data

bufferSensorprocess

Sensoridentifier and

value

Sensors (each data flow is a sensor value)

Sensoridentifier and

value

Processdata

Sensor databuffer

Sensorprocess

Sensoridentifier and

value

Sensoridentifier and

value

s1

s2

s3

s4

s5

s6

In data acquisition systemsthe sensor may be generating data quickly and the key problem is to ensure that a sensor is allocated before sensor value changeThe essenitial features of this architecture is each group of sensors has three processes associated with it and convert analogue data to digital values if necessary a buffer process and a process that consumes the data carried out further processing Two groups sensors s1-s3 and s4-s6 on the right side a further procee that diplsys the sensor data Neutron flux data acquisition

Operatordisplay

Fluxprocessing

Flux databuffer

A-Dconvertor

Sensoridentifier and

flux valueProcessedflux level

Neutron flux sensors

bull A system collects data from a set of sensors monitoring the neutron flux from a nuclear reactor

bull Each sensor has a process that converts the analog input flux level into a digita signalIt passes this flux level with sensor identifies to the sensor data buffer the data processing takes the data from this bufferprocesses it and pass it to display process for output on an operator display

A ring buffer

Consumerprocess

Producerprocess

Mutual exclusionbull Producer processes collect data and add it to the buffer Consumer processes

take data from the buffer and make elements availablebull Producer and consumer processes must be mutually excluded from accessing

the same elementThe buffer must stop producer processes adding information to a full buffer and consumer processes trying to take information from an empty buffer

99

Page 30: Unit_III

if (movesensorVal == 1 | doorsensorVal == 1 | winsensorVal == 1) a sensor has indicated an intruder if (movesensorVal == 1) room = moveroom if (doorsensorVal == 1) room = doorroom if (winsensorVal == 1 ) room = winroom lightson (room) sirenon () synthesizeron (room) break Building_monitor process 3 lightsshutdown () sirenshutdown () synthesizershutdown () windowsshutdown () doorsshutdown () movementsshutdown ()

run BuildingMonitor

Control systems

bull A burglar alarm system is primarily a monitoring system It collects data from sensors but no real-time actuator control

bull Control systems are similar but in response to sensor values the system sends control signals to actuators

bull An example of a monitoring and control system is a system that monitors temperature and switches heaters on and off

A temperature control system

Thermostatprocess

Sensorprocess

Furnacecontrol process

Heater controlprocess

500 Hz

500 Hz

Thermostat process500 Hz

Sensorvalues

Switch commandRoom number

DATA ACQUISITION SYSTEMSbull Collect data from sensors for subsequent processing and analysisbull Data collection processes and processing processes may have different periods

and deadlines bull Data collection may be faster than processing eg collecting information about

an explosion bull Circular or ring buffers are a mechanism for smoothing speed differences

The generic Architecture of data acquicition

98

DisplayProcess

dataSensor data

bufferSensorprocess

Sensoridentifier and

value

Sensors (each data flow is a sensor value)

Sensoridentifier and

value

Processdata

Sensor databuffer

Sensorprocess

Sensoridentifier and

value

Sensoridentifier and

value

s1

s2

s3

s4

s5

s6

In data acquisition systemsthe sensor may be generating data quickly and the key problem is to ensure that a sensor is allocated before sensor value changeThe essenitial features of this architecture is each group of sensors has three processes associated with it and convert analogue data to digital values if necessary a buffer process and a process that consumes the data carried out further processing Two groups sensors s1-s3 and s4-s6 on the right side a further procee that diplsys the sensor data Neutron flux data acquisition

Operatordisplay

Fluxprocessing

Flux databuffer

A-Dconvertor

Sensoridentifier and

flux valueProcessedflux level

Neutron flux sensors

bull A system collects data from a set of sensors monitoring the neutron flux from a nuclear reactor

bull Each sensor has a process that converts the analog input flux level into a digita signalIt passes this flux level with sensor identifies to the sensor data buffer the data processing takes the data from this bufferprocesses it and pass it to display process for output on an operator display

A ring buffer

Consumerprocess

Producerprocess

Mutual exclusionbull Producer processes collect data and add it to the buffer Consumer processes

take data from the buffer and make elements availablebull Producer and consumer processes must be mutually excluded from accessing

the same elementThe buffer must stop producer processes adding information to a full buffer and consumer processes trying to take information from an empty buffer

99

Page 31: Unit_III

DisplayProcess

dataSensor data

bufferSensorprocess

Sensoridentifier and

value

Sensors (each data flow is a sensor value)

Sensoridentifier and

value

Processdata

Sensor databuffer

Sensorprocess

Sensoridentifier and

value

Sensoridentifier and

value

s1

s2

s3

s4

s5

s6

In data acquisition systemsthe sensor may be generating data quickly and the key problem is to ensure that a sensor is allocated before sensor value changeThe essenitial features of this architecture is each group of sensors has three processes associated with it and convert analogue data to digital values if necessary a buffer process and a process that consumes the data carried out further processing Two groups sensors s1-s3 and s4-s6 on the right side a further procee that diplsys the sensor data Neutron flux data acquisition

Operatordisplay

Fluxprocessing

Flux databuffer

A-Dconvertor

Sensoridentifier and

flux valueProcessedflux level

Neutron flux sensors

bull A system collects data from a set of sensors monitoring the neutron flux from a nuclear reactor

bull Each sensor has a process that converts the analog input flux level into a digita signalIt passes this flux level with sensor identifies to the sensor data buffer the data processing takes the data from this bufferprocesses it and pass it to display process for output on an operator display

A ring buffer

Consumerprocess

Producerprocess

Mutual exclusionbull Producer processes collect data and add it to the buffer Consumer processes

take data from the buffer and make elements availablebull Producer and consumer processes must be mutually excluded from accessing

the same elementThe buffer must stop producer processes adding information to a full buffer and consumer processes trying to take information from an empty buffer

99