Blynk 物聯網平台: Install Local Blynk Server


2017-10-12 週四     Install Local Blynk Server

 
官網教學文件 How to install local Blynk Server
 
youtube 教學影片
 
 
       
 
 
[注意]
 
官網提動音應用 App 和服務器經常更新。 為了避免更新過程中的問題,請關閉 Blynk App 應用程序的自動更新,或同時更新本地服務器和blynk應用程序,以避免可能的遷移問題。
 

使用 Pi 當 Cloud

[材料]
 
樹莓派 3B *1 (MyPi3)
SD 8G
 
[系統需求]
 
Java 8/9 required (OpenJDK, Oracle)
Any OS that can run java
At least 30 MB of RAM (could be less with tuning)
Open ports 8443 (for app), 8442 (for hardware without ssl), 8441 (for hardware with ssl)
 
[Server]
 
[Local server setup]
 
確認樹莓派已安裝 Java 8 以上版本
java -version

java version "1.8.0_65"
Java(TM) SE Runtime Environment (build 1.8.0_65-b17)
Java HotSpot(TM) Client VM (build 25.65-b01, mixed mode)
 
若沒有安裝 ,安裝 Java 請參考下面指令
sudo apt-get install oracle-java8-jdk
 
下載 Blynk server 執行程式到電腦
https://github.com/blynkkk/blynk-server/releases
or 下載 Blynk server 執行程式到樹莓派
wget "https://github.com/blynkkk/blynk-server/releases/download/v0.28.2/server-0.28.2-java8.jar";
 
本實作以 server-0.28.2-java8.jar 為範例
 
 
 
設定工作目錄
 

 
mkdir /home/pi/my-project-by-blynk-local
cd /home/pi/my-project-by-blynk-local

pi@MyPi3:~/my-project-by-blynk-local $
 
 
 default Blynk local server 啟動命令
java -jarserver-0.28.2-java8.jar -dataFolder /path  --> /path should be real existing path to folder where you want to store all your data.
 
啟動
java -jarserver-0.28.2-java8.jar -dataFolder /home/pi/my-project-by-blynk-local &
 
執行程式會用到的相關 default port
 
hardware.mqtt.port=8440

#hardware ssl port
hardware.ssl.port=8441

#hardware plain tcp/ip port
hardware.default.port=8442

#http and web sockets port
http.port=8080

#https and web sockets port
https.port=9443

#application ssl port
app.ssl.port=8443
 
啟動結果:
default login account:admin@blynk.cc
default login password:admin

 
開機自動啟動 on unix-like systems
crontab -e
 
新增以下內容,並重新開機
@reboot java -jar /home/pi/my-project-by-blynk-local/server-0.28.2-java8.jar -dataFolder /home/pi/my-project-by-blynk-local &
 
查詢 Blynk 執行緒
ps -aux | grep java

查詢結果:
pi@MyPi3:~/my-project-by-blynk-local $  ps -aux | grep java
pi        1194 31.1  6.2 333324 59192 pts/1    Sl   10:43   0:19 java -jar /home/pi/my-project-by-blynk-local/server-0.28.2-java8.jar -dataFolder /home/pi/my-project-by-blynk-local
設定 app 連線至 Blynk local server
 

 
 
建立 SSL 憑證
openssl req -x509 -nodes -days 1825 -newkey rsa:2048 -keyout server.key -out server.crt
openssl pkcs8 -topk8 -inform PEM -outform PEM -in server.key -out server.pem
 
Server 進階組態設定
touch server.properties
sudo nano server.properties
 
範例內如:
#hardware mqtt port
hardware.mqtt.port=8440

#hardware ssl port
hardware.ssl.port=8441

#hardware plain tcp/ip port
hardware.default.port=8442

#http and web sockets port
http.port=8080

#https and web sockets port
https.port=9443

#application ssl port
app.ssl.port=8443

#address to bind to. by default bounded to all interfaces
listen.address=

