Giter Club home page Giter Club logo

blynk-library-lua's Introduction

Lua client for Blynk IoT

Note: The library has been updated for Blynk 2.0

GitHub version GitHub download GitHub stars GitHub issues License

If you like Blynk - give it a star, or fork it and contribute! GitHub stars GitHub forks


What is Blynk?

Blynk provides iOS and Android apps to control any hardware over the Internet or directly using Bluetooth. You can easily build graphic interfaces for all your projects by simply dragging and dropping widgets, right on your smartphone. Blynk is the most popular IoT platform used by design studios, makers, educators, and equipment vendors all over the world.

Blynk Banner

Download

Blynk Mobile App: Google Play | App Store

Documentation

Social: Webpage / Facebook / Twitter / Kickstarter
Documentation: https://docs.blynk.io
Community Forum: http://community.blynk.cc
Blynk for Business: http://www.blynk.io

Usage example

local Blynk = require("blynk.socket")

local blynk = Blynk.new("your_auth_token")

-- callback to run when V1 changes
blynk:on("V1", function(param)
  print("V1:", tonumber(param[1]), tonumber(param[2]))
end)

-- callback to run when cloud requests V2 value
blynk:on("readV2", function(param)
  blynk:virtualWrite(2, os.time())
end)

local sock = getSocketConnection() -- omitted
blynk:connect(sock)

while true do
  blynk:run()
end

You can run the full example:

lua ./examples/client.lua <your_auth_token>

Features

  • Lua 5.1, Lua 5.2, Lua 5.3, LuaJIT support
  • Linux, Windows, MacOS support
  • virtualWrite
  • syncVirtual
  • setProperty
  • logEvent
  • events: Vn, readVn, connected, disconnected, redirect
  • TCP and secure TLS/SSL connection support
  • can run on embedded hardware, like NodeMCU or OpenWrt

OpenWrt installation

opkg update
opkg install lua luasocket luasec
# openssl is needed for wget to handle https://
opkg install wget openssl-util libustream-wolfssl

# Get blynk-library-lua from github
cd /root
wget --no-check-certificate -qO- https://github.com/vshymanskyy/blynk-library-lua/archive/v0.2.0.tar.gz | tar xvz
cd blynk-library-lua-0.2.0

# Run it
lua ./examples/client.lua <your_auth_token>

NodeMCU installation

It is very easy to get it running on NodeMCU (or any other ESP8266/ESP32-based device):

  • Get the latest nodemcu-firmware running on your device.
    You can use their online build service.
    It is recommended to include encoder, TLS/SSL modules.
  • Edit nodemcu.lua example (put your auth token and wifi credentials)
  • Use nodemcu-tool or any other method to transfer lua files to the device.
    Note: the NodeMCU filesystem is "flat" (folders not supported), but it handles the / symbol nicely.
    Be sure to preserve the relative path when copying files:
    nodemcu-tool upload -mck ./blynk.lua ./blynk/pipe.lua ./blynk/nodemcu.lua
    nodemcu-tool upload ./examples/nodemcu.lua -n init.lua
  • Open device terminal and run dofile("init.lua")
  • blynk object is global, so you can call it from the interactive console:
    blynk:virtualWrite(1, tmr.time())

Ubuntu/Linux/Raspberry Pi installation

sudo apt-get install lua5.3 lua-sec lua-socket

Bonus

The Timer is included for demonstration purposes.
Here are also some handy functions:

local function millis()
  return math.floor(socket.gettime()*1000)
end

local function delay(msec)
  return socket.sleep(msec/1000)
end

Implementations for other platforms

License

This project is released under The MIT License (MIT)

blynk-library-lua's People

Contributors

vshymanskyy avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar

blynk-library-lua's Issues

ошибка при работе с библиотекой

Выполняю все по инструкции: подправил файл примера вписал свои данные, затем заливаю через nodemcu-tool, далее открываю консоль и наблюдаю:
NodeMCU ESP32 build unspecified powered by Lua 5.1.4 on SDK IDF
lua: module 'blynk' not found:
no field package.preload['blynk']
no file 'blynk.lc'
no file 'blynk.lua'
stack traceback:
[C]: in function 'require'
?: in main chunk
[C]: in function 'require'
init.lua:6: in main chunk
[C]: ?
можете помочь разобраться что не так?
Железо esp32 прошивка nodemcu-lua

