|     Inicio    |   |         |  |   FOROS      |  |      |      
   Elastix - VoIP B4A (Basic4Android) App inventor 2 PHP - MySQL
  Estación meteorológica B4J (Basic4Java) ADB Shell - Android Arduino
  Raspberry Pi Visual Basic Script (VBS) FireBase (BD autoactualizable) NodeMCU como Arduino
  AutoIt (Programación) Visual Basic Cosas de Windows Webs interesantes
Translate:
Búsqueda en este sitio:


.

Raspberry Pi

Tutorial de Rapberry Pi en español.
- Juan Antonio Villalpando -

Volver al índice del tutorial

____________________________

11.- IoT. Publica. Subscribe. Eclipse.

GPIO2 es SDA
GPIO3 es SCL

- Es necesario instalar Paho

- sudo pip install paho-mqtt

- sudo pip3 install paho-mqtt

- Información de Paho

https://mntolia.com/mqtt-python-with-paho-mqtt-client/

- Brokers

  • test.mosquitto.org
  • broker.hivemq.com
  • iot.eclipse.org

- Para ver los resultados utilizaremos la aplicación de la Play de Google Linear MQTT Dashboard. Consulta al final de la página para ver cómo se configura.

- También la aplicación p117_eclipse_mqtt_RPB.aia de App Inventor.

______________________________
1.- Publica un número aleatorio.

- Publica un número aleatorio a los 7 segundos de comenzar.

aleatorio.py

# import context  # Ensures paho is in PYTHONPATH
import paho.mqtt.publish as publish
import time
from random import randint
import threading

def hello():
    print "hello, world"
    aleatorio=randint(0,100)
    publish.single("juan/aleatorio", aleatorio, hostname="iot.eclipse.org")

t = threading.Timer(7.0, hello)
t.start() # after 7 seconds, "hello, world" will be printed



# while True:
  #  time.sleep(5)				 
					 

______________________________
2.- Publica un número aleatorio cada 10 segundos.

- Escribe la palabra "comienza" para comenzar. Publica un número aleatorio cada 10 segundos. Termina a las 20 publicaciones.

aleatorio_10.py

import paho.mqtt.publish as publish
import time
from random import randint

run = raw_input("Escribe la palabra: comienza")
n = 0

if run == "comienza":
    # Realizará 20 envíos.
    while n != 20:
        print ">>>>>>>>>>>>>>>>>>>>>", n
        aleatorio=randint(0,100)
        publish.single("juan/aleatorio", aleatorio, hostname="iot.eclipse.org")

        # Espera 10 segundos.
        time.sleep(10)
        # Incrementa las veces.
        n += 1

______________________________
4.- Publica el estado de dos pulsadores.

- Consulta el tutorial correspondiente a 3.- Pulsador.

- Conectamos un pulsador en los pines 10 y 3.3V. El otro pulsador en los pines 12 y 3.3V

dos_pulsadores.py

#import context  # Ensures paho is in PYTHONPATH
import paho.mqtt.publish as publish
import RPi.GPIO as GPIO
from time import sleep # Función sleep del módulo time

GPIO.setwarnings(False)
GPIO.setmode(GPIO.BOARD)
GPIO.setup(10, GPIO.IN, pull_up_down=GPIO.PUD_DOWN)
GPIO.setup(12, GPIO.IN, pull_up_down=GPIO.PUD_DOWN)

while True:
    if GPIO.input(10) == GPIO.HIGH:
        #print("10 PULSADO.")
        rojo = "ROJO PULSADO"
    else:
        #print("10 No pulsado.")
        rojo = "rojo NO"
    sleep(0.2)
    if GPIO.input(12) == GPIO.HIGH:
        #print("12 PULSADO.")
        azul = "AZUL PULSADO"
    else:
        #print("12 No pulsado.")
        azul = "azul NO"
        
    texto = rojo + " - " + azul
    publish.single("juan/consulta", texto, hostname="iot.eclipse.org")
    # Espera 3 segundos.
    sleep(3)

______________________________
5.- Publica el estado de dos pulsadores y la temperatura del sensor DHT-11

dos_pulsadores_dht_11.py

import paho.mqtt.publish as publish
import RPi.GPIO as GPIO
from time import sleep # Función sleep del módulo time
import Adafruit_DHT
from random import randint

