Summeriprojekti: MQTT-viestien lähettäminen napinpainalluksella NodeMCU ESP12-E:ltä Raspberry Pi:lle WiFin yli

MQTT summeriprojekti

Lähetä MQTT-viestejä painamalla NodeMCU ESP-12E:hen liitettyä nappia. Kun Raspberry Pi 3 vastaanottaa viestin, se soittaa summeria ja merkkivalo palaa.

Napin painaminen ESP-12E:llä julkaisee MQTT-viestin, jonka Raspberryllä pyörivä Mosquitto MQTT-broker vastaanottaa. Samalla Raspberryllä on asennettuna myös Paho-MQTT-client, joka on tilannut kyseisen MQTT-viestin aiheen. Jos viestin sisältö vastaa ennalta määriteltyä merkkijonoa, niin summeri soi ja punainen LED syttyy hetkeksi. Lisäksi Raspberry Pi myös lähettää minulle sähköpostiviestin. Siten tiedän, että nappia on painettu, vaikka en oliskaan summerin luona.

Nappien määrä on hyvin skaalautuva, ja vaatii ainoastaan pieniä lisäyksiä koodiin. NodeMCU ESP-12E:n saa alle 5 eurolla, joten nappeja voi halvalla tehdä useammankin. Summereita taas ei useampaa tarvita. Halutessaan eri nappien painamiset voisi erottaa eri värisillä LED-valoilla, mutta en nähnyt tälle tarvetta, sillä näen kuitenkin Pi:n lähettämästä viestistä, miltä napilta hälytys on lähtenyt.

Kytkentäkaavion selitykset:

  • Mustat hyppylangat = digital data
  • Siniset hyppylangat = maadoitus
  • Punaiset hyppylangat = 3.3V VCC

alt text


Osat nappia varten:

KappalemääräOsan nimi
1NodeMCU ESP-12E (esp8266)
1Large button
1Red LED
110K potentiometer
1220 ohm resistor
2Small breadboard
5Hyppylanka

Osat summeria varten:

KappalemääräOsan nimi
1Raspberry Pi 3 Model B
1Passive buzzer
1RED LED
1100 ohm resistor
1220 ohm resistor
1Small breadboard
4Hyppylanka

alt text


Nappia varten käytetyt kirjastot:

  • ESP8266WiFi.h
  • PubSubClient.h

Summeria varten käytetyt kirjastot:

  • time
  • sys
  • paho.mqtt.client
  • RPi.GPIO
  • smtplib

Raspberry Pi 3:n konfigurointi:

MQTT-brokerin ja -clientin asennus

sudo apt-get update
sudo apt-get install mosquitto
sudo apt-get install mosquitto-clients # not required but useful for testing purposes
wget https://files.pythonhosted.org/packages/2a/5f/cf14b8f9f8ed1891cda893a2a7d1d6fa23de2a9fb4832f05cef02b79d01f/paho-mqtt-1.3.1.tar.gz
tar -xzvf paho-mqtt-1.3.1.tar.gz
cd paho-mqtt-1.3.1
sudo python setup.py install

 

Python-koodin asentaminen GitHubista

sudo apt-get install git
git-clone https://github.com/PyhaMarkus/mqtt-buzzer-project.git
cd mqtt-buzzer-project
nano mqtt_buzzer.py # change the MQTT and email information to match yours

 

Python koodin ajaminen

cd mqtt-buzzer-project
python mqtt_buzzer.py

Lähdekoodi projektia varten:

Koodi on ladattavissa GitHub-repositoriostani: https://github.com/PyhaMarkus/mqtt-buzzer-project

Arduino-koodi NodeMCU ESP-12E:lle

// Include libraries:
#include <ESP8266WiFi.h>
#include <PubSubClient.h>

// WLAN information:
const char* ssid = "your_network_ssid";
const char* password = "your_password";

// MQTT-broker information:
const char* mqttServer = "192.168.43.223";
const int mqttPort = 1883; // Change this to whatever port you're using for MQTT. 1883 by default.

// Define GPIO pins
const int buttonPin = 12;
const int ledPin = 4;

int buttonState = 0; // default button status

// Allows establishing a connection to the MQTT-broker
WiFiClient espClient;
PubSubClient client(espClient);

// Setup starts here:
void setup() {
  // Initialize LED pin as output
  pinMode(ledPin, OUTPUT);

  // Initialize button pin as input:
  pinMode(buttonPin, INPUT);

  // Initialize a serial connection for outputs
  Serial.begin(115200);
  
  // Connect to the WiFi network
  WiFi.begin(ssid, password);
  // While WiFi is not connected,
  while (WiFi.status() != WL_CONNECTED) {
 
    delay(1000);
    Serial.println("Connecting to WiFi...");
    
  }

  // When WiFi has connected, output IP-address
  Serial.println(WiFi.localIP());

  // Specify the Ip-address and port of the MQTT-broker
  client.setServer(mqttServer, mqttPort);

}

