Using Webscript with Cosm

You all know Cosm (and if you don’t, here is a book chapter with a good introduction and examples). On the previous blog post I have mentioned briefly Webscript, a cool and easy way of running custom scripts without worrying about hosting and deployment!

Cosm is great for hosting and visualizing data from sensors and is also features a triggering mechanism. Triggers can be configured for each sensor datastream and can activate a HTTP Post to some server or make a Tweet. This feature is quite useful for being alerted when e.g., a sensor value goes over some threshold, does not change for some time or your feed goes to ‘frozen’ status (which could mean your device might have some networking/power issues). However when you need something more than a tweet (like doing some processing with the datastream data, a better alerting mechanism, etc.) you need to have your own server deployed.

This is where Webscript comes! For this purpose I have created a simple Lua library for using with the Cosm API. The library is here and it can be used directly with Webscript. Currently the following functions are provided:

  • read_current(apikey,feed, datastream): Returns the current value of a given datastream id that belongs to a given feed id. You have to provide a valid Cosm API Key with reading permissions
  • read_24h(apikey, feed, datastream): Returns a JSON object containing the average, maximum and minimum datastream values for the past 24 hours, e.g. [18.275, 81.3, 4.2]. You have to provide a valid Cosm API Key with reading permissions
  • list_datastreams(apikey, feed): Returns the number of datastreams for a given feed id. e.g., {“datastreams”: [“datastream1, timeupdated,currentvalue”, “datastream2,timeupdated,currentvalue”], “size”: 2}
  • isAlive(apikey, feed): Returns the status of a feed (“live” or “frozen”)


And here is an example of a webscript that will text you each day with some statistics (average, maximum and minimum value) about a specific datastream:

local cosm = require('hdoukas/cosm_lua/cosm')
local lom = require 'lxp.lom'
local xpath = require 'xpath'

local twilio = require('twilio')


local status = cosm.isAlive("COSM READ ACCESS API KEY","64820")
local message
local stats = cosm.read_24h("COSM READ ACCESS API KEY","64820", "cpu_0")
if tostring(status) == "live" then
message = "Feed status: live datastream stats:{avg:"..stats[1]..", max:"..stats[2]..", min:"..stats[3].."}"

local response = twilio.sms(ACCOUNTSID, AUTHTOKEN, '+123456789', '+123456789',message)

return message

The script will just text you if you run it, keep in mind that you will have to setup a cron job to schedule a daily execution.

Leave a Reply

Your email address will not be published. Required fields are marked *