<?xml version="1.0" encoding="UTF-8"?><rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>AnyCloud &#8211; IoT Expert</title>
	<atom:link href="https://iotexpert.com/category/tools/anycloud/feed/" rel="self" type="application/rss+xml" />
	<link>https://iotexpert.com</link>
	<description>Engineering for the Internet of Things</description>
	<lastBuildDate>Mon, 21 Jun 2021 19:50:26 +0000</lastBuildDate>
	<language>en-US</language>
	<sy:updatePeriod>
	hourly	</sy:updatePeriod>
	<sy:updateFrequency>
	1	</sy:updateFrequency>
	<generator>https://wordpress.org/?v=6.9.4</generator>

<image>
	<url>https://iotexpert.com/wp-content/uploads/2017/01/cropped-Avatar-32x32.jpg</url>
	<title>AnyCloud &#8211; IoT Expert</title>
	<link>https://iotexpert.com</link>
	<width>32</width>
	<height>32</height>
</image> 
	<item>
		<title>AnyCloud WiFi Template + WiFi Helper Library (Part 3): A New Modus Toolbox Library</title>
		<link>https://iotexpert.com/anycloud-wifi-template-wifi-helper-library-part-3-a-new-modus-toolbox-library/</link>
					<comments>https://iotexpert.com/anycloud-wifi-template-wifi-helper-library-part-3-a-new-modus-toolbox-library/#respond</comments>
		
		<dc:creator><![CDATA[Alan Hawse]]></dc:creator>
		<pubDate>Mon, 05 Jul 2021 14:02:02 +0000</pubDate>
				<category><![CDATA[AnyCloud]]></category>
		<category><![CDATA[Elkhorn Creek 3.0]]></category>
		<category><![CDATA[WIFI]]></category>
		<guid isPermaLink="false">https://iotexpert.com/?p=11298</guid>

					<description><![CDATA[Summary Instructions to create a new Modus Toolbox / AnyCloud library including modifying your master middleware manifest and updating the dependencies.  The new library and dependencies will then be available in your library browser and new project creator. Story In the previous article we discussed the steps to turn on the WiFi chip in your [&#8230;]]]></description>
										<content:encoded><![CDATA[<h1>Summary</h1>
<p>Instructions to create a new Modus Toolbox / AnyCloud library including modifying your master middleware manifest and updating the dependencies.  The new library and dependencies will then be available in your library browser and new project creator.</p>
<p><span><p><div class="table-responsive"><table  style="width:95%; "  class="easy-table easy-table-default " border="1">
<thead>
<tr><th >Article</th>
</tr>
</thead>
<tbody>
<tr><td >(Part 1) Create Basic Project &amp; Add Cypress Logging Functionality</td>
</tr>

<tr><td >(Part 2) Create New Thread to manage WiFi using the Wireless Connection Manager</td>
</tr>

<tr><td >(Part 3) Create a New Middleware Library with WiFi helper functions</td>
</tr>

<tr><td >(Part 4) Add WiFi Scan</td>
</tr>

<tr><td >Add WiFi Connect</td>
</tr>

<tr><td >Add WiFi Disconnect</td>
</tr>

<tr><td >Add WiFi Ping</td>
</tr>

<tr><td >Add Gethostbyname</td>
</tr>

<tr><td >Add MDNS</td>
</tr>

<tr><td >Add Status</td>
</tr>

<tr><td >Add StartAP</td>
</tr>

<tr><td >Make a new template project (update manifest)</td>
</tr>
</tbody></table></div></p></span></p>
<h1>Story</h1>
<p>In the previous article we discussed the steps to turn on the WiFi chip in your project using the Wireless Connection Manager Anycloud (WCM) library.  When something happens with the WCM it will give you a callback to tell you what happened.  In my example code there were three printf&#8217;s that were commented out for the conditions:</p>
<ul>
<li>CY_WCM_EVENT_IP_CHANGED</li>
<li>CY_WCM_EVENT_STA_JOINED_SOFTAP</li>
<li>CY_WCM_EVENT_STA_LEFT_SOFTAP</li>
</ul>
<p>The question you might have is &#8220;What is the new Ip Address&#8221;&#8221; or &#8220;What is the MAC address of the Station which joined the SoftAp?&#8221;</p>
<pre class="EnlighterJSRAW" data-enlighter-language="c">        case CY_WCM_EVENT_IP_CHANGED:           /**&lt; IP address change event. This event is notified after connection, re-connection, and IP address change due to DHCP renewal. */
 //               cy_wcm_get_ip_addr(wifi_network_mode, &amp;ip_addr, 1);
                printf("Station IP Address Changed: %s\n",wifi_ntoa(&amp;ip_addr));
        break;
        case CY_WCM_EVENT_STA_JOINED_SOFTAP:    /**&lt; An STA device connected to SoftAP. */
//            printf("STA Joined: %s\n",wifi_mac_to_string(event_data-&gt;sta_mac));
        break;
        case CY_WCM_EVENT_STA_LEFT_SOFTAP:      /**&lt; An STA device disconnected from SoftAP. */
//            printf("STA Left: %s\n",wifi_mac_to_string(event_data-&gt;sta_mac));
</pre>
<p>So I wrote &#8220;standard&#8221; functions to</p>
<ul>
<li>Convert an IP address structure to a string (like ntoa in Linux)</li>
<li>Convert a MAC address to a string</li>
</ul>
<p>I essentially got these from the code example where they were redundantly repeatedly repeated.  After tweaking them to suit my liking I wanted to put them in a library.</p>
<h1>Make the C-Library</h1>
<p>Follow these steps to make the c-library.  First, make a new directory in your project called &#8220;wifi_helper&#8221;.  You can do this in Visual Studio Code by pressing the folder button with the plus on it.</p>
<p><a href="https://iotexpert.com/?attachment_id=11306" rel="attachment wp-att-11306"><img fetchpriority="high" decoding="async" src="https://iotexpert.com/wp-content/uploads/2021/06/Screen-Shot-2021-06-15-at-7.27.03-PM.png" alt="" width="974" height="192" class="alignnone size-full wp-image-11306" srcset="https://iotexpert.com/wp-content/uploads/2021/06/Screen-Shot-2021-06-15-at-7.27.03-PM.png 974w, https://iotexpert.com/wp-content/uploads/2021/06/Screen-Shot-2021-06-15-at-7.27.03-PM-300x59.png 300w, https://iotexpert.com/wp-content/uploads/2021/06/Screen-Shot-2021-06-15-at-7.27.03-PM-768x151.png 768w, https://iotexpert.com/wp-content/uploads/2021/06/Screen-Shot-2021-06-15-at-7.27.03-PM-600x118.png 600w" sizes="(max-width: 974px) 100vw, 974px" /></a></p>
<p>Then create the files wifi_helper.h and wifi_helper.c</p>
<p><a href="https://iotexpert.com/?attachment_id=11307" rel="attachment wp-att-11307"><img decoding="async" src="https://iotexpert.com/wp-content/uploads/2021/06/Screen-Shot-2021-06-15-at-7.27.39-PM.png" alt="" width="956" height="414" class="alignnone size-large wp-image-11307" srcset="https://iotexpert.com/wp-content/uploads/2021/06/Screen-Shot-2021-06-15-at-7.27.39-PM.png 956w, https://iotexpert.com/wp-content/uploads/2021/06/Screen-Shot-2021-06-15-at-7.27.39-PM-300x130.png 300w, https://iotexpert.com/wp-content/uploads/2021/06/Screen-Shot-2021-06-15-at-7.27.39-PM-768x333.png 768w, https://iotexpert.com/wp-content/uploads/2021/06/Screen-Shot-2021-06-15-at-7.27.39-PM-600x260.png 600w" sizes="(max-width: 956px) 100vw, 956px" /></a></p>
<p>In &#8220;wifi_helper.h&#8221; type in the public interface.  Specifically, that we want a function that takes a mac address returns a char*.  And another function that takes an IP address and returns a char*</p>
<pre class="EnlighterJSRAW" data-enlighter-language="c">#pragma once

#include "cy_wcm.h"

char *wifi_mac_to_string(cy_wcm_mac_t mac);

char *wifi_ntoa(cy_wcm_ip_address_t *ip_addr);


</pre>
<p>All right Hassane&#8230; yes these functions need comments.  Notice that I allocated a static buffer inside of these two function.  That means that these functions are NOT NOT NOT thread safe.  However, personally I think that is fine as I think that it is unlikely that they would ever be called from multiple threads.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="generic">#include "wifi_helper.h"
#include "cy_wcm.h"
#include &lt;stdio.h&gt;
#include "cy_utils.h"
#include "cy_log.h"

char *wifi_mac_to_string(cy_wcm_mac_t mac)
{
    static char _mac_string[] = "xx:xx:xx:xx:xx:xx";
    sprintf(_mac_string,"%02X:%02X:%02X:%02X:%02X:%02X",mac[0],mac[1],mac[2],mac[3],mac[4],mac[5]);
    return _mac_string; 
}


char *wifi_ntoa(cy_wcm_ip_address_t *ip_addr)
{
    static char _netchar[32];
    switch(ip_addr-&gt;version)
    {
        case CY_WCM_IP_VER_V4:
            sprintf(_netchar,"%d.%d.%d.%d", (uint8_t)ip_addr-&gt;ip.v4,
                (uint8_t)(ip_addr-&gt;ip.v4 &gt;&gt; 8), (uint8_t)(ip_addr-&gt;ip.v4 &gt;&gt; 16),
                (uint8_t)(ip_addr-&gt;ip.v4 &gt;&gt; 24));        break;
        case CY_WCM_IP_VER_V6:
            sprintf(_netchar,"%X:%X:%X:%X", (uint8_t)ip_addr-&gt;ip.v6[0],
                (uint8_t)(ip_addr-&gt;ip.v6[1]), (uint8_t)(ip_addr-&gt;ip.v6[2]),
                (uint8_t)(ip_addr-&gt;ip.v6[3]));
        break;
    }
    CY_ASSERT(buff[0] != 0); // SOMETHING should have happened
    return _netchar;
}

</pre>
<h1>Git Repository</h1>
<p>Now that I have the files I need in the library, I want to create a place on GitHub to hold the library.</p>
<p><a href="https://iotexpert.com/?attachment_id=11319" rel="attachment wp-att-11319"><img decoding="async" src="https://iotexpert.com/wp-content/uploads/2021/06/Screen-Shot-2021-06-17-at-7.07.31-AM-1024x916.jpg" alt="" width="1024" height="916" class="alignnone size-large wp-image-11319" srcset="https://iotexpert.com/wp-content/uploads/2021/06/Screen-Shot-2021-06-17-at-7.07.31-AM-1024x916.jpg 1024w, https://iotexpert.com/wp-content/uploads/2021/06/Screen-Shot-2021-06-17-at-7.07.31-AM-300x268.jpg 300w, https://iotexpert.com/wp-content/uploads/2021/06/Screen-Shot-2021-06-17-at-7.07.31-AM-768x687.jpg 768w, https://iotexpert.com/wp-content/uploads/2021/06/Screen-Shot-2021-06-17-at-7.07.31-AM-1536x1373.jpg 1536w, https://iotexpert.com/wp-content/uploads/2021/06/Screen-Shot-2021-06-17-at-7.07.31-AM-600x536.jpg 600w, https://iotexpert.com/wp-content/uploads/2021/06/Screen-Shot-2021-06-17-at-7.07.31-AM.jpg 1908w" sizes="(max-width: 1024px) 100vw, 1024px" /></a></p>
<p>Now we need to integrate the files into Git.  To do this you need to</p>
<ol>
<li>Initialize a new git repository (git init .)</li>
<li>Add a remote (git remote add origin git@github.com:iotexpert/wifi_helper.git)</li>
<li>Pull the remote files (README and LICENSE) with (git pull origin main)</li>
<li>Add the wifi_helper files (git add wifi_helper.*)</li>
<li>Commit the changes (git commit -m &#8220;added initial c files&#8221;)</li>
<li>Push them to the remote (git push -u origin main)</li>
</ol>
<pre class="EnlighterJSRAW" data-enlighter-language="generic">arh (master *+) wifi_helper $ pwd
/Users/arh/proj/elkhorncreek3/IoTExpertWiFiTemplate/wifi_helper
arh (master *+) wifi_helper $ git init .
Initialized empty Git repository in /Users/arh/proj/elkhorncreek3/IoTExpertWiFiTemplate/wifi_helper/.git/
arh (main #) wifi_helper $ git remote add origin git@github.com:iotexpert/wifi_helper.git
arh (main #) wifi_helper $ git pull origin main
remote: Enumerating objects: 4, done.
remote: Counting objects: 100% (4/4), done.
remote: Compressing objects: 100% (4/4), done.
remote: Total 4 (delta 0), reused 0 (delta 0), pack-reused 0
Unpacking objects: 100% (4/4), 1.28 KiB | 436.00 KiB/s, done.
From iotexpert.github.com:iotexpert/wifi_helper
 * branch            main       -&gt; FETCH_HEAD
 * [new branch]      main       -&gt; origin/main
arh (main) wifi_helper $ git add wifi_helper.*
arh (main +) wifi_helper $ git commit -m "added initial c files"
[main f7d10b1] added initial c files
 2 files changed, 72 insertions(+)
 create mode 100644 wifi_helper.c
 create mode 100644 wifi_helper.h
arh (main) wifi_helper $ git push -u origin main
Enumerating objects: 5, done.
Counting objects: 100% (5/5), done.
Delta compression using up to 12 threads
Compressing objects: 100% (4/4), done.
Writing objects: 100% (4/4), 1.10 KiB | 1.10 MiB/s, done.
Total 4 (delta 0), reused 0 (delta 0), pack-reused 0
To iotexpert.github.com:iotexpert/wifi_helper.git
   3a1ad32..f7d10b1  main -&gt; main
Branch 'main' set up to track remote branch 'main' from 'origin'.
arh (main) wifi_helper $ 
</pre>
<p>Now you will have something like this on GitHub.</p>
<p><a href="https://iotexpert.com/?attachment_id=11320" rel="attachment wp-att-11320"><img loading="lazy" decoding="async" src="https://iotexpert.com/wp-content/uploads/2021/06/Screen-Shot-2021-06-17-at-7.33.33-AM-1024x523.jpg" alt="" width="1024" height="523" class="alignnone size-large wp-image-11320" srcset="https://iotexpert.com/wp-content/uploads/2021/06/Screen-Shot-2021-06-17-at-7.33.33-AM-1024x523.jpg 1024w, https://iotexpert.com/wp-content/uploads/2021/06/Screen-Shot-2021-06-17-at-7.33.33-AM-300x153.jpg 300w, https://iotexpert.com/wp-content/uploads/2021/06/Screen-Shot-2021-06-17-at-7.33.33-AM-768x392.jpg 768w, https://iotexpert.com/wp-content/uploads/2021/06/Screen-Shot-2021-06-17-at-7.33.33-AM-1536x785.jpg 1536w, https://iotexpert.com/wp-content/uploads/2021/06/Screen-Shot-2021-06-17-at-7.33.33-AM-2048x1046.jpg 2048w, https://iotexpert.com/wp-content/uploads/2021/06/Screen-Shot-2021-06-17-at-7.33.33-AM-600x307.jpg 600w" sizes="auto, (max-width: 1024px) 100vw, 1024px" /></a></p>
<h1>Manifest Files</h1>
<p>I would like to be able to have my new library show up in the library browser.  But how?  When the library browser starts up it needs to discover:</p>
<ol>
<li>Board Support Packages</li>
<li>Template Projects</li>
<li>Middleware Code Libraries</li>
</ol>
<p>To do this, it reads a series of XML files called &#8220;manifests&#8221;.  These manifest files tell the library browser where to find the libraries.  If you have ever noticed the library browser (or the new project creator) it looks like this:</p>
<p><a href="https://iotexpert.com/?attachment_id=11321" rel="attachment wp-att-11321"><img loading="lazy" decoding="async" src="https://iotexpert.com/wp-content/uploads/2021/06/Screen-Shot-2021-06-17-at-8.24.40-AM-1024x461.jpg" alt="" width="1024" height="461" class="alignnone size-large wp-image-11321" srcset="https://iotexpert.com/wp-content/uploads/2021/06/Screen-Shot-2021-06-17-at-8.24.40-AM-1024x461.jpg 1024w, https://iotexpert.com/wp-content/uploads/2021/06/Screen-Shot-2021-06-17-at-8.24.40-AM-300x135.jpg 300w, https://iotexpert.com/wp-content/uploads/2021/06/Screen-Shot-2021-06-17-at-8.24.40-AM-768x346.jpg 768w, https://iotexpert.com/wp-content/uploads/2021/06/Screen-Shot-2021-06-17-at-8.24.40-AM-1536x692.jpg 1536w, https://iotexpert.com/wp-content/uploads/2021/06/Screen-Shot-2021-06-17-at-8.24.40-AM-2048x922.jpg 2048w, https://iotexpert.com/wp-content/uploads/2021/06/Screen-Shot-2021-06-17-at-8.24.40-AM-600x270.jpg 600w" sizes="auto, (max-width: 1024px) 100vw, 1024px" /></a></p>
<p>The message &#8220;Processing super-manifest &#8230;&#8221; give you a hint to go to https://raw.githubusercontent.com/cypresssemiconductorco/mtb-super-manifest/v2.X/mtb-super-manifest-fv2.xml</p>
<p>Here it is.  Notice that the XML scheme says that this file is a &#8220;super-manifest&#8221;.  Then notice that there are sections:</p>
<ul>
<li>&lt;board-manifest-list&gt; these are BSPs</li>
<li>&lt;app-manifest-list&gt; these are template projects</li>
<li>&lt;middleware-manifest-list&gt; these are middleware code libraries</li>
</ul>
<pre class="EnlighterJSRAW" data-enlighter-language="xml">&lt;super-manifest&gt;
  &lt;board-manifest-list&gt;
    &lt;board-manifest&gt;
      &lt;uri&gt;https://github.com/cypresssemiconductorco/mtb-bsp-manifest/raw/v2.X/mtb-bsp-manifest.xml&lt;/uri&gt;
    &lt;/board-manifest&gt;
    &lt;board-manifest dependency-url="https://github.com/cypresssemiconductorco/mtb-bsp-manifest/raw/v2.X/mtb-bsp-dependencies-manifest.xml"&gt;
      &lt;uri&gt;https://github.com/cypresssemiconductorco/mtb-bsp-manifest/raw/v2.X/mtb-bsp-manifest-fv2.xml&lt;/uri&gt;
    &lt;/board-manifest&gt;
    &lt;board-manifest&gt;
      &lt;uri&gt;https://github.com/cypresssemiconductorco/mtb-bt-bsp-manifest/raw/v2.X/mtb-bt-bsp-manifest.xml&lt;/uri&gt;
    &lt;/board-manifest&gt;
    &lt;board-manifest dependency-url="https://github.com/cypresssemiconductorco/mtb-bt-bsp-manifest/raw/v2.X/mtb-bt-bsp-dependencies-manifest.xml"&gt;
      &lt;uri&gt;https://github.com/cypresssemiconductorco/mtb-bt-bsp-manifest/raw/v2.X/mtb-bt-bsp-manifest-fv2.xml&lt;/uri&gt;
    &lt;/board-manifest&gt;
  &lt;/board-manifest-list&gt;
  &lt;app-manifest-list&gt;
    &lt;app-manifest&gt;
      &lt;uri&gt;https://github.com/cypresssemiconductorco/mtb-ce-manifest/raw/v2.X/mtb-ce-manifest.xml&lt;/uri&gt;
    &lt;/app-manifest&gt;
    &lt;app-manifest&gt;
      &lt;uri&gt;https://github.com/cypresssemiconductorco/mtb-ce-manifest/raw/v2.X/mtb-ce-manifest-fv2.xml&lt;/uri&gt;
    &lt;/app-manifest&gt;
    &lt;app-manifest&gt;
      &lt;uri&gt;https://github.com/cypresssemiconductorco/mtb-bt-app-manifest/raw/v2.X/mtb-bt-app-manifest.xml&lt;/uri&gt;
    &lt;/app-manifest&gt;
    &lt;app-manifest&gt;
      &lt;uri&gt;https://github.com/cypresssemiconductorco/mtb-bt-app-manifest/raw/v2.X/mtb-bt-app-manifest-fv2.xml&lt;/uri&gt;
    &lt;/app-manifest&gt;
  &lt;/app-manifest-list&gt;
  &lt;middleware-manifest-list&gt;
    &lt;middleware-manifest&gt;
      &lt;uri&gt;https://github.com/cypresssemiconductorco/mtb-mw-manifest/raw/v2.X/mtb-mw-manifest.xml&lt;/uri&gt;
    &lt;/middleware-manifest&gt;
    &lt;middleware-manifest dependency-url="https://github.com/cypresssemiconductorco/mtb-mw-manifest/raw/v2.X/mtb-mw-dependencies-manifest.xml"&gt;
      &lt;uri&gt;https://github.com/cypresssemiconductorco/mtb-mw-manifest/raw/v2.X/mtb-mw-manifest-fv2.xml&lt;/uri&gt;
    &lt;/middleware-manifest&gt;
    &lt;middleware-manifest&gt;
      &lt;uri&gt;https://github.com/cypresssemiconductorco/mtb-bt-mw-manifest/raw/v2.X/mtb-bt-mw-manifest.xml&lt;/uri&gt;
    &lt;/middleware-manifest&gt;
    &lt;middleware-manifest dependency-url="https://github.com/cypresssemiconductorco/mtb-bt-mw-manifest/raw/v2.X/mtb-bt-mw-dependencies-manifest.xml"&gt;
      &lt;uri&gt;https://github.com/cypresssemiconductorco/mtb-bt-mw-manifest/raw/v2.X/mtb-bt-mw-manifest-fv2.xml&lt;/uri&gt;
    &lt;/middleware-manifest&gt;
    &lt;middleware-manifest&gt;
      &lt;uri&gt;https://github.com/cypresssemiconductorco/mtb-wifi-mw-manifest/raw/v2.X/mtb-wifi-mw-manifest.xml&lt;/uri&gt;
    &lt;/middleware-manifest&gt;
    &lt;middleware-manifest dependency-url="https://github.com/cypresssemiconductorco/mtb-wifi-mw-manifest/raw/v2.X/mtb-wifi-mw-dependencies-manifest.xml"&gt;
      &lt;uri&gt;https://github.com/cypresssemiconductorco/mtb-wifi-mw-manifest/raw/v2.X/mtb-wifi-mw-manifest-fv2.xml&lt;/uri&gt;
    &lt;/middleware-manifest&gt;
  &lt;/middleware-manifest-list&gt;
&lt;/super-manifest&gt;</pre>
<p>But you can&#8217;t modify this to add your own?  So what do you do now?  Cypress put in the capability for you to extend the system by creating a file called &#8220;~/.modustoolbox/manifest.loc&#8221;.  This file contains one or more URLs to super-manifest files (like the one above) where you can add whatever you want.</p>
<p>Here is the iotexpert manifest.loc</p>
<pre class="EnlighterJSRAW" data-enlighter-language="generic">arh ~ $ cd ~/.modustoolbox/
arh .modustoolbox $ more manifest.loc
https://github.com/iotexpert/mtb2-iotexpert-manifests/raw/master/iotexpert-super-manifest.xml
arh .modustoolbox $</pre>
<p>This file points to a super manifest file in a GitHub repository.  Here is the repository:</p>
<p><a href="https://iotexpert.com/?attachment_id=11322" rel="attachment wp-att-11322"><img loading="lazy" decoding="async" src="https://iotexpert.com/wp-content/uploads/2021/06/Screen-Shot-2021-06-17-at-8.34.16-AM-1024x619.jpg" alt="" width="1024" height="619" class="alignnone size-large wp-image-11322" srcset="https://iotexpert.com/wp-content/uploads/2021/06/Screen-Shot-2021-06-17-at-8.34.16-AM-1024x619.jpg 1024w, https://iotexpert.com/wp-content/uploads/2021/06/Screen-Shot-2021-06-17-at-8.34.16-AM-300x181.jpg 300w, https://iotexpert.com/wp-content/uploads/2021/06/Screen-Shot-2021-06-17-at-8.34.16-AM-768x464.jpg 768w, https://iotexpert.com/wp-content/uploads/2021/06/Screen-Shot-2021-06-17-at-8.34.16-AM-1536x928.jpg 1536w, https://iotexpert.com/wp-content/uploads/2021/06/Screen-Shot-2021-06-17-at-8.34.16-AM-2048x1237.jpg 2048w, https://iotexpert.com/wp-content/uploads/2021/06/Screen-Shot-2021-06-17-at-8.34.16-AM-600x363.jpg 600w" sizes="auto, (max-width: 1024px) 100vw, 1024px" /></a></p>
<p>Notice that it has</p>
<ul>
<li>iotexpert-super-manifest.xml &#8211; the top level iotexpert manifest</li>
<li>iotexpert-app-manifest.xml &#8211; my template projects</li>
<li>iotexpert-mw-manifest.xml &#8211; my middleware</li>
<li>manifest.loc &#8211; the file you need to put in your home directory</li>
<li>iotexpert-mw-dependencies.xml &#8211; a new file which I will talk about later</li>
</ul>
<p>And the super manifest file that looks like this:</p>
<pre class="EnlighterJSRAW" data-enlighter-language="xml">&lt;super-manifest&gt;
  &lt;board-manifest-list&gt;
  &lt;/board-manifest-list&gt;
  
  &lt;app-manifest-list&gt;
    &lt;app-manifest&gt;
      &lt;uri&gt;https://github.com/iotexpert/mtb2-iotexpert-manifests/raw/master/iotexpert-app-manifest.xml&lt;/uri&gt;
      &lt;/app-manifest&gt;
   &lt;/app-manifest-list&gt;
  &lt;board-manifest-list&gt;
  &lt;/board-manifest-list&gt;
  &lt;middleware-manifest-list&gt;
    &lt;middleware-manifest dependency-url="https://github.com/iotexpert/mtb2-iotexpert-manifests/raw/master/iotexpert-mw-dependencies.xml"&gt;
      &lt;uri&gt;https://github.com/iotexpert/mtb2-iotexpert-manifests/raw/master/iotexpert-mw-manifest.xml&lt;/uri&gt;
    &lt;/middleware-manifest&gt;
  &lt;/middleware-manifest-list&gt;
&lt;/super-manifest&gt;</pre>
<p>To add the library we created above, I need to add the new middleware into my middleware manifest.  Modify the file &#8220;<span>iotexpert-mw-manifest.xml&#8221; to have the new middleware.</span></p>
<pre class="EnlighterJSRAW" data-enlighter-language="xml">&lt;middleware&gt;
  &lt;name&gt;WiFi Helper Utilties&lt;/name&gt;
  &lt;id&gt;wifi_helper&lt;/id&gt;
  &lt;uri&gt;https://github.com/iotexpert/wifi_helper&lt;/uri&gt;
  &lt;desc&gt;A library WiFi Helper utilities (e.g. aton)&lt;/desc&gt;
  &lt;category&gt;IoT Expert&lt;/category&gt;
  &lt;req_capabilities&gt;psoc6&lt;/req_capabilities&gt;
  &lt;versions&gt;
    &lt;version flow_version="2.0"&gt;
      &lt;num&gt;main&lt;/num&gt;
      &lt;commit&gt;main&lt;/commit&gt;
      &lt;desc&gt;main&lt;/desc&gt;
    &lt;/version&gt;
  &lt;/versions&gt;
&lt;/middleware&gt;
</pre>
<p>If you recall I have the &#8220;wifi_helper&#8221; directory inside of my project.  Not what I want (because I want it to be pulled using the library browser).  So I move out my project directory.  Now, let&#8217;s test the whole thing by running the library browser.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="generic">arh (master *+) IoTExpertWiFiTemplate $ pwd
/Users/arh/proj/elkhorncreek3/IoTExpertWiFiTemplate
arh (master *+) IoTExpertWiFiTemplate $ mv wifi_helper/ ~/proj/
arh (master *+) IoTExpertWiFiTemplate $ make modlibs
Tools Directory: /Applications/ModusToolbox/tools_2.3
CY8CKIT-062S2-43012.mk: ./libs/TARGET_CY8CKIT-062S2-43012/CY8CKIT-062S2-43012.mk
Launching library-manager</pre>
<p>Excellent the WiFI Helper utilities show up.</p>
<p><a href="https://iotexpert.com/?attachment_id=11309" rel="attachment wp-att-11309"><img loading="lazy" decoding="async" src="https://iotexpert.com/wp-content/uploads/2021/06/Screen-Shot-2021-06-16-at-7.46.08-AM-1024x792.jpg" alt="" width="1024" height="792" class="alignnone size-large wp-image-11309" srcset="https://iotexpert.com/wp-content/uploads/2021/06/Screen-Shot-2021-06-16-at-7.46.08-AM-1024x792.jpg 1024w, https://iotexpert.com/wp-content/uploads/2021/06/Screen-Shot-2021-06-16-at-7.46.08-AM-300x232.jpg 300w, https://iotexpert.com/wp-content/uploads/2021/06/Screen-Shot-2021-06-16-at-7.46.08-AM-768x594.jpg 768w, https://iotexpert.com/wp-content/uploads/2021/06/Screen-Shot-2021-06-16-at-7.46.08-AM-1536x1188.jpg 1536w, https://iotexpert.com/wp-content/uploads/2021/06/Screen-Shot-2021-06-16-at-7.46.08-AM-2048x1584.jpg 2048w, https://iotexpert.com/wp-content/uploads/2021/06/Screen-Shot-2021-06-16-at-7.46.08-AM-600x464.jpg 600w" sizes="auto, (max-width: 1024px) 100vw, 1024px" /></a></p>
<p>And when I run the &#8220;update&#8221; the files show up in the project.</p>
<p><a href="https://iotexpert.com/?attachment_id=11311" rel="attachment wp-att-11311"><img loading="lazy" decoding="async" src="https://iotexpert.com/wp-content/uploads/2021/06/Screen-Shot-2021-06-16-at-7.48.25-AM-330x1024.png" alt="" width="330" height="1024" class="alignnone size-large wp-image-11311" srcset="https://iotexpert.com/wp-content/uploads/2021/06/Screen-Shot-2021-06-16-at-7.48.25-AM-330x1024.png 330w, https://iotexpert.com/wp-content/uploads/2021/06/Screen-Shot-2021-06-16-at-7.48.25-AM-97x300.png 97w, https://iotexpert.com/wp-content/uploads/2021/06/Screen-Shot-2021-06-16-at-7.48.25-AM-600x1864.png 600w, https://iotexpert.com/wp-content/uploads/2021/06/Screen-Shot-2021-06-16-at-7.48.25-AM.png 620w" sizes="auto, (max-width: 330px) 100vw, 330px" /></a></p>
<h1>Add Dependencies</h1>
<p>If you recall from the code I had this include:</p>
<pre class="EnlighterJSRAW" data-enlighter-language="c">#include "cy_wcm.h"</pre>
<p>That means that I am dependent on the library &#8220;<span>wifi-connection-manager&#8221;.  To make this work I create a new file called &#8220;iotexpert-mw-depenencies.xml&#8221;.  In that file I tell the system that &#8220;wifi_helper&#8221; is now dependent on &#8220;wcm&#8221;</span></p>
<pre class="EnlighterJSRAW" data-enlighter-language="xml">&lt;dependencies version="2.0"&gt;
  &lt;depender&gt;
    &lt;id&gt;wifi_helper&lt;/id&gt;
    &lt;versions&gt;
      &lt;version&gt;
        &lt;commit&gt;main&lt;/commit&gt;
        &lt;dependees&gt;
          &lt;dependee&gt;
            &lt;id&gt;wcm&lt;/id&gt;
            &lt;commit&gt;latest-v2.X&lt;/commit&gt;
          &lt;/dependee&gt;
        &lt;/dependees&gt;
      &lt;/version&gt;
    &lt;/versions&gt;
  &lt;/depender&gt;
&lt;/dependencies&gt;</pre>
<p>Once I have that file, I add that depencency file to my middleware manifest file.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="xml">  &lt;middleware-manifest-list&gt;
    &lt;middleware-manifest dependency-url="https://github.com/iotexpert/mtb2-iotexpert-manifests/raw/master/iotexpert-mw-dependencies.xml"&gt;
      &lt;uri&gt;https://github.com/iotexpert/mtb2-iotexpert-manifests/raw/master/iotexpert-mw-manifest.xml&lt;/uri&gt;
    &lt;/middleware-manifest&gt;
  &lt;/middleware-manifest-list&gt;
&lt;/super-manifest&gt;
</pre>
<p>Now when I start the library browser and add the &#8220;WiFi Help Utilities&#8221; it will automatically add the wireless connection manager (and all of the libraries that the wcm is dependent on.</p>
<p><a href="https://iotexpert.com/?attachment_id=11314" rel="attachment wp-att-11314"><img loading="lazy" decoding="async" src="https://iotexpert.com/wp-content/uploads/2021/06/Screen-Shot-2021-06-16-at-10.13.07-AM-1024x885.jpg" alt="" width="1024" height="885" class="alignnone size-large wp-image-11314" srcset="https://iotexpert.com/wp-content/uploads/2021/06/Screen-Shot-2021-06-16-at-10.13.07-AM-1024x885.jpg 1024w, https://iotexpert.com/wp-content/uploads/2021/06/Screen-Shot-2021-06-16-at-10.13.07-AM-300x259.jpg 300w, https://iotexpert.com/wp-content/uploads/2021/06/Screen-Shot-2021-06-16-at-10.13.07-AM-768x663.jpg 768w, https://iotexpert.com/wp-content/uploads/2021/06/Screen-Shot-2021-06-16-at-10.13.07-AM-1536x1327.jpg 1536w, https://iotexpert.com/wp-content/uploads/2021/06/Screen-Shot-2021-06-16-at-10.13.07-AM-2048x1769.jpg 2048w, https://iotexpert.com/wp-content/uploads/2021/06/Screen-Shot-2021-06-16-at-10.13.07-AM-600x518.jpg 600w" sizes="auto, (max-width: 1024px) 100vw, 1024px" /></a></p>
<p>In the next article I will add Scanning functionality to the WiFi Task.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://iotexpert.com/anycloud-wifi-template-wifi-helper-library-part-3-a-new-modus-toolbox-library/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>AnyCloud WiFi Template + WiFi Helper Library (Part 2): Enable the WiFi Network</title>
		<link>https://iotexpert.com/anycloud-wifi-template-wifi-helper-library-part-2-enable-the-wifi-network/</link>
					<comments>https://iotexpert.com/anycloud-wifi-template-wifi-helper-library-part-2-enable-the-wifi-network/#respond</comments>
		
		<dc:creator><![CDATA[Alan Hawse]]></dc:creator>
		<pubDate>Mon, 28 Jun 2021 14:03:42 +0000</pubDate>
				<category><![CDATA[AnyCloud]]></category>
		<category><![CDATA[CY8CKIT-062S2-43012]]></category>
		<category><![CDATA[WIFI]]></category>
		<guid isPermaLink="false">https://iotexpert.com/?p=11285</guid>

					<description><![CDATA[Summary Instructions on using the AnyCloud Wireless Connection manager to enable WiFi.  This article is Part 2 of a series that will build a new IoT Expert template project for WiFi. Story In the last article I got things going by starting from the old template, fixing up the Visual Studio Code configuration, adding the [&#8230;]]]></description>
										<content:encoded><![CDATA[<h1>Summary</h1>
<p>Instructions on using the AnyCloud Wireless Connection manager to enable WiFi.  This article is Part 2 of a series that will build a new IoT Expert template project for WiFi.</p>
<p><span><p><div class="table-responsive"><table  style="width:95%; "  class="easy-table easy-table-default " border="1">
<thead>
<tr><th >Article</th>
</tr>
</thead>
<tbody>
<tr><td >(Part 1) Create Basic Project &amp; Add Cypress Logging Functionality</td>
</tr>

<tr><td >(Part 2) Create New Thread to manage WiFi using the Wireless Connection Manager</td>
</tr>

<tr><td >(Part 3) Create a New Middleware Library with WiFi helper functions</td>
</tr>

<tr><td >(Part 4) Add WiFi Scan</td>
</tr>

<tr><td >Add WiFi Connect</td>
</tr>

<tr><td >Add WiFi Disconnect</td>
</tr>

<tr><td >Add WiFi Ping</td>
</tr>

<tr><td >Add Gethostbyname</td>
</tr>

<tr><td >Add MDNS</td>
</tr>

<tr><td >Add Status</td>
</tr>

<tr><td >Add StartAP</td>
</tr>

<tr><td >Make a new template project (update manifest)</td>
</tr>
</tbody></table></div></p></span></p>
<h1>Story</h1>
<p>In the last article I got things going by starting from the old template, fixing up the Visual Studio Code configuration, adding the new Cypress Logging functionality and then testing everything.</p>
<p>In this article I will</p>
<ol>
<li>Create new task to manage WiFi</li>
<li>Add Wireless Connection Manager to the project</li>
<li>Create wifi_task.h and wifi_task.c</li>
<li>Update usrcmd.c to send commands to the WiFi task</li>
</ol>
<h1>Create New Task to Manage WiFi</h1>
<p>I am going to start by creating new a new task (called wifi_task) that will be responsible for managing the WiFi connection.  In Visual Studio Code you can create a new file by pressing the little document with the + on it.  You will need a file &#8220;wifi_task.h&#8221; and one &#8220;wifi_task.c&#8221;</p>
<p><a href="https://iotexpert.com/?attachment_id=11286" rel="attachment wp-att-11286"><img loading="lazy" decoding="async" src="https://iotexpert.com/wp-content/uploads/2021/06/Screen-Shot-2021-06-15-at-12.32.14-PM-1024x1007.png" alt="" width="1024" height="1007" class="alignnone size-large wp-image-11286" srcset="https://iotexpert.com/wp-content/uploads/2021/06/Screen-Shot-2021-06-15-at-12.32.14-PM-1024x1007.png 1024w, https://iotexpert.com/wp-content/uploads/2021/06/Screen-Shot-2021-06-15-at-12.32.14-PM-300x295.png 300w, https://iotexpert.com/wp-content/uploads/2021/06/Screen-Shot-2021-06-15-at-12.32.14-PM-768x755.png 768w, https://iotexpert.com/wp-content/uploads/2021/06/Screen-Shot-2021-06-15-at-12.32.14-PM-600x590.png 600w, https://iotexpert.com/wp-content/uploads/2021/06/Screen-Shot-2021-06-15-at-12.32.14-PM.png 1068w" sizes="auto, (max-width: 1024px) 100vw, 1024px" /></a></p>
<p>Once you have wifi_task.h you will need to add the function prototype for the wifi_task.  In addition add a &#8220;guard&#8221;.  I like to use &#8220;#pragma once&#8221;</p>
<p><a href="https://iotexpert.com/?attachment_id=11287" rel="attachment wp-att-11287"><img loading="lazy" decoding="async" src="https://iotexpert.com/wp-content/uploads/2021/06/Screen-Shot-2021-06-15-at-12.33.07-PM-1024x423.png" alt="" width="1024" height="423" class="alignnone size-large wp-image-11287" srcset="https://iotexpert.com/wp-content/uploads/2021/06/Screen-Shot-2021-06-15-at-12.33.07-PM-1024x423.png 1024w, https://iotexpert.com/wp-content/uploads/2021/06/Screen-Shot-2021-06-15-at-12.33.07-PM-300x124.png 300w, https://iotexpert.com/wp-content/uploads/2021/06/Screen-Shot-2021-06-15-at-12.33.07-PM-768x317.png 768w, https://iotexpert.com/wp-content/uploads/2021/06/Screen-Shot-2021-06-15-at-12.33.07-PM-1536x635.png 1536w, https://iotexpert.com/wp-content/uploads/2021/06/Screen-Shot-2021-06-15-at-12.33.07-PM-2048x846.png 2048w, https://iotexpert.com/wp-content/uploads/2021/06/Screen-Shot-2021-06-15-at-12.33.07-PM-600x248.png 600w" sizes="auto, (max-width: 1024px) 100vw, 1024px" /></a></p>
<p>Here is copyable code.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="generic">#pragma once
void wifi_task(void *arg);
</pre>
<p>In wifi_task.c Ill start with a simple blinking LED function.  Well actually it will do a print instead of a blink.  Here it is:</p>
<pre class="EnlighterJSRAW" data-enlighter-language="c">#include "wifi_task.h"
#include "FreeRTOS.h"
#include "task.h"
#include &lt;stdio.h&gt;

void wifi_task(void *arg)
{
    while(1)
    {
        vTaskDelay(1000);
        printf("blink\n");

    }
}</pre>
<p>Now that I have a wifi_task (which doesn&#8217;t do much) lets update main.c.  First include the wifi_task.h</p>
<pre class="EnlighterJSRAW" data-enlighter-language="c">#include "wifi_task.h"</pre>
<p>Then create the task.  Notice that I start with a pretty big stack.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="c">xTaskCreate(wifi_task,   "WiFi"       , configMINIMAL_STACK_SIZE*20,0 /* args */ ,0 /* priority */, 0);
</pre>
<p>When you run this, you will have the &#8220;blink&#8221; interleaved with the blink from the last article.</p>
<p><a href="https://iotexpert.com/?attachment_id=11288" rel="attachment wp-att-11288"><img loading="lazy" decoding="async" src="https://iotexpert.com/wp-content/uploads/2021/06/Screen-Shot-2021-06-15-at-12.43.08-PM-1024x801.jpg" alt="" width="1024" height="801" class="alignnone size-large wp-image-11288" srcset="https://iotexpert.com/wp-content/uploads/2021/06/Screen-Shot-2021-06-15-at-12.43.08-PM-1024x801.jpg 1024w, https://iotexpert.com/wp-content/uploads/2021/06/Screen-Shot-2021-06-15-at-12.43.08-PM-300x235.jpg 300w, https://iotexpert.com/wp-content/uploads/2021/06/Screen-Shot-2021-06-15-at-12.43.08-PM-768x601.jpg 768w, https://iotexpert.com/wp-content/uploads/2021/06/Screen-Shot-2021-06-15-at-12.43.08-PM-1536x1202.jpg 1536w, https://iotexpert.com/wp-content/uploads/2021/06/Screen-Shot-2021-06-15-at-12.43.08-PM-600x470.jpg 600w, https://iotexpert.com/wp-content/uploads/2021/06/Screen-Shot-2021-06-15-at-12.43.08-PM.jpg 1876w" sizes="auto, (max-width: 1024px) 100vw, 1024px" /></a></p>
<h1>Add Wireless Connection Manager</h1>
<p>You next step is to add the wireless connection manager.  Start the library browser by running &#8220;make modlibs&#8221;.  Then click on the wifi-connection-manager&#8221;.  Notice that when you do that, it will bring in a bunch of other libraries as well.  These are all libraries that it (the WiFi-Connection-Manager) is depend on.</p>
<p><a href="https://iotexpert.com/?attachment_id=11289" rel="attachment wp-att-11289"><img loading="lazy" decoding="async" src="https://iotexpert.com/wp-content/uploads/2021/06/Screen-Shot-2021-06-15-at-12.47.17-PM-784x1024.jpg" alt="" width="784" height="1024" class="alignnone size-large wp-image-11289" srcset="https://iotexpert.com/wp-content/uploads/2021/06/Screen-Shot-2021-06-15-at-12.47.17-PM-784x1024.jpg 784w, https://iotexpert.com/wp-content/uploads/2021/06/Screen-Shot-2021-06-15-at-12.47.17-PM-230x300.jpg 230w, https://iotexpert.com/wp-content/uploads/2021/06/Screen-Shot-2021-06-15-at-12.47.17-PM-768x1003.jpg 768w, https://iotexpert.com/wp-content/uploads/2021/06/Screen-Shot-2021-06-15-at-12.47.17-PM-600x784.jpg 600w, https://iotexpert.com/wp-content/uploads/2021/06/Screen-Shot-2021-06-15-at-12.47.17-PM.jpg 1130w" sizes="auto, (max-width: 784px) 100vw, 784px" /></a></p>
<p>If you look in the wireless connection manager documentation you will find this nice note.  It says that the WCM uses the Cypress logging functionality and you can turn it on with a #define.  That&#8217;s cool.  So now I edit the Makefile and add the define.</p>
<p><a href="https://iotexpert.com/?attachment_id=11335" rel="attachment wp-att-11335"><img loading="lazy" decoding="async" src="https://iotexpert.com/wp-content/uploads/2021/06/Screen-Shot-2021-06-19-at-8.40.43-AM-1024x232.png" alt="" width="1024" height="232" class="alignnone size-large wp-image-11335" srcset="https://iotexpert.com/wp-content/uploads/2021/06/Screen-Shot-2021-06-19-at-8.40.43-AM-1024x232.png 1024w, https://iotexpert.com/wp-content/uploads/2021/06/Screen-Shot-2021-06-19-at-8.40.43-AM-300x68.png 300w, https://iotexpert.com/wp-content/uploads/2021/06/Screen-Shot-2021-06-19-at-8.40.43-AM-768x174.png 768w, https://iotexpert.com/wp-content/uploads/2021/06/Screen-Shot-2021-06-19-at-8.40.43-AM-1536x349.png 1536w, https://iotexpert.com/wp-content/uploads/2021/06/Screen-Shot-2021-06-19-at-8.40.43-AM-2048x465.png 2048w, https://iotexpert.com/wp-content/uploads/2021/06/Screen-Shot-2021-06-19-at-8.40.43-AM-600x136.png 600w" sizes="auto, (max-width: 1024px) 100vw, 1024px" /></a></p>
<p>The the documentation also says that this library depends on the &#8220;Wi-Fi Middleware Core&#8221;</p>
<p><a href="https://iotexpert.com/?attachment_id=11337" rel="attachment wp-att-11337"><img loading="lazy" decoding="async" src="https://iotexpert.com/wp-content/uploads/2021/06/Screen-Shot-2021-06-19-at-8.41.35-AM-1024x108.png" alt="" width="1024" height="108" class="alignnone size-large wp-image-11337" srcset="https://iotexpert.com/wp-content/uploads/2021/06/Screen-Shot-2021-06-19-at-8.41.35-AM-1024x108.png 1024w, https://iotexpert.com/wp-content/uploads/2021/06/Screen-Shot-2021-06-19-at-8.41.35-AM-300x32.png 300w, https://iotexpert.com/wp-content/uploads/2021/06/Screen-Shot-2021-06-19-at-8.41.35-AM-768x81.png 768w, https://iotexpert.com/wp-content/uploads/2021/06/Screen-Shot-2021-06-19-at-8.41.35-AM-1536x162.png 1536w, https://iotexpert.com/wp-content/uploads/2021/06/Screen-Shot-2021-06-19-at-8.41.35-AM-2048x216.png 2048w, https://iotexpert.com/wp-content/uploads/2021/06/Screen-Shot-2021-06-19-at-8.41.35-AM-600x63.png 600w" sizes="auto, (max-width: 1024px) 100vw, 1024px" /></a></p>
<p>If you go to the Wi-Fi Middleware core library documentation you will see instructions that say that you need to</p>
<ol>
<li>Enable &amp; Configure LWIP</li>
<li>Enable &amp; Configure MBEDTLS</li>
<li>Enable &amp; Configure the Cypress RTOS Abstraction</li>
</ol>
<p>In order to do that you will need to two things</p>
<ol>
<li>Copy the configuration files into your project</li>
<li>Setup some options in the Makefile</li>
</ol>
<p>Start by copying the file.  They give you default configurations in mtb_share/wifi-mw-core/version/configs.  You will want to copy those files into your project.  This can be done in the Visual Studio Code interface using ctrl-c and ctrl-v</p>
<p><a href="https://iotexpert.com/?attachment_id=11290" rel="attachment wp-att-11290"><img loading="lazy" decoding="async" src="https://iotexpert.com/wp-content/uploads/2021/06/Screen-Shot-2021-06-15-at-1.28.18-PM-737x1024.png" alt="" width="737" height="1024" class="alignnone size-large wp-image-11290" srcset="https://iotexpert.com/wp-content/uploads/2021/06/Screen-Shot-2021-06-15-at-1.28.18-PM-737x1024.png 737w, https://iotexpert.com/wp-content/uploads/2021/06/Screen-Shot-2021-06-15-at-1.28.18-PM-216x300.png 216w, https://iotexpert.com/wp-content/uploads/2021/06/Screen-Shot-2021-06-15-at-1.28.18-PM-768x1068.png 768w, https://iotexpert.com/wp-content/uploads/2021/06/Screen-Shot-2021-06-15-at-1.28.18-PM-600x834.png 600w, https://iotexpert.com/wp-content/uploads/2021/06/Screen-Shot-2021-06-15-at-1.28.18-PM.png 948w" sizes="auto, (max-width: 737px) 100vw, 737px" /></a></p>
<p>Notice that I now have two FreeRTOSConfig files.  So, delete the original file and rename the copied file.</p>
<p><a href="https://iotexpert.com/?attachment_id=11291" rel="attachment wp-att-11291"><img loading="lazy" decoding="async" src="https://iotexpert.com/wp-content/uploads/2021/06/Screen-Shot-2021-06-15-at-1.30.13-PM.png" alt="" width="948" height="390" class="alignnone size-full wp-image-11291" srcset="https://iotexpert.com/wp-content/uploads/2021/06/Screen-Shot-2021-06-15-at-1.30.13-PM.png 948w, https://iotexpert.com/wp-content/uploads/2021/06/Screen-Shot-2021-06-15-at-1.30.13-PM-300x123.png 300w, https://iotexpert.com/wp-content/uploads/2021/06/Screen-Shot-2021-06-15-at-1.30.13-PM-768x316.png 768w, https://iotexpert.com/wp-content/uploads/2021/06/Screen-Shot-2021-06-15-at-1.30.13-PM-600x247.png 600w" sizes="auto, (max-width: 948px) 100vw, 948px" /></a></p>
<p>Now your project should look like this:</p>
<p><a href="https://iotexpert.com/?attachment_id=11292" rel="attachment wp-att-11292"><img loading="lazy" decoding="async" src="https://iotexpert.com/wp-content/uploads/2021/06/Screen-Shot-2021-06-15-at-1.31.12-PM.png" alt="" width="962" height="920" class="alignnone size-full wp-image-11292" srcset="https://iotexpert.com/wp-content/uploads/2021/06/Screen-Shot-2021-06-15-at-1.31.12-PM.png 962w, https://iotexpert.com/wp-content/uploads/2021/06/Screen-Shot-2021-06-15-at-1.31.12-PM-300x287.png 300w, https://iotexpert.com/wp-content/uploads/2021/06/Screen-Shot-2021-06-15-at-1.31.12-PM-768x734.png 768w, https://iotexpert.com/wp-content/uploads/2021/06/Screen-Shot-2021-06-15-at-1.31.12-PM-600x574.png 600w" sizes="auto, (max-width: 962px) 100vw, 962px" /></a></p>
<p>The next step is to fix the Makefile by adding some defines.</p>
<p>&nbsp;</p>
<pre class="EnlighterJSRAW" data-enlighter-language="generic">DEFINES=CY_RETARGET_IO_CONVERT_LF_TO_CRLF
DEFINES+=CYBSP_WIFI_CAPABLE CY_RTOS_AWARE
DEFINES+=MBEDTLS_USER_CONFIG_FILE='"mbedtls_user_config.h"'
DEFINES+=ENABLE_WIFI_MIDDLEWARE_LOGS
</pre>
<p>The add the required components</p>
<pre class="EnlighterJSRAW" data-enlighter-language="generic">COMPONENTS=FREERTOS LWIP MBEDTLS PSOC6HAL
</pre>
<h1>Update wifi_task.c</h1>
<p>My wifi task is going to work by</p>
<ol>
<li>Sitting on Queue waiting for messages of &#8220;wifi_cmd_t&#8221;</li>
<li>When those messages come in, execute the right command.</li>
</ol>
<p>Start by adding some includes to the wifi_task.c</p>
<pre class="EnlighterJSRAW" data-enlighter-language="c">#include &lt;stdio.h&gt;
#include "wifi_task.h"
#include "FreeRTOS.h"
#include "task.h"
#include "queue.h"

#include "cy_wcm.h"
</pre>
<p>Then define the legal commands.  I will add a bunch of more commands in the future articles.  But for this article there will be only one command.  Enable.  The command message is</p>
<ol>
<li>The command</li>
<li>Three args of unknown type</li>
</ol>
<p>In addition you will require</p>
<ol>
<li>The command queue</li>
<li>An initialize state variable</li>
<li>A way to keep track of what mode you are in (AP, STA or APSTA)</li>
</ol>
<pre class="EnlighterJSRAW" data-enlighter-language="c">typedef enum {
    WIFI_CMD_ENABLE,

} wifi_cmd_t;

typedef struct {
    wifi_cmd_t cmd;
    void *arg0;
    void *arg1;
    void *arg2;
} wifi_cmdMsg_t;


static QueueHandle_t wifi_cmdQueue;
static bool wifi_initialized=false;
static cy_wcm_interface_t wifi_network_mode;</pre>
<p>The first &#8220;command&#8221; that I will create is the enable.  This will</p>
<ol>
<li>Setup the interface</li>
<li>Initialize the WiFi.  The simple init command actually does a bunch of stuff, including powering on the wifi chip, downloading the firmware into it, setting up all of the tasks in the RTOS, enabling the LWIP and MBEDTLS</li>
</ol>
<pre class="EnlighterJSRAW" data-enlighter-language="c">static void wifi_enable(cy_wcm_interface_t interface)
{
    cy_rslt_t result;
    cy_wcm_config_t config = {.interface = interface}; 
    result = cy_wcm_init(&amp;config); // Initialize the connection manager
    CY_ASSERT(result == CY_RSLT_SUCCESS);

    result = cy_wcm_register_event_callback(wifi_network_event_cb);
    CY_ASSERT(result == CY_RSLT_SUCCESS);

    wifi_network_mode = interface;
    wifi_initialized = true;
    
    printf("\nWi-Fi Connection Manager initialized\n");
    
}
</pre>
<p>In the previous block of code notice that I register a callback.  The callback looks like a switch that prints out messages based on the event type.  Notice that there are three lines which are commented out &#8211; which we will fix in the next article.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="c">static void wifi_network_event_cb(cy_wcm_event_t event, cy_wcm_event_data_t *event_data)
{
    cy_wcm_ip_address_t ip_addr;

    switch(event)
    {
        case CY_WCM_EVENT_CONNECTING:            /**&lt; STA connecting to an AP.         */
            printf("Connecting to AP ... \n");
        break;
        case CY_WCM_EVENT_CONNECTED:             /**&lt; STA connected to the AP.         */
            printf("Connected to AP and network is up !! \n");
        break;
        case CY_WCM_EVENT_CONNECT_FAILED:        /**&lt; STA connection to the AP failed. */
            printf("Connection to AP Failed ! \n");
        break;
        case CY_WCM_EVENT_RECONNECTED:          /**&lt; STA reconnected to the AP.       */
            printf("Network is up again! \n");
        break;
        case CY_WCM_EVENT_DISCONNECTED:         /**&lt; STA disconnected from the AP.    */
            printf("Network is down! \n");
        break;
        case CY_WCM_EVENT_IP_CHANGED:           /**&lt; IP address change event. This event is notified after connection, re-connection, and IP address change due to DHCP renewal. */
                cy_wcm_get_ip_addr(wifi_network_mode, &amp;ip_addr, 1);
   //             printf("Station IP Address Changed: %s\n",wifi_ntoa(&amp;ip_addr));
        break;
        case CY_WCM_EVENT_STA_JOINED_SOFTAP:    /**&lt; An STA device connected to SoftAP. */
 //           printf("STA Joined: %s\n",wifi_mac_to_string(event_data-&gt;sta_mac));
        break;
        case CY_WCM_EVENT_STA_LEFT_SOFTAP:      /**&lt; An STA device disconnected from SoftAP. */
//            printf("STA Left: %s\n",wifi_mac_to_string(event_data-&gt;sta_mac));
        break;
    }

}</pre>
<p>Now I want to update the main loop of the WiFI task.  It is just an infinite loop that processes command messages (from other tasks).</p>
<pre class="EnlighterJSRAW" data-enlighter-language="c">void wifi_task(void *arg)
{
    wifi_cmdQueue = xQueueCreate(10,sizeof(wifi_cmdMsg_t));

    wifi_cmdMsg_t msg;

    while(1)
    {
        xQueueReceive(wifi_cmdQueue,&amp;msg,portMAX_DELAY);
        switch(msg.cmd)
        {
            case WIFI_CMD_ENABLE:
                printf("Received wifi enable message\n");
                wifi_enable((cy_wcm_interface_t)msg.arg0);
            break;

        }
    }
}</pre>
<p>In the other tasks in the system you &#8220;COULD&#8221; create a message and submit it to the queue.  I always think that it is easier if you create a function which can be called in the other threads.  Here is the wifi_enable function.  This function takes a char * of either &#8220;STA&#8221;, &#8220;AP&#8221;, or &#8220;APSTA&#8221; and then submits the right message to the queue.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="c">bool wifi_cmd_enable(char *interface)
{
    wifi_cmdMsg_t msg;
    msg.cmd = WIFI_CMD_ENABLE;
    msg.arg0 = (void *)CY_WCM_INTERFACE_TYPE_STA;

    if(strcmp(interface,"STA") == 0)
        msg.arg0 = (void *)CY_WCM_INTERFACE_TYPE_STA;

    else if(strcmp(interface,"AP") == 0)
        msg.arg0 = (void *)CY_WCM_INTERFACE_TYPE_AP;

    else if(strcmp(interface,"APSTA") == 0)
        msg.arg0 = (void *)CY_WCM_INTERFACE_TYPE_AP_STA;
    
    else
    {
        printf("Legal options are STA, AP, APSTA\n");
        return false;
    }

    xQueueSend(wifi_cmdQueue,&amp;msg,0);
    return true;
}
</pre>
<p>Once I have the nice function for the other tasks, I add it to the public interface in wifi_task.h</p>
<pre class="EnlighterJSRAW" data-enlighter-language="c">#pragma once
#include &lt;stdbool.h&gt;
void wifi_task(void *arg);
bool wifi_cmd_enable(char *interface);</pre>
<h1>Add a new user command &#8220;net&#8221;</h1>
<p>Now that I have the wifi_task setup I want to add a &#8220;net&#8221; command to the command line shell.  Start by adding the include.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="c">#include "wifi_task.h"</pre>
<p>Then create a function prototype for a new command.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="c">static int usrcmd_net(int argc, char **argv);
</pre>
<p>Add the command to the list of commands that the shell knows.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="generic">static const cmd_table_t cmdlist[] = {
    { "help", "This is a description text string for help command.", usrcmd_help },
    { "info", "This is a description text string for info command.", usrcmd_info },
    { "clear", "Clear the screen", usrcmd_clear },
    { "pargs","print the list of arguments", usrcmd_pargs},
#ifdef configUSE_TRACE_FACILITY 
#if configUSE_STATS_FORMATTING_FUNCTIONS ==1
    { "tasks","print the list of RTOS Tasks", usrcmd_list},
#endif
#endif
    { "net","net [help,enable]",usrcmd_net},
};
</pre>
<p>Then create the net command.  I want a BUNCH of net commands.  They will include help, enable, connect, disconnect, &#8230;. but for now we will start with enable.  This function just calls the wifi_enable command that we added to the wifi_task.h interface.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="c">static int usrcmd_net(int argc, char **argv)
{
    if(argc == 1 || strcmp("help",argv[1]) == 0)
    {
        printf("net [help,enable,connect,disconnect,mdns,scan,ping,lookup]\n");

        printf("%-35s %s\n","net enable","Enable the WiFi Driver &amp; load the WiFi Firmware");

        return 0;
    }

    if(strcmp("enable",argv[1])==0)
    {
            if(argc == 2)
                wifi_cmd_enable("STA");
            else
                wifi_cmd_enable(argv[2]);        
            return 0;
    }

    return 0;
}
</pre>
<h1>Test</h1>
<p>Program and test.  Now the &#8220;net enable&#8221; works.  Notice that it gives you the output about the wifi firmware being loaded into the chip.  Then it tells you that the chip is enabled and the connection manager is rolling.</p>
<p><a href="https://iotexpert.com/?attachment_id=11294" rel="attachment wp-att-11294"><img loading="lazy" decoding="async" src="https://iotexpert.com/wp-content/uploads/2021/06/Screen-Shot-2021-06-15-at-2.22.57-PM-1024x467.png" alt="" width="1024" height="467" class="alignnone size-large wp-image-11294" srcset="https://iotexpert.com/wp-content/uploads/2021/06/Screen-Shot-2021-06-15-at-2.22.57-PM-1024x467.png 1024w, https://iotexpert.com/wp-content/uploads/2021/06/Screen-Shot-2021-06-15-at-2.22.57-PM-300x137.png 300w, https://iotexpert.com/wp-content/uploads/2021/06/Screen-Shot-2021-06-15-at-2.22.57-PM-768x350.png 768w, https://iotexpert.com/wp-content/uploads/2021/06/Screen-Shot-2021-06-15-at-2.22.57-PM-1536x700.png 1536w, https://iotexpert.com/wp-content/uploads/2021/06/Screen-Shot-2021-06-15-at-2.22.57-PM-600x274.png 600w, https://iotexpert.com/wp-content/uploads/2021/06/Screen-Shot-2021-06-15-at-2.22.57-PM.png 1746w" sizes="auto, (max-width: 1024px) 100vw, 1024px" /></a></p>
<p>In the next article I will create a new library of helper functions for wifi.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://iotexpert.com/anycloud-wifi-template-wifi-helper-library-part-2-enable-the-wifi-network/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>AnyCloud WiFi Template + WiFi Helper Library (Part 1): Introduction</title>
		<link>https://iotexpert.com/anycloud-wifi-template-wifi-helper-library-part-1-introduction/</link>
					<comments>https://iotexpert.com/anycloud-wifi-template-wifi-helper-library-part-1-introduction/#comments</comments>
		
		<dc:creator><![CDATA[Alan Hawse]]></dc:creator>
		<pubDate>Mon, 21 Jun 2021 09:40:58 +0000</pubDate>
				<category><![CDATA[AnyCloud]]></category>
		<category><![CDATA[Elkhorn Creek 3.0]]></category>
		<category><![CDATA[WIFI]]></category>
		<guid isPermaLink="false">https://iotexpert.com/?p=11229</guid>

					<description><![CDATA[Summary The first article in a series that discusses building a new IoT project using Modus Toolbox and the AnyCloud SDK.  Specifically: The new-ish Error Logging library AnyCloud Wireless Connection Manager Creation of New Libraries and Template Projects Dual Role WiFi Access Point and Station using CYW43012 MDNS Story I am working on a new [&#8230;]]]></description>
										<content:encoded><![CDATA[<h1>Summary</h1>
<p>The first article in a series that discusses building a new IoT project using Modus Toolbox and the AnyCloud SDK.  Specifically:</p>
<ol>
<li>The new-ish Error Logging library</li>
<li>AnyCloud Wireless Connection Manager</li>
<li>Creation of New Libraries and Template Projects</li>
<li>Dual Role WiFi Access Point and Station using CYW43012</li>
<li>MDNS</li>
</ol>
<h1>Story</h1>
<p>I am working on a new implementation of my Elkhorn Creek IoT monitoring system.  In some of the previous articles I discussed the usage of the Influx Database and Docker as a new cloud backend.  To make this whole thing better I wanted to replace the Raspberry Pi (current system) with a PSoC 6 MCU and a CYW43012 WiFi Chip.  In order to do this, I need to make the PSoC 6 talk to the Influx Database using the WiFi and the Influx DB WebAPI.  I started to build this from my IoT Expert template, but quickly realized that I should make a template project with WiFi.</p>
<p>In this series of article I teach you how to use the Wireless Connection Manager, make new libraries and make new template projects.  Here is the agenda:</p>
<p><span><p><div class="table-responsive"><table  style="width:95%; "  class="easy-table easy-table-default " border="1">
<thead>
<tr><th >Article</th>
</tr>
</thead>
<tbody>
<tr><td >(Part 1) Create Basic Project &amp; Add Cypress Logging Functionality</td>
</tr>

<tr><td >(Part 2) Create New Thread to manage WiFi using the Wireless Connection Manager</td>
</tr>

<tr><td >(Part 3) Create a New Middleware Library with WiFi helper functions</td>
</tr>

<tr><td >(Part 4) Add WiFi Scan</td>
</tr>

<tr><td >Add WiFi Connect</td>
</tr>

<tr><td >Add WiFi Disconnect</td>
</tr>

<tr><td >Add WiFi Ping</td>
</tr>

<tr><td >Add Gethostbyname</td>
</tr>

<tr><td >Add MDNS</td>
</tr>

<tr><td >Add Status</td>
</tr>

<tr><td >Add StartAP</td>
</tr>

<tr><td >Make a new template project (update manifest)</td>
</tr>
</tbody></table></div></p></span></p>
<h1>Create Basic Project</h1>
<p>Today I happen to have a CY8CKIT-062S2-43012 on my desk.</p>
<p><a href="https://iotexpert.com/anycloud-wifi-template-wifi-helper-library-part-1-introduction/img_0829/" rel="attachment wp-att-11327"><img loading="lazy" decoding="async" src="https://iotexpert.com/wp-content/uploads/2021/06/IMG_0829-scaled-e1624096593430-1024x768.jpg" alt="" width="1024" height="768" class="alignnone wp-image-11327 size-large" srcset="https://iotexpert.com/wp-content/uploads/2021/06/IMG_0829-scaled-e1624096593430-1024x768.jpg 1024w, https://iotexpert.com/wp-content/uploads/2021/06/IMG_0829-scaled-e1624096593430-300x225.jpg 300w, https://iotexpert.com/wp-content/uploads/2021/06/IMG_0829-scaled-e1624096593430-768x576.jpg 768w, https://iotexpert.com/wp-content/uploads/2021/06/IMG_0829-scaled-e1624096593430-1536x1152.jpg 1536w, https://iotexpert.com/wp-content/uploads/2021/06/IMG_0829-scaled-e1624096593430-2048x1536.jpg 2048w, https://iotexpert.com/wp-content/uploads/2021/06/IMG_0829-scaled-e1624096593430-600x450.jpg 600w" sizes="auto, (max-width: 1024px) 100vw, 1024px" /></a></p>
<p>So that looks like a good place to start.  Pick that development kit in from the new project creator.</p>
<p><a href="https://iotexpert.com/anycloud-wifi-template-wifi-helper-library-part-1-introduction/screen-shot-2021-06-15-at-9-46-28-am/" rel="attachment wp-att-11264"><img loading="lazy" decoding="async" src="https://iotexpert.com/wp-content/uploads/2021/06/Screen-Shot-2021-06-15-at-9.46.28-AM-1024x710.jpg" alt="" width="1024" height="710" class="alignnone size-large wp-image-11264" srcset="https://iotexpert.com/wp-content/uploads/2021/06/Screen-Shot-2021-06-15-at-9.46.28-AM-1024x710.jpg 1024w, https://iotexpert.com/wp-content/uploads/2021/06/Screen-Shot-2021-06-15-at-9.46.28-AM-300x208.jpg 300w, https://iotexpert.com/wp-content/uploads/2021/06/Screen-Shot-2021-06-15-at-9.46.28-AM-768x532.jpg 768w, https://iotexpert.com/wp-content/uploads/2021/06/Screen-Shot-2021-06-15-at-9.46.28-AM-1536x1064.jpg 1536w, https://iotexpert.com/wp-content/uploads/2021/06/Screen-Shot-2021-06-15-at-9.46.28-AM-2048x1419.jpg 2048w, https://iotexpert.com/wp-content/uploads/2021/06/Screen-Shot-2021-06-15-at-9.46.28-AM-600x416.jpg 600w" sizes="auto, (max-width: 1024px) 100vw, 1024px" /></a></p>
<p>I want to start from my tried and true NT Shell, FreeRTOS Template.  If you use the filter window and type &#8220;iot&#8221; it will filter things down to just the IoT templates.  Notice that I selected that I want to get a &#8220;Microsoft Visual Studio Code&#8221; target workspace.</p>
<p><a href="https://iotexpert.com/anycloud-wifi-template-wifi-helper-library-part-1-introduction/screen-shot-2021-06-15-at-9-49-07-am/" rel="attachment wp-att-11266"><img loading="lazy" decoding="async" src="https://iotexpert.com/wp-content/uploads/2021/06/Screen-Shot-2021-06-15-at-9.49.07-AM-1024x709.jpg" alt="" width="1024" height="709" class="alignnone size-large wp-image-11266" srcset="https://iotexpert.com/wp-content/uploads/2021/06/Screen-Shot-2021-06-15-at-9.49.07-AM-1024x709.jpg 1024w, https://iotexpert.com/wp-content/uploads/2021/06/Screen-Shot-2021-06-15-at-9.49.07-AM-300x208.jpg 300w, https://iotexpert.com/wp-content/uploads/2021/06/Screen-Shot-2021-06-15-at-9.49.07-AM-768x532.jpg 768w, https://iotexpert.com/wp-content/uploads/2021/06/Screen-Shot-2021-06-15-at-9.49.07-AM-1536x1064.jpg 1536w, https://iotexpert.com/wp-content/uploads/2021/06/Screen-Shot-2021-06-15-at-9.49.07-AM-2048x1418.jpg 2048w, https://iotexpert.com/wp-content/uploads/2021/06/Screen-Shot-2021-06-15-at-9.49.07-AM-600x416.jpg 600w" sizes="auto, (max-width: 1024px) 100vw, 1024px" /></a></p>
<p>After clicking create you will get a new project.</p>
<p><a href="https://iotexpert.com/anycloud-wifi-template-wifi-helper-library-part-1-introduction/screen-shot-2021-06-15-at-9-49-42-am/" rel="attachment wp-att-11265"><img loading="lazy" decoding="async" src="https://iotexpert.com/wp-content/uploads/2021/06/Screen-Shot-2021-06-15-at-9.49.42-AM-1024x414.png" alt="" width="1024" height="414" class="alignnone size-large wp-image-11265" srcset="https://iotexpert.com/wp-content/uploads/2021/06/Screen-Shot-2021-06-15-at-9.49.42-AM-1024x414.png 1024w, https://iotexpert.com/wp-content/uploads/2021/06/Screen-Shot-2021-06-15-at-9.49.42-AM-300x121.png 300w, https://iotexpert.com/wp-content/uploads/2021/06/Screen-Shot-2021-06-15-at-9.49.42-AM-768x310.png 768w, https://iotexpert.com/wp-content/uploads/2021/06/Screen-Shot-2021-06-15-at-9.49.42-AM-1536x621.png 1536w, https://iotexpert.com/wp-content/uploads/2021/06/Screen-Shot-2021-06-15-at-9.49.42-AM-2048x827.png 2048w, https://iotexpert.com/wp-content/uploads/2021/06/Screen-Shot-2021-06-15-at-9.49.42-AM-600x242.png 600w" sizes="auto, (max-width: 1024px) 100vw, 1024px" /></a></p>
<p>Something weird happened.  Well actually something bad happened.  When I start Visual Studio Code I get the message that I have multiple workspace files.  Why is that?</p>
<p><a href="https://iotexpert.com/anycloud-wifi-template-wifi-helper-library-part-1-introduction/screen-shot-2021-06-19-at-6-04-57-am/" rel="attachment wp-att-11328"><img loading="lazy" decoding="async" src="https://iotexpert.com/wp-content/uploads/2021/06/Screen-Shot-2021-06-19-at-6.04.57-AM.png" alt="" width="958" height="302" class="alignnone size-full wp-image-11328" srcset="https://iotexpert.com/wp-content/uploads/2021/06/Screen-Shot-2021-06-19-at-6.04.57-AM.png 958w, https://iotexpert.com/wp-content/uploads/2021/06/Screen-Shot-2021-06-19-at-6.04.57-AM-300x95.png 300w, https://iotexpert.com/wp-content/uploads/2021/06/Screen-Shot-2021-06-19-at-6.04.57-AM-768x242.png 768w, https://iotexpert.com/wp-content/uploads/2021/06/Screen-Shot-2021-06-19-at-6.04.57-AM-600x189.png 600w" sizes="auto, (max-width: 958px) 100vw, 958px" /></a></p>
<p>So I pick the first one.</p>
<p><a href="https://iotexpert.com/anycloud-wifi-template-wifi-helper-library-part-1-introduction/screen-shot-2021-06-19-at-6-05-04-am/" rel="attachment wp-att-11329"><img loading="lazy" decoding="async" src="https://iotexpert.com/wp-content/uploads/2021/06/Screen-Shot-2021-06-19-at-6.05.04-AM-1024x201.png" alt="" width="1024" height="201" class="alignnone size-large wp-image-11329" srcset="https://iotexpert.com/wp-content/uploads/2021/06/Screen-Shot-2021-06-19-at-6.05.04-AM-1024x201.png 1024w, https://iotexpert.com/wp-content/uploads/2021/06/Screen-Shot-2021-06-19-at-6.05.04-AM-300x59.png 300w, https://iotexpert.com/wp-content/uploads/2021/06/Screen-Shot-2021-06-19-at-6.05.04-AM-768x151.png 768w, https://iotexpert.com/wp-content/uploads/2021/06/Screen-Shot-2021-06-19-at-6.05.04-AM-600x118.png 600w, https://iotexpert.com/wp-content/uploads/2021/06/Screen-Shot-2021-06-19-at-6.05.04-AM.png 1262w" sizes="auto, (max-width: 1024px) 100vw, 1024px" /></a></p>
<p>Now there is a problem.  In the Makefile for this project I find out that the &#8220;APPNAME&#8221; is MTBShellTemplate</p>
<pre class="EnlighterJSRAW" data-enlighter-language="generic"># Name of application (used to derive name of final linked file).
APPNAME=MTBShellTemplate</pre>
<p>By default when you run &#8220;make vscode&#8221; it will make a workspace file for you with the name &#8220;APPNAME.code-workspace&#8221;.  This has now created a problem for you.  Specifically, i<span style="font-size: 1rem;">f you regenerate the workspace by running &#8220;make vscode&#8221; you will update the WRONG file.  When the new project creator runs the &#8220;make vscode&#8221; it uses the name you entered on that form, not the one in the Makefile.</span></p>
<p>To fix this, edit he Makefile &amp; delete the old MTB&#8230;workspace.  Then re-run make vscode</p>
<pre class="EnlighterJSRAW" data-enlighter-language="generic">APPNAME=IoTExpertWiFiTemplate</pre>
<p>I have been checking in the *.code-workspace file, but that may not be exactly the right thing to do.  I am not sure.  Oh well.  Here is what you screen should look like now that you have Visual Studio Code going.</p>
<p><a href="https://iotexpert.com/anycloud-wifi-template-wifi-helper-library-part-1-introduction/screen-shot-2021-06-15-at-9-52-41-am/" rel="attachment wp-att-11270"><img loading="lazy" decoding="async" src="https://iotexpert.com/wp-content/uploads/2021/06/Screen-Shot-2021-06-15-at-9.52.41-AM-1024x757.jpg" alt="" width="1024" height="757" class="alignnone size-large wp-image-11270" srcset="https://iotexpert.com/wp-content/uploads/2021/06/Screen-Shot-2021-06-15-at-9.52.41-AM-1024x757.jpg 1024w, https://iotexpert.com/wp-content/uploads/2021/06/Screen-Shot-2021-06-15-at-9.52.41-AM-300x222.jpg 300w, https://iotexpert.com/wp-content/uploads/2021/06/Screen-Shot-2021-06-15-at-9.52.41-AM-768x568.jpg 768w, https://iotexpert.com/wp-content/uploads/2021/06/Screen-Shot-2021-06-15-at-9.52.41-AM-1536x1135.jpg 1536w, https://iotexpert.com/wp-content/uploads/2021/06/Screen-Shot-2021-06-15-at-9.52.41-AM-2048x1514.jpg 2048w, https://iotexpert.com/wp-content/uploads/2021/06/Screen-Shot-2021-06-15-at-9.52.41-AM-600x444.jpg 600w" sizes="auto, (max-width: 1024px) 100vw, 1024px" /></a></p>
<p>I always like to test things to make sure everything works before I start editing.  So, press the play button, then the green play button.</p>
<p><a href="https://iotexpert.com/anycloud-wifi-template-wifi-helper-library-part-1-introduction/screen-shot-2021-06-15-at-9-56-50-am/" rel="attachment wp-att-11276"><img loading="lazy" decoding="async" src="https://iotexpert.com/wp-content/uploads/2021/06/Screen-Shot-2021-06-15-at-9.56.50-AM-1024x756.png" alt="" width="1024" height="756" class="alignnone size-large wp-image-11276" srcset="https://iotexpert.com/wp-content/uploads/2021/06/Screen-Shot-2021-06-15-at-9.56.50-AM-1024x756.png 1024w, https://iotexpert.com/wp-content/uploads/2021/06/Screen-Shot-2021-06-15-at-9.56.50-AM-300x222.png 300w, https://iotexpert.com/wp-content/uploads/2021/06/Screen-Shot-2021-06-15-at-9.56.50-AM-768x567.png 768w, https://iotexpert.com/wp-content/uploads/2021/06/Screen-Shot-2021-06-15-at-9.56.50-AM-600x443.png 600w, https://iotexpert.com/wp-content/uploads/2021/06/Screen-Shot-2021-06-15-at-9.56.50-AM.png 1056w" sizes="auto, (max-width: 1024px) 100vw, 1024px" /></a></p>
<p>It should build and program the development kit.</p>
<p><a href="https://iotexpert.com/anycloud-wifi-template-wifi-helper-library-part-1-introduction/screen-shot-2021-06-15-at-9-53-36-am/" rel="attachment wp-att-11272"><img loading="lazy" decoding="async" src="https://iotexpert.com/wp-content/uploads/2021/06/Screen-Shot-2021-06-15-at-9.53.36-AM-1024x573.png" alt="" width="1024" height="573" class="alignnone size-large wp-image-11272" srcset="https://iotexpert.com/wp-content/uploads/2021/06/Screen-Shot-2021-06-15-at-9.53.36-AM-1024x573.png 1024w, https://iotexpert.com/wp-content/uploads/2021/06/Screen-Shot-2021-06-15-at-9.53.36-AM-300x168.png 300w, https://iotexpert.com/wp-content/uploads/2021/06/Screen-Shot-2021-06-15-at-9.53.36-AM-768x429.png 768w, https://iotexpert.com/wp-content/uploads/2021/06/Screen-Shot-2021-06-15-at-9.53.36-AM-1536x859.png 1536w, https://iotexpert.com/wp-content/uploads/2021/06/Screen-Shot-2021-06-15-at-9.53.36-AM-2048x1145.png 2048w, https://iotexpert.com/wp-content/uploads/2021/06/Screen-Shot-2021-06-15-at-9.53.36-AM-600x335.png 600w" sizes="auto, (max-width: 1024px) 100vw, 1024px" /></a></p>
<p>Then stop at main.</p>
<p><a href="https://iotexpert.com/anycloud-wifi-template-wifi-helper-library-part-1-introduction/screen-shot-2021-06-15-at-9-53-20-am/" rel="attachment wp-att-11271"><img loading="lazy" decoding="async" src="https://iotexpert.com/wp-content/uploads/2021/06/Screen-Shot-2021-06-15-at-9.53.20-AM-1024x759.jpg" alt="" width="1024" height="759" class="alignnone size-large wp-image-11271" srcset="https://iotexpert.com/wp-content/uploads/2021/06/Screen-Shot-2021-06-15-at-9.53.20-AM-1024x759.jpg 1024w, https://iotexpert.com/wp-content/uploads/2021/06/Screen-Shot-2021-06-15-at-9.53.20-AM-300x222.jpg 300w, https://iotexpert.com/wp-content/uploads/2021/06/Screen-Shot-2021-06-15-at-9.53.20-AM-768x569.jpg 768w, https://iotexpert.com/wp-content/uploads/2021/06/Screen-Shot-2021-06-15-at-9.53.20-AM-1536x1138.jpg 1536w, https://iotexpert.com/wp-content/uploads/2021/06/Screen-Shot-2021-06-15-at-9.53.20-AM-2048x1518.jpg 2048w, https://iotexpert.com/wp-content/uploads/2021/06/Screen-Shot-2021-06-15-at-9.53.20-AM-600x445.jpg 600w" sizes="auto, (max-width: 1024px) 100vw, 1024px" /></a></p>
<p>Press play and your terminal should look something like this.  Notice that I typed &#8220;help&#8221; and &#8220;tasks&#8221;</p>
<p><a href="https://iotexpert.com/anycloud-wifi-template-wifi-helper-library-part-1-introduction/screen-shot-2021-06-15-at-9-54-09-am/" rel="attachment wp-att-11274"><img loading="lazy" decoding="async" src="https://iotexpert.com/wp-content/uploads/2021/06/Screen-Shot-2021-06-15-at-9.54.09-AM-1024x807.png" alt="" width="1024" height="807" class="alignnone size-large wp-image-11274" srcset="https://iotexpert.com/wp-content/uploads/2021/06/Screen-Shot-2021-06-15-at-9.54.09-AM-1024x807.png 1024w, https://iotexpert.com/wp-content/uploads/2021/06/Screen-Shot-2021-06-15-at-9.54.09-AM-300x237.png 300w, https://iotexpert.com/wp-content/uploads/2021/06/Screen-Shot-2021-06-15-at-9.54.09-AM-768x606.png 768w, https://iotexpert.com/wp-content/uploads/2021/06/Screen-Shot-2021-06-15-at-9.54.09-AM-1536x1211.png 1536w, https://iotexpert.com/wp-content/uploads/2021/06/Screen-Shot-2021-06-15-at-9.54.09-AM-600x473.png 600w, https://iotexpert.com/wp-content/uploads/2021/06/Screen-Shot-2021-06-15-at-9.54.09-AM.png 1872w" sizes="auto, (max-width: 1024px) 100vw, 1024px" /></a></p>
<h1>Add the Cypress Logging Functionality</h1>
<p>Sometime recently the Software team added a logging capability.  This seems like a good time to try that that.  Start the library browser by running &#8220;make modlibs&#8221;.  Then enable the &#8220;connectivity-utilities&#8221;.  For some silly reason that is where the logging functions were added.</p>
<p><a href="https://iotexpert.com/anycloud-wifi-template-wifi-helper-library-part-1-introduction/screen-shot-2021-06-15-at-10-06-50-am/" rel="attachment wp-att-11277"><img loading="lazy" decoding="async" src="https://iotexpert.com/wp-content/uploads/2021/06/Screen-Shot-2021-06-15-at-10.06.50-AM-1024x884.jpg" alt="" width="1024" height="884" class="alignnone size-large wp-image-11277" srcset="https://iotexpert.com/wp-content/uploads/2021/06/Screen-Shot-2021-06-15-at-10.06.50-AM-1024x884.jpg 1024w, https://iotexpert.com/wp-content/uploads/2021/06/Screen-Shot-2021-06-15-at-10.06.50-AM-300x259.jpg 300w, https://iotexpert.com/wp-content/uploads/2021/06/Screen-Shot-2021-06-15-at-10.06.50-AM-768x663.jpg 768w, https://iotexpert.com/wp-content/uploads/2021/06/Screen-Shot-2021-06-15-at-10.06.50-AM-1536x1325.jpg 1536w, https://iotexpert.com/wp-content/uploads/2021/06/Screen-Shot-2021-06-15-at-10.06.50-AM-2048x1767.jpg 2048w, https://iotexpert.com/wp-content/uploads/2021/06/Screen-Shot-2021-06-15-at-10.06.50-AM-600x518.jpg 600w" sizes="auto, (max-width: 1024px) 100vw, 1024px" /></a></p>
<p>If you look in the &#8220;mtb_shared&#8221; you will now the cy_log directory.</p>
<p><a href="https://iotexpert.com/anycloud-wifi-template-wifi-helper-library-part-1-introduction/screen-shot-2021-06-15-at-10-08-39-am/" rel="attachment wp-att-11278"><img loading="lazy" decoding="async" src="https://iotexpert.com/wp-content/uploads/2021/06/Screen-Shot-2021-06-15-at-10.08.39-AM-537x1024.png" alt="" width="537" height="1024" class="alignnone size-large wp-image-11278" srcset="https://iotexpert.com/wp-content/uploads/2021/06/Screen-Shot-2021-06-15-at-10.08.39-AM-537x1024.png 537w, https://iotexpert.com/wp-content/uploads/2021/06/Screen-Shot-2021-06-15-at-10.08.39-AM-157x300.png 157w, https://iotexpert.com/wp-content/uploads/2021/06/Screen-Shot-2021-06-15-at-10.08.39-AM-768x1464.png 768w, https://iotexpert.com/wp-content/uploads/2021/06/Screen-Shot-2021-06-15-at-10.08.39-AM-806x1536.png 806w, https://iotexpert.com/wp-content/uploads/2021/06/Screen-Shot-2021-06-15-at-10.08.39-AM-600x1144.png 600w, https://iotexpert.com/wp-content/uploads/2021/06/Screen-Shot-2021-06-15-at-10.08.39-AM.png 956w" sizes="auto, (max-width: 537px) 100vw, 537px" /></a></p>
<p>Then click on the &#8220;api_reference.html&#8221;</p>
<p><a href="https://iotexpert.com/anycloud-wifi-template-wifi-helper-library-part-1-introduction/screen-shot-2021-06-15-at-10-09-08-am/" rel="attachment wp-att-11279"><img loading="lazy" decoding="async" src="https://iotexpert.com/wp-content/uploads/2021/06/Screen-Shot-2021-06-15-at-10.09.08-AM.png" alt="" width="922" height="1010" class="alignnone size-full wp-image-11279" srcset="https://iotexpert.com/wp-content/uploads/2021/06/Screen-Shot-2021-06-15-at-10.09.08-AM.png 922w, https://iotexpert.com/wp-content/uploads/2021/06/Screen-Shot-2021-06-15-at-10.09.08-AM-274x300.png 274w, https://iotexpert.com/wp-content/uploads/2021/06/Screen-Shot-2021-06-15-at-10.09.08-AM-768x841.png 768w, https://iotexpert.com/wp-content/uploads/2021/06/Screen-Shot-2021-06-15-at-10.09.08-AM-600x657.png 600w" sizes="auto, (max-width: 922px) 100vw, 922px" /></a></p>
<p>And open it.</p>
<p><a href="https://iotexpert.com/anycloud-wifi-template-wifi-helper-library-part-1-introduction/screen-shot-2021-06-15-at-10-10-11-am/" rel="attachment wp-att-11281"><img loading="lazy" decoding="async" src="https://iotexpert.com/wp-content/uploads/2021/06/Screen-Shot-2021-06-15-at-10.10.11-AM-1024x516.png" alt="" width="1024" height="516" class="alignnone size-large wp-image-11281" srcset="https://iotexpert.com/wp-content/uploads/2021/06/Screen-Shot-2021-06-15-at-10.10.11-AM-1024x516.png 1024w, https://iotexpert.com/wp-content/uploads/2021/06/Screen-Shot-2021-06-15-at-10.10.11-AM-300x151.png 300w, https://iotexpert.com/wp-content/uploads/2021/06/Screen-Shot-2021-06-15-at-10.10.11-AM-768x387.png 768w, https://iotexpert.com/wp-content/uploads/2021/06/Screen-Shot-2021-06-15-at-10.10.11-AM-1536x775.png 1536w, https://iotexpert.com/wp-content/uploads/2021/06/Screen-Shot-2021-06-15-at-10.10.11-AM-600x303.png 600w, https://iotexpert.com/wp-content/uploads/2021/06/Screen-Shot-2021-06-15-at-10.10.11-AM.png 1832w" sizes="auto, (max-width: 1024px) 100vw, 1024px" /></a></p>
<p>Cool.  This gives you some insight into the capability.</p>
<p><a href="https://iotexpert.com/anycloud-wifi-template-wifi-helper-library-part-1-introduction/screen-shot-2021-06-15-at-10-09-38-am/" rel="attachment wp-att-11280"><img loading="lazy" decoding="async" src="https://iotexpert.com/wp-content/uploads/2021/06/Screen-Shot-2021-06-15-at-10.09.38-AM-1024x600.jpg" alt="" width="1024" height="600" class="alignnone size-large wp-image-11280" srcset="https://iotexpert.com/wp-content/uploads/2021/06/Screen-Shot-2021-06-15-at-10.09.38-AM-1024x600.jpg 1024w, https://iotexpert.com/wp-content/uploads/2021/06/Screen-Shot-2021-06-15-at-10.09.38-AM-300x176.jpg 300w, https://iotexpert.com/wp-content/uploads/2021/06/Screen-Shot-2021-06-15-at-10.09.38-AM-768x450.jpg 768w, https://iotexpert.com/wp-content/uploads/2021/06/Screen-Shot-2021-06-15-at-10.09.38-AM-1536x900.jpg 1536w, https://iotexpert.com/wp-content/uploads/2021/06/Screen-Shot-2021-06-15-at-10.09.38-AM-2048x1201.jpg 2048w, https://iotexpert.com/wp-content/uploads/2021/06/Screen-Shot-2021-06-15-at-10.09.38-AM-600x352.jpg 600w" sizes="auto, (max-width: 1024px) 100vw, 1024px" /></a></p>
<p>A simple test will be to printout a &#8220;blink&#8221; message in sync with the default blinking led.  To do this, I modify the blink_task in main.c  Take the following actions</p>
<ol>
<li>Add the include &#8220;cy_log.h&#8221;</li>
<li>Add the initialization call &#8220;cy_log_init&#8221;</li>
<li>Printout a test message using &#8220;cy_log_msg&#8221;</li>
<li>Fix the stack</li>
</ol>
<pre class="EnlighterJSRAW" data-enlighter-language="generic">#include "cyhal.h"
#include "cybsp.h"
#include "cy_retarget_io.h"
#include &lt;stdio.h&gt;
#include "FreeRTOS.h"
#include "task.h"
#include "usrcmd.h"
#include "cy_log.h"

volatile int uxTopUsedPriority ;
TaskHandle_t blinkTaskHandle;


void blink_task(void *arg)
{
    cyhal_gpio_init(CYBSP_USER_LED,CYHAL_GPIO_DIR_OUTPUT,CYHAL_GPIO_DRIVE_STRONG,0);

    for(;;)
    {
        cy_log_msg(CYLF_DEF,CY_LOG_INFO,"Blink Info\n");
    	cyhal_gpio_toggle(CYBSP_USER_LED);
    	vTaskDelay(500);
    }
}


int main(void)
{
    uxTopUsedPriority = configMAX_PRIORITIES - 1 ; // enable OpenOCD Thread Debugging

    /* Initialize the device and board peripherals */
    cybsp_init() ;
    __enable_irq();

    cy_retarget_io_init(CYBSP_DEBUG_UART_TX, CYBSP_DEBUG_UART_RX, CY_RETARGET_IO_BAUDRATE);

    cy_log_init(CY_LOG_INFO,0,0);


    // Stack size in WORDs
    // Idle task = priority 0
    xTaskCreate(blink_task, "blinkTask", configMINIMAL_STACK_SIZE*2,0 /* args */ ,0 /* priority */, &amp;blinkTaskHandle);
    xTaskCreate(usrcmd_task, "usrcmd_task", configMINIMAL_STACK_SIZE*4,0 /* args */ ,0 /* priority */, 0);
    vTaskStartScheduler();
}</pre>
<p>When you run this, you will get the message repeatedly coming on the screen (probably gonna-want-a delete this before you go on)</p>
<p><a href="https://iotexpert.com/anycloud-wifi-template-wifi-helper-library-part-1-introduction/screen-shot-2021-06-15-at-10-27-18-am/" rel="attachment wp-att-11282"><img loading="lazy" decoding="async" src="https://iotexpert.com/wp-content/uploads/2021/06/Screen-Shot-2021-06-15-at-10.27.18-AM-1024x799.png" alt="" width="1024" height="799" class="alignnone size-large wp-image-11282" srcset="https://iotexpert.com/wp-content/uploads/2021/06/Screen-Shot-2021-06-15-at-10.27.18-AM-1024x799.png 1024w, https://iotexpert.com/wp-content/uploads/2021/06/Screen-Shot-2021-06-15-at-10.27.18-AM-300x234.png 300w, https://iotexpert.com/wp-content/uploads/2021/06/Screen-Shot-2021-06-15-at-10.27.18-AM-768x599.png 768w, https://iotexpert.com/wp-content/uploads/2021/06/Screen-Shot-2021-06-15-at-10.27.18-AM-1536x1199.png 1536w, https://iotexpert.com/wp-content/uploads/2021/06/Screen-Shot-2021-06-15-at-10.27.18-AM-600x468.png 600w, https://iotexpert.com/wp-content/uploads/2021/06/Screen-Shot-2021-06-15-at-10.27.18-AM.png 1886w" sizes="auto, (max-width: 1024px) 100vw, 1024px" /></a></p>
<p>Now that we have a working project with logging, in the next article Ill add WiFi</p>
]]></content:encoded>
					
					<wfw:commentRss>https://iotexpert.com/anycloud-wifi-template-wifi-helper-library-part-1-introduction/feed/</wfw:commentRss>
			<slash:comments>1</slash:comments>
		
		
			</item>
		<item>
		<title>AnyCloud Bluetooth Advertising Scanner (Part 10)</title>
		<link>https://iotexpert.com/anycloud-bluetooth-advertising-scanner-part-10/</link>
					<comments>https://iotexpert.com/anycloud-bluetooth-advertising-scanner-part-10/#respond</comments>
		
		<dc:creator><![CDATA[Alan Hawse]]></dc:creator>
		<pubDate>Mon, 28 Dec 2020 13:00:47 +0000</pubDate>
				<category><![CDATA[4343W]]></category>
		<category><![CDATA[AnyCloud]]></category>
		<category><![CDATA[AnyCloud Advertising Scanner]]></category>
		<category><![CDATA[Bluetooth]]></category>
		<category><![CDATA[CY8CKIT-062-WiFi-BT]]></category>
		<category><![CDATA[CY8CKIT-062S2-43012]]></category>
		<category><![CDATA[CY8CPROTO-062-4343W]]></category>
		<category><![CDATA[ModusToolbox]]></category>
		<guid isPermaLink="false">https://iotexpert.com/?p=10250</guid>

					<description><![CDATA[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 [&#8230;]]]></description>
										<content:encoded><![CDATA[<h1>Summary</h1>
<p>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.</p>
<h1>Story</h1>
<p>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&#8230; and it would be nice to purge out old entries.  So that is what we are going to do.</p>
<p>There are</p>
<p><div class="table-responsive"><table  style="width:95%; "  class="easy-table easy-table-default " border="1">
<thead>
<tr><th >Article</th>
<th >Topic</th>
</tr>
</thead>
<tbody>
<tr><td ><a href="https://iotexpert.com/anycloud-bluetooth-advertising-scanner-part-1/" target="_blank" rel="noopener">AnyCloud Bluetooth Advertising Scanner (Part 1)</a></td>
<td >Introduction to AnyCloud Bluetooth Advertising</td>
</tr>

<tr><td ><a href="https://iotexpert.com/anycloud-bluetooth-advertising-scanner-part-2/" target="_blank" rel="noopener">AnyCloud Bluetooth Advertising Scanner (Part 2)</a></td>
<td >Creating an AnyCloud Bluetooth project</td>
</tr>

<tr><td ><a href="https://iotexpert.com/anycloud-bluetooth-advertising-scanner-part-3/" target="_blank" rel="noopener">AnyCloud Bluetooth Advertising Scanner (Part 3)</a></td>
<td >Adding Observing functionality to the project</td>
</tr>

<tr><td ><a class="row-title" href="https://iotexpert.com/anycloud-bluetooth-utilities-library/" aria-label="“AnyCloud Bluetooth Utilities Library” (Edit)" target="_blank" rel="noopener">AnyCloud Bluetooth Utilities Library</a></td>
<td >A set of APIs for enhancement of the AnyCloud Library</td>
</tr>

<tr><td ><a href="https://iotexpert.com/anycloud-bluetooth-advertising-scanner-part-4/" target="_blank" rel="noopener">AnyCloud Bluetooth Advertising Scanner (Part 4)</a></td>
<td >Adding a command line to the scanner</td>
</tr>

<tr><td ><a href="https://iotexpert.com/anycloud-bluetooth-advertising-scanner-part-5/" target="_blank" rel="noopener">AnyCloud Bluetooth Advertising Scanner (Part 5)</a></td>
<td >Adding a history database to the scanner</td>
</tr>

<tr><td ><a href="https://iotexpert.com/anycloud-bluetooth-advertising-scanner-part-6/" target="_blank" rel="noopener">AnyCloud Bluetooth Advertising Scanner (Part 6)</a></td>
<td >Decoding advertising packets</td>
</tr>

<tr><td ><a href="https://iotexpert.com/anycloud-bluetooth-advertising-scanner-part-7/" target="_blank" rel="noopener">AnyCloud Bluetooth Advertising Scanner (Part 7)</a></td>
<td >Adding recording commands to the command line</td>
</tr>

<tr><td ><a href="https://iotexpert.com/anycloud-bluetooth-advertising-scanner-part-8/">AnyCloud Bluetooth Advertising Scanner (Part 8)</a></td>
<td >Adding filtering to the scanner</td>
</tr>

<tr><td ><a href="https://iotexpert.com/anycloud-bluetooth-advertising-scanner-part-9/">AnyCloud Bluetooth Advertising Scanner (Part 9)</a></td>
<td >Improve the print and add packet age</td>
</tr>

<tr><td ><a href="https://iotexpert.com/anycloud-bluetooth-advertising-scanner-part-10/">AnyCloud Bluetooth Advertising Scanner (Part 10)</a></td>
<td >Sort the database</td>
</tr>
</tbody></table></div></p>
<p>All of the code can be found at git@github.com:iotexpert/AnyCloudBLEScanner.git and https://github.com/iotexpert/AnyCloudBLEScanner.git</p>
<p>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.</p>
<p>You can also create a new project with this is a template if you have the IoT Expert Manifest Files installed</p>
<h1>Fix the Database Data Structure</h1>
<p>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.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="c">static adb_adv_t adb_database[ADB_MAX_SIZE];</pre>
<p>To fix this problem I moved the database to a an array of pointers.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="c">static adb_adv_t *adb_database[ADB_MAX_SIZE];</pre>
<p>To support this, when I see a new device I malloc a block of memory to hold the actual structure.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="c">    // If it is NOT found &amp;&amp; you have room
    if(entry == -1)
    {
        adb_database[adb_db_count] = malloc(sizeof(adb_adv_t));</pre>
<p>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</p>
<p>adb_database[&#8230;].xxx is replaced by adb_database[&#8230;]-&gt; &#8230;. here are the three different cases</p>
<p>case 1: adb_database[adb_db_count].</p>
<p><a href="https://iotexpert.com/anycloud-bluetooth-advertising-scanner-part-10/screen-shot-2020-11-16-at-7-40-36-am/" rel="attachment wp-att-10254"><img loading="lazy" decoding="async" src="https://iotexpert.com/wp-content/uploads/2020/11/Screen-Shot-2020-11-16-at-7.40.36-AM.png" alt="" class="alignnone size-full wp-image-10254" width="834" height="126" srcset="https://iotexpert.com/wp-content/uploads/2020/11/Screen-Shot-2020-11-16-at-7.40.36-AM.png 834w, https://iotexpert.com/wp-content/uploads/2020/11/Screen-Shot-2020-11-16-at-7.40.36-AM-300x45.png 300w, https://iotexpert.com/wp-content/uploads/2020/11/Screen-Shot-2020-11-16-at-7.40.36-AM-768x116.png 768w, https://iotexpert.com/wp-content/uploads/2020/11/Screen-Shot-2020-11-16-at-7.40.36-AM-600x91.png 600w" sizes="auto, (max-width: 834px) 100vw, 834px" /></a></p>
<p>case 2: adb_database[entry].</p>
<p><a href="https://iotexpert.com/anycloud-bluetooth-advertising-scanner-part-10/screen-shot-2020-11-16-at-7-32-54-am/" rel="attachment wp-att-10251"><img loading="lazy" decoding="async" src="https://iotexpert.com/wp-content/uploads/2020/11/Screen-Shot-2020-11-16-at-7.32.54-AM.png" alt="" class="alignnone size-full wp-image-10251" width="842" height="132" srcset="https://iotexpert.com/wp-content/uploads/2020/11/Screen-Shot-2020-11-16-at-7.32.54-AM.png 842w, https://iotexpert.com/wp-content/uploads/2020/11/Screen-Shot-2020-11-16-at-7.32.54-AM-300x47.png 300w, https://iotexpert.com/wp-content/uploads/2020/11/Screen-Shot-2020-11-16-at-7.32.54-AM-768x120.png 768w, https://iotexpert.com/wp-content/uploads/2020/11/Screen-Shot-2020-11-16-at-7.32.54-AM-600x94.png 600w" sizes="auto, (max-width: 842px) 100vw, 842px" /></a></p>
<p>case 1: adb_database[i].</p>
<p><a href="https://iotexpert.com/anycloud-bluetooth-advertising-scanner-part-10/screen-shot-2020-11-16-at-7-33-23-am/" rel="attachment wp-att-10252"><img loading="lazy" decoding="async" src="https://iotexpert.com/wp-content/uploads/2020/11/Screen-Shot-2020-11-16-at-7.33.23-AM.png" alt="" class="alignnone size-full wp-image-10252" width="838" height="132" srcset="https://iotexpert.com/wp-content/uploads/2020/11/Screen-Shot-2020-11-16-at-7.33.23-AM.png 838w, https://iotexpert.com/wp-content/uploads/2020/11/Screen-Shot-2020-11-16-at-7.33.23-AM-300x47.png 300w, https://iotexpert.com/wp-content/uploads/2020/11/Screen-Shot-2020-11-16-at-7.33.23-AM-768x121.png 768w, https://iotexpert.com/wp-content/uploads/2020/11/Screen-Shot-2020-11-16-at-7.33.23-AM-600x95.png 600w" sizes="auto, (max-width: 838px) 100vw, 838px" /></a></p>
<p>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.</p>
<h1>Add Two New Commands</h1>
<p>Now I add the sort and purge commands to my command list.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="c">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;
</pre>
<h1>Create the Sort Functionality</h1>
<p>To sort, I will use the c-standard library function qsort.  It requires a function that compares two entries a/b and returns</p>
<ol>
<li>a negative number of a&lt;b</li>
<li>0 if a=b</li>
<li>a positive number if a&gt;b</li>
</ol>
<p>Here is the function.  Hey Hassane you like those pointers?</p>
<pre class="EnlighterJSRAW" data-enlighter-language="c">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-&gt;lastSeen - p1-&gt;lastSeen;
}</pre>
<p>The sort is actually really simple now.  Just a call to sort (then I decided to print out the table)</p>
<pre class="EnlighterJSRAW" data-enlighter-language="c">                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;</pre>
<p>Now instead of this&#8230;.</p>
<p><a href="https://iotexpert.com/anycloud-bluetooth-advertising-scanner-part-10/screen-shot-2020-11-16-at-4-35-26-pm/" rel="attachment wp-att-10256"><img loading="lazy" decoding="async" src="https://iotexpert.com/wp-content/uploads/2020/11/Screen-Shot-2020-11-16-at-4.35.26-PM-1024x678.png" alt="" class="alignnone size-large wp-image-10256" width="1024" height="678" srcset="https://iotexpert.com/wp-content/uploads/2020/11/Screen-Shot-2020-11-16-at-4.35.26-PM-1024x678.png 1024w, https://iotexpert.com/wp-content/uploads/2020/11/Screen-Shot-2020-11-16-at-4.35.26-PM-300x199.png 300w, https://iotexpert.com/wp-content/uploads/2020/11/Screen-Shot-2020-11-16-at-4.35.26-PM-768x508.png 768w, https://iotexpert.com/wp-content/uploads/2020/11/Screen-Shot-2020-11-16-at-4.35.26-PM-1536x1017.png 1536w, https://iotexpert.com/wp-content/uploads/2020/11/Screen-Shot-2020-11-16-at-4.35.26-PM-600x397.png 600w, https://iotexpert.com/wp-content/uploads/2020/11/Screen-Shot-2020-11-16-at-4.35.26-PM.png 1970w" sizes="auto, (max-width: 1024px) 100vw, 1024px" /></a></p>
<p>I get this&#8230;</p>
<p><a href="https://iotexpert.com/anycloud-bluetooth-advertising-scanner-part-10/screen-shot-2020-11-16-at-4-35-37-pm/" rel="attachment wp-att-10257"><img loading="lazy" decoding="async" src="https://iotexpert.com/wp-content/uploads/2020/11/Screen-Shot-2020-11-16-at-4.35.37-PM-1024x660.png" alt="" class="alignnone size-large wp-image-10257" width="1024" height="660" srcset="https://iotexpert.com/wp-content/uploads/2020/11/Screen-Shot-2020-11-16-at-4.35.37-PM-1024x660.png 1024w, https://iotexpert.com/wp-content/uploads/2020/11/Screen-Shot-2020-11-16-at-4.35.37-PM-300x193.png 300w, https://iotexpert.com/wp-content/uploads/2020/11/Screen-Shot-2020-11-16-at-4.35.37-PM-768x495.png 768w, https://iotexpert.com/wp-content/uploads/2020/11/Screen-Shot-2020-11-16-at-4.35.37-PM-1536x990.png 1536w, https://iotexpert.com/wp-content/uploads/2020/11/Screen-Shot-2020-11-16-at-4.35.37-PM-600x387.png 600w, https://iotexpert.com/wp-content/uploads/2020/11/Screen-Shot-2020-11-16-at-4.35.37-PM.png 2042w" sizes="auto, (max-width: 1024px) 100vw, 1024px" /></a></p>
<h1>Create the Purge Functionality</h1>
<p>The purge function needs to do two things</p>
<ol>
<li>Free all of the memory from an entry</li>
<li>Move the pointers so that the &#8220;purged&#8221; entry is gone.</li>
</ol>
<p>First I erase all of the data in the linked list with the adb_eraseEntry function.</p>
<p>Then I free the head of the list</p>
<p>Then I free the actual structure</p>
<p>Then I move all of the pointers to squeeze the able.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="c">static void adb_purgeEntry(int entry)
{

    adb_eraseEntry(entry);
    free(adb_database[entry]-&gt;list);
    free(adb_database[entry]-&gt;result);
    free(adb_database[entry]);
    adb_db_count -= 1;
    for(int i=entry;i&lt;adb_db_count;i++)
    {
        adb_database[i] = adb_database[i+1];
    }
}
</pre>
<p>And you need to add the actual command.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="c">                case ADB_PURGE:
                    if((int)msg.data0&lt;0 || (int)msg.data0&gt;=adb_db_count)
                    {
                        printf("Purge error %d\n",(int)msg.data0);
                        break;
                    }   
                    adb_purgeEntry((int)msg.data0);
                break;</pre>
<h1>The End &amp; Commentary</h1>
<p>I would like to add and maybe will one day:</p>
<ol>
<li>A connect function with a GATT browser</li>
<li>A smarter way to deal with the fact that device change addresses</li>
</ol>
<p>Finally a couple of comments about this</p>
<ol>
<li>You might notice that I don&#8217;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 &#8220;teaching&#8221; 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.</li>
<li>I don&#8217;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.</li>
<li>I don&#8217;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.</li>
<li>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.</li>
</ol>
]]></content:encoded>
					
					<wfw:commentRss>https://iotexpert.com/anycloud-bluetooth-advertising-scanner-part-10/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>AnyCloud Bluetooth Advertising Scanner (Part 9)</title>
		<link>https://iotexpert.com/anycloud-bluetooth-advertising-scanner-part-9/</link>
					<comments>https://iotexpert.com/anycloud-bluetooth-advertising-scanner-part-9/#respond</comments>
		
		<dc:creator><![CDATA[Alan Hawse]]></dc:creator>
		<pubDate>Mon, 21 Dec 2020 13:00:28 +0000</pubDate>
				<category><![CDATA[AnyCloud]]></category>
		<category><![CDATA[AnyCloud Advertising Scanner]]></category>
		<category><![CDATA[Bluetooth]]></category>
		<category><![CDATA[CY8CKIT-062-WiFi-BT]]></category>
		<category><![CDATA[CY8CKIT-062S2-43012]]></category>
		<category><![CDATA[CY8CPROTO-062-4343W]]></category>
		<guid isPermaLink="false">https://iotexpert.com/?p=10239</guid>

					<description><![CDATA[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 [&#8230;]]]></description>
										<content:encoded><![CDATA[<h1>Summary</h1>
<p>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.</p>
<h1>Story</h1>
<p>You might be starting to wonder if this series is ever going to end.  Well, this article and one more.  That is it.</p>
<p>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 &#8230; the long dark road.  That needs fixing.</p>
<p>I also was curious when I looked at the output, how long ago I had seen the packets/devices.  So I decided that having &#8220;age&#8221; in the database made sense.</p>
<p>There are</p>
<p><div class="table-responsive"><table  style="width:95%; "  class="easy-table easy-table-default " border="1">
<thead>
<tr><th >Article</th>
<th >Topic</th>
</tr>
</thead>
<tbody>
<tr><td ><a href="https://iotexpert.com/anycloud-bluetooth-advertising-scanner-part-1/" target="_blank" rel="noopener">AnyCloud Bluetooth Advertising Scanner (Part 1)</a></td>
<td >Introduction to AnyCloud Bluetooth Advertising</td>
</tr>

<tr><td ><a href="https://iotexpert.com/anycloud-bluetooth-advertising-scanner-part-2/" target="_blank" rel="noopener">AnyCloud Bluetooth Advertising Scanner (Part 2)</a></td>
<td >Creating an AnyCloud Bluetooth project</td>
</tr>

<tr><td ><a href="https://iotexpert.com/anycloud-bluetooth-advertising-scanner-part-3/" target="_blank" rel="noopener">AnyCloud Bluetooth Advertising Scanner (Part 3)</a></td>
<td >Adding Observing functionality to the project</td>
</tr>

<tr><td ><a class="row-title" href="https://iotexpert.com/anycloud-bluetooth-utilities-library/" aria-label="“AnyCloud Bluetooth Utilities Library” (Edit)" target="_blank" rel="noopener">AnyCloud Bluetooth Utilities Library</a></td>
<td >A set of APIs for enhancement of the AnyCloud Library</td>
</tr>

<tr><td ><a href="https://iotexpert.com/anycloud-bluetooth-advertising-scanner-part-4/" target="_blank" rel="noopener">AnyCloud Bluetooth Advertising Scanner (Part 4)</a></td>
<td >Adding a command line to the scanner</td>
</tr>

<tr><td ><a href="https://iotexpert.com/anycloud-bluetooth-advertising-scanner-part-5/" target="_blank" rel="noopener">AnyCloud Bluetooth Advertising Scanner (Part 5)</a></td>
<td >Adding a history database to the scanner</td>
</tr>

<tr><td ><a href="https://iotexpert.com/anycloud-bluetooth-advertising-scanner-part-6/" target="_blank" rel="noopener">AnyCloud Bluetooth Advertising Scanner (Part 6)</a></td>
<td >Decoding advertising packets</td>
</tr>

<tr><td ><a href="https://iotexpert.com/anycloud-bluetooth-advertising-scanner-part-7/" target="_blank" rel="noopener">AnyCloud Bluetooth Advertising Scanner (Part 7)</a></td>
<td >Adding recording commands to the command line</td>
</tr>

<tr><td ><a href="https://iotexpert.com/anycloud-bluetooth-advertising-scanner-part-8/">AnyCloud Bluetooth Advertising Scanner (Part 8)</a></td>
<td >Adding filtering to the scanner</td>
</tr>

<tr><td ><a href="https://iotexpert.com/anycloud-bluetooth-advertising-scanner-part-9/">AnyCloud Bluetooth Advertising Scanner (Part 9)</a></td>
<td >Improve the print and add packet age</td>
</tr>

<tr><td ><a href="https://iotexpert.com/anycloud-bluetooth-advertising-scanner-part-10/">AnyCloud Bluetooth Advertising Scanner (Part 10)</a></td>
<td >Sort the database</td>
</tr>
</tbody></table></div></p>
<p>All of the code can be found at git@github.com:iotexpert/AnyCloudBLEScanner.git and https://github.com/iotexpert/AnyCloudBLEScanner.git</p>
<p>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.</p>
<p>You can also create a new project with this is a template if you have the IoT Expert Manifest Files installed</p>
<h1>Fix the Memory Leak</h1>
<p>I noticed that a while after I started getting the message &#8220;ADV Table Max Size&#8221; that things would crash.  But Why?  The answer is a memory leak &#8211; 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:</p>
<pre class="EnlighterJSRAW" data-enlighter-language="c">    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-&gt;next = 0;
        current-&gt;data = data;
        current-&gt;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);
        }
    }</pre>
<p>A cheap fix is to just stop making new entries when the database runs out of room.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="c">    // If there is a new entry and you ran out of space
    if(entry == -1 &amp;&amp; adb_db_count &gt;= ADB_MAX_SIZE)
    {
        free(scan_result);
        free(data);
        return;
    }</pre>
<h1>Add Age</h1>
<p>As I mentioned earlier I wanted to keep track of</p>
<ol>
<li>The last time I had seen a device</li>
<li>When I saw that specific advertising packet</li>
</ol>
<p>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.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="c">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 ;</pre>
<h1>Update the Printing</h1>
<p>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&#8230;  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.</p>
<p><a href="https://iotexpert.com/anycloud-bluetooth-advertising-scanner-part-9/screen-shot-2020-11-15-at-12-28-23-pm/" rel="attachment wp-att-10244"><img loading="lazy" decoding="async" src="https://iotexpert.com/wp-content/uploads/2020/11/Screen-Shot-2020-11-15-at-12.28.23-PM-1024x326.png" alt="" class="alignnone size-large wp-image-10244" width="1024" height="326" srcset="https://iotexpert.com/wp-content/uploads/2020/11/Screen-Shot-2020-11-15-at-12.28.23-PM-1024x326.png 1024w, https://iotexpert.com/wp-content/uploads/2020/11/Screen-Shot-2020-11-15-at-12.28.23-PM-300x95.png 300w, https://iotexpert.com/wp-content/uploads/2020/11/Screen-Shot-2020-11-15-at-12.28.23-PM-768x244.png 768w, https://iotexpert.com/wp-content/uploads/2020/11/Screen-Shot-2020-11-15-at-12.28.23-PM-1536x488.png 1536w, https://iotexpert.com/wp-content/uploads/2020/11/Screen-Shot-2020-11-15-at-12.28.23-PM-600x191.png 600w, https://iotexpert.com/wp-content/uploads/2020/11/Screen-Shot-2020-11-15-at-12.28.23-PM.png 1988w" sizes="auto, (max-width: 1024px) 100vw, 1024px" /></a></p>
<p>To do this I just add a time calculation like this:</p>
<pre class="EnlighterJSRAW" data-enlighter-language="c">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-&gt;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);
</pre>
<h1>Fix up the Add</h1>
<p>The next thing that I need to do is make the &#8220;add&#8221; 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</p>
<ol>
<li>Ignore the packet (because the table is full)</li>
<li>Add a new device &amp; packet</li>
<li>Update the head of the list with a new packet</li>
<li>Insert a new packet at the head of the list</li>
<li>If you are filtering update a duplicated packet count</li>
</ol>
<p>The code for these branches all looked somewhat similar.  But, which branch to take depended on</p>
<ol>
<li>If you were &#8220;watching&#8221; that device</li>
<li>If you were &#8220;filtering&#8221; that device</li>
<li>If you were &#8220;recording&#8221;</li>
<li>If you had seen that packet before (aka it was found)</li>
</ol>
<p>I ended up making a truth table:</p>
<table width="496" cellspacing="0" cellpadding="0" border="0">
<colgroup>
<col width="87" span="4" />
<col width="148" /></colgroup>
<tbody>
<tr height="21">
<td style="text-align: center;" width="87" height="21"><strong>Watch</strong></td>
<td style="text-align: center;" width="87"><strong>Filter</strong></td>
<td style="text-align: center;" width="87"><strong>Recording</strong></td>
<td style="text-align: center;" width="87"><strong>Found</strong></td>
<td style="text-align: center;" width="148"><strong>Action</strong></td>
</tr>
<tr height="21">
<td style="text-align: center;" height="21" align="right">0</td>
<td style="text-align: center;" align="right">0</td>
<td style="text-align: center;" align="right">0</td>
<td style="text-align: center;" align="right">0</td>
<td style="text-align: center;">update the head</td>
</tr>
<tr height="21">
<td style="text-align: center;" height="21" align="right">0</td>
<td style="text-align: center;" align="right">0</td>
<td style="text-align: center;" align="right">0</td>
<td style="text-align: center;" align="right">1</td>
<td style="text-align: center;">update the head</td>
</tr>
<tr height="21">
<td style="text-align: center;" height="21" align="right">0</td>
<td style="text-align: center;" align="right">0</td>
<td style="text-align: center;" align="right">1</td>
<td style="text-align: center;" align="right">0</td>
<td style="text-align: center;">update the head</td>
</tr>
<tr height="21">
<td style="text-align: center;" height="21" align="right">0</td>
<td style="text-align: center;" align="right">0</td>
<td style="text-align: center;" align="right">1</td>
<td style="text-align: center;" align="right">1</td>
<td style="text-align: center;">update the head</td>
</tr>
<tr height="21">
<td style="text-align: center;" height="21" align="right">0</td>
<td style="text-align: center;" align="right">1</td>
<td style="text-align: center;" align="right">0</td>
<td style="text-align: center;" align="right">0</td>
<td style="text-align: center;">update the head</td>
</tr>
<tr height="21">
<td style="text-align: center;" height="21" align="right">0</td>
<td style="text-align: center;" align="right">1</td>
<td style="text-align: center;" align="right">0</td>
<td style="text-align: center;" align="right">1</td>
<td style="text-align: center;">update the head</td>
</tr>
<tr height="21">
<td style="text-align: center;" height="21" align="right">0</td>
<td style="text-align: center;" align="right">1</td>
<td style="text-align: center;" align="right">1</td>
<td style="text-align: center;" align="right">0</td>
<td style="text-align: center;">update the head</td>
</tr>
<tr height="21">
<td style="text-align: center;" height="21" align="right">0</td>
<td style="text-align: center;" align="right">1</td>
<td style="text-align: center;" align="right">1</td>
<td style="text-align: center;" align="right">1</td>
<td style="text-align: center;">update the head</td>
</tr>
<tr height="21">
<td style="text-align: center;" height="21" align="right">1</td>
<td style="text-align: center;" align="right">0</td>
<td style="text-align: center;" align="right">0</td>
<td style="text-align: center;" align="right">0</td>
<td style="text-align: center;">update the head</td>
</tr>
<tr height="21">
<td style="text-align: center;" height="21" align="right">1</td>
<td style="text-align: center;" align="right">0</td>
<td style="text-align: center;" align="right">0</td>
<td style="text-align: center;" align="right">1</td>
<td style="text-align: center;">update the head</td>
</tr>
<tr height="21">
<td style="text-align: center;" height="21" align="right">1</td>
<td style="text-align: center;" align="right">0</td>
<td style="text-align: center;" align="right">1</td>
<td style="text-align: center;" align="right">0</td>
<td style="text-align: center;">insert at the head</td>
</tr>
<tr height="21">
<td style="text-align: center;" height="21" align="right">1</td>
<td style="text-align: center;" align="right">0</td>
<td style="text-align: center;" align="right">1</td>
<td style="text-align: center;" align="right">1</td>
<td style="text-align: center;">insert at the head</td>
</tr>
<tr height="21">
<td style="text-align: center;" height="21" align="right">1</td>
<td style="text-align: center;" align="right">1</td>
<td style="text-align: center;" align="right">0</td>
<td style="text-align: center;" align="right">0</td>
<td style="text-align: center;">update the head</td>
</tr>
<tr height="21">
<td style="text-align: center;" height="21" align="right">1</td>
<td style="text-align: center;" align="right">1</td>
<td style="text-align: center;" align="right">0</td>
<td style="text-align: center;" align="right">1</td>
<td style="text-align: center;">update the found</td>
</tr>
<tr height="21">
<td style="text-align: center;" height="21" align="right">1</td>
<td style="text-align: center;" align="right">1</td>
<td style="text-align: center;" align="right">1</td>
<td style="text-align: center;" align="right">0</td>
<td style="text-align: center;">insert at the head</td>
</tr>
<tr height="21">
<td style="text-align: center;" height="21" align="right">1</td>
<td style="text-align: center;" align="right">1</td>
<td style="text-align: center;" align="right">1</td>
<td style="text-align: center;" align="right">1</td>
<td style="text-align: center;">update the found</td>
</tr>
</tbody>
</table>
<p>The case where you</p>
<ol>
<li>Had no room</li>
<li>Saw a new device</li>
</ol>
<p>Look like this:</p>
<pre class="EnlighterJSRAW" data-enlighter-language="c">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(&amp;scan_result-&gt;remote_bd_addr);

    // If there is a new entry and you ran out of space
    if(entry == -1 &amp;&amp; adb_db_count &gt;= ADB_MAX_SIZE)
    {
        free(scan_result);
        free(data);
        return;
    }
    
    // If it is NOT found &amp;&amp; you have room
    if(entry == -1)
    {
        adb_database[adb_db_count] = malloc(sizeof(adb_adv_t));
        adb_database[adb_db_count]-&gt;result = scan_result;
        adb_database[adb_db_count]-&gt;listCount = 1;
        adb_database[adb_db_count]-&gt;watch = false;
        adb_database[adb_db_count]-&gt;filter = true;
        adb_database[adb_db_count]-&gt;numSeen = 1;
        adb_database[adb_db_count]-&gt;lastSeen = timeSeen;

        adb_adv_data_t *current = malloc(sizeof(adb_adv_data_t));
        current-&gt;next = 0;
        current-&gt;data = data;
        current-&gt;numSeen = 1;
        current-&gt;lastSeen = timeSeen;

        adb_database[adb_db_count]-&gt;list = current;

        adb_db_count = adb_db_count + 1;    
        adb_db_print(ADB_PRINT_METHOD_BYTES,false,adb_db_count-1);

        return; 
    }</pre>
<p>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).</p>
<p>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.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="c">    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-&gt;next)
        {
            if(memcmp(list-&gt;data,data,len) == 0) // Found the data
            {
                updateItem = list;
                break;
            }
        }
    }

    // insert at the head
    if( (adb_database[entry].watch &amp;&amp; !adb_database[entry].filter &amp;&amp; adb_recording &amp;&amp; !updateItem) ||
        (adb_database[entry].watch &amp;&amp; !adb_database[entry].filter &amp;&amp; adb_recording &amp;&amp; updateItem) ||
        (adb_database[entry].watch &amp;&amp; adb_database[entry].filter &amp;&amp; adb_recording &amp;&amp; !updateItem)
    )
    {
        adb_adv_data_t *updateItem = malloc(sizeof(adb_adv_data_t)); // make new data
        updateItem-&gt;next = (struct adb_adv_data_t *)adb_database[entry].list;
        updateItem-&gt;numSeen = 1;
        updateItem-&gt;data = data;
        updateItem-&gt;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;
    }
</pre>
<p>The final case happens when you are just going to update a found packet.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="c">    if(updateItem == 0)
        updateItem = adb_database[entry].list;


    adb_database[entry].numSeen += 1;
    adb_database[entry].lastSeen = timeSeen;

    updateItem-&gt;lastSeen = timeSeen;

    int len = btutil_adv_len(data); // ARH maybe a bug here
    if(memcmp(updateItem-&gt;data,data,len) == 0)
    {
        updateItem-&gt;numSeen += 1;
    }
    else
    {
        updateItem-&gt;numSeen = 1;   
    }

    free(updateItem-&gt;data);
    updateItem-&gt;data = data;
    free(scan_result);

}
</pre>
<p>In the next article I will add</p>
<ol>
<li>Sort</li>
<li>Purge</li>
</ol>
<p>Then I will call it  a day.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://iotexpert.com/anycloud-bluetooth-advertising-scanner-part-9/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>AnyCloud Bluetooth Advertising Scanner (Part 8)</title>
		<link>https://iotexpert.com/anycloud-bluetooth-advertising-scanner-part-8/</link>
					<comments>https://iotexpert.com/anycloud-bluetooth-advertising-scanner-part-8/#respond</comments>
		
		<dc:creator><![CDATA[Alan Hawse]]></dc:creator>
		<pubDate>Mon, 14 Dec 2020 13:00:23 +0000</pubDate>
				<category><![CDATA[4343W]]></category>
		<category><![CDATA[AnyCloud]]></category>
		<category><![CDATA[AnyCloud Advertising Scanner]]></category>
		<category><![CDATA[CY8CKIT-062-WiFi-BT]]></category>
		<category><![CDATA[CY8CKIT-062S2-43012]]></category>
		<category><![CDATA[CY8CPROTO-062-4343W]]></category>
		<category><![CDATA[PSoC 6]]></category>
		<guid isPermaLink="false">https://iotexpert.com/?p=10220</guid>

					<description><![CDATA[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 [&#8230;]]]></description>
										<content:encoded><![CDATA[<h1>Summary</h1>
<p>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.</p>
<h1>Story</h1>
<p>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.</p>
<p>The way that the filter will work is that I will update the &#8220;add&#8221; 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.</p>
<p>The other thing that needs to happen is for me to add a &#8220;filter&#8221; command so that I can turn on packet filtering on a device by device basis.</p>
<p>And I need to fix the printing to use the new filtered packet database.</p>
<p>There are</p>
<p><div class="table-responsive"><table  style="width:95%; "  class="easy-table easy-table-default " border="1">
<thead>
<tr><th >Article</th>
<th >Topic</th>
</tr>
</thead>
<tbody>
<tr><td ><a href="https://iotexpert.com/anycloud-bluetooth-advertising-scanner-part-1/" target="_blank" rel="noopener">AnyCloud Bluetooth Advertising Scanner (Part 1)</a></td>
<td >Introduction to AnyCloud Bluetooth Advertising</td>
</tr>

<tr><td ><a href="https://iotexpert.com/anycloud-bluetooth-advertising-scanner-part-2/" target="_blank" rel="noopener">AnyCloud Bluetooth Advertising Scanner (Part 2)</a></td>
<td >Creating an AnyCloud Bluetooth project</td>
</tr>

<tr><td ><a href="https://iotexpert.com/anycloud-bluetooth-advertising-scanner-part-3/" target="_blank" rel="noopener">AnyCloud Bluetooth Advertising Scanner (Part 3)</a></td>
<td >Adding Observing functionality to the project</td>
</tr>

<tr><td ><a class="row-title" href="https://iotexpert.com/anycloud-bluetooth-utilities-library/" aria-label="“AnyCloud Bluetooth Utilities Library” (Edit)" target="_blank" rel="noopener">AnyCloud Bluetooth Utilities Library</a></td>
<td >A set of APIs for enhancement of the AnyCloud Library</td>
</tr>

<tr><td ><a href="https://iotexpert.com/anycloud-bluetooth-advertising-scanner-part-4/" target="_blank" rel="noopener">AnyCloud Bluetooth Advertising Scanner (Part 4)</a></td>
<td >Adding a command line to the scanner</td>
</tr>

<tr><td ><a href="https://iotexpert.com/anycloud-bluetooth-advertising-scanner-part-5/" target="_blank" rel="noopener">AnyCloud Bluetooth Advertising Scanner (Part 5)</a></td>
<td >Adding a history database to the scanner</td>
</tr>

<tr><td ><a href="https://iotexpert.com/anycloud-bluetooth-advertising-scanner-part-6/" target="_blank" rel="noopener">AnyCloud Bluetooth Advertising Scanner (Part 6)</a></td>
<td >Decoding advertising packets</td>
</tr>

<tr><td ><a href="https://iotexpert.com/anycloud-bluetooth-advertising-scanner-part-7/" target="_blank" rel="noopener">AnyCloud Bluetooth Advertising Scanner (Part 7)</a></td>
<td >Adding recording commands to the command line</td>
</tr>

<tr><td ><a href="https://iotexpert.com/anycloud-bluetooth-advertising-scanner-part-8/">AnyCloud Bluetooth Advertising Scanner (Part 8)</a></td>
<td >Adding filtering to the scanner</td>
</tr>

<tr><td ><a href="https://iotexpert.com/anycloud-bluetooth-advertising-scanner-part-9/">AnyCloud Bluetooth Advertising Scanner (Part 9)</a></td>
<td >Improve the print and add packet age</td>
</tr>

<tr><td ><a href="https://iotexpert.com/anycloud-bluetooth-advertising-scanner-part-10/">AnyCloud Bluetooth Advertising Scanner (Part 10)</a></td>
<td >Sort the database</td>
</tr>
</tbody></table></div></p>
<p>All of the code can be found at git@github.com:iotexpert/AnyCloudBLEScanner.git and https://github.com/iotexpert/AnyCloudBLEScanner.git</p>
<p>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.</p>
<p>You can also create a new project with this is a template if you have the IoT Expert Manifest Files installed</p>
<h1>Update the Data Structures</h1>
<p>In order to do the filters, and keep track of the data I will add</p>
<ol>
<li>A &#8220;count&#8221; field to the packet data structure</li>
<li>A &#8220;filter&#8221; boolean field to the device data structure.</li>
</ol>
<pre class="EnlighterJSRAW" data-enlighter-language="c">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 ;</pre>
<h1>Update the Add Function</h1>
<p>In the function &#8220;static void adb_db_add(wiced_bt_ble_scan_results_t *scan_result,uint8_t *data)&#8221; which is called every time I see a new advertising packet I will need to handle four different cases:</p>
<ol>
<li>The first time you see a device</li>
<li>A device you have seen AND you are recording AND have the filtering turned on</li>
<li>A device you are recording but not filtering</li>
<li>A device you have seen, but are not recording or filter.</li>
</ol>
<p>In the first case, a device you haven&#8217;t seen before, you need to</p>
<ol>
<li>Automatically turn on the filtering</li>
<li>Initialize the counts to 1</li>
<li>Do the other initialization (as before)</li>
</ol>
<pre class="EnlighterJSRAW" data-enlighter-language="c">    // 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-&gt;next = 0;
        current-&gt;data = data;
        current-&gt;count = 1;</pre>
<p>In the case where you have</p>
<ol>
<li>See the device before</li>
<li>You have room in the record buffer</li>
<li>And you are in record mode</li>
</ol>
<p>You will then decide if you are filtering.</p>
<p>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.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="c">    else if(adb_database[entry].record &amp;&amp; adb_recording_count&lt;ADB_RECORD_MAX &amp;&amp; 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-&gt;next)
            {
                if(memcmp(list-&gt;data,data,len) == 0) // Found the data
                {
                    list-&gt;count += 1;
                    printf("Count = %d\n",list-&gt;count);
                    free(data);
                    free(scan_result);
                    return;
                }
            }
        }
</pre>
<p>If you have not see the data before, then you need to add it to the linked list.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="c">        adb_adv_data_t *current = malloc(sizeof(adb_adv_data_t));
        current-&gt;next = (struct adb_adv_data_t *)adb_database[entry].list;
        current-&gt;data = data;
        current-&gt;count = 1;</pre>
<p>If you are not recording and not filtering, just increment counts.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="c">    else
    {
        adb_database[entry].numSeen += 1;
        adb_database[entry].list-&gt;count += 1;</pre>
<h1>Add a &#8220;filter&#8221; Command</h1>
<p>I want the ability for a user to &#8220;filter all&#8221; or &#8220;filter clear&#8221; or &#8220;filter #&#8221; &#8211; just like we did with watch.  So, add the #defines and new function to advDatabase.h</p>
<pre class="EnlighterJSRAW" data-enlighter-language="c">#define ADB_FILTER_ALL -1
#define ADB_FILTER_CLEAR -2
void adb_filter(int entry);
</pre>
<p>Then add the new filter command in advDatabase.c</p>
<pre class="EnlighterJSRAW" data-enlighter-language="c">typedef enum {
    ADB_ADD,
    ADB_PRINT_RAW,
    ADB_PRINT_DECODE,
    ADB_WATCH,
    ADB_ERASE,
    ADB_RECORD,
    ADB_FILTER,
} adb_cmd_t;</pre>
<p>I will use the adb_queueCmd function that I created in the last article.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="c">inline void adb_filter(int entry) { adb_queueCmd(ADB_FILTER,(void*)entry,(void *)0); }
</pre>
<p>The filter command has three cases</p>
<ol>
<li>All &#8211; turn the bool for all on</li>
<li>Clear &#8211; turn the bool for all off</li>
<li>Just a specific number &#8211; toggle that specific number</li>
</ol>
<pre class="EnlighterJSRAW" data-enlighter-language="c">static void adb_db_filter(int entry)
{
    if(entry == ADB_FILTER_ALL)
    {
        for(int i=0;i&lt;adb_db_count;i++)
        {
            adb_database[i].filter = true;
        }
        return;
    }

    if(entry == ADB_FILTER_CLEAR)
    {
        for(int i=0;i&lt;adb_db_count;i++)
        {
            adb_database[i].filter = false;
        }
        return;
    }

    if(entry &gt; adb_db_count-1 || entry &lt; ADB_WATCH_CLEAR)
    {
        printf("Record doesnt exist: %d\n",entry);
        return;      
    }
    adb_database[entry].filter = !adb_database[entry].filter; 

}
</pre>
<p>And you need to fix up the main command processor</p>
<pre class="EnlighterJSRAW" data-enlighter-language="c">                case ADB_FILTER:
                    adb_db_filter((int)msg.data0);
                break;</pre>
<p>Finally add the command to the usrcmd.c</p>
<pre class="EnlighterJSRAW" data-enlighter-language="c">static int usrcmd_filter(int argc, char **argv)
{

    if(argc == 2 &amp;&amp; !strcmp(argv[1],"all"))
    {
        adb_filter(ADB_FILTER_ALL); // all
        return 0;
    }


    if(argc == 2 &amp;&amp; !strcmp(argv[1],"clear"))
    {
        adb_filter(ADB_FILTER_CLEAR);
        return 0;
    }

    if(argc == 2)
    {
        int i;
        sscanf(argv[1],"%d",&amp;i);
        adb_filter(i);
        return 0;
    }

    return 0;
}</pre>
<h1>Fix the Printing</h1>
<p>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 &#8220;Watch&#8221; with a &#8220;*&#8221;.  When I looked at it, I decided that I should indicate filter with an &#8220;F&#8221; and watch with a &#8220;W&#8221;.  So I fix that.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="c">        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-&gt;remote_bd_addr);
        switch(method)
        {</pre>
<p>Then I test the &#8220;filter&#8221; command</p>
<p><a href="https://iotexpert.com/anycloud-bluetooth-advertising-scanner-part-8/screen-shot-2020-11-14-at-9-49-32-am/" rel="attachment wp-att-10235"><img loading="lazy" decoding="async" src="https://iotexpert.com/wp-content/uploads/2020/11/Screen-Shot-2020-11-14-at-9.49.32-AM-1024x622.jpg" alt="" class="alignnone size-large wp-image-10235" width="1024" height="622" srcset="https://iotexpert.com/wp-content/uploads/2020/11/Screen-Shot-2020-11-14-at-9.49.32-AM-1024x622.jpg 1024w, https://iotexpert.com/wp-content/uploads/2020/11/Screen-Shot-2020-11-14-at-9.49.32-AM-300x182.jpg 300w, https://iotexpert.com/wp-content/uploads/2020/11/Screen-Shot-2020-11-14-at-9.49.32-AM-768x466.jpg 768w, https://iotexpert.com/wp-content/uploads/2020/11/Screen-Shot-2020-11-14-at-9.49.32-AM-1536x933.jpg 1536w, https://iotexpert.com/wp-content/uploads/2020/11/Screen-Shot-2020-11-14-at-9.49.32-AM-600x364.jpg 600w, https://iotexpert.com/wp-content/uploads/2020/11/Screen-Shot-2020-11-14-at-9.49.32-AM.jpg 2042w" sizes="auto, (max-width: 1024px) 100vw, 1024px" /></a></p>
<h1>Fix the Printing Part (2)</h1>
<p>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 &#8220;history&#8221;</p>
<pre class="EnlighterJSRAW" data-enlighter-language="c">static void adb_db_print(adb_print_method_t method,bool history,int entry)
</pre>
<p>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.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="c">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-&gt;remote_bd_addr);

    switch(method)
    {
    
    case ADB_PRINT_METHOD_BYTES:
        printf(" Data: ");
        btutil_adv_printPacketBytes(adv_data-&gt;data);
    break;

    case ADB_PRINT_METHOD_DECODE:
        printf("\n");
        btutil_adv_printPacketDecode(adv_data-&gt;data);
    break;
    } 
    printf("\n");

}
</pre>
<p>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.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="c">static void adb_db_print(adb_print_method_t method,bool history,int entry)
{
    int start,end;
 
    if(entry &lt; 0)
    {
        start = 0;
        end = adb_db_count;
    }
    else
    {
        start = entry;
        end = entry+1;
    }

    if(end&gt;adb_db_count)
        end = adb_db_count; 

    for(int i=start;i&lt;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-&gt;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);
    }
}</pre>
<p>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 &#8220;print&#8221; from the command line that you are interested in the history.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="c">                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;</pre>
<p>But when you are printing out the packet for a new device don&#8217;t print out the history</p>
<pre class="EnlighterJSRAW" data-enlighter-language="c">            adb_db_print(ADB_PRINT_METHOD_BYTES,false,adb_db_count-1);
</pre>
<h1>Program and Test</h1>
<p>After I program my development kit, I start by typing &#8220;watch all&#8221;.  Very quickly, at my house, you can see that a bunch of devices are discovered.  You can see that all of these have a &#8220;W&#8221; (meaning that I am watching them) and an &#8220;F&#8221; meaning they are filtering out duplicates.  Then I type &#8220;record&#8221; to turn on recording. After a minute I turn off recording then do the print you can see below.</p>
<p>A couple of things to notice.</p>
<ol>
<li>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</li>
<li>You can see device 11 seems to be sending out 16 different packets.  Why?  I don&#8217;t know.</li>
</ol>
<p><a href="https://iotexpert.com/anycloud-bluetooth-advertising-scanner-part-8/screen-shot-2020-11-14-at-12-33-06-pm/" rel="attachment wp-att-10236"><img loading="lazy" decoding="async" src="https://iotexpert.com/wp-content/uploads/2020/11/Screen-Shot-2020-11-14-at-12.33.06-PM-1024x624.png" alt="" class="alignnone size-large wp-image-10236" width="1024" height="624" srcset="https://iotexpert.com/wp-content/uploads/2020/11/Screen-Shot-2020-11-14-at-12.33.06-PM-1024x624.png 1024w, https://iotexpert.com/wp-content/uploads/2020/11/Screen-Shot-2020-11-14-at-12.33.06-PM-300x183.png 300w, https://iotexpert.com/wp-content/uploads/2020/11/Screen-Shot-2020-11-14-at-12.33.06-PM-768x468.png 768w, https://iotexpert.com/wp-content/uploads/2020/11/Screen-Shot-2020-11-14-at-12.33.06-PM-1536x936.png 1536w, https://iotexpert.com/wp-content/uploads/2020/11/Screen-Shot-2020-11-14-at-12.33.06-PM-600x366.png 600w, https://iotexpert.com/wp-content/uploads/2020/11/Screen-Shot-2020-11-14-at-12.33.06-PM.png 2032w" sizes="auto, (max-width: 1024px) 100vw, 1024px" /></a></p>
<p>But we can &#8220;decode 11&#8221; to try to figure it out.  You can see that it is advertising manufactures specific data with Apple&#8217;s UUID which I happen to know is 0x004C.  But why?  I don&#8217;t know.</p>
<p><a href="https://iotexpert.com/anycloud-bluetooth-advertising-scanner-part-8/screen-shot-2020-11-14-at-12-37-51-pm/" rel="attachment wp-att-10237"><img loading="lazy" decoding="async" src="https://iotexpert.com/wp-content/uploads/2020/11/Screen-Shot-2020-11-14-at-12.37.51-PM-1024x807.jpg" alt="" class="alignnone size-large wp-image-10237" width="1024" height="807" srcset="https://iotexpert.com/wp-content/uploads/2020/11/Screen-Shot-2020-11-14-at-12.37.51-PM-1024x807.jpg 1024w, https://iotexpert.com/wp-content/uploads/2020/11/Screen-Shot-2020-11-14-at-12.37.51-PM-300x236.jpg 300w, https://iotexpert.com/wp-content/uploads/2020/11/Screen-Shot-2020-11-14-at-12.37.51-PM-768x605.jpg 768w, https://iotexpert.com/wp-content/uploads/2020/11/Screen-Shot-2020-11-14-at-12.37.51-PM-1536x1210.jpg 1536w, https://iotexpert.com/wp-content/uploads/2020/11/Screen-Shot-2020-11-14-at-12.37.51-PM-600x473.jpg 600w, https://iotexpert.com/wp-content/uploads/2020/11/Screen-Shot-2020-11-14-at-12.37.51-PM.jpg 1554w" sizes="auto, (max-width: 1024px) 100vw, 1024px" /></a></p>
<p>I really want to move onto a new series of articles&#8230; but there are two functions which I will add to the program.  Stay tuned for what they do.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://iotexpert.com/anycloud-bluetooth-advertising-scanner-part-8/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>AnyCloud Bluetooth Advertising Scanner (Part 7)</title>
		<link>https://iotexpert.com/anycloud-bluetooth-advertising-scanner-part-7/</link>
					<comments>https://iotexpert.com/anycloud-bluetooth-advertising-scanner-part-7/#respond</comments>
		
		<dc:creator><![CDATA[Alan Hawse]]></dc:creator>
		<pubDate>Mon, 07 Dec 2020 13:00:38 +0000</pubDate>
				<category><![CDATA[AnyCloud]]></category>
		<category><![CDATA[AnyCloud Advertising Scanner]]></category>
		<category><![CDATA[Bluetooth]]></category>
		<category><![CDATA[CY8CKIT-062-WiFi-BT]]></category>
		<category><![CDATA[CY8CKIT-062S2-43012]]></category>
		<category><![CDATA[PSoC 6]]></category>
		<guid isPermaLink="false">https://iotexpert.com/?p=10218</guid>

					<description><![CDATA[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 [&#8230;]]]></description>
										<content:encoded><![CDATA[<h1>Summary</h1>
<p>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.</p>
<h1>Story</h1>
<p>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.</p>
<p>Now I want to add the ability to record more than one advertising packet per device.  To that end I will add three commands:</p>
<ul>
<li>watch &#8211; Mark a device as one that needs to have the advertising data recorded.  You can type &#8220;watch 12&#8221; or you can say &#8220;watch all&#8221; or you can say &#8220;watch clear&#8221;</li>
<li>record &#8211; Turn on recording of &#8220;watched&#8221; devices.  When you type record it will toggle the recording state between On and Off.</li>
<li>erase &#8211; clear the record buffer of all but the most recent packet.</li>
</ul>
<p>There are</p>
<p><div class="table-responsive"><table  style="width:95%; "  class="easy-table easy-table-default " border="1">
<thead>
<tr><th >Article</th>
<th >Topic</th>
</tr>
</thead>
<tbody>
<tr><td ><a href="https://iotexpert.com/anycloud-bluetooth-advertising-scanner-part-1/" target="_blank" rel="noopener">AnyCloud Bluetooth Advertising Scanner (Part 1)</a></td>
<td >Introduction to AnyCloud Bluetooth Advertising</td>
</tr>

<tr><td ><a href="https://iotexpert.com/anycloud-bluetooth-advertising-scanner-part-2/" target="_blank" rel="noopener">AnyCloud Bluetooth Advertising Scanner (Part 2)</a></td>
<td >Creating an AnyCloud Bluetooth project</td>
</tr>

<tr><td ><a href="https://iotexpert.com/anycloud-bluetooth-advertising-scanner-part-3/" target="_blank" rel="noopener">AnyCloud Bluetooth Advertising Scanner (Part 3)</a></td>
<td >Adding Observing functionality to the project</td>
</tr>

<tr><td ><a class="row-title" href="https://iotexpert.com/anycloud-bluetooth-utilities-library/" aria-label="“AnyCloud Bluetooth Utilities Library” (Edit)" target="_blank" rel="noopener">AnyCloud Bluetooth Utilities Library</a></td>
<td >A set of APIs for enhancement of the AnyCloud Library</td>
</tr>

<tr><td ><a href="https://iotexpert.com/anycloud-bluetooth-advertising-scanner-part-4/" target="_blank" rel="noopener">AnyCloud Bluetooth Advertising Scanner (Part 4)</a></td>
<td >Adding a command line to the scanner</td>
</tr>

<tr><td ><a href="https://iotexpert.com/anycloud-bluetooth-advertising-scanner-part-5/" target="_blank" rel="noopener">AnyCloud Bluetooth Advertising Scanner (Part 5)</a></td>
<td >Adding a history database to the scanner</td>
</tr>

<tr><td ><a href="https://iotexpert.com/anycloud-bluetooth-advertising-scanner-part-6/" target="_blank" rel="noopener">AnyCloud Bluetooth Advertising Scanner (Part 6)</a></td>
<td >Decoding advertising packets</td>
</tr>

<tr><td ><a href="https://iotexpert.com/anycloud-bluetooth-advertising-scanner-part-7/" target="_blank" rel="noopener">AnyCloud Bluetooth Advertising Scanner (Part 7)</a></td>
<td >Adding recording commands to the command line</td>
</tr>

<tr><td ><a href="https://iotexpert.com/anycloud-bluetooth-advertising-scanner-part-8/">AnyCloud Bluetooth Advertising Scanner (Part 8)</a></td>
<td >Adding filtering to the scanner</td>
</tr>

<tr><td ><a href="https://iotexpert.com/anycloud-bluetooth-advertising-scanner-part-9/">AnyCloud Bluetooth Advertising Scanner (Part 9)</a></td>
<td >Improve the print and add packet age</td>
</tr>

<tr><td ><a href="https://iotexpert.com/anycloud-bluetooth-advertising-scanner-part-10/">AnyCloud Bluetooth Advertising Scanner (Part 10)</a></td>
<td >Sort the database</td>
</tr>
</tbody></table></div></p>
<p>All of the code can be found at git@github.com:iotexpert/AnyCloudBLEScanner.git and https://github.com/iotexpert/AnyCloudBLEScanner.git</p>
<p>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.</p>
<p>You can also create a new project with this is a template if you have the IoT Expert Manifest Files installed</p>
<h1>Update the advDatabase Interface</h1>
<p>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:</p>
<pre class="EnlighterJSRAW" data-enlighter-language="c">void adb_watch(int entry)
{
    adb_cmdMsg_t msg;
    msg.cmd = ADB_WATCH;
    msg.data0 = (void *)entry;
    xQueueSend(adb_cmdQueue,&amp;msg,0); // If the queue is full... oh well

}</pre>
<p>So I created this:</p>
<pre class="EnlighterJSRAW" data-enlighter-language="c">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,&amp;msg,0); // If you loose an adv packet it is OK...
}</pre>
<p>Then did this to eliminate the duplication.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="c">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); }
</pre>
<h1>Redo the Database</h1>
<p>If you recall from previous posts, my advertising database was just</p>
<ol>
<li>An Array of structures</li>
<li>Each structure contained the mac address and&#8230;</li>
<li>A pointer to a malloc&#8217;d copy of the advertising data</li>
</ol>
<pre class="EnlighterJSRAW" data-enlighter-language="c">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];</pre>
<p>Here is a picture of the datastructure</p>
<p><a href="https://iotexpert.com/anycloud-bluetooth-advertising-scanner-part-7/db1/" rel="attachment wp-att-10226"><img loading="lazy" decoding="async" src="https://iotexpert.com/wp-content/uploads/2020/11/db1.png" alt="" width="550" height="976" class="alignnone size-full wp-image-10226" srcset="https://iotexpert.com/wp-content/uploads/2020/11/db1.png 550w, https://iotexpert.com/wp-content/uploads/2020/11/db1-169x300.png 169w" sizes="auto, (max-width: 550px) 100vw, 550px" /></a></p>
<p>&nbsp;</p>
<p>Now what I want to do is make the &#8220;data&#8221; pointer to be a pointer to a linked list of data.  Here is the new definition.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="c">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 ;</pre>
<p>The new data structure looks like this</p>
<p><a href="https://iotexpert.com/anycloud-bluetooth-advertising-scanner-part-7/newdb/" rel="attachment wp-att-10227"><img loading="lazy" decoding="async" src="https://iotexpert.com/wp-content/uploads/2020/11/newdb-1024x863.png" alt="" width="1024" height="863" class="alignnone size-large wp-image-10227" srcset="https://iotexpert.com/wp-content/uploads/2020/11/newdb-1024x863.png 1024w, https://iotexpert.com/wp-content/uploads/2020/11/newdb-300x253.png 300w, https://iotexpert.com/wp-content/uploads/2020/11/newdb-768x647.png 768w, https://iotexpert.com/wp-content/uploads/2020/11/newdb-600x506.png 600w, https://iotexpert.com/wp-content/uploads/2020/11/newdb.png 1158w" sizes="auto, (max-width: 1024px) 100vw, 1024px" /></a></p>
<p>I wanted to limit the number advertising packets that can be stored so I don&#8217;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</p>
<ol>
<li>A counter for the number of advertising packets that are currently saved</li>
<li>A recording state (are you saving or not)</li>
</ol>
<pre class="EnlighterJSRAW" data-enlighter-language="c" ">#define ADB_RECORD_MAX (100)
static int adb_recording_count = 0;
static bool adb_recording = false;
</pre>
<h1>Update the Printing</h1>
<p>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 &#8220;watching&#8221; a device.  The columns are now:</p>
<ol>
<li>A &#8220;*&#8221; to indicate that a device is being watched</li>
<li>The device #</li>
<li>The number of packets that I have seen in total from that device</li>
<li>The number of recorded packets for that device</li>
<li>The MAC address</li>
<li>The raw bytes</li>
</ol>
<p><a href="https://iotexpert.com/anycloud-bluetooth-advertising-scanner-part-7/screen-shot-2020-11-13-at-9-11-45-am/" rel="attachment wp-att-10228"><img loading="lazy" decoding="async" src="https://iotexpert.com/wp-content/uploads/2020/11/Screen-Shot-2020-11-13-at-9.11.45-AM-1024x355.png" alt="" width="1024" height="355" class="alignnone size-large wp-image-10228" srcset="https://iotexpert.com/wp-content/uploads/2020/11/Screen-Shot-2020-11-13-at-9.11.45-AM-1024x355.png 1024w, https://iotexpert.com/wp-content/uploads/2020/11/Screen-Shot-2020-11-13-at-9.11.45-AM-300x104.png 300w, https://iotexpert.com/wp-content/uploads/2020/11/Screen-Shot-2020-11-13-at-9.11.45-AM-768x266.png 768w, https://iotexpert.com/wp-content/uploads/2020/11/Screen-Shot-2020-11-13-at-9.11.45-AM-1536x533.png 1536w, https://iotexpert.com/wp-content/uploads/2020/11/Screen-Shot-2020-11-13-at-9.11.45-AM-600x208.png 600w, https://iotexpert.com/wp-content/uploads/2020/11/Screen-Shot-2020-11-13-at-9.11.45-AM.png 1984w" sizes="auto, (max-width: 1024px) 100vw, 1024px" /></a></p>
<p>To do implement this a simple change is made to the print function:</p>
<pre class="EnlighterJSRAW" data-enlighter-language="c" ">    for(int i=start;i&lt;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-&gt;remote_bd_addr);
        switch(method)
        {
        
        case ADB_PRINT_METHOD_BYTES:
            printf(" Data: ");
            btutil_adv_printPacketBytes(adb_database[i].list-&gt;data);
        break;

        case ADB_PRINT_METHOD_DECODE:
            printf("\n");
            btutil_adv_printPacketDecode(adb_database[i].list-&gt;data);
        break;
        } 
        printf("\n");
    }</pre>
<h1>Update the Add</h1>
<p>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:</p>
<ol>
<li>You have never seen the device before</li>
<li>You have seen the device before and you are &#8220;watching&#8221; it</li>
<li>You have see the device but you are not watching it</li>
</ol>
<p>In the case where you have never seen the device you need to</p>
<ol>
<li>Save the scan result</li>
<li>Set the listCount to 1 (you only have one datapoint)</li>
<li>Turn off recording (start with the recording off)</li>
<li>Set the total numSeen to 1 as this is the first packet you have seen</li>
<li>Allocate some memory for the advertising linked list structure</li>
<li>Terminate the linked list</li>
<li>Save the advertising data</li>
<li>Increment the database count (up to the max)</li>
<li>Print out the packet you just saw</li>
</ol>
<pre class="EnlighterJSRAW" data-enlighter-language="c">    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-&gt;next = 0;
        current-&gt;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);
        }
    }</pre>
<p>In the case where you have</p>
<ol>
<li>Seen the device before</li>
<li>You are recording that device</li>
<li>There is room left in the recording buffer</li>
</ol>
<p>Then you will</p>
<ol>
<li>Increment number seen</li>
<li>Create memory for the new entry in the linked list</li>
<li>Attach the tail of the linked list to your new entry (you will insert at the front of the list)</li>
<li>Save the data</li>
<li>Increment the number of saved entries</li>
<li>Insert your new packet at the head of the list</li>
<li>Printout the packet</li>
<li>Increment the record count (the total number of packets in the recording buffer)</li>
<li>Then potentially stop recording if you have gotten to the max size.</li>
</ol>
<pre class="EnlighterJSRAW" data-enlighter-language="c">    else if(adb_database[entry].record &amp;&amp; adb_recording_count&lt;ADB_RECORD_MAX &amp;&amp; adb_recording)
    {
        adb_database[entry].numSeen += 1;

        adb_adv_data_t *current = malloc(sizeof(adb_adv_data_t));
        current-&gt;next = (struct adb_adv_data_t *)adb_database[entry].list;
        current-&gt;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");
        }
    }</pre>
<p>In the case where you have seen the device before, but you are not recoding then you will</p>
<ol>
<li>Update the numSeen</li>
<li>Erase the old packet data</li>
<li>Save the new packet</li>
<li>Erase the &#8220;result&#8221; (you already have it saved)</li>
</ol>
<pre class="EnlighterJSRAW" data-enlighter-language="c">    else
    {
        adb_database[entry].numSeen += 1;
        free(adb_database[entry].list-&gt;data);
        adb_database[entry].list-&gt;data = data;
        free(scan_result);
    }</pre>
<h1>Add a Watch Command</h1>
<p>The watch function is pretty simple.  It just needs to either mark the &#8220;record&#8221; 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 &#8220;watch all&#8221; and &#8220;watch clear&#8221;.  So, I used negative numbers for those two special meanings.  I used a #define in advDatabase.h to define those values.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="c" ">#define ADB_WATCH_ALL -1
#define ADB_WATCH_CLEAR -2</pre>
<p>The function is then pretty simple</p>
<ol>
<li>If it is watch all&#8230; then iterate through the database and turn them on</li>
<li>If it is watch clear &#8230; then iterate through the database and turn them off</li>
<li>Otherwise make sure that it is a legal number and toggle it.</li>
</ol>
<pre class="EnlighterJSRAW" data-enlighter-language="c">static void adb_db_watch(int entry)
{
    if(entry == ADB_WATCH_ALL)
    {
        for(int i=0;i&lt;adb_db_count;i++)
        {
            adb_database[i].record = true;
        }
        return;
    }

    if(entry == ADB_WATCH_CLEAR)
    {
        for(int i=0;i&lt;adb_db_count;i++)
        {
            adb_database[i].record = false;
        }
        return;
    }

    if(entry &gt; adb_db_count-1 || entry &lt; ADB_WATCH_CLEAR)
    {
        printf("Record doesnt exist: %d\n",entry);
        return;      
    }
    adb_database[entry].record = !adb_database[entry].record; 

}</pre>
<p>Once I have the infrastructure in place, I then add the watch command to usrcmd.c</p>
<pre class="EnlighterJSRAW" data-enlighter-language="c" ">static int usrcmd_watch(int argc, char **argv)
{

    if(argc == 2 &amp;&amp; !strcmp(argv[1],"all"))
    {
        adb_watch(ADB_WATCH_ALL); // all
        return 0;
    }


    if(argc == 2 &amp;&amp; !strcmp(argv[1],"clear"))
    {
        adb_watch(ADB_WATCH_CLEAR);
        return 0;
    }

    if(argc == 2)
    {
        int i;
        sscanf(argv[1],"%d",&amp;i);
        adb_watch(i);
        return 0;
    }

    return 0;
}</pre>
<h1>Add a Record Command</h1>
<p>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 &#8220;buffer&#8221;</p>
<pre class="EnlighterJSRAW" data-enlighter-language="c" ">                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;</pre>
<p>And the change to usrcmd.c is also simple.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="c" ">// record = toggles
static int usrcmd_record(int argc, char **argv)
{
    if(argc == 1)
    {
        adb_record(-1);
        return 0;
    }
    return 0;
}</pre>
<h1>Add an Erase Command</h1>
<p>The erase function is like &#8220;watch&#8221;, as I overload the &#8220;entry&#8221; to have an ALL which is setup in advDatabase.h</p>
<pre class="EnlighterJSRAW" data-enlighter-language="c" ">#define ADB_ERASE_ALL -1</pre>
<p>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.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="c" ">                case ADB_ERASE:
                    if((int)msg.data0 == ADB_ERASE_ALL)
                    {
                        for(int i=0;i&lt;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;</pre>
<p>The individual eraseEntry function checks to make sure that you have a legal &#8220;entry&#8221;.  Then it follows the linked list &#8220;freeing&#8221; the data structures.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="c" ">static void adb_eraseEntry(int entry)
{
    if(entry &gt; adb_db_count-1 || entry&lt;0)
    {
        printf("Erase Entry Not Found %d\n",entry);
        return;
    }

    adb_adv_data_t *ptr;
    ptr = (adb_adv_data_t *)adb_database[entry].list-&gt;next;
    adb_database[entry].list-&gt;next = 0;
    while(ptr)
    {
        adb_adv_data_t *next;
        next = (adb_adv_data_t *)ptr-&gt;next;
        free(ptr-&gt;data);
        free(ptr);
        adb_database[entry].listCount -= 1;
        adb_recording_count -= 1;
        ptr = next;
    }
}
</pre>
<p>And, of course, you need to add the command to usrcmd.c</p>
<pre class="EnlighterJSRAW" data-enlighter-language="c" ">// erase
// erase #
static int usrcmd_erase(int argc, char **argv)
{
    if(argc &gt; 2)
    {
        return 0;
    }

    if(argc == 1)
    {
        adb_erase(ADB_ERASE_ALL);
        return 0;
    }

    int i;
    sscanf(argv[1],"%d",&amp;i);
    adb_erase(i);
    return 0;    

}</pre>
<p>Now when you build and program the kit you can turn on/off recording and erase and&#8230;.</p>
<p><a href="https://iotexpert.com/anycloud-bluetooth-advertising-scanner-part-7/screen-shot-2020-11-14-at-7-30-37-am/" rel="attachment wp-att-10233"><img loading="lazy" decoding="async" src="https://iotexpert.com/wp-content/uploads/2020/11/Screen-Shot-2020-11-14-at-7.30.37-AM-1024x741.jpg" alt="" width="1024" height="741" class="alignnone size-large wp-image-10233" srcset="https://iotexpert.com/wp-content/uploads/2020/11/Screen-Shot-2020-11-14-at-7.30.37-AM-1024x741.jpg 1024w, https://iotexpert.com/wp-content/uploads/2020/11/Screen-Shot-2020-11-14-at-7.30.37-AM-300x217.jpg 300w, https://iotexpert.com/wp-content/uploads/2020/11/Screen-Shot-2020-11-14-at-7.30.37-AM-768x556.jpg 768w, https://iotexpert.com/wp-content/uploads/2020/11/Screen-Shot-2020-11-14-at-7.30.37-AM-1536x1112.jpg 1536w, https://iotexpert.com/wp-content/uploads/2020/11/Screen-Shot-2020-11-14-at-7.30.37-AM-600x434.jpg 600w, https://iotexpert.com/wp-content/uploads/2020/11/Screen-Shot-2020-11-14-at-7.30.37-AM.jpg 1976w" sizes="auto, (max-width: 1024px) 100vw, 1024px" /></a></p>
<p>In the next post I will add</p>
<ol>
<li>Smarter printing</li>
<li>A &#8220;filter&#8221; to eliminate duplicate advertising packets</li>
</ol>
]]></content:encoded>
					
					<wfw:commentRss>https://iotexpert.com/anycloud-bluetooth-advertising-scanner-part-7/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>AnyCloud Bluetooth Advertising Scanner (Part 6)</title>
		<link>https://iotexpert.com/anycloud-bluetooth-advertising-scanner-part-6/</link>
					<comments>https://iotexpert.com/anycloud-bluetooth-advertising-scanner-part-6/#respond</comments>
		
		<dc:creator><![CDATA[Alan Hawse]]></dc:creator>
		<pubDate>Mon, 30 Nov 2020 13:00:38 +0000</pubDate>
				<category><![CDATA[4343W]]></category>
		<category><![CDATA[AnyCloud]]></category>
		<category><![CDATA[AnyCloud Advertising Scanner]]></category>
		<category><![CDATA[Bluetooth]]></category>
		<category><![CDATA[CY8CKIT-062-WiFi-BT]]></category>
		<category><![CDATA[CY8CKIT-062S2-43012]]></category>
		<category><![CDATA[CY8CPROTO-062-4343W]]></category>
		<category><![CDATA[PSoC 6]]></category>
		<guid isPermaLink="false">https://iotexpert.com/?p=10206</guid>

					<description><![CDATA[Summary In part 6 of this series I will update the AnyCloud BLE Advertising Scanner to decode advertising packets into a more human readable textual output Story We are now 6 (or maybe 7 depending on how you count) articles into this series and we are still looking at raw bytes.  I have gotten to [&#8230;]]]></description>
										<content:encoded><![CDATA[<h1>Summary</h1>
<p>In part 6 of this series I will update the AnyCloud BLE Advertising Scanner to decode advertising packets into a more human readable textual output</p>
<h1>Story</h1>
<p>We are now 6 (or maybe 7 depending on how you count) articles into this series and we are still looking at raw bytes.  I have gotten to where I am pretty good at understanding those bytes, but that is now way to roll.  You might remember from the <a href="https://iotexpert.com/anycloud-bluetooth-utilities-library/">article</a> on the IoT Expert Bluetooth Utility library that there were a some interesting functions defined in the header.  Here it is:</p>
<pre class="EnlighterJSRAW" data-enlighter-language="c">wiced_bool_t btutil_isEddystone(uint8_t *data);
wiced_bool_t btutil_is_iBeacon(uint8_t *data);
wiced_bool_t btutil_isCypress(uint8_t *data);

int btutil_adv_len(uint8_t *packet);
void btutil_adv_printPacketDecode(uint8_t *packet);
void btutil_adv_printPacketBytes(uint8_t *packet);</pre>
<p>Lets transform our  project from part 6 to use these functions.  In this article I will</p>
<ul>
<li>Redo the print bytes (to be smarter) functionality and to use the built in function</li>
<li>Rework the logic for the &#8220;print&#8221; command implementation</li>
<li>Add a new command &#8220;decode&#8221; which will run the decode function</li>
</ul>
<p>There are</p>
<p><div class="table-responsive"><table  style="width:95%; "  class="easy-table easy-table-default " border="1">
<thead>
<tr><th >Article</th>
<th >Topic</th>
</tr>
</thead>
<tbody>
<tr><td ><a href="https://iotexpert.com/anycloud-bluetooth-advertising-scanner-part-1/" target="_blank" rel="noopener">AnyCloud Bluetooth Advertising Scanner (Part 1)</a></td>
<td >Introduction to AnyCloud Bluetooth Advertising</td>
</tr>

<tr><td ><a href="https://iotexpert.com/anycloud-bluetooth-advertising-scanner-part-2/" target="_blank" rel="noopener">AnyCloud Bluetooth Advertising Scanner (Part 2)</a></td>
<td >Creating an AnyCloud Bluetooth project</td>
</tr>

<tr><td ><a href="https://iotexpert.com/anycloud-bluetooth-advertising-scanner-part-3/" target="_blank" rel="noopener">AnyCloud Bluetooth Advertising Scanner (Part 3)</a></td>
<td >Adding Observing functionality to the project</td>
</tr>

<tr><td ><a class="row-title" href="https://iotexpert.com/anycloud-bluetooth-utilities-library/" aria-label="“AnyCloud Bluetooth Utilities Library” (Edit)" target="_blank" rel="noopener">AnyCloud Bluetooth Utilities Library</a></td>
<td >A set of APIs for enhancement of the AnyCloud Library</td>
</tr>

<tr><td ><a href="https://iotexpert.com/anycloud-bluetooth-advertising-scanner-part-4/" target="_blank" rel="noopener">AnyCloud Bluetooth Advertising Scanner (Part 4)</a></td>
<td >Adding a command line to the scanner</td>
</tr>

<tr><td ><a href="https://iotexpert.com/anycloud-bluetooth-advertising-scanner-part-5/" target="_blank" rel="noopener">AnyCloud Bluetooth Advertising Scanner (Part 5)</a></td>
<td >Adding a history database to the scanner</td>
</tr>

<tr><td ><a href="https://iotexpert.com/anycloud-bluetooth-advertising-scanner-part-6/" target="_blank" rel="noopener">AnyCloud Bluetooth Advertising Scanner (Part 6)</a></td>
<td >Decoding advertising packets</td>
</tr>

<tr><td ><a href="https://iotexpert.com/anycloud-bluetooth-advertising-scanner-part-7/" target="_blank" rel="noopener">AnyCloud Bluetooth Advertising Scanner (Part 7)</a></td>
<td >Adding recording commands to the command line</td>
</tr>

<tr><td ><a href="https://iotexpert.com/anycloud-bluetooth-advertising-scanner-part-8/">AnyCloud Bluetooth Advertising Scanner (Part 8)</a></td>
<td >Adding filtering to the scanner</td>
</tr>

<tr><td ><a href="https://iotexpert.com/anycloud-bluetooth-advertising-scanner-part-9/">AnyCloud Bluetooth Advertising Scanner (Part 9)</a></td>
<td >Improve the print and add packet age</td>
</tr>

<tr><td ><a href="https://iotexpert.com/anycloud-bluetooth-advertising-scanner-part-10/">AnyCloud Bluetooth Advertising Scanner (Part 10)</a></td>
<td >Sort the database</td>
</tr>
</tbody></table></div></p>
<p>All of the code can be found at git@github.com:iotexpert/AnyCloudBLEScanner.git and https://github.com/iotexpert/AnyCloudBLEScanner.git</p>
<p>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.</p>
<p>You can also create a new project with this is a template if you have the IoT Expert Manifest Files installed</p>
<h1>Replace two code blocks with function calls</h1>
<p>Do you remember this block of code?  It print&#8217;s out the 6-bytes of the Bluetooth Address.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="c">    for(int i=0;i&lt;BD_ADDR_LEN;i++)
    {
        printf("%02X:",adb_database[entry].result-&gt;remote_bd_addr[i]);
    }
</pre>
<p>You might have noticed that this function already exists in the BT Utility Library.  Use it.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="c">    btutil_printBDaddress(adb_database[entry].result-&gt;remote_bd_addr);</pre>
<p>Then you remember this block of code which iterates through and advertising packet and prints out the raw bytes?</p>
<pre class="EnlighterJSRAW" data-enlighter-language="c">// Print the RAW Data of the ADV Packet
    printf(" Data: ");
    int i=0;
    while(adb_database[entry].data[i])
    {
        for(int j=0;j&lt;adb_database[entry].data[i];j++)
        {
            printf("%02X ",adb_database[entry].data[i+1+j]);
        }
        i = i + adb_database[entry].data[i]+1;
    }
</pre>
<p>Well, it exists in the library as well.  Use it.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="c">btutil_adv_printPacketBytes(adb_database[entry].data);</pre>
<h1>Fix the &#8220;print&#8221; Command</h1>
<p>In the previous implementation I had two functions for &#8220;print&#8221;.  The first one printed one entry and the second one printed the whole table.  I decided that I didnt really like this logic, so I compressed those two functions into one function.  Specifically, it take a number &#8220;entry&#8221;.  If that number is -1 then it will print the whole table.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="c">static void adb_db_printRawPacket(int entry)
{
    int start,end;
 
    if(entry &lt;= -1)
    {
        start = 0;
        end = adb_db_count;
    }
    else
    {
        start = entry;
        end = entry;
    }

    if(end&gt;adb_db_count)
        end = adb_db_count; 

    for(int i=start;i&lt;=end;i++)
    {
    
        printf("%02d MAC: ",i);
        btutil_printBDaddress(adb_database[i].result-&gt;remote_bd_addr);
        printf(" Data: ");
        btutil_adv_printPacketBytes(adb_database[i].data);

        printf("\n");
    }
}
</pre>
<h1>Add a new &#8220;decode&#8221; Command</h1>
<p>The next thing to do is to add a function to print out decoded packets (or the whole table).  So I wrote this:</p>
<pre class="EnlighterJSRAW" data-enlighter-language="c">static void adb_printDecodePacket(int entry)
{
    int start,end;
 
    if(entry == -1)
    {
        start = 0;
        end = adb_db_count;
    }
    else
    {
        start = entry;
        end = entry;
    }

    if(end&gt;adb_db_count)
        end = adb_db_count; 

    for(int i=start;i&lt;=end;i++)
    {

        printf("%02d MAC: ",i);
        btutil_printBDaddress(adb_database[i].result-&gt;remote_bd_addr);
        printf("\n");
        btutil_adv_printPacketDecode(adb_database[i].data);
        printf("\n");
    }
}</pre>
<p>After finishing that block of code, I realized I had implemented almost exactly the same functionality which two different functions.  So, I decided to redo this by doing this.  Notice that it take in a adb_print_method, in other words raw bytes or decoded packet.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="c">typedef enum {
    ADB_PRINT_METHOD_BYTES,
    ADB_PRINT_METHOD_DECODE,
} adb_print_method_t;

static void adb_db_print(adb_print_method_t method,int entry)
{
    int start,end;
 
    if(entry &lt; 0)
    {
        start = 0;
        end = adb_db_count;
    }
    else
    {
        start = entry;
        end = entry;
    }

    if(end&gt;adb_db_count)
        end = adb_db_count; 

    for(int i=start;i&lt;=end;i++)
    {
    
        printf("%02d MAC: ",i);
        btutil_printBDaddress(adb_database[i].result-&gt;remote_bd_addr);
        switch(method)
        {
        
        case ADB_PRINT_METHOD_BYTES:
            printf(" Data: ");
            btutil_adv_printPacketBytes(adb_database[i].data);
        break;

        case ADB_PRINT_METHOD_DECODE:
            printf("\n");
            btutil_adv_printPacketDecode(adb_database[i].data);
        break;
        } 
        printf("\n");
    }
}
</pre>
<p>I don&#8217;t show it here, but after changing this I had to fix up the function calls in several places in the advDatabase.</p>
<h1>Add a new command to print decode packets</h1>
<p>Now that I have a new method to print packets, I add a command to the database to allow the user to call it:</p>
<pre class="EnlighterJSRAW" data-enlighter-language="c">typedef enum {
    ADB_ADD,
    ADB_PRINT_RAW,
    ADB_PRINT_DECODE,
} adb_cmd_t;
</pre>
<p>Then in the queue loop:</p>
<pre class="EnlighterJSRAW" data-enlighter-language="c">switch(msg.cmd)
            {
                case ADB_ADD:
                    scan_result = (wiced_bt_ble_scan_results_t *)msg.data0;
                    data = (uint8_t *)msg.data1;
                    adb_db_add(scan_result,data);
                break;
                case ADB_PRINT_RAW:
                    adb_db_print(ADB_PRINT_METHOD_BYTES,(int)msg.data0);
                break;
                case ADB_PRINT_DECODE:
                    adb_db_print(ADB_PRINT_METHOD_DECODE,(int)msg.data0);
                break;
            }</pre>
<p>Then the actual function</p>
<pre class="EnlighterJSRAW" data-enlighter-language="c">void adb_printDecode(int entry)
{
    adb_cmdMsg_t msg;
    msg.cmd = ADB_PRINT_DECODE;
    msg.data0 = (void *)entry;
    xQueueSend(adb_cmdQueue,&amp;msg,0); // If the queue is full... oh well
}</pre>
<p>Then add it to advDatabase.h</p>
<pre class="EnlighterJSRAW" data-enlighter-language="c">void adb_printDecode(int entry);
</pre>
<p>Finally to the usercmd.c</p>
<pre class="EnlighterJSRAW" data-enlighter-language="c">static int usrcmd_printDecode(int argc, char **argv)
{
    if(argc == 1)
    {
        adb_printDecode(-1);
    }

    if(argc == 2)
    {
        int val;
        sscanf(argv[1],"%d",&amp;val);
        adb_printDecode(val);
    }
    return 0;
}</pre>
<h1>Program and Test</h1>
<p>When I actually program the scanner you can see that I can print out 1 item.  OR I can decode one item.  Notice that one contains 3 fields</p>
<ul>
<li>flags</li>
<li>Tx Power Level</li>
<li>Manufacturers data.  Apparently an Apple something or the other</li>
</ul>
<p><a href="https://iotexpert.com/anycloud-bluetooth-advertising-scanner-part-6/screen-shot-2020-11-09-at-7-53-43-am/" rel="attachment wp-att-10211"><img loading="lazy" decoding="async" src="https://iotexpert.com/wp-content/uploads/2020/11/Screen-Shot-2020-11-09-at-7.53.43-AM-1024x219.png" alt="" class="alignnone size-large wp-image-10211" width="1024" height="219" srcset="https://iotexpert.com/wp-content/uploads/2020/11/Screen-Shot-2020-11-09-at-7.53.43-AM-1024x219.png 1024w, https://iotexpert.com/wp-content/uploads/2020/11/Screen-Shot-2020-11-09-at-7.53.43-AM-300x64.png 300w, https://iotexpert.com/wp-content/uploads/2020/11/Screen-Shot-2020-11-09-at-7.53.43-AM-768x164.png 768w, https://iotexpert.com/wp-content/uploads/2020/11/Screen-Shot-2020-11-09-at-7.53.43-AM-600x128.png 600w, https://iotexpert.com/wp-content/uploads/2020/11/Screen-Shot-2020-11-09-at-7.53.43-AM.png 1358w" sizes="auto, (max-width: 1024px) 100vw, 1024px" /></a></p>
<p>And I can print the whole table</p>
<p><a href="https://iotexpert.com/anycloud-bluetooth-advertising-scanner-part-6/screen-shot-2020-11-09-at-7-51-10-am/" rel="attachment wp-att-10213"><img loading="lazy" decoding="async" src="https://iotexpert.com/wp-content/uploads/2020/11/Screen-Shot-2020-11-09-at-7.51.10-AM-1024x629.jpg" alt="" class="alignnone size-large wp-image-10213" width="1024" height="629" srcset="https://iotexpert.com/wp-content/uploads/2020/11/Screen-Shot-2020-11-09-at-7.51.10-AM-1024x629.jpg 1024w, https://iotexpert.com/wp-content/uploads/2020/11/Screen-Shot-2020-11-09-at-7.51.10-AM-300x184.jpg 300w, https://iotexpert.com/wp-content/uploads/2020/11/Screen-Shot-2020-11-09-at-7.51.10-AM-768x472.jpg 768w, https://iotexpert.com/wp-content/uploads/2020/11/Screen-Shot-2020-11-09-at-7.51.10-AM-1536x944.jpg 1536w, https://iotexpert.com/wp-content/uploads/2020/11/Screen-Shot-2020-11-09-at-7.51.10-AM-2048x1259.jpg 2048w, https://iotexpert.com/wp-content/uploads/2020/11/Screen-Shot-2020-11-09-at-7.51.10-AM-600x369.jpg 600w" sizes="auto, (max-width: 1024px) 100vw, 1024px" /></a></p>
<p>Or decode the whole table.</p>
<p><a href="https://iotexpert.com/anycloud-bluetooth-advertising-scanner-part-6/screen-shot-2020-11-09-at-7-51-33-am/" rel="attachment wp-att-10212"><img loading="lazy" decoding="async" src="https://iotexpert.com/wp-content/uploads/2020/11/Screen-Shot-2020-11-09-at-7.51.33-AM-1024x633.jpg" alt="" class="alignnone size-large wp-image-10212" width="1024" height="633" srcset="https://iotexpert.com/wp-content/uploads/2020/11/Screen-Shot-2020-11-09-at-7.51.33-AM-1024x633.jpg 1024w, https://iotexpert.com/wp-content/uploads/2020/11/Screen-Shot-2020-11-09-at-7.51.33-AM-300x185.jpg 300w, https://iotexpert.com/wp-content/uploads/2020/11/Screen-Shot-2020-11-09-at-7.51.33-AM-768x475.jpg 768w, https://iotexpert.com/wp-content/uploads/2020/11/Screen-Shot-2020-11-09-at-7.51.33-AM-1536x949.jpg 1536w, https://iotexpert.com/wp-content/uploads/2020/11/Screen-Shot-2020-11-09-at-7.51.33-AM-2048x1266.jpg 2048w, https://iotexpert.com/wp-content/uploads/2020/11/Screen-Shot-2020-11-09-at-7.51.33-AM-600x371.jpg 600w" sizes="auto, (max-width: 1024px) 100vw, 1024px" /></a></p>
<p>&nbsp;</p>
]]></content:encoded>
					
					<wfw:commentRss>https://iotexpert.com/anycloud-bluetooth-advertising-scanner-part-6/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>AnyCloud Bluetooth Advertising Scanner (Part 5)</title>
		<link>https://iotexpert.com/anycloud-bluetooth-advertising-scanner-part-5/</link>
					<comments>https://iotexpert.com/anycloud-bluetooth-advertising-scanner-part-5/#respond</comments>
		
		<dc:creator><![CDATA[Alan Hawse]]></dc:creator>
		<pubDate>Mon, 23 Nov 2020 18:03:57 +0000</pubDate>
				<category><![CDATA[4343W]]></category>
		<category><![CDATA[AnyCloud]]></category>
		<category><![CDATA[AnyCloud Advertising Scanner]]></category>
		<category><![CDATA[Bluetooth]]></category>
		<category><![CDATA[CY8CKIT-062-WiFi-BT]]></category>
		<category><![CDATA[CY8CKIT-062S2-43012]]></category>
		<category><![CDATA[CY8CPROTO-062-4343W]]></category>
		<category><![CDATA[PSoC 6]]></category>
		<guid isPermaLink="false">https://iotexpert.com/?p=10196</guid>

					<description><![CDATA[Summary In this article I will add a new task to the AnyCloud BLE Advertising Scanning application which will save the advertising data into a database. Story There is still a boatload of mostly unintelligible advertising data coming ripping onto our screen.  It is FINALLY time to start fixing that.  In this article I will [&#8230;]]]></description>
										<content:encoded><![CDATA[<h1>Summary</h1>
<p>In this article I will add a new task to the AnyCloud BLE Advertising Scanning application which will save the advertising data into a database.</p>
<h1>Story</h1>
<p>There is still a boatload of mostly unintelligible advertising data coming ripping onto our screen.  It is FINALLY time to start fixing that.  In this article I will create a new task called the advertising database task which will hold the history of advertising packets that I have seen.  I will update the Bluetooth Manager task to submit the advertising packets to a queue running in the advertising database task.</p>
<p>There are</p>
<p><div class="table-responsive"><table  style="width:95%; "  class="easy-table easy-table-default " border="1">
<thead>
<tr><th >Article</th>
<th >Topic</th>
</tr>
</thead>
<tbody>
<tr><td ><a href="https://iotexpert.com/anycloud-bluetooth-advertising-scanner-part-1/" target="_blank" rel="noopener">AnyCloud Bluetooth Advertising Scanner (Part 1)</a></td>
<td >Introduction to AnyCloud Bluetooth Advertising</td>
</tr>

<tr><td ><a href="https://iotexpert.com/anycloud-bluetooth-advertising-scanner-part-2/" target="_blank" rel="noopener">AnyCloud Bluetooth Advertising Scanner (Part 2)</a></td>
<td >Creating an AnyCloud Bluetooth project</td>
</tr>

<tr><td ><a href="https://iotexpert.com/anycloud-bluetooth-advertising-scanner-part-3/" target="_blank" rel="noopener">AnyCloud Bluetooth Advertising Scanner (Part 3)</a></td>
<td >Adding Observing functionality to the project</td>
</tr>

<tr><td ><a class="row-title" href="https://iotexpert.com/anycloud-bluetooth-utilities-library/" aria-label="“AnyCloud Bluetooth Utilities Library” (Edit)" target="_blank" rel="noopener">AnyCloud Bluetooth Utilities Library</a></td>
<td >A set of APIs for enhancement of the AnyCloud Library</td>
</tr>

<tr><td ><a href="https://iotexpert.com/anycloud-bluetooth-advertising-scanner-part-4/" target="_blank" rel="noopener">AnyCloud Bluetooth Advertising Scanner (Part 4)</a></td>
<td >Adding a command line to the scanner</td>
</tr>

<tr><td ><a href="https://iotexpert.com/anycloud-bluetooth-advertising-scanner-part-5/" target="_blank" rel="noopener">AnyCloud Bluetooth Advertising Scanner (Part 5)</a></td>
<td >Adding a history database to the scanner</td>
</tr>

<tr><td ><a href="https://iotexpert.com/anycloud-bluetooth-advertising-scanner-part-6/" target="_blank" rel="noopener">AnyCloud Bluetooth Advertising Scanner (Part 6)</a></td>
<td >Decoding advertising packets</td>
</tr>

<tr><td ><a href="https://iotexpert.com/anycloud-bluetooth-advertising-scanner-part-7/" target="_blank" rel="noopener">AnyCloud Bluetooth Advertising Scanner (Part 7)</a></td>
<td >Adding recording commands to the command line</td>
</tr>

<tr><td ><a href="https://iotexpert.com/anycloud-bluetooth-advertising-scanner-part-8/">AnyCloud Bluetooth Advertising Scanner (Part 8)</a></td>
<td >Adding filtering to the scanner</td>
</tr>

<tr><td ><a href="https://iotexpert.com/anycloud-bluetooth-advertising-scanner-part-9/">AnyCloud Bluetooth Advertising Scanner (Part 9)</a></td>
<td >Improve the print and add packet age</td>
</tr>

<tr><td ><a href="https://iotexpert.com/anycloud-bluetooth-advertising-scanner-part-10/">AnyCloud Bluetooth Advertising Scanner (Part 10)</a></td>
<td >Sort the database</td>
</tr>
</tbody></table></div></p>
<p>All of the code can be found at git@github.com:iotexpert/AnyCloudBLEScanner.git and https://github.com/iotexpert/AnyCloudBLEScanner.git</p>
<p>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.</p>
<p>You can also create a new project with this is a template if you have the IoT Expert Manifest Files installed</p>
<h1>Create an Advertising Data Database Task</h1>
<p>We need to create the file advertisingDatabase.h which will hold the task prototype (so that main can get going).</p>
<pre class="EnlighterJSRAW" data-enlighter-language="c">#pragma once

void adb_task(void *arg);
</pre>
<p>Then create the advertisingDatabase.c to hold the actual database code.  It will start with the definition of messages which can be sent to the task.  For now just &#8220;ADB_ADD&#8221;.  To make things a little bit simpler these command can have two data elements (which I call data0 and data1).  Then the main part of the task just</p>
<ol>
<li>Creates the queue to manage the messages</li>
<li>Process the message until the end of time</li>
</ol>
<pre class="EnlighterJSRAW" data-enlighter-language="c">#include "FreeRTOS.h"
#include "queue.h"

static QueueHandle_t adb_cmdQueue;
typedef enum {
    ADB_ADD,
} adb_cmd_t;

typedef struct
{
    adb_cmd_t cmd;
    void *data0;
    void *data1;
} adb_cmdMsg_t;

void adb_task(void *arg)
{
    // setup the queue
    adb_cmdMsg_t msg;

    adb_cmdQueue = xQueueCreate(10,sizeof(adb_cmdMsg_t));
    
    while(1)
    {
        BaseType_t status = xQueueReceive(adb_cmdQueue,&amp;msg,portMAX_DELAY);
        if(status == pdTRUE) 
        {
            switch(msg.cmd)
            {
                case ADB_ADD:
                break;
            }

        }
    }
}
</pre>
<p>To start the task, you need to add it to main.c.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="c">    xTaskCreate(adb_task,"adv database",configMINIMAL_STACK_SIZE*4,0,1,0);
</pre>
<p>When I build and program this, you can now see the new task.  Good that working.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="c">AnyCloud&gt; Unhandled Bluetooth Management Event: BTM_LOCAL_IDENTITY_KEYS_REQUEST_EVT
Started BT Stack Succesfully

AnyCloud&gt; tasks
Name          State Priority   Stack  Num
------------------------------------------
usrcmd_ta       X       0       228     5
IDLE            R       0       115     7
Tmr Svc         B       0       223     8
CYBT_HCI_       B       5       950     3
sleep_tas       B       6       221     1
CYBT_BT_T       B       4       1371    2
blinkTask       B       0       98      4
adv datab       B       1       479     6
‘B’ – Blocked
‘R’ – Ready
‘D’ – Deleted (waiting clean up)
‘S’ – Suspended, or Blocked without a timeout
Stack = bytes free at highwater
AnyCloud&gt;</pre>
<h1>Update the Advertising Database to Accept Submitted ADV Packets</h1>
<p>If you recall our original setup was to take advertising packets in the Bluetooth Manager thread and print out the data.  The first thing that we want to fix up is the ability of the advertising database task to accept advertising packets which are pushed to its command queue.   To prepare for this I create two local variables to hold the data.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="c">void adb_task(void *arg)
{
    // setup the queue
    adb_cmdMsg_t msg;
    wiced_bt_ble_scan_results_t *scan_result;
    uint8_t *data;</pre>
<p>Then I update the ADB_ADD command.  My first, and really simple fix, is to grab the printing code from the Bluetooth Manager task.  Obviously this won&#8217;t be an improvement from the original program as far as the users goes, but it will verify that the tasks are working properly together.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="c">                case ADB_ADD:
                    // Print the MAC Address
                    scan_result = (wiced_bt_ble_scan_results_t *)msg.data0;
                    data = (uint8_t *)msg.data1;

                    printf("MAC: ");
                    for(int i=0;i&lt;BD_ADDR_LEN;i++)
                    {
                        printf("%02X:",scan_result-&gt;remote_bd_addr[i]);
                    }
                    // Print the RAW Data of the ADV Packet
                    printf(" Data: ");
                    int i=0;
                    while(data[i])
                    {
                        for(int j=0;j&lt;data[i];j++)
                        {
                            printf("%02X ",data[i+1+j]);
                        }
                        i = i + data[i]+1;
                    }
                    printf("\n");
    
                    free(msg.data0);
                    free(msg.data1);
                break;
</pre>
<p>Then I add a command to the advertisingDatabase.h which the Bluetooth Manager task can call to submit advertising packets</p>
<pre class="EnlighterJSRAW" data-enlighter-language="c">void adb_addAdv(wiced_bt_ble_scan_results_t *scan_result,void *data);</pre>
<p>The actual command in advertisingDatabase.c just takes the advertising information, puts it in a command message, then submits it to the command queue.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="c">void adb_addAdv(wiced_bt_ble_scan_results_t *scan_result,void *data)
{
    adb_cmdMsg_t msg;
    msg.cmd = ADB_ADD;
    msg.data0 = (void *)scan_result;
    msg.data1 = (void *)data;
    xQueueSend(adb_cmdQueue,&amp;msg,0); // If you loose an adv packet it is OK...
}
</pre>
<h1>Update the Bluetooth Manager to Submit Adv Packets</h1>
<p>Now I go and edit the bluetoothManager. c to submit packets rather than print them.  To do this I greatly simplify the callback.  There is one VERY important issue to deal with, which is one of those potential religious war issues.  Memory.</p>
<p>When you get the callback from the stack, it gives you POINTERS to data for the advertising packet that reside inside of buffers inside of the stack.  As soon as this callback returns this memory is purged.  To prevent this data from getting cleaned up by the stack I</p>
<ol>
<li>Malloc some memory for the wiced_bt_ble_scan_results</li>
<li>Malloc some memory for the advertising data</li>
<li>Make a copy of the data</li>
<li>Submit it to the Advertising Database</li>
</ol>
<p>I KNOW from the spec that the largest data packet is 31-bytes (actually it is 31-bytes + one more field with length 0).  So I know the maximum length is 32-bytes  This means that in many situations I will be copying GARBAGE into my buffer if the packet is less than 32 bytes long.  I think that this is simpler than calculating the length and then only copying that much data.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="c">void btm_advCallback(wiced_bt_ble_scan_results_t *p_scan_result, uint8_t *p_adv_data)
{
    wiced_bt_ble_scan_results_t *scan_result = malloc(sizeof(wiced_bt_ble_scan_results_t));
    uint8_t *data = malloc(32);
   
    memcpy(data,p_adv_data,32);
    memcpy(scan_result,p_scan_result-&gt;remote_bd_addr,BD_ADDR_LEN);
    adb_addAdv(scan_result,data);
}
</pre>
<p>When I run this updated program I should get the same stream of data coming out on the serial port.  Sure enough the new thread is working.</p>
<p><a href="https://iotexpert.com/anycloud-bluetooth-advertising-scanner-part-5/screen-shot-2020-11-07-at-10-23-16-am/" rel="attachment wp-att-10198"><img loading="lazy" decoding="async" src="https://iotexpert.com/wp-content/uploads/2020/11/Screen-Shot-2020-11-07-at-10.23.16-AM-1024x577.png" alt="" width="1024" height="577" class="alignnone size-large wp-image-10198" srcset="https://iotexpert.com/wp-content/uploads/2020/11/Screen-Shot-2020-11-07-at-10.23.16-AM-1024x577.png 1024w, https://iotexpert.com/wp-content/uploads/2020/11/Screen-Shot-2020-11-07-at-10.23.16-AM-300x169.png 300w, https://iotexpert.com/wp-content/uploads/2020/11/Screen-Shot-2020-11-07-at-10.23.16-AM-768x433.png 768w, https://iotexpert.com/wp-content/uploads/2020/11/Screen-Shot-2020-11-07-at-10.23.16-AM-1536x865.png 1536w, https://iotexpert.com/wp-content/uploads/2020/11/Screen-Shot-2020-11-07-at-10.23.16-AM-600x338.png 600w, https://iotexpert.com/wp-content/uploads/2020/11/Screen-Shot-2020-11-07-at-10.23.16-AM.png 1868w" sizes="auto, (max-width: 1024px) 100vw, 1024px" /></a></p>
<h1>Create an Advertising Data Database</h1>
<p>Now, lets create an actual database.  To simplify things my database is just an array of structures.  One structure per bluetooth device.  The structure will contain a pointer to the information about the device it just saw and the actual raw data.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="c">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];
int adb_db_count=0;
</pre>
<p>Then I will create several helper functions to work with the database</p>
<ol>
<li>Find devices in the database given a mac address</li>
<li>Print an entry in the database</li>
<li>Add entries to the database</li>
</ol>
<p>First, find an entry in the database.  This function will search through the database and compare the mac address against the mac address in the database.  When the memcmp ==0 meaning it found a match, it will return that entry.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="c" ">static int adb_db_find(wiced_bt_device_address_t *add)
{
    int rval=-1;
    for(int i=0;i&lt;adb_db_count;i++)
    {
        if(memcmp(add,&amp;adb_database[i].result-&gt;remote_bd_addr,BD_ADDR_LEN)==0)
        {
            rval = i;
            break;
        }
    }
    return rval;
}</pre>
<p>The print function will make sure that you asked for a legal entry (much must be greater than 0&#8230; and less than the max).  Then it will print out the mac address and the raw data.  In a future post I will add a smarter print out.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="c">static void adb_db_printEntry(int entry)
{
    if(!(entry&gt;= 0 &amp;&amp; entry &lt;= adb_db_count))
    {
        printf("Illegal entry\n");
        return;
    }
    printf("%02d MAC: ",entry);

    for(int i=0;i&lt;BD_ADDR_LEN;i++)
    {
        printf("%02X:",adb_database[entry].result-&gt;remote_bd_addr[i]);
    }

    // Print the RAW Data of the ADV Packet
    printf(" Data: ");
    int i=0;
    while(adb_database[entry].data[i])
    {
        for(int j=0;j&lt;adb_database[entry].data[i];j++)
        {
            printf("%02X ",adb_database[entry].data[i+1+j]);
        }
        i = i + adb_database[entry].data[i]+1;
    }
    printf("\n");
}</pre>
<p>To add an entry to the database, first make sure that it isn&#8217;t already in the database.  Then when you are sure that it isn&#8217;t the database, you just add the pointers to your table.  You need to make sure and not go beyond the end of the table, and if you did, you will have effectively blown away the last entry in the table.  Oh well.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="c">static void adb_db_add(wiced_bt_ble_scan_results_t *scan_result,uint8_t *data)
{
 
    int entry = adb_db_find(&amp;scan_result-&gt;remote_bd_addr);
    if(entry == -1)
    {
        
        adb_database[adb_db_count].result = scan_result;
        adb_database[adb_db_count].data = data;
        adb_db_printEntry(adb_db_count);
        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
    {
        free(scan_result);
        free(data);
    }
}
</pre>
<h1>Add a Command to Print the Database</h1>
<p>Now we want to add the ability to print from the command line.  So add a new command message to the list of legal commands.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="c">typedef enum {
    ADB_ADD,
    ADB_PRINT,
} adb_cmd_t;
</pre>
<p>Then create a new function to print.  If you send in a &#8220;-1&#8221; it will print the whole table.  Otherwise just print the individual entry.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="c" ">static void adb_printTable(int entry)
{
    if(entry == -1)
    {
        for(int i=0;i&lt;adb_db_count;i++)
        {
            adb_db_printEntry(i);
        }

    }
    else
    {
        adb_db_printEntry(entry);
    }
    

}</pre>
<p>Now edit usercmd.c to have the new command line.  Notice that I use &#8220;sscanf&#8221; which obviously has some issues.  Too bad.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="c" ">static int usrcmd_print(int argc, char **argv)
{

    if(argc == 1)
    {
        adb_print(-1); // Print whole table
    }

    if(argc == 2)
    {
        int val;
        sscanf(argv[1],"%d",&amp;val);
        adb_print(val);
    }

    return 0;
}</pre>
<p>When I program the project it immediately prints out a bunch of devices that are at my house.  Then you can see I run the &#8220;print&#8221; command which prints the table.  Finally P do a print 0 to just print the first entry.</p>
<p><a href="https://iotexpert.com/anycloud-bluetooth-advertising-scanner-part-5/screen-shot-2020-11-08-at-9-34-13-am/" rel="attachment wp-att-10201"><img loading="lazy" decoding="async" src="https://iotexpert.com/wp-content/uploads/2020/11/Screen-Shot-2020-11-08-at-9.34.13-AM-1024x782.jpg" alt="" width="1024" height="782" class="alignnone size-large wp-image-10201" srcset="https://iotexpert.com/wp-content/uploads/2020/11/Screen-Shot-2020-11-08-at-9.34.13-AM-1024x782.jpg 1024w, https://iotexpert.com/wp-content/uploads/2020/11/Screen-Shot-2020-11-08-at-9.34.13-AM-300x229.jpg 300w, https://iotexpert.com/wp-content/uploads/2020/11/Screen-Shot-2020-11-08-at-9.34.13-AM-768x587.jpg 768w, https://iotexpert.com/wp-content/uploads/2020/11/Screen-Shot-2020-11-08-at-9.34.13-AM-1536x1173.jpg 1536w, https://iotexpert.com/wp-content/uploads/2020/11/Screen-Shot-2020-11-08-at-9.34.13-AM-600x458.jpg 600w, https://iotexpert.com/wp-content/uploads/2020/11/Screen-Shot-2020-11-08-at-9.34.13-AM.jpg 1864w" sizes="auto, (max-width: 1024px) 100vw, 1024px" /></a></p>
<p>In the next article I will add smarter diagnostics to the advertising packets.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://iotexpert.com/anycloud-bluetooth-advertising-scanner-part-5/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>AnyCloud Bluetooth Advertising Scanner (Part 4)</title>
		<link>https://iotexpert.com/anycloud-bluetooth-advertising-scanner-part-4/</link>
					<comments>https://iotexpert.com/anycloud-bluetooth-advertising-scanner-part-4/#respond</comments>
		
		<dc:creator><![CDATA[Alan Hawse]]></dc:creator>
		<pubDate>Mon, 16 Nov 2020 13:00:10 +0000</pubDate>
				<category><![CDATA[AnyCloud]]></category>
		<category><![CDATA[AnyCloud Advertising Scanner]]></category>
		<category><![CDATA[Bluetooth]]></category>
		<category><![CDATA[CY8CKIT-062-WiFi-BT]]></category>
		<category><![CDATA[CY8CKIT-062S2-43012]]></category>
		<category><![CDATA[CY8CPROTO-062-4343W]]></category>
		<guid isPermaLink="false">https://iotexpert.com/?p=10185</guid>

					<description><![CDATA[Summary In this article I update the AnyCloud BLE advertising scanner to use the btutil library that was created in the previous post.  In addition, I add a command queue to the bluetoothManger and enable a new command to turn on and off scanning. Story If you have been following along until now, which I [&#8230;]]]></description>
										<content:encoded><![CDATA[<h1>Summary</h1>
<p>In this article I update the AnyCloud BLE advertising scanner to use the btutil library that was created in the <a href="https://iotexpert.com/anycloud-bluetooth-utilities-library/" target="_blank" rel="noopener noreferrer">previous post</a>.  In addition, I add a command queue to the bluetoothManger and enable a new command to turn on and off scanning.</p>
<h1>Story</h1>
<p>If you have been following along until now, which I imagine that you have if you are reading this,  you will have gotten a vomit of device data blasting out onto your serial console.  This isn&#8217;t very helpful.  So now what?  I am going to divide this problem into two parts</p>
<ol>
<li>Creating a new user command to turn on and off scanning (this article)</li>
<li>Creating a database to manage the data + a set of commands to dump it (next article)</li>
</ol>
<p>There are</p>
<p><div class="table-responsive"><table  style="width:95%; "  class="easy-table easy-table-default " border="1">
<thead>
<tr><th >Article</th>
<th >Topic</th>
</tr>
</thead>
<tbody>
<tr><td ><a href="https://iotexpert.com/anycloud-bluetooth-advertising-scanner-part-1/" target="_blank" rel="noopener">AnyCloud Bluetooth Advertising Scanner (Part 1)</a></td>
<td >Introduction to AnyCloud Bluetooth Advertising</td>
</tr>

<tr><td ><a href="https://iotexpert.com/anycloud-bluetooth-advertising-scanner-part-2/" target="_blank" rel="noopener">AnyCloud Bluetooth Advertising Scanner (Part 2)</a></td>
<td >Creating an AnyCloud Bluetooth project</td>
</tr>

<tr><td ><a href="https://iotexpert.com/anycloud-bluetooth-advertising-scanner-part-3/" target="_blank" rel="noopener">AnyCloud Bluetooth Advertising Scanner (Part 3)</a></td>
<td >Adding Observing functionality to the project</td>
</tr>

<tr><td ><a class="row-title" href="https://iotexpert.com/anycloud-bluetooth-utilities-library/" aria-label="“AnyCloud Bluetooth Utilities Library” (Edit)" target="_blank" rel="noopener">AnyCloud Bluetooth Utilities Library</a></td>
<td >A set of APIs for enhancement of the AnyCloud Library</td>
</tr>

<tr><td ><a href="https://iotexpert.com/anycloud-bluetooth-advertising-scanner-part-4/" target="_blank" rel="noopener">AnyCloud Bluetooth Advertising Scanner (Part 4)</a></td>
<td >Adding a command line to the scanner</td>
</tr>

<tr><td ><a href="https://iotexpert.com/anycloud-bluetooth-advertising-scanner-part-5/" target="_blank" rel="noopener">AnyCloud Bluetooth Advertising Scanner (Part 5)</a></td>
<td >Adding a history database to the scanner</td>
</tr>

<tr><td ><a href="https://iotexpert.com/anycloud-bluetooth-advertising-scanner-part-6/" target="_blank" rel="noopener">AnyCloud Bluetooth Advertising Scanner (Part 6)</a></td>
<td >Decoding advertising packets</td>
</tr>

<tr><td ><a href="https://iotexpert.com/anycloud-bluetooth-advertising-scanner-part-7/" target="_blank" rel="noopener">AnyCloud Bluetooth Advertising Scanner (Part 7)</a></td>
<td >Adding recording commands to the command line</td>
</tr>

<tr><td ><a href="https://iotexpert.com/anycloud-bluetooth-advertising-scanner-part-8/">AnyCloud Bluetooth Advertising Scanner (Part 8)</a></td>
<td >Adding filtering to the scanner</td>
</tr>

<tr><td ><a href="https://iotexpert.com/anycloud-bluetooth-advertising-scanner-part-9/">AnyCloud Bluetooth Advertising Scanner (Part 9)</a></td>
<td >Improve the print and add packet age</td>
</tr>

<tr><td ><a href="https://iotexpert.com/anycloud-bluetooth-advertising-scanner-part-10/">AnyCloud Bluetooth Advertising Scanner (Part 10)</a></td>
<td >Sort the database</td>
</tr>
</tbody></table></div></p>
<p>All of the code can be found at git@github.com:iotexpert/AnyCloudBLEScanner.git and https://github.com/iotexpert/AnyCloudBLEScanner.git</p>
<p>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.</p>
<p>You can also create a new project with this is a template if you have the IoT Expert Manifest Files installed</p>
<h1>Add the IoT Expert &#8220;btutil&#8221; Library</h1>
<p>Before we actually start all of the command queue stuff, lets move to the btutil library that I talked about in the previous post.  To do this, add the library using the library manager.</p>
<p><a href="https://iotexpert.com/anycloud-bluetooth-advertising-scanner-part-4/screen-shot-2020-11-02-at-1-50-08-pm/" rel="attachment wp-att-10187"><img loading="lazy" decoding="async" src="https://iotexpert.com/wp-content/uploads/2020/11/Screen-Shot-2020-11-02-at-1.50.08-PM-1024x197.png" alt="" width="1024" height="197" class="alignnone size-large wp-image-10187" srcset="https://iotexpert.com/wp-content/uploads/2020/11/Screen-Shot-2020-11-02-at-1.50.08-PM-1024x197.png 1024w, https://iotexpert.com/wp-content/uploads/2020/11/Screen-Shot-2020-11-02-at-1.50.08-PM-300x58.png 300w, https://iotexpert.com/wp-content/uploads/2020/11/Screen-Shot-2020-11-02-at-1.50.08-PM-768x148.png 768w, https://iotexpert.com/wp-content/uploads/2020/11/Screen-Shot-2020-11-02-at-1.50.08-PM-600x115.png 600w, https://iotexpert.com/wp-content/uploads/2020/11/Screen-Shot-2020-11-02-at-1.50.08-PM.png 1072w" sizes="auto, (max-width: 1024px) 100vw, 1024px" /></a></p>
<p>Then delete bt_platform_cfg_settings.h and <span>bt_platform_cfg_settings.c from your project.  Finally </span>Rebuild and make sure that everything still works.  That is it.</p>
<h1>Multithreading</h1>
<p>Id like to explain that there is now some danger.  That danger comes from the fact that we have multiple tasks which are all accessing data plus functions that are talking to each other ASYNCHRONOUSLY.  Specifically we have:</p>
<ol>
<li>The Bluetooth Stack task &#8211; running the Bluetooth stack and management callback</li>
<li>The Bluetooth Stack APIs &#8211; e.g. wiced_bt_ble_observe</li>
<li>The usrcmd task &#8211; which is interacting with the user on the serial port and talking to the other tasks</li>
<li>A timer_svc task &#8211; which runs software timers</li>
<li>The advertising data (which I will start saving in the next article)</li>
</ol>
<p>When faced with this situation what I typically like to do is provide thread safe public functions for each of the tasks.  Then any other task can call these functions and know that things are not going to get corrupted by a race condition.</p>
<p>To make the design thread safe, I typically like to put an RTOS Queue between the tasks.  These queues are a safe place to send and receive data in a &#8220;thread safe&#8221; way.  There are two basic design patterns that can be used</p>
<ol>
<li>Define a message structure (that gets pushed into the queue) and make it global (via a dot-h).  Define a queue handle and make it global (via a dot-h).  Then let any task build messages and push them into the queue to be received in the task that owns the queue.</li>
<li>Define the message structure and queue.  Then define functions which are global (via a dot-h) which know how to interact with the queue.</li>
</ol>
<p>I typically think that the 2nd method is better, so that is what I am going to do here.</p>
<ol>
<li>In BluetoothManager.h I will provide a function called &#8220;btm_cmdScan&#8221;</li>
<li>The usrcmd task will call the btm_cmdScan function which will</li>
<li>Create a btm_cmdMsg_t with the &#8220;scan&#8221; command and data of true/false</li>
<li>Then push it into the Bluetooth Manager Command Queue</li>
<li>Where a timer callback in the Bluetooth Manager Task will take it out of the queue</li>
<li>Figure out that it is a &#8220;scan&#8221; command</li>
<li>Then will either turn on or off scanning</li>
</ol>
<p><a href="https://iotexpert.com/anycloud-bluetooth-advertising-scanner-part-4/cmdmsg/" rel="attachment wp-att-10194"><img loading="lazy" decoding="async" src="https://iotexpert.com/wp-content/uploads/2020/11/cmdMsg-1024x140.png" alt="" width="1024" height="140" class="alignnone size-large wp-image-10194" srcset="https://iotexpert.com/wp-content/uploads/2020/11/cmdMsg-1024x140.png 1024w, https://iotexpert.com/wp-content/uploads/2020/11/cmdMsg-300x41.png 300w, https://iotexpert.com/wp-content/uploads/2020/11/cmdMsg-768x105.png 768w, https://iotexpert.com/wp-content/uploads/2020/11/cmdMsg-600x82.png 600w, https://iotexpert.com/wp-content/uploads/2020/11/cmdMsg.png 1182w" sizes="auto, (max-width: 1024px) 100vw, 1024px" /></a></p>
<h1>Add a Queue to the Bluetooth Manager Thread</h1>
<p>So we need two things a message to push into a queue (just a structure) and we need a queue to push it into.  First the message which is just a structure with two elements.  The first element is a command and the second element is some data of type void.  The meaning of the void *data will be different based on the command.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="c">typedef struct {
	btm_cmd_t cmd;
	void *data;
} btm_cmdMsg_t;</pre>
<p>But how about the command?  The command is just an enumerate list of commands which will now start with just one command.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="c">typedef enum {
	BTM_SCAN,
} btm_cmd_t;
</pre>
<p>And know we need to define the queue.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="c">#include "queue.h"
static QueueHandle_t btm_cmdQueue;</pre>
<p>Before you can use the queue you need to initialize it.  The best place to initialize this queue is in the management callback right after the stack gets going.  You can see that I tell FreeRTOS that there is a queue which can hold up to 10 commands.  I also tell it that each command is the sizeof the command message.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="c">    switch (event)
    {
        case BTM_ENABLED_EVT:
            printf("Started BT Stack Succesfully\n");
            btm_cmdQueue = xQueueCreate(10,sizeof(btm_cmdMsg_t));</pre>
<p>Now we need to create a way for other tasks to create these command messages.  They will do this by calling a function which we will define in the bluetoothManager.h</p>
<pre class="EnlighterJSRAW" data-enlighter-language="c">void btm_cmdScan(bool enable);
</pre>
<p>This function will live in bluetoothManager.c and it simply</p>
<ol>
<li>Creates a command</li>
<li>Set the actual command to scan</li>
<li>Sets the void* data to be enable &#8230; in other words start or stop scanning.  Remember that a void * can be anything.  See I cast a bool to a void *</li>
<li>Finally push the data into the command queue</li>
</ol>
<pre class="EnlighterJSRAW" data-enlighter-language="c">void btm_cmdScan(bool enable)
{
    btm_cmdMsg_t msg;
    msg.cmd = BTM_SCAN;
    msg.data = (void *)enable;
  	xQueueSend(btm_cmdQueue, &amp;msg,0);
}</pre>
<h1>Add a Timer to Process the Queue</h1>
<p>So now we have a method to push items into the queue.  How do we get them out of the queue?  To do that I will use a Bluetooth Stack timer that will run every 50ms.</p>
<p>First, define the timer in bluetoothManager.c</p>
<pre class="EnlighterJSRAW" data-enlighter-language="c">#include "wiced_timer.h"
static wiced_timer_ext_t btm_mgmtQueueTimer;
</pre>
<p>Then define a function which the timer will call.  This function will</p>
<ol>
<li>Try to get a message out of the queue</li>
<li>IF there is a message it will use a big switch to look at the possible messages</li>
<li>If the message is a scan</li>
<li>Then call the wiced function to either start &#8220;observing&#8221; or stop &#8220;observing&#8221;</li>
</ol>
<pre class="EnlighterJSRAW" data-enlighter-language="c">static void btm_processBluetoothAppQueue()
{
	btm_cmdMsg_t msg;

	 BaseType_t rval;

	 rval = xQueueReceive( btm_cmdQueue,&amp;msg,0);
	 if(rval == pdTRUE)
	 {
		 switch(msg.cmd)
		 {
		 case BTM_SCAN:
            wiced_bt_ble_observe((wiced_bool_t)msg.data,0,btm_advCallback);
			 break;
		 }
	 }
}</pre>
<p>The last thing you need to do is start the timer.  The best place to start the timer is in the management callback where you need to</p>
<ol>
<li>Create the timer</li>
<li>Tell it to start and run every 50ms</li>
</ol>
<pre class="EnlighterJSRAW" data-enlighter-language="c">    switch (event)
    {
        case BTM_ENABLED_EVT:
            printf("Started BT Stack Succesfully\n");
            btm_cmdQueue = xQueueCreate(10,sizeof(btm_cmdMsg_t));
            wiced_init_timer_ext (&amp;btm_mgmtQueueTimer, btm_processBluetoothAppQueue,0, WICED_TRUE);
            wiced_start_timer_ext (&amp;btm_mgmtQueueTimer, 50);
        break;</pre>
<h1>A Potential Threading Bug</h1>
<p>When I did the implementation originally I created what I thought was a threading bug.  Specifically I used the FreeRTOS timer to process the queue.  In other words instead of using a wiced_timer_ext_t I used a TimerHandle_t.  So what?</p>
<p>The wiced_timer_ext_t is run INSIDE of the BluetoothStack task where the TimerHandle_t is run inside of the Timer_SVC task.</p>
<p>So what?  I was afraid that the call to wiced_bt_ble_obsere was NOT thread safe and needed to be called inside of the same task as the stack.</p>
<p>After some digging I found out that the Bluetooth Stack is threadsafe, so I worried for no reason.  Well, actually, you can never worry enough about making these kinds of threading bugs because they are viscously difficult to debug.</p>
<h1>Add a Scan Off &amp; On Command</h1>
<p>The last thing that you need to do is add an actual command to the usercmd task to call the bluetooth manager function to turn on and off scanning.</p>
<p>First, add a new prototype for your new command in usercmd.c.  Then add it to the list of legal commands.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="c">static int usrcmd_scan(int argc, char **argv);


static const cmd_table_t cmdlist[] = {

.... deleted stuff

    { "scan","scan [on|off]", usrcmd_scan},

};
</pre>
<p>Then create the function to process the command line input and call the btm_scan function.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="c">static int usrcmd_scan(int argc, char **argv)
{

    if(argc != 2)
        return 0;

    if(strcmp(argv[1],"on") == 0)
    {
        btm_cmdScan(true);
    }
    else if(strcmp(argv[1],"off") == 0)
    {
        btm_cmdScan(false);

    }
    return 0;

}</pre>
<p>Now build it and run it.  You should still get adv packets barfing all over your screen.  But now you can turn on and off the scanning with &#8220;scan on&#8221; and &#8220;scan off&#8221;.  In the next article we will create a database to hold the scan packets.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://iotexpert.com/anycloud-bluetooth-advertising-scanner-part-4/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>AnyCloud Bluetooth Utilities Library</title>
		<link>https://iotexpert.com/anycloud-bluetooth-utilities-library/</link>
					<comments>https://iotexpert.com/anycloud-bluetooth-utilities-library/#respond</comments>
		
		<dc:creator><![CDATA[Alan Hawse]]></dc:creator>
		<pubDate>Mon, 09 Nov 2020 13:18:17 +0000</pubDate>
				<category><![CDATA[4343W]]></category>
		<category><![CDATA[AnyCloud]]></category>
		<category><![CDATA[Bluetooth]]></category>
		<category><![CDATA[CY8CKIT-062-BLE]]></category>
		<category><![CDATA[CY8CKIT-062-WiFi-BT]]></category>
		<category><![CDATA[CY8CKIT-062S2-43012]]></category>
		<category><![CDATA[CY8CPROTO-062-4343W]]></category>
		<category><![CDATA[PSoC 6]]></category>
		<guid isPermaLink="false">https://iotexpert.com/?p=10175</guid>

					<description><![CDATA[Summary This article is a discussion of a library of utilities functions that support AnyCloud Bluetooth development.  It includes settings to configure the hardware, functions to decode stack events, functions to decode advertising packets etc. Story The Cypress, now Infineon, Modus Toolbox team has been working to bring the WICED Bluetooth devices to be closer [&#8230;]]]></description>
										<content:encoded><![CDATA[<h1>Summary</h1>
<p>This article is a discussion of a library of utilities functions that support AnyCloud Bluetooth development.  It includes settings to configure the hardware, functions to decode stack events, functions to decode advertising packets etc.</p>
<h1>Story</h1>
<p>The Cypress, now Infineon, Modus Toolbox team has been working to bring the WICED Bluetooth devices to be closer and more compatible with the PSoC 6 tools.  One of the important enablement things we have done is turn on the WICED Bluetooth Host stack on the PSoC 6 so that it can effectively talk to the CYW43XXX Bluetooth / WiFi combo chips.</p>
<p>As I have been using all of the new stuff I found myself adding my own custom functionality&#8230;. and after a while I realized (finally) that I should put all of those little helper things into a library, specifically an IoT Expert library.  For now this library contains:</p>
<ul>
<li>The Bluetooth Platform Configuration Settings</li>
<li>Functions to decode stack events</li>
<li>Functions to decode advertising packets</li>
</ul>
<p>but imagine with time I will add more functions and templates.</p>
<h1><span>bt_platform_cfg_settings</span></h1>
<p>As I discussed in the article <a href="https://iotexpert.com/anycloud-bluetooth-advertising-scanner-part-1/" target="_blank" rel="noopener noreferrer">AnyCloud Bluetooth Advertising Scanner (Part 1)</a>, every single AnyCloud BLE Stack project will require a structure of type wiced_bt_cfg_settings_t.  This structure is used to setup the hardware before getting the stack going.  Remember you need to make a call like this to initialize the Bluetooth hardware.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="c">    cybt_platform_config_init(&amp;bt_platform_cfg_settings);
</pre>
<p>At some point this file will be included automatically for you by the Modus Toolbox team, but for now I have added this to my library.  This file look like this.  Basically a bunch of pin definitions which are set for you automatically by the BSP.  Obviously you can make your own, but this should work on all of the Cypress development kits (I think)</p>
<pre class="EnlighterJSRAW" data-enlighter-language="c">#include "cybt_platform_config.h"
#include "cybsp.h"
#include "wiced_bt_stack.h"

const cybt_platform_config_t bt_platform_cfg_settings =
{
    .hci_config =
    {
        .hci_transport = CYBT_HCI_UART,

        .hci =
        {
            .hci_uart =
            {
                .uart_tx_pin = CYBSP_BT_UART_TX,
                .uart_rx_pin = CYBSP_BT_UART_RX,
                .uart_rts_pin = CYBSP_BT_UART_RTS,
                .uart_cts_pin = CYBSP_BT_UART_CTS,

                .baud_rate_for_fw_download = 115200,
                .baud_rate_for_feature     = 115200,

                .data_bits = 8,
                .stop_bits = 1,
                .parity = CYHAL_UART_PARITY_NONE,
                .flow_control = WICED_TRUE
            }
        }
    },

    .controller_config =
    {
        .bt_power_pin      = CYBSP_BT_POWER,
        .sleep_mode =
        {
            #if (bt_0_power_0_ENABLED == 1) /* BT Power control is enabled in the LPA */
            #if (CYCFG_BT_LP_ENABLED == 1) /* Low power is enabled in the LPA, use the LPA configuration */
            .sleep_mode_enabled = true,
            .device_wakeup_pin = CYCFG_BT_DEV_WAKE_GPIO,
            .host_wakeup_pin = CYCFG_BT_HOST_WAKE_GPIO,
            .device_wake_polarity = CYCFG_BT_DEV_WAKE_POLARITY,
            .host_wake_polarity = CYCFG_BT_HOST_WAKE_IRQ_EVENT
            #else /* Low power is disabled in the LPA, disable low power */
            .sleep_mode_enabled = false
            #endif
            #else /* BT Power control is disabled in the LPA – default to BSP low power configuration */
            .sleep_mode_enabled = true,
            .device_wakeup_pin = CYBSP_BT_DEVICE_WAKE,
            .host_wakeup_pin = CYBSP_BT_HOST_WAKE,
            .device_wake_polarity = CYBT_WAKE_ACTIVE_LOW,
            .host_wake_polarity = CYBT_WAKE_ACTIVE_LOW
            #endif
        }
    },

    .task_mem_pool_size    = 2048
};</pre>
<h1><span>btutil_stack</span></h1>
<p>When you startup the Bluetooth Host stack you are responsible for providing a &#8220;management callback&#8221; which has the function prototype</p>
<pre class="EnlighterJSRAW" data-enlighter-language="c">typedef wiced_result_t (wiced_bt_management_cback_t) (wiced_bt_management_evt_t event, wiced_bt_management_evt_data_t *p_event_data);
</pre>
<p>The first parameter is an &#8220;event&#8221; which is  just an enumerated list of possible events by the Bluetooth Host Stack.  Here is the actual list.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="c">enum wiced_bt_management_evt_e {
    /* Bluetooth status events */
    BTM_ENABLED_EVT,                                /**&lt; Bluetooth controller and host stack enabled. Event data: wiced_bt_dev_enabled_t */
    BTM_DISABLED_EVT,                               /**&lt; Bluetooth controller and host stack disabled. Event data: NULL */
    BTM_POWER_MANAGEMENT_STATUS_EVT,                /**&lt; Power management status change. Event data: wiced_bt_power_mgmt_notification_t */
    BTM_RE_START_EVT,                               /**&lt; Bluetooth controller and host stack re-enabled. Event data: tBTM_ENABLED_EVT */
    /* Security events */
    BTM_PIN_REQUEST_EVT,                            /**&lt; PIN request (used only with legacy devices). Event data: #wiced_bt_dev_name_and_class_t */
    BTM_USER_CONFIRMATION_REQUEST_EVT,              /**&lt; received USER_CONFIRMATION_REQUEST event (respond using #wiced_bt_dev_confirm_req_reply). Event data: #wiced_bt_dev_user_cfm_req_t */
    BTM_PASSKEY_NOTIFICATION_EVT,                   /**&lt; received USER_PASSKEY_NOTIFY event. Event data: #wiced_bt_dev_user_key_notif_t */
    BTM_PASSKEY_REQUEST_EVT,                        /**&lt; received USER_PASSKEY_REQUEST event @cond DUAL_MODE (respond using #wiced_bt_dev_pass_key_req_reply). Event data: #wiced_bt_dev_user_key_req_t @endcond
                                                     @note  BR/EDR Only */
    BTM_KEYPRESS_NOTIFICATION_EVT,                  /**&lt; received KEYPRESS_NOTIFY event. Event data: #wiced_bt_dev_user_keypress_t */
    BTM_PAIRING_IO_CAPABILITIES_BR_EDR_REQUEST_EVT, /**&lt; Requesting IO capabilities for BR/EDR pairing. Event data: #wiced_bt_dev_bredr_io_caps_req_t 
                                                        @note  BR/EDR Only */
    BTM_PAIRING_IO_CAPABILITIES_BR_EDR_RESPONSE_EVT,/**&lt; Received IO capabilities response for BR/EDR pairing. Event data: @cond DUAL_MODE #wiced_bt_dev_bredr_io_caps_rsp_t @endcond
                                                        @note  BR/EDR Only*/
    BTM_PAIRING_IO_CAPABILITIES_BLE_REQUEST_EVT,    /**&lt; Requesting IO capabilities for BLE pairing. Slave can check peer io capabilities in event data before updating with local io capabilities. Event data: #wiced_bt_dev_ble_io_caps_req_t */
    BTM_PAIRING_COMPLETE_EVT,                       /**&lt; received SIMPLE_PAIRING_COMPLETE event. Event data: #wiced_bt_dev_pairing_cplt_t */
    BTM_ENCRYPTION_STATUS_EVT,                      /**&lt; Encryption status change. Event data: #wiced_bt_dev_encryption_status_t */
    BTM_SECURITY_REQUEST_EVT,                       /**&lt; Security request (respond using #wiced_bt_ble_security_grant). Event data: #wiced_bt_dev_security_request_t */
    BTM_SECURITY_FAILED_EVT,                        /**&lt; Security procedure/authentication failed. Event data: #wiced_bt_dev_security_failed_t */
    BTM_SECURITY_ABORTED_EVT,                       /**&lt; Security procedure aborted locally, or unexpected link drop. Event data: #wiced_bt_dev_name_and_class_t */

    BTM_READ_LOCAL_OOB_DATA_COMPLETE_EVT,           /**&lt; Result of reading local OOB data @cond DUAL_MODE (#wiced_bt_dev_read_local_oob_data). Event data: #wiced_bt_dev_local_oob_t @endcond 
                                                        @note  BR/EDR Only */

    BTM_REMOTE_OOB_DATA_REQUEST_EVT,                /**&lt; OOB data from remote device @cond DUAL_MODE (respond using #wiced_bt_dev_remote_oob_data_reply). Event data: #wiced_bt_dev_remote_oob_t @endcond 
                                                        @note  BR/EDR Only */

    BTM_PAIRED_DEVICE_LINK_KEYS_UPDATE_EVT,         /**&lt; Updated remote device link keys (store device_link_keys to  NV memory). This is the place to
verify that the correct link key has been generated. Event data: #wiced_bt_device_link_keys_t */
    BTM_PAIRED_DEVICE_LINK_KEYS_REQUEST_EVT,        /**&lt; Request for stored remote device link keys (restore device_link_keys from NV memory). If successful, return WICED_BT_SUCCESS. Event data: #wiced_bt_device_link_keys_t */

    BTM_LOCAL_IDENTITY_KEYS_UPDATE_EVT,             /**&lt; Update local identity key (stored local_identity_keys NV memory). Event data: #wiced_bt_local_identity_keys_t */
    BTM_LOCAL_IDENTITY_KEYS_REQUEST_EVT,            /**&lt; Request local identity key (get local_identity_keys from NV memory). If successful, return WICED_BT_SUCCESS. Event data: #wiced_bt_local_identity_keys_t */

    BTM_BLE_SCAN_STATE_CHANGED_EVT,                 /**&lt; BLE scan state change. Event data: #wiced_bt_ble_scan_type_t */
    BTM_BLE_ADVERT_STATE_CHANGED_EVT,               /**&lt; BLE advertisement state change. Event data: #wiced_bt_ble_advert_mode_t */

    /* BLE Secure Connection events */
    BTM_SMP_REMOTE_OOB_DATA_REQUEST_EVT,            /**&lt; SMP remote oob data request. Reply using wiced_bt_smp_oob_data_reply. Event data: #wiced_bt_smp_remote_oob_req_t  */
    BTM_SMP_SC_REMOTE_OOB_DATA_REQUEST_EVT,         /**&lt; LE secure connection remote oob data request. Reply using wiced_bt_smp_sc_oob_reply. Event data: #wiced_bt_smp_sc_remote_oob_req_t 
                                                        @note  BR/EDR Only */
    BTM_SMP_SC_LOCAL_OOB_DATA_NOTIFICATION_EVT,     /**&lt; LE secure connection local OOB data (wiced_bt_smp_create_local_sc_oob_data). Event data: #wiced_bt_smp_sc_local_oob_t */

    BTM_SCO_CONNECTED_EVT,                          /**&lt; SCO connected event. Event data: @cond DUAL_MODE #wiced_bt_sco_connected_t @endcond
                                                        @note  BR/EDR Only */
    BTM_SCO_DISCONNECTED_EVT,                       /**&lt; SCO disconnected event. Event data: @cond #wiced_bt_sco_disconnected_t @endcond
                                                        @note  BR/EDR Only */
    BTM_SCO_CONNECTION_REQUEST_EVT,                 /**&lt; SCO connection request event. Event data: @cond #wiced_bt_sco_connection_request_t @endcond
                                                        @note  BR/EDR Only */
    BTM_SCO_CONNECTION_CHANGE_EVT,                  /**&lt; SCO connection change event. Event data: @cond #wiced_bt_sco_connection_change_t @endcond
                                                        @note  BR/EDR Only */
    BTM_BLE_CONNECTION_PARAM_UPDATE,                /**&lt; BLE connection parameter update. Event data: #wiced_bt_ble_connection_param_update_t */
    BTM_BLE_PHY_UPDATE_EVT,                         /**&lt; BLE Physical link update. Event data: wiced_bt_ble_phy_update_t */
    BTM_LPM_STATE_LOW_POWER,                        /**&lt; BT device wake has been deasserted. Used for Host Stack Use Case. */
    BTM_MULTI_ADVERT_RESP_EVENT,                    /**&lt; Multi adv command status event Used for the status of the command sent */
#if SMP_CATB_CONFORMANCE_TESTER == TRUE
    BTM_SMP_SC_PEER_INFO_EVT                        /** The Secure Connections support information of the peer device */
#endif

};</pre>
<p>While you are trying to figure out what is going on during the development, it is very useful to be able to print out the name of the events (instead of the numbers).  In other words instead of doing</p>
<pre class="EnlighterJSRAW" data-enlighter-language="c">printf("Event = %02X\n",event);</pre>
<p>it is way better to do</p>
<pre class="EnlighterJSRAW" data-enlighter-language="c">printf("Event Name=%s\n",btutil_getBTEventName(event));</pre>
<p>While I was looking at an example project I found this function which I thought was awesome.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="c">const char *btutil_getBTEventName(wiced_bt_management_evt_t event)
{
    switch ( (int)event )
    {
    CASE_RETURN_STR(BTM_ENABLED_EVT)
    CASE_RETURN_STR(BTM_DISABLED_EVT)
    CASE_RETURN_STR(BTM_POWER_MANAGEMENT_STATUS_EVT)
    CASE_RETURN_STR(BTM_PIN_REQUEST_EVT)
    CASE_RETURN_STR(BTM_USER_CONFIRMATION_REQUEST_EVT)
    CASE_RETURN_STR(BTM_PASSKEY_NOTIFICATION_EVT)
    CASE_RETURN_STR(BTM_PASSKEY_REQUEST_EVT)
    CASE_RETURN_STR(BTM_KEYPRESS_NOTIFICATION_EVT)
    CASE_RETURN_STR(BTM_PAIRING_IO_CAPABILITIES_BR_EDR_REQUEST_EVT)
    CASE_RETURN_STR(BTM_PAIRING_IO_CAPABILITIES_BR_EDR_RESPONSE_EVT)
    CASE_RETURN_STR(BTM_PAIRING_IO_CAPABILITIES_BLE_REQUEST_EVT)
    CASE_RETURN_STR(BTM_PAIRING_COMPLETE_EVT)
    CASE_RETURN_STR(BTM_ENCRYPTION_STATUS_EVT)
    CASE_RETURN_STR(BTM_SECURITY_REQUEST_EVT)
    CASE_RETURN_STR(BTM_SECURITY_FAILED_EVT)
    CASE_RETURN_STR(BTM_SECURITY_ABORTED_EVT)
    CASE_RETURN_STR(BTM_READ_LOCAL_OOB_DATA_COMPLETE_EVT)
    CASE_RETURN_STR(BTM_REMOTE_OOB_DATA_REQUEST_EVT)
    CASE_RETURN_STR(BTM_PAIRED_DEVICE_LINK_KEYS_UPDATE_EVT)
    CASE_RETURN_STR(BTM_PAIRED_DEVICE_LINK_KEYS_REQUEST_EVT)
    CASE_RETURN_STR(BTM_LOCAL_IDENTITY_KEYS_UPDATE_EVT)
    CASE_RETURN_STR(BTM_LOCAL_IDENTITY_KEYS_REQUEST_EVT)
    CASE_RETURN_STR(BTM_BLE_SCAN_STATE_CHANGED_EVT)
    CASE_RETURN_STR(BTM_BLE_ADVERT_STATE_CHANGED_EVT)
    CASE_RETURN_STR(BTM_SMP_REMOTE_OOB_DATA_REQUEST_EVT)
    CASE_RETURN_STR(BTM_SMP_SC_REMOTE_OOB_DATA_REQUEST_EVT)
    CASE_RETURN_STR(BTM_SMP_SC_LOCAL_OOB_DATA_NOTIFICATION_EVT)
    CASE_RETURN_STR(BTM_SCO_CONNECTED_EVT)
    CASE_RETURN_STR(BTM_SCO_DISCONNECTED_EVT)
    CASE_RETURN_STR(BTM_SCO_CONNECTION_REQUEST_EVT)
    CASE_RETURN_STR(BTM_SCO_CONNECTION_CHANGE_EVT)
    CASE_RETURN_STR(BTM_BLE_CONNECTION_PARAM_UPDATE)
#ifdef CYW20819A1
    CASE_RETURN_STR(BTM_BLE_PHY_UPDATE_EVT)
#endif
    }

    return NULL;
}</pre>
<p>And then I learned something new when I looked at the &#8220;function&#8221; CASE_RETURN_STR which used compiler trick to turn an enumerated value into a string.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="c">#define CASE_RETURN_STR(enum_val)          case enum_val: return #enum_val;</pre>
<p>This allows you to do this in your management callback (notice line 16 where the string is printed out)</p>
<pre class="EnlighterJSRAW" data-enlighter-language="c">wiced_result_t app_bt_management_callback(wiced_bt_management_evt_t event, wiced_bt_management_evt_data_t *p_event_data)
{
    wiced_result_t result = WICED_BT_SUCCESS;

    switch (event)
    {
        case BTM_ENABLED_EVT:
            if (WICED_BT_SUCCESS == p_event_data-&gt;enabled.status)
            {
                printf("Started BT Stack Succesfully\n");
                wiced_bt_ble_observe(WICED_TRUE,0,obv_callback);
            }
            break;

        default:
            printf("Unhandled Bluetooth Management Event: %s\n", btutil_getBTEventName(event));
            break;
    }

    return result;
}</pre>
<p>It turns out that there are several other places where the stack gives you an event-ish thing.  So these functions were created as well</p>
<pre class="EnlighterJSRAW" data-enlighter-language="c">#pragma once

const char *btutil_getBTEventName(wiced_bt_management_evt_t event);
const char *btutil_getBLEAdvertModeName(wiced_bt_ble_advert_mode_t mode);
const char *btutil_getBLEGattDisconnReasonName(wiced_bt_gatt_disconn_reason_t reason);
const char *btutil_getBLEGattStatusName(wiced_bt_gatt_status_t status);</pre>
<h1><span>btutil_adv_decode</span></h1>
<p>In <a href="https://iotexpert.com/anycloud-bluetooth-advertising-scanner-part-3/" target="_blank" rel="noopener noreferrer">AnyCloud Bluetooth Advertising Scanner (Part 3)</a> I discussed the format of the advertising packet.  So I created functions which will decode the data in the advertising packets.  More on the future article AnyCloud Bluetooth Advertising Scanner (Part 4 or maybe 5 or maybe 6).  Here are the functions:</p>
<pre class="EnlighterJSRAW" data-enlighter-language="c">#pragma once

wiced_bool_t btutil_isEddystone(uint8_t *data);
wiced_bool_t btutil_is_iBeacon(uint8_t *data);
wiced_bool_t btutil_isCypress(uint8_t *data);

int btutil_adv_len(uint8_t *packet);
void btutil_adv_printPacketDecode(uint8_t *packet);
void btutil_adv_printPacketBytes(uint8_t *packet);</pre>
<h1>btutil</h1>
<p>And because I like to have just one include to get access to all of the function I created &#8220;btutil.h&#8221; which just includes all of the headers in one place.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="c">#pragma once

#include "btutil_adv_decode.h"
#include "btutil_stack.h"
#include "btutil_general.h"
#include "bt_platform_cfg_settings.h"
</pre>
<h1>Add to the IoT Expert Manifest</h1>
<p>In order to set it up for my library to live in the library manager I updated the IoT Expert Manifest file to have a link to the GitHub repository</p>
<pre class="EnlighterJSRAW" data-enlighter-language="c">&lt;middleware&gt;
  
    &lt;name&gt;Bluetooth Utilities&lt;/name&gt;
    &lt;id&gt;btutil&lt;/id&gt;
    &lt;uri&gt;https://github.com/iotexpert/btutil&lt;/uri&gt;
    &lt;desc&gt;A library of Bluetooth Debugging Utilties for Cypress PSoC6 Anycloud&lt;/desc&gt;
    &lt;category&gt;IoT Expert&lt;/category&gt;
    &lt;req_capabilities&gt;psoc6&lt;/req_capabilities&gt;
    &lt;versions&gt;
      &lt;version flow_version="1.0,2.0"&gt;
        &lt;num&gt;master&lt;/num&gt;
        &lt;commit&gt;master&lt;/commit&gt;
        &lt;desc&gt;master&lt;/desc&gt;
      &lt;/version&gt;
    &lt;/versions&gt;
  &lt;/middleware&gt;
</pre>
<p>And now the library manager has the IoT Expert Bluetooth Utilities.</p>
<p><a href="https://iotexpert.com/anycloud-bluetooth-utilities-library/screen-shot-2020-11-01-at-10-43-31-am/" rel="attachment wp-att-10180"><img loading="lazy" decoding="async" src="https://iotexpert.com/wp-content/uploads/2020/11/Screen-Shot-2020-11-01-at-10.43.31-AM-1024x815.png" alt="" class="alignnone size-large wp-image-10180" width="1024" height="815" srcset="https://iotexpert.com/wp-content/uploads/2020/11/Screen-Shot-2020-11-01-at-10.43.31-AM-1024x815.png 1024w, https://iotexpert.com/wp-content/uploads/2020/11/Screen-Shot-2020-11-01-at-10.43.31-AM-300x239.png 300w, https://iotexpert.com/wp-content/uploads/2020/11/Screen-Shot-2020-11-01-at-10.43.31-AM-768x611.png 768w, https://iotexpert.com/wp-content/uploads/2020/11/Screen-Shot-2020-11-01-at-10.43.31-AM-600x477.png 600w, https://iotexpert.com/wp-content/uploads/2020/11/Screen-Shot-2020-11-01-at-10.43.31-AM.png 1116w" sizes="auto, (max-width: 1024px) 100vw, 1024px" /></a></p>
<h1></h1>
<p>&nbsp;</p>
<p>&nbsp;</p>
]]></content:encoded>
					
					<wfw:commentRss>https://iotexpert.com/anycloud-bluetooth-utilities-library/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>AnyCloud Bluetooth Advertising Scanner (Part 3)</title>
		<link>https://iotexpert.com/anycloud-bluetooth-advertising-scanner-part-3/</link>
					<comments>https://iotexpert.com/anycloud-bluetooth-advertising-scanner-part-3/#respond</comments>
		
		<dc:creator><![CDATA[Alan Hawse]]></dc:creator>
		<pubDate>Mon, 02 Nov 2020 13:00:18 +0000</pubDate>
				<category><![CDATA[AnyCloud]]></category>
		<category><![CDATA[AnyCloud Advertising Scanner]]></category>
		<category><![CDATA[Bluetooth]]></category>
		<category><![CDATA[CY8CKIT-062S2-43012]]></category>
		<category><![CDATA[ModusToolbox]]></category>
		<guid isPermaLink="false">https://iotexpert.com/?p=10153</guid>

					<description><![CDATA[Summary In this article I discuss BLE &#8220;Observing&#8221; and add that functionality to my PSoC 6 &#8211; CYW43xxx AnyCloud BLE Adverting Scanner project. Story In part1 of this series I discussed the pieces parts required to get the AnyCloud Bluetooth Stack operating using the AnyCloud SDK running on a PSoC 6 with a CY43xxx combo. [&#8230;]]]></description>
										<content:encoded><![CDATA[<h1>Summary</h1>
<p>In this article I discuss BLE &#8220;Observing&#8221; and add that functionality to my PSoC 6 &#8211; CYW43xxx AnyCloud BLE Adverting Scanner project.</p>
<h1>Story</h1>
<p>In <a href="https://iotexpert.com/anycloud-bluetooth-advertising-scanner-part-1/">part1</a> of this series I discussed the pieces parts required to get the AnyCloud Bluetooth Stack operating using the AnyCloud SDK running on a PSoC 6 with a CY43xxx combo.  Then in <a href="https://iotexpert.com/anycloud-bluetooth-advertising-scanner-part-2/">part 2</a> I built a project with those parts and started up the Bluetooth Host stack.  The project didn&#8217;t really do anything, actually nothing, so it wasn&#8217;t very interesting, but it was going.  In this article I will discuss BLE advertising scanning, how to configure it in the AnyCloud project and finally how to add it to the project.</p>
<p><span><p>There are</p>
<p><div class="table-responsive"><table  style="width:95%; "  class="easy-table easy-table-default " border="1">
<thead>
<tr><th >Article</th>
<th >Topic</th>
</tr>
</thead>
<tbody>
<tr><td ><a href="https://iotexpert.com/anycloud-bluetooth-advertising-scanner-part-1/" target="_blank" rel="noopener">AnyCloud Bluetooth Advertising Scanner (Part 1)</a></td>
<td >Introduction to AnyCloud Bluetooth Advertising</td>
</tr>

<tr><td ><a href="https://iotexpert.com/anycloud-bluetooth-advertising-scanner-part-2/" target="_blank" rel="noopener">AnyCloud Bluetooth Advertising Scanner (Part 2)</a></td>
<td >Creating an AnyCloud Bluetooth project</td>
</tr>

<tr><td ><a href="https://iotexpert.com/anycloud-bluetooth-advertising-scanner-part-3/" target="_blank" rel="noopener">AnyCloud Bluetooth Advertising Scanner (Part 3)</a></td>
<td >Adding Observing functionality to the project</td>
</tr>

<tr><td ><a class="row-title" href="https://iotexpert.com/anycloud-bluetooth-utilities-library/" aria-label="“AnyCloud Bluetooth Utilities Library” (Edit)" target="_blank" rel="noopener">AnyCloud Bluetooth Utilities Library</a></td>
<td >A set of APIs for enhancement of the AnyCloud Library</td>
</tr>

<tr><td ><a href="https://iotexpert.com/anycloud-bluetooth-advertising-scanner-part-4/" target="_blank" rel="noopener">AnyCloud Bluetooth Advertising Scanner (Part 4)</a></td>
<td >Adding a command line to the scanner</td>
</tr>

<tr><td ><a href="https://iotexpert.com/anycloud-bluetooth-advertising-scanner-part-5/" target="_blank" rel="noopener">AnyCloud Bluetooth Advertising Scanner (Part 5)</a></td>
<td >Adding a history database to the scanner</td>
</tr>

<tr><td ><a href="https://iotexpert.com/anycloud-bluetooth-advertising-scanner-part-6/" target="_blank" rel="noopener">AnyCloud Bluetooth Advertising Scanner (Part 6)</a></td>
<td >Decoding advertising packets</td>
</tr>

<tr><td ><a href="https://iotexpert.com/anycloud-bluetooth-advertising-scanner-part-7/" target="_blank" rel="noopener">AnyCloud Bluetooth Advertising Scanner (Part 7)</a></td>
<td >Adding recording commands to the command line</td>
</tr>

<tr><td ><a href="https://iotexpert.com/anycloud-bluetooth-advertising-scanner-part-8/">AnyCloud Bluetooth Advertising Scanner (Part 8)</a></td>
<td >Adding filtering to the scanner</td>
</tr>

<tr><td ><a href="https://iotexpert.com/anycloud-bluetooth-advertising-scanner-part-9/">AnyCloud Bluetooth Advertising Scanner (Part 9)</a></td>
<td >Improve the print and add packet age</td>
</tr>

<tr><td ><a href="https://iotexpert.com/anycloud-bluetooth-advertising-scanner-part-10/">AnyCloud Bluetooth Advertising Scanner (Part 10)</a></td>
<td >Sort the database</td>
</tr>
</tbody></table></div></p>
<p>All of the code can be found at git@github.com:iotexpert/AnyCloudBLEScanner.git and https://github.com/iotexpert/AnyCloudBLEScanner.git</p>
<p>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.</p>
<p>You can also create a new project with this is a template if you have the IoT Expert Manifest Files installed</p></span></p>
<h1>Explain BLE Advertising &#8211; Scanner/Observer</h1>
<p>You might recall that there are four roles that a BLE device can perform</p>
<ul>
<li>Peripheral &#8211; low power devices that broadcast advertisements, then accept a single connection</li>
<li>Central &#8211; devices like cell phones that connect to peripherals.  They may run multiple connections at a time.</li>
<li>Broadcaster &#8211; a nonconnectable peripheral that sends out advertisements</li>
<li>Observer &#8211; A central-like device that listens for broadcasters (or advertising peripherals)</li>
</ul>
<p>And you might remember that advertisements are short, up to 31-byte, packets of data that give information which can be used for one or more of:</p>
<ul>
<li>advertising the availability to connect</li>
<li>advertising services</li>
<li>advertising the name</li>
<li>advertising vendor specific information</li>
<li>advertising beacon data (like temperature or &#8230;)</li>
<li>advertising location</li>
</ul>
<p>And, if you forgot, BLE operates on 40 channels.  But to save power in peripherals, all of the advertising happens on channel 37, 38 and 39.  Specifically a peripheral or broadcaster will send out the advertising data on channel 37, then 38 then 39, then wait&#8230; then do it again.  But why one channel at a time?  Because BLE radio&#8217;s can be tuned to transmit and receive on only one channel at a time (a power saving and complexity reducing feature)</p>
<p>Inside of the Central/Observer it will listen on channel 37 for a &#8220;window&#8221; amount of time.  Then it will do nothing for an interval-window amount of time.  Then it will do that same thing on channel 28 then 39.  But why only one channel at a time?  Same reason as above, it saves power and simplifies the design.  Why not have the window and the interval be the same?  Once again, it saves power.</p>
<p>Here is a picture:</p>
<p><a href="https://iotexpert.com/anycloud-bluetooth-advertising-scanner-part-1/screen-shot-2020-10-17-at-9-18-17-am/" rel="attachment wp-att-10113"><img loading="lazy" decoding="async" src="https://iotexpert.com/wp-content/uploads/2020/10/Screen-Shot-2020-10-17-at-9.18.17-AM.png" alt="" width="726" height="346" class="alignnone size-full wp-image-10113" srcset="https://iotexpert.com/wp-content/uploads/2020/10/Screen-Shot-2020-10-17-at-9.18.17-AM.png 726w, https://iotexpert.com/wp-content/uploads/2020/10/Screen-Shot-2020-10-17-at-9.18.17-AM-300x143.png 300w, https://iotexpert.com/wp-content/uploads/2020/10/Screen-Shot-2020-10-17-at-9.18.17-AM-600x286.png 600w" sizes="auto, (max-width: 726px) 100vw, 726px" /></a></p>
<p>But, what happens if you are not listening when the advertiser advertises?  You missed it.  Tough shit.  It turns out that setting the scan window and interval will greatly impact the probability that you hear advertisements.  And, you are more likely to hear advertisements because they are sent on three channels.  But it seems like it will never work.  Will it? &#8230; yes, of course, or they wouldn&#8217;t have done it that way <img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f642.png" alt="🙂" class="wp-smiley" style="height: 1em; max-height: 1em;" /></p>
<h1>BLE Advertising &#8211; The Advertiser Peripheral or Broadcaster</h1>
<p>So what exactly is inside of an advertising packet?  Volume 6 part B Section 2.3 of the bluetooth core spec describes the advertising protocol data unit (PDU)</p>
<p><a href="https://iotexpert.com/anycloud-bluetooth-advertising-scanner-part-1/screen-shot-2020-10-17-at-11-20-29-am/" rel="attachment wp-att-10114"><img loading="lazy" decoding="async" src="https://iotexpert.com/wp-content/uploads/2020/10/Screen-Shot-2020-10-17-at-11.20.29-AM.png" alt="" width="1012" height="460" class="alignnone size-full wp-image-10114" srcset="https://iotexpert.com/wp-content/uploads/2020/10/Screen-Shot-2020-10-17-at-11.20.29-AM.png 1012w, https://iotexpert.com/wp-content/uploads/2020/10/Screen-Shot-2020-10-17-at-11.20.29-AM-300x136.png 300w, https://iotexpert.com/wp-content/uploads/2020/10/Screen-Shot-2020-10-17-at-11.20.29-AM-768x349.png 768w, https://iotexpert.com/wp-content/uploads/2020/10/Screen-Shot-2020-10-17-at-11.20.29-AM-600x273.png 600w" sizes="auto, (max-width: 1012px) 100vw, 1012px" /></a></p>
<p>But what is inside of the header?</p>
<p><a href="https://iotexpert.com/anycloud-bluetooth-advertising-scanner-part-1/screen-shot-2020-10-17-at-11-20-37-am/" rel="attachment wp-att-10115"><img loading="lazy" decoding="async" src="https://iotexpert.com/wp-content/uploads/2020/10/Screen-Shot-2020-10-17-at-11.20.37-AM.png" alt="" width="1000" height="216" class="alignnone size-large wp-image-10115" srcset="https://iotexpert.com/wp-content/uploads/2020/10/Screen-Shot-2020-10-17-at-11.20.37-AM.png 1000w, https://iotexpert.com/wp-content/uploads/2020/10/Screen-Shot-2020-10-17-at-11.20.37-AM-300x65.png 300w, https://iotexpert.com/wp-content/uploads/2020/10/Screen-Shot-2020-10-17-at-11.20.37-AM-768x166.png 768w, https://iotexpert.com/wp-content/uploads/2020/10/Screen-Shot-2020-10-17-at-11.20.37-AM-600x130.png 600w" sizes="auto, (max-width: 1000px) 100vw, 1000px" /></a></p>
<p><a href="https://iotexpert.com/anycloud-bluetooth-advertising-scanner-part-1/screen-shot-2020-10-17-at-11-20-53-am/" rel="attachment wp-att-10116"><img loading="lazy" decoding="async" src="https://iotexpert.com/wp-content/uploads/2020/10/Screen-Shot-2020-10-17-at-11.20.53-AM.png" alt="" width="944" height="292" class="alignnone size-large wp-image-10116" srcset="https://iotexpert.com/wp-content/uploads/2020/10/Screen-Shot-2020-10-17-at-11.20.53-AM.png 944w, https://iotexpert.com/wp-content/uploads/2020/10/Screen-Shot-2020-10-17-at-11.20.53-AM-300x93.png 300w, https://iotexpert.com/wp-content/uploads/2020/10/Screen-Shot-2020-10-17-at-11.20.53-AM-768x238.png 768w, https://iotexpert.com/wp-content/uploads/2020/10/Screen-Shot-2020-10-17-at-11.20.53-AM-600x186.png 600w" sizes="auto, (max-width: 944px) 100vw, 944px" /></a></p>
<p>This leaves us with what is inside of the &#8220;payload&#8221;.  The answer is that the ADV_IND Payload Data Unit (PDU) contains an address of 6-bytes plus up to 31 bytes of data.</p>
<p><a href="https://iotexpert.com/anycloud-bluetooth-advertising-scanner-part-1/screen-shot-2020-10-17-at-1-13-00-pm/" rel="attachment wp-att-10125"><img loading="lazy" decoding="async" src="https://iotexpert.com/wp-content/uploads/2020/10/Screen-Shot-2020-10-17-at-1.13.00-PM.png" alt="" width="430" height="180" class="alignnone size-full wp-image-10125" srcset="https://iotexpert.com/wp-content/uploads/2020/10/Screen-Shot-2020-10-17-at-1.13.00-PM.png 430w, https://iotexpert.com/wp-content/uploads/2020/10/Screen-Shot-2020-10-17-at-1.13.00-PM-300x126.png 300w" sizes="auto, (max-width: 430px) 100vw, 430px" /></a></p>
<div class="page" title="Page 2873">
<div class="layoutArea">
<div class="column">
<p><span>The AdvA field shall contain the advertiser’s public or random device address as indicated by TxAdd.</span></p>
<p>The actual AdvData field is further broken up into &#8220;AD Structures&#8221; like this:</p>
</div>
</div>
</div>
<p><a href="https://iotexpert.com/anycloud-bluetooth-advertising-scanner-part-1/screen-shot-2020-10-17-at-11-21-59-am/" rel="attachment wp-att-10117"><img loading="lazy" decoding="async" src="https://iotexpert.com/wp-content/uploads/2020/10/Screen-Shot-2020-10-17-at-11.21.59-AM.png" alt="" width="962" height="524" class="alignnone size-large wp-image-10117" srcset="https://iotexpert.com/wp-content/uploads/2020/10/Screen-Shot-2020-10-17-at-11.21.59-AM.png 962w, https://iotexpert.com/wp-content/uploads/2020/10/Screen-Shot-2020-10-17-at-11.21.59-AM-300x163.png 300w, https://iotexpert.com/wp-content/uploads/2020/10/Screen-Shot-2020-10-17-at-11.21.59-AM-768x418.png 768w, https://iotexpert.com/wp-content/uploads/2020/10/Screen-Shot-2020-10-17-at-11.21.59-AM-600x327.png 600w" sizes="auto, (max-width: 962px) 100vw, 962px" /></a></p>
<p>And what is the &#8220;AD Type&#8221;, well it is a one byte of one of the following:</p>
<p><a href="https://iotexpert.com/anycloud-bluetooth-advertising-scanner-part-1/screen-shot-2020-10-17-at-11-22-21-am/" rel="attachment wp-att-10118"><img loading="lazy" decoding="async" src="https://iotexpert.com/wp-content/uploads/2020/10/Screen-Shot-2020-10-17-at-11.22.21-AM.png" alt="" width="962" height="112" class="alignnone size-large wp-image-10118" srcset="https://iotexpert.com/wp-content/uploads/2020/10/Screen-Shot-2020-10-17-at-11.22.21-AM.png 962w, https://iotexpert.com/wp-content/uploads/2020/10/Screen-Shot-2020-10-17-at-11.22.21-AM-300x35.png 300w, https://iotexpert.com/wp-content/uploads/2020/10/Screen-Shot-2020-10-17-at-11.22.21-AM-768x89.png 768w, https://iotexpert.com/wp-content/uploads/2020/10/Screen-Shot-2020-10-17-at-11.22.21-AM-600x70.png 600w" sizes="auto, (max-width: 962px) 100vw, 962px" /></a> <a href="https://iotexpert.com/anycloud-bluetooth-advertising-scanner-part-1/screen-shot-2020-10-17-at-11-24-26-am/" rel="attachment wp-att-10119"><img loading="lazy" decoding="async" src="https://iotexpert.com/wp-content/uploads/2020/10/Screen-Shot-2020-10-17-at-11.24.26-AM.png" alt="" width="982" height="1002" class="alignnone size-large wp-image-10119" srcset="https://iotexpert.com/wp-content/uploads/2020/10/Screen-Shot-2020-10-17-at-11.24.26-AM.png 982w, https://iotexpert.com/wp-content/uploads/2020/10/Screen-Shot-2020-10-17-at-11.24.26-AM-294x300.png 294w, https://iotexpert.com/wp-content/uploads/2020/10/Screen-Shot-2020-10-17-at-11.24.26-AM-768x784.png 768w, https://iotexpert.com/wp-content/uploads/2020/10/Screen-Shot-2020-10-17-at-11.24.26-AM-600x612.png 600w" sizes="auto, (max-width: 982px) 100vw, 982px" /></a></p>
<p>And then where do you find the assigned numbers for the field types?  In the &#8220;<a href="https://www.bluetooth.com/specifications/assigned-numbers/generic-access-profile/" target="_blank" rel="noopener noreferrer">Assigned Numbers and GAP</a>&#8220;.  Here is a clip from the spec.</p>
<p><a href="https://iotexpert.com/anycloud-bluetooth-advertising-scanner-part-1/screen-shot-2020-10-17-at-11-26-02-am/" rel="attachment wp-att-10120"><img loading="lazy" decoding="async" src="https://iotexpert.com/wp-content/uploads/2020/10/Screen-Shot-2020-10-17-at-11.26.02-AM-1024x755.png" alt="" width="1024" height="755" class="alignnone size-large wp-image-10120" srcset="https://iotexpert.com/wp-content/uploads/2020/10/Screen-Shot-2020-10-17-at-11.26.02-AM-1024x755.png 1024w, https://iotexpert.com/wp-content/uploads/2020/10/Screen-Shot-2020-10-17-at-11.26.02-AM-300x221.png 300w, https://iotexpert.com/wp-content/uploads/2020/10/Screen-Shot-2020-10-17-at-11.26.02-AM-768x566.png 768w, https://iotexpert.com/wp-content/uploads/2020/10/Screen-Shot-2020-10-17-at-11.26.02-AM-1536x1132.png 1536w, https://iotexpert.com/wp-content/uploads/2020/10/Screen-Shot-2020-10-17-at-11.26.02-AM-600x442.png 600w, https://iotexpert.com/wp-content/uploads/2020/10/Screen-Shot-2020-10-17-at-11.26.02-AM.png 1910w" sizes="auto, (max-width: 1024px) 100vw, 1024px" /></a></p>
<p><a href="https://iotexpert.com/anycloud-bluetooth-advertising-scanner-part-1/screen-shot-2020-10-17-at-11-26-15-am/" rel="attachment wp-att-10121"><img loading="lazy" decoding="async" src="https://iotexpert.com/wp-content/uploads/2020/10/Screen-Shot-2020-10-17-at-11.26.15-AM-1024x150.png" alt="" width="1024" height="150" class="alignnone size-large wp-image-10121" srcset="https://iotexpert.com/wp-content/uploads/2020/10/Screen-Shot-2020-10-17-at-11.26.15-AM-1024x150.png 1024w, https://iotexpert.com/wp-content/uploads/2020/10/Screen-Shot-2020-10-17-at-11.26.15-AM-300x44.png 300w, https://iotexpert.com/wp-content/uploads/2020/10/Screen-Shot-2020-10-17-at-11.26.15-AM-768x112.png 768w, https://iotexpert.com/wp-content/uploads/2020/10/Screen-Shot-2020-10-17-at-11.26.15-AM-1536x224.png 1536w, https://iotexpert.com/wp-content/uploads/2020/10/Screen-Shot-2020-10-17-at-11.26.15-AM-600x88.png 600w, https://iotexpert.com/wp-content/uploads/2020/10/Screen-Shot-2020-10-17-at-11.26.15-AM.png 1916w" sizes="auto, (max-width: 1024px) 100vw, 1024px" /></a></p>
<p>And conveniently enough we enumerated them for you inside of the SDK header file wiced_bt_ble.h</p>
<pre class="EnlighterJSRAW" data-enlighter-language="c">/** Advertisement data types */
enum wiced_bt_ble_advert_type_e {
    BTM_BLE_ADVERT_TYPE_FLAG                        = 0x01,                 /**&lt; Advertisement flags */
    BTM_BLE_ADVERT_TYPE_16SRV_PARTIAL               = 0x02,                 /**&lt; List of supported services - 16 bit UUIDs (partial) */
    BTM_BLE_ADVERT_TYPE_16SRV_COMPLETE              = 0x03,                 /**&lt; List of supported services - 16 bit UUIDs (complete) */
    BTM_BLE_ADVERT_TYPE_32SRV_PARTIAL               = 0x04,                 /**&lt; List of supported services - 32 bit UUIDs (partial) */
    BTM_BLE_ADVERT_TYPE_32SRV_COMPLETE              = 0x05,                 /**&lt; List of supported services - 32 bit UUIDs (complete) */
    BTM_BLE_ADVERT_TYPE_128SRV_PARTIAL              = 0x06,                 /**&lt; List of supported services - 128 bit UUIDs (partial) */
    BTM_BLE_ADVERT_TYPE_128SRV_COMPLETE             = 0x07,                 /**&lt; List of supported services - 128 bit UUIDs (complete) */
    BTM_BLE_ADVERT_TYPE_NAME_SHORT                  = 0x08,                 /**&lt; Short name */
    BTM_BLE_ADVERT_TYPE_NAME_COMPLETE               = 0x09,                 /**&lt; Complete name */
    BTM_BLE_ADVERT_TYPE_TX_POWER                    = 0x0A,                 /**&lt; TX Power level  */
    BTM_BLE_ADVERT_TYPE_DEV_CLASS                   = 0x0D,                 /**&lt; Device Class */
    BTM_BLE_ADVERT_TYPE_SIMPLE_PAIRING_HASH_C       = 0x0E,                 /**&lt; Simple Pairing Hash C */
    BTM_BLE_ADVERT_TYPE_SIMPLE_PAIRING_RAND_C       = 0x0F,                 /**&lt; Simple Pairing Randomizer R */
    BTM_BLE_ADVERT_TYPE_SM_TK                       = 0x10,                 /**&lt; Security manager TK value */
    BTM_BLE_ADVERT_TYPE_SM_OOB_FLAG                 = 0x11,                 /**&lt; Security manager Out-of-Band data */
    BTM_BLE_ADVERT_TYPE_INTERVAL_RANGE              = 0x12,                 /**&lt; Slave connection interval range */
    BTM_BLE_ADVERT_TYPE_SOLICITATION_SRV_UUID       = 0x14,                 /**&lt; List of solicitated services - 16 bit UUIDs */
    BTM_BLE_ADVERT_TYPE_128SOLICITATION_SRV_UUID    = 0x15,                 /**&lt; List of solicitated services - 128 bit UUIDs */
    BTM_BLE_ADVERT_TYPE_SERVICE_DATA                = 0x16,                 /**&lt; Service data - 16 bit UUID */
    BTM_BLE_ADVERT_TYPE_PUBLIC_TARGET               = 0x17,                 /**&lt; Public target address */
    BTM_BLE_ADVERT_TYPE_RANDOM_TARGET               = 0x18,                 /**&lt; Random target address */
    BTM_BLE_ADVERT_TYPE_APPEARANCE                  = 0x19,                 /**&lt; Appearance */
    BTM_BLE_ADVERT_TYPE_ADVERT_INTERVAL             = 0x1a,                 /**&lt; Advertising interval */
    BTM_BLE_ADVERT_TYPE_LE_BD_ADDR                  = 0x1b,                 /**&lt; LE device bluetooth address */
    BTM_BLE_ADVERT_TYPE_LE_ROLE                     = 0x1c,                 /**&lt; LE role */
    BTM_BLE_ADVERT_TYPE_256SIMPLE_PAIRING_HASH      = 0x1d,                 /**&lt; Simple Pairing Hash C-256 */
    BTM_BLE_ADVERT_TYPE_256SIMPLE_PAIRING_RAND      = 0x1e,                 /**&lt; Simple Pairing Randomizer R-256 */
    BTM_BLE_ADVERT_TYPE_32SOLICITATION_SRV_UUID     = 0x1f,                 /**&lt; List of solicitated services - 32 bit UUIDs */
    BTM_BLE_ADVERT_TYPE_32SERVICE_DATA              = 0x20,                 /**&lt; Service data - 32 bit UUID */
    BTM_BLE_ADVERT_TYPE_128SERVICE_DATA             = 0x21,                 /**&lt; Service data - 128 bit UUID */
    BTM_BLE_ADVERT_TYPE_CONN_CONFIRM_VAL            = 0x22,                 /**&lt; LE Secure Connections Confirmation Value */
    BTM_BLE_ADVERT_TYPE_CONN_RAND_VAL               = 0x23,                 /**&lt; LE Secure Connections Random Value */
    BTM_BLE_ADVERT_TYPE_URI                         = 0x24,                 /**&lt; URI */
    BTM_BLE_ADVERT_TYPE_INDOOR_POS                  = 0x25,                 /**&lt; Indoor Positioning */
    BTM_BLE_ADVERT_TYPE_TRANS_DISCOVER_DATA         = 0x26,                 /**&lt; Transport Discovery Data */
    BTM_BLE_ADVERT_TYPE_SUPPORTED_FEATURES          = 0x27,                 /**&lt; LE Supported Features */
    BTM_BLE_ADVERT_TYPE_UPDATE_CH_MAP_IND           = 0x28,                 /**&lt; Channel Map Update Indication */
    BTM_BLE_ADVERT_TYPE_PB_ADV                      = 0x29,                 /**&lt; PB-ADV */
    BTM_BLE_ADVERT_TYPE_MESH_MSG                    = 0x2A,                 /**&lt; Mesh Message */
    BTM_BLE_ADVERT_TYPE_MESH_BEACON                 = 0x2B,                 /**&lt; Mesh Beacon */
    BTM_BLE_ADVERT_TYPE_PSRI                        = 0x2E,                 /**&lt; Generic Audio Provate Set Random Identifier */
    BTM_BLE_ADVERT_TYPE_3D_INFO_DATA                = 0x3D,                 /**&lt; 3D Information Data */
    BTM_BLE_ADVERT_TYPE_MANUFACTURER                = 0xFF                  /**&lt; Manufacturer data */
};
</pre>
<h1>How does scanning work in the AnyCloud Bluetooth Stack?</h1>
<p>To turn on observing/scanning you need to call the function:</p>
<pre class="EnlighterJSRAW" data-enlighter-language="c" ">wiced_bt_dev_status_t wiced_bt_ble_observe (wiced_bool_t start, uint8_t duration, wiced_bt_ble_scan_result_cback_t *p_scan_result_cback);
</pre>
<p>Which will cause the host stack to tell the controller to start scanning for advertising packets.  It will set the scan window and scan interval the low duty scan settings from the bluetooth configuration structure&#8230; which we setup with the Bluetooth configurator.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="c" "> .low_duty_scan_interval          = CY_BT_LOW_DUTY_SCAN_INTERVAL,                              /**&lt; Low duty scan interval */
        .low_duty_scan_window            = CY_BT_LOW_DUTY_SCAN_WINDOW,                                /**&lt; Low duty scan window */
        .low_duty_scan_duration          = CY_BT_LOW_DUTY_SCAN_DURATION,                              /**&lt; Low duty scan duration in seconds (0 for infinite) */
</pre>
<p>When the controller hears an advertising packet, it will send the HCI advertising report to the Bluetooth host stack, which with then call you back.  Specifically it will call you back by calling the p_scan_result_cback&#8221; function.</p>
<p>You provide the callback function which has the prototype:</p>
<pre class="EnlighterJSRAW" data-enlighter-language="c">typedef void (wiced_bt_ble_scan_result_cback_t) (wiced_bt_ble_scan_results_t *p_scan_result, uint8_t *p_adv_data);
</pre>
<p>which contains two parameters, p_scan_result which is a structure that has the mac address and some thing data plus the p_adv_data which has the raw bytes of the advertising packet.</p>
<h1>Add Observing to our Project</h1>
<p>OK.  Lets add this to our project by creating a callback function like this:</p>
<p>Lines 5-9: Just prints out the raw bytes of the MAC address of the remote device, the one advertising</p>
<p>To print out the raw advertising data you need to remember that it is formatted as</p>
<ol>
<li>A length (of all of the data of the field)</li>
<li>A type</li>
<li>The rest of the data</li>
</ol>
<p>When you find a field of length of 0 you know that you have reached the end of the data</p>
<p>On Lines 13-20: I print out one field at a time and the raw data</p>
<pre class="EnlighterJSRAW" data-enlighter-language="c">//
void obv_callback(wiced_bt_ble_scan_results_t *p_scan_result, uint8_t *p_adv_data)
{
    // Print the MAC Address
    printf("MAC: ");
    for(int i=0;i&lt;6;i++)
    {
        printf("%02X:",p_scan_result-&gt;remote_bd_addr[i]);
    }
    // Print the RAW Data of the ADV Packet
    printf(" Data: ");
    int i=0;
    while(p_adv_data[i])
    {
        for(int j=0;j&lt;p_adv_data[i];j++)
        {
            printf("%02X ",p_adv_data[i+1+j]);
        }
        i = i + p_adv_data[i]+1;
    }
    printf("\n");
    
}</pre>
<p>Then update the management callback to start the scanner after the stack is successfully started</p>
<pre class="EnlighterJSRAW" data-enlighter-language="c" ">    switch (event)
    {
        case BTM_ENABLED_EVT:

            if (WICED_BT_SUCCESS == p_event_data-&gt;enabled.status)
            {
                printf("Started BT Stack Succesfully\n");
                wiced_bt_ble_observe(WICED_TRUE,0,obv_callback);

            }</pre>
<h1>Program and Test</h1>
<p>Now when I run the program data comes blasting out of the screen because there are a boatload of ble devices in my house</p>
<pre class="EnlighterJSRAW" data-enlighter-language="c" ">AnyCloud&gt; Unhandled Bluetooth Management Event: 0x16
Started BT Stack Succesfully
MAC: 76:99:58:E8:8B:1F:Data: 01 1A 0A 0C FF 4C 00 10 06 13 1A 54 F7 5A 7A 
MAC: 9E:7B:EF:0B:74:20:Data: 01 06 16 F7 FD 01 0C C2 81 CE 0C 74 58 77 19 C8 E3 84 A3 42 50 98 00 00 00 00 03 
MAC: 6F:11:7C:FF:02:13:Data: 01 1A 0A 05 FF 4C 00 10 06 03 1E BA 24 58 3D 
MAC: 3F:64:BE:4E:29:0C:Data: 01 04 FF 00 4C 02 15 26 86 F3 9C BA DA 46 58 85 4A A6 2E 7E 5E 8B 8D 00 01 00 00 C9 
MAC: 47:4B:F1:53:2C:84:Data: 01 06 FF 4C 00 10 05 08 18 79 1E C2 
MAC: C8:69:CD:18:BC:E6:Data: 01 1A 0A 0C FF 4C 00 10 05 0C 14 17 BF E9 
MAC: 27:F6:6F:1E:7A:78:Data: 01 1A FF 4C 00 09 06 03 12 C0 A8 20 0D 
MAC: 6F:AE:84:F6:6A:9F:Data: 01 06 FF 4C 00 10 05 08 18 79 1E C2 
MAC: 3F:64:BE:4E:29:0C:Data: 01 04 FF 00 4C 02 15 26 86 F3 9C BA DA 46 58 85 4A A6 2E 7E 5E 8B 8D 00 01 00 00 C9 
MAC: 41:EE:B4:9C:5C:5F:Data: 01 1A 0A 07 FF 4C 00 10 06 33 1A 49 59 46 B4 
MAC: 9E:7B:EF:0B:74:20:Data: 01 06 16 F7 FD 01 0C C2 81 CE 0C 74 58 77 19 C8 E3 84 A3 42 50 98 00 00 00 00 03 
MAC: C8:EB:ED:C8:AC:1C:Data: 01 0A 03 66 66 19 D0 07 FF EE 03 1C AC C8 ED EB C8 
MAC: 76:99:58:E8:8B:1F:Data: 01 1A 0A 0C FF 4C 00 10 06 13 1A 54 F7 5A 7A</pre>
<p>In the next article Ill add some more smarts to manage the data to be easier to look at.</p>
<p>For your information here is all of the file bluetoothManager.c</p>
<pre class="EnlighterJSRAW" data-enlighter-language="c" ">#include &lt;stdio.h&gt;
#include &lt;stdlib.h&gt;

#include "cybsp.h"

#include "FreeRTOS.h"

#include "bluetoothManager.h"
#include "wiced_bt_stack.h"
#include "wiced_bt_dev.h"
#include "wiced_bt_trace.h"

//
void obv_callback(wiced_bt_ble_scan_results_t *p_scan_result, uint8_t *p_adv_data)
{
    // Print the MAC Address
    printf("MAC: ");
    for(int i=0;i&lt;6;i++)
    {
        printf("%02X:",p_scan_result-&gt;remote_bd_addr[i]);
    }
    // Print the RAW Data of the ADV Packet
    printf(" Data: ");
    int i=0;
    while(p_adv_data[i])
    {
        for(int j=0;j&lt;p_adv_data[i];j++)
        {
            printf("%02X ",p_adv_data[i+1+j]);
        }
        i = i + p_adv_data[i]+1;
    }
    printf("\n");
    
}

/**************************************************************************************************
* Function Name: app_bt_management_callback()
***************************************************************************************************
* Summary:
*   This is a Bluetooth stack event handler function to receive management events from
*   the BLE stack and process as per the application.
*
* Parameters:
*   wiced_bt_management_evt_t event             : BLE event code of one byte length
*   wiced_bt_management_evt_data_t *p_event_data: Pointer to BLE management event structures
*
* Return:
*  wiced_result_t: Error code from WICED_RESULT_LIST or BT_RESULT_LIST
*
*************************************************************************************************/
wiced_result_t app_bt_management_callback(wiced_bt_management_evt_t event, wiced_bt_management_evt_data_t *p_event_data)
{
    wiced_result_t result = WICED_BT_SUCCESS;

    switch (event)
    {
        case BTM_ENABLED_EVT:

            if (WICED_BT_SUCCESS == p_event_data-&gt;enabled.status)
            {
                printf("Started BT Stack Succesfully\n");
                wiced_bt_ble_observe(WICED_TRUE,0,obv_callback);

            }
            else
            {
            	printf("Error enabling BTM_ENABLED_EVENT\n");
            }

            break;

        default:
            printf("Unhandled Bluetooth Management Event: 0x%x\n", event);
            break;
    }

    return result;
}
</pre>
<p>&nbsp;</p>
]]></content:encoded>
					
					<wfw:commentRss>https://iotexpert.com/anycloud-bluetooth-advertising-scanner-part-3/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>AnyCloud Bluetooth Advertising Scanner (Part 1)</title>
		<link>https://iotexpert.com/anycloud-bluetooth-advertising-scanner-part-1/</link>
					<comments>https://iotexpert.com/anycloud-bluetooth-advertising-scanner-part-1/#respond</comments>
		
		<dc:creator><![CDATA[Alan Hawse]]></dc:creator>
		<pubDate>Mon, 19 Oct 2020 12:40:29 +0000</pubDate>
				<category><![CDATA[4343W]]></category>
		<category><![CDATA[AnyCloud]]></category>
		<category><![CDATA[AnyCloud Advertising Scanner]]></category>
		<category><![CDATA[Bluetooth]]></category>
		<category><![CDATA[ModusToolbox]]></category>
		<category><![CDATA[PSoC 6]]></category>
		<guid isPermaLink="false">https://iotexpert.com/?p=10102</guid>

					<description><![CDATA[Summary The first of several articles discussing the use of the AnyCloud BLE Stack to build advertising scanner/observers. Story A few summers ago while I was writing the WICED Bluetooth Academy book, I created a WICED based BLE advertising scanner.  Actually, I created a framework for the scanner and the remarkable summer intern I had [&#8230;]]]></description>
										<content:encoded><![CDATA[<h1>Summary</h1>
<p>The first of several articles discussing the use of the AnyCloud BLE Stack to build advertising scanner/observers.</p>
<h1>Story</h1>
<p>A few summers ago while I was writing the WICED Bluetooth Academy book, I created a WICED based BLE advertising scanner.  Actually, I created a framework for the scanner and the remarkable summer intern I had finished the work.  That project has been sitting in the source code repository for the Bluetooth class, mostly only shown to face-to-face students.  This scanner is built using some of the original code combined with the new AnyCloud Bluetooth SDK.  It will act sort-of-like <a href="https://punchthrough.com/lightblue/" target="_blank" rel="noopener noreferrer">LightBlue</a> or one of the other Bluetooth advertising scanners you might run on your phone, but with a serial console.</p>
<p>Sometime in the last few months we released the Bluetooth SDK for AnyCloud (things have been crazy and I have lost track of time)  This SDK has all of the stuff needed to add Bluetooth to your AnyCloud project using one of the Cypress Bluetooth/WiFi combo chips.  I had not had a chance to try it out, so I decided to build a Bluetooth project and then port the scanning code.</p>
<p><span><p>There are</p>
<p><div class="table-responsive"><table  style="width:95%; "  class="easy-table easy-table-default " border="1">
<thead>
<tr><th >Article</th>
<th >Topic</th>
</tr>
</thead>
<tbody>
<tr><td ><a href="https://iotexpert.com/anycloud-bluetooth-advertising-scanner-part-1/" target="_blank" rel="noopener">AnyCloud Bluetooth Advertising Scanner (Part 1)</a></td>
<td >Introduction to AnyCloud Bluetooth Advertising</td>
</tr>

<tr><td ><a href="https://iotexpert.com/anycloud-bluetooth-advertising-scanner-part-2/" target="_blank" rel="noopener">AnyCloud Bluetooth Advertising Scanner (Part 2)</a></td>
<td >Creating an AnyCloud Bluetooth project</td>
</tr>

<tr><td ><a href="https://iotexpert.com/anycloud-bluetooth-advertising-scanner-part-3/" target="_blank" rel="noopener">AnyCloud Bluetooth Advertising Scanner (Part 3)</a></td>
<td >Adding Observing functionality to the project</td>
</tr>

<tr><td ><a class="row-title" href="https://iotexpert.com/anycloud-bluetooth-utilities-library/" aria-label="“AnyCloud Bluetooth Utilities Library” (Edit)" target="_blank" rel="noopener">AnyCloud Bluetooth Utilities Library</a></td>
<td >A set of APIs for enhancement of the AnyCloud Library</td>
</tr>

<tr><td ><a href="https://iotexpert.com/anycloud-bluetooth-advertising-scanner-part-4/" target="_blank" rel="noopener">AnyCloud Bluetooth Advertising Scanner (Part 4)</a></td>
<td >Adding a command line to the scanner</td>
</tr>

<tr><td ><a href="https://iotexpert.com/anycloud-bluetooth-advertising-scanner-part-5/" target="_blank" rel="noopener">AnyCloud Bluetooth Advertising Scanner (Part 5)</a></td>
<td >Adding a history database to the scanner</td>
</tr>

<tr><td ><a href="https://iotexpert.com/anycloud-bluetooth-advertising-scanner-part-6/" target="_blank" rel="noopener">AnyCloud Bluetooth Advertising Scanner (Part 6)</a></td>
<td >Decoding advertising packets</td>
</tr>

<tr><td ><a href="https://iotexpert.com/anycloud-bluetooth-advertising-scanner-part-7/" target="_blank" rel="noopener">AnyCloud Bluetooth Advertising Scanner (Part 7)</a></td>
<td >Adding recording commands to the command line</td>
</tr>

<tr><td ><a href="https://iotexpert.com/anycloud-bluetooth-advertising-scanner-part-8/">AnyCloud Bluetooth Advertising Scanner (Part 8)</a></td>
<td >Adding filtering to the scanner</td>
</tr>

<tr><td ><a href="https://iotexpert.com/anycloud-bluetooth-advertising-scanner-part-9/">AnyCloud Bluetooth Advertising Scanner (Part 9)</a></td>
<td >Improve the print and add packet age</td>
</tr>

<tr><td ><a href="https://iotexpert.com/anycloud-bluetooth-advertising-scanner-part-10/">AnyCloud Bluetooth Advertising Scanner (Part 10)</a></td>
<td >Sort the database</td>
</tr>
</tbody></table></div></p>
<p>All of the code can be found at git@github.com:iotexpert/AnyCloudBLEScanner.git and https://github.com/iotexpert/AnyCloudBLEScanner.git</p>
<p>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.</p>
<p>You can also create a new project with this is a template if you have the IoT Expert Manifest Files installed</p></span></p>
<h1>Bluetooth Application Architecture</h1>
<p>Bluetooth applications are divided into these four pieces</p>
<ol>
<li>You user application which responds to events and sends messages from/to the Bluetooth host stack</li>
<li>A Bluetooth Host Stack</li>
<li>A Bluetooth Controller Stack</li>
<li>The Bluetooth Radio</li>
</ol>
<p>These four pieces can be divided into multiple chips, as few as one or as many as four.  However, for this article, the project will be built to run on a PSoC 6 + CYW43012 WiFi/Bluetooth Combo chip.  Specifically:</p>
<ol>
<li>My scanner application running on the PSoC 6</li>
<li>The Bluetooth Host Stack running on the PSoC 6</li>
<li>The BlueTooth Controller Firmware running on the CYW43012</li>
<li>A Bluetooth Radio on the CYW43012</li>
</ol>
<p>But how do they talk?  Simple, there is:</p>
<ol>
<li>A UART Host Controller Interface (HCI) between the two chips</li>
<li>A GPIO to serve as a deep sleep wakeup from the 43012 &#8211;&gt; PSoC 6</li>
<li>A GPIO to serve as the bluetooth controller wakeup from the PSoC 6 &#8211;&gt; 43012</li>
<li>A GPIO to turn on the Bluetooth regulator from the PSoC 6 &#8211;&gt; 43012</li>
</ol>
<p>Here is the block diagram from the CY8CKIT-062S2-43012 Kit Guide.  Notice that signals labeled UART and Control going between the PSoC 6 and the CYW43012.</p>
<p><a href="https://iotexpert.com/anycloud-bluetooth-advertising-scanner-part-1/screen-shot-2020-10-18-at-9-34-51-am/" rel="attachment wp-att-10129"><img loading="lazy" decoding="async" src="https://iotexpert.com/wp-content/uploads/2020/10/Screen-Shot-2020-10-18-at-9.34.51-AM-1024x486.png" alt="" width="1024" height="486" class="alignnone size-large wp-image-10129" srcset="https://iotexpert.com/wp-content/uploads/2020/10/Screen-Shot-2020-10-18-at-9.34.51-AM-1024x486.png 1024w, https://iotexpert.com/wp-content/uploads/2020/10/Screen-Shot-2020-10-18-at-9.34.51-AM-300x142.png 300w, https://iotexpert.com/wp-content/uploads/2020/10/Screen-Shot-2020-10-18-at-9.34.51-AM-768x364.png 768w, https://iotexpert.com/wp-content/uploads/2020/10/Screen-Shot-2020-10-18-at-9.34.51-AM-1536x729.png 1536w, https://iotexpert.com/wp-content/uploads/2020/10/Screen-Shot-2020-10-18-at-9.34.51-AM-2048x972.png 2048w, https://iotexpert.com/wp-content/uploads/2020/10/Screen-Shot-2020-10-18-at-9.34.51-AM-600x285.png 600w" sizes="auto, (max-width: 1024px) 100vw, 1024px" /></a></p>
<p>And when you read more deeply into the schematic you can see the signals labeled</p>
<ul>
<li>BT_UART_TXD/RXD/CTS/RTS</li>
<li>BT_HOST_WAKE</li>
<li>BT_DEV_WAKE</li>
<li>BT_REG_ON</li>
</ul>
<p><a href="https://iotexpert.com/anycloud-bluetooth-advertising-scanner-part-1/screen-shot-2020-10-18-at-9-34-25-am/" rel="attachment wp-att-10128"><img loading="lazy" decoding="async" src="https://iotexpert.com/wp-content/uploads/2020/10/Screen-Shot-2020-10-18-at-9.34.25-AM-1024x875.jpg" alt="" width="1024" height="875" class="alignnone size-large wp-image-10128" srcset="https://iotexpert.com/wp-content/uploads/2020/10/Screen-Shot-2020-10-18-at-9.34.25-AM-1024x875.jpg 1024w, https://iotexpert.com/wp-content/uploads/2020/10/Screen-Shot-2020-10-18-at-9.34.25-AM-300x256.jpg 300w, https://iotexpert.com/wp-content/uploads/2020/10/Screen-Shot-2020-10-18-at-9.34.25-AM-768x656.jpg 768w, https://iotexpert.com/wp-content/uploads/2020/10/Screen-Shot-2020-10-18-at-9.34.25-AM-600x512.jpg 600w, https://iotexpert.com/wp-content/uploads/2020/10/Screen-Shot-2020-10-18-at-9.34.25-AM.jpg 1192w" sizes="auto, (max-width: 1024px) 100vw, 1024px" /></a></p>
<h1>How to Start the AnyCloud Bluetooth Stack</h1>
<p>To actually start the AnyCloud Bluetooth stack you will call two functions</p>
<ol>
<li><strong>cybt_platform_config_init</strong> &#8211; that will setup the hardware interface to the CYW43012</li>
<li><strong>wiced_bt_stack_init</strong> that will:
<ol>
<li>Start a task to manage the Host Controller Interface</li>
<li>Download the controller firmware to the CYW43012</li>
<li>Start a task to manage the host stack</li>
<li>Initialize both the host and the controller</li>
<li>Call you back when that is all done</li>
</ol>
</li>
</ol>
<p>Here is an example from main.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="c">    cybt_platform_config_init(&amp;bt_platform_cfg_settings);
    wiced_bt_stack_init (app_bt_management_callback, &amp;wiced_bt_cfg_settings);</pre>
<p>When you look at these two function calls, you will find that you need to provide three things:</p>
<ol>
<li>A platform hardware configuration structure called bt_platform_cfg_settings</li>
<li>The Bluetooth stack configuration settings structure called wiced_bt_cfg_settings</li>
<li>A management callback called app_bt_management_callback</li>
</ol>
<h1>bt_platform_cfg_settings</h1>
<p>The purpose of the hardware configuration structure is to define the UART + parameters and the wakeup GPIOs.  Specifically, the hardware configuration structure defines the configuration of the host controller interface (hci)</p>
<ol>
<li>The HCI transport scheme (in this case UART)</li>
<li>The pins of the UART</li>
<li>Baud Rate</li>
<li>Data Bits</li>
<li>Stop Bits</li>
<li>Parity</li>
<li>Flow Control</li>
</ol>
<p>And the controller low power behavior (in the .controller_config member)</p>
<p>This is a fairly standard configuration and I think that we should help you by providing this structure somewhere in the BSP.  But for now, you need to provide it (in an upcoming article I&#8217;ll update the IoT Expert Bluetooth Library to provide it).  Here is the specific structure that I will be using.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="c">const cybt_platform_config_t bt_platform_cfg_settings =
{
    .hci_config =
    {
        .hci_transport = CYBT_HCI_UART,

        .hci =
        {
            .hci_uart =
            {
                .uart_tx_pin = CYBSP_BT_UART_TX,
                .uart_rx_pin = CYBSP_BT_UART_RX,
                .uart_rts_pin = CYBSP_BT_UART_RTS,
                .uart_cts_pin = CYBSP_BT_UART_CTS,

                .baud_rate_for_fw_download = 115200,
                .baud_rate_for_feature     = 115200,

                .data_bits = 8,
                .stop_bits = 1,
                .parity = CYHAL_UART_PARITY_NONE,
                .flow_control = WICED_TRUE
            }
        }
    },

    .controller_config =
    {
        .bt_power_pin      = CYBSP_BT_POWER,
        .sleep_mode =
        {
            #if (bt_0_power_0_ENABLED == 1) /* BT Power control is enabled in the LPA */
            #if (CYCFG_BT_LP_ENABLED == 1) /* Low power is enabled in the LPA, use the LPA configuration */
            .sleep_mode_enabled = true,
            .device_wakeup_pin = CYCFG_BT_DEV_WAKE_GPIO,
            .host_wakeup_pin = CYCFG_BT_HOST_WAKE_GPIO,
            .device_wake_polarity = CYCFG_BT_DEV_WAKE_POLARITY,
            .host_wake_polarity = CYCFG_BT_HOST_WAKE_IRQ_EVENT
            #else /* Low power is disabled in the LPA, disable low power */
            .sleep_mode_enabled = false
            #endif
            #else /* BT Power control is disabled in the LPA – default to BSP low power configuration */
            .sleep_mode_enabled = true,
            .device_wakeup_pin = CYBSP_BT_DEVICE_WAKE,
            .host_wakeup_pin = CYBSP_BT_HOST_WAKE,
            .device_wake_polarity = CYBT_WAKE_ACTIVE_LOW,
            .host_wake_polarity = CYBT_WAKE_ACTIVE_LOW
            #endif
        }
    },

    .task_mem_pool_size    = 2048
};
</pre>
<h1>wiced_bt_cfg_settings</h1>
<p>The Cypress WICED Bluetooth Stack has a boatload of configuration settings.  When you call the stack start function you need to provide all of those settings in a structure of type &#8220;wiced_bt_cfg_settings_t&#8221; which is actually a structure of structures.  There are several basic ways to set these settings</p>
<ul>
<li>Start from scratch and build you own settings</li>
<li>Copy from an example project</li>
<li>Use the Bluetooth Configurator to generate the structure</li>
</ul>
<p>For the purposes of THIS project I started by copying the structure from on of the example projects and then modifying the three numbers that were relevant to me.  Specifically</p>
<ul>
<li>max_simultanous_link &#8211; which I changed to 0 because this is simply a Bluetooth Observer</li>
<li>low_duty_scan_interval &#8211; how long in the window to listen for advertising packets</li>
<li>low_duty_scan_window &#8211; how wide the window of listening should be</li>
</ul>
<pre class="EnlighterJSRAW" data-enlighter-language="c">const wiced_bt_cfg_settings_t wiced_bt_cfg_settings =
{
    .device_name                         = (uint8_t *)BT_LOCAL_NAME,                                   /**&lt; Local device name (NULL terminated) */
    .device_class                        = {0x00, 0x00, 0x00},                                         /**&lt; Local device class */
    .security_requirement_mask           = BTM_SEC_NONE,                                               /**&lt; Security requirements mask (BTM_SEC_NONE, or combinination of BTM_SEC_IN_AUTHENTICATE, BTM_SEC_OUT_AUTHENTICATE, BTM_SEC_ENCRYPT (see #wiced_bt_sec_level_e)) */

    .max_simultaneous_links              = 0,                                                          /**&lt; Maximum number simultaneous links to different devices */

    .ble_scan_cfg =                                                 /* BLE scan settings  */
    {
        .scan_mode                       = BTM_BLE_SCAN_MODE_PASSIVE,                                  /**&lt; BLE scan mode (BTM_BLE_SCAN_MODE_PASSIVE, BTM_BLE_SCAN_MODE_ACTIVE, or BTM_BLE_SCAN_MODE_NONE) */

        /* Advertisement scan configuration */
        .high_duty_scan_interval         = WICED_BT_CFG_DEFAULT_HIGH_DUTY_SCAN_INTERVAL,               /**&lt; High duty scan interval */
        .high_duty_scan_window           = WICED_BT_CFG_DEFAULT_HIGH_DUTY_SCAN_WINDOW,                 /**&lt; High duty scan window */
        .high_duty_scan_duration         = 0,                                                          /**&lt; High duty scan duration in seconds (0 for infinite) */

        .low_duty_scan_interval          = 96,                                                         /**&lt; Low duty scan interval  */
        .low_duty_scan_window            = 96,                                                         /**&lt; Low duty scan window */
        .low_duty_scan_duration          = 0,                                                          /**&lt; Low duty scan duration in seconds (0 for infinite) */

        /* Connection scan configuration */
        .high_duty_conn_scan_interval    = WICED_BT_CFG_DEFAULT_HIGH_DUTY_CONN_SCAN_INTERVAL,          /**&lt; High duty cycle connection scan interval */
        .high_duty_conn_scan_window      = WICED_BT_CFG_DEFAULT_HIGH_DUTY_CONN_SCAN_WINDOW,            /**&lt; High duty cycle connection scan window */
        .high_duty_conn_duration         = 0,                                                         /**&lt; High duty cycle connection duration in seconds (0 for infinite) */

        .low_duty_conn_scan_interval     = WICED_BT_CFG_DEFAULT_LOW_DUTY_CONN_SCAN_INTERVAL,           /**&lt; Low duty cycle connection scan interval */
        .low_duty_conn_scan_window       = WICED_BT_CFG_DEFAULT_LOW_DUTY_CONN_SCAN_WINDOW,             /**&lt; Low duty cycle connection scan window */
        .low_duty_conn_duration          = 0,                                                         /**&lt; Low duty cycle connection duration in seconds (0 for infinite) */

        /* Connection configuration */
        .conn_min_interval               = WICED_BT_CFG_DEFAULT_CONN_MIN_INTERVAL,                     /**&lt; Minimum connection interval */
        .conn_max_interval               = WICED_BT_CFG_DEFAULT_CONN_MAX_INTERVAL,                     /**&lt; Maximum connection interval */
        .conn_latency                    = WICED_BT_CFG_DEFAULT_CONN_LATENCY,                          /**&lt; Connection latency */
        .conn_supervision_timeout        = WICED_BT_CFG_DEFAULT_CONN_SUPERVISION_TIMEOUT,              /**&lt; Connection link supervision timeout */
    },

    .default_ble_power_level            = 12                                                           /**&lt; Default LE power level, Refer lm_TxPwrTable table for the power range */
};
</pre>
<h1>app_bt_management_callback</h1>
<p>The last thing that you need to provide is a management callback.  This function is called by the Bluetooth Stack when a &#8220;management event&#8221; occurs.  There is a big-long-list of enumerated events of type wiced_bt_management_event_t.  The events include things like the the stack started &#8220;BTM_ENABLED_EVENT&#8221;.  Each event may have data associated with the event which is passed to you in a pointer to wiced_bt_management_event_data_t.</p>
<p>You typically deal with these events with a giant switch statement like this:</p>
<pre class="EnlighterJSRAW" data-enlighter-language="c">wiced_result_t app_bt_management_callback(wiced_bt_management_evt_t event, wiced_bt_management_evt_data_t *p_event_data)
{
    wiced_result_t result = WICED_BT_SUCCESS;

    switch (event)
    {
        case BTM_ENABLED_EVT:

            if (WICED_BT_SUCCESS == p_event_data-&gt;enabled.status)
            {
               printf("Stack Started Successfully\n");
            }

            break;


        default:
            printf("Unhandled Bluetooth Management Event: 0x%x %s\n", event, btutil_getBTEventName(event));
            break;
    }

    return result;
}
</pre>
<h1>Tasks</h1>
<p>The Bluetooth stack on the PSoC6 is operated with two tasks.  Specifically, when you call the wiced_bt_stack_init it will startup:</p>
<ol>
<li>CYBT_HCI_Task &#8211; a task that sends and receives HCI packets going to the Radio chip</li>
<li>CY_BT_Task &#8211; a task that manages the Bluetooth Host Stack</li>
</ol>
<p>Here is print of the task list from my project:</p>
<pre class="EnlighterJSRAW" data-enlighter-language="c">AnyCloud&gt; tasks
Name          State Priority   Stack  Num
------------------------------------------
nt shell        X       0       236     5
IDLE            R       0       115     6
blink           B       0       98      4
CYBT_BT_Task    B       4       1371    2
sleep_task      B       6       217     1
CYBT_HCI_Task   B       5       950     3
Tmr Svc         B       6       76      7
‘B’ – Blocked
‘R’ – Ready
‘D’ – Deleted (waiting clean up)
‘S’ – Suspended, or Blocked without a timeout
Stack = bytes free at highwater</pre>
<p>&nbsp;</p>
<p>Now with the background in place, in the next article I will discuss Bluetooth advertising and how to build the observer project.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://iotexpert.com/anycloud-bluetooth-advertising-scanner-part-1/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>ModusToolbox 2.2 Template Project &#8211; FreeRTOS + NTShell</title>
		<link>https://iotexpert.com/modustoolbox-2-2-template-project-freertos-ntshell/</link>
					<comments>https://iotexpert.com/modustoolbox-2-2-template-project-freertos-ntshell/#respond</comments>
		
		<dc:creator><![CDATA[Alan Hawse]]></dc:creator>
		<pubDate>Mon, 05 Oct 2020 12:00:59 +0000</pubDate>
				<category><![CDATA[AnyCloud]]></category>
		<category><![CDATA[ModusToolbox]]></category>
		<category><![CDATA[PSoC 6]]></category>
		<guid isPermaLink="false">https://iotexpert.com/?p=9875</guid>

					<description><![CDATA[Summary This article discusses the new library structure that was released with ModusToolbox 2.2.  I explain it by showing the creation of a template project that use FreeRTOS and NT Shell. Story I have often started projects from the IoT Expert FreeRTOS template project.   I realized the other day that almost always the first [&#8230;]]]></description>
										<content:encoded><![CDATA[<h1>Summary</h1>
<p>This article discusses the new library structure that was released with ModusToolbox 2.2.  I explain it by showing the creation of a template project that use FreeRTOS and NT Shell.</p>
<h1>Story</h1>
<p>I have often started projects from the IoT Expert <a href="https://iotexpert.com/2017/08/31/freertos-psoc-template-project/">FreeRTOS template project</a>.   I realized the other day that almost always the first thing I do after creating the project is add the <a href="https://iotexpert.com/2019/10/14/ntshell-for-mbed-os/">NT Shell library</a>.  My friend Hassane has a personal mantra that if he is going to do the same job more than once he will always automate it.  I should have listened to him on this one because I have done it a bunch of times.</p>
<p>In Modus Toolbox 2.2 we have created a new library scheme which allows sharing of libraries between projects.  So this will also be a good example of how that works.</p>
<p>This will also give you another example of adding template projects to your own manifest.</p>
<p>Here is what I am going to do:</p>
<ol>
<li>Create a project from the IoT Expert FreeRTOS Template</li>
<li>Add the NTShell Library &amp; Examine New Library Structure</li>
<li>Update the Project and Program</li>
<li>Add the Task List functionality (a nice feature of FreeRTOS)</li>
<li>Put the new template on GitHub</li>
<li>Update the IoT Expert App Manifest</li>
<li>Test the new Template</li>
</ol>
<h1>Create &amp; Test a project from the IoT Expert FreeRTOS Template</h1>
<p>I will start the whole process by creating  new project using my existing base template.  The kit that I happen to have on my desk right now is the CY8CKIT-062S2-43012.</p>
<p><a href="https://iotexpert.com/modustoolbox-2-2-template-project-freertos-ntshell/screen-shot-2020-10-04-at-9-14-46-am/" rel="attachment wp-att-10715"><img loading="lazy" decoding="async" src="https://iotexpert.com/wp-content/uploads/2020/10/Screen-Shot-2020-10-04-at-9.14.46-AM-1024x714.jpg" alt="" class="alignnone size-large wp-image-10715" width="1024" height="714" srcset="https://iotexpert.com/wp-content/uploads/2020/10/Screen-Shot-2020-10-04-at-9.14.46-AM-1024x714.jpg 1024w, https://iotexpert.com/wp-content/uploads/2020/10/Screen-Shot-2020-10-04-at-9.14.46-AM-300x209.jpg 300w, https://iotexpert.com/wp-content/uploads/2020/10/Screen-Shot-2020-10-04-at-9.14.46-AM-768x536.jpg 768w, https://iotexpert.com/wp-content/uploads/2020/10/Screen-Shot-2020-10-04-at-9.14.46-AM-1536x1071.jpg 1536w, https://iotexpert.com/wp-content/uploads/2020/10/Screen-Shot-2020-10-04-at-9.14.46-AM-2048x1428.jpg 2048w" sizes="auto, (max-width: 1024px) 100vw, 1024px" /></a></p>
<p>Select the IoT Expert FreeRTOS Template and give it a name.  Notice that I add &#8220;NTShell&#8221; to the name (because that is what Im gonna add)</p>
<p><a href="https://iotexpert.com/modustoolbox-2-2-template-project-freertos-ntshell/screen-shot-2020-10-04-at-9-21-22-am/" rel="attachment wp-att-10716"><img loading="lazy" decoding="async" src="https://iotexpert.com/wp-content/uploads/2020/10/Screen-Shot-2020-10-04-at-9.21.22-AM-1024x959.jpg" alt="" class="alignnone size-large wp-image-10716" width="1024" height="959" srcset="https://iotexpert.com/wp-content/uploads/2020/10/Screen-Shot-2020-10-04-at-9.21.22-AM-1024x959.jpg 1024w, https://iotexpert.com/wp-content/uploads/2020/10/Screen-Shot-2020-10-04-at-9.21.22-AM-300x281.jpg 300w, https://iotexpert.com/wp-content/uploads/2020/10/Screen-Shot-2020-10-04-at-9.21.22-AM-768x719.jpg 768w, https://iotexpert.com/wp-content/uploads/2020/10/Screen-Shot-2020-10-04-at-9.21.22-AM-1536x1438.jpg 1536w, https://iotexpert.com/wp-content/uploads/2020/10/Screen-Shot-2020-10-04-at-9.21.22-AM.jpg 1754w" sizes="auto, (max-width: 1024px) 100vw, 1024px" /></a></p>
<p>When you click create, Modus will do its magic and build you a complete project.</p>
<p><a href="https://iotexpert.com/modustoolbox-2-2-template-project-freertos-ntshell/screen-shot-2020-10-04-at-9-23-18-am/"><img loading="lazy" decoding="async" src="https://iotexpert.com/wp-content/uploads/2020/10/Screen-Shot-2020-10-04-at-9.23.18-AM-1024x783.png" alt="" class="alignnone wp-image-10717 size-large" width="1024" height="783" srcset="https://iotexpert.com/wp-content/uploads/2020/10/Screen-Shot-2020-10-04-at-9.23.18-AM-1024x783.png 1024w, https://iotexpert.com/wp-content/uploads/2020/10/Screen-Shot-2020-10-04-at-9.23.18-AM-300x229.png 300w, https://iotexpert.com/wp-content/uploads/2020/10/Screen-Shot-2020-10-04-at-9.23.18-AM-768x587.png 768w, https://iotexpert.com/wp-content/uploads/2020/10/Screen-Shot-2020-10-04-at-9.23.18-AM-1536x1175.png 1536w, https://iotexpert.com/wp-content/uploads/2020/10/Screen-Shot-2020-10-04-at-9.23.18-AM.png 1624w" sizes="auto, (max-width: 1024px) 100vw, 1024px" /></a></p>
<p>Today Im going to edit using Visual Studio Code.  Actually almost always I edit using Visual Studio Code.  You can do all of these tasks using Eclipse as well.  To turn my created project into a VSCODE project run &#8220;make vscode&#8221;</p>
<p><a href="https://iotexpert.com/modustoolbox-2-2-template-project-freertos-ntshell/screen-shot-2020-10-04-at-9-26-04-am/"><img loading="lazy" decoding="async" src="https://iotexpert.com/wp-content/uploads/2020/10/Screen-Shot-2020-10-04-at-9.26.04-AM-834x1024.jpg" alt="" class="alignnone wp-image-10718 size-large" width="834" height="1024" srcset="https://iotexpert.com/wp-content/uploads/2020/10/Screen-Shot-2020-10-04-at-9.26.04-AM-834x1024.jpg 834w, https://iotexpert.com/wp-content/uploads/2020/10/Screen-Shot-2020-10-04-at-9.26.04-AM-244x300.jpg 244w, https://iotexpert.com/wp-content/uploads/2020/10/Screen-Shot-2020-10-04-at-9.26.04-AM-768x942.jpg 768w, https://iotexpert.com/wp-content/uploads/2020/10/Screen-Shot-2020-10-04-at-9.26.04-AM-1252x1536.jpg 1252w, https://iotexpert.com/wp-content/uploads/2020/10/Screen-Shot-2020-10-04-at-9.26.04-AM.jpg 1506w" sizes="auto, (max-width: 834px) 100vw, 834px" /></a></p>
<p>Before getting to far down the road I like to run a build to make sure everything is OK.  So &#8220;make -j build&#8221;</p>
<pre class="EnlighterJSRAW" data-enlighter-language="c">arh (master) IoT_Expert_FreeRTOS_NTShell_Template $ make -j build
Tools Directory: /Applications/ModusToolbox/tools_2.2
CY8CKIT-062S2-43012.mk: ../mtb_shared/TARGET_CY8CKIT-062S2-43012/latest-v2.X/CY8CKIT-062S2-43012.mk

Prebuild operations complete
Commencing build operations...

Tools Directory: /Applications/ModusToolbox/tools_2.2
CY8CKIT-062S2-43012.mk: ../mtb_shared/TARGET_CY8CKIT-062S2-43012/latest-v2.X/CY8CKIT-062S2-43012.mk

Initializing build: MTBShellTemplate Debug CY8CKIT-062S2-43012 GCC_ARM

Auto-discovery in progress...
-&gt; Found 195 .c file(s)
-&gt; Found 46 .S file(s)
-&gt; Found 23 .s file(s)
-&gt; Found 0 .cpp file(s)
-&gt; Found 0 .o file(s)
-&gt; Found 6 .a file(s)
-&gt; Found 491 .h file(s)
-&gt; Found 0 .hpp file(s)
-&gt; Found 0 resource file(s)
Applying filters...
Auto-discovery complete

Constructing build rules...
Build rules construction complete

==============================================================================
= Building application =
==============================================================================
Generating compilation database file...
-&gt; ./build/compile_commands.json
Compilation database file generation complete
Building 183 file(s)
    Compiling app file lowPower.c
    Compiling app file main.c
    Compiling ext file startup_psoc6_02_cm4.S
    Compiling ext file cy_syslib_gcc.S
    Compiling ext file cycfg.c
    Compiling ext file cycfg_capsense.c
    Compiling ext file cycfg_clocks.c

....a bunch of stuff deleted

    Compiling ext file psoc6_04_cm0p_sleep.c
    Compiling ext file cy_retarget_io.c
    Linking output file MTBShellTemplate.elf
==============================================================================
= Build complete =
==============================================================================

Calculating memory consumption: CY8C624ABZI-S2D44 GCC_ARM -Og

   ---------------------------------------------------- 
  | Section Name         |  Address      |  Size       | 
   ---------------------------------------------------- 
  | .cy_m0p_image        |  0x10000000   |  6044       | 
  | .text                |  0x10002000   |  30280      | 
  | .ARM.exidx           |  0x10009648   |  8          | 
  | .copy.table          |  0x10009650   |  24         | 
  | .zero.table          |  0x10009668   |  8          | 
  | .data                |  0x080022e0   |  1320       | 
  | .cy_sharedmem        |  0x08002808   |  8          | 
  | .noinit              |  0x08002810   |  148        | 
  | .bss                 |  0x080028a4   |  1324       | 
  | .heap                |  0x08002dd0   |  1030704    | 
   ---------------------------------------------------- 

  Total Internal Flash (Available)          2097152    
  Total Internal Flash (Utilized)           39848      

  Total Internal SRAM (Available)           1046528    
  Total Internal SRAM (Utilized with heap)  1033504    

  
arh (master) IoT_Expert_FreeRTOS_NTShell_Template $</pre>
<p>Then program it, just to make sure.  &#8220;make program&#8221;</p>
<pre class="EnlighterJSRAW" data-enlighter-language="c">arh (master) IoT_Expert_FreeRTOS_NTShell_Template $ make program
Tools Directory: /Applications/ModusToolbox/tools_2.2
CY8CKIT-062S2-43012.mk: ../mtb_shared/TARGET_CY8CKIT-062S2-43012/latest-v2.X/CY8CKIT-062S2-43012.mk

Prebuild operations complete
Commencing build operations...

Tools Directory: /Applications/ModusToolbox/tools_2.2
CY8CKIT-062S2-43012.mk: ../mtb_shared/TARGET_CY8CKIT-062S2-43012/latest-v2.X/CY8CKIT-062S2-43012.mk

Initializing build: MTBShellTemplate Debug CY8CKIT-062S2-43012 GCC_ARM

Auto-discovery in progress...
-&gt; Found 195 .c file(s)
-&gt; Found 46 .S file(s)
-&gt; Found 23 .s file(s)
-&gt; Found 0 .cpp file(s)
-&gt; Found 0 .o file(s)
-&gt; Found 6 .a file(s)
-&gt; Found 491 .h file(s)
-&gt; Found 0 .hpp file(s)
-&gt; Found 0 resource file(s)
Applying filters...
Auto-discovery complete

Constructing build rules...
Build rules construction complete

==============================================================================
= Building application =
==============================================================================
Generating compilation database file...
-&gt; ./build/compile_commands.json
Compilation database file generation complete
Building 183 file(s)
==============================================================================
= Build complete =
==============================================================================

Calculating memory consumption: CY8C624ABZI-S2D44 GCC_ARM -Og

   ---------------------------------------------------- 
  | Section Name         |  Address      |  Size       | 
   ---------------------------------------------------- 
  | .cy_m0p_image        |  0x10000000   |  6044       | 
  | .text                |  0x10002000   |  30280      | 
  | .ARM.exidx           |  0x10009648   |  8          | 
  | .copy.table          |  0x10009650   |  24         | 
  | .zero.table          |  0x10009668   |  8          | 
  | .data                |  0x080022e0   |  1320       | 
  | .cy_sharedmem        |  0x08002808   |  8          | 
  | .noinit              |  0x08002810   |  148        | 
  | .bss                 |  0x080028a4   |  1324       | 
  | .heap                |  0x08002dd0   |  1030704    | 
   ---------------------------------------------------- 

  Total Internal Flash (Available)          2097152    
  Total Internal Flash (Utilized)           39848      

  Total Internal SRAM (Available)           1046528    
  Total Internal SRAM (Utilized with heap)  1033504    


Programming target device... 
Open On-Chip Debugger 0.10.0+dev-4.1.0.1058 (2020-08-11-03:45)
Licensed under GNU GPL v2
For bug reports, read
	http://openocd.org/doc/doxygen/bugs.html
Info : auto-selecting first available session transport "swd". To override use 'transport select &lt;transport&gt;'.
adapter speed: 2000 kHz
adapter srst delay: 25
adapter srst pulse_width: 25
** Auto-acquire enabled, use "set ENABLE_ACQUIRE 0" to disable
cortex_m reset_config sysresetreq
cortex_m reset_config sysresetreq
Info : Using CMSIS loader 'CY8C6xxA_SMIF' for bank 'psoc6_smif0_cm0' (footprint 14672 bytes)
Warn : SFlash programming allowed for regions: USER, TOC, KEY
Info : CMSIS-DAP: SWD  Supported
Info : CMSIS-DAP: FW Version = 2.0.0
Info : CMSIS-DAP: Interface Initialised (SWD)
Info : SWCLK/TCK = 1 SWDIO/TMS = 1 TDI = 0 TDO = 0 nTRST = 0 nRESET = 1
Info : CMSIS-DAP: Interface ready
Info : KitProg3: FW version: 1.14.514
Info : KitProg3: Pipelined transfers disabled, please update the firmware
Info : VTarget = 3.221 V
Info : kitprog3: acquiring the device...
Info : clock speed 2000 kHz
Info : SWD DPIDR 0x6ba02477
Info : psoc6.cpu.cm0: hardware has 4 breakpoints, 2 watchpoints
***************************************
** Silicon: 0xE453, Family: 0x102, Rev.: 0x12 (A1)
** Detected Device: CY8C624ABZI-S2D44
** Detected Main Flash size, kb: 2048
** Flash Boot version: 3.1.0.378
** Chip Protection: NORMAL
***************************************
Info : psoc6.cpu.cm4: hardware has 6 breakpoints, 4 watchpoints
Info : starting gdb server for psoc6.cpu.cm0 on 3333
Info : Listening on port 3333 for gdb connections
Info : starting gdb server for psoc6.cpu.cm4 on 3334
Info : Listening on port 3334 for gdb connections
Info : SWD DPIDR 0x6ba02477
Info : kitprog3: acquiring the device...
psoc6.cpu.cm0 halted due to debug-request, current mode: Thread 
xPSR: 0x41000000 pc: 0x00000190 msp: 0x080ff800
** Device acquired successfully
** psoc6.cpu.cm4: Ran after reset and before halt...
psoc6.cpu.cm4 halted due to debug-request, current mode: Thread 
xPSR: 0x01000000 pc: 0x0000012a msp: 0x080ff800
** Programming Started **
auto erase enabled
Info : Flash write discontinued at 0x1000179c, next section at 0x10002000
Info : Padding image section 0 at 0x1000179c with 100 bytes (bank write end alignment)
[100%] [################################] [ Erasing     ]
[100%] [################################] [ Programming ]
Info : Padding image section 1 at 0x10009ba0 with 96 bytes (bank write end alignment)
[100%] [################################] [ Erasing     ]
[100%] [################################] [ Programming ]
wrote 37888 bytes from file /Users/arh/mtb22/IoT_Expert_FreeRTOS_NTShell_Template/build/CY8CKIT-062S2-43012/Debug/MTBShellTemplate.hex in 1.402638s (26.379 KiB/s)
** Programming Finished **
** Verify Started **
verified 37692 bytes in 0.080973s (454.579 KiB/s)
** Verified OK **
** Resetting Target **
Info : SWD DPIDR 0x6ba02477
shutdown command invoked
Info : psoc6.dap: powering down debug domain...
Warn : Failed to power down Debug Domains
  
arh (master) IoT_Expert_FreeRTOS_NTShell_Template $</pre>
<h1>Add the NTShell Library &amp; Examine New Library Structure</h1>
<p>Everything is working and my basic project has FreeRTOS and a blinking LED.  Now let&#8217;s add the NT Shell Library.  To do this run the library manager by running &#8220;make modlibs&#8221; (or click on the button in Eclipse).  Select Libraries &#8211;&gt; IoT Expert &#8211;&gt; ntshell<a href="https://iotexpert.com/modustoolbox-2-2-template-project-freertos-ntshell/screen-shot-2020-10-04-at-9-29-44-am/"><img loading="lazy" decoding="async" src="https://iotexpert.com/wp-content/uploads/2020/10/Screen-Shot-2020-10-04-at-9.29.44-AM-773x1024.jpg" alt="" class="alignnone wp-image-10719 size-large" width="773" height="1024" srcset="https://iotexpert.com/wp-content/uploads/2020/10/Screen-Shot-2020-10-04-at-9.29.44-AM-773x1024.jpg 773w, https://iotexpert.com/wp-content/uploads/2020/10/Screen-Shot-2020-10-04-at-9.29.44-AM-226x300.jpg 226w, https://iotexpert.com/wp-content/uploads/2020/10/Screen-Shot-2020-10-04-at-9.29.44-AM-768x1017.jpg 768w, https://iotexpert.com/wp-content/uploads/2020/10/Screen-Shot-2020-10-04-at-9.29.44-AM-1160x1536.jpg 1160w, https://iotexpert.com/wp-content/uploads/2020/10/Screen-Shot-2020-10-04-at-9.29.44-AM.jpg 1516w" sizes="auto, (max-width: 773px) 100vw, 773px" /></a></p>
<p>When you press update, the library manager will do its thing again.</p>
<p><a href="https://iotexpert.com/modustoolbox-2-2-template-project-freertos-ntshell/screen-shot-2020-10-04-at-9-30-07-am/"><img loading="lazy" decoding="async" src="https://iotexpert.com/wp-content/uploads/2020/10/Screen-Shot-2020-10-04-at-9.30.07-AM-1024x756.png" alt="" class="alignnone wp-image-10720 size-large" width="1024" height="756" srcset="https://iotexpert.com/wp-content/uploads/2020/10/Screen-Shot-2020-10-04-at-9.30.07-AM-1024x756.png 1024w, https://iotexpert.com/wp-content/uploads/2020/10/Screen-Shot-2020-10-04-at-9.30.07-AM-300x221.png 300w, https://iotexpert.com/wp-content/uploads/2020/10/Screen-Shot-2020-10-04-at-9.30.07-AM-768x567.png 768w, https://iotexpert.com/wp-content/uploads/2020/10/Screen-Shot-2020-10-04-at-9.30.07-AM.png 1398w" sizes="auto, (max-width: 1024px) 100vw, 1024px" /></a></p>
<p>When I look in the &#8220;deps&#8221; directory, I see some new file types called &#8220;.mtb&#8221;.  These files tell your project where to find each of the libraries.  Notice that the middleware-ntshell.mtb points to &#8220;$$ASSET_REPO$$&#8221;.  Where is that?</p>
<p><a href="https://iotexpert.com/modustoolbox-2-2-template-project-freertos-ntshell/screen-shot-2020-10-04-at-9-32-07-am/"><img loading="lazy" decoding="async" src="https://iotexpert.com/wp-content/uploads/2020/10/Screen-Shot-2020-10-04-at-9.32.07-AM-1024x237.png" alt="" class="alignnone wp-image-10721 size-large" width="1024" height="237" srcset="https://iotexpert.com/wp-content/uploads/2020/10/Screen-Shot-2020-10-04-at-9.32.07-AM-1024x237.png 1024w, https://iotexpert.com/wp-content/uploads/2020/10/Screen-Shot-2020-10-04-at-9.32.07-AM-300x69.png 300w, https://iotexpert.com/wp-content/uploads/2020/10/Screen-Shot-2020-10-04-at-9.32.07-AM-768x178.png 768w, https://iotexpert.com/wp-content/uploads/2020/10/Screen-Shot-2020-10-04-at-9.32.07-AM-1536x355.png 1536w, https://iotexpert.com/wp-content/uploads/2020/10/Screen-Shot-2020-10-04-at-9.32.07-AM.png 1540w" sizes="auto, (max-width: 1024px) 100vw, 1024px" /></a></p>
<p>If you have a aook at the Makefile it tell you that it is &#8220;../&#8221; and &#8220;mtb_shared&#8221;.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="c"># Relative path to the shared repo location.
#
# All .mtb files have the format, &lt;URI&gt;&lt;COMMIT&gt;&lt;LOCATION&gt;. If the &lt;LOCATION&gt; field 
# begins with $$ASSET_REPO$$, then the repo is deposited in the path specified by 
# the CY_GETLIBS_SHARED_PATH variable. The default location is one directory level 
# above the current app directory.
# This is used with CY_GETLIBS_SHARED_NAME variable, which specifies the directory name.
CY_GETLIBS_SHARED_PATH=../

# Directory name of the shared repo location.
#
CY_GETLIBS_SHARED_NAME=mtb_shared</pre>
<p>To start editing I will run Visual Studio Code by typing &#8220;code .&#8221;.  The first thing that happens is that it notices that this is a workspace instead of just a directory.</p>
<p><a href="https://iotexpert.com/modustoolbox-2-2-template-project-freertos-ntshell/screen-shot-2020-10-04-at-9-36-19-am/" rel="attachment wp-att-10723"><img loading="lazy" decoding="async" src="https://iotexpert.com/wp-content/uploads/2020/10/Screen-Shot-2020-10-04-at-9.36.19-AM.png" alt="" class="alignnone size-full wp-image-10723" width="922" height="278" srcset="https://iotexpert.com/wp-content/uploads/2020/10/Screen-Shot-2020-10-04-at-9.36.19-AM.png 922w, https://iotexpert.com/wp-content/uploads/2020/10/Screen-Shot-2020-10-04-at-9.36.19-AM-300x90.png 300w, https://iotexpert.com/wp-content/uploads/2020/10/Screen-Shot-2020-10-04-at-9.36.19-AM-768x232.png 768w" sizes="auto, (max-width: 922px) 100vw, 922px" /></a></p>
<p>And when you look at the workspace you can see that it knows about both the example project as well as &#8220;mtb_shared&#8221;.  That is sweet.</p>
<p><a href="https://iotexpert.com/modustoolbox-2-2-template-project-freertos-ntshell/screen-shot-2020-10-04-at-10-38-58-am/"><img loading="lazy" decoding="async" src="https://iotexpert.com/wp-content/uploads/2020/10/Screen-Shot-2020-10-04-at-10.38.58-AM-417x1024.png" alt="" class="alignnone wp-image-10714 size-large" width="417" height="1024" srcset="https://iotexpert.com/wp-content/uploads/2020/10/Screen-Shot-2020-10-04-at-10.38.58-AM-417x1024.png 417w, https://iotexpert.com/wp-content/uploads/2020/10/Screen-Shot-2020-10-04-at-10.38.58-AM-122x300.png 122w, https://iotexpert.com/wp-content/uploads/2020/10/Screen-Shot-2020-10-04-at-10.38.58-AM.png 486w" sizes="auto, (max-width: 417px) 100vw, 417px" /></a></p>
<h1>Update the Project and Program</h1>
<p>Now follow the instructions from the middlware-ntshell readme by copying &#8220;usrcmd.*&#8221; into my project.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="c">arh (master) IoT_Expert_FreeRTOS_NTShell_Template $ cp ../mtb_shared/middleware-ntshell/latest-v2.X/template/psoc6sdk/usrcmd.* .</pre>
<p>Then I edit main.c to</p>
<ol>
<li>#include &#8220;usrcmd.h&#8221; on line 8</li>
<li>Start the shell task which is called &#8220;usrcmd_task&#8221; on line 39</li>
</ol>
<p><a href="https://iotexpert.com/modustoolbox-2-2-template-project-freertos-ntshell/screen-shot-2020-10-04-at-9-42-45-am/"><img loading="lazy" decoding="async" src="https://iotexpert.com/wp-content/uploads/2020/10/Screen-Shot-2020-10-04-at-9.42.45-AM-1024x936.jpg" alt="" class="alignnone wp-image-10725 size-large" width="1024" height="936" srcset="https://iotexpert.com/wp-content/uploads/2020/10/Screen-Shot-2020-10-04-at-9.42.45-AM-1024x936.jpg 1024w, https://iotexpert.com/wp-content/uploads/2020/10/Screen-Shot-2020-10-04-at-9.42.45-AM-300x274.jpg 300w, https://iotexpert.com/wp-content/uploads/2020/10/Screen-Shot-2020-10-04-at-9.42.45-AM-768x702.jpg 768w, https://iotexpert.com/wp-content/uploads/2020/10/Screen-Shot-2020-10-04-at-9.42.45-AM-1536x1405.jpg 1536w, https://iotexpert.com/wp-content/uploads/2020/10/Screen-Shot-2020-10-04-at-9.42.45-AM.jpg 1824w" sizes="auto, (max-width: 1024px) 100vw, 1024px" /></a></p>
<p>Now buid/project by running &#8220;make -j program&#8221;</p>
<pre class="EnlighterJSRAW" data-enlighter-language="c">arh (master *) IoT_Expert_FreeRTOS_NTShell_Template $ make -j program
Tools Directory: /Applications/ModusToolbox/tools_2.2
CY8CKIT-062S2-43012.mk: ../mtb_shared/TARGET_CY8CKIT-062S2-43012/latest-v2.X/CY8CKIT-062S2-43012.mk

Prebuild operations complete
Commencing build operations...

Tools Directory: /Applications/ModusToolbox/tools_2.2
CY8CKIT-062S2-43012.mk: ../mtb_shared/TARGET_CY8CKIT-062S2-43012/latest-v2.X/CY8CKIT-062S2-43012.mk

Initializing build: MTBShellTemplate Debug CY8CKIT-062S2-43012 GCC_ARM

Auto-discovery in progress...
-&gt; Found 205 .c file(s)
-&gt; Found 46 .S file(s)
-&gt; Found 23 .s file(s)
-&gt; Found 0 .cpp file(s)
-&gt; Found 0 .o file(s)
-&gt; Found 6 .a file(s)
-&gt; Found 503 .h file(s)
-&gt; Found 0 .hpp file(s)
-&gt; Found 0 resource file(s)
Applying filters...
Auto-discovery complete

Constructing build rules...
Build rules construction complete

==============================================================================
= Building application =
==============================================================================
Generating compilation database file...
-&gt; ./build/compile_commands.json
Compilation database file generation complete
Building 193 file(s)
    Compiling app file main.c
    Linking output file MTBShellTemplate.elf
==============================================================================
= Build complete =
==============================================================================

Calculating memory consumption: CY8C624ABZI-S2D44 GCC_ARM -Og

   ---------------------------------------------------- 
  | Section Name         |  Address      |  Size       | 
   ---------------------------------------------------- 
  | .cy_m0p_image        |  0x10000000   |  6044       | 
  | .text                |  0x10002000   |  52780      | 
  | .ARM.exidx           |  0x1000ee2c   |  8          | 
  | .copy.table          |  0x1000ee34   |  24         | 
  | .zero.table          |  0x1000ee4c   |  8          | 
  | .data                |  0x080022e0   |  1688       | 
  | .cy_sharedmem        |  0x08002978   |  8          | 
  | .noinit              |  0x08002980   |  148        | 
  | .bss                 |  0x08002a14   |  2136       | 
  | .heap                |  0x08003270   |  1029520    | 
   ---------------------------------------------------- 

  Total Internal Flash (Available)          2097152    
  Total Internal Flash (Utilized)           62716      

  Total Internal SRAM (Available)           1046528    
  Total Internal SRAM (Utilized with heap)  1033500    


Programming target device... 
Open On-Chip Debugger 0.10.0+dev-4.1.0.1058 (2020-08-11-03:45)
Licensed under GNU GPL v2
For bug reports, read
	http://openocd.org/doc/doxygen/bugs.html
Info : auto-selecting first available session transport "swd". To override use 'transport select &lt;transport&gt;'.
adapter speed: 2000 kHz
adapter srst delay: 25
adapter srst pulse_width: 25
** Auto-acquire enabled, use "set ENABLE_ACQUIRE 0" to disable
cortex_m reset_config sysresetreq
cortex_m reset_config sysresetreq
Info : Using CMSIS loader 'CY8C6xxA_SMIF' for bank 'psoc6_smif0_cm0' (footprint 14672 bytes)
Warn : SFlash programming allowed for regions: USER, TOC, KEY
Info : CMSIS-DAP: SWD  Supported
Info : CMSIS-DAP: FW Version = 2.0.0
Info : CMSIS-DAP: Interface Initialised (SWD)
Info : SWCLK/TCK = 1 SWDIO/TMS = 1 TDI = 0 TDO = 0 nTRST = 0 nRESET = 1
Info : CMSIS-DAP: Interface ready
Info : KitProg3: FW version: 1.14.514
Info : KitProg3: Pipelined transfers disabled, please update the firmware
Info : VTarget = 3.225 V
Info : kitprog3: acquiring the device...
Info : clock speed 2000 kHz
Info : SWD DPIDR 0x6ba02477
Info : psoc6.cpu.cm0: hardware has 4 breakpoints, 2 watchpoints
***************************************
** Silicon: 0xE453, Family: 0x102, Rev.: 0x12 (A1)
** Detected Device: CY8C624ABZI-S2D44
** Detected Main Flash size, kb: 2048
** Flash Boot version: 3.1.0.378
** Chip Protection: NORMAL
***************************************
Info : psoc6.cpu.cm4: hardware has 6 breakpoints, 4 watchpoints
Info : starting gdb server for psoc6.cpu.cm0 on 3333
Info : Listening on port 3333 for gdb connections
Info : starting gdb server for psoc6.cpu.cm4 on 3334
Info : Listening on port 3334 for gdb connections
Info : SWD DPIDR 0x6ba02477
Info : kitprog3: acquiring the device...
psoc6.cpu.cm0 halted due to debug-request, current mode: Thread 
xPSR: 0x41000000 pc: 0x00000190 msp: 0x080ff800
** Device acquired successfully
** psoc6.cpu.cm4: Ran after reset and before halt...
psoc6.cpu.cm4 halted due to debug-request, current mode: Thread 
xPSR: 0x01000000 pc: 0x0000012a msp: 0x080ff800
** Programming Started **
auto erase enabled
Info : Flash write discontinued at 0x1000179c, next section at 0x10002000
Info : Padding image section 0 at 0x1000179c with 100 bytes (bank write end alignment)
[100%] [################################] [ Erasing     ]
[100%] [################################] [ Programming ]
Info : Padding image section 1 at 0x1000f4f4 with 268 bytes (bank write end alignment)
[100%] [################################] [ Erasing     ]
[100%] [################################] [ Programming ]
wrote 60928 bytes from file /Users/arh/mtb22/IoT_Expert_FreeRTOS_NTShell_Template/build/CY8CKIT-062S2-43012/Debug/MTBShellTemplate.hex in 2.017097s (29.498 KiB/s)
** Programming Finished **
** Verify Started **
verified 60560 bytes in 0.119193s (496.175 KiB/s)
** Verified OK **
** Resetting Target **
Info : SWD DPIDR 0x6ba02477
shutdown command invoked
Info : psoc6.dap: powering down debug domain...
  
arh (master *) IoT_Expert_FreeRTOS_NTShell_Template $</pre>
<p>Now I have a functional shell.  Here is the serial console.</p>
<p><a href="https://iotexpert.com/modustoolbox-2-2-template-project-freertos-ntshell/screen-shot-2020-10-04-at-9-44-30-am-1/"><img loading="lazy" decoding="async" src="https://iotexpert.com/wp-content/uploads/2020/10/Screen-Shot-2020-10-04-at-9.44.30-AM-1-1024x274.png" alt="" class="alignnone wp-image-10726 size-large" width="1024" height="274" srcset="https://iotexpert.com/wp-content/uploads/2020/10/Screen-Shot-2020-10-04-at-9.44.30-AM-1-1024x274.png 1024w, https://iotexpert.com/wp-content/uploads/2020/10/Screen-Shot-2020-10-04-at-9.44.30-AM-1-300x80.png 300w, https://iotexpert.com/wp-content/uploads/2020/10/Screen-Shot-2020-10-04-at-9.44.30-AM-1-768x206.png 768w, https://iotexpert.com/wp-content/uploads/2020/10/Screen-Shot-2020-10-04-at-9.44.30-AM-1.png 1516w" sizes="auto, (max-width: 1024px) 100vw, 1024px" /></a></p>
<h1>Add the Task List functionality</h1>
<p>In the main.c above I started up the usrcmd_task with a stack size of config_MINIMAL_STACK_SIZE * 4.  Where did I get that?  Well the first couple of times I did this it crashed by running out of stack so I tried bigger and bigger numbers until it stopped crashing.  This is a kind of a pain in the ass.   If you know FreeRTOS there is a function called &#8220;vTaskList&#8221; which will give you stats about the tasks.</p>
<p>In order to use that function you need to turn it on.  Notice that I #ifdef and #if to see if it is turned on inside of usrcmd.c</p>
<pre class="EnlighterJSRAW" data-enlighter-language="c">#ifdef configUSE_TRACE_FACILITY
#if configUSE_STATS_FORMATTING_FUNCTIONS ==1
static int usrcmd_list(int argc, char **argv);
#endif
#endif
</pre>
<p>So let&#8217;s turn it on by editing &#8220;FreeRTOSConfig.h&#8221; and enabling the two required defines.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="c">#define configUSE_TRACE_FACILITY					1
#define configUSE_STATS_FORMATTING_FUNCTIONS        1</pre>
<p>Now build/program.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="c">arh (master *) IoT_Expert_FreeRTOS_NTShell_Template $ make -j program
Tools Directory: /Applications/ModusToolbox/tools_2.2
CY8CKIT-062S2-43012.mk: ../mtb_shared/TARGET_CY8CKIT-062S2-43012/latest-v2.X/CY8CKIT-062S2-43012.mk

Prebuild operations complete
Commencing build operations...

Tools Directory: /Applications/ModusToolbox/tools_2.2
CY8CKIT-062S2-43012.mk: ../mtb_shared/TARGET_CY8CKIT-062S2-43012/latest-v2.X/CY8CKIT-062S2-43012.mk

Initializing build: MTBShellTemplate Debug CY8CKIT-062S2-43012 GCC_ARM

Auto-discovery in progress...
-&gt; Found 205 .c file(s)
-&gt; Found 46 .S file(s)
-&gt; Found 23 .s file(s)
-&gt; Found 0 .cpp file(s)
-&gt; Found 0 .o file(s)
-&gt; Found 6 .a file(s)
-&gt; Found 503 .h file(s)
-&gt; Found 0 .hpp file(s)
-&gt; Found 0 resource file(s)
Applying filters...
Auto-discovery complete

Constructing build rules...
Build rules construction complete

==============================================================================
= Building application =
==============================================================================
Generating compilation database file...
-&gt; ./build/compile_commands.json
Compilation database file generation complete
Building 193 file(s)
    Compiling app file lowPower.c
    Compiling app file main.c
    Compiling app file usrcmd.c
    Compiling ext file croutine.c
    Compiling ext file event_groups.c
    Compiling ext file list.c
    Compiling ext file heap_1.c
    Compiling ext file heap_2.c
    Compiling ext file heap_3.c
    Compiling ext file heap_4.c
    Compiling ext file heap_5.c
    Compiling ext file port.c
    Compiling ext file queue.c
    Compiling ext file stream_buffer.c
    Compiling ext file tasks.c
    Compiling ext file timers.c
    Compiling ext file psoc6_ntshell_port.c
    Linking output file MTBShellTemplate.elf
==============================================================================
= Build complete =
==============================================================================

Calculating memory consumption: CY8C624ABZI-S2D44 GCC_ARM -Og

   ---------------------------------------------------- 
  | Section Name         |  Address      |  Size       | 
   ---------------------------------------------------- 
  | .cy_m0p_image        |  0x10000000   |  6044       | 
  | .text                |  0x10002000   |  54876      | 
  | .ARM.exidx           |  0x1000f65c   |  8          | 
  | .copy.table          |  0x1000f664   |  24         | 
  | .zero.table          |  0x1000f67c   |  8          | 
  | .data                |  0x080022e0   |  1688       | 
  | .cy_sharedmem        |  0x08002978   |  8          | 
  | .noinit              |  0x08002980   |  148        | 
  | .bss                 |  0x08002a14   |  2136       | 
  | .heap                |  0x08003270   |  1029520    | 
   ---------------------------------------------------- 

  Total Internal Flash (Available)          2097152    
  Total Internal Flash (Utilized)           64812      

  Total Internal SRAM (Available)           1046528    
  Total Internal SRAM (Utilized with heap)  1033500    


Programming target device... 
Open On-Chip Debugger 0.10.0+dev-4.1.0.1058 (2020-08-11-03:45)
Licensed under GNU GPL v2
For bug reports, read
	http://openocd.org/doc/doxygen/bugs.html
Info : auto-selecting first available session transport "swd". To override use 'transport select &lt;transport&gt;'.
adapter speed: 2000 kHz
adapter srst delay: 25
adapter srst pulse_width: 25
** Auto-acquire enabled, use "set ENABLE_ACQUIRE 0" to disable
cortex_m reset_config sysresetreq
cortex_m reset_config sysresetreq
Info : Using CMSIS loader 'CY8C6xxA_SMIF' for bank 'psoc6_smif0_cm0' (footprint 14672 bytes)
Warn : SFlash programming allowed for regions: USER, TOC, KEY
Info : CMSIS-DAP: SWD  Supported
Info : CMSIS-DAP: FW Version = 2.0.0
Info : CMSIS-DAP: Interface Initialised (SWD)
Info : SWCLK/TCK = 1 SWDIO/TMS = 1 TDI = 0 TDO = 0 nTRST = 0 nRESET = 1
Info : CMSIS-DAP: Interface ready
Info : KitProg3: FW version: 1.14.514
Info : KitProg3: Pipelined transfers disabled, please update the firmware
Info : VTarget = 3.220 V
Info : kitprog3: acquiring the device...
Info : clock speed 2000 kHz
Info : SWD DPIDR 0x6ba02477
Info : psoc6.cpu.cm0: hardware has 4 breakpoints, 2 watchpoints
***************************************
** Silicon: 0xE453, Family: 0x102, Rev.: 0x12 (A1)
** Detected Device: CY8C624ABZI-S2D44
** Detected Main Flash size, kb: 2048
** Flash Boot version: 3.1.0.378
** Chip Protection: NORMAL
***************************************
Info : psoc6.cpu.cm4: hardware has 6 breakpoints, 4 watchpoints
Info : starting gdb server for psoc6.cpu.cm0 on 3333
Info : Listening on port 3333 for gdb connections
Info : starting gdb server for psoc6.cpu.cm4 on 3334
Info : Listening on port 3334 for gdb connections
Info : SWD DPIDR 0x6ba02477
Info : kitprog3: acquiring the device...
psoc6.cpu.cm0 halted due to debug-request, current mode: Thread 
xPSR: 0x41000000 pc: 0x00000190 msp: 0x080ff800
** Device acquired successfully
** psoc6.cpu.cm4: Ran after reset and before halt...
psoc6.cpu.cm4 halted due to debug-request, current mode: Thread 
xPSR: 0x01000000 pc: 0x0000012a msp: 0x080ff800
** Programming Started **
auto erase enabled
Info : Flash write discontinued at 0x1000179c, next section at 0x10002000
Info : Padding image section 0 at 0x1000179c with 100 bytes (bank write end alignment)
[100%] [################################] [ Erasing     ]
[100%] [################################] [ Programming ]
Info : Padding image section 1 at 0x1000fd24 with 220 bytes (bank write end alignment)
[100%] [################################] [ Erasing     ]
[100%] [################################] [ Programming ]
wrote 62976 bytes from file /Users/arh/mtb22/IoT_Expert_FreeRTOS_NTShell_Template/build/CY8CKIT-062S2-43012/Debug/MTBShellTemplate.hex in 2.092903s (29.385 KiB/s)
** Programming Finished **
** Verify Started **
verified 62656 bytes in 0.123619s (494.968 KiB/s)
** Verified OK **
** Resetting Target **
Info : SWD DPIDR 0x6ba02477
shutdown command invoked
Info : psoc6.dap: powering down debug domain...</pre>
<p>When I run help you can see I have a new command called &#8220;tasks&#8221; which lists all of the tasks and their stack high water marks.<br />
<a href="https://iotexpert.com/modustoolbox-2-2-template-project-freertos-ntshell/screen-shot-2020-10-04-at-9-48-14-am/"><img loading="lazy" decoding="async" src="https://iotexpert.com/wp-content/uploads/2020/10/Screen-Shot-2020-10-04-at-9.48.14-AM-1024x418.png" alt="" class="alignnone wp-image-10728 size-large" width="1024" height="418" srcset="https://iotexpert.com/wp-content/uploads/2020/10/Screen-Shot-2020-10-04-at-9.48.14-AM-1024x418.png 1024w, https://iotexpert.com/wp-content/uploads/2020/10/Screen-Shot-2020-10-04-at-9.48.14-AM-300x123.png 300w, https://iotexpert.com/wp-content/uploads/2020/10/Screen-Shot-2020-10-04-at-9.48.14-AM-768x314.png 768w, https://iotexpert.com/wp-content/uploads/2020/10/Screen-Shot-2020-10-04-at-9.48.14-AM.png 1522w" sizes="auto, (max-width: 1024px) 100vw, 1024px" /></a></p>
<h1>Put the Template on GitHub</h1>
<p>I am happy with my new template.  So, I go to GitHub and create a new repository.<br />
<a href="https://iotexpert.com/modustoolbox-2-2-template-project-freertos-ntshell/screen-shot-2020-10-04-at-9-50-46-am/"><img loading="lazy" decoding="async" src="https://iotexpert.com/wp-content/uploads/2020/10/Screen-Shot-2020-10-04-at-9.50.46-AM-1024x749.png" alt="" class="alignnone wp-image-10729 size-large" width="1024" height="749" srcset="https://iotexpert.com/wp-content/uploads/2020/10/Screen-Shot-2020-10-04-at-9.50.46-AM-1024x749.png 1024w, https://iotexpert.com/wp-content/uploads/2020/10/Screen-Shot-2020-10-04-at-9.50.46-AM-300x219.png 300w, https://iotexpert.com/wp-content/uploads/2020/10/Screen-Shot-2020-10-04-at-9.50.46-AM-768x562.png 768w, https://iotexpert.com/wp-content/uploads/2020/10/Screen-Shot-2020-10-04-at-9.50.46-AM-1536x1123.png 1536w, https://iotexpert.com/wp-content/uploads/2020/10/Screen-Shot-2020-10-04-at-9.50.46-AM.png 1704w" sizes="auto, (max-width: 1024px) 100vw, 1024px" /></a></p>
<p>Then on my current project:</p>
<ol>
<li>I blow away the git history (didnt really have to do that).</li>
<li>Create a new git repo &#8220;git init .&#8221;</li>
<li>Add a pointer to GitHub &#8220;git remote add&#8230;.&#8221;</li>
<li>Add all of the files &#8220;git add *&#8221;</li>
<li>Add the .gitignore &#8220;git add .gitignore&#8221;</li>
<li>Commit the changes &#8220;git commit&#8230;&#8221;</li>
<li>Push it to GitHub &#8220;git push &#8230;&#8221;</li>
</ol>
<pre class="EnlighterJSRAW" data-enlighter-language="c">arh (master *) IoT_Expert_FreeRTOS_NTShell_Template $ rm -rf .git
arh IoT_Expert_FreeRTOS_NTShell_Template $ git init .
Initialized empty Git repository in /Users/arh/mtb22/IoT_Expert_FreeRTOS_NTShell_Template/.git/
arh (master #) IoT_Expert_FreeRTOS_NTShell_Template $ git remote add origin git@iotexpert.github.com:iotexpert/mtb2-freertos-ntshell-template.git
arh (master #) IoT_Expert_FreeRTOS_NTShell_Template $ git add * 
The following paths are ignored by one of your .gitignore files:
build
Use -f if you really want to add them.
arh (master #) IoT_Expert_FreeRTOS_NTShell_Template $ git add .gitignore
arh (master #) IoT_Expert_FreeRTOS_NTShell_Template $ git status
On branch master

No commits yet

Changes to be committed:
  (use "git rm --cached &lt;file&gt;..." to unstage)
	new file:   .gitignore
	new file:   FreeRTOSConfig.h
	new file:   LICENSE
	new file:   MTBShellTemplate.code-workspace
	new file:   Makefile
	new file:   README.md
	new file:   deps/TARGET_CY8CKIT-062S2-43012.mtb
	new file:   deps/freertos.mtb
	new file:   deps/middleware-ntshell.mtb
	new file:   deps/retarget-io.mtb
	new file:   global.h
	new file:   lowPower.c
	new file:   main.c
	new file:   openocd.tcl
	new file:   usrcmd.c
	new file:   usrcmd.h

Untracked files:
  (use "git add &lt;file&gt;..." to include in what will be committed)
	.vscode/

arh (master #) IoT_Expert_FreeRTOS_NTShell_Template $ git commit -m "Initial commit"
[master (root-commit) 26b5d3c] Initial commit
 16 files changed, 994 insertions(+)
 create mode 100644 .gitignore
 create mode 100644 FreeRTOSConfig.h
 create mode 100644 LICENSE
 create mode 100644 MTBShellTemplate.code-workspace
 create mode 100644 Makefile
 create mode 100644 README.md
 create mode 100644 deps/TARGET_CY8CKIT-062S2-43012.mtb
 create mode 100644 deps/freertos.mtb
 create mode 100644 deps/middleware-ntshell.mtb
 create mode 100644 deps/retarget-io.mtb
 create mode 100644 global.h
 create mode 100644 lowPower.c
 create mode 100644 main.c
 create mode 100644 openocd.tcl
 create mode 100644 usrcmd.c
 create mode 100644 usrcmd.h
arh (master) IoT_Expert_FreeRTOS_NTShell_Template $ git push -u origin master
Enumerating objects: 19, done.
Counting objects: 100% (19/19), done.
Delta compression using up to 12 threads
Compressing objects: 100% (19/19), done.
Writing objects: 100% (19/19), 16.21 KiB | 5.40 MiB/s, done.
Total 19 (delta 0), reused 0 (delta 0)
To iotexpert.github.com:iotexpert/mtb2-freertos-ntshell-template.git
 * [new branch]      master -&gt; master
Branch 'master' set up to track remote branch 'master' from 'origin'.
arh (master) IoT_Expert_FreeRTOS_NTShell_Template $</pre>
<h1>Update the Manifests</h1>
<p>To get access to the new template I need to add it to the IoT Expert App Manifest.  I edit the xml file to have the new app</p>
<pre class="EnlighterJSRAW" data-enlighter-language="c">&lt;apps&gt;
  &lt;app&gt;
    &lt;name&gt;IoT Expert FreeRTOS Template&lt;/name&gt;
    &lt;id&gt;mtb2-freertos-template&lt;/id&gt;
    &lt;uri&gt;https://github.com/iotexpert/mtb2-freertos-template&lt;/uri&gt;
    &lt;description&gt;This template provide a starting point for FreeRTOS projects.  Including a starting blinking LED task&lt;/description&gt;
    &lt;req_capabilities&gt;psoc6&lt;/req_capabilities&gt;
    &lt;versions&gt;
      &lt;version&gt;
        &lt;num&gt;Latest 1.X release&lt;/num&gt;
        &lt;commit&gt;master&lt;/commit&gt;
      &lt;/version&gt;
    &lt;/versions&gt;
  &lt;/app&gt;
    &lt;app&gt;
    &lt;name&gt;IoT Expert FreeRTOS NTShell Template&lt;/name&gt;
    &lt;id&gt;mtb2-freertos-ntshell-template&lt;/id&gt;
    &lt;uri&gt;https://github.com/iotexpert/mtb2-freertos-ntshell-template&lt;/uri&gt;
    &lt;description&gt;This template provide a starting point for FreeRTOS projects.  Including a starting blinking LED task and shell&lt;/description&gt;
    &lt;req_capabilities&gt;psoc6&lt;/req_capabilities&gt;
    &lt;versions&gt;
      &lt;version&gt;
        &lt;num&gt;Latest 1.X release&lt;/num&gt;
        &lt;commit&gt;master&lt;/commit&gt;
      &lt;/version&gt;
    &lt;/versions&gt;
  &lt;/app&gt;
&lt;/apps&gt;</pre>
<p>Now I need to git add, git commit and git push it to GitHub.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="c">arh (master) mtb2-iotexpert-manifests $ code .
arh (master) mtb2-iotexpert-manifests $ git status
On branch master
Your branch is up to date with 'origin/master'.

Changes not staged for commit:
  (use "git add &lt;file&gt;..." to update what will be committed)
  (use "git restore &lt;file&gt;..." to discard changes in working directory)
	modified:   iotexpert-app-manifest.xml

no changes added to commit (use "git add" and/or "git commit -a")
arh (master *) mtb2-iotexpert-manifests $ git add iotexpert-app-manifest.xml
arh (master +) mtb2-iotexpert-manifests $ git commit -m "Updated with ntshell example"
[master 47a7bb1] Updated with ntshell example
 1 file changed, 13 insertions(+)
arh (master) mtb2-iotexpert-manifests $ git push
Enumerating objects: 5, done.
Counting objects: 100% (5/5), done.
Delta compression using up to 12 threads
Compressing objects: 100% (3/3), done.
Writing objects: 100% (3/3), 554 bytes | 554.00 KiB/s, done.
Total 3 (delta 1), reused 0 (delta 0)
remote: Resolving deltas: 100% (1/1), completed with 1 local object.
To iotexpert.github.com:iotexpert/mtb2-iotexpert-manifests.git
   28ed2d0..47a7bb1  master -&gt; master
</pre>
<h1>Test the new Template</h1>
<p>Everything should be working so make a new project.<br />
<a href="https://iotexpert.com/modustoolbox-2-2-template-project-freertos-ntshell/screen-shot-2020-10-04-at-10-00-29-am/"><img loading="lazy" decoding="async" src="https://iotexpert.com/wp-content/uploads/2020/10/Screen-Shot-2020-10-04-at-10.00.29-AM-1024x701.jpg" alt="" class="alignnone wp-image-10711 size-large" width="1024" height="701" srcset="https://iotexpert.com/wp-content/uploads/2020/10/Screen-Shot-2020-10-04-at-10.00.29-AM-1024x701.jpg 1024w, https://iotexpert.com/wp-content/uploads/2020/10/Screen-Shot-2020-10-04-at-10.00.29-AM-300x205.jpg 300w, https://iotexpert.com/wp-content/uploads/2020/10/Screen-Shot-2020-10-04-at-10.00.29-AM-768x526.jpg 768w, https://iotexpert.com/wp-content/uploads/2020/10/Screen-Shot-2020-10-04-at-10.00.29-AM-1536x1052.jpg 1536w, https://iotexpert.com/wp-content/uploads/2020/10/Screen-Shot-2020-10-04-at-10.00.29-AM-2048x1402.jpg 2048w" sizes="auto, (max-width: 1024px) 100vw, 1024px" /></a></p>
<p>Cool.  There is the new template.<br />
<a href="https://iotexpert.com/modustoolbox-2-2-template-project-freertos-ntshell/screen-shot-2020-10-04-at-10-08-12-am/"><img loading="lazy" decoding="async" src="https://iotexpert.com/wp-content/uploads/2020/10/Screen-Shot-2020-10-04-at-10.08.12-AM-1024x700.jpg" alt="" class="alignnone wp-image-10712 size-large" width="1024" height="700" srcset="https://iotexpert.com/wp-content/uploads/2020/10/Screen-Shot-2020-10-04-at-10.08.12-AM-1024x700.jpg 1024w, https://iotexpert.com/wp-content/uploads/2020/10/Screen-Shot-2020-10-04-at-10.08.12-AM-300x205.jpg 300w, https://iotexpert.com/wp-content/uploads/2020/10/Screen-Shot-2020-10-04-at-10.08.12-AM-768x525.jpg 768w, https://iotexpert.com/wp-content/uploads/2020/10/Screen-Shot-2020-10-04-at-10.08.12-AM-1536x1050.jpg 1536w, https://iotexpert.com/wp-content/uploads/2020/10/Screen-Shot-2020-10-04-at-10.08.12-AM-2048x1401.jpg 2048w" sizes="auto, (max-width: 1024px) 100vw, 1024px" /></a></p>
<p>When I program it&#8230; everything is cool.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="c">arh (master) TestNTS $ make -j program
Tools Directory: /Applications/ModusToolbox/tools_2.2
CY8CKIT-062S2-43012.mk: ../mtb_shared/TARGET_CY8CKIT-062S2-43012/latest-v2.X/CY8CKIT-062S2-43012.mk

Prebuild operations complete
Commencing build operations...

Tools Directory: /Applications/ModusToolbox/tools_2.2
CY8CKIT-062S2-43012.mk: ../mtb_shared/TARGET_CY8CKIT-062S2-43012/latest-v2.X/CY8CKIT-062S2-43012.mk

Initializing build: MTBShellTemplate Debug CY8CKIT-062S2-43012 GCC_ARM

Auto-discovery in progress...
-&gt; Found 205 .c file(s)
-&gt; Found 46 .S file(s)
-&gt; Found 23 .s file(s)
-&gt; Found 0 .cpp file(s)
-&gt; Found 0 .o file(s)
-&gt; Found 6 .a file(s)
-&gt; Found 503 .h file(s)
-&gt; Found 0 .hpp file(s)
-&gt; Found 0 resource file(s)
Applying filters...
Auto-discovery complete

Constructing build rules...
Build rules construction complete

==============================================================================
= Building application =
==============================================================================
Generating compilation database file...
-&gt; ./build/compile_commands.json
Compilation database file generation complete
Building 193 file(s)
    Compiling app file lowPower.c
    Compiling app file main.c
    Compiling app file usrcmd.c
    Compiling ext file startup_psoc6_02_cm4.S
    Compiling ext file cy_syslib_gcc.S
    Compiling ext file cycfg.c
    Compiling ext file cycfg_capsense.c
    Compiling ext file cycfg_clocks.c
    Compiling ext file cycfg_peripherals.c
    Compiling ext file cycfg_pins.c
    Compiling ext file cycfg_qspi_memslot.c
    Compiling ext file cycfg_routing.c
    Compiling ext file cycfg_system.c
    Compiling ext file system_psoc6_cm4.c
    Compiling ext file cybsp.c
    Compiling ext file cy_capsense_centroid.c
    Compiling ext file cy_capsense_control.c
    Compiling ext file cy_capsense_csd.c
    Compiling ext file cy_capsense_csx.c
    Compiling ext file cy_capsense_filter.c
    Compiling ext file cy_capsense_processing.c
    Compiling ext file cy_capsense_selftest.c
    Compiling ext file cy_capsense_sensing.c
    Compiling ext file cy_capsense_structure.c
    Compiling ext file cy_capsense_tuner.c
    Compiling ext file croutine.c
    Compiling ext file event_groups.c
    Compiling ext file list.c
    Compiling ext file heap_1.c
    Compiling ext file heap_2.c
    Compiling ext file heap_3.c
    Compiling ext file heap_4.c
    Compiling ext file heap_5.c
    Compiling ext file port.c
    Compiling ext file queue.c
    Compiling ext file stream_buffer.c
    Compiling ext file tasks.c
    Compiling ext file timers.c
    Compiling ext file ntlibc.c
    Compiling ext file ntshell.c
    Compiling ext file text_editor.c
    Compiling ext file text_history.c
    Compiling ext file vtrecv.c
    Compiling ext file vtsend.c
    Compiling ext file psoc6_ntshell_port.c
    Compiling ext file ntopt.c
    Compiling ext file ntstdio.c
    Compiling ext file cyhal_adc.c
    Compiling ext file cyhal_analog_common.c
    Compiling ext file cyhal_clock.c
    Compiling ext file cyhal_comp.c
    Compiling ext file cyhal_comp_ctb.c
    Compiling ext file cyhal_comp_lp.c
    Compiling ext file cyhal_crc.c
    Compiling ext file cyhal_crypto_common.c
    Compiling ext file cyhal_dac.c
    Compiling ext file cyhal_deprecated.c
    Compiling ext file cyhal_dma.c
    Compiling ext file cyhal_dma_dmac.c
    Compiling ext file cyhal_dma_dw.c
    Compiling ext file cyhal_ezi2c.c
    Compiling ext file cyhal_flash.c
    Compiling ext file cyhal_gpio.c
    Compiling ext file cyhal_hwmgr.c
    Compiling ext file cyhal_i2c.c
    Compiling ext file cyhal_i2s.c
    Compiling ext file cyhal_interconnect.c
    Compiling ext file cyhal_lptimer.c
    Compiling ext file cyhal_not_implemented.c
    Compiling ext file cyhal_opamp.c
    Compiling ext file cyhal_pdmpcm.c
    Compiling ext file cyhal_pwm.c
    Compiling ext file cyhal_qspi.c
    Compiling ext file cyhal_rtc.c
    Compiling ext file cyhal_scb_common.c
    Compiling ext file cyhal_sdhc.c
    Compiling ext file cyhal_spi.c
    Compiling ext file cyhal_syspm.c
    Compiling ext file cyhal_system.c
    Compiling ext file cyhal_tcpwm_common.c
    Compiling ext file cyhal_timer.c
    Compiling ext file cyhal_trng.c
    Compiling ext file cyhal_uart.c
    Compiling ext file cyhal_udb_sdio.c
    Compiling ext file cyhal_usb_dev.c
    Compiling ext file cyhal_utils.c
    Compiling ext file cyhal_wdt.c
    Compiling ext file cyhal_psoc6_01_104_m_csp_ble.c
    Compiling ext file cyhal_psoc6_01_104_m_csp_ble_usb.c
    Compiling ext file cyhal_psoc6_01_116_bga_ble.c
    Compiling ext file cyhal_psoc6_01_116_bga_usb.c
    Compiling ext file cyhal_psoc6_01_124_bga.c
    Compiling ext file cyhal_psoc6_01_124_bga_sip.c
    Compiling ext file cyhal_psoc6_01_43_smt.c
    Compiling ext file cyhal_psoc6_01_68_qfn_ble.c
    Compiling ext file cyhal_psoc6_01_80_wlcsp.c
    Compiling ext file cyhal_psoc6_02_100_wlcsp.c
    Compiling ext file cyhal_psoc6_02_124_bga.c
    Compiling ext file cyhal_psoc6_02_128_tqfp.c
    Compiling ext file cyhal_psoc6_02_68_qfn.c
    Compiling ext file cyhal_psoc6_03_100_tqfp.c
    Compiling ext file cyhal_psoc6_03_49_wlcsp.c
    Compiling ext file cyhal_psoc6_03_68_qfn.c
    Compiling ext file cyhal_psoc6_04_64_tqfp.c
    Compiling ext file cyhal_psoc6_04_68_qfn.c
    Compiling ext file cyhal_psoc6_04_80_tqfp.c
    Compiling ext file cyhal_triggers_psoc6_01.c
    Compiling ext file cyhal_triggers_psoc6_02.c
    Compiling ext file cyhal_triggers_psoc6_03.c
    Compiling ext file cyhal_triggers_psoc6_04.c
    Compiling ext file cy_ble_clk.c
    Compiling ext file cy_canfd.c
    Compiling ext file cy_crypto.c
    Compiling ext file cy_crypto_core_aes_v1.c
    Compiling ext file cy_crypto_core_aes_v2.c
    Compiling ext file cy_crypto_core_cmac_v1.c
    Compiling ext file cy_crypto_core_cmac_v2.c
    Compiling ext file cy_crypto_core_crc_v1.c
    Compiling ext file cy_crypto_core_crc_v2.c
    Compiling ext file cy_crypto_core_des_v1.c
    Compiling ext file cy_crypto_core_des_v2.c
    Compiling ext file cy_crypto_core_ecc_domain_params.c
    Compiling ext file cy_crypto_core_ecc_ecdsa.c
    Compiling ext file cy_crypto_core_ecc_key_gen.c
    Compiling ext file cy_crypto_core_ecc_nist_p.c
    Compiling ext file cy_crypto_core_hmac_v1.c
    Compiling ext file cy_crypto_core_hmac_v2.c
    Compiling ext file cy_crypto_core_hw.c
    Compiling ext file cy_crypto_core_hw_v1.c
    Compiling ext file cy_crypto_core_mem_v1.c
    Compiling ext file cy_crypto_core_mem_v2.c
    Compiling ext file cy_crypto_core_prng_v1.c
    Compiling ext file cy_crypto_core_prng_v2.c
    Compiling ext file cy_crypto_core_rsa.c
    Compiling ext file cy_crypto_core_sha_v1.c
    Compiling ext file cy_crypto_core_sha_v2.c
    Compiling ext file cy_crypto_core_trng_v1.c
    Compiling ext file cy_crypto_core_trng_v2.c
    Compiling ext file cy_crypto_core_vu.c
    Compiling ext file cy_crypto_server.c
    Compiling ext file cy_csd.c
    Compiling ext file cy_ctb.c
    Compiling ext file cy_ctdac.c
    Compiling ext file cy_device.c
    Compiling ext file cy_dma.c
    Compiling ext file cy_dmac.c
    Compiling ext file cy_efuse.c
    Compiling ext file cy_flash.c
    Compiling ext file cy_gpio.c
    Compiling ext file cy_i2s.c
    Compiling ext file cy_ipc_drv.c
    Compiling ext file cy_ipc_pipe.c
    Compiling ext file cy_ipc_sema.c
    Compiling ext file cy_lpcomp.c
    Compiling ext file cy_lvd.c
    Compiling ext file cy_mcwdt.c
    Compiling ext file cy_pdm_pcm.c
    Compiling ext file cy_pra.c
    Compiling ext file cy_pra_cfg.c
    Compiling ext file cy_profile.c
    Compiling ext file cy_prot.c
    Compiling ext file cy_rtc.c
    Compiling ext file cy_sar.c
    Compiling ext file cy_scb_common.c
    Compiling ext file cy_scb_ezi2c.c
    Compiling ext file cy_scb_i2c.c
    Compiling ext file cy_scb_spi.c
    Compiling ext file cy_scb_uart.c
    Compiling ext file cy_sd_host.c
    Compiling ext file cy_seglcd.c
    Compiling ext file cy_smartio.c
    Compiling ext file cy_smif.c
    Compiling ext file cy_smif_memslot.c
    Compiling ext file cy_sysanalog.c
    Compiling ext file cy_sysclk.c
    Compiling ext file cy_sysint.c
    Compiling ext file cy_syslib.c
    Compiling ext file cy_syspm.c
    Compiling ext file cy_systick.c
    Compiling ext file cy_tcpwm_counter.c
    Compiling ext file cy_tcpwm_pwm.c
    Compiling ext file cy_tcpwm_quaddec.c
    Compiling ext file cy_tcpwm_shiftreg.c
    Compiling ext file cy_trigmux.c
    Compiling ext file cy_usbfs_dev_drv.c
    Compiling ext file cy_usbfs_dev_drv_io.c
    Compiling ext file cy_usbfs_dev_drv_io_dma.c
    Compiling ext file cy_wdt.c
    Compiling ext file psoc6_01_cm0p_sleep.c
    Compiling ext file psoc6_02_cm0p_sleep.c
    Compiling ext file psoc6_03_cm0p_sleep.c
    Compiling ext file psoc6_04_cm0p_sleep.c
    Compiling ext file cy_retarget_io.c
    Linking output file MTBShellTemplate.elf
==============================================================================
= Build complete =
==============================================================================

Calculating memory consumption: CY8C624ABZI-S2D44 GCC_ARM -Og

   ---------------------------------------------------- 
  | Section Name         |  Address      |  Size       | 
   ---------------------------------------------------- 
  | .cy_m0p_image        |  0x10000000   |  6044       | 
  | .text                |  0x10002000   |  54876      | 
  | .ARM.exidx           |  0x1000f65c   |  8          | 
  | .copy.table          |  0x1000f664   |  24         | 
  | .zero.table          |  0x1000f67c   |  8          | 
  | .data                |  0x080022e0   |  1688       | 
  | .cy_sharedmem        |  0x08002978   |  8          | 
  | .noinit              |  0x08002980   |  148        | 
  | .bss                 |  0x08002a14   |  2136       | 
  | .heap                |  0x08003270   |  1029520    | 
   ---------------------------------------------------- 

  Total Internal Flash (Available)          2097152    
  Total Internal Flash (Utilized)           64812      

  Total Internal SRAM (Available)           1046528    
  Total Internal SRAM (Utilized with heap)  1033500    


Programming target device... 
Open On-Chip Debugger 0.10.0+dev-4.1.0.1058 (2020-08-11-03:45)
Licensed under GNU GPL v2
For bug reports, read
	http://openocd.org/doc/doxygen/bugs.html
Info : auto-selecting first available session transport "swd". To override use 'transport select &lt;transport&gt;'.
adapter speed: 2000 kHz
adapter srst delay: 25
adapter srst pulse_width: 25
** Auto-acquire enabled, use "set ENABLE_ACQUIRE 0" to disable
cortex_m reset_config sysresetreq
cortex_m reset_config sysresetreq
Info : Using CMSIS loader 'CY8C6xxA_SMIF' for bank 'psoc6_smif0_cm0' (footprint 14672 bytes)
Warn : SFlash programming allowed for regions: USER, TOC, KEY
Info : CMSIS-DAP: SWD  Supported
Info : CMSIS-DAP: FW Version = 2.0.0
Info : CMSIS-DAP: Interface Initialised (SWD)
Info : SWCLK/TCK = 1 SWDIO/TMS = 1 TDI = 0 TDO = 0 nTRST = 0 nRESET = 1
Info : CMSIS-DAP: Interface ready
Info : KitProg3: FW version: 1.14.514
Info : KitProg3: Pipelined transfers disabled, please update the firmware
Info : VTarget = 3.221 V
Info : kitprog3: acquiring the device...
Info : clock speed 2000 kHz
Info : SWD DPIDR 0x6ba02477
Info : psoc6.cpu.cm0: hardware has 4 breakpoints, 2 watchpoints
***************************************
** Silicon: 0xE453, Family: 0x102, Rev.: 0x12 (A1)
** Detected Device: CY8C624ABZI-S2D44
** Detected Main Flash size, kb: 2048
** Flash Boot version: 3.1.0.378
** Chip Protection: NORMAL
***************************************
Info : psoc6.cpu.cm4: hardware has 6 breakpoints, 4 watchpoints
Info : starting gdb server for psoc6.cpu.cm0 on 3333
Info : Listening on port 3333 for gdb connections
Info : starting gdb server for psoc6.cpu.cm4 on 3334
Info : Listening on port 3334 for gdb connections
Info : SWD DPIDR 0x6ba02477
Info : kitprog3: acquiring the device...
psoc6.cpu.cm0 halted due to debug-request, current mode: Thread 
xPSR: 0x41000000 pc: 0x00000190 msp: 0x080ff800
** Device acquired successfully
** psoc6.cpu.cm4: Ran after reset and before halt...
psoc6.cpu.cm4 halted due to debug-request, current mode: Thread 
xPSR: 0x01000000 pc: 0x0000012a msp: 0x080ff800
** Programming Started **
auto erase enabled
Info : Flash write discontinued at 0x1000179c, next section at 0x10002000
Info : Padding image section 0 at 0x1000179c with 100 bytes (bank write end alignment)
[100%] [################################] [ Erasing     ]
[100%] [################################] [ Programming ]
Info : Padding image section 1 at 0x1000fd24 with 220 bytes (bank write end alignment)
[100%] [################################] [ Erasing     ]
[100%] [################################] [ Programming ]
wrote 62976 bytes from file /Users/arh/mtb22/TestNTS/build/CY8CKIT-062S2-43012/Debug/MTBShellTemplate.hex in 2.082329s (29.534 KiB/s)
** Programming Finished **
** Verify Started **
verified 62656 bytes in 0.122516s (499.425 KiB/s)
** Verified OK **
** Resetting Target **
Info : SWD DPIDR 0x6ba02477
shutdown command invoked
Info : psoc6.dap: powering down debug domain...
  
arh (master) TestNTS $</pre>
<p>And the project seems to be doing the needful.<br />
<a href="https://iotexpert.com/modustoolbox-2-2-template-project-freertos-ntshell/screen-shot-2020-10-04-at-10-09-31-am/"><img loading="lazy" decoding="async" src="https://iotexpert.com/wp-content/uploads/2020/10/Screen-Shot-2020-10-04-at-10.09.31-AM-1024x475.png" alt="" class="alignnone wp-image-10713 size-large" width="1024" height="475" srcset="https://iotexpert.com/wp-content/uploads/2020/10/Screen-Shot-2020-10-04-at-10.09.31-AM-1024x475.png 1024w, https://iotexpert.com/wp-content/uploads/2020/10/Screen-Shot-2020-10-04-at-10.09.31-AM-300x139.png 300w, https://iotexpert.com/wp-content/uploads/2020/10/Screen-Shot-2020-10-04-at-10.09.31-AM-768x356.png 768w, https://iotexpert.com/wp-content/uploads/2020/10/Screen-Shot-2020-10-04-at-10.09.31-AM.png 1478w" sizes="auto, (max-width: 1024px) 100vw, 1024px" /></a></p>
]]></content:encoded>
					
					<wfw:commentRss>https://iotexpert.com/modustoolbox-2-2-template-project-freertos-ntshell/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>AnyCloud &#8211; Wireless Connection Manager (Part 1)</title>
		<link>https://iotexpert.com/anycloud-wireless-connection-manager-part-1/</link>
					<comments>https://iotexpert.com/anycloud-wireless-connection-manager-part-1/#respond</comments>
		
		<dc:creator><![CDATA[Alan Hawse]]></dc:creator>
		<pubDate>Mon, 04 May 2020 12:00:44 +0000</pubDate>
				<category><![CDATA[4343W]]></category>
		<category><![CDATA[AnyCloud]]></category>
		<category><![CDATA[CY8CKIT-062S2-43012]]></category>
		<category><![CDATA[CY8CPROTO-062-4343W]]></category>
		<category><![CDATA[PSoC 6]]></category>
		<guid isPermaLink="false">https://iotexpert.com/?p=9019</guid>

					<description><![CDATA[Summary A discussion of using the Infineon (Cypress) PSoC 6 with a CYW4343W and the AnyCloud Connection Manager with Modus Toolbox.  The AnyCloud Connection Manager is an RTOS thread that lets you manage a connection to a WiFi network.  It knows how to scan for networks, attach, detach etc. and was recently released for use [&#8230;]]]></description>
										<content:encoded><![CDATA[<h1>Summary</h1>
<p>A discussion of using the Infineon (Cypress) PSoC 6 with a CYW4343W and the AnyCloud Connection Manager with Modus Toolbox.  The AnyCloud Connection Manager is an RTOS thread that lets you manage a connection to a WiFi network.  It knows how to scan for networks, attach, detach etc. and was recently released for use with PSoC6 and 43xxx WiFi combos.</p>
<h1>The Story</h1>
<p>In the WICED WiFI SDK there is an example program called &#8220;test.console&#8221; which allows you to use a UART command line to do networking &#8220;stuff&#8221;.  With the release of the new AnyCloud SDK I decided that I should rebuild some of that program using the PSoC and WiFi.  Basically a set of commands like &#8220;scan&#8221; to interact with the Radio World!  In the picture you below you can see that I use the command &#8220;scan&#8221; to list out the networks at my house.</p>
<p><a href="https://iotexpert.com/2020/05/04/anycloud-wireless-connection-manager-part-1/screen-shot-2020-04-27-at-1-04-36-pm/" rel="attachment wp-att-9021"><img loading="lazy" decoding="async" src="https://iotexpert.com/wp-content/uploads/2020/04/Screen-Shot-2020-04-27-at-1.04.36-PM-1024x623.png" alt="" width="1024" height="623" class="alignnone size-large wp-image-9021" srcset="https://iotexpert.com/wp-content/uploads/2020/04/Screen-Shot-2020-04-27-at-1.04.36-PM-1024x623.png 1024w, https://iotexpert.com/wp-content/uploads/2020/04/Screen-Shot-2020-04-27-at-1.04.36-PM-600x365.png 600w, https://iotexpert.com/wp-content/uploads/2020/04/Screen-Shot-2020-04-27-at-1.04.36-PM-300x182.png 300w, https://iotexpert.com/wp-content/uploads/2020/04/Screen-Shot-2020-04-27-at-1.04.36-PM-768x467.png 768w, https://iotexpert.com/wp-content/uploads/2020/04/Screen-Shot-2020-04-27-at-1.04.36-PM-1536x934.png 1536w, https://iotexpert.com/wp-content/uploads/2020/04/Screen-Shot-2020-04-27-at-1.04.36-PM.png 1950w" sizes="auto, (max-width: 1024px) 100vw, 1024px" /></a></p>
<p>You can also use the command &#8220;help&#8221; to list out the commands.</p>
<p><a href="https://iotexpert.com/2020/05/04/anycloud-wireless-connection-manager-part-1/screen-shot-2020-04-27-at-1-04-58-pm/" rel="attachment wp-att-9022"><img loading="lazy" decoding="async" src="https://iotexpert.com/wp-content/uploads/2020/04/Screen-Shot-2020-04-27-at-1.04.58-PM-1024x299.png" alt="" width="1024" height="299" class="alignnone size-large wp-image-9022" srcset="https://iotexpert.com/wp-content/uploads/2020/04/Screen-Shot-2020-04-27-at-1.04.58-PM-1024x299.png 1024w, https://iotexpert.com/wp-content/uploads/2020/04/Screen-Shot-2020-04-27-at-1.04.58-PM-600x175.png 600w, https://iotexpert.com/wp-content/uploads/2020/04/Screen-Shot-2020-04-27-at-1.04.58-PM-300x88.png 300w, https://iotexpert.com/wp-content/uploads/2020/04/Screen-Shot-2020-04-27-at-1.04.58-PM-768x224.png 768w, https://iotexpert.com/wp-content/uploads/2020/04/Screen-Shot-2020-04-27-at-1.04.58-PM-1536x449.png 1536w, https://iotexpert.com/wp-content/uploads/2020/04/Screen-Shot-2020-04-27-at-1.04.58-PM.png 1732w" sizes="auto, (max-width: 1024px) 100vw, 1024px" /></a><a href="https://iotexpert.com/2020/05/04/anycloud-wireless-connection-manager-part-1/screen-shot-2020-04-27-at-1-04-58-pm/" rel="attachment wp-att-9022"></a></p>
<h1>Architecture</h1>
<p>My implementation will have three tasks</p>
<ol>
<li>A Blinking LED Task (which doesn&#8217;t interact with any other tasks)</li>
<li>The NT Shell &#8211; which will send commands to the network queue.</li>
<li>The Network Task which will receive commands from the NT Shell task and trigger the Wireless Connection Manager to do something</li>
<li>The Wireless Connection Manager which will interact with the WiFI Radio via the Wireless Host driver.</li>
</ol>
<p><a href="https://iotexpert.com/?attachment_id=9131" rel="attachment wp-att-9131"><img loading="lazy" decoding="async" src="https://iotexpert.com/wp-content/uploads/2020/05/arch-1-1024x569.png" alt="" width="1024" height="569" class="alignnone size-large wp-image-9131" srcset="https://iotexpert.com/wp-content/uploads/2020/05/arch-1-1024x569.png 1024w, https://iotexpert.com/wp-content/uploads/2020/05/arch-1-600x333.png 600w, https://iotexpert.com/wp-content/uploads/2020/05/arch-1-300x167.png 300w, https://iotexpert.com/wp-content/uploads/2020/05/arch-1-768x426.png 768w, https://iotexpert.com/wp-content/uploads/2020/05/arch-1.png 1358w" sizes="auto, (max-width: 1024px) 100vw, 1024px" /></a></p>
<h1>Make the Basic Project</h1>
<p>To build this project start by creating a new project.  The development board that I had plugged into my computer when I began this project is a CY8CPROTO-062-4343W so this is the one I will select.</p>
<p><a href="https://iotexpert.com/2020/05/04/anycloud-wireless-connection-manager-part-1/img_1741/" rel="attachment wp-att-9045"><img loading="lazy" decoding="async" src="https://iotexpert.com/wp-content/uploads/2020/04/IMG_1741-1024x768.jpg" alt="" width="1024" height="768" class="alignnone size-large wp-image-9045" srcset="https://iotexpert.com/wp-content/uploads/2020/04/IMG_1741-1024x768.jpg 1024w, https://iotexpert.com/wp-content/uploads/2020/04/IMG_1741-scaled-600x450.jpg 600w, https://iotexpert.com/wp-content/uploads/2020/04/IMG_1741-300x225.jpg 300w, https://iotexpert.com/wp-content/uploads/2020/04/IMG_1741-768x576.jpg 768w, https://iotexpert.com/wp-content/uploads/2020/04/IMG_1741-1536x1152.jpg 1536w, https://iotexpert.com/wp-content/uploads/2020/04/IMG_1741-2048x1536.jpg 2048w" sizes="auto, (max-width: 1024px) 100vw, 1024px" /></a></p>
<p>In the new project creator pick the &#8220;CY8CPROTO-062-4343W&#8221;</p>
<p><a href="https://iotexpert.com/2020/05/04/anycloud-wireless-connection-manager-part-1/screen-shot-2020-04-27-at-2-52-43-pm/" rel="attachment wp-att-9031"><img loading="lazy" decoding="async" src="https://iotexpert.com/wp-content/uploads/2020/04/Screen-Shot-2020-04-27-at-2.52.43-PM-1024x757.png" alt="" width="1024" height="757" class="alignnone size-large wp-image-9031" srcset="https://iotexpert.com/wp-content/uploads/2020/04/Screen-Shot-2020-04-27-at-2.52.43-PM-1024x757.png 1024w, https://iotexpert.com/wp-content/uploads/2020/04/Screen-Shot-2020-04-27-at-2.52.43-PM-600x443.png 600w, https://iotexpert.com/wp-content/uploads/2020/04/Screen-Shot-2020-04-27-at-2.52.43-PM-300x222.png 300w, https://iotexpert.com/wp-content/uploads/2020/04/Screen-Shot-2020-04-27-at-2.52.43-PM-768x567.png 768w, https://iotexpert.com/wp-content/uploads/2020/04/Screen-Shot-2020-04-27-at-2.52.43-PM-1536x1135.png 1536w, https://iotexpert.com/wp-content/uploads/2020/04/Screen-Shot-2020-04-27-at-2.52.43-PM-2048x1513.png 2048w" sizes="auto, (max-width: 1024px) 100vw, 1024px" /></a></p>
<p>I created a FreeRTOS template project that does all of the right stuff.  I wrote an article about how to use the IoT Expert Manifestt <a href="https://iotexpert.com/2020/03/30/modustoolbox-2-0-libraries-an-example-for-emwin-super-manifests/">here</a>, and until you add the IoT Manifest to your setup you will not get the FreeRTOS Template project.</p>
<p><a href="https://iotexpert.com/2020/05/04/anycloud-wireless-connection-manager-part-1/screen-shot-2020-04-27-at-2-53-09-pm/" rel="attachment wp-att-9032"><img loading="lazy" decoding="async" src="https://iotexpert.com/wp-content/uploads/2020/04/Screen-Shot-2020-04-27-at-2.53.09-PM-1024x756.png" alt="" width="1024" height="756" class="alignnone size-large wp-image-9032" srcset="https://iotexpert.com/wp-content/uploads/2020/04/Screen-Shot-2020-04-27-at-2.53.09-PM-1024x756.png 1024w, https://iotexpert.com/wp-content/uploads/2020/04/Screen-Shot-2020-04-27-at-2.53.09-PM-600x443.png 600w, https://iotexpert.com/wp-content/uploads/2020/04/Screen-Shot-2020-04-27-at-2.53.09-PM-300x222.png 300w, https://iotexpert.com/wp-content/uploads/2020/04/Screen-Shot-2020-04-27-at-2.53.09-PM-768x567.png 768w, https://iotexpert.com/wp-content/uploads/2020/04/Screen-Shot-2020-04-27-at-2.53.09-PM-1536x1134.png 1536w, https://iotexpert.com/wp-content/uploads/2020/04/Screen-Shot-2020-04-27-at-2.53.09-PM-2048x1512.png 2048w" sizes="auto, (max-width: 1024px) 100vw, 1024px" /></a></p>
<p>After the new project work is done you should see</p>
<p><a href="https://iotexpert.com/2020/05/04/anycloud-wireless-connection-manager-part-1/screen-shot-2020-04-27-at-2-53-33-pm/" rel="attachment wp-att-9033"><img loading="lazy" decoding="async" src="https://iotexpert.com/wp-content/uploads/2020/04/Screen-Shot-2020-04-27-at-2.53.33-PM-1024x228.png" alt="" width="1024" height="228" class="alignnone size-large wp-image-9033" srcset="https://iotexpert.com/wp-content/uploads/2020/04/Screen-Shot-2020-04-27-at-2.53.33-PM-1024x228.png 1024w, https://iotexpert.com/wp-content/uploads/2020/04/Screen-Shot-2020-04-27-at-2.53.33-PM-600x134.png 600w, https://iotexpert.com/wp-content/uploads/2020/04/Screen-Shot-2020-04-27-at-2.53.33-PM-300x67.png 300w, https://iotexpert.com/wp-content/uploads/2020/04/Screen-Shot-2020-04-27-at-2.53.33-PM-768x171.png 768w, https://iotexpert.com/wp-content/uploads/2020/04/Screen-Shot-2020-04-27-at-2.53.33-PM-1536x342.png 1536w, https://iotexpert.com/wp-content/uploads/2020/04/Screen-Shot-2020-04-27-at-2.53.33-PM-2048x456.png 2048w" sizes="auto, (max-width: 1024px) 100vw, 1024px" /></a></p>
<p>Add the nt-shell, which comes from my IoT Expert library (read about how to add the IoT Expert library <a href="https://iotexpert.com/2020/03/30/modustoolbox-2-0-libraries-an-example-for-emwin-super-manifests/">here</a>).</p>
<p><a href="https://iotexpert.com/2020/05/04/anycloud-wireless-connection-manager-part-1/screen-shot-2020-04-27-at-2-57-07-pm/" rel="attachment wp-att-9034"><img loading="lazy" decoding="async" src="https://iotexpert.com/wp-content/uploads/2020/04/Screen-Shot-2020-04-27-at-2.57.07-PM-1024x889.png" alt="" width="1024" height="889" class="alignnone size-large wp-image-9034" srcset="https://iotexpert.com/wp-content/uploads/2020/04/Screen-Shot-2020-04-27-at-2.57.07-PM-1024x889.png 1024w, https://iotexpert.com/wp-content/uploads/2020/04/Screen-Shot-2020-04-27-at-2.57.07-PM-600x521.png 600w, https://iotexpert.com/wp-content/uploads/2020/04/Screen-Shot-2020-04-27-at-2.57.07-PM-300x261.png 300w, https://iotexpert.com/wp-content/uploads/2020/04/Screen-Shot-2020-04-27-at-2.57.07-PM-768x667.png 768w, https://iotexpert.com/wp-content/uploads/2020/04/Screen-Shot-2020-04-27-at-2.57.07-PM-1536x1334.png 1536w, https://iotexpert.com/wp-content/uploads/2020/04/Screen-Shot-2020-04-27-at-2.57.07-PM.png 1976w" sizes="auto, (max-width: 1024px) 100vw, 1024px" /></a></p>
<p>I have been on a kick of using Visual Studio code.  So, run &#8220;make vscode&#8221; to setup the project for Visual Studio Code.</p>
<p><a href="https://iotexpert.com/2020/05/04/anycloud-wireless-connection-manager-part-1/screen-shot-2020-04-27-at-2-57-32-pm/" rel="attachment wp-att-9035"><img loading="lazy" decoding="async" src="https://iotexpert.com/wp-content/uploads/2020/04/Screen-Shot-2020-04-27-at-2.57.32-PM-870x1024.png" alt="" width="870" height="1024" class="alignnone size-large wp-image-9035" srcset="https://iotexpert.com/wp-content/uploads/2020/04/Screen-Shot-2020-04-27-at-2.57.32-PM-870x1024.png 870w, https://iotexpert.com/wp-content/uploads/2020/04/Screen-Shot-2020-04-27-at-2.57.32-PM-600x706.png 600w, https://iotexpert.com/wp-content/uploads/2020/04/Screen-Shot-2020-04-27-at-2.57.32-PM-255x300.png 255w, https://iotexpert.com/wp-content/uploads/2020/04/Screen-Shot-2020-04-27-at-2.57.32-PM-768x904.png 768w, https://iotexpert.com/wp-content/uploads/2020/04/Screen-Shot-2020-04-27-at-2.57.32-PM-1305x1536.png 1305w, https://iotexpert.com/wp-content/uploads/2020/04/Screen-Shot-2020-04-27-at-2.57.32-PM.png 1704w" sizes="auto, (max-width: 870px) 100vw, 870px" /></a></p>
<p>In the finder, copy the template files from nt-shell into your project.</p>
<p><a href="https://iotexpert.com/2020/05/04/anycloud-wireless-connection-manager-part-1/screen-shot-2020-04-27-at-2-23-34-pm/" rel="attachment wp-att-9027"><img loading="lazy" decoding="async" src="https://iotexpert.com/wp-content/uploads/2020/04/Screen-Shot-2020-04-27-at-2.23.34-PM.png" alt="" width="1012" height="604" class="alignnone size-full wp-image-9027" srcset="https://iotexpert.com/wp-content/uploads/2020/04/Screen-Shot-2020-04-27-at-2.23.34-PM.png 1012w, https://iotexpert.com/wp-content/uploads/2020/04/Screen-Shot-2020-04-27-at-2.23.34-PM-600x358.png 600w, https://iotexpert.com/wp-content/uploads/2020/04/Screen-Shot-2020-04-27-at-2.23.34-PM-300x179.png 300w, https://iotexpert.com/wp-content/uploads/2020/04/Screen-Shot-2020-04-27-at-2.23.34-PM-768x458.png 768w" sizes="auto, (max-width: 1012px) 100vw, 1012px" /></a></p>
<p>You can also do it with the command line.</p>
<p><a href="https://iotexpert.com/2020/05/04/anycloud-wireless-connection-manager-part-1/screen-shot-2020-04-27-at-2-58-45-pm/" rel="attachment wp-att-9036"><img loading="lazy" decoding="async" src="https://iotexpert.com/wp-content/uploads/2020/04/Screen-Shot-2020-04-27-at-2.58.45-PM-1024x139.png" alt="" width="1024" height="139" class="alignnone size-large wp-image-9036" srcset="https://iotexpert.com/wp-content/uploads/2020/04/Screen-Shot-2020-04-27-at-2.58.45-PM-1024x139.png 1024w, https://iotexpert.com/wp-content/uploads/2020/04/Screen-Shot-2020-04-27-at-2.58.45-PM-600x81.png 600w, https://iotexpert.com/wp-content/uploads/2020/04/Screen-Shot-2020-04-27-at-2.58.45-PM-300x41.png 300w, https://iotexpert.com/wp-content/uploads/2020/04/Screen-Shot-2020-04-27-at-2.58.45-PM-768x104.png 768w, https://iotexpert.com/wp-content/uploads/2020/04/Screen-Shot-2020-04-27-at-2.58.45-PM.png 1168w" sizes="auto, (max-width: 1024px) 100vw, 1024px" /></a></p>
<p>Edit main.c to include the configuration.</p>
<pre class="start-line:9 EnlighterJSRAW" data-enlighter-language="c"">#include "ntshell.h"
#include "psoc6_ntshell_port.h"</pre>
<p>Update the main.c to have the ntShellThread</p>
<pre class="start-line:18 EnlighterJSRAW" data-enlighter-language="c"">// Global variable with a handle to the shell
ntshell_t ntshell;

void ntShellTask()
{

  printf("Started ntshell\n");
  setvbuf(stdin, NULL, _IONBF, 0);
  ntshell_init(
               &amp;ntshell,
               ntshell_read,
               ntshell_write,
               ntshell_callback,
               (void *)&amp;ntshell);
  ntshell_set_prompt(&amp;ntshell, "AnyCloud&gt; ");
  vtsend_erase_display(&amp;ntshell.vtsend);
  ntshell_execute(&amp;ntshell);
}</pre>
<p>And start the ntshell task.</p>
<pre class="start-line:71 EnlighterJSRAW" data-enlighter-language="c"">    xTaskCreate(ntShellTask, "nt shell task", configMINIMAL_STACK_SIZE*2,0 /* args */ ,4 /* priority */, 0);</pre>
<p>When you want to add a command to the shell you need to do three things</p>
<ol>
<li>Add a function prototype for the command</li>
<li>Add the command to the command list</li>
<li>Write the function</li>
</ol>
<pre class="start-line:54 EnlighterJSRAW" data-enlighter-language="c"">static int usrcmd_help(int argc, char **argv);
static int usrcmd_info(int argc, char **argv);
static int usrcmd_clear(int argc, char **argv);
static int usrcmd_printargs(int argc, char **argv);
static const cmd_table_t cmdlist[] = {
    { "help", "This is a description text string for help command.", usrcmd_help },
    { "info", "This is a description text string for info command.", usrcmd_info },
    { "clear", "Clear the screen", usrcmd_clear },
    { "printargs","print the list of arguments", usrcmd_printargs},
};</pre>
<p>Here is an example of of the printargs command.  The shell will call your function with a ARGC=number of arguments and ARGV[] an array of the pointers to the actual arguments.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="c" ">static int usrcmd_printargs(int argc, char **argv)
{
    printf("ARGC = %d\n",argc);

    for(int i =0;i&lt;argc;i++)
    {
        printf("argv[%d] = %s\n",i,argv[i]);
    }
    return 0;

}</pre>
<p>Build and test your program.</p>
<p><a href="https://iotexpert.com/2020/05/04/anycloud-wireless-connection-manager-part-1/screen-shot-2020-04-27-at-2-28-29-pm/" rel="attachment wp-att-9029"><img loading="lazy" decoding="async" src="https://iotexpert.com/wp-content/uploads/2020/04/Screen-Shot-2020-04-27-at-2.28.29-PM-1024x288.png" alt="" width="1024" height="288" class="alignnone size-large wp-image-9029" srcset="https://iotexpert.com/wp-content/uploads/2020/04/Screen-Shot-2020-04-27-at-2.28.29-PM-1024x288.png 1024w, https://iotexpert.com/wp-content/uploads/2020/04/Screen-Shot-2020-04-27-at-2.28.29-PM-600x169.png 600w, https://iotexpert.com/wp-content/uploads/2020/04/Screen-Shot-2020-04-27-at-2.28.29-PM-300x84.png 300w, https://iotexpert.com/wp-content/uploads/2020/04/Screen-Shot-2020-04-27-at-2.28.29-PM-768x216.png 768w, https://iotexpert.com/wp-content/uploads/2020/04/Screen-Shot-2020-04-27-at-2.28.29-PM-1536x431.png 1536w, https://iotexpert.com/wp-content/uploads/2020/04/Screen-Shot-2020-04-27-at-2.28.29-PM.png 1666w" sizes="auto, (max-width: 1024px) 100vw, 1024px" /></a></p>
<h1>Turn on the Connection Manager and Core Middleware Library</h1>
<p>Now, add the wifi-mw-core library &amp; Connection Manager using the library manager.  You can start it with &#8220;make modlibs&#8221;.  These two libraries are in the &#8220;WiFi Middleware&#8221; category.</p>
<p><a href="https://iotexpert.com/2020/05/04/anycloud-wireless-connection-manager-part-1/screen-shot-2020-04-27-at-3-04-40-pm/" rel="attachment wp-att-9037"><img loading="lazy" decoding="async" src="https://iotexpert.com/wp-content/uploads/2020/04/Screen-Shot-2020-04-27-at-3.04.40-PM-1024x787.png" alt="" width="1024" height="787" class="alignnone size-large wp-image-9037" srcset="https://iotexpert.com/wp-content/uploads/2020/04/Screen-Shot-2020-04-27-at-3.04.40-PM-1024x787.png 1024w, https://iotexpert.com/wp-content/uploads/2020/04/Screen-Shot-2020-04-27-at-3.04.40-PM-600x461.png 600w, https://iotexpert.com/wp-content/uploads/2020/04/Screen-Shot-2020-04-27-at-3.04.40-PM-300x231.png 300w, https://iotexpert.com/wp-content/uploads/2020/04/Screen-Shot-2020-04-27-at-3.04.40-PM-768x591.png 768w, https://iotexpert.com/wp-content/uploads/2020/04/Screen-Shot-2020-04-27-at-3.04.40-PM-1536x1181.png 1536w, https://iotexpert.com/wp-content/uploads/2020/04/Screen-Shot-2020-04-27-at-3.04.40-PM-2048x1575.png 2048w" sizes="auto, (max-width: 1024px) 100vw, 1024px" /></a></p>
<p>Copy the FreeRTOSConfig.h from the libs/wifi-mw-core/configs directory into your project (so you can modify it)</p>
<p><a href="https://iotexpert.com/2020/05/04/anycloud-wireless-connection-manager-part-1/screen-shot-2020-04-27-at-2-13-57-pm/" rel="attachment wp-att-9026"><img loading="lazy" decoding="async" src="https://iotexpert.com/wp-content/uploads/2020/04/Screen-Shot-2020-04-27-at-2.13.57-PM-1024x677.png" alt="" width="1024" height="677" class="alignnone size-large wp-image-9026" srcset="https://iotexpert.com/wp-content/uploads/2020/04/Screen-Shot-2020-04-27-at-2.13.57-PM-1024x677.png 1024w, https://iotexpert.com/wp-content/uploads/2020/04/Screen-Shot-2020-04-27-at-2.13.57-PM-600x396.png 600w, https://iotexpert.com/wp-content/uploads/2020/04/Screen-Shot-2020-04-27-at-2.13.57-PM-300x198.png 300w, https://iotexpert.com/wp-content/uploads/2020/04/Screen-Shot-2020-04-27-at-2.13.57-PM-768x507.png 768w, https://iotexpert.com/wp-content/uploads/2020/04/Screen-Shot-2020-04-27-at-2.13.57-PM-1536x1015.png 1536w, https://iotexpert.com/wp-content/uploads/2020/04/Screen-Shot-2020-04-27-at-2.13.57-PM.png 1562w" sizes="auto, (max-width: 1024px) 100vw, 1024px" /></a></p>
<p>Update the Makefile to include the WiFi components (line 71) and the MBED TLS configuration (line 86)</p>
<pre class="start-line:70 EnlighterJSRAW" data-enlighter-language="c"">COMPONENTS=FREERTOS PSOC6HAL LWIP MBEDTLS 4343W
# Like COMPONENTS, but disable optional code that was enabled by default.
DISABLE_COMPONENTS=

# By default the build system automatically looks in the Makefile's directory
# tree for source code and builds it. The SOURCES variable can be used to
# manually add source code to the build process from a location not searched
# by default, or otherwise not found by the build system.
SOURCES=

# Like SOURCES, but for include directories. Value should be paths to
# directories (without a leading -I).
INCLUDES=

# Add additional defines to the build process (without a leading -D).
DEFINES=MBEDTLS_USER_CONFIG_FILE='"configs/mbedtls_user_config.h"' CYBSP_WIFI_CAPABLE</pre>
<h1>Create networkTask.h/.c &amp; Start the Task in main.c</h1>
<p>Now let&#8217;s create the networkTask.  This task will control all of the networking functions in the system.  The first file, networkTask.h, is the public interface.  It declares a Queue where you can push messages (line 5) an enumeration of the messages (lines 7-14), a definition of the message data (lines 17-22) and finally the network task declaration (line 24).</p>
<pre class="EnlighterJSRAW" data-enlighter-language="c" ">#pragma once
#include "FreeRTOS.h"
#include "queue.h"

extern QueueHandle_t networkQueue;

typedef enum {
    net_scan,
    net_connect,
    net_disconnect,
    net_printip,
    net_printmac,

} networkCmd_t;


typedef struct {
    networkCmd_t cmd;
    uint32_t val0;
    uint32_t val1;

} networkQueueMsg_t;

void networkTask(void *arg);</pre>
<p>Ill go ahead and modify main.c to start the yet to be written network task.  You need to include the header file for the task and define a handle for the task.</p>
<pre class="start-line:11 EnlighterJSRAW" data-enlighter-language="c"">#include "networkTask.h"

TaskHandle_t networkTaskHandle;</pre>
<p>Finally in main function, start the task.</p>
<pre class="start-line:60 EnlighterJSRAW" data-enlighter-language="c"">    xTaskCreate(networkTask, "networkTask", configMINIMAL_STACK_SIZE*8,0 /* args */ ,4/* priority */, &amp;networkTaskHandle);</pre>
<p>Create the file networkTask.c.  Make a bunch of includes.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="c">#include &lt;stdio.h&gt;
#include &lt;stdlib.h&gt;
#include "FreeRTOS.h"
#include "task.h"
#include "cy_wcm.h"
#include "cy_wcm_error.h"
#include "whd_types.h"
#include "queue.h"
#include "semphr.h"
#include "networkTask.h"</pre>
<p>Now let&#8217;s define the actual task function.  This function will</p>
<ol>
<li>Call the wcm_init function to make a WiFi Station (lines 201-203)</li>
<li>Tell the task that you would like to be called back when things happen (line 205)</li>
<li>Initialize the Queue to receive command messages from other tasks.</li>
<li>Make an infinite loop to receive the commands and process the messages.  Notice that I dont do anything with the message for now.  Ill add the code later.</li>
</ol>
<pre class="start-line:190 EnlighterJSRAW" data-enlighter-language="c"">// The networkTask will:
// - startup the wireless connection manager
// - sit waiting on the rtos queue... getting messages from other tasks
// - and do ( net_scan, net_connect, net_disconnect, net_printip, net_printmac,)

void networkTask(void *arg)
{
	cy_rslt_t result;
	cy_wcm_config_t config;
	cy_wcm_scan_filter_t scanFilter;

	memset(&amp;config, 0, sizeof(cy_wcm_config_t));
    config.interface = CY_WCM_INTERFACE_TYPE_STA;
	cy_wcm_init	(&amp;config);

	cy_wcm_register_event_callback(	wcmCallback	);

	networkQueue = xQueueCreate( 5, sizeof(networkQueueMsg_t));

	while(1)
	{
		networkQueueMsg_t msg;

		xQueueReceive(networkQueue,(void *)&amp;msg,portMAX_DELAY);  // Wait for commands from other tasks

		switch(msg.cmd)
		{
			case net_scan: // 0=stop scan !0=start scan
			break;

			case net_connect:
			break;

			case net_disconnect:
			break;

			case net_printip:
			break;

			case net_printmac:
			break;
		}
	}

}</pre>
<h1>Create Utilities for Printing out the IP and MAC Address</h1>
<p>It the network task I want to be able to print out IP address (both IPV4 and IPV6).  I also want to be able to print out 6-byte MAC address.  In the Cypress drivers, an IP address is a structure that holds either a IPV4 or and IPV6 address.  It then contains the 4 or 6 bytes of the address.  Here is the type definition.</p>
<pre class="start-line:387 EnlighterJSRAW" data-enlighter-language="c"">/**
 * IP Address Structure
 */
typedef struct
{
    cy_wcm_ip_version_t version;  /**&lt; IP version */
    union
    {
        uint32_t v4;     /**&lt; IPv4 address bytes */
        uint32_t v6[4];  /**&lt; IPv6 address bytes */
    } ip;                /**&lt; IP address bytes */
} cy_wcm_ip_address_t;</pre>
<p>The IP v ersion is just an enumeration.</p>
<pre class="start-line:164 EnlighterJSRAW" data-enlighter-language="c"">/**
 * IP Version
 */
typedef enum
{
    CY_WCM_IP_VER_V4 = 4,      /**&lt; Denotes IPv4 version */
    CY_WCM_IP_VER_V6 = 6       /**&lt; Denotes IPv6 version */
} cy_wcm_ip_version_t;</pre>
<p>To print an address, figure out which version you are working on.  Then dump the raw bytes.  Notice in the IPV4 case it is encoded into a uint32_t as 4 continuous bytes.</p>
<pre class="start-line:18 EnlighterJSRAW" data-enlighter-language="c"">void printIp(cy_wcm_ip_address_t *ipad)
{
	if(ip_addr.version == CY_WCM_IP_VER_V4)
	{
		printf("%d.%d.%d.%d",(int)ipad-&gt;ip.v4&gt;&gt;0&amp;0xFF,(int)ipad-&gt;ip.v4&gt;&gt;8&amp;0xFF,(int)ipad-&gt;ip.v4&gt;&gt;16&amp;0xFF,(int)ipad-&gt;ip.v4&gt;&gt;24&amp;0xFF);
	}
	else if (ip_addr.version == CY_WCM_IP_VER_V6)
	{
		for(int i=0;i&lt;4;i++)
		{
			printf("%0X:",(unsigned int)ip_addr.ip.v6[i]);
		}
	}
	else
	{
		printf("IP ERROR %d",ipad-&gt;version);
	}			
}</pre>
<p>A MAC address is just an array of uint8_t of length CY_WCM_MAC_ADDR_LEN  (which we pound defined to 6)</p>
<pre class="EnlighterJSRAW" data-enlighter-language="c">typedef uint8_t cy_wcm_mac_t[CY_WCM_MAC_ADDR_LEN];                   /**&lt; Unique 6-byte MAC address */</pre>
<p>So, the print is just a loop. (probably should have done something slightly better so I dont end up with the trailing : &#8211; oh well)</p>
<pre class="EnlighterJSRAW" data-enlighter-language="c" ">void printMac(cy_wcm_mac_t mac)
{
	for(int i=0;i&lt;CY_WCM_MAC_ADDR_LEN;i++)
	{
		uint8_t val = mac[i];
		printf("%02X:",val);
	}
}</pre>
<h1>Add the Scan Command</h1>
<p>For the scan I want to print out the:</p>
<ol>
<li>SSID</li>
<li>RSSI (in dBM)</li>
<li>Channel</li>
<li>Band</li>
<li>Speed</li>
<li>Type of Ap</li>
<li>Country Code</li>
<li>MAC address of the Access Point (AKA BSSID)</li>
<li>Type of Security</li>
</ol>
<p><a href="https://iotexpert.com/2020/05/04/anycloud-wireless-connection-manager-part-1/screen-shot-2020-04-27-at-1-04-36-pm/" rel="attachment wp-att-9021"><img loading="lazy" decoding="async" src="https://iotexpert.com/wp-content/uploads/2020/04/Screen-Shot-2020-04-27-at-1.04.36-PM-1024x623.png" alt="" width="1024" height="623" class="alignnone size-large wp-image-9021" srcset="https://iotexpert.com/wp-content/uploads/2020/04/Screen-Shot-2020-04-27-at-1.04.36-PM-1024x623.png 1024w, https://iotexpert.com/wp-content/uploads/2020/04/Screen-Shot-2020-04-27-at-1.04.36-PM-600x365.png 600w, https://iotexpert.com/wp-content/uploads/2020/04/Screen-Shot-2020-04-27-at-1.04.36-PM-300x182.png 300w, https://iotexpert.com/wp-content/uploads/2020/04/Screen-Shot-2020-04-27-at-1.04.36-PM-768x467.png 768w, https://iotexpert.com/wp-content/uploads/2020/04/Screen-Shot-2020-04-27-at-1.04.36-PM-1536x934.png 1536w, https://iotexpert.com/wp-content/uploads/2020/04/Screen-Shot-2020-04-27-at-1.04.36-PM.png 1950w" sizes="auto, (max-width: 1024px) 100vw, 1024px" /></a></p>
<p>In order to have the WCM run a scan you need to call the function cy_wcm_start_scan.  What this will do is tell the 4343W to scan all the channels on the 2.4GHZ band and listen for access point beacons.  This function has three arguments</p>
<ol>
<li>A function pointer to call back when you find an AP</li>
<li>A user settable data pointer</li>
<li>A filter (which can limit to an SSID, BSSID or RSSI)</li>
</ol>
<pre class="EnlighterJSRAW" data-enlighter-language="c">cy_rslt_t cy_wcm_start_scan(cy_wcm_scan_result_callback_t callback, void *user_data, cy_wcm_scan_filter_t *scan_filter)</pre>
<p>Here is my version of the scanCallback which I put in the networkTask.c file.</p>
<pre class="start-line:60 EnlighterJSRAW" data-enlighter-language="c"">// This function is called back when the user asks for an overall scan.
// It just prints out the information about the networks that it hears about
void scanCallback( cy_wcm_scan_result_t *result_ptr, void *user_data, cy_wcm_scan_status_t status )</pre>
<p>The result_ptr is a pointer to a structure that contains the data for the found access point.</p>
<pre class="start-line:460 EnlighterJSRAW" data-enlighter-language="c" ">/**
 * Structure for storing scan results
 */
typedef struct
{
    cy_wcm_ssid_t                SSID;             /**&lt; Service Set Identification (i.e. Name of Access Point)                    */
    cy_wcm_mac_t                 BSSID;            /**&lt; Basic Service Set Identification (i.e. MAC address of Access Point)       */
    int16_t                      signal_strength;  /**&lt; Receive Signal Strength Indication in dBm. &lt;-90=Very poor, &gt;-30=Excellent */
    uint32_t                     max_data_rate;    /**&lt; Maximum data rate in kilobits/s                                           */
    cy_wcm_bss_type_t            bss_type;         /**&lt; Network type                                                              */
    cy_wcm_security_t            security;         /**&lt; Security type                                                             */
    uint8_t                      channel;          /**&lt; Radio channel that the AP beacon was received on                          */
    cy_wcm_wifi_band_t           band;             /**&lt; Radio band                                                                */
    uint8_t                      ccode[2];         /**&lt; Two letter ISO country code from AP                                       */
    uint8_t                      flags;            /**&lt; flags                                                                     */
    uint8_t                      *ie_ptr;          /**&lt; Pointer to received Beacon/Probe Response IE(Information Element)         */
    uint32_t                     ie_len;           /**&lt; Length of IE(Information Element)                                         */
} cy_wcm_scan_result_t;
</pre>
<p>The other parameter to the callback is the status.  The status will either be CY_WCM_SCAN_COMPLETE or CY_WCM_SCAN_INCOMPLETE.  The first thing that to do is see if this callback is the one that tells me that the scan is complete, if so I just return (and don&#8217;t print anything)</p>
<pre class="start-line:67 EnlighterJSRAW" data-enlighter-language="c"">	if(status == CY_WCM_SCAN_COMPLETE)
		return;</pre>
<p>Then I print out the raw SSID, Signal Strength and Channel.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="c" ">	printf("%32s\t%d\t%d\t",result_ptr-&gt;SSID,result_ptr-&gt;signal_strength,result_ptr-&gt;channel);</pre>
<p>Next I figure out what channel we are talking about.  The 4343W is single band 2.4GHZ, however, other Cypress chips have dual band.</p>
<pre class="start-line:68 EnlighterJSRAW" data-enlighter-language="c"">	switch(result_ptr-&gt;band)
	{
		case CY_WCM_WIFI_BAND_ANY:
			printf("ANY");
		break;
		case CY_WCM_WIFI_BAND_5GHZ:
			printf("5.0 GHZ");
		break;
		case CY_WCM_WIFI_BAND_2_4GHZ:
			printf("2.4 GHZ");
		break;
	}</pre>
<p>Then I printout the maximum data rate, which is 0 for all of my test cases.  I have no idea why.</p>
<pre class="start-line:82 EnlighterJSRAW" data-enlighter-language="c"">	printf("%d",(int)result_ptr-&gt;max_data_rate);</pre>
<p>Then I printout what type of AP we are talking about.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="c">	switch(result_ptr-&gt;bss_type)
	{
		case CY_WCM_BSS_TYPE_INFRASTRUCTURE:
			printf("INFR");
		break; 	
		case CY_WCM_BSS_TYPE_ADHOC: 
			printf("ADHOC");
		break;	
		case CY_WCM__BSS_TYPE_ANY: 	
			printf("ANY");
		break;
		case CY_WCM_BSS_TYPE_MESH:
			printf("MESG");
		break;
		case CY_WCM_BSS_TYPE_UNKNOWN: 
			printf("UNKWN");
		break;
	}</pre>
<p>Then the country code.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="c" ">	printf("%c%c",result_ptr-&gt;ccode[0],result_ptr-&gt;ccode[1]);
</pre>
<p>Then the Basic Service Set ID of the AP, which is also known as the MAC address of the AP.</p>
<pre class="start-line:105 EnlighterJSRAW" data-enlighter-language="c"">	printMac(result_ptr-&gt;BSSID);</pre>
<p>Then the security type.</p>
<pre class="start-line:108 EnlighterJSRAW" data-enlighter-language="c"">	switch(result_ptr-&gt;security)
	{
		case CY_WCM_SECURITY_OPEN:
			printf("OPEN");
		break;
    	case CY_WCM_SECURITY_WEP_PSK:
			printf("WEP_PSK");
		break;
		case CY_WCM_SECURITY_WEP_SHARED:
			printf("WEP_SHARED");
		break;
    	case CY_WCM_SECURITY_WPA_TKIP_PSK:
			printf("WPA_TKIP_PSK");
		break;
		case CY_WCM_SECURITY_WPA_AES_PSK:
			printf("WPA_AES_PSK");
		break;
		case CY_WCM_SECURITY_WPA_MIXED_PSK:
			printf("WPA_MIXED_PSK");
		break;
		case CY_WCM_SECURITY_WPA2_AES_PSK:
			printf("WPA2_AES_PSK");
		break;
		case CY_WCM_SECURITY_WPA2_TKIP_PSK:
			printf("WPA2_TKIP_PSK");
		break;
		case CY_WCM_SECURITY_WPA2_MIXED_PSK:
			printf("WPA2_MIXED_PSK");
		break;
		case CY_WCM_SECURITY_WPA2_FBT_PSK:
			printf("WPA2_FBT_PSK");
		break;
		case CY_WCM_SECURITY_WPA3_SAE:
			printf("WPA3_SAE");
		break;
		case CY_WCM_SECURITY_WPA3_WPA2_PSK:
			printf("WPA3_WPA2_PSK");
		break;
		case CY_WCM_SECURITY_IBSS_OPEN:
			printf("IBSS_OPEN");
		break;
		case CY_WCM_SECURITY_WPS_SECURE:
			printf("WPS_SECURE");
		break;
		case CY_WCM_SECURITY_UNKNOWN:
			printf("UNKNOWN");
		break;
		case CY_WCM_SECURITY_FORCE_32_BIT:
			printf("FORCE_32_BIT");
		break;
	}</pre>
<p>With a complete scanCallback function I can now update the networkTask to deal with the queued commands of net_scan type.  This simply either stops or starts the scan based on the message parameter.</p>
<pre class="start-line:212 EnlighterJSRAW" data-enlighter-language="c"">			case net_scan: // 0=stop scan !0=start scan
				if(msg.val0 == 0)
					cy_wcm_stop_scan();
				else
				{
					printf("\n");
					result = cy_wcm_start_scan(scanCallback,0,0);
					if(result != CY_RSLT_SUCCESS)
						printf("Scan error\n");
				}
			break;</pre>
<p>The last things to do is to add the scan command to the usrcmd.c</p>
<pre class="start-line:149 EnlighterJSRAW" data-enlighter-language="c"">static int usrcmd_scan(int argc, char **argv)
{

    static int state=0;

    if(argc==1)
    {
        state = (state ==0)?1:0;
    }
    else if(argc == 2)
    {
        if(strcmp(argv[1],"on") == 0)
        {
            state=1;
        } 
        else if(strcmp(argv[1],"off") == 0)
        {
            state = 0;
        }
        else
        {
            printf("usage: scan [on|off]\n");
            return 0;
        }
        
    }
    else
    {
        printf("usage scan: [on|off]\n");
        return 0;
    }
    
    networkQueueMsg_t msg;
    msg.cmd = net_scan;
    msg.val0 = state;
    xQueueSend(networkQueue,(const void *)&amp;msg,portMAX_DELAY);
    return 0;
}</pre>
<p>OK.  Let it rip.  You should be able to run network scans.  In the next Article I will add a connect and disconnect commands.</p>
<p>You can find all of this example code at https://github.com/iotexpert/wcm_example</p>
]]></content:encoded>
					
					<wfw:commentRss>https://iotexpert.com/anycloud-wireless-connection-manager-part-1/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
	</channel>
</rss>
