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

Whitethorn Games combines two completely...
If you have ever gone fishing then you know that it is a lesson in patience, sitting around waiting for a bite that may never come. Well, that's because you have been doing it wrong, since as Whitehorn Games now demonstrates in new release Skate... | Read more »
Call of Duty Warzone is a Waiting Simula...
It's always fun when a splashy multiplayer game comes to mobile because they are few and far between, so I was excited to see the notification about Call of Duty: Warzone Mobile (finally) launching last week and wanted to try it out. As someone who... | Read more »
Albion Online introduces some massive ne...
Sandbox Interactive has announced an upcoming update to its flagship MMORPG Albion Online, containing massive updates to its existing guild Vs guild systems. Someone clearly rewatched the Helms Deep battle in Lord of the Rings and spent the next... | Read more »
Chucklefish announces launch date of the...
Chucklefish, the indie London-based team we probably all know from developing Terraria or their stint publishing Stardew Valley, has revealed the mobile release date for roguelike deck-builder Wildfrost. Developed by Gaziter and Deadpan Games, the... | Read more »
Netmarble opens pre-registration for act...
It has been close to three years since Netmarble announced they would be adapting the smash series Solo Leveling into a video game, and at last, they have announced the opening of pre-orders for Solo Leveling: Arise. [Read more] | Read more »
PUBG Mobile celebrates sixth anniversary...
For the past six years, PUBG Mobile has been one of the most popular shooters you can play in the palm of your hand, and Krafton is celebrating this milestone and many years of ups by teaming up with hit music man JVKE to create a special song for... | Read more »
ASTRA: Knights of Veda refuse to pump th...
In perhaps the most recent example of being incredibly eager, ASTRA: Knights of Veda has dropped its second collaboration with South Korean boyband Seventeen, named so as it consists of exactly thirteen members and a video collaboration with Lee... | Read more »
Collect all your cats and caterpillars a...
If you are growing tired of trying to build a town with your phone by using it as a tiny, ineffectual shover then fear no longer, as Independent Arts Software has announced the upcoming release of Construction Simulator 4, from the critically... | Read more »
Backbone complete its lineup of 2nd Gene...
With all the ports of big AAA games that have been coming to mobile, it is becoming more convenient than ever to own a good controller, and to help with this Backbone has announced the completion of their 2nd generation product lineup with their... | Read more »
Zenless Zone Zero opens entries for its...
miHoYo, aka HoYoverse, has become such a big name in mobile gaming that it's hard to believe that arguably their flagship title, Genshin Impact, is only three and a half years old. Now, they continue the road to the next title in their world, with... | Read more »

Price Scanner via MacPrices.net

B&H has Apple’s 13-inch M2 MacBook Airs o...
B&H Photo has 13″ MacBook Airs with M2 CPUs and 256GB of storage in stock and on sale for up to $150 off Apple’s new MSRP, starting at only $849. Free 1-2 day delivery is available to most US... Read more
M2 Mac minis on sale for $100-$200 off MSRP,...
B&H Photo has Apple’s M2-powered Mac minis back in stock and on sale today for $100-$200 off MSRP. Free 1-2 day shipping is available for most US addresses: – Mac mini M2/256GB SSD: $499, save $... Read more
Mac Studios with M2 Max and M2 Ultra CPUs on...
B&H Photo has standard-configuration Mac Studios with Apple’s M2 Max & Ultra CPUs in stock today and on Easter sale for $200 off MSRP. Their prices are the lowest available for these models... Read more
Deal Alert! B&H Photo has Apple’s 14-inch...
B&H Photo has new Gray and Black 14″ M3, M3 Pro, and M3 Max MacBook Pros on sale for $200-$300 off MSRP, starting at only $1399. B&H offers free 1-2 day delivery to most US addresses: – 14″ 8... Read more
Department Of Justice Sets Sights On Apple In...
NEWS – The ball has finally dropped on the big Apple. The ball (metaphorically speaking) — an antitrust lawsuit filed in the U.S. on March 21 by the Department of Justice (DOJ) — came down following... Read more
New 13-inch M3 MacBook Air on sale for $999,...
Amazon has Apple’s new 13″ M3 MacBook Air on sale for $100 off MSRP for the first time, now just $999 shipped. Shipping is free: – 13″ MacBook Air (8GB RAM/256GB SSD/Space Gray): $999 $100 off MSRP... Read more
Amazon has Apple’s 9th-generation WiFi iPads...
Amazon has Apple’s 9th generation 10.2″ WiFi iPads on sale for $80-$100 off MSRP, starting only $249. Their prices are the lowest available for new iPads anywhere: – 10″ 64GB WiFi iPad (Space Gray or... Read more
Discounted 14-inch M3 MacBook Pros with 16GB...
Apple retailer Expercom has 14″ MacBook Pros with M3 CPUs and 16GB of standard memory discounted by up to $120 off Apple’s MSRP: – 14″ M3 MacBook Pro (16GB RAM/256GB SSD): $1691.06 $108 off MSRP – 14... Read more
Clearance 15-inch M2 MacBook Airs on sale for...
B&H Photo has Apple’s 15″ MacBook Airs with M2 CPUs (8GB RAM/256GB SSD) in stock today and on clearance sale for $999 in all four colors. Free 1-2 delivery is available to most US addresses.... Read more
Clearance 13-inch M1 MacBook Airs drop to onl...
B&H has Apple’s base 13″ M1 MacBook Air (Space Gray, Silver, & Gold) in stock and on clearance sale today for $300 off MSRP, only $699. Free 1-2 day shipping is available to most addresses in... Read more

Jobs Board

Senior Product Associate - *Apple* Pay (AME...
…is seeking a Senior Associate of Digital Product Management to support our Apple Pay product team. Labs drives innovation at American Express by originating, Read more
Medical Assistant - Surgical Oncology- *Apple...
Medical Assistant - Surgical Oncology- Apple Hill Location: WellSpan Medical Group, York, PA Schedule: Full Time Sign-On Bonus Eligible Remote/Hybrid Regular Apply Read more
Omnichannel Associate - *Apple* Blossom Mal...
Omnichannel Associate - Apple Blossom Mall Location:Winchester, VA, United States (https://jobs.jcp.com/jobs/location/191170/winchester-va-united-states) - Apple 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
Operations Associate - *Apple* Blossom Mall...
Operations Associate - Apple Blossom Mall Location:Winchester, VA, United States (https://jobs.jcp.com/jobs/location/191170/winchester-va-united-states) - Apple Read more
All contents are Copyright 1984-2011 by Xplain Corporation. All rights reserved. Theme designed by Icreon.