CodeLabs
  • Introduction
  • Cities
    • Cover
    • Summary
    • Introduction
      • Getting Started
      • Resources
      • Naming Convention
    • Caracol
      • Architecture
        • Intel
        • Operating Systems
        • Hardware Platform
        • Field Requirements
        • Software Development
        • Video Conference Station
          • Applications
          • Entertainment System
            • Services
              • Graphics
              • Video
              • Camera
              • Text To Speech
              • Speech To Text
              • Photography
              • Gaming
                • Super Nintendo Emulators
                • Super Nintendo ROMs
              • Twitter
              • Keyboard
              • Google Drive
              • WiFi
            • Modules
            • Tbd
        • Functionality
        • Bill Of Materials
        • Open Questions
        • Future
    • Chacmultun
      • JHD1313M1
        • Background
          • Inter-Integrated Circuit
          • Linux I2C Subsystem
        • Device Drivers
          • User Space Library UPM
          • User Space Library MRAA
          • User Space I2C Library
          • Kernel Space I2C Driver
    • Chicanna
      • OpenCV
        • Face Recognition
        • Web Streaming
    • Chichen Itza
      • Audio
        • Advanced Linux Sound Architecture
        • PortAudio
        • PyAudio
          • Record
          • Play
      • Text To Speech
        • eSpeak
          • pyttsx
        • VoiceRss
          • VoiceRss Text To Speech Python SDK
      • Speech To Text
        • CMU Sphinx
          • Sphinx Knowledge Base Tool
          • PocketSphinx
          • PyAudio
        • SpeechRecognition
    • Coba
      • Linux Kernel Source Code
        • Git Source Code Management
      • Linux Kernel Development Process
        • A Guide To The Linux Kernel Development Process
        • Challenge
      • Linux Kernel Compilation
      • Linux Kernel Modules
      • Linux Kernel Build System
        • Compilation Kernel Object
        • Compilation Built-In
      • Linux Kernel Patch
        • Patchset
      • Linux Kernel Developer
      • Learn More
    • Dos Pilas
    • Dzibilchaltun
    • Edzna
      • MQ Telemetry Transport
        • MQTT Broker
      • Home Assistant
        • Setup
        • Default Configuration
        • Hello
      • Home Automation
        • Device
          • Light ESP8266
          • Intel Edison
        • Server
          • MQTT
            • Light
            • Sensor
            • Binary Sensor
            • Alarm
          • Dweet
          • Weather
          • Binary Sensor
          • Telegram
          • Camera
          • Automation
      • Shack Automation
        • Configuration Yaml
    • Ek Balam
      • Google Cloud Platform
        • Google API Keys
        • Google Application Default Credentials
      • Google Cloud Translation API
      • Google Cloud Vision API
      • Google Cloud Speech
    • Hochob
      • Introduction
      • Accounts
      • Areas
        • Naming Conventions
      • Digital Media Players
        • Chromecast
      • Keypads
      • Mobile Device
      • Amikoo
        • Architecture
          • Hardware Components
            • Intel® Edison Breakout Board
        • Amikoo
          • Setup
          • Git Repositories
          • Audio
          • Main Intel Edison
          • Main x86
        • Sandbox
          • Tbd
      • Server
        • Setup
          • Root
          • PulseAudio
        • Architecture
        • Media
        • Services
          • Automation
            • Home Assistant
              • Setup
          • Calendar
          • Camera
          • Communications
          • Games
            • Loteria Mexicana
            • Caras Y Gestos
            • Sopa De Letras
          • Image
          • Institution
          • Keypad
          • Messaging
          • Motion
          • Robot
          • Sound
            • Play
            • Speech Synthetizer
          • Stream
          • Usb
          • Survey
        • Applications
          • Captain Maya Lands
          • Southern Maya Highlands
          • Amikoo Maya Lands
          • Central Maya Lowlands
          • Northern Maya Lowlands
          • Console Maya Lands
          • Media Maya Lands
          • Calendar Maya Lands
          • Tradition Maya Lands
          • Techie Maya Lands
          • NohochTata Maya Lands
      • Stations
      • Architecture
      • Release Notes
        • v0.1
        • v0.2
    • Hormiguero
    • Kaminaljuyu
      • WRI Workshop
        • Environmental Protection Agency
      • Arquitecture
        • Bill Of Materials
      • Intel
    • Kanki
      • Device
      • Gateway
    • Kinich KaK Moo
    • Kohunlich
    • La Ruta Puuc
    • Mayapan
    • Mixco Viejo
    • Muyil
    • Palenque
    • Qumarkaj
      • Amazon
      • Amazon Echo
        • Lifx
        • IFTTT
      • Amazon Alexa
        • Alexa Skills Kit
          • Training: Developing Alexa Skills - Hello, Alexa!
          • Training: Alexa - A Free Introduction
          • Projects
            • Intel GDC Visitor Center
              • Cloudy
              • Geek
              • Trivia
              • Kit
            • Voice Control Intel Edison
        • Alexa Voice Service
          • Intel Edison
    • Seibal
    • Tabasqueno
    • Tikal
      • Mexican Red Cross
      • Emergency Medical Services
        • Prehospital Care Strategies
      • Intel
      • Bitalino
      • My Signals
      • Architecture
        • Objectives
    • Tulum
      • Introduction
      • Device
        • Development Board
        • Telegram Bot
        • Bootup
        • Text Editors
        • Setup
        • Main
        • IoT101 Inc
        • Mqtt Clients
        • Sensors
      • Server
        • Setup
        • Dashboard
        • Mqtt Broker
      • Challenge
    • Uxmal
    • Xcambo
    • Xpuhil
    • Xunantunich
    • Sandbox
      • Text To Speech
      • Face Recognition Web Streaming
      • Web Server Flask
      • Speech To Text
      • Image Webpage Flask
      • Audio Capture Playback
      • Image Capture OpenCV
    • Tbd
      • Tbd
      • Linux Kernel Architecture
      • Linux Kernel Device Drivers
      • Tbd
  • Gods
    • Acat
      • Node-RED
        • Installation
          • General
          • Base
          • Npm Packages
          • Node-RED Packages
        • Autostart
      • Projects
        • GPIO
        • MQTT
        • Intel GDC Visitor Center
      • Sandbox
    • Ah Puch
      • Recon Instruments
        • ReconJet
          • Get Started
        • ReconEngage
        • Uplink
        • Intel Developer Zone
          • Recon Dev Kit for Jetâ„¢
      • Bicycles
    • Akna
      • Hardware
        • Intel Edison
        • Sphero
        • Bluetooth Dongle
      • Software
        • Javascript
        • Cylon.js
          • Cylon.js Intel Edison
          • Cylon.js Intel Edison Sphero
            • Examples
        • Sphero Linux API
    • Alom
    • Bacab
      • Getting Started
        • Inventory
        • Accounts
        • Software
      • Proof Of Concepts
        • Doorbell
    • Bitol
      • Drone Software Development Environment
        • PX4
        • JMAVSim
        • Ardupilot
        • SITL Simulator
        • DroneKit
        • QGroundControl
        • MAVLink
        • OpenCV
        • Git Source Code Management
      • Drone Solution Architect
        • Companies
      • Dronecode Project
      • Base Drone Solution
        • Flight Controller Hardware
          • PixHawk
          • Intel® Aero Ready to Fly Drone
          • Emlid
          • Erle Brain
        • Flight Controller Operating System
        • Autopilot
          • Px4
            • Architecture
              • NuttX
              • DriverFramework
            • Shell
          • Ardupilot
          • Software In The Loop
            • jMAVSim
            • DroneKit SITL
        • Communications
          • Mavlink
            • PyMAVLink
        • Ground Control Station
          • QGroundControl
        • Developer APIs
      • Hybrid Drone Solution
      • Autonomous Drone Solution
      • Drone Solutions
        • Erle Robotics
        • Emlid
      • Training
        • Drone Solution Architect
          • Demos
            • Ka’an
            • Múuyal
            • lik’
            • Chak iik’
    • Chaac
    • Bolon Ts'akab
    • Buluc Chabtan
      • Challenge
    • Chaac Uayab Xoc
    • Cacoch
      • Background
        • Open Source
        • Do It Yourself Communities
      • The Project
        • History
        • Career Profile
        • Education Strategy
        • Courses
        • Infrastructure
