football_project_wo_output

Dependencies:   mbed

Fork of football_project by MZJ

Revision:
11:d3aa5fca2330
Parent:
10:72ceef287b0f
Child:
12:6d313d575f84
--- a/main.cpp	Tue Apr 21 07:00:55 2015 +0000
+++ b/main.cpp	Thu Apr 23 06:36:57 2015 +0000
@@ -1,6 +1,10 @@
 /*
  * TA test
  *
+ *  TODO maybe have a mode where the serial port I/O can be swapped,
+ *   such that what the nRF generates is sent out the serial port,
+ *   and what comes in the serial port goes into the nRF.
+ *   Maybe could use the now-unused CTS pin for that.
  */
 
 /* mbed Microcontroller Library
@@ -27,13 +31,12 @@
 #include "DeviceInformationService.h"
 
 #include "MTSSerialFlowControl.h"
-#include "Vars.h"
 #include "PhoneAppIO.h"
 
 #define NEED_CONSOLE_OUTPUT 0 /* Set this if you need debug messages on the console;
                                * it will have an impact on code-size and power consumption. */
 
-// #define LOOPBACK_MODE         // Loopback mode
+#define LOOPBACK_MODE       0  // Loopback mode
 
 #if NEED_CONSOLE_OUTPUT
 #define DEBUG(...) { printf(__VA_ARGS__); }
@@ -43,9 +46,6 @@
 
 BLEDevice  ble;
 
-
-#define TXRX_BUF_LEN  20
-
 extern "C"
 {
 //    serial_t _my_serial;
@@ -54,27 +54,23 @@
 
 // Note:  From the datasheet:
 //  PSELRXD, PSELRTS, PSELTRTS and PSELTXD must only be configured when the UART is disabled.
-// But serial_init() erroneously enables the uart before the setting of those,
-//  which messes up flow control.  Apparently the setting is ONCE per ON mode.  ARGH!
-//  So we made our own versions of Serial and SerialBase to (MySerial and MySerialBase)
+// But a version of serial_init() erroneously enabled the uart before the setting of those,
+//  which messed up flow control.  Apparently the setting is ONCE per ON mode.  ARGH!
+//  So we made our own versions of Serial and SerialBase (MySerial and MySerialBase)
 //  to not use serial_init() in serial_api.c, so flow control is setup correctly *
 //  MTSSerial now uses our MySerial instead of Serial, and now uses hw flow control by default *
-//  * But unfortunately we can't change the uart interrupt vector in the interrupt table,
-//    and the current low-level support in serial_api.c won't pass through non-tx/rx interrupts,
-//    so we change it/rebuild the mbed lib for low-level hw flow control to work.
+//  * We can't change the uart interrupt vector, so we comment-out the handler in
+//    serial_api.c, and rebuild the mbed lib for low-level hw flow control to work.
 // MTSSerialFlowControl uses "manual" (non-hardware-low-level) flow control based on its
-//  internal buffer--Rx servicing seems fast enough not to need hw flow control, so it's okay.
+//  internal buffer--Rx servicing usually is fast enough not to need hw flow control, so it's okay.
 //
 // mts::MTSSerialFlowControl pcfc( USBTX, USBRX, RTS_PIN_NUMBER, CTS_PIN_NUMBER, 384, 2688 );
-mts::MTSSerial pcfc( USBTX, USBRX, 256, 2560, RTS_PIN_NUMBER, NC );
+mts::MTSSerial pcfc( USBTX, USBRX, 256, 1280, RTS_PIN_NUMBER, NC );  // 256, 2560
 
 uint8_t txPayload[TXRX_BUF_LEN] = { 0 };
 
-static uint8_t rx_buf[TXRX_BUF_LEN];
-static uint8_t rx_len = 0;
 
-
-DigitalOut _led1( LED1 );
+DigitalOut led1( LED1 );
 // DigitalOut rts( RTS_PIN_NUMBER );
 
 
@@ -89,12 +85,22 @@
 };
 
 UARTService *uartServicePtr;
