AnyCloud Bluetooth Advertising Scanner (Part 10)

Summary

We have finally reached the end of the AnyCloud Bluetooth Advertising Scanner.  In this article I will add the ability to sort the database.  In addition I will add the ability to purge a device.  And finally, truly finally, a bit of commentary.

Story

I originally built this program to help me learn about the AnyCloud Bluetooth SDK.  Well, originally I built this functionality to try to find and talk to a specific device (in an upcoming series).  The problem is that there are so many devices at my house that are blasting out so much data it is hard to see what I am looking for.  What I realized would help is add the ability to sort the devices from newest to oldest.  In addition I noticed that occasionally my database would fill up… and it would be nice to purge out old entries.  So that is what we are going to do.

There are

Article Topic
AnyCloud Bluetooth Advertising Scanner (Part 1) Introduction to AnyCloud Bluetooth Advertising
AnyCloud Bluetooth Advertising Scanner (Part 2) Creating an AnyCloud Bluetooth project
AnyCloud Bluetooth Advertising Scanner (Part 3) Adding Observing functionality to the project
AnyCloud Bluetooth Utilities Library A set of APIs for enhancement of the AnyCloud Library
AnyCloud Bluetooth Advertising Scanner (Part 4) Adding a command line to the scanner
AnyCloud Bluetooth Advertising Scanner (Part 5) Adding a history database to the scanner
AnyCloud Bluetooth Advertising Scanner (Part 6) Decoding advertising packets
AnyCloud Bluetooth Advertising Scanner (Part 7) Adding recording commands to the command line
AnyCloud Bluetooth Advertising Scanner (Part 8) Adding filtering to the scanner
AnyCloud Bluetooth Advertising Scanner (Part 9) Improve the print and add packet age
AnyCloud Bluetooth Advertising Scanner (Part 10) Sort the database

All of the code can be found at git@github.com:iotexpert/AnyCloudBLEScanner.git and https://github.com/iotexpert/AnyCloudBLEScanner.git

There are git tags in place starting at part 5 so that you can look at just that version of the code.  "git tag" to list the tags.  And "git checkout part6" to look at the part 6 version of the code.

You can also create a new project with this is a template if you have the IoT Expert Manifest Files installed

Fix the Database Data Structure

You might remember that the database was built as an array of structures.  This mean that any moving around of the data would be a require a replacement of the whole structure.

static adb_adv_t adb_database[ADB_MAX_SIZE];

To fix this problem I moved the database to a an array of pointers.

static adb_adv_t *adb_database[ADB_MAX_SIZE];

