Yeah, I determined that it was my particular app. It doesn't matter if 
I'm debugging or not. My app always causes a reset loop if I use it. 
Also, it didn't free up the bluetooth resources either... even though I 
explicitly had it close the port and library.

I've not had much luck trying to write bluetooth apps.
I can attach the entire source for the program... can anyone point out 
something I'm doing wrong right off the bat?

Thanks

Kasny J. wrote:
>> Hi,
>>
>> I'm attempting to use the Palm OS Debugger to debug my apps on a 
>> device. Whenever I'm finished, the device goes into a reset loop and 
>> continues to do so until I delete my app that I installed. I dunno 
>> why it does this. Its a bluetooth app, but I don't think I'm doing 
>> anything I shouldn't.
>
> It is normal, that the device goes into the reset loop after finish. 
> But the loop reset is propably caused by your application. Maybe 
> memory leak or something like this. Or insufficient memory space. 
> Check it.
>
> zozo
>
> __________ Informace od ESET NOD32 Antivirus, verze databaze 4573 
> (20091104) __________
>
> Tuto zpravu proveril ESET NOD32 Antivirus.
>
> http://www.eset.cz
>
>
>
>

-- 
For information on using the ACCESS Developer Forums, or to unsubscribe, please 
see http://www.access-company.com/developers/forums/
 /******************************************************************************
 *
 * Copyright (c) 2007, ACCESS Systems Americas, Inc. All Rights Reserved.
 *
 * File: AppMain.c
 *
 *****************************************************************************/
#include "PalmOS.h"
#include <Event.h>
#include <SysEvent.h>


#include "../rsc/AppResources2.h"

#include "AppMain.h"
#include "BtCommVdrv.h"
#include "SerialMgr.h"
#include "FeatureMgr.h"
#include "BtLib.h"
/***********************************************************************
 *
 *      Entry Points
 *
 ***********************************************************************/


/***********************************************************************
 *
 *      Internal Constants
 *
 ***********************************************************************/
#define appFileCreator                  'SHRN'  // register your own at 
http://www.palmos.com/dev/creatorid/
#define appVersionNum                   0x01
#define appPrefID                               0x00
#define appPrefVersionNum               0x01


 void OpenPort(void);
 
 void Disconnect(void);
 
 void SendString(void);
 
 void ServerOpen(void);
 void GetReceivedData(void);

UInt32 ports[12] = {
        serPortLocalHotSync,
        serPortCradlePort,
        serPortIrPort,
        serPortConsolePort,
        serPortCradleRS232Port,
        serPortCradleUSBPort,
        sysFileCUart328,
        sysFileCUart328EZ,
        sysFileCUart650,
        sysFileCVirtIrComm,
        sysFileCVirtRfComm,
        sysFileCBtConnectPanelHelper };
UInt32 speeds[10] = {
        115200,
        57600,
        38400,
        28800,
        19200,
        14400,
        9600,
        4800,
        2400,
        1200};
        
UInt32 serial_port_choice;
UInt32 speed_choice;

/* CODE FROM http://www.webalice.it/rodolfo.turco/DevelTips.html#Tip9 
 * 
 * 
Here is a simple way to communicate with your bluetooth serial device, 
this example code  is as simple as possible you have to implement the 
errors management.

You have to:
1) Load the Library
2) Find a device if not already known
3) Open the connection
4) Use it (Receive, Send, Flush, etc.)
5) Close the connection

*/