+PhoneAppIO  *phoneP;
 
-// PhoneAppIO toPhone( &ble );
+bool connected = false;
 
+void connectionCallback( Gap::Handle_t, Gap::addr_type_t peerAddrType,
+                         const Gap::address_t peerAddr, const Gap::ConnectionParams_t *connParams )
+{
+    connected = true;
+
+    DEBUG( "Connected!\n\r" );
+}
 
 void disconnectionCallback( Gap::Handle_t handle, Gap::DisconnectionReason_t reason )
 {
+    connected = false;
+
     DEBUG( "Disconnected!\n\r" );
     DEBUG( "Restarting the advertising process\n\r" );
     ble.startAdvertising();
@@ -102,11 +108,7 @@
 
 bool updateCharacteristic( GattAttribute::Handle_t handle, const uint8_t *data, uint16_t bytesRead )
 {
-    ble_error_t err;
-
-//    toPhone.toPhoneBuf( (uint8_t *)data, bytesRead );
-
-    err = ble.updateCharacteristicValue( handle, data, bytesRead );
+    ble_error_t err = ble.updateCharacteristicValue( handle, data, bytesRead );
 
     if( (err == BLE_ERROR_BUFFER_OVERFLOW) ||
         (err == BLE_ERROR_PARAM_OUT_OF_RANGE ) )
@@ -115,6 +117,7 @@
 
     } else if ( err == BLE_STACK_BUSY )
       {
+          // Common error when pumping data.
       }
 
     return  (err != BLE_ERROR_NONE);
@@ -122,91 +125,74 @@
 
 void onDataWritten( const GattCharacteristicWriteCBParams *params )
 {
-    if( (uartServicePtr != NULL) && (params->charHandle == uartServicePtr->getTXCharacteristicHandle()) )
+    if( phoneP != NULL )
     {
-        uint8_t buf[TXRX_BUF_LEN];
-        uint16_t bytesRead = MIN( params->len, TXRX_BUF_LEN );
-
-        DEBUG( "received %u bytes\n\r", bytesRead );
-
-#ifdef LOOPBACK_MODE
-        // Loopback data from Central.
-        updateCharacteristic( uartServicePtr->getRXCharacteristicHandle(), params->data, bytesRead );  // Notifies.
-#endif
+        uint16_t bytesRead = phoneP->maybeHandleRead( params );  // Also writes to txPayload
+        if( 0 != bytesRead )
+        {
+            DEBUG( "received %u bytes\n\r", bytesRead );
 
-        ble.readCharacteristicValue( uartServicePtr->getTXCharacteristicHandle(), buf, &bytesRead );
+            // Also write to serial port...
+//            pcfc.printf( "From app: " );
+            pcfc.write( (char *)txPayload, bytesRead );
+//            pcfc.printf( "\r\n" );
 
-        // Also write to serial port...
-        memset( txPayload, 0, TXRX_BUF_LEN );
-        memcpy( txPayload, buf, bytesRead );
-//        pcfc.printf( "From app: " );
-        pcfc.write( (char *)txPayload, bytesRead );
-//        pcfc.printf( "\r\n" );
+            return;
+        }
     }
+
+    // Other Characteristics here.
 }
 
-bool bleWasntReady;
-
 void onDataSent( unsigned count )
 {
 }
 
 void periodicCallback( void )
 {
-    _led1 = !_led1;
+    led1 = !led1;
 //    rts  = !rts;
 }
 
-void uartCB( void )
+void toPhoneChk( void )
 {
 //    if( 0 != rts.read() )  pcfc.puts( "\r\n!RTS disengaged.\r\n" );  // When not using HWFC.
 
-    // Set line from serial port to RX characteristic (From cone)
-    while( true )
+    if( phoneP != NULL )
     {
-        if( !bleWasntReady )
+        char ch;
+        // Get any data from serial port buffer--Full lines if avail--Last line after >= 20 chars.
+        for( int cnt=1; 0 != pcfc.atomicRead( ch ); cnt++ )
         {
-            int cReadCnt = 0;
-            char ch;
-
-            pcfc.disableRxIrq();
-            if( pcfc.MTSBufferedIO::readable() )  cReadCnt = pcfc.read( ch );
-            pcfc.enableRxIrq();
-
-            if( 0 == cReadCnt )  break;
-
-//            if( '\n' == ch )  continue;  // Filter linefeeds.
-            rx_buf[rx_len++] = ch;
+            if( 0 > phoneP->putchar( ch ) )
+            {
+                pcfc.printf( " * " );
+                break;
+            }
+            if( (cnt >= 20) && ('\n' == ch) )  break;
         }
-        if( bleWasntReady || rx_len>=TXRX_BUF_LEN || rx_buf[rx_len-1]=='\0' || rx_buf[rx_len-1]=='\r' )
+        // Write to outgoing characteristic if anything is pending.
+        if( 0 != phoneP->maybeHandleWrite() )
         {
-            bleWasntReady = updateCharacteristic( uartServicePtr->getRXCharacteristicHandle(), rx_buf, rx_len );  // Notifies.
-
-//            pcfc.printf( "RecHandler \r\n" );
-
-            if( bleWasntReady )  break;  // Don't loop on not ready (Don't starve main loop.)
-
-            rx_len = 0;
-            break;
+            // pcfc.printf( "ToPhoneHandler \r\n" );
         }
     }
 }
 
 int main( void )
 {
-    _led1 = 1;
+    led1 = 1;
     Ticker ticker;
     ticker.attach( periodicCallback, 1 );
 
 
     pcfc.baud( 57600 );
-    pcfc.rxClear();
-    // pc.attach( uartCB, pc.RxIrq );
 
     DEBUG( "Initialising the nRF51822\n\r" );
 
 
     ble.init();
+    ble.onConnection( connectionCallback );
     ble.onDisconnection( disconnectionCallback );
     ble.onDataWritten( onDataWritten );
     ble.onDataSent( onDataSent );
@@ -220,7 +206,7 @@
     sprintf( deviceName, "T%02X%02X", macAddr[1], macAddr[0] );
 
     pcfc.printf( "\r\nNano nano!   I am \"%s\"\r\n", deviceName );
-#ifdef LOOPBACK_MODE
+#if LOOPBACK_MODE
     pcfc.printf( "\r\nIn BLE Loopback mode.\r\n" );
 #endif
 
@@ -232,7 +218,7 @@
     ble.accumulateScanResponse( GapAdvertisingData::COMPLETE_LIST_16BIT_SERVICE_IDS,
                                       (const uint8_t *)DevInfoServiceUUID_rev, sizeof(DevInfoServiceUUID_rev) );
 
-    ble.setAdvertisingInterval( Gap::MSEC_TO_ADVERTISEMENT_DURATION_UNITS( 1000 ) );
+    ble.setAdvertisingInterval( Gap::MSEC_TO_ADVERTISEMENT_DURATION_UNITS( 200 ) );
     ble.startAdvertising();
 
     DeviceInformationService deviceInfo( ble, "TRX", "TrueAgility", "SN0001", "hw-rev1", "fw-rev1" );
@@ -245,11 +231,24 @@
     UARTService uartService( ble );
     uartServicePtr = &uartService;
 
-    while( true )
+    PhoneAppIO phone( ble, uartService.getRXCharacteristicHandle(),
+                           uartService.getTXCharacteristicHandle() );
+    phone.loopbackMode = LOOPBACK_MODE;
+    phoneP = ☎
+
+    Timer tmr;
+    tmr.start();
+
+    // Main Loop
+    for( uint32_t loop=1; ;loop++ )
     {
         ble.waitForEvent();
 
-        uartCB();
+        toPhoneChk();  // Write any pending data to phone.
+
+        while( 0 <= phone.getchar() );  // Eat input.
+
+//        if( !(loop % 50) )  phone.printf( "Post: %d\r\n", tmr.read_ms() );
     }
 }