Powered by GitBook
On this page
  1. Cities
  2. Edzna
  3. Home Automation
  4. Device

Light ESP8266

/*
   MQTT Light for Home-Assistant - NodeMCU (ESP8266)
   https://home-assistant.io/components/light.mqtt/

   Libraries :
    - ESP8266 core for Arduino : https://github.com/esp8266/Arduino
    - PubSubClient : https://github.com/knolleary/pubsubclient

   Sources :
    - File > Examples > ES8266WiFi > WiFiClient
    - File > Examples > PubSubClient > mqtt_auth
    - File > Examples > PubSubClient > mqtt_esp8266

   Schematic :
    - https://github.com/mertenats/open-home-automation/blob/master/ha_mqtt_light/Schematic.png
    - GND - LED - Resistor 220 Ohms - D1/GPIO5

   Configuration (HA) : 
    light:
      platform: mqtt
      name: Office light'
      state_topic: 'office/light1/status'
      command_topic: 'office/light1/switch'
      optimistic: false

   Samuel M. - v1.1 - 08.2016
   If you like this example, please add a star! Thank you!
   https://github.com/mertenats/open-home-automation
*/

#include <ESP8266WiFi.h>
#include <PubSubClient.h>

#define MQTT_VERSION MQTT_VERSION_3_1_1