/**************/
/* BT Globals      */
/**************/
static UInt16 unPortId;
static UInt16 btLibRefNum;
static UInt8   cAddress[6];
static Err err;
static SrmOpenConfigType config;
static BtVdOpenParams    btParams;
static BtLibSdpUuidType  sppUuid;
/************************************/
/* Pause n milliseconds                                    */
/************************************/
static void Uti_WaitMilliSec(UInt32 ulMilliSec)
{
 UInt16  unTickPerSec;

 unTickPerSec=SysTicksPerSecond();
 if(unTickPerSec)
  SysTaskDelay(ulMilliSec*unTickPerSec/1000);
 else
  SysTaskDelay(ulMilliSec/10);
}
/**************************************/
/* Close a Bluetooth serial connetion                    */
/**************************************/
static void BT_Close()
{
 if(unPortId)
  {
   SrmClose(unPortId);
   unPortId=0;
   Uti_WaitMilliSec(500);
   SrmClose(unPortId); // Retry, on some system it's hard to die
  }
}
/*************************************/
/* Open a Bluetooth serial connetion                  */
/*************************************/
static void BT_Open()
 {
  BT_Close();
  MemSet(&sppUuid, sizeof(sppUuid), 0);
  sppUuid.size = btLibUuidSize16;
  sppUuid.UUID[0] = 0x11;
  sppUuid.UUID[1] = 0x01;
  MemSet(&btParams, sizeof(btParams), 0);
  btParams.u.client.remoteDevAddr.address[0]=cAddress[0];
  btParams.u.client.remoteDevAddr.address[1]=cAddress[1];
  btParams.u.client.remoteDevAddr.address[2]=cAddress[2];
  btParams.u.client.remoteDevAddr.address[3]=cAddress[3];
  btParams.u.client.remoteDevAddr.address[4]=cAddress[4];
  btParams.u.client.remoteDevAddr.address[5]=cAddress[5];
  btParams.role = btVdClient;
  btParams.u.client.method = btVdUseUuidList;
  btParams.u.client.u.uuidList.tab = &sppUuid;
  btParams.u.client.u.uuidList.len = 1;
  MemSet(&config, sizeof(config), 0);
  config.function = serFncUndefined;
  config.drvrDataP = (MemPtr)&btParams;
  config.drvrDataSize = sizeof(btParams);
  err=SrmExtOpen(sysFileCVirtRfComm,&config,sizeof(config),&unPortId);
 }
 
//Server Listen
static void BT_Server_Listen()
 {
  BT_Close();
  MemSet(&sppUuid, sizeof(sppUuid), 0);
  sppUuid.size = btLibUuidSize16;
  sppUuid.UUID[0] = 0x11;
  sppUuid.UUID[1] = 0x01;
  MemSet(&btParams, sizeof(btParams), 0);
  btParams.role = btVdServer;
  btParams.u.client.method = btVdUseUuidList;
  btParams.u.client.u.uuidList.tab = &sppUuid;
  btParams.u.client.u.uuidList.len = 1;
  MemSet(&config, sizeof(config), 0);
  config.function = serFncUndefined;
  config.drvrDataP = (MemPtr)&btParams;
  config.drvrDataSize = sizeof(btParams);
  btParams.u.server.name = "PalmView";
  err=BtLibOpen(btLibRefNum,false);
  if(err==0)
        BtLibSdpUuidInitialize(btParams.u.server.uuid, 
btLibSdpUUID_SC_SERIAL_PORT, btLibUuidSize16);
  BtLibClose(btLibRefNum);
  
  err=SrmExtOpen(sysFileCVirtRfComm,&config,sizeof(config),&unPortId);
 }
/***************************/
/* Find a BT device on air             */
/***************************/
static void BT_FindDevice()
{
 BT_Close();

 if(btLibRefNum)
  {
   err=BtLibOpen(btLibRefNum,false);
   if(err==0)
     err=BtLibDiscoverSingleDevice(btLibRefNum,NULL,NULL,0, 
(BtLibDeviceAddressType *)cAddress,false,true);
   BtLibClose(btLibRefNum);
  }
}
/***********************/
/* Load the BT library           */
/***********************/
static void BT_LoadLibrary()
{
 btLibRefNum=0;

 err=SysLibFind("Bluetooth Library",&btLibRefNum);
 if(err)
  err=SysLibLoad(sysFileTLibrary,sysFileCBtLib,&btLibRefNum);
}
/****************/
/* Flush BT ser        */
/****************/
static void BT_Flush(UInt16 unTimeout)
{
 if(unPortId)
   err=SrmReceiveFlush(unPortId,unTimeout);
}
/****************/
/* Send BT data      */
/****************/
static void BT_Send(char * pData,UInt16 unLen)
{
 SrmSendFlush(unPortId);
 if(unPortId){
   SrmSend(unPortId,pData,unLen,&err);
   if(err == errNone)
      SrmSendFlush(unPortId);
 }
}
/*******************/
/* Receive BT data        */
/*******************/
static UInt16 BT_Receive(char * pData,UInt16 unLen,UInt16 unTimeout)
{
 UInt16 unLenRead;
 if(unPortId)
   unLenRead=SrmReceive(unPortId,pData,unLen,unTimeout,&err); //It resets on 
this line in server mode... i wonder why? Do i have to flush beforehand?
 return(unLenRead);
}


