Skip to content

Instantly share code, notes, and snippets.

@vimyum
Last active October 23, 2017 04:20
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save vimyum/d5469c14204132891a1adb595f7eb183 to your computer and use it in GitHub Desktop.
Save vimyum/d5469c14204132891a1adb595f7eb183 to your computer and use it in GitHub Desktop.
const express = require('express');
const app = express();
const axios = require('axios');
const successMsg = { status: 200, message: 'success' };
const POWER_ON = 100;
const POWER_OFF = 0;
const RETRY_NUM = 10;
// レポーターブロックで返す値
let isReady = false;
let isPush = false;
// 各MabeeeのPWMの値
const pwm_status = [0, 0];
// PWMに変更の有無があるかチェック
function checkPwm(id, newPwm) {
const isUpdated = (pwm_status[id - 1] != newPwm);
pwm_status[id - 1] = newPwm;
return isUpdated;
}
// Scratchによるポーリングへの応答
app.get('/poll', function (req, res) {
// レポーターブロックへ値を返す
res.send(`ready ${isReady}\npush ${isPush}`);
// 初期化
isPush = false;
});
// 電池をONにする
app.get('/start/:id', function (req, res) {
const mabeeeId = req.params.id;
// 既にONならば
if (!checkPwm(mabeeeId, POWER_ON)) {
res.json({status: 304, message:`no need to update.`});
return;
}
// MabeeeMacAppにリクエスト
axios.get(`http://localhost:11111/devices/${mabeeeId}/set?pwm_duty=100`).then(() => {
res.json(successMsg);
}).catch((error) => {
res.json({status: 400, message:`failed:${error}`});
});
});
// 電池をOFFにする
app.get('/stop/:id', function (req, res) {
const mabeeeId = req.params.id;
// 既にONならば
if (!checkPwm(mabeeeId, POWER_OFF)) {
res.json({status: 304, message:`no need to update.`});
return;
}
// MabeeeMacAppにリクエスト
axios.get(`http://localhost:11111/devices/${mabeeeId}/set?pwm_duty=0`).then(() => {
res.json(successMsg);
}).catch((error) => {
res.json({status: 400, message:`failed:${error}`});
});
});
app.get('/setSpeed/:id/:pwm', function (req, res) {
const mabeeeId = req.params.id;
const mabeeePwm = req.params.pwm;
// 既に同じ値ならば
if (!checkPwm(mabeeeId, mabeeePwm)) {
res.json({status: 304, message:`no need to update.`});
return;
}
// MabeeeMacAppにリクエスト
axios.get(`http://localhost:11111/devices/${mabeeeId}/set?pwm_duty=${mabeeePwm}`).then(() => {
res.json(successMsg);
}).catch((error) => {
res.json({status: 400, message:`failed:${error}`});
});
});
// IoTボタンから呼ばれる
app.get('/push', function (req, res) {
isPush = true;
res.json(successMsg);
});
// デバイスが認識されたか確認(認識した時もしないときも3秒ウェイト)
function checkDevice() {
return new Promise((resolve, reject) => {
axios.get('http://localhost:11111/devices').then((response) => {
if (response.data.devices.length) {
//検出
setTimeout(()=> resolve(response.data.devices), 3000);
} else {
console.log('Cannot find any Mabeee device.');
setTimeout(()=> reject(), 3000);
}
}).catch((error) => {
console.log('Failed to access MabeeeMacApp:' + error);
reject();
});
});
}
// 起動時の初期化処理
async function init() {
// スキャン開始
const startResult = await axios.get('http://localhost:11111/scan/start');
console.log('scan start result');
// デバイス確認 (認識できなかったばあいはRETRY_NUMだけ再実行)
const devices = await retryable(RETRY_NUM, checkDevice).catch(err => {
console.log('Gave up to find Mabeee devices.')
});
if (!devices) {
return;
}
console.log(`Find Mabeee devices: ${JSON.stringify(devices, null, ' ')}`);
// デバイスに接続 (デバイスのIDは1から振られる(1,2,..))
for (i in devices) {
await axios.get(`http://localhost:11111/devices/${parseInt(i) + 1}/connect`).catch((e) => {
console.log('failed to connect scan:' + e);
});
}
// Scan停止
await axios.get('http://localhost:11111/scan/stop').catch((e) => {
console.log('failed to stop scan:' + e);
});
// ポーリングへ応答する値を変更
isReady = true;
console.log('Ready.');
}
// リトライ処理は`http://tech.mti.co.jp/entry/2017/09/19/205854`を参考にしまた。
function retryable(retryCount, func) {
let promise = Promise.reject().catch(() => func());
for (let i = 0; i < retryCount; i++) {
promise = promise.catch(err => func());
}
return promise;
}
app.listen(12345);
init();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment