TweetFollow Us on Twitter

Jun 98 Tips

Volume Number: 14 (1998)
Issue Number: 6
Column Tag: Tips & Tidbits

June 1998 Tips & Tidbits

by Steve Sisak

Over the past few months we've had a few tips submitted on how to open a serial port or detect if it is in use. Unfortunately, we haven't received one that was sufficiently correct or complete to publish as a winner. Since this seems like an interesting topic (and one that lots of people get wrong), I'm going to try a new format: a terse mini-article with enough information to get you started and pointers to more information.

If you like this format, have a good idea for a topic but don't know the answer, or have other ideas how to make this space more useful, please send mail to tips@mactech.com. I'll be glad to pay the standard reward and give you credit for a really good question (assuming I can find the answer and it's generally useful).

Serial Port TidBits

If you've ever tried to write an application which uses the serial port on a Macintosh, you've probably discovered that (1) it didn't work on the first try, (2) the information on what to do was scattered all over the place and (3) it still didn't work in all cases.

In case you haven't, the information for how to correctly open and use the serial drivers is scattered across Inside Macintosh, the Communication Toolbox documentation, the ARA SDK and various tech notes. There are also several misleading and obsolete descriptions in Inside Macintosh Vols. I-VI.

The most authoritative sources are Inside Macintosh: Devices and Tech note 1119, by Quinn (The Eskimo!) which pulls most of the relevant information together in one place.

Listing the Serial Ports

In the beginning, every Macintosh had exactly 2 serial ports named "Modem Port" and "Printer Port" and the names of their drivers were hard coded -- these days PowerBooks often have only one port and/or a built-in modem, NuBus and PCI cards make it possible for the user to add ports, and software creates "virtual" ports to make it possible for multiple programs to share the same physical port.

To determine how many ports a machine has and what their human-readable name are, you need to use the Communications Resource Manager (CRM), which is part of the Communications Toolbox (one of those managers that Apple has declared obsolete, but hasn't gotten around to replacing yet).

For each port, the CRM maintains a CRMSerialRecord containing the following information:

typedef struct CRMSerialRecord {
  short         version;
  StringHandle   inputDriverName;
  StringHandle   outputDriverName;
  StringHandle   name;
  CRMIconHandle  deviceIcon;
  long           ratedSpeed;
  long           maxSpeed;
  long           reserved;
} CRMSerialRecord, *CRMSerialPtr;

To iterate over the available ports, you use the function CRMSearch(). The following code fragment finds a port by name -- you can easily adapt it to build a menu, etc.:

CRMSerialPtr FindPortInfo(ConstStr255Param name)
{
  CRMRec      crmRec;
  CRMRecPtr    crm   = &crmRec;

  // Get the search started
  crmRec.crmDeviceType = crmSerialDevice;  crmRec.crmDeviceID   = 0;

  while ((crm = CRMSearch(crm)) != nil)
  {
    CRMSerialPtr portInfo = 
      (CRMSerialPtr) crm->crmAttributes;
    
    if (EqualString(*portInfo->name, name, false, true))
    {
      return portInfo;
    }
  }
  
  return nil;
}

Opening, Initializing and Closing a Serial port

There is a specific sequence of calls you must use to open, configure and close a serial port. It is listed in Inside Macintosh: Devices on page 7-11. If you do not make the calls in this order, strange things will happen.

The sequence is:

  1. Open the output driver, then the input driver; always open both.
  2. (optional) allocate a buffer larger than the default 64-byte buffer and call SerSetBuf.
  3. Set the handshaking mode.
  4. Set the baud rate and data format.
  5. Read and/or write the desired data.
  6. Call KillIO on both drivers to terminate any pending IO.
  7. Restore the default input buffers.
  8. Close the input driver, then the output driver.

Determining If a Serial Driver is Open

Determining if a serial driver is open in use is a little bit tricky and a lot of software gets it wrong. The problem is twofold: first, OpenDriver() doesn't bother to check if a driver is already open -- it just returns noErr and the reference number of the already-open driver. If you use it (or worse, close it when you're done) Bad Things(tm) will happen.

To get around this you must walk the device list in low memory to see if a driver is already open before trying to open it again.

The following routine finds the index of a driver in the unit table (or -1 if it doesn't exist):

short FindDriverIndex(ConstStr255Param name)
{
  StringPtr    driverName;
  short      index;
  AuxDCEHandle  entry;
  AuxDCEHandle*  table = (AuxDCEHandle*) LMGetUTableBase();
  short      count = LMGetUnitNtryCount();
  
  for (index = 0; index < count; index++)
  {
    if ((entry = table[index]) != nil)
    {
      if ((**entry).dCtlFlags & dRAMBasedMask)
      {
        driverName = (**((DRVRHeaderHandle)((**entry).dCtlDriver))).drvrName;
      }
      else
      {
        driverName = (*((DRVRHeaderPtr)((**entry).dCtlDriver))).drvrName;
      }
      
      if (EqualString(driverName, name, false, true))
      {
        return index;
      }
    }
  }
  
  return -1;
}

To check if a port is open, we can write:

Boolean  IsDriverOpen(ConstStr255Param name)
{
  short index = FindDriverIndex(name);
  
  if (index >= 0)
  {
    AuxDCEHandle dce = 
      ((AuxDCEHandle*) LMGetUTableBase())[index];
    
    if ((**dce).dCtlFlags & dOpenedMask)
    {
      return true;
    }
  }
  
  return false;
}

NOTE: LMGetUTableBase() is missing from some versions of the Universal Headers you may have to implement it yourself (or use newer headers).

Now for the second half of the problem -- the Serial Port Arbitrator, included with the Appletalk Remote Access server and other software allows a port to be opened "passively" meaning that a server may have a the port open to look for an incoming call, but will relinquish it if another application wants to use it.

In this case OpenDriver will return portInUse (-97) if the driver is open or noErr if it is not. (in either case, it will return a valid refNum). However, software which walks the device table will incorrectly think that the driver is open and report an error.

The correct procedure here is to use Gestalt to determine if the Serial Port Arbitrator is present and, if it is, then just call OpenDriver(), otherwise, walk the Unit Table:

Boolean  HaveSerialPortArbitration(void)
{
  long  result;
  OSErr  err;
  
  err = Gestalt(gestaltArbitorAttr, &result);
  
  return (err == noErr) && (result & (1 << gestaltSerialArbitrationExists));
}

OSErr OpenSerialDriver(ConstStr255Param name, short* refNum)
{
  if (!HaveSerialPortArbitration())
  {
    short index = FindDriverIndex(name);

    if (index >= 0)  // Driver is already open
    {
      *refNum = ~index;
      return portInUse;
    }
  }
  
  return OpenDriver(name, refNum);
}

Reading from a Serial Port

You can read from a serial port just like a file by using PBRead or FSRead, however you can't seek and if you try to read more bytes are actually available, you will hang the machine in SyncWait() until the number of bytes you requested is actually available.

To avoid this, you can make a status call to the input driver with csCode = 2 to find out how many bytes are available in the drivers buffer and then only request that many bytes.

Correction to May Tip -- Wrapper for ParamText

The tip "Wrapper for ParamText" incorrectly states that one cannot pass nil arguments to ParamText(). In fact, ParamText() has always accepted nil arguments, and leaves the corresponding parameters unchanged.

I use this feature frequently in order to conserve stack space. I can set all 4 parameters using only one Str255, as long as I do it one at a time.

Actually, this example only sets 3 params:

  void
ReportError( short doingIx, const char *what )
{
Str255          str;

  if( spareMem )
    DisposeHandle( spareMem );
  spareMem = NULL;

  CtoPstrcpy( str, (const unsigned char *)what, sizeof str );
  ParamText( str, NULL, NULL, NULL );

  GetErrString( doingIx, str );
  ParamText( NULL, str, NULL, NULL );

  /* Eww. But I don't have to ParamText menu item text every command,
    which might slow things down if we're being scripted.
  */

  if( doingIx == doingMenuCmd ) {
    str[0] = 0;
  if( tg.doingItem )
      GetID( tg.doingItem, str );
    ParamText( NULL, NULL, NULL, str );
  }

  else if( doingIx == doingMenuAct ) {
    str[0] = 0;
    if( tg.doingItem && tg.doingMenu )
    GetMenuItemText( GetMenu(tg.doingMenu), tg.doingItem, str );
    ParamText( NULL, NULL, NULL, str );
  }

  VerifyAlert( 144 );
  InitCursor();
  StopAlert( 144, DefaultFilter );
}

Tony Nelson
tonyn@tiac.net

 

Community Search:
MacTech Search:

Software Updates via MacUpdate

Latest Forum Discussions

See All

Tokkun Studio unveils alpha trailer for...
We are back on the MMORPG news train, and this time it comes from the sort of international developers Tokkun Studio. They are based in France and Japan, so it counts. Anyway, semantics aside, they have released an alpha trailer for the upcoming... | Read more »
Win a host of exclusive in-game Honor of...
To celebrate its latest Jujutsu Kaisen crossover event, Honor of Kings is offering a bounty of login and achievement rewards kicking off the holiday season early. [Read more] | Read more »
Miraibo GO comes out swinging hard as it...
Having just launched what feels like yesterday, Dreamcube Studio is wasting no time adding events to their open-world survival Miraibo GO. Abyssal Souls arrives relatively in time for the spooky season and brings with it horrifying new partners to... | Read more »
Ditch the heavy binders and high price t...
As fun as the real-world equivalent and the very old Game Boy version are, the Pokemon Trading Card games have historically been received poorly on mobile. It is a very strange and confusing trend, but one that The Pokemon Company is determined to... | Read more »
Peace amongst mobile gamers is now shatt...
Some of the crazy folk tales from gaming have undoubtedly come from the EVE universe. Stories of spying, betrayal, and epic battles have entered history, and now the franchise expands as CCP Games launches EVE Galaxy Conquest, a free-to-play 4x... | Read more »
Lord of Nazarick, the turn-based RPG bas...
Crunchyroll and A PLUS JAPAN have just confirmed that Lord of Nazarick, their turn-based RPG based on the popular OVERLORD anime, is now available for iOS and Android. Starting today at 2PM CET, fans can download the game from Google Play and the... | Read more »
Digital Extremes' recent Devstream...
If you are anything like me you are impatiently waiting for Warframe: 1999 whilst simultaneously cursing the fact Excalibur Prime is permanently Vault locked. To keep us fed during our wait, Digital Extremes hosted a Double Devstream to dish out a... | Read more »
The Frozen Canvas adds a splash of colou...
It is time to grab your gloves and layer up, as Torchlight: Infinite is diving into the frozen tundra in its sixth season. The Frozen Canvas is a colourful new update that brings a stylish flair to the Netherrealm and puts creativity in the... | Read more »
Back When AOL WAS the Internet – The Tou...
In Episode 606 of The TouchArcade Show we kick things off talking about my plans for this weekend, which has resulted in this week’s show being a bit shorter than normal. We also go over some more updates on our Patreon situation, which has been... | Read more »
Creative Assembly's latest mobile p...
The Total War series has been slowly trickling onto mobile, which is a fantastic thing because most, if not all, of them are incredibly great fun. Creative Assembly's latest to get the Feral Interactive treatment into portable form is Total War:... | Read more »

Price Scanner via MacPrices.net

Early Black Friday Deal: Apple’s newly upgrad...
Amazon has Apple 13″ MacBook Airs with M2 CPUs and 16GB of RAM on early Black Friday sale for $200 off MSRP, only $799. Their prices are the lowest currently available for these newly upgraded 13″ M2... Read more
13-inch 8GB M2 MacBook Airs for $749, $250 of...
Best Buy has Apple 13″ MacBook Airs with M2 CPUs and 8GB of RAM in stock and on sale on their online store for $250 off MSRP. Prices start at $749. Their prices are the lowest currently available for... Read more
Amazon is offering an early Black Friday $100...
Amazon is offering early Black Friday discounts on Apple’s new 2024 WiFi iPad minis ranging up to $100 off MSRP, each with free shipping. These are the lowest prices available for new minis anywhere... Read more
Price Drop! Clearance 14-inch M3 MacBook Pros...
Best Buy is offering a $500 discount on clearance 14″ M3 MacBook Pros on their online store this week with prices available starting at only $1099. Prices valid for online orders only, in-store... Read more
Apple AirPods Pro with USB-C on early Black F...
A couple of Apple retailers are offering $70 (28%) discounts on Apple’s AirPods Pro with USB-C (and hearing aid capabilities) this weekend. These are early AirPods Black Friday discounts if you’re... Read more
Price drop! 13-inch M3 MacBook Airs now avail...
With yesterday’s across-the-board MacBook Air upgrade to 16GB of RAM standard, Apple has dropped prices on clearance 13″ 8GB M3 MacBook Airs, Certified Refurbished, to a new low starting at only $829... Read more
Price drop! Apple 15-inch M3 MacBook Airs now...
With yesterday’s release of 15-inch M3 MacBook Airs with 16GB of RAM standard, Apple has dropped prices on clearance Certified Refurbished 15″ 8GB M3 MacBook Airs to a new low starting at only $999.... Read more
Apple has clearance 15-inch M2 MacBook Airs a...
Apple has clearance, Certified Refurbished, 15″ M2 MacBook Airs now available starting at $929 and ranging up to $410 off original MSRP. These are the cheapest 15″ MacBook Airs for sale today at... Read more
Apple drops prices on 13-inch M2 MacBook Airs...
Apple has dropped prices on 13″ M2 MacBook Airs to a new low of only $749 in their Certified Refurbished store. These are the cheapest M2-powered MacBooks for sale at Apple. Apple’s one-year warranty... Read more
Clearance 13-inch M1 MacBook Airs available a...
Apple has clearance 13″ M1 MacBook Airs, Certified Refurbished, now available for $679 for 8-Core CPU/7-Core GPU/256GB models. Apple’s one-year warranty is included, shipping is free, and each... Read more

Jobs Board

Seasonal Cashier - *Apple* Blossom Mall - J...
Seasonal Cashier - Apple Blossom Mall Location:Winchester, VA, United States (https://jobs.jcp.com/jobs/location/191170/winchester-va-united-states) - Apple Read more
Seasonal Fine Jewelry Commission Associate -...
…Fine Jewelry Commission Associate - Apple Blossom Mall Location:Winchester, VA, United States (https://jobs.jcp.com/jobs/location/191170/winchester-va-united-states) Read more
Seasonal Operations Associate - *Apple* Blo...
Seasonal Operations Associate - Apple Blossom Mall Location:Winchester, VA, United States (https://jobs.jcp.com/jobs/location/191170/winchester-va-united-states) - Read more
Hair Stylist - *Apple* Blossom Mall - JCPen...
Hair Stylist - Apple Blossom Mall Location:Winchester, VA, United States (https://jobs.jcp.com/jobs/location/191170/winchester-va-united-states) - Apple Blossom Read more
Cashier - *Apple* Blossom Mall - JCPenney (...
Cashier - Apple Blossom Mall Location:Winchester, VA, United States (https://jobs.jcp.com/jobs/location/191170/winchester-va-united-states) - Apple Blossom Mall Read more
All contents are Copyright 1984-2011 by Xplain Corporation. All rights reserved. Theme designed by Icreon.