#by default server uses embedded in jar cert to simplify local server installation.
#WARNNING DO NOT USE THIS CERTIFICATES ON PRODUCTION OR IN WHERE ENVIRNOMENTS REAL SECURITY REQUIRED.
#provide either full path to files either use '.' for specifying current directory. For instance "./myfile.crt"
#server.ssl.cert=
#server.ssl.key=
#server.ssl.key.pass=

server.ssl.cert=/home/pi/my-project-by-blynk-local/server.crt
server.ssl.key=/home/pi/my-project-by-blynk-local/server.pem
server.ssl.key.pass=999999

#by default System.getProperty("java.io.tmpdir")/blynk used
data.folder=

#folder for logs.
logs.folder=./logs

#log debug level. trace|debug|info|error. Defines how precise logging will be.
log.level=info

#maximum number of devices allowed per account
user.devices.limit=25

#maximum number of tags allowed per account
user.tags.limit=100

#defines maximum allowed number of user dashboards. Needed to limit possible number of tokens.
user.dashboard.max.limit=100

#defines maximum allowed widget size in KBs as json string.
user.widget.max.size.limit=20

#user is limited with 100 messages per second.
user.message.quota.limit=100

#maximum allowed number of notification queue. Queue responsible for processing email, pushes, twits sending.
#Because of performance issue - those queue is processed in separate thread, this is required due
#to blocking nature of all above operations. Usually limit shouldn't be reached.
notifications.queue.limit=2000

#Number of threads for performing blocking operations - push, twits, emails, db queries.
#Recommended to hold this value low unless you have to perform a lot of blocking operations.
blocking.processor.thread.pool.limit=6

#this setting defines how often we can send mail/tweet/push or any other notification. Specified in seconds
notifications.frequency.user.quota.limit=15

#this setting defines how often we can send webhooks. Specified in miliseconds
webhooks.frequency.user.quota.limit=1000

#this setting defines how big could be response for webhook GET request. Specified in kbs
webhooks.response.size.limit=72

#maximum size of user profile in kb's
user.profile.max.size=128

#number of strings to store in terminal widget
terminal.strings.pool.size=25

#number of strings to store in map widget
map.strings.pool.size=25

#number of strings to store in lcd widget
lcd.strings.pool.size=6

#maximum number of rows allowed
table.rows.pool.size=100

#period in millis for saving all user DB to disk.
profile.save.worker.period=60000

#period in millis for saving stats to disk.
stats.print.worker.period=60000

#specifies maximum period of time when hardware socket could be idle. After which
#socket will be closed due to non activity. In seconds. Default value 15 if not provided.
#leave it empty for infinity timeout
hard.socket.idle.timeout=15

#enable DB
enable.db=false

#enable raw data storage to DB
enable.raw.db.data.store=false

#size of async logger ring buffer. should be increased for loads >2-3k req/sec
async.logger.ring.buffer.size=2048

#initial amount of energy
initial.energy=100000

#ADMINISTRATION SECTION

admin.rootPath=/admin

#used for reset password page and certificate generation.
#by default current server IP is taken. could be replaced with more friendly hostname.
#it is recommended to override this property with your server IP to avoid possible problems of host resolving
#server.host=test.blynk.cc

#email used for certificate registration, could be omitted in case you already specified it in mail.properties
#contact.email=

#network interface to determine server's current IP.
#only the first characters of the interface's name are needed.
#the default setting eth will use the first ethX interface found (i.e. eth0)
net.interface=eth

#comma separated list of administrator IPs. allow access to admin UI only for those IPs.
#you may set it for 0.0.0.0/0 to allow access for all.
#you may use CIDR notation. For instance, 192.168.0.53/24
allowed.administrator.ips=0.0.0.0/0,::/0

# default admin name and password. that will be created on initial server start
admin.email=admin@blynk.cc
admin.pass=admin

#comma separated list of users allowed to create accounts. leave it empty if no restriction required.
allowed.users.list=
 
