Thursday, October 9, 2025

How To Connect ESP8266 To Firebase

There are so many tutorials that discuss how to connect the ESP8266, particularly using a secret key. However, it actually makes the read process between the ESP8266 and Firebase very slow (it takes more than one second to retrieve the data).

This tutorial will provide valuable information on how to establish the fastest connection between the ESP8266 and Firebase using the Web API key.


Install the Firebase client in the Arduino Library manager. This library allows programmers to use the command : #include <Firebase_ESP_Client.h>



The Web API key will not appear by default because it is not yet activated.


To activate the connection between the ESP8266 and Firebase using the Web API key, you need to configure the Firebase project as follows :


Click Authentication Menu - Sign-In method - Add new provider - Email/Password
Access menu Authentication - Users - Add user - then insert the email and password





Web API Key will appear then copy it


Now this is the source cade that can be usesd for read and update the firebase data :

#include <Arduino.h>
#include <ESP8266WiFi.h>
// Make sure you include the main library header
#include <Firebase_ESP_Client.h>

// Provide the token generation process info.
#include "addons/TokenHelper.h"
// Provide the RTDB payload printing info.
#include "addons/RTDBHelper.h"

// Define WiFi credentials
#define WIFI_SSID "Infinix"
#define WIFI_PASSWORD "alpha3"

// Define Firebase project credentials
#define WEB_API_KEY "AIzaSyCb1YXRbtjFFE5OP-1YdgDCo1zRKkxE"
#define DATABASE_URL "https://monitor-41aaf-rtdb.asia-southeast1.firebasedatabase.app/"

// Define Firebase user credentials
#define USER_EMAIL "labinside01@gmail.com"
#define USER_PASS "Roo57325yyffyyyyy29*"

// Declare the object that holds Firebase data for requests and responses
FirebaseData fbdo;

// Declare the authentication and configuration objects
FirebaseAuth auth;
FirebaseConfig config;

// Variable to store the authentication status
bool isAuthenticated = false;

// Example function to handle async data (if you use streams)
void streamCallback(FirebaseStream data)
{
  Serial.printf("stream path, %s\nevent path, %s\ndata type, %s\nevent type, %s\n\n",
                data.streamPath().c_str(),
                data.dataPath().c_str(),
                data.dataType().c_str(),
                data.eventType().c_str());
  printResult(data); //See addons/RTDBHelper.h
  Serial.println();
}


void setup()
{
  pinMode(BUILTIN_LED, OUTPUT);
  digitalWrite(BUILTIN_LED, HIGH);
  Serial.begin(115200);
  WiFi.begin(WIFI_SSID, WIFI_PASSWORD);
  Serial.print("Connecting to Wi-Fi");
  while (WiFi.status() != WL_CONNECTED)
  {
    Serial.print(".");
    delay(300);
  }
  Serial.println();
  Serial.print("Connected with IP: ");
  Serial.println(WiFi.localIP());
  Serial.println();

  /* Assign the project credentials */
  config.api_key = WEB_API_KEY;
  config.database_url = DATABASE_URL;

  /* Assign the user sign in credentials */
  auth.user.email = USER_EMAIL;
  auth.user.password = USER_PASS;

  /* Assign the callback function for the long running token generation task */
  config.token_status_callback = tokenStatusCallback; //see addons/TokenHelper.h

  // Initialize the Firebase library
  Firebase.begin(&config, &auth);
  Firebase.reconnectWiFi(true);
  digitalWrite(BUILTIN_LED, LOW);
}

void loop()
{
  if (Firebase.ready()) {
      if (!isAuthenticated) {
          Serial.println("Firebase is authenticated and ready!");
          isAuthenticated = true;
      }
      
      if (Firebase.RTDB.getInt(&fbdo, "/vehicle_1/alarm")) {
        if (fbdo.dataType() == "int") {
          int alarmStatus = fbdo.intData();
          Serial.print("Alarm status is: ");
          Serial.println(alarmStatus);

          Firebase.RTDB.setInt(&fbdo, "/vehicle_1/alarm", 1);
          
        }
      } else {
        Serial.println("Failed to get integer. Reason: " + fbdo.errorReason());
      }

  } else {
      isAuthenticated = false;
      Serial.println("Waiting for Firebase authentication...");
  }

  delay(1); // Wait 5 seconds before the next read
}







 



Monday, October 6, 2025

Connect The ESP8266 to Wi-Fi

Connecting one peripheral to anything is the cornerstone of the IOT's functionality. The ESP 8266 is one of several microcontroller modules developed for the purpose of receiving commands and sharing valuable data through wireless media. In this section, the author will explain how to connect the ESP8266 to a Wi-Fi hotspot. Make sure you have the SSID and password for legal communication.

The source code is visible in the captured Arduino program below:

if the internal LED on the ESP8266 turns on, it indicates that the ESP8266 has successfully connected to Wi-Fi.









Saturday, October 4, 2025

Stream Video Web Camera to Twitch Using Python for Free

 

Figure 1. Stream camera framework.

