adding wireless communication capability to embedded systems

12
M odern microcon- trollers offer more capability than is often used in a typi- cal embedded system application. Normally, processor capacity is applied to data gathering and control functions such as sensing temperature, controlling motors, or dri- ving other physical interfaces. Communications capability is usually a secondary consideration resulting in applications that don’t really work together if they communicate at all. For this reason, many of today’s prod- ucts don’t team up and share a work- load or exchange information. Future microcontroller-based products will have the smarts to operate as a collec- tive whole by taking advantage of a variety of communication technolo- gies. One technology gaining popular- ity is wireless data communications. Mobitex wireless data is a mobile radio system used for a variety of applica- tions. Available in more than 6,000 U.S. cities and 33 countries world- wide, it is an international standard for packet switched messaging and data interchange. In this article, I show how wireless data capability can be incor- porated into an embedded system by looking at the Mobitex system and exploring the design and usage of Mobitex interface software intended to be highly portable across many micro- controller platforms. The focus is on the software design and system inte- gration aspects rather than radio fre- quency application and theory. THE MOBITEX NETWORK T he original concept was the design of a mobile alarm system used by field personnel of the Swedish telephone company. Mobitex has evolved into a widespread public mobile radio service in use in over 83 by ROY TARANTINO Adding Wireless Communication Capability to Embedded Systems 38 EMBEDDED SYSTEMS PROGRAMMING FEBRUARY 1996 How practical is it to use the air- waves as a communications medi- um for embedded systems? The author describes his experience developing a packet radio protocol stack for a single-board computer and the issues involved with inte- grating wireless communications into embedded systems. TR2

Upload: idmond

Post on 02-Dec-2015

212 views

Category:

Documents


0 download

DESCRIPTION

Adding Wireless Communication Capability to Embedded Systems

TRANSCRIPT

Page 1: Adding Wireless Communication Capability to Embedded Systems

Modern microcon-trollers offer morecapability than isoften used in a typi-cal embedded system

application. Normally, processorcapacity is applied to data gatheringand control functions such as sensingtemperature, controlling motors, or dri-ving other physical interfaces.Communications capability is usuallya secondary consideration resulting inapplications that don’t really worktogether if they communicate at all.For this reason, many of today’s prod-ucts don’t team up and share a work-load or exchange information. Futuremicrocontroller-based products willhave the smarts to operate as a collec-tive whole by taking advantage of avariety of communication technolo-gies. One technology gaining popular-ity is wireless data communications.Mobitex wireless data is a mobile radiosystem used for a variety of applica-tions. Available in more than 6,000U.S. cities and 33 countries world-wide, it is an international standard forpacket switched messaging and datainterchange. In this article, I show howwireless data capability can be incor-porated into an embedded system bylooking at the Mobitex system andexploring the design and usage ofMobitex interface software intended tobe highly portable across many micro-controller platforms. The focus is onthe software design and system inte-gration aspects rather than radio fre-quency application and theory.

THE MOBITEX NETWORK

The original concept was thedesign of a mobile alarm systemused by field personnel of the

Swedish telephone company. Mobitexhas evolved into a widespread publicmobile radio service in use in over 83

by ROY TARANTINO

Adding Wireless CommunicationCapability to Embedded Systems

38 EMBEDDED SYSTEMS PROGRAMMING FEBRUARY 1996

How practical is it to use the air-waves as a communications medi-um for embedded systems? Theauthor describes his experiencedeveloping a packet radio protocolstack for a single-board computerand the issues involved with inte-grating wireless communicationsinto embedded systems.

TR

2

Page 2: Adding Wireless Communication Capability to Embedded Systems

countries around the world. Stan-dardization of all Mobitex networksand compatibility of network featuresis ensured by the Mobitex OperatorsAssociation (MOA). MOA is an inde-pendent organization that publishes anopen standard document known as theMobitex Interface Specification. Thestandard defines the following specifi-cations in great detail:

■ The interface between radiomodems and mobile terminals

