Skip to content

Instantly share code, notes, and snippets.

@mkody
Created July 13, 2016 11:16
Show Gist options
  • Save mkody/655df7c48c917d89130ceee34201f9eb to your computer and use it in GitHub Desktop.
Save mkody/655df7c48c917d89130ceee34201f9eb to your computer and use it in GitHub Desktop.
Display last X content you sent to thingspeak
<script>
// === Configure the variables here ===
// our channel id
var channel_id = 134049
// how many entries to load
var entries_count = 5
// api key (read)
var api_key = 'TNKUVEP15UGJ8HIK'
// select date locale ('en' or 'fr-ch')
var date_locale = 'fr-ch'
</script>
<!-- Just to make things pretty -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.14.1/moment.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.14.1/locale/fr-ch.js"></script>
<!-- Utilities -->
<script>
// Why use jquery?
function getJSON(path, callback) {
var httpRequest = new XMLHttpRequest()
httpRequest.onreadystatechange = function() {
if (httpRequest.readyState === 4) {
if (httpRequest.status === 200) {
var data = JSON.parse(httpRequest.responseText)
if (callback) callback(data)
}
}
}
httpRequest.open('GET', path)
httpRequest.send();
}
// And who doesn't like to use .format?
String.prototype.format = function (o) {
return this.replace(/{([^{}]*)}/g,
function (a, b) {
var r = o[b]
return typeof r === 'string' ? r : a
}
)
}
</script>
<!-- Our code -->
<script>
// Change our locale
moment.locale(date_locale)
// Get the thing
getJSON('https://api.thingspeak.com/channels/' + channel_id + '/feeds.json?results=' + entries_count + '&api_key=' + api_key, function (data) {
data.feeds.forEach(function (entry) {
// Format the date
nice_date = moment(entry.created_at, 'YYYY-MM-DDTHH:mm:ssZ').format('L LTS') // DD/MM/YYY HH:mm:ss
// Template to display
template = '<span title="{0}">[{1}]</span> {2}<br>'
// Array of values for template
variables = [entry.created_at, nice_date, entry.field1]
// Format the template and write the log
document.write(template.format(variables))
})
})
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment