sailracer-signalk-plugin
Version:
stream/convert sailracer data to signalk
318 lines (303 loc) • 10.8 kB
JavaScript
var net = require('net')
//// globals
// currentParams contains associations between custom slot values (v*) and
// signalk paths (see comments below). Is updated by updateCustomSlots() for
// each message received from sailracer.
var currentParams = {}
module.exports = function (app) {
var plugin = {};
plugin.id = 'sailracer-signalk-plugin';
plugin.name = 'Sailracer SignalK Plugin';
plugin.description = 'Stream sailracer data to SignalK';
const client = new net.Socket()
plugin.start = function (options, restartPlugin) {
app.debug('Plugin started, connecting to sailracer on '+ options.host + '...')
// handle TCP connect/reconnect
var intervalConnect = false
function connect() {
console.log('Connecting to sailracer on ' + options.host + ':' + options.port)
client.connect({
port: 58170,
host: options.host
})
}
function launchIntervalConnect() {
if(false != intervalConnect) return
intervalConnect = setInterval(connect, 5000)
}
function clearIntervalConnect() {
if(false == intervalConnect) return
clearInterval(intervalConnect)
intervalConnect = false
}
client.on('close', launchIntervalConnect)
client.on('end', launchIntervalConnect)
connect()
// main loop
client.on('connect', () => {
clearIntervalConnect()
app.debug('connected to sailracer app on ', options.host)
client.write('CLIENT connected');
})
client.on('error', (err) => {
app.debug('Error connecting to sailracer')
launchIntervalConnect()
})
client.on('connect', function () { // wait for connection
app.debug('connected to data source');
let received = new MessageBuffer("\n")
client.on("data", data => {
received.push(data)
while (!received.isFinished()) {
const message = JSON.parse(received.handleData())
app.handleMessage(plugin.id, currentUpdate(message))
}
})
});
};
plugin.stop = function () {
// Here we put logic we need when the plugin stops
app.debug('Disconnecting from sailracer');
client.destroy()
app.debug('Plugin stopped');
};
plugin.schema = {
type: 'object',
required: ['host'],
properties: {
host: {
type: 'string',
title: 'Sailracer app IP address',
default: '10.10.10.100'
}
}
}
plugin.uiSchema = {
title: "Sailracer plugin",
type: "object",
required: ["host"],
properties: {
host: { type: "string", title: "Host", default: "10.10.10.100" }
}
}
return plugin;
};
//// Utils
// Scan message and return found keys/values
function currentUpdate(message) {
let payload = {}
payload.updates = []
payload.updates.values = []
let currentValues = []
// Sailracer "API" is coupled with 10 data slots on the app.
// Custom slots can be customized by the user in real time.
// _Only Data that are currently shown on the app, are present in the tcp stream._
//
// START DATA SLOTS
// Some data are shown only during the pre-start ("start" and "line" objs).
// If "hide" key in "start" and "line" objs is set to true,
// we do not pass the data to signalk:
if (message.start) {
if (!message.start.hide) {
currentValues.push({ "path": "navigation.racing.start", "value": true })
if (message.start.rv) {
currentValues.push({ "path": "navigation.racing.timeToBurn", "value": message.start.rv.toSeconds() })
}
if (message.start.cv == "↓") {
currentValues.push({ "path": "navigation.racing.holdStart", "value": true })
}
if (message.start.cv == "↑") {
currentValues.push({ "path": "navigation.racing.holdStart", "value": false })
}
if (message.start.lv) {
currentValues.push({ "path": "navigation.racing.timeToStart", "value": message.start.lv.toSeconds() })
}
}
else {
currentValues.push({ "path": "navigation.racing.start", "value": false })
}
if (message.line && message.line.tv && !message.line.hide) {
currentValues.push({ "path": "navigation.racing.distanceStartLine", "value": message.line.tv.toInt() })
}
}
//
// FIXED SLOTS
// Some data are always sent, regardless of user's UI customization
// polar efficiency:
if (message.e) {
if (val = message.e.match(/(\d+)/)) {
let ratio = val[1].toFloat() / 100
currentValues.push({ "path": "navigation.racing.polarEfficiency", "value": ratio })
}
}
// UNUSED FIXED SLOTS
// - "0", "1", "2", "3" arrays: unknown!
// - declination
// - version
// - stable
// - t (unix time in s)
//
// CUSTOM SLOTS
// The user has 10 available data slots
// For each slot we have the following keys/values (* is a number from 0 to 9)
// t* title
// u* unit
// v* value
// g* value with unit
//
// To assign the values, we lookup through t* keys and assign a number
// to each available key, matching a given title via regex.
// For each matching key, we call the "updateCustomSlots" function
// to get and format the actual values
//
// look for keys like t*
let titles = []
for (const [key, value] of Object.entries(message)) {
if (match = key.match(/t(\d)/)) {
// update customSlots and get data from titles
currentValues = currentValues.concat(updateCustomSlots(match[1], value))
}
}
// get data from available customSlots
currentValues = currentValues.concat(getCustomSlotsData(message))
payload.updates = [{ 'values': currentValues }]
// send data to signalk
return payload
}
// Update global currentParams hash and return matched values or [].
// Lookup for available custom params by regex'ing the sailracer slot title.
// Some titles contain values as well (!): they are regex'd and set in the
// related path key.
function updateCustomSlots(slotId, title) {
// 1h Wind avg. (N) 107°±9
if (matchResult = title.match(/1h Wind avg\.? \(N\) (\d+)°±(\d+)/)) {
currentParams['navigation.racing.windAverage1hShift'] = slotId
let windAvg1h_data = []
windAvg1h_data.push({"path": "navigation.racing.windAverage1hDirection", "value": matchResult[1].toRadians()})
windAvg1h_data.push({"path": "navigation.racing.windAverage1hShiftRange", "value": matchResult[2].toRadians()})
return windAvg1h_data
}
// Wind avg. (N) 104°±37
if (matchResult = title.match(/Wind avg\.? \(N\) (\d+)°±(\d+)/)) {
currentParams['navigation.racing.windAverage6mShift'] = slotId
let windAvg6m_data = []
windAvg6m_data.push({"path": "navigation.racing.windAverage6mDirection", "value": matchResult[1].toRadians()})
windAvg6m_data.push({ "path": "navigation.racing.windAverage6mShiftRange", "value": matchResult[2].toRadians() })
return windAvg6m_data
}
// VMG Mark
if (matchResult = title.match(/VMG Mark/)) {
currentParams['navigation.racing.VmgToMark'] = slotId
return []
}
// Turn instruction
if (matchResult = title.match(/Turn instruction/)) {
currentParams['navigation.racing.relativeBearingToMark'] = slotId
return []
}
// Layline -5.38 nm | Layline 33 m
if (matchResult = title.match(/Layline (\S+) ((?:nm|m))/)) {
currentParams['navigation.racing.layline.time'] = slotId
let laylineDistanceInMeters = 0;
if (matchResult[2] === "nm") {
laylineDistanceInMeters = matchResult[1].toFloat() * 1835
} else {
laylineDistanceInMeters = matchResult[1].toFloat()
}
return [{"path": "navigation.racing.layline.distance","value": laylineDistanceInMeters}]
}
// if nothing matched, delete customParams entry with value slotId
// (value is no more displayed on the app)
delete currentParams[Object.keys(currentParams).find(key => currentParams[key] === slotId)]
return []
}
// get data from message n* fields referenced in currentParams
function getCustomSlotsData(message) {
// temp array to store found values
customValues = []
if (val = message["n"+currentParams["navigation.racing.windAverage1hShift"]]) {
customValues.push({"path": "navigation.racing.windAverage1hShift", "value": val.toRadians()})
}
if (val = message["n"+currentParams["navigation.racing.windAverage6mShift"]]) {
customValues.push({"path": "navigation.racing.windAverage6mShift", "value": val.toRadians()})
}
if (val = message["n"+currentParams["navigation.racing.VmgToMark"]]) {
customValues.push({"path": "navigation.racing.VmgToMark", "value": val.toFloat()})
}
if (val = message["n"+currentParams["navigation.racing.layline.time"]]) {
customValues.push({"path": "navigation.racing.layline.time", "value": val.toSeconds() })
}
if (val = message["n" + currentParams["navigation.racing.relativeBearingToMark"]]) {
bearing = 0;
side = 0;
if (valueMatch = val.match(/(\S?)\s+(\d+)\s+(\S?)/)) {
if (valueMatch[2]) { bearing = valueMatch[2] }
if (valueMatch[1]) { side = 1 } // starboard
if (valueMatch[3]) { side = -1 } // port
}
customValues.push({"path": "navigation.racing.relativeBearingToMark", "value": bearing.toRadians() * side })
}
// return found values
return customValues
}
// Handle TCP stream message buffer
class MessageBuffer {
constructor(delimiter) {
this.delimiter = delimiter
this.buffer = ""
}
isFinished() {
if (
this.buffer.length === 0 ||
this.buffer.indexOf(this.delimiter) === -1
) {
return true
}
return false
}
push(data) {
this.buffer += data
}
getMessage() {
const delimiterIndex = this.buffer.indexOf(this.delimiter)
if (delimiterIndex !== -1) {
const message = this.buffer.slice(0, delimiterIndex)
this.buffer = this.buffer.replace(message + this.delimiter, "")
return message
}
return null
}
handleData() {
/**
* Try to accumulate the buffer with messages
*
* If the server isnt sending delimiters for some reason
* then nothing will ever come back for these requests
*/
const message = this.getMessage()
return message
}
}
// Convert strings to signalk units
String.prototype.toSeconds = function () {
if (!this) return null
var hms = this.split(':')
if (hms.length == 2) {
return (+hms[0]) * 60 + (+hms[1] || 0)
}
if (hms.length == 3) {
return (+hms[0]) * 60 * 60 + (+hms[1]) * 60 + (+hms[2] || 0)
}
}
String.prototype.toRadians = function () {
if (!this) return null;
return parseFloat(this) * Math.PI / 180;
}
String.prototype.toFloat = function () {
if (!this) return null;
return parseFloat(this)
}
String.prototype.toInt = function () {
if (!this) return null;
return parseInt(this)
}