Arduino-esp32 course – Espressif is on the www WebServer vs HttpClient – Chapter 4

As a preamble I wanted to make clear that is not my intention to teach C or C++ here, since they are very good online resources for that, and more to make my point in some easy ways to get the most of espressif/arduino-esp32 Framework.

In chapter 2 it was explained how to connect the ESP32 to WiFi so I thought it would be great to make an additional chapter that makes use of the connection in both directions:

  1. WebServer class – the ESP32 will listen on a port and reply or react to your query
    Additionally, we will use the ESPmDNS class to enable multicast DNS
  2. HttpClient class – it will send a GET or POST request to an endpoint

For the HttpClient I will make a special endpoint that it will be available in a subdomain of fasani.de and it will just answer with the time (HH:MM). Please note that after chapter 3 I will only focus on ESP32 since it was already explained how you can write code that works in both Espressif chips ESP8266 or ESP32 using Platformio environments and #ifdef conditionals.

1. WebServer example: ESP32 listens on port 80

The first example will be very simple and to the point. We will just take as a base what we wrote in chapter 2 to connect to WiFi and we will extend it using WebServer class. Once the ESP32 is online and we got the IP Address in the Serial output we will hit the route: http://ESP_IP_ADDRESS/switch

And in this route, using WebServer event handlers, we are going to toggle a GPIO high and low. Pretty simple, but powerful since if instead of a LED, we could use a relay that turns a 220v light or any other device On/Off via WiFi, so you can control it from any other terminal connected to the same WiFi Network. Using your imagination, you may build multiple endpoints that perform different things using predefined routes and modifying this example.

#include "Arduino.h"
#include <WiFi.h>
#include <ESPmDNS.h>  // multicast DNS
#include <WebServer.h>
#define LED_GPIO 25   // Update to a internal LED or just connect one with a resistance in that GPIO
int lostConnectionCount = 0;
char apName[] = "fasani";
bool switchState = false;
WebServer server(80); // port where we start the server

// Callback see defineServerRouting
void onServerSwitch(){
   switchState = !switchState;
   digitalWrite(LED_GPIO, switchState);
   String switchStatus = "OFF";
   if (switchState) {
     switchStatus = "ON";
   }
   server.send(200, "text/html", switchStatus);
}