const char* WIFI_SSID = "INFINITUM";
const char* WIFI_PASSWORD = "xxxxxxxxxx";

const PROGMEM char* MQTT_CLIENT_ID = "edznalight";
const PROGMEM char* MQTT_SERVER_IP = "test.mosquitto.org";
const PROGMEM uint16_t MQTT_SERVER_PORT = 1883;
const PROGMEM char* MQTT_USER = "";
const PROGMEM char* MQTT_PASSWORD = "";

const char* MQTT_LIGHT_STATE_TOPIC = "edzna/principal/light/status";
const char* MQTT_LIGHT_COMMAND_TOPIC = "edzna/principal/light/switch";

const char* LIGHT_ON = "ON";
const char* LIGHT_OFF = "OFF";

const PROGMEM uint8_t LED_PIN = LED_BUILTIN;
boolean m_light_state = false; // light is turned off by default

WiFiClient wifiClient;
PubSubClient client(wifiClient);

void publishLightState() {
  if (m_light_state) {
    client.publish(MQTT_LIGHT_STATE_TOPIC, LIGHT_ON, true);
  } else {
    client.publish(MQTT_LIGHT_STATE_TOPIC, LIGHT_OFF, true);
  }
}

void setLightState() {
  if (m_light_state) {
    digitalWrite(LED_PIN, LOW);
    Serial.println("INFO: Turn light on...");
  } else {
    digitalWrite(LED_PIN, HIGH);
    Serial.println("INFO: Turn light off...");
  }
}

void callback(char* p_topic, byte* p_payload, unsigned int p_length) {
  String payload;
  for (uint8_t i = 0; i < p_length; i++) {
    payload.concat((char)p_payload[i]);
  }

  if (String(MQTT_LIGHT_COMMAND_TOPIC).equals(p_topic)) {
    if (payload.equals(String(LIGHT_ON))) {
      if (m_light_state != true) {
        m_light_state = true;
        setLightState();
        publishLightState();
      }
    } else if (payload.equals(String(LIGHT_OFF))) {
      if (m_light_state != false) {
        m_light_state = false;
        setLightState();
        publishLightState();
      }
    }
  }
}

void reconnect() {
  while (!client.connected()) {
    Serial.print("INFO: Attempting MQTT connection...");
    if (client.connect(MQTT_CLIENT_ID)) {
      Serial.println("INFO: connected");
      publishLightState();
      client.subscribe(MQTT_LIGHT_COMMAND_TOPIC);
    } else {
      Serial.print("ERROR: failed, rc=");
      Serial.print(client.state());
      Serial.println("DEBUG: try again in 5 seconds");
      delay(5000);
    }
  }
}

void setup() {
  Serial.begin(115200);

  pinMode(LED_PIN, OUTPUT);
  setLightState();

  Serial.println();
  Serial.println();
  Serial.print("INFO: Connecting to ");
  Serial.println(WIFI_SSID);
  WiFi.begin(WIFI_SSID, WIFI_PASSWORD);

  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }

  Serial.println("");
  Serial.println("INFO: WiFi connected");
  Serial.print("INFO: IP address: ");
  Serial.println(WiFi.localIP());

  client.setServer(MQTT_SERVER_IP, MQTT_SERVER_PORT);
  client.setCallback(callback);
}

void loop() {
  if (!client.connected()) {
    reconnect();
  }
  client.loop();
}
PreviousDeviceNextIntel Edison

Last updated 7 years ago