forked from yammmt/Sphero-Auto-Pilot
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.js
132 lines (120 loc) · 2.89 KB
/
main.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
// モジュールの読み込み
var sphero = require("sphero");
var config = require("./config");
var powerState = require("./powerState");
var keypressManager = require("./keypressManager");
var timer = require("./timer");
// Spheroの初期化
var orb = sphero(config.serialPort);
var myOrb_degree = config.defaultDegree; // 初期角度 (0-359 度表記)
var collision_num = 0;
var refreshId = -1;
var isNextCollision = false;
/**
* 曲がります。引数は曲がる角度。省略すると270°になります
*/
function changeDegree(deg) {
var _deg = (typeof deg === "undefined" ? 270 : deg);
console.log(_deg);
myOrb_degree = (myOrb_degree+_deg)%360;
};
/**
* 衝突時に呼び出されます
*/
function collision() {
if (isNextCollision) {
console.log("痛い!");
changeDegree();
setRefreshId();
} else {
console.log("スキップします");
}
orb.color(config.collisionColor);
roll();
countCollision();
setTimeout(function() {
orb.color(config.defaultColor);
}, 250);
isNextCollision = !isNextCollision;
}
/**
* 衝突した回数を記録し、一定回数衝突し、切断するかどうか判断します
* (Todo: 関数名英語おかしい?)
*/
function countCollision() {
collision_num++;
if(collision_num >= config.collisionLimit) {
disConnect();
}
}
/**
* Spheroとの切断の処理を行います。
*/
function disConnect() {
orb.color("firebrick");
orb.disconnect(function() {
console.log("end");
});
}
/**
* 一定時間collisionが呼び出されなかった時の処理を行います。
*/
function refresh() {
console.log("リフレッシュします");
orb.color(config.defaultColor);
changeDegree();
roll();
setRefreshId();
}
/**
* refreshを呼び出すsetTimeoutを設定します。
*/
function setRefreshId() {
if (refreshId !== -1) {
clearTimeout(refreshId);
}
refreshId = setTimeout(refresh, config.refreshTime);
}
/**
* Keypressを初期化します。
*/
function initKeyPress() {
keypressManager.init(keyPress);
}
/**
* Keypressされた時の処理です。
*/
function keyPress(ch, key) {
if (key.ctrl && key.name === "c") {
// Ctrl+Cで終了できるようにする
process.stdin.pause();
process.exit();
} else if (key.name === "g") {
// ゴール時の処理
var time = timer.getTime(false);
console.log("Goal Time: " + (time / 1000) + "秒");
disConnect();
}
}
/**
* 現在の角度で動かします
*/
function roll() {
orb.roll(config.speed, myOrb_degree);
}
/**
* 接続された時の処理を行います。
*/
function connect() {
console.log("つながりました");
orb.color(config.defaultColor);
orb.detectCollisions();
powerState().then(data => {
console.log("batteryState:", data.batteryState);
});
orb.on("collision", collision);
roll();
setRefreshId();
timer.start(true);
}
orb.connect(connect);