void onServerNotFound(){
  Serial.println("404");
  server.send(200, "text/html", "404 this route is not defined on "We could not read the time.\nPlease check in the browser that the given url: %d is correct anddefineServerRouting()");
}

// ROUTING Definitions. Add your server routes here
void defineServerRouting() {
  server.on("/switch", HTTP_GET, onServerSwitch);
  server.onNotFound(onServerNotFound);
}

/** Callback for receiving IP address from AP */
void gotIP(system_event_id_t event) {
  Serial.println("Online. Local IP address:");
  Serial.println(WiFi.localIP().toString());

  MDNS.begin(apName);
  MDNS.addService("http", "tcp", 80);
  Serial.println(String(apName)+".local mDns started");
  defineServerRouting();
  server.begin();

  Serial.println("Server started");
}

/** Callback for connection loss */
void lostCon(system_event_id_t event) {
  ++lostConnectionCount;
  Serial.printf("WiFi lost connection try %d to connect again\n", lostConnectionCount);
  WiFi.begin(WIFI_SSID, WIFI_PASS);
  if (lostConnectionCount==4) {
    Serial.println("Cannot connect to the internet. Check your WiFI credentials");
  }
}

void setup() {
  Serial.begin(115200);
  Serial.println("setup() started let's connect to WiFI");
  pinMode(LED_GPIO,OUTPUT);
  Serial.printf("WiFi name: %s\nWiFi pass: %s\n", WIFI_SSID, WIFI_PASS);
// Start our connection attempt
  WiFi.begin(WIFI_SSID, WIFI_PASS);
// Event driven WiFi callbacks
// Setup callback function for successful connection
  WiFi.onEvent(gotIP, SYSTEM_EVENT_STA_GOT_IP);

// Setup callback function for lost connection
  WiFi.onEvent(lostCon, SYSTEM_EVENT_STA_DISCONNECTED);
}

void loop() {
  // Run our server engine
  server.handleClient();
}

Note: Only Linux and Mac support mDNS out of the box. If you use windows you will need to install additional software for that. Now since we use a multicast DNS server if we are using a client that supports it once we upload that code to an ESP32 we could access it from this 2 URLs:

  1. http://ESP_IP_ADDRESS/switch
  2. http://fasani.local/switch

Please note that even that WordPress makes the links above are not clickable and I also used fasani as ApName as shameless self-promotion. Please feel free to change it to your own updating the apName char variable.

This little program will just connect to WiFi, start a mDNS server and a WebServer in port 80, define the route /switch and simply turn a GPIO High and give 3.3v (ON) or Low 0v (OFF) to a GPIO. I just added a function where the routes are defined, since I’m a web developer, and I would like to emulate how other Web frameworks do to keep the routing in a single place. It’s useful, both for the program and for the documentation, to have a single function to place all the actions that your Firmware will support. This example is very simple but it has potential since you can expand it with as many actions you want, and not only turn High or Low a Gpio but also change variables using your server routes, or any other thing you desire.

2. HttpClient: The ESP32 will make a GET request

For this I prepared a very simple endpoint:

http://fs.fasani.de/time.php -> Will return the time in Europe/Berlin as default
http://fs.fasani.de/time.php?tz=America/Los_Angeles will return the time of that timezone

Of course you can use any timezone you want. The source of time.php is just 4 lines and you can put it in any server that supports PHP no matter what version:

<?php
$tz = isset($_GET['tz'])?$_GET['tz']:'Europe/Berlin';
date_default_timezone_set($tz);
echo date("H:i");

So this example will be even easier than number 1. It will simply connect to WiFi and query this URL to print in the Serial output the current time. The applications can be endless, for example, you can return only the hour as an integer, and your program can decide to turn on something depending on the hour.

#include "Arduino.h"
#include <WiFi.h>
#include <HTTPClient.h>
int lostConnectionCount = 0;
HTTPClient http;
String url = "http://fs.fasani.de/time.php?tz=Europe/Berlin";

void gotIP(system_event_id_t event) {
  Serial.println("Online. Local IP address:");
  Serial.println(WiFi.localIP().toString());
  http.begin(url);
  int httpCode = http.GET();  //Make the request
  Serial.printf("http status:%d\n", httpCode);

  if (httpCode == 200) { 
     String response = http.getString();
     Serial.printf("The time now is: %s\n", response);
  } else {
    Serial.printf("We could not read the time.\nPlease check in the browser that the given url: %s is correct and replies with an HTTP 200 OK status", url);
  }
}

void lostCon(system_event_id_t event) {
  ++lostConnectionCount;
  Serial.printf("WiFi lost connection try %d to connect again\n", lostConnectionCount);
  WiFi.begin(WIFI_SSID, WIFI_PASS);
  if (lostConnectionCount==4) {
    Serial.println("Cannot connect to the internet. Check your WiFI credentials");
  }
}

void setup() {
  Serial.begin(115200);
  Serial.println("setup() started let's connect to WiFI");
  WiFi.begin(WIFI_SSID, WIFI_PASS);
  WiFi.onEvent(gotIP, SYSTEM_EVENT_STA_GOT_IP);
  WiFi.onEvent(lostCon, SYSTEM_EVENT_STA_DISCONNECTED);
}

void loop() {
}

I hope this two easy examples will serve you to build more powerful things on top. I will be monitoring the commentaries if you want to achieve things that are not explained here.
In the next chapters we will explore more possibilities, based on my last 2 years journey, but also on your feedback.

Tippgeschwindigkeit Composer (Making it faster)

Nach letzes composer update, ich kriege immer diese Meldung nach update /install : “You are running composer with xdebug enabled. This has a major impact on performance and will break your balls”
So ich habe die richtige Lösung gefunden und wurde mit euch teilen:
$ php -i | xdebug

Guck mal welche config ist schuldig, in meine Ubuntu ist:
/etc/php5/cli/conf-d/20-xdebug.ini

Und einfach comment:
;zend_extension=xdebug.so

Voila! Deine composer is viel schneller ab jetzt. Für mich ist ungefähr 3x schneller.

01 NOV 2015 TechnoSphärenKlänge – Loop

Mit Lorenzo Senni, Holly Herndon und Tim Hecker

Ghostly Tim Hecker, Music Gallery June 14th
https://soundcloud.com/majical-cloudz/savage-tim-hecker-version

Eine Zusammenarbeit mit dem Berliner CTM Festival. Das Konzert am 1. 11. 2015 findet im Rahmen der Musikkonferenz Loop der Musiksoftwareschmiede Ableton statt.
Lorenzo Senni wird unterstützt von SHAPE platform, gefördert vom Programm Kreatives Europa der EU

Sieht schon gut aus, Tim Hecker gefällt mir sehr!  Mehr info dazu

 

Neues Projekt: Codeigniter wegen Symfony 2

Ich habe noch 1 Woche Zeit. Die Aufgabe ist, diese kleine MVC Projekt:

https://github.com/martinberlin/onstage

In Codeigniter MVC, nach Symfony 2 MVC framework Weiterentwicklung

Dann Ich freue ich mich sowohl in Bezug auf die Frameworks vergleichen in Hinsicht auf:

  • Geschwindigkeit
  • Struktur und Data Models
  • und wie schwer ist es, eine Admin-Panel zu Entwickeln
    (and how hard is to code an admin panel, in case my german is not so clear)

 

Chemiewerk Coswig und Movision team

Wochen habe ich in Chemiewerk Rüdersdorf war und ich trafen uns ein paar coole Jungs, die machen ein Video.

“Don’t get set into one form, adapt it and build your own, let it grow, be like water.” – Bruce Lee

Im Ortsteil Tasdorf, unweit des Kalksteintagebaus und des großen Zementwerks, steht eine gewaltige Industrieruine. Die beiden riesigen Schornsteine sind sogar von den Trümmerbergen Berlins aus sichtbar und riefen so mein Interesse hervor. In einer Fahrradtour ging es dann von Berlin-Marzahn aus nach Rüdersdorf, immer auf die beiden Schlote zu. (source: furry.de)

Deutsch Klasse #2

Ebay classes

If you want to learn some useful business words in Deutsch I highly recommend to start using ebay.de

“Wir drücken Ihnen die Daumen!”

We cross the fingers for you ebay says when you place a bid.

Another interesting phrase I learn for conversation this days it’s:
Es hängt davon ab”  – It depends

Looking for work

“Sehr gute Deutschkenntnisse”  – Means that you have a good knowledge of the language.
Usually at the middle of a work interview your Arbeitgeber will ask “Shall we switch to Deutsch” And at that precise moment if you say “Nein!” you will loose like 4 points.

If you speak english you will tend to speak shitty Deutsch or “retarded Deustch” mixing both languages.

For example you will say:

Ich habe ins Rathaus anmelded

Nein! Take that chewingum out of your mouth and write down in richtig Deutsch:

Ich habe mich ins Rathaus angemelded

Hangover related

“Ich habe einen Kater”  – I have a hangover.
Never say this at work, if you’ve been brave enough to get out into that “cool” bar in Neuköln with your spanisch friends, then you stand like a man until the end of work and you hold the tears tight.

“Ich gehe 4 stunde ins fitnesscenter. Ich habe einen Muskelkater” – I’ve been 4 hours in the gym. I have a muscle ache (Or muscle hangover)

Deutsch Phrases. Klasse #1

Dear Deutsch students level A zwei. Please sit down, take the chewing gums out of your mouths, and join the class.

Phrases / Keywords I find funny

Durchfall  – diarrhea
It has a sound like falls like a shower…and yeah! Probably ;)

Eichhörnchen – squirrel
I bet a beer that even after spending years in Deutschland you won’t be able to say Eichhörnchen properly. Now, repeat with me “aich heuernchen”. You can pay my beer at the end of this class.

In a mobile conversation

Hörst du mich? 
Do you hear me ?

Erzähl mir keine Märchen…
Don’t tell me stories

Dieses Märchen kannst du deiner Großmutter erzählen!
Tell this bullshit stories to your grandmother!

Appendix die Klasse

„Das Publikum klatschte, als das Theaterstück zu Ende war.“

Bis die nächste Klasse. Schöne abend.