ps -aux | grep java
 
 
重新執行
java -jar /home/pi/my-project-by-blynk-local/server-0.28.2-java8.jar -dataFolder /home/pi/my-project-by-blynk-local-serverConfig/home/pi/my-project-by-blynk-local/server.properties&
 
一併修改
crontab -e
 
@reboot java -jar /home/pi/my-project-by-blynk-local/server-0.28.2-java8.jar -dataFolder /home/pi/my-project-by-blynk-local-serverConfig/home/pi/my-project-by-blynk-local/server.properties&
 
 
[Client]
 
設定工作目錄
 

 
mkdir /home/pi/my-project-by-blynk-local-client
cd /home/pi/my-project-by-blynk-local-client

pi@MyPi3:~/my-project-by-blynk-local $
 
 
LED 控制:建立 index.js
touch index.js
sudo nano index.js
 
內容如下:(Change your rasp PI javascript from 修改 ip 藍色字體  default port 8442 non ssl)
var Blynk = require('blynk-library');
var Gpio= require('onoff').Gpio;
var led = new Gpio(18,'out');

var AUTH = 'c15ac4653185420883aed51095c28c4c';


/* var blynk = new Blynk.Blynk(AUTH, options= {addr:"192.168.100.235"});  your ip address */

var blynk = new Blynk.Blynk(AUTH, options = {
  connector : new Blynk.TcpClient(options = { addr:"192.168.100.235", port:8442 })
});


var v0 = new blynk.VirtualPin(0);

v0.on('write', function(param) {

   if (param[0] == '1') {
     led.writeSync(1);
   } else {
     led.writeSync(0);
   }

   console.log('V0:',param[0]);

});
 
執行:
sudo NODE_PATH=/usr/lib/node_modules node index.js
執行內容:
 

 
溫濕度監控:建立 blynk-sensor-test.js
touch blynk-sensor-test.js && sudo nano blynk-sensor-test.js
 
var blynkLib = require('blynk-library');
var sensorLib = require('node-dht-sensor');

var AUTH = 'c15ac4653185420883aed51095c28c4c';

// Setup Blynk
var blynk = new blynkLib.Blynk(AUTH, options = {
  connector : new blynkLib.TcpClient(options = { addr:"192.168.100.235", port:8442 })
});


// Setup sensor, exit if failed
var sensorType = 11; // 11 for DHT11, 22 for DHT22 and AM2302
var sensorPin  = 4;  // The GPIO pin number for sensor signal
if (!sensorLib.initialize(sensorType, sensorPin)) {
    console.warn('Failed to initialize sensor');
    process.exit(1);
}

// Automatically update sensor value every 2 seconds
setInterval(function() {
    var readout = sensorLib.read();
    blynk.virtualWrite(3, readout.temperature.toFixed(1));
    blynk.virtualWrite(4, readout.temperature.toFixed(1));
    blynk.virtualWrite(5, readout.humidity.toFixed(1));

    console.log('Temperature:', readout.temperature.toFixed(1) + 'C');
    console.log('Humidity:   ', readout.humidity.toFixed(1)    + '%');
}, 2000);
 
啟動:
sudo NODE_PATH=/usr/lib/node_modules node ./blynk-sensor-test.js

Blynk 物聯網平台:Raspberry Pi + Node.js + Blynk App + DHT11/DHT22/AM2302)

 
 
[材料]
 
樹莓派 3*1
DHT11*2
 
[Install Sensor Libraries]
 
For DHT11/DHT22/AM2302 sensors,you need to download and install:
node-dht-sensor npm package
bcm2835 library
 
wget http://www.airspayce.com/mikem/bcm2835/bcm2835-1.46.tar.gz
tar zxvf bcm2835-1.46.tar.gz
cd bcm2835-1.46
./configure
make
sudo make check
sudo make install
sudo npm install -g node-dht-sensor

node-dht-sensor

npm install node-dht-sensor

 

[接線]
 
接單一 sensor

DHT11
pi:BCM
+
5v
out
4
GND
 
DHT22
pi:BCM
+
5v
out
4
GND
 
