forked from noelportugal/google-home-notifier
-
Notifications
You must be signed in to change notification settings - Fork 0
/
google-home-notifier.js
66 lines (61 loc) · 1.75 KB
/
google-home-notifier.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
var Client = require('castv2-client').Client;
var DefaultMediaReceiver = require('castv2-client').DefaultMediaReceiver;
var mdns = require('mdns');
var googletts = require('google-tts-api');
var browser = mdns.createBrowser(mdns.tcp('googlecast'));
var deviceAddress;
var device = function(name) {
device = name;
return this;
}
var notify = function(message, callback) {
if (!deviceAddress){
browser.start();
browser.on('serviceUp', function(service) {
console.log('Device "%s" at %s:%d', service.name, service.addresses[0], service.port);
if (service.name.includes(device.replace(' ', '-'))){
deviceAddress = service.addresses[0];
getSpeechUrl(message, deviceAddress, function(res) {
callback(res);
});
}
browser.stop();
});
}else {
getSpeechUrl(message, deviceAddress, function(res) {
callback(res);
});
}
}
var getSpeechUrl = function(text, host, callback) {
googletts(text, 'en', 1).then(function (url) {
onDeviceUp(host, url, function(res){
callback(res)
});
}).catch(function (err) {
console.error(err.stack);
});
}
var onDeviceUp = function(host, url, callback) {
var client = new Client();
client.connect(host, function() {
client.launch(DefaultMediaReceiver, function(err, player) {
var media = {
contentId: url,
contentType: 'audio/mp3',
streamType: 'BUFFERED', // or LIVE
};
player.load(media, { autoplay: true }, function(err, status) {
client.close();
callback('Device notified');
});
});
});
client.on('error', function(err) {
console.log('Error: %s', err.message);
client.close();
callback('error');
});
}
exports.device = device;
exports.notify = notify;