/***********************************************************************
 *
 * FUNCTION:    PilotMain
 *
 * DESCRIPTION: This is the main entry point for the application.
 *
 * PARAMETERS:  cmd - word value specifying the launch code. 
 *              cmdPB - pointer to a structure that is associated with the 
launch code. 
 *              launchFlags -  word value providing extra information about the 
launch.
 * RETURNED:    Result of launch
 *
 * REVISION HISTORY: 
 *
 *
 ***********************************************************************/
UInt32 PilotMain(UInt16 cmd, MemPtr cmdPBP, UInt16 launchFlags)
{
        Err error = errNone;
        
        serial_port_choice= ports[0]; //just use default or 
whatever:serPortLocalHotsync
        speed_choice = speeds[0]; //115200
        
        switch (cmd) {
                case sysAppLaunchCmdNormalLaunch:
                        if ((error = AppStart()) == 0) {                        
                                AppEventLoop();
                                AppStop();
                        }
                        break;

                default:
                        break;
        }
        
        return error;
}



/***********************************************************************
 *
 *      Internal Functions
 *
 ***********************************************************************/


/***********************************************************************
 *
 * FUNCTION:    MainFormDoCommand
 *
 * DESCRIPTION: This routine performs the menu command specified.
 *
 * PARAMETERS:  command  - menu item id
 *
 * RETURNED:    nothing
 *
 * REVISION HISTORY:
 *
 *
 ***********************************************************************/
static Boolean MainFormDoCommand(UInt16 command)
{
        Boolean handled = false;
        FormType * pForm;

        switch (command) {
                case kMainFormMenuBarAboutPalmViewMenuItem:
                        pForm = FrmInitForm(kAboutForm);
                        FrmDoDialog(pForm);                                     
// Display the About Box.
                        FrmDeleteForm(pForm);
                        handled = true;
                        break;

        }
        
        return handled;
}


/***********************************************************************
 *
 * FUNCTION:    MainFormHandleEvent
 *
 * DESCRIPTION: This routine is the event handler for the 
 *              "MainForm" of this application.
 *
 * PARAMETERS:  pEvent  - a pointer to an EventType structure
 *
 * RETURNED:    true if the event has handle and should not be passed
 *              to a higher level handler.
 *
 * REVISION HISTORY:
 *
 *
 ***********************************************************************/
 

static Boolean MainFormHandleEvent(EventType* pEvent)
{
        Boolean         handled = false;
        FormType*       pForm;
        UInt16 index;
        struct popSelect* structure;
        
        switch (pEvent->eType) {
                case menuEvent:
                        return MainFormDoCommand(pEvent->data.menu.itemID);

                case frmOpenEvent:
                        pForm = FrmGetActiveForm();
                        FrmDrawForm(pForm);
                        handled = true;
                        break;
                case popSelectEvent:
                        structure = &pEvent->data;
                        switch(structure->listID)//we don't care what control 
it was ... the list tells us enough.
                        {
                                case kMainFormPortList:
                                        index = structure->selection;
                                        if(index > -1 && index < 12)
                                                serial_port_choice=ports[index];
                                        //handled = true;
                                        break;
                                case kMainFormSpeedList:
                                        index = structure->selection;
                                        if(index > -1 && index < 10) //no 
selection is = -1.
                                                
speed_choice=speeds[index];//our nifty pre-list.
                                        //handled = true;
                                        break;
                                default:
                                        break;
                        }       
                        break;
                case ctlSelectEvent:
                        switch(pEvent->data.ctlSelect.controlID)
                        {
                        case kMainFormConnectSerialPortButton:
                                //Open the connection... and stuff- DRAT we 
can't do this on the simulator!
                                OpenPort();
                                break;
                        case kMainFormDisconnectButton:
                                //Disconnect?
                                Disconnect();
                                break;
                        case kMainFormSendButton:
                                SendString();
                                break;
                        case kMainFormStartServerButton:
                                ServerOpen();
                                break;
                        case kMainFormWaitforDataButton:
                                GetReceivedData();
                                break;
                        default:
                                break;
                        }
                        break;
                default:
                        break;
        }
        
        return handled;
}

