Important changes to repositories hosted on mbed.com
Mbed hosted mercurial repositories are deprecated and are due to be permanently deleted in July 2026.
To keep a copy of this software download the repository Zip archive or clone locally using Mercurial.
It is also possible to export all your personal repositories from the account settings page.
Fork of football_project by
Revision 60:d1fad57e8bfb, committed 2016-01-16
- Comitter:
- elmbed
- Date:
- Sat Jan 16 19:11:49 2016 +0000
- Parent:
- 59:297133497153
- Child:
- 61:dd7002ceea96
- Commit message:
- Buggy pattern mode
Changed in this revision
--- a/DataStore.cpp Sat Jan 16 17:31:27 2016 +0000
+++ b/DataStore.cpp Sat Jan 16 19:11:49 2016 +0000
@@ -37,6 +37,11 @@
*/
static void writeError(uint32_t code)
{
+ if (!Dbg)
+ {
+ return;
+ }
+
switch(code)
{
case NRF_SUCCESS:
@@ -107,12 +112,10 @@
if( NRF_SUCCESS == result )
{
data_loaded = true; // Flag to signal load is done.
- writeToPhone("DSS\r\n");
}
else
{
data_err = true;
- writeToPhone("DSE %s\r\n", result);
}
break;
case PSTORAGE_UPDATE_OP_CODE:
@@ -120,12 +123,10 @@
if( NRF_SUCCESS == result )
{
data_stored = true; // Flag to signal store is done.
- writeToPhone("DSS\r\n");
}
else
{
data_err = true;
- writeToPhone("DSE: %d\r\n", result);
}
break;
case PSTORAGE_CLEAR_OP_CODE:
@@ -154,7 +155,7 @@
{
pstorage_module_param_t pstorage_param;
- pstorage_param.block_size = sizeof(cone_table);
+ pstorage_param.block_size = data_size;
pstorage_param.block_count = 4;
pstorage_param.cb = pstorage_cb_handler;
@@ -222,6 +223,45 @@
writeError(err_code);
}
+/* Writes the selected pattern to pstore.
+ *
+ * @param pattern - the pattern index (0 based)
+ */
+void datastore_write_pattern(uint8_t pattern)
+{
+ uint8_t *cones = &cone_table[pattern * STATIONS];
+ uint8_t *masks = &mask_table[pattern * STATIONS];
+ uint16_t *times = &time_table[pattern * STATIONS];
+
+ uint32_t err_code = 0;
+ pstorage_handle_t p_block_id;
+
+ err_code = pstorage_block_identifier_get(&pstorage_id, CONE_BLOCK, &p_block_id);
+ writeError(err_code);
+ err_code = pstorage_store(&p_block_id, cones, sizeof(uint8_t) * STATIONS, sizeof(uint8_t) * STATIONS * pattern);
+ writeError(err_code);
+
+ err_code = pstorage_block_identifier_get(&pstorage_id, MASK_BLOCK, &p_block_id);
+ writeError(err_code);
+ err_code = pstorage_store(&p_block_id, masks, sizeof(uint8_t) * STATIONS, sizeof(uint8_t) * STATIONS * pattern);
+ writeError(err_code);
+
+ // Calculate which block the time value is in
+ int tblock = pattern * STATIONS > data_size ? TIME_BLOCK_1 : TIME_BLOCK_0;
+ int toffset = sizeof(uint16_t) * STATIONS * pattern;
+
+ if (tblock == 1)
+ {
+ toffset -= data_size;
+ }
+
+ err_code = pstorage_block_identifier_get(&pstorage_id, tblock, &p_block_id);
+ writeError(err_code);
+ err_code = pstorage_store(&p_block_id, (uint8_t*)times, sizeof(uint16_t) * STATIONS, toffset);
+ writeError(err_code);
+}
+
+
/* Gets the cone table
*
* @return pointer to cone table
@@ -249,30 +289,40 @@
return time_table;
}
+/* Populates the patterns with data useful for testing
+ */
void write_test_pattern()
{
- uint8_t cone = 1;
+ uint8_t cone = 1;
+ uint16_t start_time = 4000;
+ uint16_t time = 4000;
+ int idx = 0;
- //for (int j = 1; j <= SEQUENCES; ++j)
+ for (int j = 1; j <= SEQUENCES; ++j)
{
for (int i = 0; i < STATIONS; ++i)
{
- cone_table[i] = cone;
- mask_table[i] = 0x07;
- time_table[i] = 5000;
-
- //writeToPhone("PT: %d %x %d\r\n", cone_table[i], mask_table[i], time_table[i]);
-
+ cone_table[idx] = cone;
+ mask_table[idx] = 0x07;
+ time_table[idx++] = time;
++cone;
-
+
if (cone >= 3)
{
cone = 1;
- }
- }
+ }
+
+ time += 1000;
+
+ if (time > 20000)
+ {
+ time = start_time;
+ }
+ }
+
+ start_time += 2000;
+ time = start_time;
}
-
- datastore_write_patterns();
}
void init_datastore()
@@ -282,6 +332,10 @@
pstorage_setup();
datastore_read_patterns();
- //write_test_pattern();
+
+ if(Dbg)
+ {
+ write_test_pattern();
+ }
}
--- a/main.cpp Sat Jan 16 17:31:27 2016 +0000
+++ b/main.cpp Sat Jan 16 19:11:49 2016 +0000
@@ -138,11 +138,6 @@
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)
-
int tickTock = 0; // Counter used by periodicCallback().
class ChgChg : public InterruptIn
@@ -193,7 +188,6 @@
// 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
-Serial pc(SERTX,SERRX);
uint8_t txPayload[TXRX_BUF_LEN] = { 0 };
@@ -313,11 +307,6 @@
const Gap::address_t peerAddr, const Gap::ConnectionParams_t *connParams )
{
connected = true;
-
- // DEBUG( "Connected!\n\r" );
-
-// char dummy;
-// writeToPhone( "Hi. Curr stack bot: 0x%08X\r\n", &dummy );
}
void disconnectionCallback( Gap::Handle_t handle, Gap::DisconnectionReason_t reason )
@@ -326,9 +315,6 @@
updateBatt( getBattLevel() );
- // DEBUG( "Disconnected!\n\r" );
- // DEBUG( "Restarting the advertising process\n\r" );
-
ble.startAdvertising();
ta.post_color(0);
@@ -358,10 +344,7 @@
va_list arg;
va_start( arg, format );
-/**/phoneP->vprintf( format, arg );
-
-/**/// Also write same to serial port... TODO
-/**/ // pcfc.vprintf( format, arg );
+ phoneP->vprintf( format, arg );
va_end(arg);
}
@@ -485,25 +468,9 @@
}
}
-/*
-void led_thread( void const *args )
-{
- while( true )
- {
- led0 = !led0;
- led1 = !led1;
- Thread::wait( 1000 );
- }
-}
-*/
-
-
int main( void )
{
Ticker ticker;
-////// ticker.attach( periodicCallback, 0.125 /** 0.2 **/ /** 0.5 **/ /* 1 */ );
-
- pc.baud( 57600 );
ble.init();
@@ -552,8 +519,6 @@
unsigned long lastMillis = millis();
unsigned long currMillis = lastMillis +25;
- int counter = 0;
-
// Main Loop
while( true )
{
--- a/main.cpp.orig Sat Jan 16 17:31:27 2016 +0000
+++ /dev/null Thu Jan 01 00:00:00 1970 +0000
@@ -1,821 +0,0 @@
-/*
- * 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.
- * Maybe could use the now-unused CTS pin for that.
- *
- * Using
- * rev 327 of BLE_API
- * rev 102 of nRF51822 w/ modification--See below
- * 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
- * so things compile properly.*
- * * Now using $Sub$$UART0_IRQHandler to override UART0_IRQHandler without needing to use lib source.
- *
- * *** Now using mbed-src again to modify startup code to use full 32k RAM on QFAC part 20160104 ALS
- * while still using RBL BLE Nano as a target:
- * Copied files nRF51822.sct and startup_nRF51822.s
- * from targets/cmsis/TARGET_NORDIC/TARGET_MCU_NRF51822/TOOLCHAIN_ARM_STD/TARGET_MCU_NORDIC_32K
- * to targets/cmsis/TARGET_NORDIC/TARGET_MCU_NRF51822/TOOLCHAIN_ARM_STD/TARGET_MCU_NORDIC_16K
- * (Stomping the 16k settings w/ 32k settings.)
- *
- * Changed
- * nRF51822/nordic/pstorage_platform.h PSTORAGE_MIN_BLOCK_SIZE changed from 0x010 to 4.
- */
-
-/* mbed Microcontroller Library
- * Copyright (c) 2006-2013 ARM Limited
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-#include <cstdarg>
-#include <cstdio>
-#include "mbed.h"
-// #include "rtos.h"
-#include "BLEDevice.h"
-
-#include "DFUService.h"
-#include "UARTService.h"
-#include "DeviceInformationService.h"
-#include "BatteryService.h"
-
-#include "MTSSerialFlowControl.h"
-#include "PhoneAppIO.h"
-
-#include "types.h"
-#include "TA.h"
-
-#define NEED_CONSOLE_OUTPUT 1 /* Set this if you need debug messages on the console;
- * it will have an impact on code-size and power consumption. */
-
-#define LOOPBACK_MODE 0 // Loopback mode
-
-#if NEED_CONSOLE_OUTPUT
-#define DEBUG(...) { printf(__VA_ARGS__); }
-#else
-#define DEBUG(...) /* nothing */
-#endif /* #if NEED_CONSOLE_OUTPUT */
-
-#ifdef MASTER
-static bool is_master = true;
-#else
-static bool is_master = false;
-#endif
-
-void loop();
-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()
-{
- return tmr.read_ms();
-}
-
-unsigned long micros()
-{
- return tmr.read_us();
-}
-
-extern "C"
-{
-#include "softdevice_handler.h" // Attempt to get pstorage enqueued cmd callbacks.
-#include "app_timer.h"
-#include "pstorage.h"
-
-// void My_UART0_IRQHandler();
-
- void pin_mode( PinName, PinMode );
-}
-
-#if BLENANO
-#define ADC_IN_BATT P0_6
-#define CHARGING_IN P0_29
-#else
-#define ADC_IN_BATT P0_4
-#define CHARGING_IN P0_2
-#endif
-AnalogIn batt( ADC_IN_BATT );
-
-// DigitalOut rts( RTS_PIN_NUMBER );
-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 );
-
-// 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 ); // TA New Baseboard LED High=On ("STATUS") (OK on Nano: LED Low=On)
-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)
-
-int tickTock = 0; // Counter used by periodicCallback().
-
-class ChgChg : public InterruptIn
-{
- public:
- ChgChg( PinName pin, PinMode pull=PullUp ) : InterruptIn( pin )
- {
- mode( pull ); // Set pull mode
- fall( this, &ChgChg::chargeStart ); // Attach ISR for fall
- rise( this, &ChgChg::chargeStop ); // Attach ISR for rise
-
- led0 = !read();
- }
- void chargeStart()
- {
- led0 = 1;
- tickTock = 0; // Trigger batt level update.
- }
- void chargeStop()
- {
- led0 = 0;
- tickTock = 0; // Trigger batt level update.
- }
-};
-ChgChg notcharge( CHARGING_IN, PullUp );
-
-
-// App timer, app scheduler, and pstorage are already setup by bootloader.
-
-static BLEDevice ble;
-
-
-// Note: From the datasheet:
-// PSELRXD, PSELRTS, PSELTRTS and PSELTXD must only be configured when the UART is disabled.
-// 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 *
-// [* 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.] - No need now.
-// * Now using $Sub$$UART0_IRQHandler to override UART0_IRQHandler without needing to use lib source.
-// NVIC_SetVector( UART0_IRQn, (uint32_t)My_UART0_IRQHandler ); // Might have worked--No need.
-//
-// 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 ? 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 };
-
-
-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 uint8_t batt_and_id[] = { GattService::UUID_BATTERY_SERVICE & 0xff,
- GattService::UUID_BATTERY_SERVICE >> 8,
- 99, // Batt level
- 'T', 'X' }; // Custom ID trick
-
-UARTService *uartServicePtr;
-PhoneAppIO *phoneP;
-BatteryService *battServiceP;
-
-// Buffer for holding data from the phone
-// to the device
-static char phoneToDev[MAX_LEN] = {0};
-
-extern TA ta;
-
-extern void radio_init();
-extern void radio_loop(int mac);
-
-void setAdvData()
-{
- ble.accumulateAdvertisingPayload( GapAdvertisingData::BREDR_NOT_SUPPORTED |
- GapAdvertisingData::LE_GENERAL_DISCOVERABLE );
- ble.setAdvertisingType( GapAdvertisingParams::ADV_CONNECTABLE_UNDIRECTED );
-
- // Get MAC addr so we can create a device name using it.
- ble.getAddress( pAdType, macAddr );
-
- sprintf( deviceName, "%c%02X%02X", (is_master?'T':'S'), macAddr[1], macAddr[0] );
-
- ble.accumulateAdvertisingPayload( GapAdvertisingData::COMPLETE_LOCAL_NAME,
- (const uint8_t *)deviceName, strlen(deviceName) );
-
-// 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 ) ); // Batt lev + "TX"
-
- ble.accumulateScanResponse( GapAdvertisingData::INCOMPLETE_LIST_128BIT_SERVICE_IDS,
- (const uint8_t *)UARTServiceUUID_reversed, sizeof( UARTServiceUUID_reversed ) );
-}
-
-void updateBatt( uint8_t pct )
-{
- static uint8_t prev;
- static bool wasCharging;
-
- if( notcharge )
- {
- if( wasCharging ) ta.beep_off(); // Alarm Clock TMP TODO remove once hardware is fixed.
-
- if( pct > 100 ) pct = 100;
-
- if( wasCharging )
- {
- pct = 102; // Show 102% at charger unplug.
- tickTock = 50; // Cause another normal update in 5s (60 -50 = 10 half s).
-
- } else
- {
- // Use if we update quite often.
-// if( abs( (int)prev -(int)pct ) < 3 ) return; // Don't register change of less than 3%.
- }
-
- prev = pct;
- wasCharging = false;
-
- } else // Charging
- {
- // Plugged-in seems to add ~23% to level, so checking for 99% is like 76% unplugged.
- // But I had a failure with a smaller gap, so reduced another 8%.
- if( pct >= 91 ) ta.beep( 15000 ); // Alarm Clock TMP TODO remove once hardware is fixed.
-
- if( !wasCharging )
- pct = 101; // Show 101% at start of charging.
- wasCharging = true; // Force show when done charging.
- }
-
- if( pct <= 10 ) ta.batteryLow = true;
-
- batt_and_id[2] = pct;
- ble.clearAdvertisingPayload();
- setAdvData();
- ble.setAdvertisingPayload();
-
- if( NULL != battServiceP ) battServiceP->updateBatteryLevel( pct );
-}
-
-#define BAT_TOP 793 // 3250 // 52000
-#define BAT_BOT 684 // 2800 // 44800
-uint8_t getBattLevel()
-{
- int battI = (int)(batt * 1000.f);
- // Normalize to usable range...
- // Note: These levels should also give 0% if powered by programmer.
- if( battI > BAT_TOP ) battI = BAT_TOP; // Fully charged reading ~3.85V
- if( battI < BAT_BOT ) battI = BAT_BOT; // Device failing reading ~3.32V
- battI-= BAT_BOT;
- return (uint8_t)(battI*100 / (BAT_TOP-BAT_BOT));
-}
-
-// True when connected to a phone
-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" );
-
-// char dummy;
-// writeToPhone( "Hi. Curr stack bot: 0x%08X\r\n", &dummy );
-}
-
-void disconnectionCallback( Gap::Handle_t handle, Gap::DisconnectionReason_t reason )
-{
- connected = false;
-
- updateBatt( getBattLevel() );
-
- // DEBUG( "Disconnected!\n\r" );
- // DEBUG( "Restarting the advertising process\n\r" );
-
- ble.startAdvertising();
-
- ta.post_color(0);
-}
-
-bool updateCharacteristic( GattAttribute::Handle_t handle, const uint8_t *data, uint16_t bytesRead )
-{
- ble_error_t err = ble.updateCharacteristicValue( handle, data, bytesRead );
-
- if( (err == BLE_ERROR_BUFFER_OVERFLOW) ||
- (err == BLE_ERROR_PARAM_OUT_OF_RANGE ) )
- {
- // pcfc.printf( "\r\nBLE %d! ", err );
-
- } else if ( err == BLE_STACK_BUSY )
- {
- // Common error when pumping data.
- }
-
- return (err != BLE_ERROR_NONE);
-}
-
-extern "C" void writeToPhone(char *format, ...)
-{
- if( NULL == phoneP ) return;
-
- va_list arg;
- va_start( arg, format );
-
-/**/phoneP->vprintf( format, arg );
-
-/**/// Also write same to serial port... TODO
-/**/ // pcfc.vprintf( format, arg );
-
- va_end(arg);
-}
-
-/**/ // Byte bits to ASCII.
-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 )
- {
- uint16_t bytesRead = phoneP->maybeHandleRead( params ); // Also writes to txPayload
-
- if( 0 != 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;
- }
- }
-}
-
-void onDataSent( unsigned count )
-{
-}
-
-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;
-static uint16_t data_offset = 0; // 12 for 16-byte blocks.
-static bool data_loaded = false;
-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;
-
- pstorage_handle_t p_block_id;
-
- do
- {
- err_code = pstorage_block_identifier_get( &pstorage_id, data_block, &p_block_id );
- if( NRF_SUCCESS != err_code ) break;
-
- err_code = pstorage_load( (uint8_t *)&boot_cnt_data, &p_block_id, data_size, data_offset );
- if( NRF_SUCCESS != err_code ) break;
-
- } while( 0 );
-
- return err_code;
-}
-static uint32_t pstorage_clear_test()
-{
- uint32_t err_code;
-
- pstorage_handle_t p_block_id;
-
- do
- {
- err_code = pstorage_block_identifier_get( &pstorage_id, data_block, &p_block_id );
- if( NRF_SUCCESS != err_code ) break;
-
- err_code = pstorage_clear( &p_block_id, PSTORAGE_MIN_BLOCK_SIZE );
- if( NRF_SUCCESS != err_code ) break;
-
- } while( 0 );
-
- return err_code;
-}
-static uint32_t pstorage_write_test()
-{
- uint32_t err_code;
-
- pstorage_handle_t p_block_id;
-
- do
- {
- err_code = pstorage_block_identifier_get( &pstorage_id, data_block, &p_block_id );
- if( NRF_SUCCESS != err_code ) break;
-
- err_code = pstorage_store( &p_block_id, (uint8_t *)&boot_cnt_data, data_size, data_offset );
-
- } while( 0 );
-
- 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 )
- {
- case PSTORAGE_LOAD_OP_CODE:
- if( NRF_SUCCESS == result )
- {
- // Load operation successful.
- data_loaded = true; // Flag to signal load is done.
-
- } else
- {
- // Load operation failed.
- //pcfc.printf( "\r\nWarn: pstorage load operation error: %x\r\n", result );
- }
- break;
- case PSTORAGE_UPDATE_OP_CODE:
- case PSTORAGE_STORE_OP_CODE:
- if( NRF_SUCCESS == result )
- {
- // Store operation successful.
- data_stored = true; // Flag to signal store is done.
-
- } else
- {
- // Store operation failed.
- //pcfc.printf( "\r\nWarn: pstorage store operation error: %x\r\n", result );
- }
- // Source memory can now be reused or freed.
- break;
- case PSTORAGE_CLEAR_OP_CODE:
- if( NRF_SUCCESS == result )
- {
- // Clear operation successful.
- data_cleared = true; // Flag to store to the same data area.
-
- } else
- {
- // Clear operation failed.
- //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;
-
- // Setup pstorage with 9*20 +76 blocks of 4 bytes each. (or 9*20/4 + 19 for 16 byte blocks)
- pstorage_param.block_size = 4; // Recommended to be >= 4 bytes.
- pstorage_param.block_count = 9*20 +76; // 9 Sequences x 20 Stations + 76 blocks to fill out to 1k.
- pstorage_param.cb = pstorage_cb_handler;
-
- return pstorage_register( &pstorage_param, &pstorage_id );
-}
-
-
-void periodicCallback( void )
-{
- static unsigned long prevMillis = millis() +125;
- static int callCnt = 0;
-
- unsigned long elapsedMillis = millis() -prevMillis;
-
- if( elapsedMillis >= 125 )
- {
- do
- {
- prevMillis = millis();
-
-// if( is_master && ((callCnt % 3) == 0) ) writeToPhone( "Rnd: %x\r\n", rndHW() );
-
- if( (callCnt % 4) != 0 ) break;
-
-#if BLENANO
- led0 = !led0;
-#endif
- led1 = !led1;
- led2 = !led2;
-// rts = !rts;
-
- // Check battery level every 30s.
- if( 0 == (tickTock % 60 ) ) updateBatt( getBattLevel() );
-
- tickTock++;
-
- } while( false );
-
- callCnt++;
- }
-}
-
-/*
-void led_thread( void const *args )
-{
- while( true )
- {
- led0 = !led0;
- led1 = !led1;
- Thread::wait( 1000 );
- }
-}
-*/
-
-
-int main( void )
-{
- Ticker ticker;
-////// ticker.attach( periodicCallback, 0.125 /** 0.2 **/ /** 0.5 **/ /* 1 */ );
-
- /*
- // Thread thread( led_thread );
- */
-
- /////pcfc.baud( 57600 );
-
- /*
- DEBUG( "Initialising the nRF51822\n\r" );
- */
-
- ble.init();
-
- ble.onConnection( connectionCallback );
- ble.onDisconnection( disconnectionCallback );
- ble.onDataWritten( onDataWritten );
- ble.onDataSent( onDataSent );
-
- /* setup advertising */
- setAdvData();
-
- /////pcfc.printf( "\r\nNano nano! I am \"%s\"\r\n", deviceName );
-
- /*
-#if LOOPBACK_MODE
- pcfc.printf( "\r\nIn BLE Loopback mode.\r\n" );
-#endif
- */
-
- srnd( rndHW() ); // Seed the sw RNG w/ the hw.
-
- 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 );
- /// writeToPhone( "\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 );
- /// writeToPhone( "\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 );
- /// writeToPhone( "\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.
- }
- }
- }
-
-
- DeviceInformationService deviceInfo( ble, "TRX", "TrueAgility", "SN0001", "hw-rev1", "fw-rev1" );
- BatteryService battService( ble );
- battServiceP = &battService;
- updateBatt( getBattLevel() );
-
- /* 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 );
- uartServicePtr = &uartService;
-
- ble.setAdvertisingInterval( Gap::MSEC_TO_ADVERTISEMENT_DURATION_UNITS( is_master ? 132 : 132 ) );
-
- ble.startAdvertising();
-
- PhoneAppIO *phone = new PhoneAppIO( ble,
- uartServicePtr->getRXCharacteristicHandle(),
- uartServicePtr->getTXCharacteristicHandle() );
-
- phone->loopbackMode = LOOPBACK_MODE;
- phoneP = phone;
-
- setup();
- radio_init();
- tmr.start();
-
- int mac_addr = ((int)macAddr[0]);
- mac_addr |= ((int)macAddr[1] << 8);
-
- unsigned long lastMillis = millis();
- unsigned long currMillis = lastMillis +25;
-
- // Main Loop
- while( true ) // for( uint32_t loop=1; ;loop++ )
- {
-////// ble.waitForEvent();
-
- currMillis = millis();
- if( currMillis -lastMillis < 25 ) continue;
- lastMillis = currMillis;
-
- periodicCallback();
-
-/**/ 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.
- */
-
-#ifdef MASTER
-/**/ int bytes = MIN( MAX_LEN, phoneP->readable() );
- getRadioInput( phoneToDev, phoneP->read( phoneToDev, bytes, 1 ) );
-#endif
-
- loop();
- radio_loop(mac_addr);
- }
-}
-
-/**@brief Function for error handling, which is called when an error has occurred.
- *
- * @warning This handler is an example only and does not fit a final product. You need to analyze
- * how your product is supposed to react in case of error.
- *
- * @param[in] error_code Error code supplied to the handler.
- * @param[in] line_num Line number where the handler is called.
- * @param[in] p_file_name Pointer to the file name.
- */
-void $Sub$$app_error_handler( uint32_t error_code, uint32_t line_num, const uint8_t * p_file_name )
-{
- // nrf_gpio_pin_set( ASSERT_LED_PIN_NO );
- //led1 = 1;
-
- // This call can be used for debug purposes during application development.
- // @note CAUTION: Activating this code will write the stack to flash on an error.
- // This function should NOT be used in a final product.
- // It is intended STRICTLY for development/debugging purposes.
- // The flash write will happen EVEN if the radio is active, thus interrupting
- // any communication.
- // Use with care. Uncomment the line below to use.
- // ble_debug_assert_handler(error_code, line_num, p_file_name);
-
- // On assert, the system can only recover with a reset.
- NVIC_SystemReset();
-}
-
-uint32_t rndHW()
-{
- uint32_t rndVal;
- uint8_t bytes_available;
- for(;;)
- {
- sd_rand_application_bytes_available_get( &bytes_available );
- if( bytes_available >= 4 )
- {
- if( NRF_SUCCESS == sd_rand_application_vector_get( (uint8_t *)&rndVal, 4 ) )
- break;
- }
- }
-
- return rndVal;
-}
-
-static uint32_t rndZ = 0xCAFE, rndW = 0xF00D;
-// Seed for rnd()
-void srnd( uint32_t seed )
-{
- rndZ = 0xCAFE;
- rndW = seed;
-}
-
-// Simple RNG -- Allows cross-platform compat if we want to run
-// an apples-to-apples freeform competition by using same seed.
-uint32_t rnd()
-{
- rndZ = 36969 * (rndZ & 0xffff) + (rndZ >>16);
- rndW = 18000 * (rndW & 0xffff) + (rndW >>16);
-
- return ((rndZ <<16) + rndW);
-}
-
-/* EOF */
--- a/proto_code.cpp Sat Jan 16 17:31:27 2016 +0000
+++ b/proto_code.cpp Sat Jan 16 19:11:49 2016 +0000
@@ -398,8 +398,11 @@
{
active_cone = getRandomCone();
- if( Dbg ) writeToPhone("GN_AC: %d\r\n", active_cone);
-
+ if(Dbg)
+ {
+ writeToPhone("GN_AC: %d\r\n", active_cone);
+ }
+
mask = 0x07;
ta.setMask(mask & LIGHTS);
timeout = ~0;
@@ -435,7 +438,11 @@
if(ta.recieve(m_in))
{
- if( Dbg ) writeToPhone("SR: %d '%c'\r\n", m_in->cone, m_in->command);
+ if(Dbg)
+ {
+ writeToPhone("SR: %d '%c'\r\n", m_in->cone, m_in->command);
+ }
+
command = m_in->command;
value = m_in->value;
}
@@ -531,7 +538,10 @@
m->command = 'g';
ta.send(m);
- if( Dbg ) writeToPhone("ACW: %d\r\n", active_cone);
+ if(Dbg)
+ {
+ writeToPhone("ACW: %d\r\n", active_cone);
+ }
}
ta.post_color(( ta.activated())?touch_colour:idle_colour);
@@ -552,13 +562,20 @@
if(state_p == WAITING_P)
{
- if( Dbg ) writeToPhone("NSW\r\n");
+ if(Dbg)
+ {
+ writeToPhone("NSW\r\n");
+ }
+
new_state = true;
- }
+ }
}
else if(~timeout != 0 && mode == PATTERN && timer >= (timeout + ((fail_quick)?0:GRACE_PERIOD)))
{
- if( Dbg ) writeToPhone("FW\r\n");
+ if(Dbg)
+ {
+ writeToPhone("FW\r\n");
+ }
state_p = FAIL_P;
}
break;
@@ -763,8 +780,6 @@
}
else
{
- write_test_pattern();
- datastore_read_patterns();
writeToPhone("Selected pattern %d\r\n", value);
if(value <= SEQUENCES && value > 0)
@@ -774,9 +789,12 @@
times = (uint16_t*)time_table + (value-1)*STATIONS;
masks = (uint8_t*)mask_table + (value-1)*STATIONS;
- for (int i = 0; i < STATIONS; ++i)
+ if (Dbg)
{
- writeToPhone("PS: %d %x %d\r\n", cones[i], masks[i], times[i]);
+ for (int i = 0; i < STATIONS; ++i)
+ {
+ writeToPhone("PS: %d %x %d\r\n", cones[i], masks[i], times[i]);
+ }
}
}
else
@@ -1131,7 +1149,10 @@
lonely = true;
- if( Dbg ) writeToPhone("FC\r\n");
+ if(Dbg)
+ {
+ writeToPhone("FC\r\n");
+ }
int retry_count = 0;
@@ -1147,7 +1168,10 @@
unsigned long current = 0L;
unsigned long delta = 0L;
- if( Dbg ) writeToPhone("S: %lu F: %d\r\n", st, i);
+ if(Dbg)
+ {
+ writeToPhone("S: %lu F: %d\r\n", st, i);
+ }
while(1)
{
@@ -1156,7 +1180,10 @@
if(delta > 300L)
{
- if( Dbg ) writeToPhone("FT: %d %lu\r\n", i, current);
+ if(Dbg)
+ {
+ writeToPhone("FT: %d %lu\r\n", i, current);
+ }
if (++retry_count < 3)
{
@@ -1172,7 +1199,10 @@
lonely = false;
active_cones[m_in->cone] = true;
- if( Dbg ) writeToPhone("FS: %d\r\n", m_in->cone);
+ if(Dbg)
+ {
+ writeToPhone("FS: %d\r\n", m_in->cone);
+ }
break;
}
}
--- a/types.h Sat Jan 16 17:31:27 2016 +0000 +++ b/types.h Sat Jan 16 19:11:49 2016 +0000 @@ -9,9 +9,9 @@ #define SL_DEBUG(...) /* Nothing */ #endif -#define NUM_CONES 3 -#define STATIONS 20 // max length of a pattern -#define SEQUENCES 9 // number of patterns to store +const static int NUM_CONES = 3; +const static int STATIONS = 20; // max length of a pattern +const static int SEQUENCES = 9; // number of patterns to store #define MASTER //#define SLAVE
--- a/types.h.orig Sat Jan 16 17:31:27 2016 +0000
+++ /dev/null Thu Jan 01 00:00:00 1970 +0000
@@ -1,61 +0,0 @@
-#ifndef TYPES_H
-#define TYPES_H
-
-//#define D
-
-#ifdef D
-const static bool Dbg = true;
-#define SL_DEBUG(...) writeToPhone(__VA_ARGS__)
-#else
-const static bool Dbg = false;
-#define SL_DEBUG(...) /* Nothing */
-#endif
-
-#define MASTER
-//#define SLAVE
-
-// these must be here because of magic in the Arduino IDE (otherwise functions cannot retun these types
-#ifdef MASTER
-
-enum Mode_t{ IDLE, FREEFORM, PATTERN };
-#else
-enum State_t{ ACTIVE_TARGET, IDLE, FAIL, SUCCESS };
-#endif
-enum patternState_t{ START_P, WAITING_P, ACTIVE_TARGET_P, IDLE_P, FAIL_P, SUCCESS_P };
-//enum freeformState_t{ START_F, WAITING_F, ACTIVE_TARGET_F, IDLE_F };
-
-enum inputState_t{ IDLE_I, RUNNING_I, MENU_I, PATTERN_SELECT_I, TEACH_I };
-
-//enum event_t{};
-//class Events { enum e { };
-
-/*struct Event{
- enum E{none, tap, long_press, } e;
- };*/
-
-#ifdef MASTER
-const static int NODE_ID = 1;
-#else
-const static int NODE_ID = 99;
-#endif
-
-struct Event{
- uint8_t value;
- enum Types{none, tap, press, finish};
- Types type;
- /*Type t_;
-Event(Type t) : t_(t) {}
- operator Type () const {return t_;}
-private:
- //prevent automatic conversion for any other built-in types such as bool, int, etc
- template<typename T>
- operator T () const;*/
-};
-
-extern "C" void writeToPhone(char *data, ...);
-extern "C" void writeBitsToPhone( uint8_t byte, uint8_t minbits = 1 );
-extern uint32_t rndHW();
-extern void srnd( uint32_t seed );
-extern uint32_t rnd();
-
-#endif
\ No newline at end of file
