-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
122 lines (101 loc) · 2.37 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
// mqtt-stocks
const MQTT_TOPIC = 'hass/stock-price';
const URL = 'https://www.cnbc.com/quotes/?symbol=';
const attribs = [
'name',
'url',
'tickerSymbol',
'exchange',
'exchangeTimezone',
'price',
'priceChange',
'priceChangePercent',
'quoteTime',
'dataSource',
'priceCurrency',
];
require('dotenv').config();
var request = require('request-promise-native');
const cheerio = require('cheerio');
const mqtt = require('async-mqtt');
const client = mqtt.connect(process.env.MQTT || 'mqtt://localhost');
const tickers = process.env.TICKERS || 'SPY';
/**
* xxxx
*/
client.on('connect', getAndPostAll);
function getAndPostAll() {
console.log('Connected to MQTT');
let re = /,\s*/;
let promises = tickers.split(re).map(async ticker => {
console.log(`Getting ${ticker}`);
await getAndPost(ticker);
console.log(` [${ticker}] done getAndPost`);
});
// console.log(promises);
Promise.all(promises).then(async () => {
console.log('done');
await client.end();
process.exit();
});
}
async function getAndPost(stock) {
let url = URL + stock;
let topic = MQTT_TOPIC + '/' + stock;
try {
console.log(` [${stock}] request ${url}`);
let html = await request(url);
console.log(` [${stock}] parse data`);
let data = parseHtml(html);
console.log(` [${stock}] publish to ${topic}:`, JSON.stringify(data));
let resp = await client.publish(topic, JSON.stringify(data), {
retain: true,
});
console.log(` [${stock}] published`);
} catch (e) {
console.error(` [${stock}] error processing: `, e);
}
}
function parseHtml(html) {
let $ = cheerio.load(html);
let data = {};
attribs.forEach(attrib => {
data[attrib] = $(`#structured-data [itemprop="${attrib}"]`).attr('content');
});
return data;
}
/**
* Want to notify controller that garage is disconnected before shutting down
*/
function handleAppExit(options, err) {
if (err) {
console.error(err.stack);
}
if (options.cleanup) {
// client.publish('garage/connected', 'false')
}
if (options.exit) {
process.exit();
}
}
/**
* Handle the different ways an application can shutdown
*/
process.on(
'exit',
handleAppExit.bind(null, {
cleanup: true,
})
);
process.on(
'SIGINT',
handleAppExit.bind(null, {
exit: true,
})
);
process.on(
'uncaughtException',
handleAppExit.bind(null, {
exit: true,
})
);