Thursday, February 23, 2017

Scanning for WiFi Networks

The next few blog posts will be based on some of the code samples included with the Arduino IDE for ESP8266. The specific examples are chosen for their particular relevance to IoT applications. The examples will NOT be exactly like the examples included in the Arduino IDE, but will be extended to demonstrate additional features, to illustrate coding techniques, etc.

The ESP8266's wifi can be in one of four modes:

# Name Description
0 WIFI_OFF The wifi is... off!
1 WIFI_STA Station mode - the ESP is working as a wifi client
2 WIFI_AP Access point mode - other wifi clients will be able to connect to the ESP
3 WIFI_AP_STA  AP + Station mode - The ESP8266 is acting both as a station and as an access point

The WiFi class is fundamental to most of these examples, so here is a quick overview of some of its properties and methods, as well as associated constants. Since this example is only about scanning wifi networks, and not connecting to them, the methods for actually connecting to an access point will be covered in a later tutorial.

WiFi.mode(modeName) - set the ESP8266's wifi mode to be one of the four values listed above

WiFi.disconnect() - disconnect from a station

WiFi.scanNetworks() - returns the number of available networks as well as some information about each

  • SSID - Service set identifier, essentially the network name
  • BSSID - MAC address of the network access point
  • RSSI - Received Signal Strength Indicator; access points with RSSIs closer to zero have stronger signals
  • isHidden
  • channel
  • encryptionType - see below code for the encryption types recognized by the ESP8266

For the wifi scanner, we will be using station mode, but again we will not be connecting to any of the access points we find. The code will list each access point, it's name, encryption type, etc., in the Serial Monitor window.

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
/*
 * WiFiScanDetails
 * 
 * By: Mike Klepper
 * Date: 22 Feb 2017
 * 
 * This program checks for available networks and displays details about each in the Serial Monitor. 
 * It is based upon the WiFiScan example in the Arduino IDE for the ESP8266
 * 
 */
 
#include "ESP8266WiFi.h"

void setup() 
{
  Serial.begin(115200);
  
  WiFi.mode(WIFI_STA);
  WiFi.disconnect();
  
  delay(100);

  Serial.println("Setup done");
}

void loop() 
{
  Serial.println("Scan start");

  int numNetworks = WiFi.scanNetworks();
  Serial.println("Scan done");
  
  if(numNetworks == 0)
  {
    Serial.println("No networks found");
  }
  else
  {
    Serial.print(numNetworks);
    Serial.println(" networks found");
    
    for(int i = 0; i < numNetworks; i++)
    {
      Serial.print(i + 1);
      Serial.print(": ");
      Serial.println(WiFi.SSID(i));

      Serial.print("     BSSID = ");
      Serial.println(WiFi.BSSIDstr(i));

      Serial.print("     RSSI = ");
      Serial.println(WiFi.RSSI(i));

      Serial.print("     isHidden = ");
      Serial.println(WiFi.isHidden(i));

      Serial.print("     channel = ");
      Serial.println(WiFi.channel(i));

      Serial.print("     encryptionType = ");
      Serial.print(readableEncryptionType(WiFi.encryptionType(i)));
      Serial.print(" (");
      Serial.print(WiFi.encryptionType(i));
      Serial.println(")");
      
      delay(10);
      yield();
    }
  }
  
  Serial.println("");

  delay(5000);
  yield();
}

String readableEncryptionType(uint8_t encType)
{
  String encTypeAsString;
  
  switch(encType)
  {
    case ENC_TYPE_TKIP:
    {
      encTypeAsString = "WPA";
      break;
    }
    case ENC_TYPE_WEP:
    {
      encTypeAsString = "WEP";
      break;
    }
    case ENC_TYPE_CCMP:
    {
      encTypeAsString = "WPA2";
      break;
    }
    case ENC_TYPE_NONE:
    {
      encTypeAsString = "None";
      break;
    }
    case ENC_TYPE_AUTO:
    {
      encTypeAsString = "Auto";
      break;
    }
    default:
    {
      encTypeAsString = "Other";
      break;
    }
  }

  return encTypeAsString;
}