接兩個 sensor
DHT 11/DHT22
pi:BCM
+
5v
out
17
GND
單個 sensor:dht1.js(若為DHT22型號請修改為22)
touch dht1.js && sudo nano dht1.js
 
複製貼上
var sensor = require('node-dht-sensor');

sensor.read(11, 4, function(err, temperature, humidity) {
    if (!err) {
        console.log('temp: ' + temperature.toFixed(1) + '°C, ' +
            'humidity: ' + humidity.toFixed(1) + '%'
        );
    }
});
 
sudo node dht1.js
 
 
兩個 sensor:dht2.js(若為DHT22型號請修改為22)
touch dht2.js && sudo nano dht2.js
 
複製貼上
var sensorLib = require("node-dht-sensor");

var sensor = {
    sensors: [ {
        name: "Indoor",
        type:11,
        pin: 17
    }, {
        name: "Outdoor",
        type:22,
        pin: 4
    } ],
    read: function() {
        for (var a in this.sensors) {
            var b = sensorLib.read(this.sensors[a].type, this.sensors[a].pin);
            console.log(this.sensors[a].name + ": " +
              b.temperature.toFixed(1) + "°C, " +
              b.humidity.toFixed(1) + "%");
        }
        setTimeout(function() {
            sensor.read();
        }, 2000);
    }
};
sensor.read();
 
sudo node dht2.js
 
 
Scan/create Blynk Project

修改部分設定,如以下畫面

sudo touch blynk-sensor-test.js && sudo nano blynk-sensor-test.js
若為DHT22型號請修改為22
var blynkLib = require('blynk-library');
var sensorLib = require('node-dht-sensor');

var AUTH = '132c63edcda24bcd9066badebab74a95';

// Setup Blynk
var blynk = new blynkLib.Blynk(AUTH);

// Setup sensor, exit if failed
var sensorType =11; // 11 for DHT11, 22 for DHT22 and AM2302
var sensorPin  = 4;  // The GPIO pin number for sensor signal
if (!sensorLib.initialize(sensorType, sensorPin)) {
    console.warn('Failed to initialize sensor');
    process.exit(1);
}

// Automatically update sensor value every 2 seconds
setInterval(function() {
    var readout = sensorLib.read();
    blynk.virtualWrite(3, readout.temperature.toFixed(1));
    blynk.virtualWrite(4, readout.temperature.toFixed(1));
    blynk.virtualWrite(5, readout.humidity.toFixed(1));
    
    console.log('Temperature:', readout.temperature.toFixed(1) + 'C');
    console.log('Humidity:   ', readout.humidity.toFixed(1)    + '%');
}, 2000);
 
 
pi@MyPi4:~ $ sudo NODE_PATH=/usr/local/lib/node_modules node ./blynk-sensor-test.js
異常訊息
module.js:471
    throw err;
    ^

Error: Cannot find module 'blynk-library'
    at Function.Module._resolveFilename (module.js:469:15)
    at Function.Module._load (module.js:417:25)
    at Module.require (module.js:497:17)
    at require (internal/module.js:20:19)
    at Object.<anonymous> (/home/pi/blynk-sensor-test.js:1:78)
    at Module._compile (module.js:570:32)
    at Object.Module._extensions..js (module.js:579:10)
    at Module.load (module.js:487:32)
    at tryModuleLoad (module.js:446:12)
    at Function.Module._load (module.js:438:3)
解決:確認 node modules 安裝目錄所在位置,若不確定,可重新安裝,並將安裝目錄路徑抄寫下來
sudo npm install blynk-library -g
確認安裝目錄,應該如以下訊息
/usr/bin/blynk-client -> /usr/lib/node_modules/blynk-library/bin/blynk-client.js
/usr/bin/blynk-ctrl -> /usr/lib/node_modules/blynk-library/bin/blynk-ctrl.js
/usr/lib
`-- blynk-library@0.4.7
啟動
sudo NODE_PATH=/usr/lib/node_modules node ./blynk-sensor-test.js