football_project_wo_output

Dependencies:   mbed

Fork of football_project by MZJ

Revision:
19:afcbb425b3cf
Parent:
18:affef3a7db2a
Child:
20:d6c6099b60be
Child:
23:26f27c462976
--- a/main.cpp	Sun Nov 29 13:52:53 2015 +0000
+++ b/main.cpp	Tue Dec 01 16:03:15 2015 +0000
@@ -1,6 +1,8 @@
 /*
  * TA test
  *
+ *  Updated for New TA Baseboard (rev Aug-Nov 2015.)
+ *
  *  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.
@@ -12,8 +14,8 @@
  *     rev  97 of mbed lib
  *       corresponding to:
  *         rev 493 of mbed-src   w/ modification to targets/hal/TARGET_NORDIC/TARGET_MCU_NRF51822/serial_api.c
- *         (Source no longer needed now that 
- *     so things compile properly.
+ *                                so things compile properly.*
+ *        * Now using $Sub$$UART0_IRQHandler to override UART0_IRQHandler without needing to use lib source.
  *
  *   Changed
  *     nRF51822/nordic/pstorage_platform.h  PSTORAGE_MIN_BLOCK_SIZE  changed from 0x010 to 4.
@@ -44,6 +46,7 @@
 #include "DFUService.h"
 #include "UARTService.h"
 #include "DeviceInformationService.h"
+#include "BatteryService.h"
 
 #include "MTSSerialFlowControl.h"
 #include "PhoneAppIO.h"
@@ -65,6 +68,16 @@
 void setup();
 void getRadioInput(char *ibuffer, int size);
 
+#define BLENANO  0  // BLE Nano vs. TA New Baseboard (rev Aug-Nov 2015.)
+
+#if BLENANO
+#define SERTX  USBTX
+#define SERRX  USBRX
+#else  // Same RTS pin used by all (P0_08) and unused CTS (P0_10)
+#define SERTX  P0_18
+#define SERRX  P0_17
+#endif
+
 static Timer tmr;
 
 unsigned long millis()
@@ -74,7 +87,7 @@
 
 unsigned long micros()
 {
-    return tmr.read_us();    
+    return tmr.read_us();
 }
 
 extern "C"
@@ -89,23 +102,29 @@
 }
 
 // DigitalOut rts( RTS_PIN_NUMBER );
-//DigitalIn cts( CTS_PIN_NUMBER, PullDown );  // We'll use as a mode switch for serial data source.  TODO
+DigitalIn cts( CTS_PIN_NUMBER, PullDown );  // We'll use as a mode switch for serial data source.  TODO
 
 // Check if we should swap serial Rx/Tx for early rev of "Little Brain"
-//DigitalIn trSwp( P0_30, PullUp );
+DigitalIn trSwp( P0_30, PullUp );
 
 // Wait to settle.
 int foo = (wait( 0.1 ), 0);
 
 // Not using "LED" or "LED1" because target NRF51822 for FOTA uses different pins.
-static DigitalOut led0( P0_19, 1 );                  // BLE Nano      Low =On
-static DigitalOut led1( P0_3,  0 );                  // TA Baseboard  High=On  (OK on Nano: Alt RxD)
+static DigitalOut led0( P0_19, 1 );           // TA New Baseboard  LED High=On / Buzzer Low=En ("STATUS")  (OK on Nano: LED Low=On)
+                                              // Note: TA New Baseboard LED off only if Buzzer is sounding.
+static DigitalOut led1( P0_21, 0 );           // TA New Baseboard  High=On  (OK on Nano: NC)
+DigitalOut led2( P0_22, 1 );                  // TA New Baseboard  High=On  (OK on Nano: NC)
+
+// DigitalOut led1( P0_3,  0 );                  // TA Baseboard  High=On  (OK on Nano: Alt RxD)
 // DigitalOut led1( (trSwp ? P0_4 : P0_3), 0 );  // TA Baseboard  High=On  (And don't use P0_4 on Nano)
 
+DigitalOut buzz( P0_20, 1 );                  // TA New Baseboard  Low=On  (OK on Nano: NC)
+
 // App timer, app scheduler, and pstorage are already setup by bootloader.
 
 static BLEDevice  ble;
-//int trSwp = 0;
+
 
 // Note:  From the datasheet:
 //  PSELRXD, PSELRTS, PSELTRTS and PSELTXD must only be configured when the UART is disabled.
@@ -122,8 +141,8 @@
 // MTSSerialFlowControl uses "manual" (non-hardware-low-level) flow control based on its
 //  internal buffer--Rx servicing usually is fast enough not to need hw flow control, so it's okay.
 //
-// mts::MTSSerialFlowControl pcfc( (trSwp ? USBRX : USBTX), (trSwp ? USBTX : USBRX), RTS_PIN_NUMBER, CTS_PIN_NUMBER, 384, 2688 );
-//mts::MTSSerial pcfc( USBTX, USBRX, 256, 1280, RTS_PIN_NUMBER, NC );  // 256, 2560
+// mts::MTSSerialFlowControl pcfc( (trSwp ? SERRX : SERTX), (trSwp ? SERTX : SERRX), RTS_PIN_NUMBER, CTS_PIN_NUMBER, 384, 2688 );
+//mts::MTSSerial pcfc( (trSwp ? SERRX : SERTX), (trSwp ? SERTX : SERRX), 128, 64, RTS_PIN_NUMBER, NC );  // 256, 1280  // 256, 2560
 
 uint8_t txPayload[TXRX_BUF_LEN] = { 0 };
 
@@ -131,16 +150,24 @@
 char deviceName[6];  // "TAF00";
 Gap::address_t   macAddr;
 Gap::addr_type_t *pAdType;
+static const uint16_t uuid16_list[] = { GattService::UUID_DEVICE_INFORMATION_SERVICE,
+                                        GattService::UUID_BATTERY_SERVICE };
+static const uint8_t  batt_and_id[] = { GattService::UUID_BATTERY_SERVICE & 0xff,
+                                        GattService::UUID_BATTERY_SERVICE >> 8,
+                                        99,          // Batt level TODO
+                                        'T', 'X' };  // Custom ID trick
+
+UARTService *uartServicePtr;
+PhoneAppIO  *phoneP;
 
 // Buffer for holding data from the phone
 // to the device
-static char phoneToDev[200] = {0};
+#define PHTODEV_BUF_LEN    200  /**/
+/// static char phoneToDev[200] = {0};
+static char phoneToDev[PHTODEV_BUF_LEN] = {0};
 
