Scriptable AS to feed Dashboard (Web API)

So you are thinking what could I do with AppleScript records or scriptable application.
You may ask could I take data from system A to system B… In event-driven application like
Node-Red (it use Node.js). To make this simple we need to first make sure we have the right format as input for Node-Red.

That format is JSON String.

  1. So we need to convert AppleScript record to JSONString. We will use ASObjC for that.
  2. In Node-Red we inject message every 5s
  3. The flow in Node-Red will convert JSON String to JSON Object.
  4. To visual the change we setup a dashboard of table in Node-Red.

We play tracks from Apple Music that will feed the dashboard with data every 5s.

Ps. This is a standard script to execute a handler function it doesn’t use any arguments.

If you wonder what this is… return “[”… “]” in handler is all about.
To make a array object of JSON Objects we need it for the table in the dashboard. If we only like to get the values from some keys in JSON we do not need it.

use framework "Foundation"
use scripting additions

on run argv
	set aList to {}
		set countItems to count items of argv
		repeat with i from 1 to countItems
			if countItems > 0 then
				copy item i of argv to end of aList
			end if
		end repeat
	end try
	-- the handler
	its makeJSONString(getTrackInfo())
end run

on getTrackInfo()
	tell application "Music"
		if player state is playing then
			set currentTrack to current track
			tell currentTrack
				{|Artist|:its artist, |Name|:its name, |Album|:its album, |Genre|:its genre, |Year|:its year}
			end tell
		end if
	end tell
end getTrackInfo

on makeJSONString(theRecord)
	set {theData, theError} to current application's NSJSONSerialization's dataWithJSONObject:theRecord options:0 |error|:(reference)
	if theData is missing value then error (theError's localizedDescription() as text)
	set theString to current application's NSString's alloc()'s initWithData:theData encoding:(current application's NSUTF8StringEncoding)
	return "[" & (theString as text) & "]"
end makeJSONString

Node-Red - flows

Dashboard (From Node-Red)