Client crashed line 95

stack traceback:
[C]: in function 'assert'
blynkmon.lua:95: in function 'connectBlynk'
blynkmon.lua:121: in function 'fun'
./blynk.lua:54: in function 'emit'
./blynk.lua:107: in function 'disconnect'
./blynk/socket.lua:31: in function 'run'
blynkmon.lua:179: in main chunk
[C]: ?

if use_ssl then
print("Connecting Blynk (secure)...")
sock:connect(host, 443)
local opts = {
mode = "client",
protocol = "tlsv1_2"
}
sock = assert(ssl.wrap(sock, opts))
assert(sock:dohandshake())
else
print("Connecting Blynk...")
sock:connect(host, 80)
end

Here is the whole script

#!/usr/bin/env lua

--[[
This is the default example for Linux, Windows, OpenWrt
]]

local socket = require("socket")
local use_ssl, ssl = pcall(require, "ssl")

local Blynk = require("blynk.socket")
local Timer = require("timer")

assert(#arg >= 1, "Please specify Auth Token")
local auth = arg[1]

local blynk = Blynk.new(auth, {
heartbeat = 30, -- default h-beat is 50
--log = print,
})

function exec_out(cmd)
local file = io.popen(cmd)
if not file then return nil end
local output = file:read('*all')
file:close()
print("Run: "..cmd.." -> "..output)
return output
end
function read_file(path)
local file = io.open(path, "rb")
if not file then return nil end
local content = file:read "*a"
file:close()
print("Read: "..path.." -> "..content)
return content
end

function getArpClients()
return tonumber(exec_out("cat /proc/net/arp | grep br-lan | grep 0x2 | wc -l"))
end
function getUptime()
return tonumber(exec_out("cat /proc/uptime | awk '{print $1}'"))
end
function getWanIP()
return exec_out("ifconfig eth0 | grep 'inet addr:' | cut -d: -f2 | awk '{print $1}'")
end
function getWirelessIP()
return exec_out("ifconfig 3g-modem_1_1_2 | grep 'inet addr:' | cut -d: -f2 | awk '{print $1}'")
end
function getCpuLoad()
return tonumber(exec_out("top -bn1 | grep 'CPU:' | head -n1 | awk '{print $2+$4}'"))
end
function getRamUsage()
return tonumber(exec_out("free | grep Mem | awk '{print ($3-$7)/$2 * 100.0}'"))
end

function getWanRxBytes()
return tonumber(read_file("/sys/class/net/eth0/statistics/rx_bytes"))
end
function getWanTxBytes()
return tonumber(read_file("/sys/class/net/eth0/statistics/tx_bytes"))
end
function getWirelessRxBytes()
return tonumber(read_file("/sys/class/net/3g-modem_1_1_2/statistics/rx_bytes"))
end
function getWirelessTxBytes()
return tonumber(read_file("/sys/class/net/3g-modem_1_1_2/statistics/tx_bytes"))
end
function getWirelessSINR()
return tonumber(exec_out("gl_modem cells | jq .[0].sinr | awk '{ print $1 }' | tr -d '"'"))
end
function getWirelessRSSI()
return tonumber(exec_out("gl_modem cells | jq .[0].rssi | awk '{ print $1 }' | tr -d '"'"))
end
function getWirelessRSRQ()
return tonumber(exec_out("gl_modem cells | jq .[0].rsrq | awk '{ print $1 }' | tr -d '"'"))
end
function getWirelessRSRP()
return tonumber(exec_out("gl_modem cells | jq .[0].rsrp | awk '{ print $1 }' | tr -d '"'"))
end
local function connectBlynk()
local host = "blynk.cloud"

local sock = assert(socket.tcp())
sock:setoption("tcp-nodelay", true)

if use_ssl then
print("Connecting Blynk (secure)...")
sock:connect(host, 443)
local opts = {
mode = "client",
protocol = "tlsv1_2"
}
sock = assert(ssl.wrap(sock, opts))
assert(sock:dohandshake())
else
print("Connecting Blynk...")
sock:connect(host, 80)
end

-- tell Blynk to use this socket
blynk:connect(sock)
end

blynk:on("connected", function(ping)
print("Ready. Ping: "..math.floor(ping*1000).."ms")
blynk:virtualWrite(12, getWanIP())
blynk:virtualWrite(13, getWirelessIP())
blynk:virtualWrite(40, getWirelessSINR())
blynk:virtualWrite(41, getWirelessRSSI())
blynk:virtualWrite(42, getWirelessRSRQ())
blynk:virtualWrite(43, getWirelessRSRP())
-- whenever we connect, request an update of V1
blynk:syncVirtual(1)
end)

blynk:on("disconnected", function()
print("Disconnected.")
-- auto-reconnect after 5 seconds
socket.sleep(5)
connectBlynk()
end)

-- callback to run when V1 changes
blynk:on("V1", function(param)
print("V1:", tonumber(param[1]), tonumber(param[2]))
end)

-- callback to run when cloud requests V2 value
blynk:on("readV2", function(param)
blynk:virtualWrite(2, os.time())
end)

local prevWanTx, prevWanRx, prevWirelessTx, prevWirelessRx

-- create a timer to update widget property
local tmr1 = Timer:new{interval = 5000, func = function()
blynk:setProperty(2, "label", os.time())
blynk:virtualWrite(5, getCpuLoad())
blynk:virtualWrite(6, getRamUsage())
local wantx = getWanTxBytes()
local wanrx = getWanRxBytes()
local wirelesstx = getWirelessTxBytes()
local wirelessrx = getWirelessRxBytes()
if prevWanTx and prevWanTx ~= wantx then
blynk:virtualWrite(30, wantx - prevWanTx)
print(wantx - prevWanTx)
end
if prevWanRx and prevWanRx ~= wanrx then
blynk:virtualWrite(31, wanrx - prevWanRx)
print(wanrx - prevWanRx)
end
if prevWirelessTx and prevWirelessTx ~= wirelesstx then
blynk:virtualWrite(32, wirelesstx - prevWirelessTx)
print(wirelesstx - prevWirelessTx)
end
if prevWirelessRx and prevWirelessRx ~= wirelessrx then
blynk:virtualWrite(33, wirelessrx - prevWirelessRx)
print(wirelessrx - prevWirelessRx)
end
prevWanTx = wantx
prevWanRx = wanrx
prevWirelessTx = wirelesstx
prevWirelessRx = wirelessrx
end}

local tmr2 = Timer:new{interval = 5601000, func = function()
blynk:virtualWrite(10, getArpClients())
blynk:virtualWrite(11, string.format("%.1f h", getUptime()/60/60))
blynk:virtualWrite(40, getWirelessSINR())
blynk:virtualWrite(41, getWirelessRSSI())
blynk:virtualWrite(42, getWirelessRSRQ())
blynk:virtualWrite(43, getWirelessRSRP())
end}

connectBlynk()

while true do
blynk:run()
tmr1:run()
tmr2:run()

end

ESP8266 - Cannot connect to Blynk cloud.. (Disconnected)

Hi, thanks for the library
I tried this on my two ESP modules, but none oh them seems to be working.
It only displays Connecting and then Disconnected.

Board used:

  1. ESP8266-01 Module
  2. NodeMCU Devboard, Lolin V3

Firmware Info:

NodeMCU custom build by frightanic.com
	branch: master
	commit: c708828bbe853764b9de58fb8113a70f5a24002d
	SSL: false
	modules: cron,crypto,encoder,file,gpio,mqtt,net,node,rtctime,sntp,tmr,uart,wifi
 build created on 2018-11-07 05:01
 powered by Lua 5.1.4 on SDK 2.2.1(6ab97e9)

Output Log:

> dofile("run.lua")
    ___  __          __
   / _ )/ /_ _____  / /__
  / _  / / // / _ \/  '_/
 /____/_/\_, /_//_/_/\_\
        /___/ for Lua v0.1.3

Connecting WiFi...
> Connecting Blynk...
Disconnected.
Connecting Blynk...
Disconnected.
Connecting Blynk...
Disconnected.
Connecting Blynk...
Disconnected.
Connecting Blynk...
...
...
(repeats..)

Could you look into this?

invalid token

Running it on OpenWRT, it tells me auth token is invalid? I copy the auth token from #define BLYNK_AUTH_TOKEN under device? Is it not the right place?

cannot run on openwrt

hello am trying to install it on openwrt runing under intel nuc

the commmand:
lua ./examples/client.lua auth

disconnects all the time:
Connecting Blynk (secure)...
Disconnected.
Connecting Blynk (secure)...
Invalid auth token
Disconnected.

any how to fix this issue?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.