https://javascript.plainenglish.io/physical-computing-with-javascript-8-8-connecting-to-internet-151ba3dfce59にある例題
kalumaはfirwareこわれやすいのでkaluma flash ./index.js --bundle で止まる時は入れ直す
node app.jsで頓死おこるならPC再起動
--------nodejs-------app.js---------
const express = require('express');
const ip = require('ip');
const app = express();
const addr=ip.address();
const port=3001;
const html = `
<html>
<head></head>
<body>
<h1>{{t}}</h1>
<h1>{{h}}</h1>
</body>
</html>
`
let temperature='0.0'
let humidity='0';
app.get('/update',(req,res) => {
temperature = req.query.t
humidity = req.query.h
res.status(200).send('OK')
})
app.get('/',(req,res) => {
res.setHeader('content-type','text/html');
res.send(html
.replace('{{t}}',temperature)
.replace('{{h}}',humidity))
})
app.listen(port,()=> {
console.log(`app listen at htpp://${addr}:${port}`)
})
-----kalumajs--index.js--
const { DHT } = require('dht');
const { ESP8266HTTPClient } = require('esp8266-http-client');
// 設定
const WIFI_SSID = 'Buffalo-2G-8340';
const WIFI_PASSWORD = '636nsa535ds3v';
const ADDRESS = '192.168.11.8';
const PORT = '3001';
// DHT11
const dht = new DHT(15, DHT.DHT11);
// ESP8266
const esp = new ESP8266HTTPClient();
function start() {
setInterval(() => {
try {
dht.read();
let t = dht.temperature.toFixed(1);
let h = dht.humidity.toFixed(0);
console.log(`TEMP=${t} HUM=${h}`);
const url =
`http://${ADDRESS}:${PORT}/update?t=${t}&h=${h}`;
console.log(url);
esp.http(url)
.then(res => {
console.log('send ok');
})
.catch(err => {
console.log('http error');
console.log(err);
});
} catch(err) {
console.log('dht error');
console.log(err);
}
}, 10000);
}
// WiFi接続
esp.wifi(WIFI_SSID, WIFI_PASSWORD)
.then(() => {
console.log('wifi connected');
start();
})
.catch(err => {
console.log('wifi connect failed');
console.log(err);
});