Play the Control Panel with Arduino (ESP32):A fan counter for Station B

As we all know, the Control Panel is widely used in the Creator Education. It is a learning development board based on ESP32.People use graphical programming methods to program the control panel, such as mPython, Mind+and so on.However, since the dashboard is based on the ESP32 chip, we can also program it with Arduino software.So, if you have time, I'm ready to share a series of tutorials on programming the Control Panel (ESP32) with Arduino code: Playing the Control Panel (ESP32) series with Arduino

This issue brings you: B Fan Counter (B Station Fan Counter)

Preface

If you are playing some self-Media platforms, such as WeChat Public Number, Station B, Knowledgement, Jitter, etc., then I believe you will pay more attention to the related data such as your number of fans, number of reads or playback volume, but it is more troublesome to view them manually each time.

So is there a simpler way?In the eyes of Creator Technology House, everything can be automated!

Take station B as an example today, to teach you how to make a table B fan counter!Why station B?Because B is the easiest way to get up...(crying...)

To see the effect first, I uploaded the program to the control panel (ESP32) and NodeMCU (ESP8266) with Arduino software, and the effect is basically the same.Originally, I wanted to make a shell, but I was isolated from the epidemic at home. There are not many devices, so I can only make a simple version. Let's have a look.

What!There are so few fans!Lose face, don't support me three times yet

What's wrong? No. 1 fraud powder!

Start the formal tutorial below.

Get B-Station API

Start with **Google Browser (Recommended)** to open the personal home page of Station B. As shown in the following image, focus on a few places I circled: Number of concerns, number of fans, number of points of approval, playback scores. These data meanings will be understood at a glance and will not be explained.Also, pay attention to the UID in the lower right corner, which is a series of numbers that are your only ID in Station B. This number is very important and will be used later.
Then press F12 or Ctrl+Shift+I on the keyboard to enter the browser debugging mode, refresh the personal home page of Station B, and you will see a stack of returned data under the Network tab, from which we can see the method of data request (such as GET) and the corresponding Domain (domain name of the web address).Here we're going to focus on a couple of lines of data where Domain is api.bilibili.com, which I've circled in the following image.
We went in one by one and switched to the Response tab, where we saw two familiar data: following (102) and follower (133), which is not exactly how many followers (102) and fans (133) we saw on the personal home page of Station B?
When we switch to the Headers tab, we see that the requested web address (Request URL) is as follows, and the request method is GET.

We'll copy this web address and look at it:

https://api.bilibili.com/x/relation/stat?vmid=224425204&jsonp=jsonp&callback=__jp4

There's a vmid=224425204, isn't that the UID we mentioned earlier?The following jsonp, callback should be some corresponding callback functions, we will delete these, only keep the previous part:

https://api.bilibili.com/x/relation/stat?vmid=224425204

Copy it to the browser address bar to visit, what do you see?Is it just the simplest data we have left that includes the number of people we care about and the number of fans we have?And this is in JSON format for the data.

We'll format the data for us to see.VS Code is used here, or you can use other JSON online formatting tools on the web, which are not expanded here.

In the same way, let's check where we can find the number of playback and the number of favorites.

I'm sure you'll find it soon. Find the data location first, as shown in the following figure:

Check the API web address again:

https://api.bilibili.com/x/space/upstat?mid=224425204&jsonp=jsonp&callback=__jp5


After deleting the end-independent parameter:

https://api.bilibili.com/x/space/upstat?mid=224425204

Then open the website in your browser and we'll see familiar playback counts (view:9047) and favorites (likes:57).

Format the data in VS Code for easy viewing.

Coding

Networking Settings

To get data from Station B, of course, you have to connect to the Internet.At the beginning of the program, we introduce a bunch of header files related to networking.A special feature here is that we have introduced the header files corresponding to ESP32 and ESP8266 at the same time, so when compiling the program, the corresponding parts will be compiled automatically according to the selected development board, without error, so that a set of programs can be compatible with both development boards (ESP32 and ESP8266).

#if defined(ESP32)
    #include <WiFi.h>
    #include <HTTPClient.h>
#elif defined(ESP8266)
    #include <ESP8266WiFi.h>
    #include <ESP8266HTTPClient.h>