Lines Explanation
1-10 This is a multi-line comment. Arduino sketches support C/C++/Java/JavaScript's style of single-line and multi-line comments
12 This makes the WiFi class available for use in the code!
14 The setup() function is ran exactly once when the ESP8266 is powered-on or reset
16 Enables serial communication over the USB port between the board and the computer to which it is attached. The baud rate is set to 115200 here
18 Set the ESP8266 into station mode
19 Disconnect from any previous network connection
26 The loop() function is ran after the setup() function completes
30 This line accomplishes two things: it returns the number of available wifi networks, and it allows us to get properties of those networks, as we'll see below
33-37 If the number of networks found is zero, say so, otherwise...
42 ... loop over the available wifi networks
46 Print the current network's SSID
49 Print the current network's BSSID as a string
52 Print the current network's RSSI
55 Print whether the current network is hidden
58 Print the current network's channel
61 Print the current network's encryption type in a human-readable manner (see line 81 for the readableEncryptionType function)
63 Print the current network's encryption type as an integer
73-74 Wait for five seconds, yield so that background processes can be handled, then do it again!
77 This function converts the encryption type into a human-readable string
81 We do a switch-case statement to choose the right descriptive string for the corresponding encryption type
115 Return the descriptive string to whatever called this function

After flashing this code, open the Serial Monitor to see the output.

Monday, February 20, 2017

Getting Started with the NodeMCU ESP8266 Board

In this tutorial we will use the Arduino IDE to compile and flash our code to the NodeMCU ESP8266. When we "flash" code to an embedded device, it will be written so that the device will retain that code and run it on reset or next power-up.

These instructions have been tested on Mac OS X 10.11.6.


Part 1: Connect Board and Install Drivers

By default, Mac OS X will not recognize the NodeMCU ESP8266 when it is plugged in! So we will install a driver so that ESP8266, when connected, appears as a serial port.

  1. Connect the ESP8266 dev board to your computer using a USB cable. Note: not all USB cables will work for this! In particular, cables designed for portable phone rechargers will usually not work. USB cables that are used for synching Android phones should be OK.
  2. On Mac, open a terminal window and type:
    ls /dev/cu.*
    You will find Bluetooth ports, but nothing we really want!
  3. Download and install the Silicon Labs VCP Driver. The URL is: https://www.silabs.com/products/development-tools/software/usb-to-uart-bridge-vcp-drivers
  4. Now we need to determine the serial port the ESP8266 is using, as the Arduino IDE may or may not detect it automatically. So, open a terminal window and type:
    ls -l /dev/cu.*
    The desired port should be something like /dev/cu.SLAB_USBtoUART
  5. If that port does not show, try using a different USB cable. Also, you may need to restart your computer at this point.

NOTE: In Windows, use the Device Manager to determine the NodeMCU's USB port.


Part 2: Setup Arduino IDE for ESP8266 Development

  1. Download IDE from Arduino.cc - current version is 1.8.1. URL is: https://www.arduino.cc/en/Main/Software
  2. On Mac, this will download arduino-1.8.1-macosx.zip to the Downloads folder. Double-click to install.
  3. Start the Arduino IDE
  4. Open Preferences window by choosing Arduino | Preferences… menu
  5. Add the following URL to the “Additional Boards Manager URLs” field: http://arduino.esp8266.com/stable/package_esp8266com_index.json
  6. While we’re here, click the “Display line numbers” checkbox
  7. Press “OK” button to save these changes
  8. Open the Boards Manager by using “Tools | Board | Boards Manager…” menu
  9. In search box at top right of that window, enter “esp8266”
  10. Click on the “esp8266 by ESP8266 Community” item, and an “Install” button appears. Click it, and this will start the installation process.
  11. Once installation is complete, click the close button.
As a result of doing this:
  1. You can now target your code for the ESP8266
  2. A number of example programs have been installed, available from “File | Examples” menu

Part 3: Connect Board and Configure the IDE

  1. Connect the ESP8266 dev board to your computer using a USB cable.
  2. Start Arduino IDE if it isn't already running.
  3. Under “Tools | Board” menu, choose NodeMCU 1.0 (ESP-12E Module)
  4. In Arduino IDE, choose “Tools | Port | /dev/cu.SLAB_USBtoUART”
  5. If all goes well, the board type and port will be shown at bottom of Arduino IDE window.

Part 4: First Program

The default program in the IDE window is as follows:

1
2
3
4
5
6
7
8
9
void setup() {
  // put your setup code here, to run once:

}

void loop() {
  // put your main code here, to run repeatedly:

}

