Lab 3 – The Washing Machine (Message based communication)

Lab 3 – The Washing Machine (Message based communication)
Exercises and Labs
Lab 3 – The Washing Machine (Message
based communication)
Exercise session – preparation
Your task is to develop the control software for a washing machine. The machine is
equipped with water level and temperature sensors. In addition, four buttons allow the
user to select a washing program (1, 2, 3) or stop the machine (0). Output signals from
your software will control the following:
• A valve for letting water into the machine.
• A drain pump for draining the machine.
• A heater for heating the water.
• A motor for rotation of the barrel. The motor has the modes left spin, right spin,
fast spin (centrifuge), and stop.
Objective
After the lab you should know the following terms:
• Mailboxes
• Periodic and transactional activities
and be able to
• Share data between threads using asynchronous communication
• Understand and extract the design of a partially implemented system from specification and handout code
• Complete a partially prepared implementation
Preparation and design
Discuss the handout code (see below and in the .zip-file) and the specification given below. The code contains a skeleton design that you need to understand and build on for
your implementation. Extract this skeleton and prepare a respective drawing. The following questions might help you to understand the design. Indicate, which parts are given
and which ones you will have to add. Keep in mind that a complete system should be
implemented before the lab session.
43
Multi-Threaded Programming in Java
• Which concurrent activities (i.e., threads) do you need? Think about which inputs
the system should handle, and how it should handle them.
• Is there any thread that is more time-critical than the rest (and should be given a
higher priority)?
• Is it appropriate to introduce more threads to accomplish a clearer and more understandable design?
• Will the CMLA requirements be easy to verify (by quickly inspecting the code) in
your implementation?
• Which threads need to communicate? Draw a simple diagram to show your design.
What information (which classes) should be communicated?
Mailboxes should be used to send events for thread synchronization and communication.
Specification
The machine shall have three washing programs with the following behavior:
Program 1 Color wash: Lock the hatch, let water into the machine, heat to 60¶ C, keep
the temperature for 30 minutes, drain, rinse 5 times 2 minutes in cold water, centrifuge for 5 minutes and unlock the hatch.
Program 2 White wash: Like program 1, but with a 15 minute pre-wash in 40¶ C. The
main wash should be performed in 90¶ C.
Program 3 Draining: Turn off heating and rotation. After pumping out the water (if
any), unlock the hatch. Note: the user should select this program as soon as possible
after 0 (stop).
In addition, the machine shall have a special program for immediately stopping it:
Program 0 Stop: All motors, as well as any filling/draining of water, should be turned
off immediately.
The main difference between 3 and 0 is that 0 can used as an emergency stop. Program 3
can be used to end a washing after interrupting it (with 0) or after a power failure. The
program selector should require the user to always stop the machine (i.e., press 0) before
switching from one program to another.
Additional requirements
• The temperature must not exceed the ones stated above (60, 40, and 90¶ C) but may
sporadically drop down to 2¶ C below.
• An electromechanical relay controls the power to the heater. To avoid wearing out
the relay, it should not be switched on/off too often.
• While washing, the barrel should alternate between left and right rotation. The
direction should be changed once every minute.
44
Exercises and Labs
Requirements for CMLA certification
To market the washing machine in the EU, the control software must be reviewed and
certified by a special committee, CMLA (Comité de Machines à Laver Automatiques), in
Brussels. The special requirements from CMLA are listed below. Since the review is a
costly and time-consuming process, it is very important that the software is written in a
way that allows the CMLA requirements to be verified easily. In other words, it should be
easy to convince oneself that the requirements are fulfilled by simply inspecting the code.
CMLA states the following requirements, motivated by environmental and safety reasons, for a washing machine to be certified:
1. The drain pump must not be running while the input valve is open.
2. The machine must not be heated while it is free of water.
3. There must not be any water in the machine when the hatch is unlocked.
4. Centrifuging must not be performed when there is any measurable amounts of water
in the machine.
Handout code
The hardware for the new washing machine is developed in parallel with the control software. To make it possible to test the control software early (and save some water), a
software simulation of a washing machine has been developed. The simulator is available
in the done folder of the handout code. Your control software should be implemented in
the todo folder.
Hardware access interface
The abstract class AbstractWashingMachine describes the properties of a washing machine
and provides operations for manipulating the (possibly simulated) hardware. Your control
software will only communicate with the AbstractWashingMachine class, not the concrete
subclasses implementing the actual hardware interface and the simulation.
45
Multi-Threaded Programming in Java
package done;
/**
* Abstract description of a washing machine . Specialized
* into simulations and actual hardware implementations .
*/
public abstract class AbstractWashingMachine {
/**
* Read the water temperature .
* @return Temperature in Centigrades (0 -100).
*/
public abstract double getTemperature ();
/**
* Read the water level in the machine .
* @return A real number between 0 and 1, where 1 indicates an
*
absolutely full (i.e. overflowing ) machine and 0
*
indicates a ( practically ) empty one.
*/
public abstract double getWaterLevel ();
/**
* Check if the front door is open.
* @return True if the door is locked , false if it is open.
*/
public abstract boolean isLocked ();
/**
* Turns the heating on/off.
* @param on True means "heat on", false means "heat off ".
*/
public abstract void setHeating ( boolean on);
/**
* Open/close the water input tap.
* @param on True means "open tap", false means "close tap ".
*/
public abstract void setFill ( boolean on);
/**
* Start /stop the water drain pump.
* @param on True means "start pump", false means "stop pump ".
*/
public abstract void setDrain ( boolean on);
/**
* Lock/ unlock the front door.
* @param on True means "lock door", false means " unlock door ".
*/
public abstract void setLock ( boolean on);
/**
* Control the turning motor.
* @param direction SPIN_OFF , SPIN_LEFT , SPIN_RIGHT , or SPIN_FAST .
*/
public abstract void setSpin (int direction );
public abstract void start ();
/**
* Set button listener . The listener ’s processButton () method will be
* called whenever a button is pressed .
*/
abstract void setButtonListener ( ButtonListener l);
/**
* Stop spin.
*/
public static final int SPIN_OFF
/**
46
= 0;
Exercises and Labs
* Slow left spin.
*/
public static final int SPIN_LEFT
= 1;
/**
* Slow right spin.
*/
public static final int SPIN_RIGHT = 2;
/**
* Fast left spin.
*/
public static final int SPIN_FAST
= 3;
};
Simulation startup excerpt
The simulator main method is located in the Wash class. The simulator basically instantiates a simulation object, registers a ButtonListener that calls the WashingController upon
keypresses, and starts a simulation thread.
package done;
import todo. WashingController ;
public class Wash {
public static void main( String [] args)
// ...
// Create a washing machine simulation and a controller
AbstractWashingMachine theMachine
= new WashingMachineSimulation (theSpeed , freakShowProbability );
// ...
theMachine . setButtonListener (new WashingController (theMachine , theSpeed ));
theMachine .start ();
// ...
}
}
WashingController
The WashingController is implemented by you in the todo folder. Note that a reference to
the hardware access interface is provided for you in the WashingController constructor.
package todo;
import se.lth.cs. realtime .*;
import se.lth.cs. realtime . event .*;
import done .*;
public class WashingController implements ButtonListener {
public WashingController ( AbstractWashingMachine theMachine , double theSpeed ) {
// Create and start your controller threads here
}
public
//
//
//
}
void processButton (int theButton ) {
Handle button presses (0, 1, 2, or 3). A button press
corresponds to starting a new washing program. What should
happen if there is already a running washing program?
}
Washing program
Each washing program is implemented as a transactional thread, i.e. the thread starts up,
accomplishes its task, and dies when done. The WashingProgram class acts as a superclass
47
Multi-Threaded Programming in Java
to your washing programs and handles InterruptedException so you do not need to. It
also stores references to your controllers (temp, water, spin) so you can access them as
myXController in your washing program subclasses. The washing program is implemented
in the abstract method wash called from the run method.
public abstract class WashingProgram extends RTThread {
/**
* @param
mach
The washing machine to control
* @param
speed
Simulation speed
* @param
tempController
The TemperatureController to use
* @param
waterController The WaterController to use
* @param
spinController
The SpinController to use
*/
protected WashingProgram ( AbstractWashingMachine mach ,
double speed ,
TemperatureController tempController ,
WaterController waterController ,
SpinController spinController ) {
super ();
myMachine
mySpeed
myTempController
myWaterController
mySpinController
=
=
=
=
=
mach;
speed;
tempController ;
waterController ;
spinController ;
}
/**
* This run () method does two things .
* <OL >
* <LI >Call the wash () method implemented in the subclass .
* <LI >If wash () was interrupted , turn all off machinery .
* </OL >
*/
public void run () {
boolean wasInterrupted = false;
try {
wash ();
}
catch ( InterruptedException e) {
wasInterrupted = true;
}
catch( RTInterrupted e) {
// Thrown by semaphores
wasInterrupted = true;
}
if ( wasInterrupted ) {
System .out. println (" Washing program aborted .");
myTempController . putEvent (
new TemperatureEvent (this , TemperatureEvent .TEMP_IDLE , 0.0));
myWaterController . putEvent (
new WaterEvent (this , WaterEvent .WATER_IDLE , 0.0));
mySpinController . putEvent (
new SpinEvent (this , SpinEvent . SPIN_OFF ));
}
}
/**
* Called by run () to perform the actual washing stuff.
* Should be implemented by the subclass . Does not need to
* catch InterruptedException .
*/
abstract protected void wash () throws InterruptedException ;
/**
* The machine to regulate
*/
protected AbstractWashingMachine myMachine ;
/**
48
Exercises and Labs
* Simulation speed
*/
protected double mySpeed ;
/**
* The temperature controller
*/
protected TemperatureController myTempController ;
/**
* The water controller
*/
protected WaterController myWaterController ;
/**
* The spin controller
*/
protected SpinController mySpinController ;
}
WashingProgram3
The WashingProgram3 class is an example of a washing program implemented for the
washing machine.
package todo;
import done .*;
/**
* Program 3 of washing machine . Does the following :
* <UL >
*
<LI > Switches off heating
*
<LI > Switches off spin
*
<LI >Pumps out water
*
<LI > Unlocks the hatch.
* </UL >
*/
class WashingProgram3 extends WashingProgram {
/**
* @param
mach
The washing machine to control
* @param
speed
Simulation speed
* @param
tempController
The TemperatureController to use
* @param
waterController The WaterController to use
* @param
spinController
The SpinController to use
*/
public WashingProgram3 ( AbstractWashingMachine mach ,
double speed ,
TemperatureController tempController ,
WaterController waterController ,
SpinController spinController ) {
super(mach , speed , tempController , waterController , spinController );
}
/**
* This method contains the actual code for the washing program . Executed
* when the start () method is called .
*/
protected void wash () throws InterruptedException {
// Switch of temp regulation
myTempController . putEvent (new TemperatureEvent (this ,
TemperatureEvent .TEMP_IDLE ,
0.0));
// Switch off spin
mySpinController . putEvent (new SpinEvent (this , SpinEvent . SPIN_OFF ));
49
Multi-Threaded Programming in Java
// Drain
myWaterController . putEvent (new WaterEvent (this ,
WaterEvent . WATER_DRAIN ,
0.0));
mailbox . doFetch (); // Wait for Ack
// Set water regulation to idle => drain pump stops
myWaterController . putEvent (new WaterEvent (this ,
WaterEvent .WATER_IDLE ,
0.0));
// Unlock
myMachine . setLock (false );
}
}
Example controller
All controllers are be implemented as periodic threads. Note the usage of the simulation
speed parameter to adjust the period. The perform method will be called periodically. It
is important that you do not implement any lengthy actions or block/sleep in this method.
public class WaterController extends PeriodicThread {
// TODO: add suitable attributes
public WaterController ( AbstractWashingMachine mach , double speed) {
super (( long) (3000/ speed )); // TODO: replace with suitable period
}
public void perform () {
// TODO: check if there are any messages in the mailbox ( tryFetch ).
// Take action depending on the last received message .
}
}
Messages
The washing program communicates with the controllers through messages. Subclasses of
the main message (RTEvent) class suitable for the washing mashine are available in the
todo folder.
/**
* This event is sent by the temperature and water level control
* processes to the washing programs . Indicates that the previous order
* has been carried out.
*/
public class AckEvent extends RTEvent {
public AckEvent ( Object source ) { ... }
}
/**
* This event is sent by washing program processes to the water level
* controller process . It is an order to reach and hold a given level.
*/
public class WaterEvent extends RTEvent {
/**
* @param
mode
Regulation mode (WATER_IDLE , WATER_FILL , WATER_DRAIN )
* @param
target
Water level to reach and hold
*/
public WaterEvent ( Object source , int mode , double level) { ... }
/**
* @return Water regulation mode (WATER_IDLE , WATER_FILL , WATER_DRAIN )
*/
public int getMode () { ... }
50
Exercises and Labs
/**
* @return Target level
*/
public double getLevel () { ... }
/** Regulation off , turn off all pumps */
public static final int WATER_IDLE = 0;
/** Fill water to a given level */
public static final int WATER_FILL
= 1;
/** Drain , leave drain pump running when finished */
public static final int WATER_DRAIN = 2;
}
/**
* This event is sent by washing program processes to the temperature
* controller process . It is an order to reach and hold a given
* temperature .
*/
public class TemperatureEvent extends RTEvent {
/**
* @param
mode
Temperature regulation mode (TEMP_IDLE , TEMP_SET )
* @param
target
Target temperature to reach and hold
*/
public TemperatureEvent ( Object source , int mode , double temp) { ... }
/**
* @return Temperature regulation mode
*/
public int getMode () { ... }
/**
* @return Target temperature
*/
public double getTemperature () { ... }
/** Temperature regulation off (no heating ) */
public static final int TEMP_IDLE = 0;
/** Reach and hold the given temperature */
public static final int TEMP_SET
= 1;
}
/**
* This event is sent by washing program processes to the spin
* controller process . It is an order to set a particular spin.
*/
public class SpinEvent extends RTEvent {
/**
* @param
mode
Spin regulation mode (SPIN_OFF , SPIN_SLOW , SPIN_FAST )
*/
public SpinEvent ( Object source , int mode) { ... }
/**
* @return Spin regulation mode (SPIN_OFF , SPIN_SLOW , or SPIN_FAST )
*/
public int getMode () { ... }
public static final int SPIN_OFF = 0;
public static final int SPIN_SLOW = 1;
public static final int SPIN_FAST = 2;
}
Terminating washing programs from WashingController
When the user presses button 0, the current washing program should be terminated. You
can do this by calling the interrupt() method on that washing program. This method will,
51
Multi-Threaded Programming in Java
in turn, result in an InterruptedException being thrown in your washing program.
Allowing your washing program to be terminated
Your washing program may be terminated at any point. This will result in an InterruptedException being thrown from, for example, a waitEvent call to the event queue in your
washing program. You should not catch the InterruptedException in your washing programs. Instead, use the WashingProgram class as a superclass and write your washing
program in the wash() method. That method propagates the InterruptedException to the
run() method of the WashingProgram superclass, which handles that exception. InterruptedException may be thrown in a few other situations, as you may know, such as sleep calls.
You should handle these the same way, that is, not at all.
Checklist for self- and peer assessment of your design
You should be able to answer the following questions with yes before asking your teacher
for approval of your completed system design:
• Does your design contain the correct number of (periodic) controller thread classes?
• Are all washing programs planned for in respective (transactional) thread classes?
• Is the only way of communication between threads handled through event / message
passing?
• Are all messages / message types passed between the correct threads according to
the specification and task description?
Once you assume all questions positively answered for your own design, hand it over
to your partner group for cross checking. Do the same check for the other group’s design.
After getting a confirmation for the checklist, show your solution to the teacher. All
students in your group need to be able to explain the design for approval!
52
Multi-Threaded Programming in Java
Laboratory session - programming
You will implement the control system for the washing machine, prepared in exercise 5.
Programming advice
It is generally a good idea to start programming before the lab occasion. The handout
code is available on the course homepage as a zipped Eclipse workspace (it is part of the
same zip you downloaded for lab 1). Before you start programming you need to have your
completed design of the system approved by your teacher. If you do not have this approval,
start over with the preparation exercise!
The todo folder contains skeletons for most of the classes that you need to implement.
Technical data
The simulation is based on the following data:
Volume:
Power:
Water input flow:
Water output flow:
Rotation speed:
Recommended temperature for heating on:
Recommended temperature for heating off:
54
20 l (filled up to 10 l)
2 kW
0.1 l/s
0.2 l/s
15 rpm (slow), 800 rpm (fast)
temp < target temp - 1.8¶ C
temp > target temp - 1.2¶ C
Exercises and Labs
A complete wash typically takes 1h - 2h to complete. To facilitate testing the simulation
has a speed parameter which can be used to speed up the simulation. Speed=1 corresponds
to actual time, and e.g. speed=10 makes the simulation go 10 times as fast. Although the
prewritten simulation software takes the speed parameter into account, you still have to
use it yourself in some parts of your code. For instance, the washing times (15, 30, and 45
minutes) must be scaled in the control software to get a consistent simulation.
Checklist and hints for self- and peer assessment (and correction) of the implementation
You should be able to answer / confirm the following questions / statements with yes
before asking your teacher for approval of your program:
• Is the washing machine working according to CMLA criteria?
• Are all three (washing) programs correctly implemented (check against the specification)?
• Is the procedure for aborting a program and “resetting” the machine implemented
exactly as described?
• There are no semaphores or monitors used for thread communication, only mailboxes
/ messages (RTEvents).
• The CPU is not unnecessarily used.
A few hints on where to look for the cause of classic issues:
• The machine burns up or you get “the fish” – there is some race condition, review
your implementation of the periodic checks for new messages vs continued handling
of old, but still valid, messages in the controller threads for temperature and water
level; review also the handling of AckEvents sent back to the original sender of control
messages.
• Somehow nothing is happening – make sure your threads are started correctly and
you have implemented the correct performing methods (perform vs run, check the
description of the RTThread / JThread / PeriodicThread classes in the booklet).
• You get an OwnerError – The OwnerError is thrown when a putEvent (or similar) is
called within anRTThread object using a different thread than the one associated with
the object. Typically you get this error when starting washing programs using program.wash() instead of program.start() within WashingController.processButton(),
i.e., you let the simulation thread run the washing program instead of starting a new
washing program thread.
In case you get stuck beyond the hints given above, consult with your partner group
first, then turn to the lab assistant or teacher for help.
Once you assume all questions positively answered for your own implementation, hand it
over to your partner group for cross checking. Do the same check for the other group’s
implementation. After getting a confirmation for the checklist, show your program to the
teacher. All students in your group need to be able to explain the program for approval!
55
Was this manual useful for you? yes no
Thank you for your participation!

* Your assessment is very important for improving the work of artificial intelligence, which forms the content of this project

Download PDF

advertising