newton technology journal: volume 1, number 1

Upload: pablomarx

Post on 03-Apr-2018

217 views

Category:

Documents


0 download

TRANSCRIPT

  • 7/28/2019 Newton Technology Journal: Volume 1, Number 1

    1/24

    Newton Deliversfor Vertical

    MarketsBy Jane Cur ley,Apple Computer, Inc.

    ApplesNewton platform deliverspowerfulnew technologiesthat can help create entire-

    lynew marketsfor developers. The combina-

    tion of power, ease-of-use and personal

    portabilitymakesit a great vehicle for attack-

    ing and solving problemswhose solution can

    not onlyopen up new businessopportuni-

    ties, but also make a real difference in how

    people can do their work. Recently, we came

    acrossa project in Boston that providesan

    excellent example of thisprocess.

    Health care professionalshave a unique

    need for accessto the resourcesof massive

    amountsof information at their fingertips,

    often immediately. Much of the information

    theyreference dailyin life or death situations

    isnot onlyclinical data, but also educational

    resources, decision aids, and other profes-

    sional and practical information. Manytimes,

    health care professionalsdo not consult ref-

    erence materialswhen making clinical deci-sions. Thisisdue, in part, to the fact that

    there isa lack of availabilityof resource infor-

    mation in areaswhere it isneeded most. But

    ApplesNewton MessagePad in the health care

    environment ischanging some of that.

    BostonsBrigham and WomensHospital

    will begin a joint pilot program with the

    MassachusettsGeneral Hospital using Apples

    BusinessOpportunities

    Newton Deliversfor Vertical Markets 1

    Communications

    Newton Communications 1

    DeveloperGroup News

    New Developer Support Programs

    For Newton Developers 3

    NewtonScriptTechniques

    Exception Handling in NewtonScript 4

    UnderstandingNewtonScript

    NewtonScript Functions 7

    NewtonCommunications

    Beam Me Up, Newt! 10

    continued on page 14 continued on page 15

    Volume I, Number 1 February 1995

    NewtonCommunicationsby Bill Worzel, Arroyo Software

    [email protected]

    Newton communicationsprogramming isoften viewed with a mixture of awe and fear.

    Somehow the notion of programming a PDA

    to connect to everything from wireless

    devicesto infrared to networksseemsslightly

    unreal.

    Once you begin to explore the communi-

    cationschapter in the Newton Programmers

    Guide (NPG), astonishment maygive wayto

    puzzlement. The situation often becomes

    worse when a programmer beginsto write

    and debug code.

    This article isintended to make things

    easier for the programmer bygiving more

    details, code examplesand inside looksat the

    architecture of the communicationsside of

    the Newton. Thisarticle first discussesthe

    architecture and fundamentalsof creating,

    connecting and using Newton endpoints.

    Next, it talksabout serial and modem connec-

    tions. Lastly, a related article (Beam Me Up

    Newt!) discussesuse of the infrared link for

    connection both to other Newtonsand to

    remote home appliancessuch astelevisions,VCRs, CD players, and so on.

    Thisarticle assumesyou are familiar with

    the Newton, NewtonScript and the Newton

    Toolkit (NTK). Because unusual programming

    techniquesand constructswill be discussed,

    it also helpsif you have some experience in

    doing communicationsprogramming. This

    article isdesigned to cover much the same

    ground (though not in asmuch detail ) asis

    Business Opportunities CommunicationsInside This Issue

  • 7/28/2019 Newton Technology Journal: Volume 1, Number 1

    2/24

    February 1995 Newton Technology Journal

    2

    Welcome to the premier issue ofNewton Technology Journal! The

    Personal Interactive Electronics(PIE) divi-

    sion at Apple Computer, Inc. ispleased to

    be able to bring you thisnew, bi-month-

    lypublication. From itsfirst conception,

    thisjournal hasbeen designed and tai-

    lored specificallyfor you, the Newton

    platform developer. Our intent isto make

    Newton Technology Journal your primary

    resource for the latest information on

    Newton platform technology, Newton

    development tools, and PDA business

    and market newsfrom Apple Computer

    and our licensees. While our focuswill

    be primarilytechnical, we also want to

    provide our developerswith a well-

    rounded picture of the opportunities

    that the Newton platform isbuildingfor

    the developer community.

    AsManaging Editor of ApplesNewton

    Technology Journal, I know I speak for

    the entire publishing team when I sayI m

    thrilled to be able to provide such a sup-

    port resource to Newton developers.

    With our recent introduction of a full

    range of Newton Developer Programsin

    December, 1994, were reallyfilli ng out

    our range of servicesto assist develop-

    ersin creating and publishing winning

    Newton applications. I hope Newton

    Technology Journal will go a long way in

    making those support servicesindis-

    pensable to you.

    In thispremier issue, youll find arti-

    cleson Newton communications, excep-

    tion handling, and function objects,

    written byexpert Newton programmers

    Bill Worzel, Neil Rhodes, and Julie

    McKeehan. Youll also get a recap of the

    recentlyintroduced Newton Partnersand

    Newton AssociatesDeveloper Programs.

    On the businessside, well give you a

    look at a vertical market successstoryin

    the medical arena.

    Well look forward to bringing you

    the latest in technical and businessnews

    on the Newton platform in future edi-

    tions. We also invite you to send your

    comments, suggestions, and article ideas

    to usvia Internet at

    piesysop@ applelink.apple.com. The

    Newton TechnologyJournal isthe perfect

    forum to share your tips, tricks, and pro-

    gramming expertise. The Newton platform

    isgrowing fast, and we hope to grow

    our communityof authorsand contribu-

    torsequallyfast with your help. Do you

    have an article youd like to write and

    have published in Newton Technology

    Journal? Just let usknow.

    For those of you currentlydeveloping

    for Newton, congratulationson your

    accomplishmentsand successesthusfar.

    For readersjust beginning their Newton

    development experience, I m happyto

    welcome you aboard thisexciting plat-

    form. The Newton TechnologyJournal is

    for all of you, and the great products

    youre going to create!

    Published by Apple Computer,Inc.

    Lee DePalma Dorsey Managing Editor

    G erry Kane Coordinating Editor,Technical Content

    Tony Espinoza Coordinating Editor,Technical Tools

    Marketing

    D avid Glickman Coordinating Editor, Business

    Content

    G abriel Acosta-Lopez Coordinating Editor, DTS and

    Training Content

    Philip Ivanier Manager,Newton Developer Relations

    Technical Peer Review Board

    J. Christopher Bell, Bob Ebert, Jim Schram,

    M aurice Sharp, Steve Strong, Bruce Thompson

    Contributors

    Jane Curley, Steven E. Labkoff, Julie M cKeehan,

    N eil Rhodes, Bill Worzel

    Produced by Xplain Corporation

    N eil T icktin Publisher

    Scott T Boyd Editor

    John Kawakami Editorial Assistant

    Judith Chaplin Art Director

    1994 Apple Computer, Inc., 1 Infinite Loop,Cupertino,C A 95014, 408-996-1010. A ll rightsreserved.

    Apple, the Apple logo, APDA , AppleD esign, AppleLink,AppleShare, A pple SuperDrive, A ppleTalk, HyperCard, LightBulb Logo, M ac, M acApp, M acintosh, M acintosh Q uadra,

    M PW, N ewton, N ewton Toolkit, N ewtonScript, Performa,Q uickT ime, and WorldScript are trademarks of A pple

    Computer, Inc., registered in the U.S. and other countries.AO CE, AppleScript, AppleSearch, ColorSync, develop,eWorld, Finder, O penD oc, Power M acintosh, Q uickD raw,SNA ps, and Sound Manager are trademarks, and AC O T isa

    service mark of Apple Computer, Inc. N uBusis a trademarkof TexasInstruments. PowerPC isa trademark of InternationalBusiness M achines Corporation, used under license there-from. W indowsisa trademark of M icrosoft Corporation andSoftWindows is a trademark used under license by Insignia

    from M icrosoft Corporation. UN IX is a registered trademarkof UN IX System Laboratories, Inc. A ll other trademarks arethe property of their respective owners.

    M ention of products in thispublication is for information-

    al purposesonlyand constitutesneither an endorsement nora recommendation. A ll product specifications and descrip-tions were supplied by the respective vendor or supplier.Apple assumesno responsibi lity with regard to the selection,

    performance, or use of the products listed in this publication.A ll understandings, agreements, or warranties take placedirectly between the vendors and prospective users.Limitation of liability:A pple makesno warrantieswith respectto the contentsof productslisted in thispublication or of the

    completenessor accuracyof thispublication.Apple specifical-ly disclaims all warranties, express or implied, including, butnot limited to, the implied warranties of merchantability andfitnessfor a particular purpose.

    Volume I, Number 1 February 1995

    by Lee DePalma Dorsey, Managing Editor

    Editors Note

    Apple Computer, Inc.would like to thank Xplain Corporation (the publishersof MacTech Magazine)

    for lending their expertise in producing the Newton TechnologyJournal.

  • 7/28/2019 Newton Technology Journal: Volume 1, Number 1

    3/24

    Newton Technology Journal February 1995

    3

    Apple Computer, Inc.sPersonal Interactive ElectronicsDivision (PIE)and the Apple Developer Group are pleased to announce the introduc-

    tion of the Newton AssociatesProgram for Newton MessagePad and

    Newton platform developers, aswell asseveral enhancementsto the

    Newton PartnersProgram (formerlythe PIE PartnersProgram). Effective

    December 1, 1994, Newton developersnow have a range of support ser-

    vicesfrom which to choose to meet all of their development needs.

    Answering the developers call for affordable, qualitysupport, the

    establishment of the Newton AssociatesProgram further reinforces

    Applesongoing commitment to the Newton platform and itsdevelop-

    ers. said Shane Robison, Vice President and General Manager of Apples

    Personal Interactive ElectronicsDivision. Developersare crucial to the

    platformssuccessand viabilityand we are verypleased to be able to

    expand support to a broader developer community.

    Newton Associates Program

    The Newton AssociatesProgram isa low cost, high quality, self-help

    development support program. It isavailable for a US$400 annual fee

    and includesthe following features:

    Support servicesfrom ApplesDeveloper Support Center

    Discounted ratesfor online technical information

    Accessto a technical Q&A reference library

    Discountson Newton and Macintosh hardware

    Receipt of regular Newton developer mailingswhich include the

    Newton Developer CD and the Newton TechnologyJournal

    Use of Applesthird partycompatibilitylab

    Discountson Newton development classes

    Automatic invitation to the Newton and Worldwide Developer

    Conferences

    Eligibilityto participate in StarCoresAffiliate Label Program

    Newton Partners Program

    The Newton PartnersProgram (formerlycalled the PIE Partners

    Program) includesall the featuresof the Newton AssociatesProgram

    plusservicessuch asexpert-level programming support via e-mail, free

    updatesto Newton development toolsand participation in select Apple

    marketing and PR opportunities. The price hasbeen reduced from

    US$2850 to US$2500 annually. In addition, the Newton PartnersProgram

    hasbeen enhanced with new featuressuch asa Newton-focused

    monthlymailing, a Newton orientation kit, regular deliveryof the

    Newton Developer CD, and the Newton TechnologyJournal, a new tech-

    nical publication for Newton developers.

    Both the Newton PartnersProgram and Newton AssociatesProgram

    are onlyavailable to developersin the US and Canada at present.

    Developersoutside of the US and Canada should contact their local

    Apple office for detailson current or planned Newton support options

    in their region.

    For more information on joining the Newton Associatesor

    Newton PartnersProgram, you maycontact the Apple Developer

    Support Center at (408)974-4897, Internet:

    devsupport@ applelink.apple.com or AppleLink: DEVSUPPORT.

    New Developer Support ProgramsFor Newton Developers

    To request information or an application on Apple'sNewton developer programs,

    contact Apple'sDeveloper Support Center

    at 408-974-4897

    or Applelink: DEVSUPPORT

    or Internet: devsupport@ applelink.apple.com.

    N

    Developer Group News

  • 7/28/2019 Newton Technology Journal: Volume 1, Number 1

    4/24

    February 1995 Newton Technology Journal

    4

    ANOVERVIEWOFEXCEPTIONS

    Exceptionsare a wayof dealing with errors. An exception isa report of

    an abnormal condition. It terminatesthe execution of the current func-

    tion and of the function that called it, and so on up the call chain until

    an exception handler isfound to respond to the error. The exception

    handler in turn isusuallyresponsible for cleanup and for reporting the

    error/exception to the user. Exceptionsare an alternative to returning

    error codes.

    Figure 1 showshow thiswhole mechanism operates. Here we have

    function A calling B calling C calling D calling E. Function B hasthe

    exception handler and function E throwsthe exception. At thispoint,

    Function E terminatesfollowed likewise byD and C. Function Bsnormal

    flow isstopped and execution continueswithin Bsexception handler.

    Figure 1.

    THEADVANTAGESOFUSINGEXCEPTIONSIn your programming, there are a couple of clear advantagesto using

    exceptionsasopposed to returning error codes. The first advantage is

    that functionsthat do not generate exceptions( like C and D) , but

    which call functionsthat do, dont need to do anything special.

    Without anyextra work, the exception will be propagated to calling

    functions(like B). On the other hand, if you relied onlyon error codes,

    C and D would need to return error codesaswell, since theycall the

    function with the error in it.

    The second advantage isthe simplification of functions. Since the

    execution of a function terminatesassoon asan exception occurs,

    you can be sure that the statementsprior to the exception executed

    successfully. Conversely, functionswhich use error codescommonly

    look like this:X := func()begin

    error := A();if error == noErr then begin

    error := B();if error == noErr then begin

    error := C();end;

    end;return error;

    end;

    Itsclear that the logic of the functionscan get lost in the error-check-

    ing. With exceptions, however, X could be neatlywritten as:

    X := func()begin

    A();B();C();

    end;

    WORKINGWITHEXCEPTIONS

    Having a fairlygood idea whyprogramming with exceptionsmakes

    sense, note the type of code that would profit from it use. Code that

    typicallyfollowsthispattern will be of interest:

    set some statecode which could cause an exceptionrestore the state

    Of the typesof statesthat benefit from exception handling, it is

    worth reviewing those statesyou might be familiar with from other

    typesof machines, and then looking at the situation with the Newton.

    EXCEPTIONHANDLINGINOTHERENVIRONMENTSOn desktop machinesusing traditional languages, exception handlers

    are common. Here are some examplesof common statesthat require

    exception handlers:

    Allocate some memory

    Do something with the memorythat could cause an exception

    Deallocate the memory

    Lock some memory

    Do something with the memorythat could cause an exception

    Unlock the memory

    Open a file

    Write to the file

    Close the file

    Create a temporaryfile

    Use the temporaryfile

    Delete the file

    Each of these requiresan exception handler. When a resource has

    been acquired, it must be given up in the event that an exception

    occurs.

    Exception Handling in NewtonScript

    1994, Apple Computer, Inc. and Calliope Enterpri ses, Inc.

    NewtonScript Techniques

  • 7/28/2019 Newton Technology Journal: Volume 1, Number 1

    5/24

    Newton Technology Journal February 1995

    5

    EXCEPTIONHANDLINGINTHENEWTONENVIRONMENTBecause of NewtonScriptssuperior handling of memory, the need for

    exception handlersisminimized. Since NewtonScript hasgarbage col-

    lection, explicitlydeallocating memoryisnot necessary. Likewise, the

    Newton hasno memorylocking, making unlocking unnecessaryaswell.

    Another nice point isthe Newtonslack of files; if you dont have a fileopen, you dont have to close it.

    Asyou can see then, none of the typical stateson other platforms

    are a problem on the Newton. So what is?In applications, two common

    placesyou will need exception handling are when calling the

    EntryChangemethod and thePutAwaymethod used for

    beaming and mailing. A rarer situation involvesthe creation of a tempo-

    rarysoup on the Newton; in thiscase you would use exception han-

    dling to ensure itsdeletion.

    TheStructure of Exceptions

    Thissection describeshow you would write an exception handler

    using

    proper NewtonScript syntax. Next, it looksat the hierarchical relation-

    ship

    of exceptions.

    Exception HandlingSyntax

    The actual syntax for exception handlersin NewtonScript is:

    trycode which could generate an exception

    onException exceptionSymbol docode to handle this type of exception

    onException exceptionSymbol2 docode to handle this type of exception

    To propagate an exception from within an exception handler, use

    theRethrow function:

    Rethrow();

    TheHierarchy of Exceptions

    There isa hierarchyof exceptions(Figure 2 showsa small subset of

    the whole tribe). Thishierarchyexistsso that you can write exception

    handlersfor a specific exception, a group, or for all of them.

    Figure 2.

    Everyexception symbol containsanevt.ex part (since the sym-

    bolscontain embedded periods, theymust be surrounded by||).

    Portionsafter the.part signifylower levelsin the hierarchy. For exam-

    ple, the exception|evt.ex.fr.intrp| isa kind of|evt.ex.fr|

    exception. You use semicolons(asshown in Figure 2) to separate

    multiple exception types.

    So, if you wish to catch all exceptionsuse:

    onException |evt.ex|

    You can also use more specific exception types. For instance, to catchonlytype.ref exceptions, use:

    onException |type.ref|

    It isalso possible to cascade exception handlers. In thiscase, the first

    one that matchesthe current exception isthe one that getscalled. For

    example:

    trycode

    onException |evt.ex.div0|deal with divide-by-zero error

    onException |type.ref|deal with a type error

    onException |evt.ex|deal with all other errors

    UsingExceptions in Newton Applications

    There are two typical problemsyou might encounter on the Newton

    that could benefit from the use of exceptions. The first involvesusing

    EntryChange,and the second involvesthePutAway

    method.

    Exception Handlingand EntryChange

    TheEntryChange method isthe mechanism used on the

    Newton to allow an application to save a modified entryback into its

    soup. Although the view system will provide a reasonable notification

    to the user (see Figure 3), you will see that more isneeded.

    Figure 3.

    Here iswhy. These code snippetshandle saving a modified entrywhen

    the user scrollsup:

    viewScrollUpScript: func()begin

    :SaveModifiedEntry(currentEntry);:DisplayPreviousEntry();

    end;

    SaveModifiedEntry: func()begin

  • 7/28/2019 Newton Technology Journal: Volume 1, Number 1

    6/24

    February 1995 Newton Technology Journal

    6

    EntryChange(currentEntry);

    end;

    IfEntryChange throwsan exception, the notification shown in

    Figure 3 will be presented bythe view system. A problem remains, how-

    ever. The user isstuck viewing the current entryand anyeffort to saveit ( like closing the application) , causesSaveModifiedEntry to

    throw an exception (because ofEntryChange) . Thus, no

    progresscan be made.

    The solution isto change the behavior ofSaveModifiedEntry.

    Rather than having it swing between successfullysaving or throwing an

    exception, modifyitsbehavior to successfullysave or to notifythe user of

    the error. You can also rename the function to describe more accuratelyits

    newresponsibilities:viewScrollUpScript: func()begin

    :HandleModifiedEntry(currentEntry);:DisplayPreviousEntry();

    end;

    HandleModifiedEntry: func()begin

    try

    EntryChange(currentEntry)onException |evt.ex.fr.store| dobegin

    :Notify(kNotifyAlert, EnsureInternal(kAppName),EnsureInternal(There is not enough space tosave the modified item));

    EntryUndoChanges(currentEntry);end;

    end;

    The call toEntryUndoChanges isnecessary; that ishow

    you wipe out modificationsmade to the entry. Otherwise, the soup

    holdsthe unmodified entry, while the entrycache containsa modified

    entry. The right course of action isto have the view reflect the fact that

    you were unable to save the entry. Thus, you must revert to the saved

    entryand then displaythat version.

    WARNINGThe union soup methodAddToDefaultStoredoesnot throw

    an exception when a store isfull, although the documentation says

    that it does. In reality, AddToDefaultStoreshowsthat it failsby

    returningnil and bycallingNotify to alert the user. Thisfailure to

    follow documented behavior can create problemsfor applicationsthat

    do not check to ensure that AddToDefaultStoresucceeds.

    You might want to consider writing a wrapper around the

    AddToDefaultStoremethod that will throw an exception in the

    event that theAddToDefaultStoremethod returnsnil:

    DefConst('kMyAddToDefaultStore, func(unionSoup, frame)begin

    result := unionSoup:AddToDefaultStore(frame);if not result then

    Throw('|evt.ex.fr.store|, '{error: 10617});return result;

    end);

    Exception Handlingand PutAway

    The other place where exception handling iscommonlyneeded isin

    thePutAwaymethod, used for beaming and mailing. Remember

    thatPutAway callskRegisterCardSoup, addsan entry to

    a soup, and then callskUnregisterCardSoup. Since adding an

    entrymaythrow an exception, an exception handler isneeded to call

    kUnregisterCardSoup. Here isa stripped-downPutAway

    method that showsthe problem:

    PutAway := func(item)begin

    local soup;

    soup := call kRegisterCardSoupFunc with (kSoupName,kSoupIndexes, kAppSymbol, kAppObject);

    soup:AddToDefaultStore(item.body);call kUnregisterCardSoupFunc with (kSoupName);

    en d

    The Sample Code with Exception Handling

    Now, look at how to fix the problem with exception handling:

    PutAway := func(item)begin

    local soup;

    soup := call kRegisterCardSoupFunc with (kSoupName,kSoupIndexes, kAppSymbol, kAppObject);

    try

    To send commentsor to make requestsfor articlesin Newton TechnologyJournal,

    send mail via internet to: piesysop@ applelink.apple.com

    N

  • 7/28/2019 Newton Technology Journal: Volume 1, Number 1

    7/24

    Newton Technology Journal February 1995

    7

    FUNCTIONOBJECTSINNEWTONSCRIPTIn NewtonScript, function objects(sometimescalled closures) are first-

    classobjectsthat can be manipulated and stored just like other values.

    For example, you can store a function object in:

    a local variable

    an array

    a slot in a frame

    a soup entry

    You can use function objectsin a varietyof waysaswell: you can

    passa function object asa parameter, make aClone, or

    DeepCloneof it. Thisconsistencybetween function objectsand

    other valuesmakesNewtonScript veryflexible.

    These aspectsof function objectsare usuallywell understood by

    NewtonScript programmers. There isanother aspect to a NewtonScript

    function object, however, that islessclear:

    When a function object is created, by executing a func statement, it

    saves the envi ronment that exists at that time.

    Bydoing so, the function object can have accessto local variables,

    parameters, and inherited variable lookup that existed at itscreation

    time.

    The term function object, rather than just function, isused to

    emphasize the fact that onefunc statement can give rise to manydif-

    ferent function objects. These functionswill differ based on the envi-

    ronment that existsat the time thefunc statement isexecuted.

    Function Environment

    To understand how you can use thisaspect of a function in your

    applications, itsgood to review the environment of most NewtonScript

    functions. Usually, you create a function object at compile time. These

    could be slotsin a template, edited using a slot browser, or theycould

    be functionscreated in a Project Data file. In either case, the environ-

    ment that existsisthe top-level environment of NTK. Thus, there are no

    local variables, parametersor inherited variablesavailable when that

    function object iscreated.Now, look at a different wayto create a function object. In thiscase

    the environment in which it iscreated will matter. Thiswill be a run-time

    function object. Note that bydefinition, these will be nested functions

    (onescreated inside other functions).

    For example:

    outerFunction := func(aParameter)begin

    local aVariable := 3;

    local nestedFunction := func(nestedParameter)

    beginlocal nestedlocal := 5;Print(aParameter);Print(aVariable);Print(nestedParameter);Print(nestedFunction);Print(nestedlocal);

    end;

    The function object, nestedFunction, iscreated as

    outerFunction isexecuting. At the run-time point when

    nestedFunction isactuallycreated, the environment includesa

    local variable,aVariable, and a parameter,aParameter. Since

    nestedFunction hasaccessto that environment, it can access

    both itsown parametersand local variables, aswell asthose of the

    function in which it isnested.

    HowFunction Objects Are Used Call/Perform/Apply

    Before talking about how you can use function objectsin your pro-

    gramming, itsnecessaryto addressthe manner in which you call a

    function object. There are four waysto do this:

    With a compile-time argument list (Call):

    Call functionObject with (argumentList)

    With a run-time argument list (Apply):

    Apply(functionObject, argumentArray)

    Bysending a message with a compile-time argument list (:and:?):

    frameExpression.message(argumentList)

    Bysending a message with a run-time argument list (Perform):

    Perform(frameExpression, messageSymbol, argumentArray)

    Here issome sample code that usesthese four ways:

    local Pow := func(num, iterations)begin

    for i := 1 to iterations do

    total := total * num;return total;

    end;Call Pow with (2, 3) 8local argArray:= [2, 3];Apply(Pow, argArray) 8local account := {

    balance: 0,Deposit: func(amount)

    return balance := balance + amount,};account:Deposit(50) 50Perform(account, 'Deposit, [75]) 12 5Print(account) {balance: 125,

    NewtonScript Functions

    1994, Apple Computer, Inc. and Calliope Enterpri ses, Inc.

    Understanding NewtonScript

  • 7/28/2019 Newton Technology Journal: Volume 1, Number 1

    8/24

    February 1995 Newton Technology Journal

    8

    Deposit: }

    Abstract DataTypes

    One use of function objectsisto implement Abstract Data Types.

    These are typesthat can onlybe modified procedurally; their actual

    data ishidden. Frameswith methodsdont provide the same functional-ity, though it might appear theydo. In a frame, the data valuesin the

    slotsare visible and can be modified, even when not using the appro-

    priate methods.

    Consider the following account generator:

    MakeAccount := func()begin

    local balance := 0;local Deposit := func(amount) begin

    return balance := balance + amount;end;return Deposit;

    end;

    Calling MakeAccount returnsa function object:

    myAccount := call MakeAccount with ()

    Thisfunction object referencesthebalance local variable from

    MakeAccount. ThoughMakeAccount isno longer execut-

    ing, the nested functionDeposit referencesbalance, and so the

    balance variable continuesto exist. Thus, callingmyAccount

    modifiesthe hidden variablebalance:

    call myAccount with (50) 50call myAccount with (75) 10 0

    Notice also that one function object can return multiple function

    objects, each of which referencesshared data. For instance, suppose

    you want both Deposit and Clear capabilitiesin your account:

    MakeAccount := func()begin

    local balance := 0;local Deposit := func(amount) begin

    return balance := balance + amount;end;local Clear := func() begin

    balance := 0;end;return [Deposit, Clear];

    end;

    BecauseMakeAccountneedsto return two values(two func-

    tion objects), it returnsthem in an array:

    myAccount := call MakeAccount with ();myOtherAccount := call MakeAccount with ();call myAccount[0] with (50) 50

    call myOtherAccount[0] with (40) 40call myAccount[0] with (75) 12 5call myAccount[1] with () 0call myOtherAccount[1] with () 0

    Using an arrayfor the two function objectsissomewhat inconve-

    nient, however, since the numbers0 and 1 dont describe the

    DepositandClear functionsin a veryuseful manner. To fix this

    problem, you rewriteMakeAccount to return the two function

    objectsin a frame rather than in an array. Thisway, the function objects

    can be referenced byname, rather than byarraylocation.

    MakeAccount := func()begin

    local balance := 0;local d := func(amount) begin

    return balance := balance + amount;end;local c := func() begin

    balance := 0;end;return {

    Deposit: d,Clear: c,

    };end;myAccount := call MakeAccount with ();call myAccount.Deposit with (50) 50call myAccount.Deposit with (75) 12 5call myAccount.Clear with () 0

    Remember, however, that the frame above isused onlyasa wayto

    store two named values. No object programming hasstarted, however,

    asno messagesare being sent.

    Admittedly, thisuse of function objectsto create Abstract Data Types

    isnot common. There are cases, however, where function objectsare

    necessaryin your Newton programming. One of the most common

    examplesoccurswhen an application issupporting Date Find.

    UsingFunction Objects to Support Date Find

    Here isan excerpt of code from DateFind:

    func(comparison, time, )begin

    cursor := Query(, {type: 'index,validTest: func(e)begin

    if comparison = 'dateBefore thenreturn e.date < time

    else

    return e.date > time;en d

    });return cursor to caller

    end;

    Even though thevalidTest function isembedded in the cursor,

    it iscalled from the Find resultsslip to displaythe found entries. Notice

    howDateFindscomparison and time parametersare used bythe

    nested functionvalidTest. Keep in mind that thevalidTest is

    called after theDateFind function hasfinished executing.

    Here isanother example of how you might use function objects.

    Imagine that you want to count the number of entriesin a particular

    query. In such a case, you might use a function object to count the

    number of entriesin a cursor usingMapCursor:CountEntries := func(cursor)begin

    local total := 0;MapCursor(cursor, func(e)

    begintotal := total + 1;nil;

    end);return total;

    en d

    The function object passed toMapCursor incrementsa variable

  • 7/28/2019 Newton Technology Journal: Volume 1, Number 1

    9/24

    inCountEntries. Notice that the function object returnsnil, and

    thusMapCursorwill end up returning an emptyarray.

    Stack Frames/Activation Records

    In most programming languages, when a function isentered, an

    activation record ( also called a stack frame) ispushed on the stack. Thisactivation record containsthe parametersto the function and local

    variables. When the function returns, the activation record ispopped

    from the stack.

    In NewtonScript, some allowance needsto be made for variablesthat

    are closed over; that is, variablesthat are accessed bynested functions.

    Since nested functionsmayneed to accessvariablesfrom outer func-

    tionseven after the outer function hasexited, a stack-based system

    which alwayspopsouter referencesfrom the stack could not help but

    fail.

    One possible implementation could be to allocate activation records

    in dynamicmemory(the heap). Like all other allocated memory, when

    no more referencesare made to the memory, it can be garbage-collect-

    ed. Thus, the activation record isnot freed when a function object exits

    if anynested functionsstill exist. Onlywhen all nested functionsare

    freed isthe activation record available for garbage collection.

    Another implementation might store part of an activation record on

    the stack, and part on the heap (onlythose variablesreferenced by

    nested functionsneed be on the heap) .

    Message Context

    A function object hasaccessto more than local variablesand para-

    metersfrom enclosing functions. It also hasinheritance lookup based

    on the value of self at the time the function object wascreated. This

    meansthat a function object hasaccessto all variables, including

    inherited slots, that are available to the code that created the function

    object.

    Thisinheritance lookup isimplemented bystoring a message con-

    text aspart of a function object. Thismessage context containsthe

    value ofself at the time a function object iscreated. Calling a func-

    tion object usesthe value ofself stored in itsmessage context.

    The major difference between calling a function object and sending a

    message isthat sending a message setsthe value ofself to the frame

    where the message issent. Thus, sending a message causesthe mes-

    sage context of the function object to be ignored.

    There are times, however, when you need to use inheritance in a

    function that hasnot been executed in response to a message send. A

    common case of thisin Newton programming isfound in the implemen-

    tation of filing. Filing isusuallyimplemented bycreating a cursor thatcontainsavalidTest. The cursor isusuallycreated when the appli-

    cation opens:

    app.viewSetupFormScript := func()begin

    self.theCursor := Query(, {type: 'index,

    validTest: func(e)begin

    return labelsFilter = '_all orlabelsFilter = e.labels;

    end,});

    en d

    The cursor savesthevalidTest function object and callsit every

    time the cursor ismoved. When thevalidTest iscalled, the

    labelsFilter variable islooked up first asa local, and then usinginheritancebased on the value ofself at the time thevalidTest

    function object was created. Sinceselfwasthe application view

    when thevalidTestwascreated, self isset to the application

    base view when thevalidTest iscalled.

    SENDINGAMESSAGECHANGESTHEMESSAGECONTEXTSending a message changesthe message context, thusthe major differ-

    ence between sending a message and calling a functionhas to do with

    the value ofself. When a message issent, self isset to the frame

    that wassent the message. When a function iscalled directly,self is

    based on the message context of the function object.

    Function Objects Created at Compile Time Have No LexicalEnvironment or Message Context

    When a top-level function object iscreated at compile time either

    asa slot in a template editor, or in the top-level of the Project Data file

    the lexical environment and message context are empty. ( Technically,

    the lexical environment and message context exist, but areniled out

    after the function iscreated). Thisisimportant to remember when you

    are creating standalone function objects(those that have no references

    to your package). Examplesof such function objectsare those that will

    be copied to a soup, or the one used asapostParse routine for

    Intelligent Assistance. If you use a function object that hasa non-

    emptymessage context here, the whole message context will be copied

    into the soup (or into memoryin the case of Intelligent Assistance). Not

    a good idea, in most cases. Thus, for function objectswhich need to

    execute independentlyof your package, make sure theyare created at

    compile time, rather than run time.

    SUMMARYIn NewtonScript, function objectsare first-classobjectswhich have

    accessto the environment that existsat the time theyare created. They

    have accessto variablesin enclosing functions, aswell asto inherited

    slotsbased on the value ofself at the time the function object was

    created. Because of these characteristics, you can do thingswith func-

    tion objectsthat can not be done in most other languages.

    If you have an idea for an article you'd like to

    write for Newton TechnologyJournal, send it via

    internet to: piesysop@ applelink.apple.com

    or AppleLink: PIESYSOP

    Newton Technology Journal February 1995

    9

    N

  • 7/28/2019 Newton Technology Journal: Volume 1, Number 1

    10/24

    February 1995 Newton Technology Journal

    10

    INTRODUCTION

    The infrared (IR) beaming device that isembedded in the head of the

    Newton can be used to send messagesbetween Newtons. You may

    have alreadyused thisfacilityto "Beam" a note or card from your

    Newton to another. Thisarticle will show how to send messagesand

    data directlyfrom your application. Another use of the IR beam isto

    control remote devicessuch asa VCR or TV. You will learn how to set

    up a control pattern that will control a CD player.

    IR BeamingProtocolBeaming between Newtonsrequiresa half-duplex, asynchronous

    framed protocol. Thismeansthat onlyone Newton can send messages

    at a time. Deliveryof the message to the receiver cannot be not guar-

    anteed. If the Newtonsare not pointed correctly, the data can't be

    passed between them. However, if the data doesarrive, the message is

    guaranteed to be complete and correct. The sending Newton will try

    for about two minutesto complete a transmission before giving up and

    throwing an exception.

    The IR Endpoint

    Asisthe case with the other Newton communication tools, the focal

    point isthe endpoint through which NewtonScript linksto the outside

    service. The IR Beaming endpoint service isdefined asfollows:

    myEndPoint:= { _proto: protoEndpoint,configOptions: [

    {label: kCMSSlowIR,type: 'service,opCode: opSetRequired }],

    }

    Although two Newtonspassing IR information define the endpoint

    in the same way, theyconnect the endpoint differently. The passive

    receiver must set the endpoint to wait for a connection using:

    myEndPoint:Listen(nil);

    while the active sender must connect the endpoint using:myEndPoint:Connect(nil,nil)

    If the two Newtonsare unable to make a successful connection within

    2 minutes, an exception error -38001 iscreated. To avoid thiserror condi-

    tion, and to allow a user to abort the connection in a more reasonable

    time frame, like 10 seconds, you maywant to connect using

    AddDeferredActionandAddDelayedAction. The

    AddDeferredActionmethod happensalmost immediately, but

    runsin a separate Newton task thread, allowing you to continue with

    your own code at the same time that the connection attempt processis

    being handled. For the active sending Newton, the complete endpoint

    creation and connection functionsare asfollows:TryToConnect: func() begin

    err := myEndpoint:Instantiate(myEndPoint,nil);if err then begin

    :HandleError();return:end;

    AddDeferredAction(func(ep) ep:Connect(nil,nil),[myEndPoint]);AddDelayedAction( func(ep) begin

    if ep:State() < 5 then begin // Not Connectedep:Abort(); // Kill the connection attemptAddDelayedAction( func(ep) ep:Dispose(), [ep], 500 ;

    // Remove the endpointGetRoot():Confirm("","Try Again?", base,

    'ConnectAgain);end;

    end,[myEndPoint], 10000);

    end,ConnectAgain: func(OK) begin

    if OK thenTryToConnect();

    end,

    TheConfirmmethod, which isaccessed through the root,

    throwsup a dialog with a message (TryAgain?) in which the user can

    tap on OK or Cancel. It then sendsa message (ConnectAgain) to your

    base view with an argument oftrue ornil.

    Message Sending Between Newtons

    Because of the half-duplex nature of the IR beam, a Newton must

    alternate between being a sender and a receiver. Thismust be part of

    the high-level protocol established between the two Newtonsbyyour

    program.

    To change from being a receiver to a sender, you must kill the cur-

    rentinputSpecand set the nextinputSpec tonil:

    myEndPoint.nextInputSpec := nil;myEndPoint:SetInputSpec(nil);

    Onlythen can you begin to output data. IR output must specifythe

    start and end of the data using system defined flags:

    thekFrame flag indicatesa low-level data frame (nota Newtonframe)

    thekMore flag indicatesmore data to come

    These flagsare used asargumentsto theOutput and

    OutputFramemessagespassed to the endpoint.

    myEndPoint:Output("the beginning", kFrame+kMore);myEndPoint:Output(" and almost end", kFrame + kMore);

    Beam me up, Newt!

    Newton Communications

  • 7/28/2019 Newton Technology Journal: Volume 1, Number 1

    11/24

    Newton Technology Journal February 1995

    11

    myEndPoint:Output(unicodeCR, kFrame);

    The receiver must match the framing flag bysetting therecvFlags

    slot in the endpoint tokFrame:

    myEndPoint:= { _proto: protoEndpoint,configOptions: [

    {label: kCMSSlowIR,type: 'service,opCode: opSetRequired }],recvFlags: kFrame,

    }

    Since Newtonsknow about framesthat can hold a lot of information, i t

    makesgood sense to build a transaction of data asa frame, such as:

    trade := { action: "Buy",security: "appl",quantity: 11000,price: 85.25,trader: "SJ",allocation:[ {client:"XYZ Co", quantity:1000},

    {client:"ABC INC", quantity:5000},{client:"NewtDTS", quantity:5000}

    ],}

    and then transmit the entire transaction asa frame using

    OutputFrame:

    myEndPoint:OutputFrame(trade, kFrame);myEndPoint:FlushOutput(); // good ideawith frames to flush

    Using frames, the state machine can be quite complex, but easyto fol-

    low.

    The complexitylieswithin the content of the frame, not in the external

    state machine. A singleinputSpeccan handle all incoming messages

    and decide what to do, based on the value of a single keyslot such as

    'action.

    It should be noted that for the time being, you must useOutput

    at least once before usingOutputFrame. Failure to do so causes

    an error.

    TRACKINGTHEELUSIVENEWTONEarlier, it wasnoted that the IR endpoint cannot guarantee deliveryof a

    message if the Newtonslose IR contact with one another. If thislossof

    contact occursduring a transmission, the receiving Newton will wait

    happilyforever, while the sending Newton will either freeze, or time out

    with an error after about two minutes.

    To avoid thiserror condition, the sending Newton needsto use an

    AddDeferredAction method and an

    AddDelayedActionmethod similar to the onesdescribed for

    connecting. The difference will lie in determining whether the messagedid or did not get through, and what resulting action to take. Ideally,

    the action should be to allow the two Newtonsto search for each

    other, and when contact isreestablished, to resend the original mes-

    sage.

    The following code example isa description of how to conduct such

    a search for that elusive Newton. The sender triesto output a repeat-

    ing message at regular intervals, in thiscase, everysecond. The mes-

    sage containsthe delayin 1/60 of a second since the last time the mes-

    sage wassent. If the last message got through successfully, thiswould

    be a value of 60.

    viewIdleScript: func() beginif quitSearch then return nil;:SendTest();1000;end,

    SendTest: func() beginlocal thisTick := Ticks(); // aclock time in 1/60 secondif NOT lastTick then // lastTick is initialized to nil

    local delay := 60;else

    local delay := thisTick - lastTick;:SetNextValue(thisTick); // set new value for lastTickmyEndPoint:Output(UnicodeSTX,kFrame + kMore);myEndPoint:Output(NumberStr(delay),kFrame + kMore);myEndPoint:Output(UnicodeETX,kFrame);myEndPoint:FlushOutput();end,

    The receiving Newton decodesthe sender'sdelaybetween mes-

    sagesand comparesthiswith the delayat the receiving end. The

    InputScriptmethod computesa value for a gauge meter, based on

    the difference between the two delays.

    waitForTest: {inputForm: 'string,endCharacter: unicodeETX,discardAfter: 10,

    InputScript: func(endpoint, s) beginlocal thisTick := Ticks();local meterVal := 0;local stx := "\u0002\u";local startStx := StrPos(s,stx,0);

    if startStx then // did we get whole message?begin// extract sender's delaybetween messageslocal txt:=SubStr(s,startStx+1,StrLen(s)-

    startStx-2);local val:=StringToNumber(txt);

    local expected := endpoint:GetLastTick();if expected then begin // not the first?

    expected := thisTick - expected; // receiver's delay// compare sender delay& receiver delaymeterVal := Max(10,100-(val-expected));

    end;else

    meterVal := 70; // first test messageend;

    elsemeterVal:=50; // onlypart of message

    endpoint:UpdateGauge(meterVal);// update gauge meter

    endpoint:SetNextValue(thisTick); // set new// value for lastTick

    end,

    },

    The receiver usesa gauge view to displaythe degree of contactbetween the two Newtons. The gauge ispushed up asthe difference

    between the sender'sdelayand the receiver'sapproacheszero, and is

    pushed down a small amount at intervalsof half a second.

    SearchGauge := {viewValue: 0,minvalue: 0,maxvalue: 100,...,viewIdleScript: func() begin

    local newValue := Max(0, self.viewValue - 5);SetValue(SearchGauge, 'viewValue, newValue);500;

  • 7/28/2019 Newton Technology Journal: Volume 1, Number 1

    12/24

    February 1995 Newton Technology Journal

    12

    end,}

    When the gauge stabilizesat a high value, the receiver getsa mes-

    sage that contact hasnow been reliablyestablished.

    UpdateGauge: func(newValue) beginif (newValue >= 80) AND(SearchGauge.viewValue >= 80) then

    :PutDataInStatusArea("Locked on target\nYou can Stop Search ");

    else:PutDataInStatusArea("Searching...");

    SetValue(SearchGauge, 'viewValue, newValue);end,

    At thispoint, the sender and receiver would cancel the search and

    return to normal operation. If thistype of code isincluded in an applica-

    tion, the user will feel much more in control and a good deal lessfrustrat-

    ed. Forcing the user to pressthe reset button isan option of last resort

    and much to be avoided.

    ANEXAMPLEOFIR USINGABOARDGAMEAn excellent wayto develop your IR skillsisto build a simple game in

    which movesand resultsare passed back and forth asframesof informa-

    tion. Thisgame contains: a board view, in which the game isplayed; a

    statusview, to tell the player what isexpected next; a glance view, to

    provide transitorymessageson the successof the last move; and some

    buttonsto set the game in motion.

    The 'Arena' is the Board view. The space below the buttons is a

    protoGlance view for transient information.

    The game isverysimple:

    Each player placesfive pieces( spots) on their board

    The playersdecide who goesfirst, and tap either PlayFirst or PlaySecond

    Each player takesa turn to tap once on the board, to tryto locate

    the other playerspieces

    The game continue until one player haslocated all five pieceson

    the other playersboard

    The state machine breaksdown into four parts:

    1. Setup

    Get tapson Board and create playing pieces

    Connect playersand handshake for proper connection

    Change to MyTurn if PlayFirst,

    Change to Their Turn if PlaySecond,

    2. MyTurn

    If all pieceshit, send win message and change to end of game

    Displayhistoryof myshots: missesasO and hitsasX

    Get tap on board and send shot

    Wait for a hit or missmessage and displaythe result

    Change to Their Turn

    3. Their Turn

    Displaymypiecesand historyof opponent'sshots

    Wait for next message (shot or win)

    If a win message, change to end of game

    Else Displaynew shot,

    Determine if a hit,

    Send hit or missmessage

    Change to MyTurn

    3. End of Game

    Disconnect

    Prepare for new game setup

    Thisscenario describesthe fundamentalsof almost all board games,

    including Chess, Checkersand Go.

    REMOTEIR

    Remote IR isusing the IR beam to control a VCR, TV, CD Player orother device.

    It isa one-way broadcast of an IR signal. The Newton filtersincom-

    ing remote signalsat the hardware level, so there isno wayto receive

    input from a remote device.

    There isalso no particular listener specified and no guarantee of

    good delivery, even if the sender pointsthe beam in the right direction.

    Aswith other remote controllers, thismeansthat if the device doesn't

    respond the first time, a user must pressthe button again. Given the

    number of timesthishappensin dailylife when all that isbeing trans-

    mitting isabout 2 bytesof command, you can appreciate whya three-

  • 7/28/2019 Newton Technology Journal: Volume 1, Number 1

    13/24

  • 7/28/2019 Newton Technology Journal: Volume 1, Number 1

    14/24

    February 1995 Newton Technology Journal

    14

    Newton MessagePad to put evidence-based, background and

    portable content into the handsof itsresidentsfor the purpose offacilitating patient evaluation and management in a project called

    Constellation.

    The goal isto provide residentswith immediate accessto general

    background information on disease processes. A collection of specially

    developed toolsassist professionalsin navigating thiscontent. The

    Constellation project will put information toolsat the touch of a resi-

    dentsfingertips, giving him or her immediate accessto general disease

    and management descriptions, referencesto the recent and relevant

    medical literature, and accessto a selected set of medical guidelines

    all in order to applythiscontent to their patients. Traditionally, to

    accessthisinformation, the resident relieson a library, textbooks, com-

    putersor fellow residentsand must take the time to go and research

    the needed information. Now with the Newton, physicianscan tap into

    the equivalent of over 1,500 pagesof medical and drug information in

    the hospital corridor or at a patient'sbedside. In lesstime than it

    would take to do anykind of research, a doctor can flip open hisor her

    Newton and with a few stylustapson the screen, learn about the ramifi-

    cationsof prescribing a particular drug, research a rare congenital dis-

    ease, or browse through a seriesof medical journal articles.

    Dr. Steven Labkoff, an internist and head of the DecisionsSystems

    Group at Brigham, isalso head of the Constellation Project and is

    responsible for some of the custom programming of the units. He cred-

    itsSandeep Shah, President of K2 Consultant, Inc. with devising the

    data compression and search strategyprograms.

    Shah and Labkoff chose the Newton MessagePad for the project at

    the hospitalsfor a number of reasons. Among them, the Newton form

    factor provided the right size with the appropriate amount of comput-

    ing power to provide for the physiciansneeds. While there were smaller

    form factorsavailable in other products, none were asflexible.

    Newtonstouch input technologyappealed to a physicianskeyboard

    shyness. Additionally, the ease of programming with Newton BookMaker wasveryappealing. Shah needed to reference information from a

    varietyof sourcesin a number of different formats. The fact that he

    could deliver everything from outlinesto full chapterson specific sub-

    jects, with full search and find capabilities, and with fontsembedded in

    data, allowed deliveryof a fast, user friendlyinterface that doctorsare

    comfortable using.

    Currently, the Newtonscontain an electronic version of the

    American College of Physicians (ACP) Medical Knowledge Self

    Assessment Program, the American College of Physicians Journal Club,

    the Electronic MonthlyPrescribing Guide, handbooksand residency

    phone booksfor both Brigham and Womensand Massachusetts

    General hospitals, and the Intensive Care Unit/Cardiac Care Unit Drug

    Reference Book. All of these publicationsare being referenced on a

    regular basisbyresidentsin the Constellation program.

    Shah commented that Newton hasthe technologythat we need

    todayin order to deliver on the product we want, without relying on

    the promise of future technologies. He viewsthe Newton asprovid-

    ing great opportunitiesfor developersinterested in bringing technol-

    ogyinto a number of vertical markets.

    The Constellation project hasdelivered a wide varietyof informa-

    tion into the fingertipsof doctorsat Brigham and WomensHospital

    and at MassachusettsGeneral Hospital. It hasbeen a successat

    demonstrating how Newton technology can be used to solve previ-

    ouslyunsolvable problemswhile creating new marketsfor develop-

    ersto explore and own in the process.

    Developersinterested in creating and conquering new markets

    should rethink the wayproblemsare solved today. The first step isto

    think about what would a perfect world solution be if you didnt have

    to keep anytechnical or computer related considerationsin mind. The

    continued from page 1

    Newton Deliversfor Vertical Markets

    N

    To request information or an application on Apple'sNewton developer programs,

    contact ApplesDeveloper Support Center

    at 408-974-4897

    or Applelink: DEVSUPPORT

    or Internet: devsupport@ applelink.apple.com.

  • 7/28/2019 Newton Technology Journal: Volume 1, Number 1

    15/24

    Newton Technology Journal February 1995

    15

    covered in Apple PIEsclass: Newton Programming: Communications.

    HARDWAREThe first and most commonlyused piece of communicationshardware

    in the Newton isan SCC ( Serial Controller Chip) , identical to the one

    used on most Macintoshes. Thisiswhat isused for serial connections,

    modem connectionsand AppleTalk. While the SCC chip can be pro-

    grammed to run at a varietyof speedswithout specialized hardware or

    cabling, it cannot normallybe used at speedsof over 19,200 to 38,400

    bps(bitsper second).

    The Newton also hasa built-in infrared transceiver. Thiscan be used

    to communicate between Newtonsand can also be programmed to

    interact with remote IR devicessuch asTVs, VCRs, and so on.

    The last hardware interface isthe PCMCIA slot, which can be used to

    add such thingsasfax modems, cellular communicationscards, and so

    on. These cardsmust have specialized driverswritten for them; to date

    there have been no documentsor toolsrelated to thisavailable from

    Apple. However, asthisarticle isbeing written, the Driver Developers

    Kit ( DDK) isbeing put into Alpha testing byApple for release sometime

    down the road. Driverswill be written in C+ + using the DDK.

    ARCHITECTUREFigure 1 showshow the Newton isorganized. The top layer showssys-

    tem software written in NewtonScript. Thismostlyconsistsof prototypes

    and other NewtonScript interfacesto the variousservices. The next layer

    down showsthe OS software, which isprimarilywritten in C+ + . The

    last layer isthe Newton hardware including the SCC and the IRDCU

    (infrared controller).

    Figure 1

    For communications, the important thing isthat there isa high-

    level communicationsinterface written in NewtonScript the end-

    points and a low-level communicationsinterface communica-

    tionstasks, toolsand drivers written in C+ + , which talksdirectly

    to the hardware.

    The NewtonScript interface providesa common interface to all

    typesof communicationshardware via a virtual connection called an

    endpoint.To create and use an endpoint, appropriate connection

    parametersmust be established to describe the endpoint. For exam-

    ple, for a serial connection you must specifybaud rate, stop bits,

    parity, and so on, before you can connect to the service. Once a

    connection isestablished, an endpoint actsasa pipeline down

    which bytesare sent or received.

    The stepsnecessaryto create and use an endpoint are asfollows:

    1. Define the endpoint frame, including the type of communications

    service, the particular connectionsoptions(baud rate, error cor-

    rection, and so on), the methodsfor receiving data through the

    endpoint, and any other slotsand methodsyou may want to

    accessfrom the endpoint.

    2. Instantiate the endpoint. Thiscreatesa NewtonScript object and

    notifiesthe low-level communicationscode of the existence of

    continued from page 1

    Newton Communications

  • 7/28/2019 Newton Technology Journal: Volume 1, Number 1

    16/24

    February 1995 Newton Technology Journal

    16

    the endpoint.

    3. Open a connection to the hardware through which communica-

    tionscan take place.

    4. Send and receive data through the endpoint. Sending isdone bycalling theOutput method. Receiving isdone byestablishing

    a frame describing expected input format and containing an

    inputScriptmethod or other input methods.

    5. Disconnect the endpoint. When you are done, disconnect after

    first aborting any pending incoming transfers.

    6. Destroy the endpoint. Having disconnected successfully, the

    endpoint maynow be destroyed. Thisdestroysthe NewtonScript

    object and the connection to the low-level communications

    code.

    Detailsand code examplesfor each of these stepswill be dis-

    cussed in depth in thisarticle.

    The Newton hasa true multi-tasking micro-kernel-based architec-

    ture. Figure 2 showsseveral of the taskswhich commonlyrun under

    direction of the micro-kernel task scheduler.

    Figure 2

    There are several thingshere that have an impact on communica-

    tionsprogramming. The first and most obviouspoint isthat there

    are separate tasksfor the low-level CommunicationsManager and for

    the CommunicationsTool that iscurrentlyactive. An equallyimpor-

    tant though lessobviousfactor isthat there isonly one

    NewtonScript task. Thismeansthat all NewtonScript code runsin the

    same task space, though not necessarilywithin the same application

    context.For example, in doing communicationsprogramming you may

    provide an exception handler that dealswith communicationsprob-

    lemsthat occur after an endpoint isconnected. Thisexception han-

    dler will be called from the root view and so maynot have accessto

    your applicationsslots, framesand methods. Because of this, it may

    be necessaryto find your application from the root view. For exam-

    ple,

    GetRoot().|MyApp:MyCompany|:AMethod

    Figure 3a showsthe relationship between the NewtonScript task

    and the low-level communicationstaskswhen an endpoint isinstan-

    tiated. A message issent from the NewtonScript task to the

    CommunicationsManager task to open a communicationsconnec-

    tion.

    Figure 3a - Duri ng Instantiation of Endpoint

    Figure 3b showsthe response of the CommunicationsManager to

    thisrequest. It haslaunched the appropriate communicationstool

    for the type of connection specified in the endpoint frame, which in

    turn hasestablished the appropriate connection with the hardware.

    Figure 3b: Response From Instantiation

    Figure 3c showsthe next step of connecting an endpoint to the

    device. Here the Newton endpoint sendsa connection request to

  • 7/28/2019 Newton Technology Journal: Volume 1, Number 1

    17/24

    Newton Technology Journal February 1995

    17

    the Comm Tool which waslaunched when the endpoint wasinstanti-

    ated. In response, the Comm Tool sendsa response to the Newton

    task describing the successof the request.

    Figure 3c: Connection

    The significance of thissequence isprimarilyto point out that

    communicationswith hardware isdone through a separate task from

    the NewtonScript task. Thismeansthat all communication to the

    device istrulyasynchronousto your code. You cannot be certain

    when a communicationsaction occursor of the statusof the connec-

    tion represented bythe endpoint, without explicitlychecking the

    statusof the endpoint. It isfor thisreason that in certain code you

    must check the statusafter you have sent a message to the endpoint

    but before you do something drastic to i t.

    An example would be to abort ongoing data transfersprior to dis-

    connecting and destroying the endpoint. Thisalso meansthat in

    debugging the endpoint you must take care not to make assump-

    tionsabout when an error might occur, asi t ispossible that the last

    command sent to the endpoint hasnot yet executed.

    Another lessobviousimplication of the sequence of instantiation

    described in the preceding figuresisthat at anytime onlyone end-

    point can be active. Otherwise the separate NewtonScript endpoint

    methodscollide. Thismeansthat when an endpoint isinstantiated

    there can be no other instantiated endpoints.

    For example, you should not have an IR endpoint and a serial

    endpoint active at the same time. From a programming point of view

    thisisparticularlyimportant, asit meansthat you cannot use NTKs

    Inspector to debug endpoint code, because it usesa serial endpoint

    to talk to the Newton.

    ENDPOINTSAsmentioned before, endpointsare virtual connectionscreated

    in NewtonScript. What thismeansisthat in theory, once an end-point iscreated in NewtonScript and a service isconnected, the

    same code could be used in all casesto send and receive data. In

    practice, thisisalmosttrue.

    Creating an Endpoint

    To create an endpoint you must first define a NewtonScript frame

    which describesthe endpoint you wish to create. You do thisbycre-

    ating a frame which hasa_proto slot with a value of

    ProtoEndpoint, and a seriesof other slotsthat define the char-

    acteristicsof the endpoint. Thisistypicallydone in the

    viewSetupFormScriptmethod of the base view, so that the

    endpoint isdefined the entire time an application isrunning.

    For example, below isan endpoint definition you might use for a

    serial endpoint:

    mySerialEndpoint := {_proto:protoEndpoint,configOptions: [

    { label: kCMSAsyncSerial,type: 'service,opCode: opSetRequired },

    { label: kCMOSerialIOParms,type: 'option,opCode: opSetNegotiate,data: { bps: k9600bps,

    databits: k8DataBits,stopBits: k1StopBits,parity: kNoParity } },

    { label: kCMOInputFlowControlParms,type: 'option,opCode: opSetNegotiate,data: { xonChar: unicodeDC1,

    xoffChar: unicodeDC3,useSoftFlowControl: true,useHardFlowcontrol: nil } },

    { label: kCMOOutputFlowControlParms,type: 'option,opCode: opSetNegotiate,data: { xonChar: unicodeDC1,

    xoffChar: unicodeDC3,useSoftFlowControl: true,useHardFlowcontrol: nil } },

    ],}

    Note thatconfigOptions isan arrayof frames, each of which

    definessome aspect of the endpoint. TheconfigOptions

    framescontain different data depending on what theyare setting, but

    theyall have a frame with atype slot whose value isthe symbol

    'service. Thisidentifiesthat thisoption describesthe kind of

    endpoint being established (for example, SlowIR, Serial, AppleTalk, and

    so on) . Thelabel slot of thisoption frame namesthe service. In the

    example above, thisisthe valuekCMSAsyncSerial, a system

    constant defining a serial connection.

    EachconfigOptions array also hasanopCode slot which

    describeswhether the particular option must have the value set

    (opCode:opSetRequired) or open to negotiation between

    the Newton and the hardware (opCode:opSetNegotiate) .

    A required option must be exactlywhat isspecified, whereasa nego-

    tiable option meansyou can accept something lessthat what isasked for. An example of a negotiated option isthe baud rate setting

    shown in the previousexample. You areaskingfor a connection of

    9600 bps, but since thisisa negotiable option you can accept a data

    rate of lessthan 9600.

    Asyou can also see from the example, the third component of a

    configOptionsarrayisthedata slot. Thisslot isusually

    another frame which providesthe necessaryinformation for the

    option being set. You must read the documentation in the Newton

    ProgrammersGuide, Chapter 14, to find out what data ( if any) is

  • 7/28/2019 Newton Technology Journal: Volume 1, Number 1

    18/24

    February 1995 Newton Technology Journal

    18

    needed for each option.

    While you typicallyset the optionsonce when defining an end-

    point, theymaychange later asyou instantiate and connect the

    endpoint (or even later after sending or receiving data, though this

    isnot recommended). However, i t isfar more common to set the val-

    uesonce when defining the endpoint and leave them thereafter.You should also beware that not all optionscanbe successfully

    changed after the endpoint isinstantiated. Which onescannot be

    changed?Thishasnot yet been documented so if you wish to trythis,

    beware, asyou might crash unexpectedly. Just to make it interesting,

    the successor failure of changing an option isdependent on the com-

    munication tool in use ; what workswith one endpoint maynot work

    with another.

    Note that you mayadd other slotsto your endpoint. Asyou will

    see later, there are at least a couple more slotsyou will typicallywant

    to add in order to receive data and handle endpoint specific excep-

    tions.

    Asdiscussed in the previoussection, before connecting an end-

    point to a service you must first instantiate it, in order to create a

    NewtonScript object and to open the correct communication tool.

    You do thisby sending theInstantiate message to the end-

    point. For example:

    mySerialEndpoint:Instantiate(mySerialEndpoint, nil);

    The second argument isan optional set ofconfigOptions

    similar to those just discussed. Byspecifyingnil for thisargument,

    you are simplyusing the onesdefined in mySerialEndpoint.

    Having instantiated the endpoint, you can now connect i t by

    sending theConnectmessage:

    mySerialEndpoint:Connect(nil, nil);

    Here the first argument isa frame which describesthe addressof

    the thing you wish to connect to; in the case of a serial endpoint,

    you need no addressasyou are connecting to the device on the

    other end of the cable. However for a modem endpoint, thiswould

    probablybe the phone number you wanted to dial; an AppleTalk

    connection would have the NBP of the entityyou wished to connect

    to. An example of an addressframe might be:

    anAddress:= {type:'address,label:kCMARouteLabel,opCode:opSetRequired,data:{addressType:kNamedAppleTalkAddress,

    addressData:"LlamaFarm:LlamaServer@*"}

    The second argument isagain an opportunity to change the end-

    point optionsand aswithInstantiate, you typically passa

    nil value.

    In most casesthisisall that isnecessaryto connect an endpoint,

    and if successful, you would now be open for business. However, as

    detailed in the related article in thisissue, since infrared beaming is

    half-duplex (cannot send and receive at the same time), the receiving

    device must send aListen message to itsendpoint before a con-

    nection can be established.

    Sending Data

    There are two endpoint methodswhich maybe used to send data

    out from the Newton: Output andOutputFrame. The

    OutputFramemethod isused to send flattened frames; that is,

    NewtonScript framesin which all of the referenceshave been

    resolved into a stream of bytes. While thisisuseful, it relieson bothsender and receiver knowing that a frame iscoming. Since the exact

    format of a flattened frame isnot documented, thismethod isgener-

    allyonlyuseful when sending between two Newtons.

    For thisreasonOutput isusuallyused in all casesexcept for

    Newton-to-Newton communications. The exact format of the

    Output andOutputFramemethodsisasfollows:

    Output(data, flags)OutputFrame (data, flags)

    where thedata argument isthe data being sent and theflags

    argument isused to control output in the infrared case. O ther than

    in infrared communicationsthen, theflag argument will benil.

    The data which can be sent usingOutput includesNewton

    strings, integers, and binary arrays. In the case of stringsall outgo-

    ing data will go through a Unicode-to-ASCI I translation, asall

    Newton stringsare kept internallyin Unicode (16-bit character val-

    ues) format, but it isassumed that anyexternal device will be expect-

    ing ASCII. I f you wish to send the raw valueswithout thistranslation

    you can send an arrayof character values. Since the arrayisnot a

    string, it will be sent asraw Unicode values.

    Currently thisUnicode-to-ASCI I translation isthe onlytranslation

    available and isthe default, but in the future you maybe able to

    specify your own translation tables.

    In NewtonScript, integersare represented as30-bit values.

    However, when integersare sent from the Newton, onlythe least sig-

    nificant byte isactuallysent. Thismeansthat to send a 30-bit value

    you must send 4 values, one for each byte in the integer. Thisis

    shown below:

    ep:Output(len >> 24, nil) // output 1st (MSB) byte

    ep:Output(len >> 16, nil) // output 2nd byte

    ep:Output(len >> 8, nil) // output 3rd byte

    ep:Output(len, nil); // output 4th (LSB) byte

    To useOutputFrame,you simplypassa reference to the frame

    you wish to send asthe data and again use anil for the flags argu-

    ment unlessyou are sending the frame over an infrared link. A brief

    example of thisisshown here:

    aFrame:={ slot1:4, slot2:"abcd" };mySerialEndpoint:OutputFrame(aFrame,nil);

    When outputting data, you should flush the output channel in

    order to avoid losing data in an internal buffer i f something should

    go wrong. Thisisdone by sending the messageFlushOutput

    to the endpoint.

    Receiving Data

    To receive data through an endpoint you must set up a special

  • 7/28/2019 Newton Technology Journal: Volume 1, Number 1

    19/24

    Newton Technology Journal February 1995

    19

    frame called aninputSpecthat hasin it a method that will be called

    when a certain input condition isreached. The input conditionsare

    described in thisframe aswell.

    You then use the methodSetInputSpec(inputSpec) to

    notifythe endpoint that thisistheinputSpecyou want for

    future input. Note that you may( and probablywill) change theinputSpec that iscurrent asyour application runs. Complex

    state machinescreated bychaininginputSpecswill be dis-

    cussed in a future article.

    An exampleinputSpec isshown in here:

    receiveNameSpec:= {inputForm: 'string,endCharacter: unicodeCR,InputScript: func (theEndpoint, inputStr)begin

    baseView.nameSlot:=inputStr;en d

    };

    ThisinputSpecwill now be discussed in detail.

    There are a number of conditionsthat can be used astriggersfor

    the input method. The commonest of these isto use a single character

    specified asbytheendCharacter slot of theinputSpec

    frame. ThisessentiallykeystheInputScript method to be called

    when the character specified isreceived. In thiscase the character isa

    carriage return.

    TheinputForm slot defineswhat the expected input will be.

    In thiscase the'string symbol specifiesthat the input isexpected

    to be charactersand, since the Newton usesthe Unicode character

    set for strings, the input will be automaticallyconverted to Unicode

    from ASCII.

    TheInputScript slot isthe method that iscalled when the

    trigger condition ( in thiscase an incoming carriage return charac-

    ter) occurs. It iscommon for aninputSpecsInputScript to

    activate a differentinputSpec.

    There are several other triggersthat maybe used the most

    common issetting an input length of charactersreceived. Thisis

    done by setting a slot in theinputSpec frame called

    byteCountwith an integer value that specifiesthe number of

    input charactersto be received before calling theInputScript.

    There are other waysto handle input which will not be covered

    here. However, an important point in all input schemesisthat the

    sender and the receiver must know what to expect. In other words,

    theymust have a higher-level protocol to coordinate the format and

    meaning of successive data received.

    You set theinputSpec asthe one currentlyin use with thefollowing code:

    ep:SetInputSpec ( receiveNameSpec );

    NEWTONSERIAL& MODEMCOMMUNICATIONS

    Asdescribed earlier in thisarticle, all Newton communications

    software isdirected through an endpoint. Connection, input and

    output are all channeled through thisvirtual software device. An

    endpoint can handle manyforms, including infrared and AppleTalk,

    but thisarticle isdevoted to itsform asa serial and modem service.

    On the hardware front, the Newton isequipped with a serial plug

    (mini DI N-8) which allowsit to link via a cable to either a desktop

    computer serial port or to a modem.

    Serial communication maybe used to move data to and from a

    desktop computer or a data-gathering device such asa scientificprobe or an industrial sensor.

    Modem communicationscan be used to hook into the myriad ser-

    vicesnow being provided worldwide, including the Internet, and for

    sending data to an office LAN, or placing an order with the local gro-

    cery store.

    Serial Communications

    The endpoint in NewtonScript isthe keyto linking your applica-

    tion to the outside world. Ashasbeen shown earlier in thisarticle,

    the endpoint isan interchangeable object that allowsyour code to

    talk to remote devices, without requiring you to make changesin

    your application code.

    The minimum definition of a serial communicationsendpoint

    includesa statement that it isan asynchronousservice, and an

    option describing the speed of the communicationslink, itsparity

    and number of data and stop bits.

    mySerialEndpoint := {_proto:protoEndPoint,configOptions: [

    { label: kCMSAsyncSerial,type: 'service,opCode: opSetRequired },

    { label: kCMOSerialIOParms,type: 'option,opCode: opSetNegotiate,data: { bps: k9600bps,

    dataBits: k8DataBits,stopBits: k1StopBits,

    parity: kNoParity },],

    };

    Note that all namesstarting withk , such as

    kCMSAsyncSerial are defined system constants. Also note

    that if the value ofopCode isopSetNegotiate (another

    system defined constant) , it meansthat when the requested values

    such as9600 baud, are not available, a reasonable substi tute will be

    accepted. The Newton supportsasynchronousspeedsfrom 300

    baud up to 57,600 baud.1

    In thebps slot you can use anyof the following:

    CONSTANT VALUEk300bps 300k600bps 600k1200bps 1200k2400bps 2400k4800bps 4800k7200bps 7200k9600bps 9600k12000bps 12000k14400bps 14400k19200bps 19200k38400bps 38400k57600bps 57600

  • 7/28/2019 Newton Technology Journal: Volume 1, Number 1

    20/24

    February 1995 Newton Technology Journal

    20

    In thedataBits slot, you can use the following constants:

    CONSTANT VALUE(# of DataBits)k5DataBits 5

    k6DataBits 6k7DataBits 7k8DataBits 8

    In thestopBits slot, you can use the following constants:

    CONSTANT VALUE(# of Stop Bits)

    k1StopBits 0k1pt5StopBits 1k2StopBits 2

    In theparity slot, you can use the following constants:

    CONSTANT VALUEkNoParity 0kOddParity 1kEvenParity 2

    FlowControl

    Flow control for the serial endpoint can be handled byeither soft-

    ware or hardware. For example, to use XON/XOFF software control for

    your endpoint, add the following optionsto theconfigOptions

    array:

    { label: kCMOInputFlowControlParms,type: 'option,opCode: opSetNegotiate,data: { xonChar: unicodeDC1,

    xoffChar: unicodeDC3,useSoftFlowControl: true,

    useHardFlowControl: nil } },{ label: kCMOOutputFlowControlParms,type: 'option,opCode: opSetNegotiate,data: { xonChar: unicodeDC1,

    xoffChar: unicodeDC3,useSoftFlowControl: true,

    useHardFlowControl: nil } },

    You maywell recognize UnicodeDC1 ascontrol-Q or ASCII 13hex,

    and UnicodeDC3 ascontrol-S or ASCI I 11hex. Note that software

    handshaking can drop charactersif a modem isoverrun, ( that is, if a

    modem isoverrun before the XOFF can be sent) so for high transfer

    rates, hardware handshaking may be necessary and issupported in

    the Newton.

    The following constantsare useful for specifying Unicode characters:

    CONSTANT VALUEunicodeNUL $\u0000unicodeSOH $\u0001unicodeSTX $\u0002unicodeETX $\u0003unicodeEOT $\u0004unicodeENQ $\u0005unicodeACK $\u0006unicodeBEL $\u0007

    unicodeBS $\u0008unicodeHT $\u0009unicodeLF $\u000AunicodeVT $\u000BunicodeFF $\u000CunicodeCR $\u000DunicodeSO $\u000E

    unicodeSI $\u000FunicodeDLE $\u0010unicodeDC1 $\u0011unicodeDC2 $\u0012unicodeDC3 $\u0013unicodeDC4 $\u0014unicodeNAK $\u0015unicodeSYN $\u0016unicodeETB $\u0017unicodeCAN $\u0018unicodeEM $\u0019unicodeSUB $\u001AunicodeESC $\u001BunicodeFS $\u001CunicodeGS $\u001DunicodeRS $\u001EunicodeUS $\u001F

    CompressionTo improve the performance of serial communications, a number

    of compression featureshave been added under the general heading

    of MNP. To create a serial endpoint with MNP compression, you must

    specifya different service "kCMSMNPID" and add three

    options: one to allocate a buffer for MNP compression; one to specify

    the type of MNP compression you want; and one to set the rate for

    data transfers.

    mySerialMNPEndpoint := {_proto:protoEndpoint,configOptions: [{ label: kCMSMNPID,type: 'service,opCode: opSetRequired },

    { label: kCMOSerialIOParms,type: 'option,opCode: opSetNegotiate,data: { bps: k9600bps,

    dataBits: k8DataBits,stopBits: k1StopBits,parity: kNoParity } },

    { label: kCMOMNPAllocate,type: option,opCode: opSetRequired,data: kMNPDoAllocate},

    { label: kCMOMNPCompression,type: 'option,opCode: opSetRequired,data: kMNPCompressionV42bis},

    { label: kCMOMNPDataRate,type: 'option,opCode: opSetRequired,data: k9600bps},

    ],};

    ThekCMOMNPAllocate option specifieswhether you want a

    buffer allocated for MNP compression; possible data slot valuesare as

    follows:

    CONSTANT MEANINGkMNPDoAllocate allocate buffer

  • 7/28/2019 Newton Technology Journal: Volume 1, Number 1

    21/24

    Newton Technology Journal February 1995

    21

    kMNPDontAllocate do not allocate buffer

    ThekCMOMNPCompression option specifieswhich MNP

    compression to use; possible data slot valuesare asfollows:

    CONSTANT MEANINGkMNPCompressionNone connect with no compressionkMNPCompressionMNP5 connect with MNP 5compressionkMNPCompressionV42bis connect with V42biscompression

    If you specifiedkMNPDontAllocate for the

    kCMOMNPAllocateoption, you must specify

    kMNPCompressionNone for the compression type. If you

    specifiedkMNPDoAllocate, you need to specifyeither

    kMNPCompressionMNP5 or

    kMNPCompressionV42bis.

    There isa fall-back mechanism wherebyif you request MNP

    V42biscompression and it isnt available, the modem tool will try

    MNP5 compression. I f MNP5 compression isunavailable, the endpoint

    will be created without MNP compression.

    STATEMACHINESANDINPUTSPECSSo far thisarticle hasdealt with a single state state machine, in

    which all incoming data isexpected to be of the same type (strings) ,

    and terminated with the same character (a carriage return). In

    Newton communications, each state isrepresented bya separate

    inputSpec. AninputSpec isa frame which isusuallykept as

    a slot in the endpoint and which defineshow incoming data isto be

    decoded, terminated and handled upon receipt. Asan

    inputSpechandlesitsreceived data, it can change the state to

    another inputSpec, so that the next input stream will be han-

    dled in a different fashion.

    To demonstrate how multiple statescan interact, an example cre-

    ated byApple PIEDTS isincluded. The example application iscalled

    Serial Protocol; i t handlesa handshake protocol, a command state

    and a message-receiving mode.

    ep := {_proto: protoEndpoint,_parent: self,...,// this is just the initial handshakingpart to make sure that both ends are alive// this would be set as the startinginputSpec in the connect method// ep:SetInputSpec(ep.waitforACK);

    waitforACK:{

    InputForm: 'string,discardAfter: 4, // onlyexpecting3 characters and the ?endCharacter: $?, // ACK?expected

    InputScript: func(endpoint, s) beginif (StrPos(s, "ACK?", 0)) then // was it ACK?begin

    endpoint:SetInputSpec(endpoint.waitForFUNCTION);// the main state

    endpoint:Output("ACK", nil); // send responseendpoint:FlushOutput();

    en dend,

    },

    // This is the generic dispatcher state, other end sends something// endingwith ! and the Newton will serve.

    waitForFUNCTION:{

    InputForm: 'string,discardAfter: 10,endCharacter: $!, // expects a'!' as end of the command

    InputScript: func(endpoint, s)

    beginif(StrPos(s, "CARD!", 0)) then // card functionbeginendpoint:Output(endpoint:DumpNameSoup(), nil);

    // Send names in cardsendpoint:Output(unicodeCR, nil);endpoint:Output(unicodeLF, nil);endpoint:FlushOutput();

    end;

    if(StrPos(s, "NAME!", 0)) then // name functionbegin

    // Call the Name function (just awrapper around// userConfiguration.name)

    endpoint:Output(endpoint:DumpName(), nil);endpoint:Output(unicodeCR, nil);endpoint:Output(unicodeLF, nil);endpoint:FlushOutput();

    end;

    if(StrPos(s, "SIZE!", 0)) then // size functionbegin

    //Send size of internal storageendpoint:Output(endpoint:DumpSize(), nil);endpoint:Output(unicodeCR, nil);endpoint:Output(unicodeLF, nil);endpoint:FlushOutput();

    end;

    if(StrPos(s, "SEND!", 0)) then //Stringsendingfcnbegin

    // switch to receive stringstateendpoint:SetInputSpec(endpoint.waitForSTRING);

    end;

    if(StrPos(s, "BYE!", 0)) then // bye functionbegin

    endpoint:Output("Bye", nil); // send responseendpoint:FlushOutput();

    end;end,

    },// our special stringhandlingstate for receivingmessages

    waitForSTRING:{

    InputForm: 'string,discardAfter: 200, // maximumlength of messageendCharacter: $>, // terminate message with >

    InputScript: func(endpoint, s)begin

    // back to the mainendpoint:SetInputSpec(endpoint.waitForFUNCTION);

    endpoint:SendOverInfo(s); // handle the message sentendpoint:Output("OK!", nil); // send responseendpoint:FlushOutput();end,

    }.

    };

    After making a successful connection, theinputSpecwould

    be set towaitForACK. AsthisinputSpec istriggered by

    the incoming data stream, i t switchestheinputSpec to

    waitForFunction. ThisinputSpec checksthe content of

    the command that wassent and executesan appropriate method

    based on the command received.

    Several of these messages, such asDumpNameSoup are

    being sent to the endpoint(endpoint:DumpNameSoup

  • 7/28/2019 Newton Technology Journal: Volume 1, Number 1

    22/24

    February 1995 Newton Technology Journal

    22

    ), but these methodsare not in the endpoint.

    To find them, you have to look further back in the endpoint defin-

    ition, where there isa_parent slot defined asself (_par-

    ent: self ) . Since the endpoint isusuallydefined in the context

    of the base view, the parent of the endpoint istherefore the base

    view. Now, when messagesare sent to the endpoint and are not rec-ognized, theyare passed on to itsparent, the base view, where all

    the data-handling methodsare defined.

    UPLOAD/DOWNLOADFILES/SOUPSIn the desktop world, data filestend to have a structure with field

    namesand recordswhich are often converted to tab-delimited text.

    The Newton storesdata in soupsusing entriesof frameswith slots

    for the field names.

    Thismeansthat to passfilesgenericallybetween these two envi-

    ronments, the first state you must define isthe interchange of field

    and slot names. The second state would be to passthe number of

    recordsor entrieswhich you intend to transfer. The third state to

    define isthe actual passing of a record or entry. The final state

    would be some form of confirmation that all the data hasbeen trans-

    ferred successfully.

    Trace the flow of the code to see how the state ischanged from

    oneinputSpec to another.

    getFieldNames:{inputForm: 'string,endCharacter: unicodeETX, // not acharacter found in afield name

    inputScript: func(endpoint, s)begin

    endpoint:SetInputSpec(getNumberOfRecords);endpoint:SetUpSoup(s); // create soup frame based on field names

    end,},

    getNumberOfRecords:{inputForm: 'byte,byteCount: 4,

    inputScript: func(endpoint, b)begin

    endpoint:SetInputSpec(getRecords);//assemble integer of number of recordslocal num := b[0]

  • 7/28/2019 Newton Technology Journal: Volume 1, Number 1

    23/24

    Newton Technology Journal February 1995

    23

    opCode: opSetRequired,data: kModemECProtocolMNP + kModemECProtocolNone

    },

    ThekCMOModemECType option specifieswhich error correc-

    tion method to use; possible data slot valuesare asfollows:

    CONSTANT MEANINGkModemECProtocolNone connect with no error

    correction

    kModemECProtocolMNP connect with internal MNP

    (class4)

    kModemECProtocolExternal connect using external

    modemsbuilt in error

    control

    Other optionsspecific to modemsare dialing preferences. You

    specifythese preferencesbyadding the

    kCMOModemDialing option to theconfigOptions

    array.

    { label: kCMOModemDialing,type: 'option,opCode: opSetRequired,data: { speakeron: nil,

    detectdialtone: true,waitforcarrier: 60, },

    The first three preferencesin the table can be set bya user in the

    Modem section of the Newton preferences. The rest have the default