// Loop function runs over and over again
void loop() {
  // Read the state of the button:
  buttonState = digitalRead(buttonPin);

    // If WiFi has been connected to and the button has been pressed,
    if (WiFi.status() == WL_CONNECTED && buttonState == HIGH) {

      Serial.println("We're connected to WiFi/MQTT-broker and the buttonState is HIGH!");

      // While MQTT-broker has not been connected to,
      while (!client.connected()) {
        Serial.println("Connecting to MQTT-broker...");

        // If connection has been successful,
        if (client.connect("ESP8266Client")) {
 
          Serial.println("Connected to MQTT-broker and the button has been pressed!");  

        // If not,
        } else {
 
            Serial.print("failed with state ");
            Serial.print(client.state());
            delay(2000);
 
          }
      }

      // Publish a message with the topic and contents of:
      client.publish("support/location1", "buttonState is HIGH - Location1");

      // Turn the LED on for 3 seconds.
      digitalWrite(ledPin, HIGH);
      delay(3000);
      digitalWrite(ledPin, LOW);

      // If the WiFi has been connected to but the button has not been pressed,
    } else if (WiFi.status() == WL_CONNECTED && buttonState == LOW) {
     
      Serial.println("We're connected to WiFi and buttonState is LOW!");
      
      // If neither of the above arguments is True, then...
    } else {

      Serial.println("We're NOT connected to WiFi!");
      
      }  
}

Python koodi Raspberry Pi 3:lle

#!/usr/bin/python
#-*- coding: utf-8 -*-

# Import libraries
import time
import sys
import paho.mqtt.client as mqtt
import RPi.GPIO as GPIO
import smtplib

# Define GPIO pins for the LED and the buzzer
ledPin = 23
buzzerPin = 18 #GPIO18 is PWM capable

# Initialize GPIO pins as output
GPIO.setmode(GPIO.BCM)
GPIO.setwarnings(False)
GPIO.setup(ledPin,GPIO.OUT)
GPIO.setup(buzzerPin, GPIO.OUT)

# When a connection to MQTT-broker is successful
def on_connect(client, userdata, flags, rc):
	print("Connected with result code"+str(rc))
	client.subscribe("support/#") # Subscribe to topic

# When a message is received
def on_message(client, userdata, msg):

	#global sender_ID
	if msg.payload == "buttonState is HIGH - Location1":
		sender_ID = "location1"
		print("Location1: The button has been pressed!\nSounding the alarm...") 
		GPIO.output(ledPin,GPIO.HIGH) # Turn on the LED
		buzzer = GPIO.PWM(buzzerPin, 440) # Turn on the buzzer
		buzzer.start(10) # Buzzer volume 10%
		time.sleep(1.0)
		buzzer.stop() # Turn off the buzzer
		time.sleep(4.0)
		GPIO.output(ledPin,GPIO.LOW) # Turn off the LED

	elif msg.payload == "buttonState is HIGH - Location2":
		sender_ID = "location2"
		print("Location2: The button has been pressed!\nSounding the alarm...")
		GPIO.output(ledPin,GPIO.HIGH) # Turn on the LED
		buzzer = GPIO.PWM(buzzerPin, 440) # Turn on the buzzer
		buzzer.start(10) # Buzzer volume 10%
		time.sleep(1.0)
		buzzer.stop() # Turn off the buzzer
		time.sleep(4.0)
		GPIO.output(ledPin,GPIO.LOW) # Turn off the LED

        # GMAIL message contents
        TO = 'example.email@gmail.com'
        SUBJECT = 'Button Alert!'
        TEXT = "The button has been pressed in: %s!" % sender_ID 

        # GMAIL user setup
        gmail_sender = 'sender.email@gmail.com'
        gmail_passwd = 'sender_gmail_password'

        # GMAIL authentication
        server = smtplib.SMTP('smtp.gmail.com', 587)
        server.ehlo()
        server.starttls()
        server.ehlo()
        server.login(gmail_sender, gmail_passwd)

        # GMAIL message structure
        BODY = "\r\n".join([
                "TO: %s" % TO,
                "FROM: %s" % gmail_sender ,
                "Subject: %s" % SUBJECT ,
                "",
                TEXT
                ])

	# Send the mail
	server.sendmail(gmail_sender, [TO], BODY)

# MQTT information
client = mqtt.Client()
client.connect("127.0.0.1",1883,60)
client.on_connect = on_connect
client.on_message = on_message

client.loop_forever()

TÄTÄ DOKUMENTTIA SAA KOPIOIDA JA MUOKATA GNU GENERAL PUBLIC LICENSE (VERSIO 3 TAI UUDEMPI) MUKAISESTI: http://www.gnu.org/licenses/gpl.html

MARKUS PYHÄRANTA

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top
Scroll to Top