For our first program, we will make the NodeMCU's onboard LED blink. Modify the code to read as follows:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
/*
 * BlinkLED
 * 
 * By: Mike Klepper
 * Date: 19 Feb 2017
 * 
 * This program blinks the LED on the NodeMCU board
 * 
 * LED_BUILTIN is used to find the pin for the onboard LED; 
 * the delay constants at the top are in milliseconds
 */

const int LED_ON_DELAY = 500;
const int LED_OFF_DELAY = 2000;

void setup() 
{
  pinMode(LED_BUILTIN, OUTPUT); 
  Serial.begin(115200);
}

void loop() 
{
  Serial.print("LED pin is: ");
  Serial.println(LED_BUILTIN);
  
  digitalWrite(LED_BUILTIN, LOW);
  Serial.println("LED is on");
  delay(LED_ON_DELAY); 
  
  digitalWrite(LED_BUILTIN, HIGH);
  Serial.println("LED is off");
  delay(LED_OFF_DELAY); 
  
  yield();
  Serial.println("");
}

Lines Explanation
1-11 This is a multi-line comment. Arduino sketches support C/C++/Java/JavaScript's style of single-line and multi-line comments
13-14 Constants determining the length of time the LED is lit and unlit, measured in milliseconds
16 The setup() function is ran exactly once when the ESP8266 is powered-on or reset
18 LED_BUILTIN determines the pin number for controlling the user-controllable LED. This line sets that pin for output
19 Enables serial communication over the USB port between the board and the computer to which it is attached. The baud rate is set to 115200 here
16 The loop() function is ran after the setup() function completes
24-25 Write values to the serial port
27 Set the voltage sent to the pin to be LOW (on)
29 Causes control to wait for the specified number of milliseconds
31 Set the voltage sent to the pin to be HIGH (off)
35 Allows the ESP8266 to handle background processes, like WiFi connections

We now compile and flash this program:

  1. Click the arrow button at the top-left of the IDE window. The program will be compiled and then will be flashed to the ESP8266 board. When flashing, a blue LED on the NodeMCU board will flicker. Once the program starts, the red LED will turn-on for 0.5 seconds, and then turn-off for 2 seconds.
  2. The ArduinoIDE has a built-in serial monitor. To open it, click the magnifier glass icon at top right corner of the IDE.
  3. Set the speed to be 115200 baud to match the rate that the above program is transmitting. The serial monitor will display the results of the Serial.println() and Serial.print() statements. As you can see, LED_BUILTIN resolves to pin 16.

If you've completed this tutorial, then you now know how to use the Arduino IDE to write code for the ESP8266! Ooh RAH!

Two More Minutes of Hate

Reposting this from my other blog, "The Other Side of History". It is Comcast's reaction to the previous post, "Two Minutes of Hate".


The shortest distance between two points is a straight line. This maxim holds not only in geometry, but in business as well. In that situation, the two points are the producer of goods or services, and the customer. The transactions between the two, for it to be "businesslike", must not involve any interference by any agency, government "service", third party, or side issues. No diversions must come on the shortest path between producer and customer.

This singlemindedness is the hallmark of a good businessman, and a similar thing holds for any person with any talent: no irrelevancies allowed.

Unfortunately, American businesses have forgotten that: they allow distractions to enter. Like politics, for example.

We've seen National Football League player Colin Kaepernick kneel at the playing of the national anthem. He's protesting "a country that oppresses black people and people of color". In 2016, he had a base salary of $11,900,000, a roster bonus of $2,000,000 and a workout bonus of $400,000, according to SpoTrac. Poor Colin. Poor, poor Colin.

We've read Starbucks promise to hire 10,000 refugees over the next five years in the 75 countries in which they conduct business. Will these include the Starbucks that anti-Trump protesters destroyed during the inauguration? How about the Starbucks destroyed by the rioters at UC Berkeley?

These issues are nothing but distractions from the respective purposes of the NFL and Starbucks, yet they are allowed to happen.

On Thursday, February 2nd, Comcast held protests over Trump's executive order limiting immigrants from seven countries known to breed terrorists. Those protests took place at several Comcast offices, including the Philadelphia one.

The organization of these protests started in the Comcast Silicon Valley (CSV) office located in Sunnyvale, CA. The organizers created a Slack "channel" (a chatroom) that soon included over a thousand members. As plans were evolving, a VP from that office sent the following email to a list of current and former CSV workers:

Hi folks,

