Thanks to the Text-To_Speech engine, I can easily add a nice function to the MagicHat: the capability to say wisdom phrases while it's idling
The implementation will be based on a web service that provides quotes as a JSON document
I found a lot of alternatives on www.mashape.com and I selected the quotes service provided by quotbook.com
The URL to invoke to get a new quote has the following format
https://yusufnb-quotes-v1.p.mashape.com/widget/~{search}.jsonwhere {search} is the topic you are interested to get a quote about. To stay on the challenge topic, I will randomly search for the following topics
- rowling
- magician
- harry potter
The quote web service will be queried by theNodeJS application
function getQuote(topic) {
var http = require('http');
options = {
host: 'yusufnb-quotes-v1.p.mashape.com',
path: '/widget/~' + topic + '.json',
port: '1338',
headers: {
'X-Mashape-Key': '<your mashape key>',
'Accept': 'application/json"
} };
callback = function(response) {
r str = '';
response.on('data', function(chunk) {
str += chunk;
});
response.on('end', function() {
console.log(str);
var obj = JSON.parse(str);
var mp3url='http://tts-api.com/tts.mp3?q='+encodeURIComponent(obj.quote);
getMp3(mp3url, filename, function() {
exec('/usr/bin/madplay -A10 ' + filename);
});
});
}
req = http.request(options, callback);
req.end();
};
Since the Arduino side is aware whether the MagicHat is idling or not, the quote function will be triggered by Arduino itself by sending a new command
Serial1.println("QUOTE");This command will be parsed by the serial port's data handler
// quote topics
var topics = ['rowling', 'magician', 'harry_potter'];
// generate a random int value between low and high (including limits)
function randomInt (low, high) {
return Math.floor(Math.random() * (high - low) + low);
}
// serial port data handler
yunPort.on('data', function(data) {
//console.log('data ' + data);
_data = _data + data;
var eol = _data.indexOf("\r\n");
if (eol > 0)
{
_data = _data.substring(0, eol);
if (_data.substring(0,5) == "PLAY ")
{
console.log("Received command " + _data.substring(0,5)+","+_data.substring(5));
var text = _data.substring(5);
_data = "";
text = text.replace(/ /g, '_');
var filename = '/mnt/sda1/' + text + '.mp3';
console.log("Checking file " + filename);
if (fs.existsSync(filename))
{
console.log("Playing file " + filename);
exec('/usr/bin/madplay -A10 ' + filename);
}
else
{
var mp3url='http://tts-api.com/tts.mp3?q='+encodeURIComponent(text);
getMp3(mp3url, filename, function() {
exec('/usr/bin/madplay -A10 ' + filename);
});
}
}
else if (_data.substring(0,5) == "QUOTE")
{
getQuote(topics[randomInt(0,topics.length-1)]);
}
else
{
if (_ws)
_ws.send(_data);
_data = "";
}
}
});
Top Comments