Twitch is a live-streaming platform similar to YouTube and other entertainment services. It allows developers to express their creativity by creating programs for streaming data such as video, audio, and chat.

Twitch is a free solution for regular users who don’t have or don’t want to rent a VPS to develop RTMP services for video streaming. Twitch can be connected to an IP camera or other software tools loke OBS for video streaming.

In this study, the author proposes a framework for streaming video from a parking lot camera to Twitch. Figure 1 shows a brief visualization of the proposed framework. The objective of this proposed framework is to provide an inexpensive solution for online video streaming using components that can easily be gathered from the market.

The components are consist of :

  • 1.      The rear park assist dash camera has a 170-degree wide-angle view.
  • 2.      Easy CAP
  • 3.      Python source code that streams incoming video data from Easy CAP to Twitch.
  • 4.      Twitch the live streaming titan of the internet

The rear park assists dash camera’s output is in an analog signal form, which is the RCA standard for video data. The video analog output is captured and converted into digital data that can be recognized by any programming language with Easy CAP device.

Easy CAP is a generic name for an inexpensive, widely available USB video capture adapter. These small devices, which resemble dongles, are designed to capture analog audio and video signals from sources such as VHS players, camcorders, DVD players, and older video game consoles. This device can convert analog signals into a digital format on a computer. The digital video data is then managed and transmitted using a Python source code, enabling it to live on Twitch.

This is the source code that was used to stream video data to Twitch (https://www.twitch.tv/).

The source code uses the Python programming language.

This code requires a combination of ingest endpoints to speed up streaming video, which can be accessed at https://help.twitch.tv/s/twitch-ingest-recommendation?language=en_US as well as a stream key, which can be accessed at https://dashboard.twitch.tv/. The ingest endpoints and stream key are then located in the RTMP_URL variable.

import cv2

import subprocess

 

# --- Configuration ---

# Webcam capture settings

WEBCAM_INDEX = 1  # Default webcam

FRAME_WIDTH = 640

FRAME_HEIGHT = 480

FPS = 30

 

# RTMP server URL

RTMP_URL = 'rtmp://jkt02.contribute.live-video.net/app/live_1329481927_EzJgamxsFHyjz8GT5YN14FsI86blUT'

 

# --- FFmpeg Command ---

# This command is configured to receive raw video data from the script,

# encode it to H.264, and stream it to the RTMP server.

ffmpeg_cmd = [

    'ffmpeg',

    '-y',  # Overwrite output file if it exists

    '-f', 'rawvideo',

    '-vcodec', 'rawvideo',

    '-pix_fmt', 'bgr24',  # OpenCV provides frames in BGR format

    '-s', f'{FRAME_WIDTH}x{FRAME_HEIGHT}',

    '-r', str(FPS),

    '-i', '-',  # Input from stdin

    '-c:v', 'libx264',

    '-pix_fmt', 'yuv420p',

    '-preset', 'ultrafast',

    '-f', 'flv',

    RTMP_URL

]

 

# --- Main Streaming Logic ---

def stream_webcam():

    """

    Captures the webcam feed and streams it to the RTMP server.

    """

    # Start the FFmpeg subprocess

    process = subprocess.Popen(ffmpeg_cmd, stdin=subprocess.PIPE)

 

    # Open the webcam

    cap = cv2.VideoCapture(WEBCAM_INDEX)

    cap.set(cv2.CAP_PROP_FRAME_WIDTH, FRAME_WIDTH)

    cap.set(cv2.CAP_PROP_FRAME_HEIGHT, FRAME_HEIGHT)

    cap.set(cv2.CAP_PROP_FPS, FPS)

 

    if not cap.isOpened():

        print("Error: Could not open webcam.")

        return

 

    print("Streaming to RTMP server. Press 'q' to quit.")

 

    while True:

        ret, frame = cap.read()

        if not ret:

            print("Error: Could not read frame.")

            break

 

        # Write the frame to the stdin of the FFmpeg subprocess

        try:

            process.stdin.write(frame.tobytes())

        except (BrokenPipeError, IOError):

            # FFmpeg process has closed

            print("FFmpeg process closed. Exiting.")

            break

 

        # Display the frame (optional)

        cv2.imshow('Webcam Feed', frame)

        if cv2.waitKey(1) & 0xFF == ord('q'):

            break

 

    # --- Cleanup ---

    print("Stopping stream.")

    cap.release()

    process.stdin.close()

    process.wait()

    cv2.destroyAllWindows()

 

if __name__ == '__main__':

    stream_webcam()

 

 

REFERENCES :

How to connected the IP cam to Twitch : https://www.cctvcameraworld.com/live-streaming-cameras/how-to-stream-ip-camera-to-twitch.html?fbclid=IwY2xjawLXKZ5leHRuA2FlbQIxMABicmlkETFrcXRPM3g0eVlKNGp2WlRjAR79S9xdMXnpa5YbtfIFT7so7KEd8HpBiSiz-MN8NMTAXI_IxXTNXf5O-lrEnw_aem_J-oOgSQ9RdJr49DS8zUcSw