//Quickly returns the data if it has been sent
void GetReceivedData(void)
{
        UInt32 bytes;
        MemHandle buffer;
        char* edit_buffer;      
        FormPtr         frm;
        FieldPtr        fld;
        UInt16          obj;
        UInt16 b;

        frm = FrmGetFormPtr(kMainForm);
        obj = FrmGetObjectIndex(frm, kMainFormSendStrField);
        fld = (FieldPtr)FrmGetObjectPtr(frm, obj);
        
        bytes=0;
        err = SrmReceiveCheck(unPortId, &bytes);
        if(bytes == 0)
                return;
        
        buffer = MemHandleNew(bytes + sizeof(char));
        if(buffer == 0)
        {
                ErrDisplay("Couldn't allocate memory to receive data!");
                return;
        }
        
        
        BT_Receive(buffer, bytes, 300);
        if(err != 0)
        {
                ErrDisplay("Timeout or error occurred.");
        }
        
        BT_Flush(300);
        if(err != 0)
        {
                ErrDisplay("Timeout or error occurred.");
        }
        
        // Add a null char to the end of the new string.
        b = StrLen(buffer);
        edit_buffer = (char *)MemHandleLock(buffer);
        edit_buffer[b-1] = '\0';
        MemHandleUnlock(buffer);
        
        
        //free the old string, if it exists.
        FldFreeMemory(fld);
                
        //Set the new string!
        FldSetText(fld, buffer, 0, bytes+sizeof(char)); 
}

