--------------以下は最初は動くがだんだんremote errorとなる。。。。----------------
kill -9 $(lsof -t -i:3000)でいちいちportを閉じるのが重要だった
//$ mkdir thermo-server
// $ cd thermo-server
//$ npm init -y
//$ npm install express ip --save
--------------node app.js------------------------
const express = require('express');
const ip = require('ip');
const app = express();
const addr = ip.address();
const port = 3000;
let temperature = '0.0';
let humidity = '0';
// ========================================
// データ受信エンドポイント
// ========================================
app.get('/update', (req, res) => {
if (req.query.t) temperature = req.query.t;
if (req.query.h) humidity = req.query.h;
console.log(`[受信] 温度: ${temperature} °C / 湿度: ${humidity} %`);
// 【対策】明示的に Connection: close ヘッダーを付与して接続を即時切断する
res.setHeader('Connection', 'close');
// 文字列を返してレスポンスを完了する
res.status(200).send('OK');
});
// ========================================
// 画面表示用エンドポイント
// ========================================
app.get('/', (req, res) => {
res.setHeader('Content-Type', 'text/html');
res.setHeader('Connection', 'close'); // こちらも念のため追加
res.send(`
<html>
<head>
<meta charset="utf-8">
<title>Pico W センサーデータ</title>
</head>
<body>
<h1>温度: ${temperature} °C</h1>
<h1>湿度: ${humidity} %</h1>
</body>
</html>
`);
});
// ========================================
// サーバー起動
// ========================================
app.listen(port, () => {
console.log(`Server running at http://${addr}:${port}`);
});
----------------kaluma shell------------------------
const { DHT } = require('dht');
const { WiFi } = require('wifi');
const http = require('http');
// ========================================
// Wi-Fi設定
// ========================================
const WIFI_SSID = 'Pikara2-91d8e4';
const WIFI_PASSWORD = '090e219cbdbf5';
// ========================================
// HTTPサーバー設定
// ========================================
const SERVER_ADDRESS = '192.168.0.11';
const SERVER_PORT = 3000;
// ========================================
// DHT11設定:GP15
// ========================================
const dht = new DHT(15, DHT.DHT11);
const wifi = new WiFi();
// ========================================
// 状態管理
// ========================================
let sending = false;
let timerStarted = false;
let requestTimer = null;
// ========================================
// リクエスト終了処理
// ========================================
function finishRequest(reason) {
if (!sending) {
return;
}
sending = false;
if (requestTimer !== null) {
clearTimeout(requestTimer);
requestTimer = null;
}
console.log('Request finished: ' + reason);
}
// ========================================
// センサー読み取り・HTTP送信
// ========================================
function sendSensorData() {
if (sending) {
console.log('Previous request is running. Skip.');
return;
}
sending = true;
try {
// DHT11読み取り
dht.read();
const temp = dht.temperature;
const hum = dht.humidity;
//const temp = 23;
//const hum = 56;
console.log('--------------------------');
console.log('Temperature: ' + temp + ' C');
console.log('Humidity: ' + hum + ' %');
// センサー値の検査
if (
!Number.isFinite(temp) ||
!Number.isFinite(hum) ||
temp < 0 ||
temp > 50 ||
hum < 0 ||
hum > 100
) {
console.log('Invalid DHT11 reading. Skip sending.');
finishRequest('invalid sensor data');
return;
}
const temperature = temp.toFixed(1);
const humidity = hum.toFixed(0);
const path =
'/update?t=' +
encodeURIComponent(temperature) +
'&h=' +
encodeURIComponent(humidity);
console.log(
'Request: http://' +
SERVER_ADDRESS + ':' +
SERVER_PORT + path
);
// endイベントが来ない場合の保護タイマー
requestTimer = setTimeout(function () {
console.log('HTTP response timeout');
finishRequest('timeout');
}, 5000);
// HTTP GET
const req = http.get({
host: SERVER_ADDRESS,
port: SERVER_PORT,
path: path,
headers: {
'Connection': 'close' // 【対策】サーバー側に即時切断を促す
}
}, function (res) {
console.log('HTTP response received');
console.log('HTTP status: ' + res.statusCode);
// 【対策】ストリームを明示的に流し、内部バッファの詰まりを防ぐ
res.resume();
// レスポンス本文の受信
res.on('data', function (chunk) {
console.log('Response data: ' + chunk.toString());
});
// レスポンスの正常終了
res.on('end', function () {
console.log('HTTP response end');
finishRequest('response end');
});
// レスポンスエラー
res.on('error', function (err) {
console.log('HTTP response error: ' + err);
finishRequest('response error');
});
});
// リクエストエラー
req.on('error', function (err) {
console.log('HTTP request error: ' + err);
finishRequest('request error');
});
// リクエスト送信
req.end();
console.log('req.end() called');
} catch (err) {
console.log('Sensor/HTTP error: ' + err);
finishRequest('exception');
}
}
// ========================================
// メイン処理
// ========================================
function main() {
console.log('Pico W DHT11 HTTP Client');
console.log('KalumaJS v1.2.1');
console.log('Connecting to Wi-Fi...');
wifi.connect({
ssid: WIFI_SSID,
password: WIFI_PASSWORD
}, function (err) {
if (err) {
console.log('Wi-Fi connection failed');
console.log(err);
return;
}
console.log('Wi-Fi connected');
if (timerStarted) {
return;
}
timerStarted = true;
// 初回送信
sendSensorData();
// 10秒ごとに送信
setInterval(function () {
sendSensorData();
}, 10000);
});
}
// ========================================
// プログラム開始
// ========================================
main();