As many of you know, a group of Comcasters in Philly and CSV are organizing a walkout for tomorrow (Thursday) at 11 Pacific to protest the Trump administration’s immigration policies. The organizers were inspired by the walkouts at Google campuses around the world on Monday.

If you want to participate or learn more about this, join the #walkout Slack channel.

I’m personally extremely supportive of this action. As a grandchild of immigrants, I understand the contribution immigrants from all over the world have made, and continue to make to this country. And I deeply appreciate that our country, at its best, has extended the opportunity for life, liberty and the pursuit of happiness to people in need.

I want to emphasize that this action is being taken by a group of individuals, motivated by their own social and political views. This isn’t a company-sponsored event, and the participants aren’t making any demands of the company. If your views are different, or if you don’t agree with the action for whatever reason, you shouldn’t feel any pressure. We’re supposed to be “the land of the free” so let’s all respect each other’s rights to speak our minds, or stay silent if that’s what feels right.

-A-

I learned of this chatroom from that email. There were various informal and heated discussions of this protest by my coworkers, and there seemed to be a concerted effort to exclude me from such discussions. Which is fine by me.

Organizers of the protest had consulted with management and Comcast legal services. They determined that protesters were not allowed to use the Comcast logo or name on any of their signs.

The protest was not mandatory. It was not an official Comcast event, though employees were allowed to take one hour of paid time off to participate.

I decided to counter-protest.

The night before the protest, I finished the essay called "Two Minutes of Hate" in response to the protests at various airports (and soon, Comcast) over Trump's order. About a half-hour before the protest was to start, I posted it to this blog, as well as to that chatroom. I also sent it in response to that email from the CSV VP.

Almost immediately, people began talking to me about the protests, and the consequences of either boycotting or counter protesting. Typically, my response to them was that they should be resolute, and to remember that they are correct on this issue. Here's an atypical response...

Fellow employee who was afraid to counter-protest: "You think the police will protect you?"
Me: "You think the police can protect them from me?"

The protesters gathered at the plaza in front of the Comcast Center building, as shown in this photo:

The man on the right with the megaphone used to be my manager. His parents were Vietnamese Boat People. They started a highly-respected restaurant, and are living the American dream. Their son didn't learn.

I stood with a sign that read "#RememberTheVictims" and also held a photo of a man with whom I used to do business, and who was killed in the Orlando night club shootings. I stood in a place where people could see those signs as the left the plaza and headed to City Hall.

I followed them to City Hall, listened to them chat, then again stood in a place where the protesters could see the signs as they returned to Comcast. It was a short protest, management gave them only one hour of PTO.

Of course, my manager, most of my teammates, as well as everyone with whom I sit were against Trump’s executive order, so they were protesting, and they saw me with my signs.

The next day, I was fired. My contracting company said they wanted to continue to work with me, and that Comcast was willing to rehire me for another team.

The reasons for my termination are becoming muddied, and I've already received two different excuses for my termination: one was that I was "unhappy" at my current position, the other that my team wanted an operations person instead of a software developer.

I've been a contractor at Comcast Philadelphia for approximately two years. Near the end of my first year there, they tried to hire me full time, but we were unable to agree on the salary. Before my contract ended, my old manager worked to move me to another team. That new team was dissolved a few months later, and that manager found me a spot with what used to be my current team.

Comcast was happy with me and I was happy with them. Until the counter-protest, that is.

I'm uncertain about working with Comcast in the future. Like all corporations, the chicken choking left hand does not know whom the right hand is wanking. For that reason, I hold no ill will towards the company as a whole.

But I am certain that I can no longer trust them. This is the first consequence for employers who become political, when they stray from the shortest path: doubt is introduced into the employee's mind about any action that management takes. Management undermines themselves, thus revealing their own incompetence.

Thursday, February 2, 2017

Two Minutes of Hate

Reposting this from my other blog, "The Other Side of History". Comcast, the company for which I contract, held paid protests today at their offices in Philly, DC, NYC, Denver, and Sunnyvale, in response to Trump's immigration-related executive order. I decided to hold a one-man counter-protest. Here's the e-mail I sent to the protesters. I'm sure I'll hear about it tomorrow...


Trump's "Protecting the Nation from Foreign Terrorist Entry into the United States" implemented a temporary ban on immigration from Iraq, Iran, Syria, Yemen, Sudan, Somalia, and Libya. The text of that executive order is available at: https://www.whitehouse.gov/the-press-office/2017/01/27/executive-order-protecting-nation-foreign-terrorist-entry-united-states

