I have a perfectly working script. Basically, I am polling an API every 5 seconds for myJson.Temperature and a MIDI note is played corresponding to the returned value. The values are between 0 and 16. Here is the script:
let easymidi = require("easymidi")
let output = new easymidi.Output("mindiPort", true)
let interval;
const fetch = require("node-fetch");
let sendNote = (noteValue, duration) => {
output.send("noteon", noteValue)
setTimeout(()=> {
output.send("noteoff", noteValue)
}, duration);
}
const api_url = 'https://www.placeholder_url.com?timeout=1000'
setInterval(() =>
fetch(api_url)
.then((response) => {
return response.json();
})
.then((myJson) => {
let note;
if (myJson.temperature == 0) {
note = 24;
} else if (myJson.temperature == 2) {
note = 25;
} else if (myJson.temperature == 4) {
note = 26;
} else if (myJson.temperature == 6) {
note = 27;
} else if (myJson.temperature == 8) {
note = 28;
} else if (myJson.temperature == 10) {
note = 29;
} else if (myJson.temparature == 12) {
note = 30;
} else if (myJson.temperature == 14) {
note = 31;
} else {
note = 32;
}
let noteValue = {
note: note,
velocity: 100,
channel: 1
}
sendNote(noteValue, 500)
}), 5000); // API call every 5 seconds **This will also play a (same) note every five seconds
// if conditions are met**
How do can I get the note to only play once ie; - if a subsequent poll is done and returns the same value, that note can be ignored until a unique value is returned? I have looked at filter and onlyUnique but I am not sure how to incorporate them into the code. Thank You in advance.
I would go for a simple approach and keep track of last emited note:
EDIT: my code was wrong because it was checking against complex objects equality, fixed it
let easymidi = require("easymidi")
let output = new easymidi.Output("mindiPort", true)
let interval;
const fetch = require("node-fetch");
let lastNote = null;
let sendNote = (noteValue, duration) => {
output.send("noteon", noteValue)
setTimeout(()=> {
output.send("noteoff", noteValue)
}, duration);
}
const api_url = 'https://www.placeholder_url.com?timeout=1000'
setInterval(() =>
fetch(api_url)
.then((response) => {
return response.json();
})
.then((myJson) => {
let note;
if (myJson.temperature == 0) {
note = 24;
} else if (myJson.temperature == 2) {
note = 25;
} else if (myJson.temperature == 4) {
note = 26;
} else if (myJson.temperature == 6) {
note = 27;
} else if (myJson.temperature == 8) {
note = 28;
} else if (myJson.temperature == 10) {
note = 29;
} else if (myJson.temparature == 12) {
note = 30;
} else if (myJson.temperature == 14) {
note = 31;
} else {
note = 32;
}
if (lastNote !== note) {
let noteValue = {
note: note,
velocity: 100,
channel: 1
}
sendNote(noteValue, 500)
}
lastNote = note;
}), 5000); // API call every 5 seconds **This will also play a (same) note every five seconds
// if conditions are met**