#else
    #error "Please check your mode setting,it must be esp8266 or esp32."
#endif

#include <Wire.h>

// Wi-Fi
const char *ssid = "wifi_name";
const char *password = "wifi_password";

void setup()
{
    Serial.begin(115200);
    WiFi.begin(ssid, password);
    while (WiFi.status() != WL_CONNECTED)
    {
        delay(500);
        Serial.print(".");
    }
    Serial.println("");
    Serial.println("WiFi connected");
}

void loop()
{
}

Since you want to connect to the Internet, you need to define your network name and password, so you can modify it accordingly:

const char *ssid = "wifi_name";
const char *password = "wifi_password";

The above program which connects to Wi-Fi will not be expanded. It is basically standard writing. In this library of WiFi, just find a routine and copy it.

Get Number of Fans

After connecting to the network, you can get the number of fans, in addition to the header file HTTPClient that has been introduced above, this library file can be used to get data on the website.We also need ArduinoJson, a JSON parsing library that can be used to parse the JSON data returned by the website and initialize a JSON parsing object, jsonBuffer.

ArduinoJson is currently more popular with two versions: V5 and V6, V5 is more classic and stable, and V6 is newer.The two versions are slightly different. The blogger uses V5 here.

#include <ArduinoJson.h>

DynamicJsonBuffer jsonBuffer(256); // ArduinoJson V5

In addition, we also need to define the API's web address and initialize the number of fans, which can be easily modified by each individual.Note that our web address is accessed here at http, not https, because the code is more complex with https.

// bilibili api: follower, view, likes
String UID = "224425204";
String followerUrl = "http://api.bilibili.com/x/relation/stat?vmid=" + UID;   // Number of fans

long follower = 0;   // Number of fans

Then write a function getFollower(String url) to get the number of fans. Once you pass in the corresponding API web address, you can use the GET method in the HTTPClient to get the corresponding data and parse it with the ArduinoJson library.

void getFollower(String url)
{
    HTTPClient http;
    http.begin(url);

    int httpCode = http.GET();
    Serial.printf("[HTTP] GET... code: %d\n", httpCode);

    if (httpCode == 200)
    {
        Serial.println("Get OK");
        String resBuff = http.getString();

        // ---------- ArduinoJson V5 ----------
        JsonObject &root = jsonBuffer.parseObject(resBuff);
        if (!root.success())
        {
          Serial.println("parseObject() failed");
          return;
        }

        follower = root["data"]["follower"];
        Serial.print("Fans: ");
        Serial.println(follower);
    }
    else
    {
        Serial.printf("[HTTP] GET... failed, error: %d\n", httpCode);
    }

    http.end();
}

Finally, call it again in setup() to see the effect:

void setup()
{
    // other setup codes ...
    getFollower(followerUrl);
}

Open the Arduino serial port monitor and return the data to normal, indicating success.

Get playback and favorites

This is the same as getting the number of fans. No more details, just look at the code:

// bilibili api: follower, view, likes
String UID = "224425204";
String followerUrl = "http://api.bilibili.com/x/relation/stat?vmid=" + UID;   // Number of fans
String viewAndLikesUrl = "http://api.bilibili.com/x/space/upstat?mid=" + UID; // Play Count, Point Count

long follower = 0;   // Number of fans
long view = 0;   // Play Count
long likes = 0;   // Won favor

void setup()
{
    // other setup codes ...
    getFollower(followerUrl);
    getViewAndLikes(viewAndLikesUrl);
}

void getViewAndLikes(String url)
{
    HTTPClient http;
    http.begin(url);

    int httpCode = http.GET();
    Serial.printf("[HTTP] GET... code: %d\n", httpCode);

    if (httpCode == 200)
    {
        Serial.println("Get OK");
        String resBuff = http.getString();

        // ---------- ArduinoJson V5 ----------
        JsonObject &root = jsonBuffer.parseObject(resBuff);
        if (!root.success())
        {
          Serial.println("parseObject() failed");
          return;
        }

        likes = root["data"]["likes"];
        view = root["data"]["archive"]["view"];
        Serial.print("Likes: ");
        Serial.println(likes);
        Serial.print("View: ");
        Serial.println(view);
    }
    else
    {
        Serial.printf("[HTTP] GET... failed, error: %d\n", httpCode);
    }

    http.end();
}