Based on the level of vitriol in the reaction to that order, people would rather spend hours protesting something they did not spend 30 minutes reading. After all, why take 30 minutes out of your day to determine what to think when the media will do that for you in two minutes?

What is this executive order about, and what are the protests about?

The executive order is not about immigration
Most everybody is from someplace else, therefore there is nothing special about immigration, regardless of how much immigrants are apotheosized. America is not a country of immigrants, we are a country of pioneers. What is important about immigration is how immigrants arrived and what the individual immigrants do with their lives after arriving. Do they open a restaurant or other business, do they provide for their family, do they integrate into the larger community - in essence, do they become proud Americans? Or do they try their hardest to stay "economic migrants" or "hyphenated-Americans"? Or, at worst, do they attempt to convert America into the countries from which they escaped? Becoming American is commendable, and should be supported, but there are no provisions in that executive order excluding immigrants who merely wish to stand on our soil.

It is the right of every sovereign nation to determine who can and who cannot legally enter within its borders. Of the 196 countries on this planet, only seven were excluded by this executive order. So, the order isn't about immigration. Nor is it an absolute ban on immigration from those seven countries, since there are exceptions made for people from those seven countries "traveling on diplomatic visas, North Atlantic Treaty Organization visas, C-2 visas for travel to the United Nations, and G-1, G-2, G-3, and G-4 visas" as well as explicit provisions for case-by-case review.

Lest we forget, Trump's wife is herself an immigrant.

It is not about Islam
The order not only bans Muslims from the seven countries covered by the order, it bans all people, with the exceptions listed above. In fact, two of the families stranded at Philadelphia International Airport were Christian families fleeing from Syria - and they were not returned to Syria.

None of the five countries with the largest Muslim populations are on the list. The words "Muslim" or "Islam" appear nowhere in the EO. The references to Islam are indirect, like this paragraph from section 1 of the EO:

"In order to protect Americans, the United States must ensure that those admitted to this country do not bear hostile attitudes toward it and its founding principles. The United States cannot, and should not, admit those who do not support the Constitution, or those who would place violent ideologies over American law. In addition, the United States should not admit those who engage in acts of bigotry or hatred (including "honor" killings, other forms of violence against women, or the persecution of those who practice religions different from their own) or those who would oppress Americans of any race, gender, or sexual orientation."

There can be no justification for harboring those who enjoy the benefits of living in our republic while trying destroy it, so why not deny entry to those who harbor ill will to our Constitution and our founding principles? We are not obligated to aid and abet our own destruction.

Further, why shouldn't we keep out anyone who would "oppress Americans of any race, gender, or sexual orientation"? We have fought too long and too hard to win the rights of minorities and women and gays and lesbians in this country, and it makes no sense to reverse those gains.

What else isn't the executive order about?
It isn't about racism, since there is no such thing as the "Islamic race" or the "immigrant race". It isn't about free speech, either. If you think this is a "free speech" issue, look at what happened yesterday at UC Berkeley, home of the Free Speech Movement. So much for Michelle Obama's "when they go low, we go high" policy.

What, then, is the executive order about?
The executive order is an attempt to protect America against foreign terrorism. The seven countries are not even specified in the executive order itself, but were identified in the Terrorist Prevention Act of 2015 and its 2016 extension as being current fomenters of terrorism. The order limits entry to people from only those seven countries, requires that the vetting process be improved, requires the completion of a biometric tracking system, and requires public reporting of immigration statistics.

These are the types of actions that should have been taken following the terrorist attacks on 9-11, or at Boston, Ft. Hood, San Bernardino, Orlando, or Mumbai, or multiple places in Pakistan, or Paris (two times), or Berlin, Cologne, or at a whole host of other attack locations.

Finally, what are the protests about?
When Obama banned Cuban immigrants from arriving here, there were no protests. When the Obama administration chose that list of seven countries in 2015 and 2016, where was the outrage? It is easy to say that the root cause of the protests is the election of Trump, or rather, Hillary Clinton's loss. While this is true in part, it is also about the abrogation of the individual's responsibility to determine beliefs based on his or her own observations, research, and reasoning. The protesters are being told what to think, rather than figuring it out for themselves. And they see no problem with this.

The protests are nothing but "Two Minutes of Hate."