GPIO.setwarnings(False)
GPIO.setmode(GPIO.BOARD)
GPIO.setup(10, GPIO.IN, pull_up_down=GPIO.PUD_DOWN)
GPIO.setup(12, GPIO.IN, pull_up_down=GPIO.PUD_DOWN)

while True:
    humidity, temperature = Adafruit_DHT.read_retry(11, 4)
    temperature = randint(0,100)
    publish.single("juan/temperatura", temperature, hostname="iot.eclipse.org")
        
    if GPIO.input(10) == GPIO.HIGH:
        rojo = "ROJO PULSADO"
    else:
        rojo = "rojo NO"
    if GPIO.input(12) == GPIO.HIGH:
        azul = "AZUL PULSADO"
    else:
        azul = "azul NO"
        
    texto = rojo + " - " + azul
    publish.single("juan/consulta", texto, hostname="iot.eclipse.org")
    # Espera 3 segundos.
    sleep(3)
					 

______________________________
5b.- Otra forma de Publicar.

-

pub.py


import Adafruit_DHT
import paho.mqtt.client as mqtt
client = mqtt.Client()
host = "iot.eclipse.org"
client.connect (host, port=1883, keepalive=60)
client.loop_start()

while True:

    humidity, temperature = Adafruit_DHT.read_retry(11, 4)
    print ("Humidity = {} %; Temperature = {} C".format(humidity, temperature))
    
    client.publish("juan/humedad", humidity)
    client.publish("juan/temperatura", temperature)

 

______________________________
6.- Subscribe el estado de un Botón.

- En la aplicación Linear MQTT Dashboard, hay un Botón, cuando lo pulsamos obtenemos su estado en Rapsberry.

boton.py

import paho.mqtt.subscribe as subscribe
topics = ['juan/boton']

m = subscribe.simple(topics, hostname="iot.eclipse.org", retained=False, msg_count=2)
for a in m:
    print(a.topic)
    print(a.payload)

______________________________
7.- Subscribe el estado de un Botón 2.

- En la aplicación Linear MQTT Dashboard, hay un Botón, cuando lo pulsamos obtenemos su estado en Rapsberry.

boton_2.py

import paho.mqtt.subscribe as subscribe

def print_msg(client, userdata, message):
    print("%s : %s" % (message.topic, message.payload))

subscribe.callback(print_msg, "juan/boton", hostname="iot.eclipse.org")

______________________________
8.- Subscribe el estado de dos Botones.

boton_3.py

import paho.mqtt.subscribe as subscribe
import I2C_LCD_driver
mylcd = I2C_LCD_driver.lcd()

def print_msg(client, userdata, message):
    #print("%s" % (message.payload))
    s =  str(message.payload)
    #print(s)
    led1 = " "
    led2 = " "
    if s == "b'a'":
        led1 = " ENCENDIDO 1"
    if s == "b'b'":
        led1 = " APAGADO   1"
    if s == "b'c'":
        led2 = " ENCENDIDO 2"
    if s == "b'd'":
        led2 = " APAGADO   2"

    #mylcd.lcd_display_string(str(s), 1)
    mylcd.lcd_display_string(led1, 1)
    mylcd.lcd_display_string(led2, 2)


subscribe.callback(print_msg, "juan/#", hostname="iot.eclipse.org")

______________________________
9.- Subscribe el estado de dos Botones y enciende dos LED.

- Conectamos dos LED a los terminales 16 y 18.

boton_3.py

import RPi.GPIO as GPIO
GPIO.setwarnings(False)
GPIO.setmode(GPIO.BOARD)
GPIO.setup(16, GPIO.OUT, initial=GPIO.LOW)
GPIO.setup(18, GPIO.OUT, initial=GPIO.LOW)

import paho.mqtt.subscribe as subscribe
import I2C_LCD_driver
mylcd = I2C_LCD_driver.lcd()

def print_msg(client, userdata, message):
    #print("%s" % (message.payload))
    s =  str(message.payload)
    #print(s)
    led1 = " "
    led2 = " "
    if s == "b'a'":
        led1 = " ENCENDIDO 1"
        GPIO.output(16, GPIO.HIGH)
    if s == "b'b'":
        led1 = " APAGADO   1"
        GPIO.output(16, GPIO.LOW)
    if s == "b'c'":
        led2 = " ENCENDIDO 2"
        GPIO.output(18, GPIO.HIGH)
    if s == "b'd'":
        led2 = " APAGADO   2"
        GPIO.output(18, GPIO.LOW)

    #mylcd.lcd_display_string(str(s), 1)
    mylcd.lcd_display_string(led1, 1)
    mylcd.lcd_display_string(led2, 2)


