はじめに
ProtoOutスタジオの宿題の質問です。
やりたいこと
LINEbotに「#計測」とメッセージを送ると、超音波センサーで距離を測り、何ミリ離れているのかを通知させる。
実装
'use strict';
const express = require('express');
const line = require('@line/bot-sdk');
const axios = require('axios');
const PORT = process.env.PORT || 3001;
const Obniz = require('obniz');
const config = {
channelSecret: 'xxxx',
channelAccessToken: 'xxxx'
};
const app = express();
var distance = 0;
app.get('/', (req, res) => res.send('Hello LINE BOT!(GET)'));
app.post('/webhook', line.middleware(config), (req, res) => {
console.log(req.body.events);
Promise
.all(req.body.events.map(handleEvent)) //引数のすべてのpromiseを集約する
.then((result) => res.json(result));
});
const client = new line.Client(config); // LINEのclientを介してpushMessageなど処理する
function handleEvent(event) {
// textメッセージ以外は処理しない
if (event.type !== 'message' || event.message.type !== 'text') {
return Promise.resolve(null);
}
const message = event.message.text
if (message === '#計測') {
hcsr04mesure(event.source.userId);
return client.replyMessage(event.replyToken, {
type: 'text',
text: '計測中...'
});
}
}
// 測るとこ
const hcsr04mesure = async (userID) => {
// process.on('unhandledRejection', console.dir);
var obniz = new Obniz("xxxx-xxxx");
obniz.onconnect = async () => {
obniz.display.clear();
var hcsr04 = obniz.wired("HC-SR04", {gnd:0, echo:1, trigger:2, vcc:3});
distance = await hcsr04.measureWait();
obniz.display.print(distance); //ここのdistanceは最新
// 困り1
// pushMsg(userID, distance) //ここでpushMsg する場合にuserIDがスコープ外になる
}
// 困り2
pushMsg(userID, distance) //ここのdistanceは前回の値になっている
}
function pushMsg(userId, message) {
return client.pushMessage(userId, {
type: 'text',
text: message,
})
}
困り1
hcsr04mesureに引数としてuserIDを渡していますが、これをobniz.onconnect = async () => {} の中で利用する方法がわかりません。
obniz.onconnect = async (userID) => {} としても、userIDがobnizのデータで置きかわります。
困り2
obniz.onconnect = async () => {}の中の値の更新をどうやって待つのかがわからなかったです。
この状態のとき、測定してobnizのディスプレイに表示させてる値は最新の値ですが、
Lineにpushされる値は前回測定した値になります。