To support this, when I see a new device I malloc a block of memory to hold the actual structure.

    // If it is NOT found && you have room
    if(entry == -1)
    {
        adb_database[adb_db_count] = malloc(sizeof(adb_adv_t));

Then I had to fix all of the references to the structure.  And there were a bunch (actually 43 of them).  But the replacement was pretty simple

adb_database[…].xxx is replaced by adb_database[…]-> …. here are the three different cases

case 1: adb_database[adb_db_count].

case 2: adb_database[entry].

case 1: adb_database[i].

That was actually way less painful that I thought it was going to be.  Probably what would actually be best is a library of these data structures with an API that would not have changed when the key changed, but that I suppose, is for another day.

Add Two New Commands

Now I add the sort and purge commands to my command list.

typedef enum {
    ADB_ADD,
    ADB_PRINT_RAW,
    ADB_PRINT_DECODE,
    ADB_WATCH,
    ADB_ERASE,
    ADB_RECORD,
    ADB_FILTER,
    ADB_SORT,
    ADB_PURGE,
} adb_cmd_t;

Create the Sort Functionality

To sort, I will use the c-standard library function qsort.  It requires a function that compares two entries a/b and returns

  1. a negative number of a<b
  2. 0 if a=b
  3. a positive number if a>b

Here is the function.  Hey Hassane you like those pointers?

static int adb_sort_cmpfunc(const void * a, const void * b) 
{
    adb_adv_t *p1 = *((adb_adv_t **)a);
    adb_adv_t *p2 = *((adb_adv_t **)b);
        
    return p2->lastSeen - p1->lastSeen;
}

The sort is actually really simple now.  Just a call to sort (then I decided to print out the table)

                case ADB_SORT:
                    qsort(adb_database, adb_db_count, sizeof(adb_adv_t *), adb_sort_cmpfunc);
                    adb_db_print(ADB_PRINT_METHOD_BYTES,true,-1);
                break;

Now instead of this….

I get this…

Create the Purge Functionality

The purge function needs to do two things

  1. Free all of the memory from an entry
  2. Move the pointers so that the “purged” entry is gone.

First I erase all of the data in the linked list with the adb_eraseEntry function.

Then I free the head of the list

Then I free the actual structure

Then I move all of the pointers to squeeze the able.

static void adb_purgeEntry(int entry)
{

    adb_eraseEntry(entry);
    free(adb_database[entry]->list);
    free(adb_database[entry]->result);
    free(adb_database[entry]);
    adb_db_count -= 1;
    for(int i=entry;i<adb_db_count;i++)
    {
        adb_database[i] = adb_database[i+1];
    }
}

And you need to add the actual command.

                case ADB_PURGE:
                    if((int)msg.data0<0 || (int)msg.data0>=adb_db_count)
                    {
                        printf("Purge error %d\n",(int)msg.data0);
                        break;
                    }   
                    adb_purgeEntry((int)msg.data0);
                break;

The End & Commentary

I would like to add and maybe will one day:

  1. A connect function with a GATT browser
  2. A smarter way to deal with the fact that device change addresses

Finally a couple of comments about this

  1. You might notice that I don’t check very many possible errors.  I do this in the interest of simpler to read code.  This is a tradeoff that I make for “teaching” code.  I hope that you understand that if you want to do something like this in a real product that you need to be much more careful.
  2. I don’t have unit testing.  This falls into the same category as the error checking.  Really this is a bad idea as code without unit testing is obsolete the second it comes out of your fingers.  But, it is easier to read.
  3. I don’t have many comments.  This is something that my colleagues bitch about all of the time with me.  And I know that it must be a personality defect.
  4. I use malloc/free all over the place.  This is a religious war.  You can make a static allocation scheme, but it would be really complicated in this case.  I personally think that the tradeoff of using a battle worn and tested malloc/free is totally worthwhile against the complexity of custom static memory allocation schemes.

AnyCloud Bluetooth Advertising Scanner (Part 9)

Summary

In this series of articles I am building a Bluetooth Low Energy Scanner using the Cypress/Infineon AnyCloud SDK running on a PSoC 6 and CYW43xxx.  In Part 9, I will fix a memory leak, add packet age, and improve the printing.

Story

You might be starting to wonder if this series is ever going to end.  Well, this article and one more.  That is it.

This morning as I was looking at the serial console window I noticed that I had hit the limit of device in the buffer,  OK.  But that it had also crashed, gone, bye bye, so long … the long dark road.  That needs fixing.

I also was curious when I looked at the output, how long ago I had seen the packets/devices.  So I decided that having “age” in the database made sense.

There are

Article Topic
AnyCloud Bluetooth Advertising Scanner (Part 1) Introduction to AnyCloud Bluetooth Advertising
AnyCloud Bluetooth Advertising Scanner (Part 2) Creating an AnyCloud Bluetooth project
AnyCloud Bluetooth Advertising Scanner (Part 3) Adding Observing functionality to the project
AnyCloud Bluetooth Utilities Library A set of APIs for enhancement of the AnyCloud Library
AnyCloud Bluetooth Advertising Scanner (Part 4) Adding a command line to the scanner
AnyCloud Bluetooth Advertising Scanner (Part 5) Adding a history database to the scanner
AnyCloud Bluetooth Advertising Scanner (Part 6) Decoding advertising packets
AnyCloud Bluetooth Advertising Scanner (Part 7) Adding recording commands to the command line
AnyCloud Bluetooth Advertising Scanner (Part 8) Adding filtering to the scanner
AnyCloud Bluetooth Advertising Scanner (Part 9) Improve the print and add packet age
AnyCloud Bluetooth Advertising Scanner (Part 10) Sort the database

All of the code can be found at git@github.com:iotexpert/AnyCloudBLEScanner.git and https://github.com/iotexpert/AnyCloudBLEScanner.git

There are git tags in place starting at part 5 so that you can look at just that version of the code.  "git tag" to list the tags.  And "git checkout part6" to look at the part 6 version of the code.

You can also create a new project with this is a template if you have the IoT Expert Manifest Files installed

Fix the Memory Leak

I noticed that a while after I started getting the message “ADV Table Max Size” that things would crash.  But Why?  The answer is a memory leak – go figure. I originally thought when I get a new device I would just overwrite the last entry in the table.  But, when I overwrote the adb_database[adb_db_count]. record with a new scan_result and a new list, I left memory that was previously allocated, here is the code:

    if(entry == -1)
    {
        adb_database[adb_db_count].result = scan_result;
        adb_database[adb_db_count].listCount = 1;
        adb_database[adb_db_count].record = false;
        adb_database[adb_db_count].filter = true;
        adb_database[adb_db_count].numSeen = 1;

        adb_adv_data_t *current = malloc(sizeof(adb_adv_data_t));
        current->next = 0;
        current->data = data;
        current->count = 1;

        adb_database[adb_db_count].list = current;

        adb_db_count = adb_db_count + 1;
        if(adb_db_count == ADB_MAX_SIZE)
        {
            printf("ADV Table Max Size\n");
            adb_db_count = adb_db_count - 1;
        }
        else
        {    
            adb_db_print(ADB_PRINT_METHOD_BYTES,false,adb_db_count-1);
        }
    }

A cheap fix is to just stop making new entries when the database runs out of room.

    // If there is a new entry and you ran out of space
    if(entry == -1 && adb_db_count >= ADB_MAX_SIZE)
    {
        free(scan_result);
        free(data);
        return;
    }

Add Age

As I mentioned earlier I wanted to keep track of

  1. The last time I had seen a device
  2. When I saw that specific advertising packet

The FreeRTOS has a free running millisecond counter that starts a 0 and counts up to 2^32.  A really cheap way to keep track of time is just to use this counter. To do this the first step is add the time to the database.  Both in the device record and the packet record.

typedef struct {
    uint8_t *data;
    int count;
    TickType_t lastSeen;
    struct adb_adv_data_t *next;
} adb_adv_data_t;

typedef struct {
    wiced_bt_ble_scan_results_t *result;
    bool record;
    bool filter;
    int numSeen;
    int listCount;
    TickType_t lastSeen;
    adb_adv_data_t *list;
} adb_adv_t ;

Update the Printing

I am going to make the output look like this with a new column representing the seconds since I heard the packet.  In the picture below you can see that I heard 00 at 0.0 seconds ago…  Then you can see that I had a recording of device 5 where I have a bunch of packets that I heard back into time.

To do this I just add a time calculation like this:

static void adb_db_printEntry(adb_print_method_t method, int entry, adb_adv_data_t *adv_data)
{
    float time = ((float)xTaskGetTickCount() - (float)(adv_data->lastSeen))/1000;

    printf("%c%c%02d %05d %03d %6.1f ",adb_database[entry].watch?'W':' ',
    adb_database[entry].filter?'F':' ',
    entry,adb_database[entry].numSeen,adb_database[entry].listCount,
    time);

Fix up the Add

The next thing that I need to do is make the “add” function add the time.  The problem is that this function has gotten totally totally out of control.  It turns out that there are x different possibilities

  1. Ignore the packet (because the table is full)
  2. Add a new device & packet
  3. Update the head of the list with a new packet
  4. Insert a new packet at the head of the list
  5. If you are filtering update a duplicated packet count

The code for these branches all looked somewhat similar.  But, which branch to take depended on

  1. If you were “watching” that device
  2. If you were “filtering” that device
  3. If you were “recording”
  4. If you had seen that packet before (aka it was found)

I ended up making a truth table:

Watch Filter Recording Found Action
0 0 0 0 update the head
0 0 0 1 update the head
0 0 1 0 update the head
0 0 1 1 update the head
0 1 0 0 update the head
0 1 0 1 update the head
0 1 1 0 update the head
0 1 1 1 update the head
1 0 0 0 update the head
1 0 0 1 update the head
1 0 1 0 insert at the head
1 0 1 1 insert at the head
1 1 0 0 update the head
1 1 0 1 update the found
1 1 1 0 insert at the head
1 1 1 1 update the found

The case where you

  1. Had no room
  2. Saw a new device

Look like this:

static void adb_db_add(wiced_bt_ble_scan_results_t *scan_result,uint8_t *data)
{

    TickType_t timeSeen = xTaskGetTickCount();

    int entry = adb_db_find(&scan_result->remote_bd_addr);

    // If there is a new entry and you ran out of space
    if(entry == -1 && adb_db_count >= ADB_MAX_SIZE)
    {
        free(scan_result);
        free(data);
        return;
    }
    
    // If it is NOT found && you have room
    if(entry == -1)
    {
        adb_database[adb_db_count] = malloc(sizeof(adb_adv_t));
        adb_database[adb_db_count]->result = scan_result;
        adb_database[adb_db_count]->listCount = 1;
        adb_database[adb_db_count]->watch = false;
        adb_database[adb_db_count]->filter = true;
        adb_database[adb_db_count]->numSeen = 1;
        adb_database[adb_db_count]->lastSeen = timeSeen;

        adb_adv_data_t *current = malloc(sizeof(adb_adv_data_t));
        current->next = 0;
        current->data = data;
        current->numSeen = 1;
        current->lastSeen = timeSeen;

        adb_database[adb_db_count]->list = current;

        adb_db_count = adb_db_count + 1;    
        adb_db_print(ADB_PRINT_METHOD_BYTES,false,adb_db_count-1);

        return; 
    }

At this point in the code you know that you have seen this device before.  If you are filtering you should look in the linked list to see if you can find the specific packet (lines 1-15).

If you look at the truth table above you will see three cases where you should insert at the head of this list.  Those cases are identified with the sprawling if on lines 17-21).  Once you identify that scenario you do the needful.

    adb_adv_data_t *updateItem=0; 

    if(adb_database[entry].filter) // if filtering is on.
    {
        int len = btutil_adv_len(data); // ARH maybe a bug here
        
        for(adb_adv_data_t *list = adb_database[entry].list;list;list = (adb_adv_data_t *)list->next)
        {
            if(memcmp(list->data,data,len) == 0) // Found the data
            {
                updateItem = list;
                break;
            }
        }
    }

    // insert at the head
    if( (adb_database[entry].watch && !adb_database[entry].filter && adb_recording && !updateItem) ||
        (adb_database[entry].watch && !adb_database[entry].filter && adb_recording && updateItem) ||
        (adb_database[entry].watch && adb_database[entry].filter && adb_recording && !updateItem)
    )
    {
        adb_adv_data_t *updateItem = malloc(sizeof(adb_adv_data_t)); // make new data
        updateItem->next = (struct adb_adv_data_t *)adb_database[entry].list;
        updateItem->numSeen = 1;
        updateItem->data = data;
        updateItem->lastSeen = timeSeen;

        adb_database[entry].list = updateItem;
        adb_database[entry].numSeen += 1;
        adb_database[entry].lastSeen = timeSeen;
        adb_database[entry].listCount += 1;
        free(scan_result);
        
        adb_db_print(ADB_PRINT_METHOD_BYTES,false,entry);


        adb_recording_count += 1;
        if(adb_recording_count == ADB_RECORD_MAX)
        {
            adb_recording = false;
            printf("Recording buffer full\n");
        }
        return;
    }

The final case happens when you are just going to update a found packet.

    if(updateItem == 0)
        updateItem = adb_database[entry].list;


    adb_database[entry].numSeen += 1;
    adb_database[entry].lastSeen = timeSeen;

    updateItem->lastSeen = timeSeen;

    int len = btutil_adv_len(data); // ARH maybe a bug here
    if(memcmp(updateItem->data,data,len) == 0)
    {
        updateItem->numSeen += 1;
    }
    else
    {
        updateItem->numSeen = 1;   
    }

    free(updateItem->data);
    updateItem->data = data;
    free(scan_result);

}

In the next article I will add

  1. Sort
  2. Purge

Then I will call it  a day.

Beer Smith Water Volume Calculator

Summary

A discussion of the algorithms to calculate water volume in Beer Smith 3.0 including a spreadsheet showing the calculations.  What does this have to do with IoT?  Nothing.

Story

I am a new brewer. I started at the beginning of COVID in March 2020.  At this point I have only done 26 batches so I am a long way from expert.  For sure there is no danger of BrewExpert.com from me any time soon.  But, I am also an engineer so I like to “know” (and if there are any IoT Expert people still reading, you will already know that)

I have been struggling to understand how much strike and sparge water to use during the making process. I own and use a Grainfather, so I have been using their software, but honestly Im not a huge fan.  Nathan at BrewerDude, my local home brew store, told me that using Beer Smith was the best way to improve my results.  And, as you know figuring things out is more than half the fun for me.  Game on.

Beer Smith 3.0 is a interesting piece of software written by Brad Smith that was made to design and help you implement beer recipes.  The software was clearly built with years of “experience” in making beer and is also clearly a reflection of his workflow.  The tool is seems to have a substantial amount of empirical knowledge built into the tool – Ohm’s laws for beer?

Now to the problem.  I started trying to reconcile the water volume information coming out of Beer Smith with what was coming out of the Grainfather software.  The numbers didn’t really add up and there were a bunch of things which I didn’t really know. Google here we come. Turns out there are a boatload hits that are some variant of “how do I match what the Grainfather and BeerSmith think for water volumes”.  I am sure that there is a beautiful document in the Beer Smith documentation library which I haven’t found which explains the answer to the question of how the water volumes are calculated in Beer Smith, but I couldn’t find it.

So I decided to reverse engineer the calculations, which I mostly have done (with a few issues).  They are all in a spreadsheet which you can download from the IoT Expert Github respository which you can find at https://github.com/iotexpert/Beer.git That repository contains a spreadsheet called “beer-smith-water.xlsx” which has my version of the formulas which seem to match BeerSmith 3.1.08

I am quite sure that this water volume issue is obvious to everyone, except me.  But, as I said, I’m only 26 batches into this brewing adventure.  For the rest of this article I will focus only on the parameters that impact water volume in Beer Smith.

First I will walk through the screens that impact water then I will show the “Vols” tab and my spreadsheet which mimics the calculations.

Getting Started

I will use the recipe “Abbey of the Blonds” from BrewerDude and my setup which is a Grainfather G30 and a Grainfather Conical Fermenter.  Here is a picture of the front cover of the book that came with the recipe.  Notice my handwritten notes that are the strike and sparge water… in both metric and imperial… and my note that the water values that I used to get a good result.

Before you can really look at the water volume numbers you need to do several things:

  1. Enter the recipe (which I copied from the nice document that came from BrewerDude along with the kit)
  2. Add your equipment (in the picture you can see that I added Grainfather G30 110V ARH).  “ARH” are my initials and is my copy of the default configuration.
  3. Add your mash profile (in the picture you can see that I picked Single Infusion Medium Body, Batch Sparge)
  4. Set the boil time to 90 minutes (which over-rides the default of this equipment of 60 minutes)
  5. Notice the Batch Size of 5.5 gallons (which was copied from the equipment profile)

In the picture you can see that I changed the fields in the middle right to display the three water volume numbers that I am interested in, specifically:

  • Tot Mash Water
  • Sparge Water
  • Total Volume

I do not believe that BH Efficiency impacts the water volume calculations.

Batch Size & A GUI Comment

The starting value for Batch Size is copied from Equipment Setup configuration.  This number was intensely confusing to me for a good while until I got it sorted out that this is the total volume of cold wort going into the fermenter after the mash and boil.  One thing that you should watch for is that this value is linked onto multiple menus/screens and a change in one place will effectively change it multiple places.  When you change this value it appears to propagate throughout your recipe but it does not change the original source equipment profile.

Equipment Setup

As I stated above, when you create the recipe you effectively COPY the equipment profile into your recipe.  In other words the values in this tab become the default values for your recipe when you configure this equipment profile to be used for your recipe.

In the equipment profile the following values impact water:

  • Batch Volume – How much wort you want to go into the fermenter
  • Fermenter Loss – Dead space at bottom of the fermenter i.e. below the line where you bottle from
  • Mash Tun Volume – Used as a check to make sure you don’t overflow during the mash.  This doesn’t change the calculations, just a warning.
  • Mash Tun Weight – No impact on water? (pretty sure)
  • Mash Tun Specific Heat – No impact on water? (pretty sure)
  • Boil Time – The default length of time to boil.  This is copied into your reciepe.  This parameter is used in the boil off calculation
  • Boil Off – The input variable to the total boil off calculation
  • Use boil as an hourly rate (if you click this boil off will vary with the boil time)
  • Total Boil Off: Calculated boil off = Batch Size * boil time / 60 * Boil Off
  • Recoverable Mash Deadspace – volume of water below the false bottom which WILL be part of the final wort
  • Mash Deadspace Losses – the volume of water below the false bottom which willl be LOST and not part of the final wort
  • Top Up Water for Kettle: How much water you add pre-boil
  • Post Boil Vol: This is a calculated estimate based on the input parameters (more details later)
  • Cooling Shrinkage: how much volume you loose as the wort cools
  • Loss to Trub and Chiller – what it says
  • Top Up Water – How much water you add into the fermenter

You will find that most of these values are copied onto the “Vols” screen later on.

Mash Profile

When you choose the mash profile it is the major input to the strike water calculations.

On the Mash screen the parameters:

  1. Grain Weight Basis – used for the calculation of strike water (derived from your inputs on the recipe)
  2. Mash In – will take you to the next screen where the strike water is calculated

I was lost trying to figure out where the strike water came from for quite a while until I realized that you could change the values on the “Mash In” step screen.  To do this click on it and press “Edit Step” (where the water volume action happens).  Really what is happening here is that you can create multiple steps in your mash process.  Each step can/will impact the water used by that step.  When you configure your reciepe to use a mash profile, you are essentially copying those steps into your recipe and they drive the values for strike water in your recipe.

As I work to write this article I notice for the first time “Batch Sparge using batches that fill 90%” but I have no idea what that impacts.

The Mash Step screen calculates the mash water for this step.  The key metric is the Water/Grain Ratio which is used to calculate the “Water to add”.  Where did the 1.250 qt/lb come from?  I suspect that this is empirical.  Notice that the water to add does NOT include the Mash Tun Deadspace Addition.  This number was copied from the Equipment profile (which recall was 0.92 gallon = 3.68qt).  Im sure that there was a good reason to add a place to enter this value here, but damn if I can figure it out.  I’m also sure there was some good reason to change units, but Im also not sure why, but probably convenience.

The Advanced Options

The advanced options screen (which can be accessed from the preferences button) has two numbers which are relevant to the water calculations

  1. Grain Absorption (how much water is absorbed by the grain) = 0.96 Fluid Oz per Oz of Grain
  2. Grain Volume (how much physical space is taken by the wet grain) = 0.6520 l/kg

Im quite sure that both of these numbers were arrived at empirically.  These numbers are used in the upcoming “Vols” calculations.

The “Vols” Tab

This tab is where the action happens.  You can see and edit most of what you might want from a water volume point of view.  This screen is broken up into four sections which I will walk through one by one.

  1. Water Needed
  2. Mash
  3. Boil and Fermentation
  4. Fermentation/Bottling

The first thing you should know on the “Vols” tab is that the Total Volume = Tot Mash Water + Sparge Vol and is calculated for you.

The next section is Mash

The Mash Grain Wt (weight) comes from your recipe.

Grain Absorption = Mash Grain Wt * Grain Absorption (from the advanced options)

The Tot Mash Water comes from the Mash Profile which you set earlier plus the Mash Tun Addition.  In this specific case it was calculated with

  • 10.88 pounds * 1.25 qts/pound * 1 gallon/4 quarts = 3.4 Gallons + 0.92 Gallons = 4.32 Gallons

The Tun Deadspace is a parameter for you to enter and is the unrecoverable amount of fluid in the mash tun (things below the pickup in the bottom of the Grainfather)

The Mash Volume Needed = Total Mash Water + Volume of the Wet Grain (which isn’t shown on this screen but is on my spreadsheet)

The Volume of the Wet Grain = Grain weight * gallons/pound  Remember from the advanced tab which had Grain Volume in litres/pound.  This is how much space is taken up inside of your mash tun for wet grain.

Water Available from the Mash = Total Mash Waster – Grain Absorption (this is how much wort can move to the next step)

The Sparge Vol comes from a long chain of calculations on the next sections…

Here is the section of my spreadsheet which represents these calculations.

Now I am going to skip the Boil and Fermentation section and come back because the Fermentation/Bottling section uses data from the this section as an Input.

Top Up Water is how much water you add to the boiled wort as you add it into the Fermenter.  I am not sure why you would do this, perhaps to lower the gravity?

The Batch Size is a parameter that came from the recipe page and is all over this software.  This value is how much wort you are going to put into the fermenter.

The bottling/fermentation loss is how much you loose at the bottom of your fermenter and by taking samples or draining crap during the fermentation process.

I don’t know what “Starter Size Used” is, but I believe that it was put there for a Yeast starter (I have been using Propper Starter).  This would add 32 Ozs (aren’t the units fun here) or 0.94 of a liter.  On a semi-related note I wonder why they addition of Wort doesn’t change the gravity enough to add into their calculations … I suppose adding 16oz at 1.040 isn’t material.  (late edit: I did the math and adding 16oz of 1.040 to a 5.5 gallon batch of 1.060 lower the gravity by 0.04%)

Here is the Fermentation section from my spreadsheet.  Notice that in the picture there are two yellow fields for you to override the calculations from that step.

Back to the  “Boil and Fermentation” section.

Kettle Top Up is how much water you add before you boil after the mash (I have no idea why you would do this)

The best way to think about the rest of this is to

  1. Remember that we are trying to back calculate Sparge Water
  2. Start from the bottom and work back to the top

Trub loss is what it say it is.  With this you can now calculate a value which isn’t shown on this screen.  I call that value “Post Cool Volume”

Post Cool Volume = Batch Size + Trub Loss – Kettle Top Up

In order to achieve the “Post Cool Volume” you need to increase the work volume by the amount of Cooling Shrinkage.

Pre Cool Volume = Post Boil Volume / (1-Pct Cool Loss)

Cooling Shrinkage = Pre Cool Vol – Post Cool Volume

I suppose that I was surprised that the number was anything other than 0 as I thought that liquids dont change their volume very much.  Shows what an electrical engineer knows eh.

Est Pre-Boil Vol = Pre Cool Volume / ( 1 – (Evaporation Rate * Boil Time / 60 Minutes))

With that you can now calculate Boil Off = Pre  boil – Post Boil

Finally Sparge Volume = Est Pre Boil – Kettle Top Up + Grain Absorption + Tun Deadspace – Tot Mash Water

Here is my spreadsheet:

Final Thoughts

I have not answered (at least) the following questions

  1. Where did the Grainfather numbers come from?
  2. Given (1) why is there a difference between Beer Smith and Grainfather
  3. What other calculators are out there?
  4. What is “Batch Sparge Using Batches that fill %” used for?

I am pretty sure that the right thing for me to do next is to design a set of experiments that will arrive at the configuration parameters that best match my setup.  I think that it would be useful to describe this procedure.

There may very well be an error in here.  In fact I would say with certainty that I made some error.  If you have made it this far and you spotted the error I would very much like to know what it is so that I can fix it.

AnyCloud Bluetooth Advertising Scanner (Part 8)

Summary

In this series of articles I am building a Bluetooth Low Energy Scanner using the Cypress/Infineon AnyCloud SDK running on a PSoC 6 and CYW43xxx.  In Part 8 I will turn on the ability to filter duplicate advertising packets.

Story

In the previous article I added the ability to record advertising packets.  The problem is, of course, that many devices are blasting out advertising packets, which will quickly overwhelm you.  I suppose more importantly it will overwhelm the packet buffer.  Most of the device are just advertising their presence, so they send the same data over and over.  Some devices alternate between a small number of different advertising packets, e.g. an iBeacon then and Eddystone beacon.

The way that the filter will work is that I will update the “add” function to search through all of the packets that device has launched, then if I have seen the packet before (Ill use a memcmp) then I will just keep a count of how many times I have see that packet.

The other thing that needs to happen is for me to add a “filter” command so that I can turn on packet filtering on a device by device basis.

And I need to fix the printing to use the new filtered packet database.

There are

Article Topic
AnyCloud Bluetooth Advertising Scanner (Part 1) Introduction to AnyCloud Bluetooth Advertising
AnyCloud Bluetooth Advertising Scanner (Part 2) Creating an AnyCloud Bluetooth project
AnyCloud Bluetooth Advertising Scanner (Part 3) Adding Observing functionality to the project
AnyCloud Bluetooth Utilities Library A set of APIs for enhancement of the AnyCloud Library
AnyCloud Bluetooth Advertising Scanner (Part 4) Adding a command line to the scanner
AnyCloud Bluetooth Advertising Scanner (Part 5) Adding a history database to the scanner
AnyCloud Bluetooth Advertising Scanner (Part 6) Decoding advertising packets
AnyCloud Bluetooth Advertising Scanner (Part 7) Adding recording commands to the command line
AnyCloud Bluetooth Advertising Scanner (Part 8) Adding filtering to the scanner
AnyCloud Bluetooth Advertising Scanner (Part 9) Improve the print and add packet age
AnyCloud Bluetooth Advertising Scanner (Part 10) Sort the database

All of the code can be found at git@github.com:iotexpert/AnyCloudBLEScanner.git and https://github.com/iotexpert/AnyCloudBLEScanner.git

There are git tags in place starting at part 5 so that you can look at just that version of the code.  "git tag" to list the tags.  And "git checkout part6" to look at the part 6 version of the code.

You can also create a new project with this is a template if you have the IoT Expert Manifest Files installed

Update the Data Structures

In order to do the filters, and keep track of the data I will add

  1. A “count” field to the packet data structure
  2. A “filter” boolean field to the device data structure.
typedef struct {
    uint8_t *data;
    int count;
    struct adb_adv_data_t *next;
} adb_adv_data_t;

typedef struct {
    wiced_bt_ble_scan_results_t *result;
    bool record;
    bool filter;
    int numSeen;
    int listCount;
    adb_adv_data_t *list;
} adb_adv_t ;

Update the Add Function

In the function “static void adb_db_add(wiced_bt_ble_scan_results_t *scan_result,uint8_t *data)” which is called every time I see a new advertising packet I will need to handle four different cases:

  1. The first time you see a device
  2. A device you have seen AND you are recording AND have the filtering turned on
  3. A device you are recording but not filtering
  4. A device you have seen, but are not recording or filter.

In the first case, a device you haven’t seen before, you need to

  1. Automatically turn on the filtering
  2. Initialize the counts to 1
  3. Do the other initialization (as before)
    // If it is NOT found
    if(entry == -1)
    {
        adb_database[adb_db_count].result = scan_result;
        adb_database[adb_db_count].listCount = 1;
        adb_database[adb_db_count].record = false;
        adb_database[adb_db_count].filter = true;
        adb_database[adb_db_count].numSeen = 1;

        adb_adv_data_t *current = malloc(sizeof(adb_adv_data_t));
        current->next = 0;
        current->data = data;
        current->count = 1;

In the case where you have

  1. See the device before
  2. You have room in the record buffer
  3. And you are in record mode

You will then decide if you are filtering.

Then you will iterate through all of the packets and compare the data to the data you just received.  If there is a match then you update the count, free the duplicate data and return.

    else if(adb_database[entry].record && adb_recording_count<ADB_RECORD_MAX && adb_recording)
    {
        adb_database[entry].numSeen += 1;

        if(adb_database[entry].filter) // if filtering is on.
        {
            int len = btutil_adv_len(data); 
            for(adb_adv_data_t *list = adb_database[entry].list;list;list = (adb_adv_data_t *)list->next)
            {
                if(memcmp(list->data,data,len) == 0) // Found the data
                {
                    list->count += 1;
                    printf("Count = %d\n",list->count);
                    free(data);
                    free(scan_result);
                    return;
                }
            }
        }

If you have not see the data before, then you need to add it to the linked list.

        adb_adv_data_t *current = malloc(sizeof(adb_adv_data_t));
        current->next = (struct adb_adv_data_t *)adb_database[entry].list;
        current->data = data;
        current->count = 1;

If you are not recording and not filtering, just increment counts.

    else
    {
        adb_database[entry].numSeen += 1;
        adb_database[entry].list->count += 1;

Add a “filter” Command

I want the ability for a user to “filter all” or “filter clear” or “filter #” – just like we did with watch.  So, add the #defines and new function to advDatabase.h

#define ADB_FILTER_ALL -1
#define ADB_FILTER_CLEAR -2
void adb_filter(int entry);

Then add the new filter command in advDatabase.c

typedef enum {
    ADB_ADD,
    ADB_PRINT_RAW,
    ADB_PRINT_DECODE,
    ADB_WATCH,
    ADB_ERASE,
    ADB_RECORD,
    ADB_FILTER,
} adb_cmd_t;

I will use the adb_queueCmd function that I created in the last article.

inline void adb_filter(int entry) { adb_queueCmd(ADB_FILTER,(void*)entry,(void *)0); }

The filter command has three cases

  1. All – turn the bool for all on
  2. Clear – turn the bool for all off
  3. Just a specific number – toggle that specific number
static void adb_db_filter(int entry)
{
    if(entry == ADB_FILTER_ALL)
    {
        for(int i=0;i<adb_db_count;i++)
        {
            adb_database[i].filter = true;
        }
        return;
    }

    if(entry == ADB_FILTER_CLEAR)
    {
        for(int i=0;i<adb_db_count;i++)
        {
            adb_database[i].filter = false;
        }
        return;
    }

    if(entry > adb_db_count-1 || entry < ADB_WATCH_CLEAR)
    {
        printf("Record doesnt exist: %d\n",entry);
        return;      
    }
    adb_database[entry].filter = !adb_database[entry].filter; 

}

And you need to fix up the main command processor

                case ADB_FILTER:
                    adb_db_filter((int)msg.data0);
                break;

Finally add the command to the usrcmd.c

static int usrcmd_filter(int argc, char **argv)
{

    if(argc == 2 && !strcmp(argv[1],"all"))
    {
        adb_filter(ADB_FILTER_ALL); // all
        return 0;
    }


    if(argc == 2 && !strcmp(argv[1],"clear"))
    {
        adb_filter(ADB_FILTER_CLEAR);
        return 0;
    }

    if(argc == 2)
    {
        int i;
        sscanf(argv[1],"%d",&i);
        adb_filter(i);
        return 0;
    }

    return 0;
}

Fix the Printing

Now we nee to fix the printing.  I want to add an indicate of the filtering to the output.  Remember from the previous article I indicated “Watch” with a “*”.  When I looked at it, I decided that I should indicate filter with an “F” and watch with a “W”.  So I fix that.

        printf("%c%c%02d %05d %03d MAC: ",adb_database[i].record?'W':' ',
            adb_database[i].filter?'F':' ',
            i,adb_database[i].numSeen,adb_database[i].listCount);
        btutil_printBDaddress(adb_database[i].result->remote_bd_addr);
        switch(method)
        {

Then I test the “filter” command

Fix the Printing Part (2)

As I noodled on how to change the printing I decide that it would be nice to sometimes print out only one packet e.g. no history and sometimes print them all out e.g. history.  So, I add a new parameter to the function called “history”

static void adb_db_print(adb_print_method_t method,bool history,int entry)

As I looked at the printing code, I decided that it would be better to have a new function to print only one entry.  I suppose that I could have left the code inline, but I thought that intent was clearer.

static void adb_db_printEntry(adb_print_method_t method, int entry, adb_adv_data_t *adv_data)
{
    printf("%c%c%02d %05d %03d MAC: ",adb_database[entry].record?'W':' ',
    adb_database[entry].filter?'F':' ',
    entry,adb_database[entry].numSeen,adb_database[entry].listCount);
    btutil_printBDaddress(adb_database[entry].result->remote_bd_addr);

    switch(method)
    {
    
    case ADB_PRINT_METHOD_BYTES:
        printf(" Data: ");
        btutil_adv_printPacketBytes(adv_data->data);
    break;

    case ADB_PRINT_METHOD_DECODE:
        printf("\n");
        btutil_adv_printPacketDecode(adv_data->data);
    break;
    } 
    printf("\n");

}

With the new function in place I now need to update the print function to call the new entry function.  Printing the history is just a matter of iterating through the linked list.

static void adb_db_print(adb_print_method_t method,bool history,int entry)
{
    int start,end;
 
    if(entry < 0)
    {
        start = 0;
        end = adb_db_count;
    }
    else
    {
        start = entry;
        end = entry+1;
    }

    if(end>adb_db_count)
        end = adb_db_count; 

    for(int i=start;i<end;i++)
    {
        if(history) // then iterate through the linked list print all of the packets
        {
            for(adb_adv_data_t *list = adb_database[i].list;list;list = (adb_adv_data_t *)list->next)
            {
                adb_db_printEntry(method,i,list);    
            }
        }
        else // Just print the first packet in the list
            adb_db_printEntry(method,i,adb_database[i].list);
    }
}

Now, I need to update all of the calls to adb_db_print to have the new history parameter.  First, I made the decision that when you “print” from the command line that you are interested in the history.

                case ADB_PRINT_RAW:
                    adb_db_print(ADB_PRINT_METHOD_BYTES,true,(int)msg.data0);
                break;
                case ADB_PRINT_DECODE:
                    adb_db_print(ADB_PRINT_METHOD_DECODE,true,(int)msg.data0);
                break;

But when you are printing out the packet for a new device don’t print out the history

            adb_db_print(ADB_PRINT_METHOD_BYTES,false,adb_db_count-1);

Program and Test

After I program my development kit, I start by typing “watch all”.  Very quickly, at my house, you can see that a bunch of devices are discovered.  You can see that all of these have a “W” (meaning that I am watching them) and an “F” meaning they are filtering out duplicates.  Then I type “record” to turn on recording. After a minute I turn off recording then do the print you can see below.

A couple of things to notice.

  1. Device #4 (which I highlighted) appears to be sending out a pattern of alternating packets.  See that I have heard 3335 packets yet there are only two in the buffer
  2. You can see device 11 seems to be sending out 16 different packets.  Why?  I don’t know.

But we can “decode 11” to try to figure it out.  You can see that it is advertising manufactures specific data with Apple’s UUID which I happen to know is 0x004C.  But why?  I don’t know.

I really want to move onto a new series of articles… but there are two functions which I will add to the program.  Stay tuned for what they do.

AnyCloud Bluetooth Advertising Scanner (Part 7)

Summary

In this series of articles I am building a Bluetooth Low Energy Scanner using the Cypress/Infineon AnyCloud SDK running on a PSoC 6 and CYW43xxx.  In Part 7 I will add the ability to record BLE ADV packets.

Story

If you have been reading along, at this point we have built a BLE scanner that can see Bluetooth devices that are advertising.  My scanner has a command line and you can print out the most recent data.  Even better, we built a decoder that allows you to better understand the data.

Now I want to add the ability to record more than one advertising packet per device.  To that end I will add three commands:

  • watch – Mark a device as one that needs to have the advertising data recorded.  You can type “watch 12” or you can say “watch all” or you can say “watch clear”
  • record – Turn on recording of “watched” devices.  When you type record it will toggle the recording state between On and Off.
  • erase – clear the record buffer of all but the most recent packet.

There are

Article Topic
AnyCloud Bluetooth Advertising Scanner (Part 1) Introduction to AnyCloud Bluetooth Advertising
AnyCloud Bluetooth Advertising Scanner (Part 2) Creating an AnyCloud Bluetooth project
AnyCloud Bluetooth Advertising Scanner (Part 3) Adding Observing functionality to the project
AnyCloud Bluetooth Utilities Library A set of APIs for enhancement of the AnyCloud Library
AnyCloud Bluetooth Advertising Scanner (Part 4) Adding a command line to the scanner
AnyCloud Bluetooth Advertising Scanner (Part 5) Adding a history database to the scanner
AnyCloud Bluetooth Advertising Scanner (Part 6) Decoding advertising packets
AnyCloud Bluetooth Advertising Scanner (Part 7) Adding recording commands to the command line
AnyCloud Bluetooth Advertising Scanner (Part 8) Adding filtering to the scanner
AnyCloud Bluetooth Advertising Scanner (Part 9) Improve the print and add packet age
AnyCloud Bluetooth Advertising Scanner (Part 10) Sort the database

All of the code can be found at git@github.com:iotexpert/AnyCloudBLEScanner.git and https://github.com/iotexpert/AnyCloudBLEScanner.git

There are git tags in place starting at part 5 so that you can look at just that version of the code.  "git tag" to list the tags.  And "git checkout part6" to look at the part 6 version of the code.

You can also create a new project with this is a template if you have the IoT Expert Manifest Files installed

Update the advDatabase Interface

The first thing I realized as I went to add a new command was that I was typing the exact same code over and over for the public interface.  The code looked like this:

void adb_watch(int entry)
{
    adb_cmdMsg_t msg;
    msg.cmd = ADB_WATCH;
    msg.data0 = (void *)entry;
    xQueueSend(adb_cmdQueue,&msg,0); // If the queue is full... oh well

}

So I created this:

static void adb_queueCmd(adb_cmd_t cmd,void *data0, void *data1)
{
    adb_cmdMsg_t msg;
    msg.cmd = cmd;
    msg.data0 = data0;
    msg.data1 = data1;
    xQueueSend(adb_cmdQueue,&msg,0); // If you loose an adv packet it is OK...
}

Then did this to eliminate the duplication.

inline void adb_addAdv(wiced_bt_ble_scan_results_t *scan_result,void *data) { adb_queueCmd(ADB_ADD,(void *)scan_result,(void *)data);}
inline void adb_print(int entry) { adb_queueCmd(ADB_PRINT_RAW,(void *)entry,(void *)0); }
inline void adb_decode(int entry) { adb_queueCmd(ADB_PRINT_DECODE,(void*)entry,(void *)0); }

Redo the Database

If you recall from previous posts, my advertising database was just

  1. An Array of structures
  2. Each structure contained the mac address and…
  3. A pointer to a malloc’d copy of the advertising data
typedef struct {
    wiced_bt_ble_scan_results_t *result;
    uint8_t *data;
} adb_adv_t ;

#define ADB_MAX_SIZE (40)
adb_adv_t adb_database[ADB_MAX_SIZE];

Here is a picture of the datastructure

 

Now what I want to do is make the “data” pointer to be a pointer to a linked list of data.  Here is the new definition.

typedef struct {
    uint8_t *data;
    struct adb_adv_data_t *next;
} adb_adv_data_t;

typedef struct {
    wiced_bt_ble_scan_results_t *result;
    int listCount;
    bool record;
    int numSeen;
    adb_adv_data_t *list;
} adb_adv_t ;

The new data structure looks like this

I wanted to limit the number advertising packets that can be stored so I don’t run out of memory.  I am not actually sure how many can be stored, but I suppose a bunch as the chip has 1MB of RAM.  But, I pick 100 which seems like enough to start out with.  I create two variables

  1. A counter for the number of advertising packets that are currently saved
  2. A recording state (are you saving or not)
#define ADB_RECORD_MAX (100)
static int adb_recording_count = 0;
static bool adb_recording = false;

Update the Printing

You probably noticed that I declared two new members of the adb_adv_t structure, specifically numSeen and listCount, which I would like to print out.   I also wanted a visual indication that I am “watching” a device.  The columns are now:

  1. A “*” to indicate that a device is being watched
  2. The device #
  3. The number of packets that I have seen in total from that device
  4. The number of recorded packets for that device
  5. The MAC address
  6. The raw bytes

To do implement this a simple change is made to the print function:

    for(int i=start;i<end;i++)
    {
    
        printf("%s%02d %05d %03d MAC: ",adb_database[i].record?"*":" ",i,adb_database[i].numSeen,adb_database[i].listCount);
        btutil_printBDaddress(adb_database[i].result->remote_bd_addr);
        switch(method)
        {
        
        case ADB_PRINT_METHOD_BYTES:
            printf(" Data: ");
            btutil_adv_printPacketBytes(adb_database[i].list->data);
        break;

        case ADB_PRINT_METHOD_DECODE:
            printf("\n");
            btutil_adv_printPacketDecode(adb_database[i].list->data);
        break;
        } 
        printf("\n");
    }

Update the Add

Now that we have all of the infrastructure in place we need to update the function that saves advertising data.  When an advertising packet comes in you have three situations to consider:

  1. You have never seen the device before
  2. You have seen the device before and you are “watching” it
  3. You have see the device but you are not watching it

In the case where you have never seen the device you need to

  1. Save the scan result
  2. Set the listCount to 1 (you only have one datapoint)
  3. Turn off recording (start with the recording off)
  4. Set the total numSeen to 1 as this is the first packet you have seen
  5. Allocate some memory for the advertising linked list structure
  6. Terminate the linked list
  7. Save the advertising data
  8. Increment the database count (up to the max)
  9. Print out the packet you just saw
    if(entry == -1)
    {
        adb_database[adb_db_count].result = scan_result;
        adb_database[adb_db_count].listCount = 1;
        adb_database[adb_db_count].record = false;
        adb_database[adb_db_count].numSeen = 1;

        adb_adv_data_t *current = malloc(sizeof(adb_adv_data_t));
        current->next = 0;
        current->data = data;

        adb_database[adb_db_count].list = current;

        adb_db_count = adb_db_count + 1;
        if(adb_db_count == ADB_MAX_SIZE)
        {
            printf("ADV Table Max Size\n");
            adb_db_count = adb_db_count - 1;
        }
        else
        {    
            adb_db_print(ADB_PRINT_METHOD_BYTES,adb_db_count-1);
        }
    }

In the case where you have

  1. Seen the device before
  2. You are recording that device
  3. There is room left in the recording buffer

Then you will

  1. Increment number seen
  2. Create memory for the new entry in the linked list
  3. Attach the tail of the linked list to your new entry (you will insert at the front of the list)
  4. Save the data
  5. Increment the number of saved entries
  6. Insert your new packet at the head of the list
  7. Printout the packet
  8. Increment the record count (the total number of packets in the recording buffer)
  9. Then potentially stop recording if you have gotten to the max size.
    else if(adb_database[entry].record && adb_recording_count<ADB_RECORD_MAX && adb_recording)
    {
        adb_database[entry].numSeen += 1;

        adb_adv_data_t *current = malloc(sizeof(adb_adv_data_t));
        current->next = (struct adb_adv_data_t *)adb_database[entry].list;
        current->data = data;
        adb_database[entry].listCount += 1;
        adb_database[entry].list = current;

        adb_db_print(ADB_PRINT_METHOD_BYTES,entry);

        adb_recording_count += 1;
        if(adb_recording_count == ADB_RECORD_MAX)
        {
            adb_recording = false;
            printf("Recording buffer full\n");
        }
    }

In the case where you have seen the device before, but you are not recoding then you will

  1. Update the numSeen
  2. Erase the old packet data
  3. Save the new packet
  4. Erase the “result” (you already have it saved)
    else
    {
        adb_database[entry].numSeen += 1;
        free(adb_database[entry].list->data);
        adb_database[entry].list->data = data;
        free(scan_result);
    }

Add a Watch Command

The watch function is pretty simple.  It just needs to either mark the “record” boolean as true or false.  When I decided to implement this function I decided to make positive numbers be the entry in the table.  But, I also wanted to be able to “watch all” and “watch clear”.  So, I used negative numbers for those two special meanings.  I used a #define in advDatabase.h to define those values.

#define ADB_WATCH_ALL -1
#define ADB_WATCH_CLEAR -2

The function is then pretty simple

  1. If it is watch all… then iterate through the database and turn them on
  2. If it is watch clear … then iterate through the database and turn them off
  3. Otherwise make sure that it is a legal number and toggle it.
static void adb_db_watch(int entry)
{
    if(entry == ADB_WATCH_ALL)
    {
        for(int i=0;i<adb_db_count;i++)
        {
            adb_database[i].record = true;
        }
        return;
    }

    if(entry == ADB_WATCH_CLEAR)
    {
        for(int i=0;i<adb_db_count;i++)
        {
            adb_database[i].record = false;
        }
        return;
    }

    if(entry > adb_db_count-1 || entry < ADB_WATCH_CLEAR)
    {
        printf("Record doesnt exist: %d\n",entry);
        return;      
    }
    adb_database[entry].record = !adb_database[entry].record; 

}

Once I have the infrastructure in place, I then add the watch command to usrcmd.c

static int usrcmd_watch(int argc, char **argv)
{

    if(argc == 2 && !strcmp(argv[1],"all"))
    {
        adb_watch(ADB_WATCH_ALL); // all
        return 0;
    }


    if(argc == 2 && !strcmp(argv[1],"clear"))
    {
        adb_watch(ADB_WATCH_CLEAR);
        return 0;
    }

    if(argc == 2)
    {
        int i;
        sscanf(argv[1],"%d",&i);
        adb_watch(i);
        return 0;
    }

    return 0;
}

Add a Record Command

The record command simply turns on the global bool to either true or false and prints out the number of spaces free in the record “buffer”

                case ADB_RECORD:
                    adb_recording = !adb_recording;
                    printf("Record %s Buffer Entries Free=%d\n",adb_recording?"ON":"OFF",
                        ADB_RECORD_MAX-adb_recording_count);
                break;

And the change to usrcmd.c is also simple.

// record = toggles
static int usrcmd_record(int argc, char **argv)
{
    if(argc == 1)
    {
        adb_record(-1);
        return 0;
    }
    return 0;
}

Add an Erase Command

The erase function is like “watch”, as I overload the “entry” to have an ALL which is setup in advDatabase.h

#define ADB_ERASE_ALL -1

The erase is a bit more complicated than the watch.  When you receive a erase command you will either erase them all by iterating over the whole dates, or just erase one.

                case ADB_ERASE:
                    if((int)msg.data0 == ADB_ERASE_ALL)
                    {
                        for(int i=0;i<adb_db_count;i++)
                        {
                            adb_eraseEntry(i);
                        }
                    }
                    else
                        adb_eraseEntry((int)msg.data0);

                    printf("Record Buffer Free %d\n",ADB_RECORD_MAX-adb_recording_count);
                break;

The individual eraseEntry function checks to make sure that you have a legal “entry”.  Then it follows the linked list “freeing” the data structures.

static void adb_eraseEntry(int entry)
{
    if(entry > adb_db_count-1 || entry<0)
    {
        printf("Erase Entry Not Found %d\n",entry);
        return;
    }

    adb_adv_data_t *ptr;
    ptr = (adb_adv_data_t *)adb_database[entry].list->next;
    adb_database[entry].list->next = 0;
    while(ptr)
    {
        adb_adv_data_t *next;
        next = (adb_adv_data_t *)ptr->next;
        free(ptr->data);
        free(ptr);
        adb_database[entry].listCount -= 1;
        adb_recording_count -= 1;
        ptr = next;
    }
}

And, of course, you need to add the command to usrcmd.c

// erase
// erase #
static int usrcmd_erase(int argc, char **argv)
{
    if(argc > 2)
    {
        return 0;
    }

    if(argc == 1)
    {
        adb_erase(ADB_ERASE_ALL);
        return 0;
    }

    int i;
    sscanf(argv[1],"%d",&i);
    adb_erase(i);
    return 0;    

}

Now when you build and program the kit you can turn on/off recording and erase and….

In the next post I will add

  1. Smarter printing
  2. A “filter” to eliminate duplicate advertising packets