subscribe.callback(print_msg, "juan/#", hostname="iot.eclipse.org")

______________________________
10.- Publica y Suscribe a la vez.

- Una forma de hacerlo sería abrir el programa de Raspberry Python 3 (IDLE) y abrir y ejecutar el archivo del ejemplo 5. Luego abrir otro programa Python 3 (IDLE) y ejecutar el archivo del ejemplo 9.

- Aquí tenemos otra manera más práctica, publica y suscribe en el mismo archivo:

pub_sub.py


# Juan Antonio Villalpando
# kio4.com

import paho.mqtt.client as mqtt
import paho.mqtt.publish as publish
import paho.mqtt.subscribe as subscribe

import RPi.GPIO as GPIO
from time import sleep # Función sleep del módulo time
import Adafruit_DHT
from random import randint # Función aleatorio

GPIO.setwarnings(False)
GPIO.setmode(GPIO.BOARD)
# Pulsadores
GPIO.setup(10, GPIO.IN, pull_up_down=GPIO.PUD_DOWN)
GPIO.setup(12, GPIO.IN, pull_up_down=GPIO.PUD_DOWN)
# LED o Relés
GPIO.setup(16, GPIO.OUT, initial=GPIO.LOW)
GPIO.setup(18, GPIO.OUT, initial=GPIO.LOW)
# LCD
import I2C_LCD_driver
mylcd = I2C_LCD_driver.lcd()


# Respuesta de la conexión.
def on_connect(client, userdata, flags, rc):
    print("Codigo de conexion "+str(rc))
    client.subscribe("juan/#") # Nos suscribimos a todo

# Esto lo hace al Recibir un mensaje:
def on_message(client, userdata, msg):
    mensaje = str(msg.payload)
    print(msg.topic+" "+mensaje)
    #print("%s" % (message.payload))
    #s =  str(message.payload)
    #print(s)
    led1 = " "
    led2 = " "
    if mensaje == "b'a'":
        led1 = " ENCENDIDO 1"
        GPIO.output(16, GPIO.HIGH)
    if mensaje == "b'b'":
        led1 = " APAGADO   1"
        GPIO.output(16, GPIO.LOW)
    if mensaje == "b'c'":
        led2 = " ENCENDIDO 2"
        GPIO.output(18, GPIO.HIGH)
    if mensaje == "b'd'":
        led2 = " APAGADO   2"
        GPIO.output(18, GPIO.LOW)

    #mylcd.lcd_display_string(str(s), 1)
    mylcd.lcd_display_string(led1, 1)
    mylcd.lcd_display_string(led2, 2)

# Publica.
def on_publish(mosq, obj, mid):
    print("mid: " + str(mid))

# Conexión. Deber ir aquí, no arriba.
client = mqtt.Client()
client.on_connect = on_connect
client.on_message = on_message
client.connect("iot.eclipse.org", 1883, 60)
client.loop_start()

# Bucle 3 segundos para Publicación.
while True:
    # Publicación de Temperatura
    #humidity, temperature = Adafruit_DHT.read_retry(11, 4)
    temperature = randint(28,31)
    client.publish("juan/temperatura", str(temperature))

    # Publicación de Pulsadores
    if GPIO.input(10) == GPIO.HIGH:
        rojo = "ROJO PULSADO"
    else:
        rojo = "rojo NO"
    if GPIO.input(12) == GPIO.HIGH:
        azul = "AZUL PULSADO"
    else:
        azul = "azul NO"
        
    texto = rojo + " - " + azul
    publish.single("juan/consulta", texto, hostname="iot.eclipse.org")
    sleep(3)

- Configuración de la aplicación Linear MQTT Dashboard.

- También la aplicación p117_eclipse_mqtt_RPB.aia de App Inventor. Lo puedes instalar con este QR.

iot.pdf

___________________________________________________

 

- Mi correo:
juana1991@yahoo.com
- KIO4.COM - Política de cookies. Textos e imágenes propiedad del autor:
© Juan A. Villalpando
No se permite la copia de información ni imágenes.
Usamos cookies propias y de terceros que entre otras cosas recogen datos sobre sus hábitos de navegación y realizan análisis de uso de nuestro sitio.
Si continúa navegando consideramos que acepta su uso. Acepto    Más información