-// Current position in the buffer
-static int phoneToDevPos = 0; 
-
-UARTService *uartServicePtr;
-PhoneAppIO  *phoneP;
+/// // Current position in the buffer
+/// static int phoneToDevPos = 0;
 
 extern TA ta;
 
@@ -154,12 +181,16 @@
                          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();
     ta.post_color(0);
 }
@@ -171,7 +202,7 @@
     if( (err == BLE_ERROR_BUFFER_OVERFLOW) ||
         (err == BLE_ERROR_PARAM_OUT_OF_RANGE ) )
     {
-       // pcfc.printf( "\r\nBLE %d!  ", err );
+      // pcfc.printf( "\r\nBLE %d!  ", err );
 
     } else if ( err == BLE_STACK_BUSY )
       {
@@ -181,10 +212,11 @@
     return  (err != BLE_ERROR_NONE);
 }
 
-/* Writes the string given to the phone.
- *
- * @param *data - the string to send.
- */
+/// /* Writes the string given to the phone.
+///  *
+/// * @param *data - the string to send.
+/// */
+/***
 static void writeToPhoneImpl(char *data)
 {
     if (phoneP != NULL)
@@ -208,19 +240,53 @@
         phoneP->maybeHandleWrite();
     }
 }
+***/
 
-static char wtp_buff[150] = {0};
+/// static char wtp_buff[150] = {0};
 extern "C" void writeToPhone(char *format, ...)
 {
     va_list arg;
     va_start(arg, format );
     
-    vsnprintf(wtp_buff, sizeof(wtp_buff), format, arg);
-    
-    writeToPhoneImpl(wtp_buff);    
+///    vsnprintf(wtp_buff, sizeof(wtp_buff), format, arg);
+/**/phoneP->vprintf( format, arg );
+
+///    writeToPhoneImpl(wtp_buff);    
+
+/**/// Also write same to serial port... TODO
+/**/ // pcfc.vprintf( format, arg );
+
     va_end(arg);
 }
 