Open the Arduino serial port monitor and return the data to normal, indicating success.

OLED screen: data display

After we get the data, we can't always view it in the serial monitor, so we use an OLED 12864 screen to display the data on the screen.The code is as follows:

#include <U8g2lib.h>

// 1.3' OLED12864
U8G2_SH1106_128X64_NONAME_F_HW_I2C u8g2(U8G2_R0, U8X8_PIN_NONE);
// 0.96' OLED12864
//U8G2_SSD1306_128X64_NONAME_F_HW_I2C u8g2(U8G2_R0, U8X8_PIN_NONE);

void setup()
{
    // other setup codes ...
    u8g2.begin();
    u8g2.enableUTF8Print();
    u8g2.setFont(u8g2_font_wqy12_t_gb2312b);
    u8g2.setFontPosTop();
    u8g2.clearDisplay();
}

void loop()
{
    u8g2.firstPage();
    do
    {
        display(follower, likes, view);
    } while (u8g2.nextPage());
}

void display(long follower, long likes, long view)
{
    u8g2.clearDisplay();
    u8g2.setCursor(5, 2);
    u8g2.print("B Station Fan Counter");
    u8g2.setCursor(5, 20);
    u8g2.print("Number of fans:" + String(follower));
    u8g2.setCursor(5, 36);
    u8g2.print("Accepted:" + String(likes));
    u8g2.setCursor(5, 52);
    u8g2.print("Number of Plays:" + String(view));
}

Here we use the u8g2 library, which is designed to control various displays.setup() sets the corresponding display parameters and defines a display function (long follower, long likes, long view), which can simultaneously pass in the corresponding data and display it.Then call it in loop() to see how it looks.

Timer: Get data on time

With the previous steps, we can already get the data and display it properly, but you might ask: Why put the function to get the data in setup() when debugging earlier?Not in loop()?Isn't it too troublesome to read a program only once each time it starts?Can't I keep reading and updating a loop()?

No, if we put it in loop() and keep reading it without any other intervention, it will trigger the protection mechanism of station B because of the high access frequency.If you don't believe it, try refreshing one of the API addresses on Station B. I'm sure you'll see the following pages "This page is not accessible".

So, we need a timer to get data every once in a while, and we're not big V, and the data doesn't change very fast, so every 10 minutes is more than enough.Look directly at the code:

#include <Ticker.h>

Ticker timer;
int count = 0;
boolean flag = true;

void setup()
{
    // other setup codes ...
    timer.attach(600, timerCallback); // Every 10 minutes
}

void loop()
{
    while (flag)
    {
        if (count == 0)
        {
            // display data
            Serial.println("count = 0, display data");
            u8g2.firstPage();
            do
            {
            display(follower, likes, view);
            } while (u8g2.nextPage());
            flag = false;
        }
        else if (count == 1)
        {
            // get follower
            Serial.println("count = 1, get follower");
            getFollower(followerUrl);
            flag = false;
        }
        else if (count == 2)
        {
            // get view and likes
            Serial.println("count = 2, get view and likes");
            getViewAndLikes(viewAndLikesUrl);
            flag = false;
        }
    }
}

void timerCallback()
{
    count++;
    if (count == 3)
    {
        count = 0;
    }
    flag = true;
}

We used the timer library Ticker that comes with ESP32 and ESP8266.Set a count variable to do the wrong thing according to count = 0, 1, 2: refresh the data on the display, read the number of fans, read the number of playback, and get approval.flag variables are used to mark whether the appropriate function is performed.These two parameters are changed every 10 minutes in the timer callback function timerCallback(), and the corresponding function is triggered in the loop().

So far, the fans counter in station B has been made, and the final result can be seen at the beginning of the article.

Appendix: Control Panel mPython graphical program

The same function is programmed graphically with the following code:

10 original articles published, 4 praised, 4544 visited
Private letter follow

Tags: JSON network Programming shell

Posted on Thu, 13 Feb 2020 21:21:51 -0500 by Voodoo Jai