■ The over-the-air protocol betweenradio modems and base stations

■ The network level protocol andpacket format

■ The interface between fixed termi-nals and the network

■ Application services

Under Mobitex, packet switching isa very efficient way to transfer data. Inpacket switching, no end-to-end con-nection is established. Instead, a pack-et of data is transferred between suc-cessive nodes until it reaches its finaldestination. In circuit switched sys-tems, a circuit must be set up betweenthe two endpoints. When a circuitswitched system is used over sharedradio channels, no other traffic can beput on the channel during the setupphase, which is one reason why packet

switched data is more efficient forwireless data communication overshared radio channels.

RAM Mobile Data USA LimitedPartnership operates a Mobitex net-work with an over-the-air speed of 8Kbits per second in the 900MHz fre-quency range. Coverage extends toover 7,000 cities and towns. RAM alsoprovides standard interfaces for cus-tomer fixed host connectivity througha variety of protocols includingTCP/IP, LU2, X.25, POS, and AT.

The RAM Mobitex network is illus-trated in Figure 1. The network is madeof the following components:

■ Mobile Data Terminal—Typically aPC or other device used to run theend-user application.

■ Radio Modem or Adapter—Connects the mobile terminal to thenetwork via RF protocol. Uses theMASC protocol to maintain a con-nection to the Mobile DataTerminal.

■ Base Station—Manages all of the

radio communications in a givenarea or cell of the network. Two fre-quencies are used for each channel,one for transmitting and one forreceiving. Handles traffic routing,roaming, subscriber registration,and protocol handling for all usersin a given cell.

■ Regional Switch—Connected be-tween the main exchange and thebase stations. Joins a set of base sta-tions into a subnet.

■ Main Exchange—The top-mostswitching node in the network.Routes packet traffic between theregional switches.

■ Network Control Center—Used bythe system personnel to supervise,configure, control, manage andoperate the entire Mobitex system.

The structure is hierarchical andcontains five levels: mobiles, base sta-tions, local switches, regional switch-es, and the network control center. Thesystem turns around messages betweencustomers at the lowest common net-

FEBRUARY 1996 EMBEDDED SYSTEMS PROGRAMMING 39

Under Mobitex,

packet switching

is a very efficient

way to transfer

data. In packet

switching, no end-

to-end connection

is established.

Page 3: Adding Wireless Communication Capability to Embedded Systems

FEBRUARY 1996 EMBEDDED SYSTEMS PROGRAMMING 41

work node, ensuring quick responsetime and reducing traffic in the net-work. Only packets with destinationsat the farthest service area must propa-gate to the highest level.

Customer fixed or non-mobile hostconnections are made at the localswitch level, and any carrier can beused for the land line connection.Fixed-host connections can be madethrough gateways that translateMobitex to customer protocols such asTCP/IP or SNA. As an alternative tousing a gateway, host software can beused for building Mobitex awarenessinto applications. Many third-partyvendors provide host Mobitex softwarefor platforms ranging from IBM main-frames and Unix systems to PCs.

Other Mobitex terminology used inthis article include: Mobitex AccessNumber (MAN), a seven-digit numberthat makes up a subscriber’s address;Mobitex Asynchronous Communi-cations (MASC), the protocol betweenthe PC and the radio modem; andMobitex Packet (MPAK), which refersto the format of the network packets.

THE MOBITEX PROTOCOL

Applications designed to inter-face with Mobitex networksmay use many protocols. The

two required for interfacing between amobile terminal and radio modem are:MASC and MPAK (Mobitex Packet).

MASC operates on top of the RS-232 physical layer and provides a reli-able data link connection between theterminal and radio modem. MASC for-mats the data into frames with se-quence numbers and error detectioncapability. Information about the statusof the radio, base station coverage, andbattery strength is available from theMASC layer. MASC requires a hand-shake between the radio modem andterminal at least every 30 seconds dur-ing periods of inactivity to maintainthe connection.