+/**/ // Byte bits to ASCII - Use until we convert protocol to ASCII-hex.
+extern "C" void writeBitsToPhone( uint8_t byte, uint8_t minbits )
+{
+    static char ascbits[9] = { 0 };
+    int pos = 0;
+    if( 0 == minbits )  minbits = 1;
+
+    uint16_t ibyt = byte & 0xFF;
+    bool leading0 = true;
+
+    for( short b=7; b >= 0; b-- )
+    {
+        ibyt<<=1;
+        if( ibyt & 0x100 )
+        {
+            leading0 = false;
+            ascbits[pos++] = '1';
+
+        } else if( !leading0 || (b < minbits) )
+          {
+              ascbits[pos++] = '0';
+          }
+    }
+    ascbits[pos] = '\0';
+
+    writeToPhone( "%s", ascbits );
+}
+
 void onDataWritten( const GattCharacteristicWriteCBParams *params )
 {
     if( phoneP != NULL )
@@ -229,9 +295,18 @@
         
         if( 0 != bytesRead )
         {
-            memcpy(phoneToDev+phoneToDevPos, txPayload, bytesRead);
-            phoneToDevPos += bytesRead;
-            
+///            memcpy(phoneToDev+phoneToDevPos, txPayload, bytesRead);
+///            phoneToDevPos += bytesRead;
+
+          /*
+            DEBUG( "received %u bytes\n\r", bytesRead );
+
+            // Also write to serial port...
+//            pcfc.printf( "From app: " );
+            pcfc.write( (char *)txPayload, bytesRead );
+//            pcfc.printf( "\r\n" );
+          */
+
             return;
         }
     }
@@ -243,10 +318,34 @@
 
 void toPhoneChk( void )
 {
+    if( phoneP != NULL )
+    {
+      /*
+        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++ )
+        {
+        /// For from-serial straight to-phone.
+        /// if( 0 > phoneP->putchar( ch ) )
+        /// {
+        ///     pcfc.printf( " * " );
+        ///     break;
+        /// }
 
+            // For from-serial inject-to-dev as-if from phone.          
+            phoneP->injectHandleRead( &ch, 1 );
+
+            if( (cnt >= 20) && ('\n' == ch) )  break;
+        }
+      */
+        // Write to outgoing characteristic if anything is pending.
+        if( 0 != phoneP->maybeHandleWrite() )
+        {
+            // pcfc.printf( "ToPhoneHandler \r\n" );
+        }
+    }
 }
-
-
+/*
 static uint32_t boot_cnt_data = 0;
 static uint16_t data_block    = 9*20 +75;   // Last block -- Use for app-start count.
 static uint16_t data_size     = 4;
@@ -255,6 +354,7 @@
 static bool     data_cleared  = false;
 static bool     data_stored   = false;
 static pstorage_handle_t pstorage_id;
+
 static uint32_t pstorage_read_test()
 {
     uint32_t err_code;
@@ -308,6 +408,7 @@
 
     return  err_code;
 }
+
 static void pstorage_cb_handler( pstorage_handle_t *handle, uint8_t op_code, uint32_t result, uint8_t *p_data, uint32_t data_len )
 {
     switch( op_code )
@@ -350,8 +451,11 @@
               //pcfc.printf( "\r\nWarn: pstorage clear operation error: %x\r\n", result );
           }
         break;
+      //default:
+        //pcfc.printf( "\r\nWarn: pstorage unknown op: %x  error: %x\r\n", op_code, result );
     }
 }
+
 static uint32_t pstorage_setup()
 {
     pstorage_module_param_t pstorage_param;    
@@ -363,11 +467,18 @@
 
     return  pstorage_register( &pstorage_param, &pstorage_id );
 }
+*/
 
 void periodicCallback( void )
 {
+    static int foo;
+    foo++;
+#if BLENANO
     led0 = !led0;
+#endif
     led1 = !led1;
+    led2 = !led2;
+//    buzz = (foo & 2)>>1;
 //    rts  = !rts;
 }
 