void ServerOpen(void)
{
        
        BT_LoadLibrary();
        if(err != 0)
        {
                ErrDisplay("Couldn't load BT library!");
        }
        BT_Server_Listen();
        if(err != 0)
        {
                ErrDisplay("Couldn't Open BT Connection for listening!");
        }
        
        //** USE ThE CONNECTION HERE!
}
void SendString(void)
{
        FormPtr         frm;
        FieldPtr        fld;
        UInt16          obj;
        Char* textstr;

        frm = FrmGetFormPtr(kMainForm);
        obj = FrmGetObjectIndex(frm, kMainFormSendStrField);
        fld = (FieldPtr)FrmGetObjectPtr(frm, obj);
        
        textstr = FldGetTextPtr(fld);
        if(textstr == NULL)
                return;
        if(StrLen(textstr) == 0)
                return;
        
        BT_Send(textstr, StrLen(textstr));
        if(err != 0)
        {
                ErrDisplay("Some kind of sending error!");
        }       
}
void OpenPort(void)
{
        /////////////////////////////////////
        //CHECK FOR FEATURE AVAILABILITY
        
        /*UInt32 btVersion; 
 
        // Make sure Bluetooth components are installed 
        // This check also ensures Palm OS 4.0 or greater 
        if (FtrGet(btLibFeatureCreator, btLibFeatureVersion, 
                &btVersion) != errNone) 
        { 
                // Alert the user if it's the active application 
                if ((launchFlags & sysAppLaunchFlagNewGlobals) && 
                        (launchFlags & sysAppLaunchFlagUIApp)) 
                        FrmAlert (MissingBtComponentsAlert); 
                return; 
        } */
        //////////////////////////////////////
        
        /*
        //////////////////////////////////////
        // Load the BT Lib
        UInt16 btLibRefNum; 
        UInt16 portId; 
        Boolean serPortOpened = false; 
        Err err; 
        UInt32 tos;
        UInt32 numSent; 
        Char msg[] = "logon\n";
        SrmOpenConfigType config;
        BtVdOpenParams params;
        BtLibSdpUuidType sdp_param;
        
        err = SysLibFind(btLibName, &btLibRefNum);
        if (err == 0) { 
                
                err = SysLibLoad(sysFileTLibrary, sysFileCBtLib, 
                                                &btLibRefNum); 
                if(err != errNone)
                        return;
        }else{
                FrmCustomAlert(ID_MSG_ALERT, "Error", "Couldn't load BT Lib 
Library", " ");
                return;
        }
        
        //////////////////////////////////////
        
        //////////////////////////////////////
        // Open the BT library
        // Only open the BT library if you need to use a function from it (?)
        
        err = BtLibOpen (btLibRefNum, false);
        if(err != errNone)
                return;
                        
        /*FormPtr frm;
        UInt16 focus;
        FormObjectKind objType;
        
        frm = FrmGetActiveForm();
        FieldPtr TblGetCurrentField(FrmGetObjectPtr(frm, focus))
        */
//      UInt16 focus;
//      FormObjectKind objType;
        
        //It doesn't like UInt32 in the middle of the function for some reason.
        
        //Read the value on the form
        
        //frm = FrmGetActiveForm();
        //TblGetCurrentField(FrmGetObjectPtr(frm, focus))
         //Alternate is sysFileCVirtRfComm but we probably have to use 
SrmExtOpen with special BT settings. 
         // See 
http://www.mail-archive.com/palm-dev-forum@news.palmos.com/msg61007.html 
        //we want a BK connection because we will eventually exit this app.
        
        //Background connection didn't work... lets try foreground connection.
        //Trying something new
/*
#define BT_CLIENT

#ifdef BT_CLIENT

// Fix a bug in the Bluetooth SDK?
#ifdef BtLibSdpUuidInitialize
#undef BtLibSdpUuidInitialize
#endif
#define BtLibSdpUuidInitialize(uuid, define, defineSize)  { (uuid).size = 
(defineSize); \
 MemMove((uuid).UUID, (define), (uuid).size); }
 
        //sdp_param.size = btLibUuidSize16;
        //BtLibSdpUuidInitialize(sdp_param,  btLibSdpUUID_SC_SERIAL_PORT, 
btLibUuidSize16);
        
        params.role = btVdClient;
        params.u.client.remoteDevAddr.address[0] = 0;
        params.u.client.remoteDevAddr.address[1] = 0;
        params.u.client.remoteDevAddr.address[2] = 0;
        params.u.client.remoteDevAddr.address[3] = 0;
        params.u.client.remoteDevAddr.address[4] = 0;
        params.u.client.remoteDevAddr.address[5] = 0;
        
        params.u.client.method = btVdUseUuidList;
        //params.u.client.u.uuidList.tab = &sdp_param; //line used to be gone.
        params.u.client.u.uuidList.len = 0;



#else
//TRYING SERVER LISTENING VERSION.


                params.role = btVdServer;
                BtLibSdpUuidInitialize(params.u.server.uuid, 
btLibSdpUUID_SC_SERIAL_PORT, btLibUuidSize16);
                params.u.server.name = "PalmView";

#endif
        //params.authenticate = false;
        //params.encrypt = false;

        config.baud = 9600;
        config.function = serFncUndefined;
        config.drvrDataP = &params;
        config.drvrDataSize = sizeof(params);
        
        config.sysReserved1 = 0;
        config.sysReserved2 = 0;

        BtLibClose(btLibRefNum);
        err = SrmExtOpen(sysFileCVirtRfComm, &config, sizeof(config), &portId);
        if ((err == errNone) || (err == serErrAlreadyOpen))
                serPortOpened = true;
        else{
                ErrDisplay("Couldn't open BT port.");
                ErrAlert(err);
                return;
        }
                */      
        /*err = SrmOpen(serial_port_choice  , speed_choice,  &portId);  
//changed from "SrmOpenBackground"
        if (err) { 
           //Display error here.
           //ErrDisplay("Connection error! Are you running this in the 
simulator?");
           switch(err){
           case serErrAlreadyOpen:
                        ErrDisplay("Port already open");
                        break;
                case serErrBadPort:
                        ErrDisplay("Bad port");
                        return;
                        break;
                case memErrNotEnoughSpace:
                        ErrDisplay("Not enough memory to open the port");
                        return;
                        break;
           }
           ErrAlert(err);
           //We are not returning on the already open one because it might be 
non-fatal, as I saw in someone else's code.
        }*/
        /*//record our open status in global. 
        serPortOpened = true;
        
        ///////////
        //Test send
        
        tos = StrLen(msg); 
        numSent = SrmSend(portId, msg, tos, &err); 
        if (err == serErrTimeOut) { 
          //cts timeout detected 
          //ErrDisplay("Send Error!");
          ErrAlert(err);
          SrmClose(portId);
          return;
        }
        SrmClose(portId); //no errors hopefully.
        ErrAlert(1000); //success message.
        */
        BT_LoadLibrary();
        if(err != 0)
        {
                ErrDisplay("Couldn't load BT library!");
        }
        BT_FindDevice();
        if(err != 0)
        {
                ErrDisplay("Couldn't find a device, or cancelled or 
something...");
        }
        BT_Open();
        if(err != 0)
        {
                ErrDisplay("Couldn't Open BT Connection!");
        }
        
        //** USE ThE CONNECTION HERE!
                
}

//Disconnect fcn... closes the connection.
void Disconnect()
{
        BT_Flush(1500); //flush, with timeout.
        if(err != 0)
        {
                ErrDisplay("Flush failed");
        }
        BT_Close();
        if(err != 0)
        {
                ErrDisplay("Unable to close BT Connection");
        }
        
        err = BtLibClose(btLibRefNum);
        if( err == btLibErrNotOpen )
        {
                ErrDisplay("BT Lib was not open, you didn't need to close it.");
        }else if(err != 0){
                ErrDisplay("Some other error with closing the bt lib!");
        }
        
        
        err=SysLibRemove(btLibRefNum); //This might be a BAD idea (like 
unloading it from future app's use!) so we won't bother with this for now.
        if(err != 0)
        {
                ErrDisplay("Unable to unload BT Lib");
        }
}
/***********************************************************************
 *
 * FUNCTION:    AppHandleEvent
 *
 * DESCRIPTION: This routine loads form resources and set the event
 *              handler for the form loaded.
 *
 * PARAMETERS:  event  - a pointer to an EventType structure
 *
 * RETURNED:    true if the event has handle and should not be passed
 *              to a higher level handler.
 *
 * REVISION HISTORY:
 *
 *
 ***********************************************************************/
static Boolean AppHandleEvent(EventType* pEvent)
{
        UInt16          formId;
        FormType*       pForm;
        Boolean         handled = false;

        if (pEvent->eType == frmLoadEvent) {
                // Load the form resource.
                formId = pEvent->data.frmLoad.formID;
                
                pForm = FrmInitForm(formId);
                FrmSetActiveForm(pForm);

                // Set the event handler for the form.  The handler of the 
currently
                // active form is called by FrmHandleEvent each time is 
receives an
                // event.
                switch (formId) {
                        case kMainForm:
                                FrmSetEventHandler(pForm, MainFormHandleEvent);
                                break;

                        default:
                                break;
                }
                handled = true;
        }
        
        return handled;
}


/***********************************************************************
 *
 * FUNCTION:     AppStart
 *
 * DESCRIPTION:  Get the current application's preferences.
 *
 * PARAMETERS:   nothing
 *
 * RETURNED:     Err value errNone if nothing went wrong
 *
 * REVISION HISTORY:
 *
 *
 ***********************************************************************/
static Err AppStart(void)
{
        FrmGotoForm(kMainForm);
        return errNone;
}


/***********************************************************************
 *
 * FUNCTION:    AppStop
 *
 * DESCRIPTION: Save the current state of the application.
 *
 * PARAMETERS:  nothing
 *
 * RETURNED:    nothing
 *
 * REVISION HISTORY:
 *
 *
 ***********************************************************************/
static void AppStop(void)
{
        // Close all the open forms.
        FrmCloseAllForms();
}


/***********************************************************************
 *
 * FUNCTION:    AppEventLoop
 *
 * DESCRIPTION: This routine is the event loop for the application.  
 *
 * PARAMETERS:  nothing
 *
 * RETURNED:    nothing
 *
 * REVISION HISTORY:
 *
 *
 ***********************************************************************/
static void AppEventLoop(void)
{
        Err                     error;
        EventType       event;

        do {
                EvtGetEvent(&event, evtWaitForever);

                if (SysHandleEvent(&event))
                        continue;
                        
                if (MenuHandleEvent(0, &event, &error))
                        continue;
                        
                if (AppHandleEvent(&event))
                        continue;

                FrmDispatchEvent(&event);

        } while (event.eType != appStopEvent);
}



Reply via email to