Real-time Driver
Volume Number: 5
Issue Number: 10
Column Tag: Assembly Lab
Related Info: Serial Drivers File Mgr (PBxxx) Event Manager
Time Manager
Real-Time Driver
By Jeff E. Mandel, MD MS, New Orleans, LA
A Real-Time Device Driver in MPW Asm
When working in the laboratory or in engineering, it is often necessary to use
the Mac to control serial devices. Such devices are generally configured to respond to
simple commands, and provide a simple response. An example would be the American
Edwards AccuPro™ Volumetric Infusion Pump, which is a device for delivering
intravenous infusions of drugs. This device contains an RS-232 interface, supports
full duplex 2400 baud communication, and has a simple command language for setting
and interrogating the device’s infusion rate, the limits for infused volume and infusion
time, the volume already infused, and the status of the pump.
Programming the pump involves four steps; the command string is built in
memory, a pointer to this string is placed in a parameter block for a _PBWrite, a
_PBRead is used to obtain the pump’s response, and the returned string is decoded.
While this may seem simple, one must remember that the serial communication takes
a significant amount of time, and could take forever if the pump or the serial line fails.
Additionally, the serial communications controller is capable of functioning with
minimal CPU supervision, which transpires at interrupt level, and thus, it would be
nice to use asynchronous device driver calls, to free the Mac to work on keeping the
user interface going, while the serial controller handles the IO in the background.
The program I will describe for performing these tasks is a driver. Most Mac
programmers are familiar with drivers from writing DAs, however, a device driver is
somewhat of a different animal, particularly when one wishes it to be “real-time”
without intervention from the foreground program. The device driver has several
purposes:
1) To insulate the application from the peculiarities of the device, so that the device
can be changed without requiring a change in the application. Additionally, the
device could be simulated by a driver, so that debugging of application code can be
done without having to have the physical device.
2) To insulate the application programmer from having to understand how serial
communications, real-time IO, etc. work.
3) To permit all of the resources associated with the IO task to be grouped together,
so that they can be installed and uninstalled easily.
In writing such a driver, it is important to recall several important factors:
1) Drivers cannot utilize application globals for their own storage.
2) Drivers are only notified of events that pertain to them when they own the
frontmost window, and then only receive mouse, keyboard, update, and activate
events.
3) Activities which occur at interrupt level (i.e. ioCompletion routines, Vertical
retrace tasks, Time manager tasks, etc.) are extremely limited in what they can
do, due to the uncertainty of the heap.
In order to write such a driver, several decisions were made:
1) The driver utilizes app1Evts to signal that it needed to regain control. Thus, the
serial reads and writes utilize an ioCompletion routine which simply posts an
app1Evt.
2) Serial driver calls have a time limit. When the serial call is queued
(asynchronously), a Time manager task is primed. If the serial IO completed
first, it stops the Time manager task from completing by setting the tmCount
field to zero, and if the read or write did not complete within the specified time,
the time manager task issues a _KillIO call on the relevant serial driver. This
results in the ioCompletion routine being called, which notifies the driver. The
time manager task is contained in a resource of type ‘TMMR’, which is loaded into
the heap, locked, dereferenced, and the pointer placed in the tmAddr field of the
time manager queue entry. The resource also contains a longword of private
storage, which holds a pointer to a private parameter block (used for the KillIO
call).
3) App1evts are posted with the parameter block pointer of the completed serial call
as the message. The pump driver places the parameter block pointer of the
pending pump driver in the ioMisc field of the serial call parameter block so the
downstream routines can keep track of it. Alternatively, the downstream routines
could get this pointer from the dCtlQHead field of the DCE.
4) App1Evts are passed to the driver by a GetNextEvent filter. This routine is called
at the end of the _GetNextEvent trap, with A1 pointing to the EventRecord, and
boolean result in both D0 and at 4(A7) (See Macintosh Technical Note #85). If
the what field of the EventRecord equals app1Evt, the routine examines the
message, and if it contains a negative word in the ioRefNum field of the parameter
block pointed to by the message, it processes the event. If the event is processed,
the filter sets the boolean result to False, so the the application knows not to deal
with it. In either case, the routine exits by a JMP to the previous contents of the
JGNEFilter global. This pointer is stored locally in our GNEFilter proc.
5) The GNEFilter is a separate resource (type = ‘GNEF’), which is loaded in the
pump driver Open routine. The resource is patterned after the DRVR resource,
in that it contains an offset to the code as its first word, and some local storage is
provided between this word and the beginning of the code. The GNEFilter is loaded
into the heap during the driver Open routine, using a _GetNamedResource call.
This is done so that several drivers can share the GNEFilter, since only the first
driver will load the resource into the heap. The GNEFilter keeps track of which
resources have opened it by keeping their reference numbers in the local storage.
Duplicate entries are avoided. The GNEFilter also keeps a parameter block
pointer in its private storage for its private use.
6) When the GNEFilter processes an app1Evt with a negative ioRefNum, it accesses
the parameter block pointer in the ioMisc field of the parameter block referenced
in the message field of the event, and checks to see that the ioRefNum of this PB is
in the list of cooperating drivers in the GNEFilter private storage. If it is, then
we place the event pointer in the csParam field of the GNEFilter’s private
parameter block, set the csCode to accEvent, and the ioRefNum to reference
number of the ioMisc parameter block (this will be the ioRefNum of our driver;
the ioRefNum of the parameter block passed in the message field will be one of the
serial drivers). We then issue an immediate _Control call.
7) The Control routine supports four csCodes - accEvent, accRun, KillIO, and
GoodBye. Goodbye simply JMPs to the Close routine. KillIO issues KillIO calls on
the serial drivers and returns. AccRun asynchronously queues a Status call on
the driver to inquire the pump status (thus, irrespective of what the application
does, it will be notified of the pump status periodically). The accEvent csCode is
generated by our GNEFilter, and is used to allow the driver to respond to serial IO
completion at event level (that is, when the heap is consistent). The routine
examines the low nibble of the ioTrap field of the parameter block pointed to by
the event message. If the trap was _Write, the routine sets up the parameter
block for single character reads on the serial input channel and queues an
asynchronous _Read. If the trap was _Read, the routine examines the character
read. If the character is a carriage return (ASCII 13), the accumulated input
buffer is sent to be digested, if it is an asterisk (*), it is ignored (the McGaw
pump generates these periodically to let us know it is pumping), and if it is any
other character, it is appended to the input buffer. In the latter two cases, the
routine queues another asynchronous _Read. In the first case, the routine posts
an app2Evt with the message the pointer to the original parameter block used to
queue the status call, and exits via JIODone.
8) The Status routine uses the three words in the csParam field of the parameter
block to figure out what the application wants the driver to send to the pump. The
Request field is used to look up a single character in a table (which is loaded from
a resource of type ‘PDDF’). This character specifies which of the pump
functions is to be interrogated or set, as specified in the Action field. The Info
field contains the numeric value to be passed to the pump and/or returned to the
application. The pump in general wants decimal integers, but in some cases
wants a hex word, and the formatting information is specified in the table.
Having constructed the string to be sent to the pump, the routine allocates a
parameter block, places the string pointer in the ioBuffer field, the pointer to
the driver Status parameter block in the ioMisc field, fills in the ioCompletion
address, and queues an asynchronous _Write. Note that if the noQueueBit of the
trap is set, the Status routine places the request at the head of the queue. It does
this by checking the queue, and if there are zero or one queue entries, issuing the
_Status call asynchronously, but if there are two or more queue entries, it slips
the request after the current queue head by changing the qLink fields of the qHead
PB and the PB in question.
9) The Open routine loads the GNEFilter and time manager task (as detailed above),
opens the serial drivers and configures them for the pump, loads the pump
request table, allocates the dCtlStorage handle, and sets up the driver globals
there.
10) The Close routine removes the time manager task, closes the serial ports,
removes the driver’s reference number from the GNEFilter private storage, and
restores the previous GNEFilter if it is the last value there. It then deallocates
all the pointers and handles it allocated and exits.
The application thus needs only do the following things to utilize the driver:
1) Open the driver
2) Allocate a pointer for the parameter block, setting the three words in the
csParam field to pass the desired function, and queue the _Control call. The call
should be made asynchronously. Immediate calls can be used to “jump the line”,
that is, make sure the call is the next one to be taken from the queue.
3) The event loop should handle app2Evts by first processing the information in the
ioResult and csParam fields, then disposing of the pointer.
4) If the pump driver is to function irrespective of what the application is doing,
the application must frequently call _GetNextEvent with the event mask app1Evt
mask set. In order to guarantee this you will need a FilterProc for ModalDialogs
and Alerts which calls _GetNextEvent with the event mask set to app1Mask when
the routine receives a null event, and a DragHook and MenuHook which calls
_GetNextEvent with the event mask set to app1Mask. Additionally, any
compute-intensive routines might include a call to the DragHook routine. The
alternative is to keep track of driver calls and repost the ones that time out.
5) Call _SystemTask if you want periodic events.
6) Prior to closing the driver, you should do one of two things:
a) Issue a _KillIO call on the driver to flush the queue.
b) Wait until the queue empties itself. This can be done by waiting until the
dCtlQHead field of the driver’s DCE is zero.
This is necessary because the _Close trap sits and waits for the driver to
complete the pending request. The driver cannot complete the request, however,
without the event loop, so we hang forever.
7) While the driver is set up to handle goodbye kisses to close the structures, it is
much safer to close the driver explicitly, due to the serious adverse consequences
of exiting without restoring the JGNEFilter pointer. The truly paranoid can load
the GNEFilter into the system heap. The same caveat applies to the time manager
queue entry (the pointer, not the routine) - if this is deallocated but not removed
from the time manager queue, bad stuff will happen. I have not extensively
worked on making the driver “safe as milk”, in general, during debugging, if it
crashed, I rebooted. But then, I just got my Mac II.
8) The program is written in MPW assembler, and uses the structured
programming macros. I have hacked up some of these to make them work
properly for writing drivers. The only significant change is in DRVRExit, which
checks the noQueueBit of the argument, and if it is clear, exits via the JIODone
vector, otherwise, RTS.
The code for the driver, the GNEFilter, and the timer task, as well as the rez files
and the shell commands to build the driver are presented below. Note that I actually
build the driver as a desk accessory. This is done so that I can install it with the DA
Mover. This is easier during development, but once the driver is debugged, it can be
changed with the resource editor.
The sources have been hacked for the sake of brevity. All INCLUDES were deleted,
many equates omitted, and code specific to the pump deleted as well. If you really want
to assemble this, get the source disk.
TITLE ‘Pump driver’
ParamBlockSize equ 108
ActionOffset equ csParam
RequestOffset equ csParam+2
InfoOffset equ csParam+4
EnabledFlags equ (1<
+ (1<
EventMask equ 1<
DStore Record 0
WriteUnit DS.W 1
ReadUnit DS.W 1
TimeCount DS.L 1
KillBlock DS.L 1
KillTask DS.L 1
IncomingLength DS.B 1
IncomingString DS.B 9
Align 2
TableOffset equ *
TableLen DS.W 1
Table DS.W 5
ENDR
IOString Record 0
OutgoingString DS.B 8
ReadBuffer DS.B 1
Align 2
StringAllocation equ *
ENDR
DRVRStart DRVREntry
DRVRBegin Save=A2-A4/D1-D2,\ with=(DStore,IOString,GNEGlobals);
DC.B EnabledFlags
DC.B 0
DC.W 7*60 ; 7 seconds
DC.W EventMask
DC.W 0 ; No menu
DC.W DRVROpen
DC.W DRVRPrime
DC.W DRVRControl
DC.W DRVRStatus
DC.W DRVRClose
DRVRTitle
DC.B ‘PumpDriver’
ALIGN 2
DRVROpen DRVREnter
MOVE.L A1,A2
* Load the pump request table from the
* resource fork
Call _GetNamedResource:L (#’PDDF’:L, #’Table’:A ),A4:L
EXG A0,A4
_HLock
_GetHandleSize
If# D0 LT.L #0 Then.S
MOVE.W #openErr,ioResult(A4)
Return
EndIf#
EXG A0,A4
MOVE.L D0,D1
MOVE.L A0,-(SP)
* Get a new handle to put the Driver
* globals and the pump request table into