@@ -387,7 +498,17 @@
 int main( void )
 {
     Ticker ticker;
-    ticker.attach( periodicCallback, 0.1 );
+    ticker.attach( periodicCallback, 0.5 /*** 0.1 ***/ /* 1 */ );
+
+  /*
+    // Thread thread( led_thread );
+  */
+
+ /////pcfc.baud( 57600 );
+
+  /*
+    DEBUG( "Initialising the nRF51822\n\r" );
+  */
 
     ble.init();
     
@@ -406,62 +527,118 @@
     ble.getAddress( pAdType, macAddr );
     sprintf( deviceName, "T%02X%02X", macAddr[1], macAddr[0] );
 
+    /////pcfc.printf( "\r\nNano nano!   I am \"%s\"\r\n", deviceName );
+
+  /*
+#if LOOPBACK_MODE
+    pcfc.printf( "\r\nIn BLE Loopback mode.\r\n" );
+#endif
+  */
+
     uint32_t p_count;
     uint32_t pstorageErr = pstorage_init();  // This needs to be called, even though apparently called in bootloader--Check other stuff.
     pstorage_access_status_get( &p_count );
 
+  /*
+//    pcfc.printf( "\r\nInitial pstorage count: %d\r\n", p_count );
+
+    if( NRF_SUCCESS != pstorageErr )  pcfc.printf( "\r\nWarn: pstorage init error: %x\r\n", pstorageErr );
+      else
+      {
+          pstorageErr = pstorage_setup();
+          if( NRF_SUCCESS != pstorageErr )  pcfc.printf( "\r\nWarn: pstorage setup error: %x\r\n", pstorageErr );
+            else
+            {
+                pstorageErr = pstorage_read_test();
+                if( NRF_SUCCESS != pstorageErr )  pcfc.printf( "\r\nWarn: pstorage read attempt error: %x\r\n", pstorageErr );
+                  else
+                  {
+                      // In this test setup, we use the load callback to signal start to clear,
+                      //  then we use the clear callback to signal start to write.
+                  }
+            }
+      }
+    */
+
     ble.accumulateAdvertisingPayload( GapAdvertisingData::COMPLETE_LOCAL_NAME,
                                       (const uint8_t *)deviceName, strlen(deviceName) );
-    ble.accumulateAdvertisingPayload( GapAdvertisingData::INCOMPLETE_LIST_128BIT_SERVICE_IDS,
-                                      (const uint8_t *)UARTServiceUUID_reversed, sizeof(UARTServiceUUID_reversed) );
+
+// Moved to scan response packet to give more room in AD packet...
+//    ble.accumulateAdvertisingPayload( GapAdvertisingData::INCOMPLETE_LIST_128BIT_SERVICE_IDS,
+//                                      (const uint8_t *)UARTServiceUUID_reversed, sizeof(UARTServiceUUID_reversed) );
 
+    ble.accumulateAdvertisingPayload( GapAdvertisingData::COMPLETE_LIST_16BIT_SERVICE_IDS,
+                                      (uint8_t *)uuid16_list, sizeof( uuid16_list ) );
+    ble.accumulateAdvertisingPayload( GapAdvertisingData::SERVICE_DATA,
+                                      (uint8_t *)batt_and_id, sizeof( batt_and_id ) );  // Unused batt lev + "TX"
+
+    ble.accumulateScanResponse( GapAdvertisingData::INCOMPLETE_LIST_128BIT_SERVICE_IDS,
+                                (const uint8_t *)UARTServiceUUID_reversed, sizeof( UARTServiceUUID_reversed ) );
 
     ble.setAdvertisingInterval( Gap::MSEC_TO_ADVERTISEMENT_DURATION_UNITS( 200 ) );
     ble.startAdvertising();
 
     DeviceInformationService deviceInfo( ble, "TRX", "TrueAgility", "SN0001", "hw-rev1", "fw-rev1" );
+    BatteryService battService( ble );
 
-    /* Enable over-the-air firmware updates. Instantiating DFUSservice introduces a
+    /* Enable over-the-air firmware updates. Instantiating DFUService introduces a
      * control characteristic which can be used to trigger the application to
      * handover control to a resident bootloader. */
     DFUService dfu( ble );
 
-    UARTService uartService ( ble );
+    UARTService uartService( ble );
     uartServicePtr = &uartService;
 
-    PhoneAppIO *phone = new PhoneAppIO(ble, 
-                                       uartServicePtr->getRXCharacteristicHandle(),
-                                       uartServicePtr->getTXCharacteristicHandle() );
-                           
+    PhoneAppIO *phone = new PhoneAppIO( ble,
+                                        uartServicePtr->getRXCharacteristicHandle(),
+                                        uartServicePtr->getTXCharacteristicHandle() );
+
     phone->loopbackMode = LOOPBACK_MODE;
     phoneP = phone;
     
-    DigitalOut *buzzPin = new DigitalOut(p20);
-    *buzzPin = 1;
+//    DigitalOut *buzzPin = new DigitalOut(p20);
+//    *buzzPin = 1;
     setup();
     //radio_init();
     tmr.start();
     
     // Main Loop
-    while( true)
+    while( true )  // for( uint32_t loop=1; ;loop++ )
     {
         ble.waitForEvent();
-        
+
+/**/    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() );
+
+        app_sched_execute();  // Attempt to get pstorage enqueued cmd callbacks.
+      */
+
+/***
         if (phoneToDevPos > 0)
         {
             getRadioInput(phoneToDev, phoneToDevPos ); 
             phoneToDevPos = 0;   
         }
-        
+***/
+
+/**/    int bytes = MIN( PHTODEV_BUF_LEN, phoneP->readable() );
+/**/    getRadioInput( phoneToDev, phoneP->read( phoneToDev, bytes, 1 ) );
+
         loop();
         //radio_loop();
-        
+
+/***
         if (connected)
         {
             phoneP->maybeHandleWrite(); 
         }
 
         while( 0 <= phone->getchar() );  // Eat input.
+***/
     }
 }