センサの値をAPIとして公開する
エンドポイントができたので,もう一歩先に進んで,部屋の室温をapi化してみましょう
アナログ温度センサLM35をこのようにつなげます
このようなデータを返すAPIを作ります
{
"status" : "success",
"temperature" : 25.3
}
もし,obnizがつながっていなかった場合はこう返します
{
"status" : "failed",
"error" : "Cannot connect to obniz."
}
それではコードを書いてみましょう
// Runkit Endpoint Example
const Obniz = require("obniz");
const express = require("@runkit/runkit/express-endpoint/1.0.0");
const app = express(exports);
const yourObnizId = "OBNIZ\_ID\_HERE"; // write your obniz id
app.get("/", async (req, res) => {
let obniz = new Obniz(yourObnizId);
let connected = await obniz.connectWait({timeout:10});
if(connected){
let tempSensor = obniz.wired('LM35', { gnd: 0, output: 1, vcc: 2 });
await obniz.wait(100); //wait for stabilizing
let temp = await tempSensor.getWait();
obniz.close();
req.json({ status: "success", temprature : temp});
}else{
req.json({ status: "failed", error : "Caonnot connect to obniz."});
}
});
実行し、URLにアクセスしてみましょう。温度が計測され、レスポンスが返されると思います。