Veb-server va WebSocket
WebSocket nima?
WebSocket Internet orqali real vaqtda ikki tomonlama aloqani ta’minlaydi.
WebSocket oddiy HTTP serveri bilan birga ishga tushirilishi mumkin. Siz veb-brauzerdagi tugmani bosishingiz va uyingizdagi chiroqni yoqadigan Raspberry Pi-da GPIO-ni yoqishingiz mumkin. Hammasi real vaqt rejimida va aloqa ikkala tomonga ham boradi!
Ushbu bobda biz WebSocket yordamida veb-serverni o‘rnatamiz. Keyin LEDni tugma yordamida yoqish va o‘chirish haqidagi oldingi misolimiz bilan o‘zaro ishlash uchun brauzer interfeysini yarating.
Menga nima kerak?
Ushbu qo‘llanma uchun sizga Raspberry Pi kerak. Bizning misollarimizda biz Raspberry Pi 3 dan foydalanamiz, lekin bu qo‘llanma ko‘pchilik versiyalar uchun ishlashi kerak.
Buning uchun sizga kerak:
- Node.js o‘rnatilgan Raspian, internet, SSH bilan Raspberry Pi
- Node.js uchun o‘chirish moduli
- Node.js uchun socket.io moduli
- 1 x Breadboard
- 1 x 68 Ohm qarshilik
- 1 x 1k Ohm qarshilik
- 1 x Teshik orqali LED
- 1 x Bosish tugmasi
- 4 x Ayoldan erkakka o‘tkazgich simlari
- 1 x Erkakdan erkakka o‘tkazgich simlari
Turli xil tavsiflar uchun yuqoridagi ro‘yxatdagi havolalarni bosing komponentlar.
Eslatma: Sizga kerak bo‘lgan rezistor siz foydalanadigan LED turiga qarab biz foydalanadigandan farq qilishi mumkin. Ko‘pgina kichik LEDlar faqat 200-500 ohm atrofida kichik qarshilikka muhtoj. Qaysi qiymatdan foydalanayotganingiz umuman muhim emas, lekin rezistorning qiymati qanchalik kichik bo‘lsa, LED shunchalik yorqinroq bo‘ladi. porlash.
Oldingi misolimiz bilan solishtirganda, bizga kerak bo‘lgan yagona yangi narsa - veb-serverni sozlash va socket.io modulini o‘rnatish.
Raspberry Pi va Node.js uchun veb-server
Ushbu Node.js qo‘llanmasining oldingi boblaridan so‘ng internetni o‘rnatamiz HTML fayllarga xizmat ko‘rsatishi mumkin bo‘lgan server.
Bizning "nodetest" katalogimizda statik html fayllari uchun foydalanishimiz mumkin bo‘lgan yangi katalog yarating:
pi@w3demopi:~/nodetest $ mkdir public
Endi veb-serverni o‘rnatamiz. So‘ralganni ochadigan Node.js faylini yarating faylni ochadi va kontentni mijozga qaytaradi. Agar biror narsa noto‘g‘ri bo‘lsa, 404 ni tashlang xato.
pi@w3demopi:~/nodetest $ nano webserver.js
webserver.js:
let http = require('http').createServer(handler); //require http server, and
create server with function handler()
let fs = require('fs'); //require filesystem module
http.listen(8080); //listen to port 8080
function handler (req, res) { //create server
fs.readFile(__dirname + '/public/index.html', function(err, data) { //read
file index.html in public folder
if (err)
{
res.writeHead(404,
{'Content-Type': 'text/html'}); //display 404 on error
return res.end("404 Not Found");
}
res.writeHead(200, {'Content-Type': 'text/html'}); //write HTML
res.write(data); //write data from index.html
return res.end();
});
}
"Ommaviy" jildiga o‘ting:
pi@w3demopi:~/nodetest $ cd public
Va HTML faylini yarating, index.html:
pi@w3demopi:~/nodetest/public $ nano index.html
index.html:
<!DOCTYPE html>
<html>
<body>
<h1>Control LED light</h1>
<input
id="light" type="checkbox">LED
</body>
</html>
Bu fayl hali hech qanday funksiyaga ega bo‘lmaydi. Hozircha bu faqat a joy ushlagich. Veb-server ishlayotganligini ko‘rib chiqaylik:
pi@w3demopi:~/nodetest/public $ cd ..
pi@w3demopi:~/nodetest $ node webserver.js
Veb-saytni http://[RaspberryPi_IP]:8080/ yordamida brauzerda oching:
Veb-server hozir ishlayotgan bo‘lishi kerak va biz o‘tishimiz mumkin WebSocket qismi.
Node.js uchun socket.io ni o‘rnating
Veb-serverni sozlash bilan Raspberry Pi tizim paketlarini so‘nggi versiyalariga yangilang.
Tizim paketingiz ro‘yxatini yangilang:
pi@w3demopi:~ $ sudo apt-get update
O‘rnatilgan barcha paketlaringizni so‘nggi versiyasiga yangilang:
pi@w3demopi:~ $ sudo apt-get dist-upgrade
Buni muntazam ravishda bajarish Raspberry Pi o‘rnatishingizni yangilab turadi.
Socket.io ning eng yangi versiyasini yuklab olish va o‘rnatish uchun quyidagi buyruqdan foydalaning:
pi@w3demopi:~ $ npm install socket.io --save
Veb-serverimizga WebSocket-ni qo‘shish
Endi biz ilovamizda WebSocket dan foydalanishimiz mumkin. Keling, index.html ni yangilaymiz fayl:
index.html:
<!DOCTYPE html>
<html>
<body>
<h1>Control LED
light</h1>
<p><input type="checkbox" id="light"></p>
<script src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/2.0.3/socket.io.js"></script>
<!-- include socket.io client side script -->
<script>
let socket = io();
//load socket.io-client and connect to the host that serves the page
window.addEventListener("load", function(){ //when page loads
let
lightbox = document.getElementById("light");
lightbox.addEventListener("change", function() { //add event listener for
when checkbox changes
socket.emit("light", Number(this.checked));
//send button status to server (as 1 or 0)
});
});
socket.on('light',
function (data) { //get button status from client
document.getElementById("light").checked = data; //change checkbox according
to push button on Raspberry Pi
socket.emit("light", data); //send
push button status to back to server
});
</script>
</body>
</html>
Va bizning webserver.js faylimiz:
webserver.js:
let http = require('http').createServer(handler); //require http server, and
create server with function handler()
let fs = require('fs'); //require filesystem module
let io
= require('socket.io')(http) //require socket.io module and pass the http
object (server)
http.listen(8080); //listen to port 8080
function handler (req, res) { //create server
fs.readFile(__dirname + '/public/index.html', function(err, data) { //read
file index.html in public folder
if (err)
{
res.writeHead(404,
{'Content-Type': 'text/html'}); //display 404 on error
return res.end("404 Not Found");
}
res.writeHead(200, {'Content-Type': 'text/html'}); //write HTML
res.write(data); //write data from index.html
return res.end();
});
}
io.sockets.on('connection', function (socket) {// WebSocket Connection
let lightvalue = 0; //static variable for current status
socket.on('light',
function(data) { //get light switch status from client
lightvalue = data;
if (lightvalue) {
console.log(lightvalue); //turn LED on or off, for now we will just show it
in console.log
}
});
});
Serverni sinab ko‘raylik:
pi@w3demopi:~ $ node webserver.js
Veb-saytni http://[RaspberryPi_IP]:8080/ yordamida brauzerda oching:
Endi server tasdiqlash qutisiga kiritilgan barcha o‘zgarishlarni konsolga chiqarishi kerak Raspberry Pi-da.
Mijoz o‘zgarishlarni serverga yubormoqda, server esa javob berish.
bosish tugmachasini qo‘shishga ruxsat bering oldingi bobdan boshqariladigan LED.
Uskunani qo‘shish va mijozga javob yuborish
Keling, webserver.js faylimizni yana yangilaymiz. Biz ko‘p kodlardan foydalanamiz Bosish tugmasi bilan boshqariladigan LED bo‘limi.
webserver.js:
let http = require('http').createServer(handler); //require http server, and
create server with function handler()
let fs = require('fs'); //require filesystem module
let io
= require('socket.io')(http) //require socket.io module and pass the http
object (server)
let Gpio = require('onoff').Gpio; //include onoff to
interact with the GPIO
let LED = new Gpio(4, 'out'); //use GPIO pin 4 as
output
let pushButton = new Gpio(17, 'in', 'both'); //use GPIO pin 17 as
input, and 'both' button presses, and releases should be handled
http.listen(8080); //listen to port 8080
function handler (req, res)
{ //create server
fs.readFile(__dirname
+ '/public/index.html', function(err, data) { //read file index.html in
public folder
if (err) {
res.writeHead(404, {'Content-Type': 'text/html'}); //display 404 on error
return res.end("404 Not Found");
}
res.writeHead(200, {'Content-Type': 'text/html'}); //write HTML
res.write(data); //write data from index.html
return res.end();
});
}
io.sockets.on('connection', function (socket) {// WebSocket Connection
let lightvalue = 0; //static variable for current status
pushButton.watch(function (err, value) { //Watch for hardware interrupts on
pushButton
if (err) { //if an error
console.error('There was an error', err); //output error message to console
return;
}
lightvalue = value;
socket.emit('light', lightvalue); //send button status to client
});
socket.on('light', function(data) { //get light switch status
from client
lightvalue = data;
if (lightvalue != LED.readSync()) { //only change LED if status has changed
LED.writeSync(lightvalue); //turn LED on or off
}
});
});
process.on('SIGINT', function () { //on ctrl+c
LED.writeSync(0); // Turn LED off
LED.unexport(); // Unexport LED
GPIO to free resources
pushButton.unexport(); // Unexport Button
GPIO to free resources
process.exit(); //exit completely
});
Serverni sinab ko‘raylik:
pi@w3demopi:~ $ node webserver.js
Veb-saytni http://[RaspberryPi_IP]:8080/ yordamida brauzerda oching:
Endi server tasdiqlash qutisiga kiritilgan barcha o‘zgarishlarni konsolga chiqarishi kerak Raspberry Pi-da.
Mijoz o‘zgarishlarni serverga yubormoqda, server esa javob berish.
Dasturni Ctrl+c bilan yakunlang.
W3Schools Pathfinder
Yutuqlaringizni kuzating – bu bepul!