All messages are sent through thenetwork in packets called MPAKs thatcontain up to 512 bytes of user datacoded as ASCII text or binary data.

Each MPAK contains addressinginformation, network data, and userdata. Messages longer than 512 bytesmust be sent in multiple MPAKs. Thesource and destination addresses, orMAN numbers, must be specified inthe MPAK for delivery. To broadcastmessages to multiple users, destina-tions can be lists of MAN numbers orgroup MAN numbers. In any case, thesystem will only send a single copy ofthe packet over the air.

If the destination mobile user is notcurrently active on the network, anoptional store and forward feature hasthe network retain the message anddeliver it the next time the mobile useris active on the network.

Other optional features supported bythe network include: positive acknowl-edgment of messages, personal userlogins, and a battery saving mode formobile terminals. Packet overheadincurred by the network amounts toonly eight bytes.

Because MASC provides the linklayer necessary to send and receiveMPAKs between a radio modem and aterminal, MPAKs are encapsulated inMASC frames. When it is time to sendthe MPAK over the radio link, theMPAK is removed from the MASCframe and sent using the over-the-airradio link layer protocol to ensureproper reception by the base station. Iwill not go into the radio link protocol.I make the assumption that once theradio modem has the MPAK, and if themobile is in coverage, the base stationwill receive the MPAK correctly.

Now that I’ve described the wirelessnetwork and the protocols, it should beclear that for a device to communicatewirelessly, it must be able to send andreceive data from a Mobitex radiomodem over a serial link and imple-ment the MASC and MPAK protocols.The remainder of this article describesthe design elements and portabilityaspects of Mobitex interface software,a wireless data application implement-ed with the software, and generaldesign considerations for wirelessapplications.

Page 4: Adding Wireless Communication Capability to Embedded Systems

42 EMBEDDED SYSTEMS PROGRAMMING FEBRUARY 1996

Wireless

MOBITEX INTERFACE TECHNOLOGY

RAM Mobile Data has devel-oped Mobitex interface soft-ware designed to make it rela-

tively easy to build wireless applica-tions. The software is written in ANSIC and designed to be ported to manyhardware platforms including embed-ded microcontrollers. Highly modular,the interface software allows Mobitexconfigurations ranging from full func-tionality to the minimal subset neces-sary for network communications.Two levels of configurability are pro-vided. Compiler time constants elimi-nate code and data during the compilephase, and because functional areas arepartitioned into separate source codefiles, memory requirements are furtherreduced by linking in only necessaryfunctions.

The interface software is made up ofthree modules: an operating systeminterface that contains interfaces tosystem resources, a MASC modulethat contains the MASC protocolimplementation, and an MPAK thatimplements the MPAK network proto-col. All three modules work together topresent a complete Mobitex interfaceto application designers without plac-ing high demands on system resources.Each module is described in the fol-lowing and illustrated in Figure 2:

■ Operating system interface—Contains interfaces to systemsresources including timers, memo-ry, queues, process dispatching,system configuration, and commu-nication ports

■ MASC module—Implements theMASC protocol by handling thecommunication dialog between theradio modem and the computer

■ MPAK module—Implements theMPAK protocol including the pack-et dialogs between the mobile com-puter and the network

Because the serial port is accessedexclusively through interfaces in theOS Interface module, it corresponds tolayer 1 or the physical layer of the OSI

Page 5: Adding Wireless Communication Capability to Embedded Systems

FEBRUARY 1996 EMBEDDED SYSTEMS PROGRAMMING 43

seven layer model. MASC maps intolink layer or level 2 of OSI since it pro-vides a data channel between two adja-cent nodes of the network. By provid-ing reliable end-to-end services, theMPAK module is at the network orlevel 3 of the OSI model. The interfacesoftware modules also correspond tothe OSI model in the way the data ispassed across the layers. A higher layerregisters with a lower layer for ser-vices. When an event occurs that is ofinterest to a higher layer, the lowerlayer will provide an indication to thehigher layer by executing a callbackfunction specified during registration.For example, MPAK registers withMASC to receive packets that arrive atthe radio modem. When a packet isavailable, MASC calls the receivepacket function that was provided byMPAK during registration. Similarly,MASC registers with the OS interfaceto receive characters when they comeinto the serial port. Upon arrival ofdata at the communications port, OS

