Tag - nodemcu

Entries feed

Thursday, October 27 2016

Envoyer un courriel avec NodeMCU sur l'ESP8266

Nous avons précédemment parlé de l'ESP8266 en le propulsant à l'aide de Micropython. Il est églament possible de propulser un ESP8266 à l'aide de NodeMCU, un microframework en lua (attention, c'est trompeur, NodeMCU désigne à la fois un type de matériel et le logiciel qui le propulse).

9865736.png

Pour bâtir la version du firmware NodeMCU adapté à son usage, on peut utiliser ce site internet : https://nodemcu-build.com/

Une fois NodeMCU construit, on l'envoie à l'aide des commandes :

esptool.py --port /dev/ttyUSB0 erase_flash
esptool.py --port /dev/ttyUSB0 --baud 460800 write_flash --flash_size=8m 0 /path/to/nodemcu.bin

Voyons maintenant comment utiliser NodeMCU. Nous allons d'abord placer sur l'ESP8266 un fichier "init.lua" qui servira à l'initialisation de l'ESP8266 et notamment à sa connexion au WIfi local :

function startup()
    if file.open("init.lua") == nil then
      print("init.lua deleted")
    else
      print("Running")
      file.close("init.lua")
      print("Running main.lua")
      dofile("main.lua")
    end
end

--init.lua
wifi.sta.disconnect()
print("Set up wifi mode")
wifi.setmode(wifi.STATION) --on active la connexion à un point d'accès
wifi.sta.config("ssid","password",0) --SSID et mot de passe du point d'accès
wifi.sta.connect()
tmr.alarm(1, 1000, 1, function()
    if wifi.sta.getip()== nil then
        print("IP unavailable, Waiting...")
    else
        tmr.stop(1)
        print("Config done, IP is "..wifi.sta.getip()) --si réussite, alors on affiche les infos du réseau
        print("You have 5 seconds to abort Startup")
        print("Waiting...")
        tmr.alarm(0,5000,0,startup)
    end
 end)

Le code est assez facile à lire. Une fois les instructions de init.lua terminées, on lance le fichier main.lua. Il est alors possible de faire exécuter les actions de son choix à l'ESP8266.

Imaginons que l'on souhaite faire envoyer des courriels de notification par l'ESP8266 : on utiliserait alors le code suivant dans main.lua. Comme la librairie crypto est utilisée, il faut bien évidemment construire NodeMCU avec cette librairie.

require("crypto")

-- The email and password from the account you want to send emails from
local LOGIN = "login"
local MY_EMAIL = "name@domain.tld"
local EMAIL_PASSWORD = "password"

-- The SMTP server and port of your email provider.
-- If you don't know it google [my email provider] SMTP settings
local SMTP_SERVER = "smtp.domain.tld"
local SMTP_PORT = "465"

-- The account you want to send email to
local mail_to = "name@domain.tld"

-- These are global variables. Don't change their values
-- they will be changed in the functions below
local email_subject = ""
local email_body = ""
local count = 0

local smtp_socket = nil -- will be used as socket to email server

-- The display() function will be used to print the SMTP server's response
function display(sck,response)
     print(response)
end

-- The do_next() function is used to send the SMTP commands to the SMTP
server in the required sequence.
-- I was going to use socket callbacks but the code would not run
callbacks after the first 3.
function do_next()
            if(count == 0)then
                count = count+1
                local IP_ADDRESS = wifi.sta.getip()
                smtp_socket:send("HELO "..IP_ADDRESS.."\r\n")
            elseif(count==1) then
                count = count+1
                smtp_socket:send("AUTH LOGIN\r\n")
            elseif(count == 2) then
                count = count + 1
                smtp_socket:send(crypto.toBase64(LOGIN).."\r\n")
            elseif(count == 3) then
                count = count + 1
                smtp_socket:send(crypto.toBase64(EMAIL_PASSWORD).."\r\n")
            elseif(count==4) then
                count = count+1
               smtp_socket:send("MAIL FROM:<" .. MY_EMAIL .. ">\r\n")
            elseif(count==5) then
                count = count+1
               smtp_socket:send("RCPT TO:<" .. mail_to ..">\r\n")
            elseif(count==6) then
                count = count+1
               smtp_socket:send("DATA\r\n")
            elseif(count==7) then
                count = count+1
                local message = string.gsub(
                "From: "".. MY_EMAIL ..""<"..MY_EMAIL..">\r\n" ..
                "To: "".. mail_to .. ""<".. mail_to..">\r\n"..
                "Subject: ".. email_subject .. "\r\n\r\n"  ..
                email_body,"\r\n.\r\n","")

                smtp_socket:send(message.."\r\n.\r\n")
            elseif(count==8) then
               count = count+1
                 tmr.stop(0)
                 smtp_socket:send("QUIT\r\n")
            else
               smtp_socket:close()
            end
end

-- The connectted() function is executed when the SMTP socket is
connected to the SMTP server.
-- This function will create a timer to call the do_next function which
will send the SMTP commands
-- in sequence, one by one, every 5000 milliseconds.
-- You can change the time to be smaller if that works for you, I used
5000ms just because.
function connected(sck)
    tmr.alarm(0,5000,1,do_next)
end

-- @name send_email
-- @description Will initiated a socket connection to the SMTP server
and trigger the connected() function
-- @param subject The email's subject
-- @param body The email's body
function send_email(subject,body)
     count = 0
     email_subject = subject
     email_body = body
     smtp_socket = net.createConnection(net.TCP,1) -- the last paramater indicates the connection is secured by TLS/SSL
     smtp_socket:on("connection",connected)
     smtp_socket:on("receive",display)
     smtp_socket:connect(SMTP_PORT,SMTP_SERVER)
end

function query()
    subject = "Notification email"
    body = "This is the body of the email"
    send_email(subject,body.."\n.\n")
end

print("Ready to work. Sending email.")
query()