This repository has been archived by the owner on Mar 10, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
executable file
·376 lines (348 loc) · 9.78 KB
/
index.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
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
#!/usr/bin/env node
const fs = require('fs')
const wifi = require('node-wifi')
const puppeteer = require('puppeteer')
const sqlite3Wrapper = require('sqlite3-wrapper')
const sqlite3 = require('sqlite3').verbose()
const minimist = require('minimist')
const blessed = require('blessed')
const contrib = require('blessed-contrib')
const VERSION = require('./package.json').version
const OLD_DB_NAME = './database.sqlite'
const DB_NAME = './howsmywifi.sqlite'
let active_db_name = DB_NAME
// When the project was first release the sqlite db file name
// was generic and it was impossible to know what that file
// represented. The new name is better. But for the sake of
// legacy, only use the new name if the old name hasn't been
// used.
if (fs.existsSync(OLD_DB_NAME) && !fs.existsSync(DB_NAME)) {
active_db = OLD_DB_NAME
}
const initDb = () => {
const dbRaw = new sqlite3.Database(active_db_name)
dbRaw.serialize(function() {
dbRaw.run(`
CREATE TABLE IF NOT EXISTS measurements
(
id INTEGER PRIMARY KEY,
speed FLOAT NULL,
date DATETIME NOT NULL,
ssid TEXT NOT NULL
)
`)
})
dbRaw.close()
}
const currentSSID = () => {
wifi.init({
iface: null // network interface, choose a random wifi interface if set to null
})
return wifi.getCurrentConnections().then(wifi => wifi[0].ssid)
}
const fastCom = async options => {
const browser = await puppeteer.launch()
const page = await browser.newPage()
try {
await page.goto('http://fast.com', {
waitUntil: 'networkidle2'
})
await page.waitFor('#speed-progress-indicator.succeeded')
} catch (err) {
// console.log('ERROR CATCH!')
// console.error(err)
await browser.close()
return
// return Promise.reject(err)
}
const result = { speedValue: null } // assume we can't get it
const speedObj = await page.evaluate(() => {
const el = document.querySelector('#speed-value')
if (el) {
const unit = document.querySelector('#speed-units')
return { value: el.textContent, unit: unit.textContent }
}
return null
})
if (speedObj) {
let speed = parseFloat(speedObj.value)
if (speedObj.unit !== 'Mbps') {
speed = speed / 1024
}
result.speedValue = speed
}
if (options.screenshot) {
const date = new Date().toISOString().replace(/\//g, '.')
const fn = `screenshots/screenshot.${date}.png`
if (!fs.existsSync('screenshots')) {
fs.mkdirSync('screenshots')
}
await page.screenshot({ path: fn })
result.screenshot = fn
// console.log('Screenshot in', fn);
}
await browser.close()
return Promise.resolve(result)
}
const run = (db, options) => {
const log = options.log
initDb()
const t0 = new Date()
return currentSSID()
.then(ssid => {
log('SSID:', ssid)
const t1 = new Date()
return fastCom(options)
.then((result, error) => {
const t2 = new Date()
if (error) {
console.warn('WARNING:', error)
}
const speedValue = result ? result.speedValue : null
if (speedValue) {
log('speedValue', formatSpeed(result.speedValue))
if (options.screenshot) {
log('Screenshot', result.screenshot)
}
const took = (t2 - t1) / 1000
log('Took', took.toFixed(1) + 's', '\n')
}
return db.insert(
'measurements',
{ speed: speedValue, date: new Date(), ssid: ssid },
(error, id) => {
if (error) {
throw error
}
// console.log('Row inserted')
}
)
})
.catch(error => {
console.error(error)
return error
})
})
.catch(err => {
throw err
})
}
const formatSecondsAgo = secs => {
let n = secs,
u = 's'
if (secs > 3600) {
let hours = Math.floor(secs / 3600)
let minutes = Math.floor((secs % 3600) / 60)
return `-${hours}h${minutes}m`
} else if (secs > 60) {
let minutes = Math.floor(secs / 60)
return `-${minutes}m`
} else {
n = Math.ceil(secs)
}
return `-${n}${u}`
}
const formatSpeed = mbps => {
if (mbps < 1) {
return `${Math.floor(mbps / 1000)} Kbps`
} else if (mbps > 1000) {
return `${(mbps / 1000).toFixed(1)} Gbps`
} else {
return `${mbps.toFixed(1)} Mbps`
}
}
// https://rosettacode.org/wiki/Averages/Simple_moving_average#JavaScript
function simple_moving_averager(period) {
var nums = []
return function(num) {
nums.push(num)
if (nums.length > period) nums.splice(0, 1) // remove the first element of the array
var sum = 0
for (var i in nums) sum += nums[i]
var n = period
if (nums.length < period) n = nums.length
return sum / n
}
}
var sma3 = simple_moving_averager(3)
var sma5 = simple_moving_averager(5)
const runScreen = db => {
const getGraphData = graphOptions => {
const limit = graphOptions.limit || 10
return new Promise((resolve, reject) => {
db.select(
{ table: 'measurements', limit: limit, order: 'date desc' },
(err, measurements) => {
if (err) {
reject(err)
}
const data = {
// title: `SSID: ${ssid}`,
// https://github.com/yaronn/blessed-contrib/issues/133
title: 'Speed',
x: [],
y: [],
style: {
line: 'red'
}
}
const movingAverage = {
// https://github.com/yaronn/blessed-contrib/issues/133
// title: 'Moving Average',
title: 'Average',
x: [],
y: [],
style: {
line: 'yellow'
}
}
const now = new Date().getTime()
let maxY = 0
let maxID = 0
const speeds = []
measurements.forEach(measurement => {
if (!measurement.speed) {
// skip those with null
// XXX Do a WHERE clause in the query
return
}
speeds.push(measurement.speed)
if (!maxID) {
maxID = measurement.id
}
const secAgo = (now - measurement.date) / 1000
data.x.unshift(formatSecondsAgo(secAgo))
movingAverage.x.unshift(formatSecondsAgo(secAgo))
data.y.unshift(measurement.speed)
if (measurements.length >= limit) {
movingAverage.y.unshift(sma5(measurement.speed))
} else {
movingAverage.y.unshift(sma3(measurement.speed))
}
if (measurement.speed > maxY) {
maxY = measurement.speed
}
})
maxY *= 1.2 // extra padding
const datum = [data, movingAverage]
resolve({ datum, maxY, maxID })
}
)
})
}
const screen = blessed.screen()
const grid = new contrib.grid({ rows: 12, cols: 12, screen: screen })
const speedLine = grid.set(0, 6, 12, 6, contrib.line, {
style: {
line: 'red',
text: 'white',
baseline: 'black'
},
label: 'Speed in Mbps',
maxY: 10,
showLegend: true
})
const log = grid.set(0, 0, 12, 6, contrib.log, {
fg: 'green',
selectedFg: 'green',
label: 'Log'
})
let lastMaxID = null
setInterval(() => {
getGraphData({ limit: 30 }).then(graphData => {
const { maxY, datum, maxID } = graphData
if (!lastMaxID || maxID !== lastMaxID) {
// the values have actually changed!
speedLine.options.maxY = maxY
speedLine.setData(datum)
lastMaxID = maxID
}
})
screen.render()
}, 2000)
screen.key(['escape', 'q', 'C-c'], (ch, key) => {
process.exit(0)
})
// fixes https://github.com/yaronn/blessed-contrib/issues/10
screen.on('resize', function() {
speedLine.emit('attach')
log.emit('attach')
})
screen.render()
// leak this so it can be written to
return log
}
const args = process.argv.slice(2)
const argv = minimist(args, {
boolean: ['help', 'version', 'screenshots', 'loop', 'noloopgui'],
integer: ['sleepseconds'],
string: ['output', 'skip'],
default: {
sleepseconds: 30
},
alias: {
help: 'h',
version: 'v',
sleepseconds: 't',
loop: 'l',
screenshots: 'screenshot'
},
unknown: param => {
if (param.startsWith('-')) {
console.warn('Ignored unknown option: ' + param + '\n')
return false
}
}
})
if (argv['version']) {
console.log(VERSION)
process.exit(0)
}
if (argv['help']) {
console.log(
'Usage: index.js [opts]\n\n' +
'Available options:\n' +
' --loop or -l Run repeatedly (sleepseconds) and keep taking measurements.\n' +
' --sleepseconds or -t Number of seconds to wait between runs (default 300).\n' +
' --screenshots Save a screenshot for each measurement.\n' +
' --version or -v Print minimalcss version.\n' +
''
)
process.exit(0)
}
const options = {
screenshot: argv['screenshots'],
log: (...args) => {
console.log(...args)
}
}
const db = sqlite3Wrapper.open(active_db_name)
if (argv['report']) {
// todo
} else if (argv['loop']) {
if (!argv['noloopgui']) {
const log = runScreen(db)
log.log('Starting up...')
options.log = (...args) => {
log.log(args.join(' '))
}
}
const interval = argv['sleepseconds'] * 1000
// The reason for using setTimeout instead of setInterval is that we
// want to sleep AFTER the run() function has FINISHED.
const loop = () => {
run(db, options)
.then(() => {
setTimeout(loop, interval)
})
.catch(err => {
// throw err
console.log('Run failed. Better luck next time')
console.log(err.toString())
setTimeout(loop, interval)
})
}
loop()
} else {
run(db, options)
}