interface functions try to assemble acomplete data frame before passing anindication to MASC.

Wireless data applications writtenon top of the MPAK layer follow thesame procedure. These applicationsregister for packets with the MPAKlayer and are invoked when the packetsof interest are received. Applicationscan also register for MASC events. Forexample, users of wireless data appli-cations need to be aware of when theyare in coverage and the radio signalstrength at any given time, so they candecide when to send or expect data.Because MASC is the interface to theradio and is the provider of such infor-mation, applications can registerdirectly with MASC to receive notifi-cation of coverage status changes orwhen signal strength value crosses agiven threshold. Applications can alsoavail themselves of services in theoperating system module. If a periodictimer is needed, the application canregister to be interrupted at regular

FIGURE 1A basic Mobitex system.

L o c a lSwitch(MQX)

RegionalS w i t c h(MHX)

L o c a lSwitch(MQX)

L o c a lSwitch(MQX)

Subnet

SubnetSubnet

Page 6: Adding Wireless Communication Capability to Embedded Systems

44 EMBEDDED SYSTEMS PROGRAMMING FEBRUARY 1996

Wireless Communication

intervals to poll for a certain event orperform some housekeeping.Therefore, unlike the OSI seven-layermodel, a higher layer process using theMobitex interface software is not limit-ed to the services of the next lowerlayer. It can make use of interfaces thatreside in all three lower layer modules.

The service interface to all threemodules follows the same pattern: ahigher layer registers with a lowerlayer with an API call that specifies theevent of interest and a function to becalled when the event occurs.Registration information is maintainedby each layer in queues, and when the

event is triggered, the queue is scannedto determine who should be informedof the event. This mechanism can beabstracted and generalized in all layers.In software design, whenever a con-cept can be generalized, code savingscan be realized by developing areusable framework that implementsthe generic functions. In this case, eachMobitex interface module can beabstracted into two discrete compo-nents. The first component contains theentry points or registration functionsfor users of the layer. Action functionsthat are used internally within the layermake up the second component. Theentry functions “present” the layer tothe outside world by exposing the ser-vice definition and facilitating dataflow across the layer. The action func-tions are the internals of the layer andare users of entry functions of otherlayers. Action functions are alsoresponsible for delivering indicationsto upper layers or users of the entryfunctions. Figure 3 illustrates the struc-ture of the service and user layers.

FIGURE 2Mobitex Interface Software Modules.

Wireless Application

Operating System Interface

MPAK Module

MASC Module

System Resources: Timer,Comm. Port, Memory

Page 7: Adding Wireless Communication Capability to Embedded Systems

FEBRUARY 1996 EMBEDDED SYSTEMS PROGRAMMING 45

Finite state machines are almostalways used for implementing commu-nication protocols because they pro-vide a framework for correlating inputdata with actions. Both the MASC,MPAK, and portions of the operatingsystem interface are structured as finitestate machines. Again, a genericframework is used for implementationto reduce the code size. The finite statemachine framework consists of a set ofstates and a set of transition functionsthat drive the machine though differentprotocol phases based on input events.States are represented in a table andcorresponding function pointers refer-ence the transition functions. An entryfunction maintains the current state,passes input events and invokes thetransition functions.

In the Mobitex interface software,finite state machines are coupled withthe service model previously describedto implement the MASC and MPAKprotocols. Registration requests trans-late to events and are put on a deferredevent queue. The dispatch machineretrieves the next event from the queueand invokes the machine responsiblefor handling the event or request. Real-time events such as characters receivedor timers firing are treated the sameway. Each queue element contains theID of the machine and data parametersspecific to the event that will be passedto the machine. The dispatcher main-tains a table containing machine entryfunctions, a machine ID. The eventstructure and finite state machine tableis defined by the following structuredefinitions:

typedef struct {DLINK DataLink;

/* Pointer to next deferred event */MACHINE_ENT *Machine;

/* Destination machine */void *Param;

/* Data to be passed */USHORT Event;

/* Associated event number */} DEFERRED_EVENT;

typedef struct{FSM_ID MachID;

/* ID number of machine */VOID_FPTR MachEntry;

/* Address of machine entry function */} MACHINE_ENT;

A machine can register with the dis-patcher by providing a machine entryfunction, a machine ID, and an initialstate. The event queuing function anddispatcher is implemented by the fol-lowing code:

/*Queue an event for machine execution.

*/RetCode EventDefer(FSM_ID MachID, ushort

event, void *param){MACHINE_ENT *LookupMachine(FSM_ID);MACHINE_ENT *Machine =

LookupMachine(MachID);DEFERRED_EVENT DeferredEvent;RetCode AppendList( LIST list, void

*ListElem);

if (Machine == NULL_MACHINE){

/* Not found, return error */return (MACHINE_NOT_FOUND);

}

DeferredEvent.Machine = Machine;DeferredEvent.Event = event;DeferredEvent.Param = param;return (AppendList(DeferredEventList,

&DeferredEvent);}/*Execute the next event on the deferred

event queue.*/void DispatchEvent(){DEFERRED_EVENT DeferredEventMACHINE_ENT *Machine;

DeferredEvent = (DEFERRED_EVENT *)ListRemoveHead(DeferredEventList);if (DeferredEvent != NULL_EVENT){

Page 8: Adding Wireless Communication Capability to Embedded Systems

46 EMBEDDED SYSTEMS PROGRAMMING FEBRUARY 1996

Wireless Communication

Machine = DeferredEvent->Machine;Machine->MachEntry(DeferredEvent->Event,

DeferredEvent->Param);MemFree(DeferredEvent);

}else{/* No work to do. */}}

The EventDispatch function can becalled during idle time and will per-form a unit of work. Entry functionsare implemented by queuing an eventfor each request and then returning anin-progress indicator to the caller.Action functions are called by themachine entry functions and carry outthe state transitions necessary to com-plete the request. For example, if theuser requests coverage status from theMASC module, the coverage statusentry function is called, which willqueue the request and then return.Eventually the action function associ-ated with coverage status is called bythe MASC machine. The action func-tion will then construct the necessarycommand and send it to the radiomodem. When the radio modemresponds, the response is queued by theserial port interrupt handler in theoperating system interface module.The MASC machine will then com-plete the request by taking the responseand passing it back to the originalrequester by calling the requester’scallback or completion function.

The Mobitex interface software hasminimal impact on the system CPUbecause the majority of the protocolwork is triggered by the dispatch func-tion, which is completely controlled bythe application. Both the serial com-munications and timer interrupt han-dlers perform minimal work queuingrequests to the deferred event queue.The queuing operation involves only asingle address write to append therequest. The serial communicationsinterrupt handler must buffer everycharacter that comes into the serial portand call the OS interface function to

assemble a frame. In the timer interruptservice routine, a queue must bescanned for expired timers. But sincethe timer queue is maintained in sortedorder in memory, the search time isminimal.

PORTING ISSUES

When looking at the targetplatform under considera-tion for running the Mobitex

interface software, the processor mustbe capable of handling interrupts froma real-time clock and a communicationport. The communication port must beRS-232 capable with at least send,receive, and ground signals. Memoryrequirements depend on the exactMobitex features that are needed andrange from 70K of code and 10K ofdata for full Mobitex features, to 40Kof code and 8K of data for a minimalfeature set. Flash RAM can be used forcode memory and static constant data.

To port the Mobitex interface soft-ware to a microcontroller, native func-tions must be written for dynamicmemory allocation and deallocation,receiving and sending characters viathe serial communications port on aninterrupt basis, and a timer interruptthat will get control at least every500ms.

Memory allocation and deallocationcan be directly implemented by nativemalloc and free function calls usuallysupplied with the run time library ofthe C compiler. The OS Interface mod-ule keeps careful track of all memoryallocations. All locations are main-tained on an independent linked list toensure that memory is returned to thesystem when it is no longer needed.

Serial communication functions arenot as generic as memory functions—they must be interrupt driven and capa-ble of reading and writing charactersfrom an RS-232 port. The followingare the communications interrupt rou-tines for a 68332 processor:

/*Mobitex Interface Software Character

Interrupt Routine

Uses the 68332 Time Processor Unit (TPU)Uart Function

*/#define UARTDATAREG 0xf04

void ServiceInputChar(void){/* Get the character from the UART memory

mapped area */InputBuff[InputCount++] = 0xff & *((uspv)

(IMBASE + (UARTDATAREG +(TPU_INPUT_CHAN<<1))));

if (inputCount >= BUFF_SIZE){

OSIntCommProc(InputBuff, InputCount);InputCount = 0;

}TPUClearInterrupt(TPU_INPUT_CHANNEL);}

ServiceInputChar supplies charactersto the MASC module by buffering upBUFF_SIZE characters as they arereceived and then calling the OS inter-face function, OSIntCommProc, to processthe buffer. The buffer size should be nolarger than the smallest MASC framethat requires a response (four bytes).Otherwise the radio modem will waitforever because the buffer will neverbe processed—it will be sitting in theinput buffer waiting for more charac-ters to arrive.

OSIntCommProc assembles thereceived bytes into a complete frame.When a complete frame has beenreceived, OSIntCommProc queues theframe on a receive queue and thenqueues an event on the deferred eventqueue for the MASC module. Whenthe MASC action function that handlesreceived frame gets called it will fetchthe frame from the receive queue andprocess it.

The send character function is sym-metrical to the ServeInputChar routineexcept that it maintains an outputbuffer and writes it out to the UARTwhen it is full. After the buffer is sent,an output completion event is queuedon the deferred event queue to indicateto the MASC layer that a frame wassent. The buffer size for the send char-acter function should be no larger than

Page 9: Adding Wireless Communication Capability to Embedded Systems

FEBRUARY 1996 EMBEDDED SYSTEMS PROGRAMMING 47

the smallest frame to be sent.Timer services provided by the OS

interface module are driven by a500ms timer. The timer interrupt ser-vice routine must call TimerProc tomaintain the timer request queues.

The MASC and MPAK modulescall the OS interface functions exclu-sively, so no porting is needed. It usu-ally takes less than one day to get theMobitex interface software running ona new platform.

Listing 1 demonstrates the use of theMPAK layer by reflecting back to thesender any packet that is received. Allcalls return immediately with an in-progress return code. Final completionis always indicated by invoking thesupplied callback function.

APPLICATION DESIGNCONSIDERATIONS

Because of the high latency andconnection intermittency asso-ciated with wireless data net-

works, existing applications based onwired technology must be re-workedfor wireless. Applications that set upvirtual circuits and stream data end-to-end must be redesigned to follow theconnectionless model where data is

partitioned into individual units andsent out as packets. Because packetdrivers that will run TCP/IP-basedapplications transparently over wire-less are available, it is often assumedthat no changes to the application arerequired. This assumption leads to dis-astrous results because transport proto-cols such as TCP conduct a three-wayhandshake during the connectionphase, which uses the round-trip pack-et time to calculate time-out values. Ona wireless network the round-trip timegrows excessively large and eventuallytimes out on most TCP/IP protocolstacks. Similar scenarios occur withIPX protocols. You can’t assume justbecause the transport is available andthe protocol stack will function, thatthe application will run wireless with-out modification. There is work under-way to improve this situation by pro-viding protocol optimization overwireless transparently to the protocolstack. Two methods include spoofingthe transport layer by eliminating pro-tocol handshake phases and other traf-fic intensive dialogs, and using veryaggressive data compression schemes.But, wireless awareness to the applica-tion is still strongly recommended.

FIGURE 3The service layer framework.

User Layer

Deferred Event QueueService Layer

Action Functions (Layer Internals)

Entry Functions(Exposed Interface)

Indications

Function calls

User FunctionsCallbacks

→←

QueuedEvent

QueuedEvent

QueuedEvent

Page 10: Adding Wireless Communication Capability to Embedded Systems

48 EMBEDDED SYSTEMS PROGRAMMING FEBRUARY 1996

Wireless Communication

#include "mpakuser.h"

int my_state=0;

MPAK_STATS StatsData;

MACH_HNDL hMachine;

char mpakbuf[512];

main()

{

RQST_ID Request;

*/

Wait for a packet, when one comes in reflect it

back to the sender.

*/

#include <stdio.h>

#include <string.h>

LISTING 1Simple Mobitex Interface SoftwareTest Program.

REG_HNDL RegHdl, RegStats;

void MyCompletionFunctions (WORD, RET_CODE,

RQST_ID,

void *, LEN_TYPE);

RET_CODE MyRcvFunction (int, REG_HNDL, PKT_TYPE,

void *, LEN_TYPE);

long rc;

/* 1. Initialize the OS Int and MPAK Modules. */

printf("main: calling OsIntInit()\n");

OsIntInit();

printf("main: calling Mpak_Init()\n");

rc = Mpak_Init(&hMachine, &Request,

(VOID_FUNC_PTR) MyCompletionFunctions);

if (rc != REQUEST_PENDING)

{

printf("Mpak_Init failed\n");

exit(1);

}

printf("waiting for INIT_CPLT...\n");

while(my_state != MPAK_INIT_CPLT)

; /* Do some other work */

/* 2. Register for all packets. */

rc = Mpak_DataRegister(hMachine, &Request,

&RegHdl,

(RC_FUNC_PTR) MyRcvFunction, MPAK_REG_ANY,

HPID_ANY, MAN_ANY, MAN_ANY);

if (rc != REQUEST_PENDING)

{

printf("Mpak_DataRegister failed\n");

exit(1);

}

/* 3. Enable the MPAK Layer. */

rc = Mpak_Enable(hMachine, &Request);

if (rc != REQUEST_PENDING)

{

printf("Mpak_Enable failed\n");

exit(1);

}

printf("waiting for ENABLE_CPLT...\n");

while(my_state != MPAK_ENABLE_CPLT)

; /* Do some other work */

/* 4. Now wait for a packet. */

printf("Waiting for incoming packets:\n");

while (1)

; /* Do some other work */

} /* end of main */

void MyCompletionFunction (WORD IndType, RET_CODE

Status,

Page 11: Adding Wireless Communication Capability to Embedded Systems

FEBRUARY 1996 EMBEDDED SYSTEMS PROGRAMMING 49

There are other considerations aswell. If the data is private, encryptionschemes must be used because every-one has free access to the airwaves andthe data could be easily intercepted.Data compression should be used end-to-end to minimize packet sizes,reduce cost, and conserve the airlink.Dialogs between applications shouldbe structured in such a way that multi-ple commands can be sent to be oper-ated on. For example, a client processshould include a login string and sev-eral commands to be processed by theserver process, rather than sending thelogin string and waiting for a responsebefore sending commands. The con-cept of a user agent is now becomingpopular for wireless applications. Useragents are resident processes on largehosts or server computers and are pre-programmed with libraries of agentscripts. The mobile client sends smallhigh-level commands to the agent whocarries out the request by executing astored procedure that performs manycommands on the host on behalf of themobile. The idea is to minimize theover-the-air dialog by making theagent very smart. This process is doneby including decision-making logicand only sending complete informationback to the mobile.

Applications should also take into

RQST_ID RqstID, void *data, LEN_TYPE

length)

{

printf("main: in MyCompletionFunctions ");

switch(IndType)

{

case MPAK_INIT_CPLT:

printf("status=%s\n",

(Status==SUCCESS)?"SUCCESS":"FAILED");

my_state=MPAK_INIT_CPLT;

break;

case MPAK_ENABLE_CPLT:

printf("status=%s\n",

(Status==SUCCESS)?"SUCCESS":"FAILED");

my_state=MPAK_ENABLE_CPLT;

break;

case MPAK_DATA_REG_CPLT:

printf("status=%s\n",

(Status==SUCCESS)?"SUCCESS":"FAILED");

my_state=MPAK_DATA_REG_CPLT;

break;

case MPAK_SEND_CPLT:

printf("status=%s\n",

(Status==SUCCESS)?"SUCCESS":"FAILED");

my_state=MPAK_SEND_CPLT;

break;

}

}

RET_CODE MyRcvFunction (int ind_type, REG_HNDL

hreg,

PKT_TYPE pkt_type, void *pbuf, LEN_TYPE

len)

{

RQST_ID Request;

MAN_TYPE SrcMan , CharToMan();

int mpak_len;

RET_CODE rc;

if (ind_type == MPAK_RECV_DATA_IND)

{

printf("MyRcvFunction: MPAK_RECV_DATA_IND len=%d

PKT_TYPE=%d\n",

len, pkt_type);

SrcMan = CharToMan ((char *) pbuf);

printf("source man =%ld\n", SrcMan);

printf("Packet:\n");

hexout(pbuf, len);

memcpy(mpakbuf, pbuf, len);

mpakbuf[0] = mpakbuf[3];

mpakbuf[1] = mpakbuf[4];

mpakbuf[2] = mpakbuf[5];

ManToChar((MAN_TYPE) SrcMan, &mpakbuf[3]);

mpak_len = len;

mpakbuf[MPAK_TYP_OFFSET] = MPAK_TYP_DATA;

mpakbuf[TRAFFIC_STATE_OFFSET] = 0;

printf("Sending %d bytes tp %ld\n",

mpak_len, SrcMan);

Mpak_SendData (hMachine, &Request,

mpakbuf, mpak_len);

}

else

printf("my_recvd_func: unknown ind

type:%d\n", ind_type);

return(ACCEPT_RELEASE_MPAK);

}

LISTING 1 (CONTINUED)

Page 12: Adding Wireless Communication Capability to Embedded Systems

50 EMBEDDED SYSTEMS PROGRAMMING FEBRUARY 1996

Wireless

account that wireless links are con-stantly changing. In a vehicle mountedsystem, the mobile could go in and outof signal coverage as the vehiclemoves across the cell. Intelligent sendand receive retry algorithms should beused, which take into account the cov-erage state, and should not attempt aretry until the signal is strong enoughto ensure good reception or transmis-sion. Feedback should be given to theuser. In some cases users should beincluded in the retry decision. Userswill have a good idea of the coverageat a given location, and the combina-tion battery level and signal strengthcan be used to conserve or optimizepower usage. A good test for wirelessapplications is to stress the applicationat a fringe area of coverage to see howit reacts to the transitions. Finally,applications should always give theuser the capability to silence the radioat any time to prevent radio interfer-ence with other more critical systemssuch as medical devices or construc-tion site equipment.

AFTERTHOUGHTS

Wireless data communicationstechnology offers the em-bedded system designer the

capability to add sophisticated commu-nications functions without the needfor wires or cabling. The technology isnow widely accepted. Reliable net-work infrastructures are in place anddevelopment tools are available.

Roy Tarantino is a consulting engineerwith RAM Mobile Data. At RAM hedevelops connectivity tools for RAM'swireless Mobitex network. Prior toRAM, Roy was active in many projectsincluding the development of embed-ded medical device software, networkmanagement tools, cellular infrastruc-ture planning, and firmware develop-ment for a combination pager, mobilephone, and two way radio. He holds anMS degree in Engineering andComputer Science from StevensInstitute of Technology and can bereached at [email protected].