diff --git a/src/app.coffee b/src/app.coffee index 890a938a..2b813346 100644 --- a/src/app.coffee +++ b/src/app.coffee @@ -58,3 +58,12 @@ knex('config').select('value').where(key: 'uuid').then ([uuid]) -> , 5 * 60 * 1000) # Every 5 mins supervisor.update() + updateIpAddr = -> + utils.findIpAddrs().then (ipAddrs) -> + application.updateDeviceInfo( + ip_address: ipAddrs.join(' ') + ) + console.log('Starting periodic check for IP addresses..') + setInterval(updateIpAddr, 5 * 60 * 1000) # Every 5 mins + updateIpAddr() + diff --git a/src/application.coffee b/src/application.coffee index ad3703d0..0ca55c05 100644 --- a/src/application.coffee +++ b/src/application.coffee @@ -222,3 +222,29 @@ exports.update = -> setTimeout(exports.update) # Set the updating as finished currentlyUpdating = 0 + +exports.updateDeviceInfo = (body) -> + Promise.all([ + knex('config').select('value').where(key: 'apiKey') + knex('config').select('value').where(key: 'uuid') + ]) + .spread ([{value: apiKey}], [{value: uuid}]) -> + resinAPI.get( + resource: 'device' + options: + filter: + uuid: uuid + customOptions: + apikey: apiKey + ) + .then (devices) -> + if devices.length is 0 + throw new Error('Could not find this device?!') + deviceID = devices[0].id + resinAPI.patch( + resource: 'device' + id: deviceID + body: body + customOptions: + apikey: apiKey + ) \ No newline at end of file diff --git a/src/utils.coffee b/src/utils.coffee index 74ed3a7a..0749512c 100644 --- a/src/utils.coffee +++ b/src/utils.coffee @@ -22,3 +22,27 @@ exports.mixpanelTrack = (event, properties={}) -> properties = _.assign(_.cloneDeep(properties), mixpanelProperties) mixpanelClient.track(event, properties) + +# Returns an array of the host's ip address(es) by parsing the host /proc/net/fib_trie +exports.findIpAddrs = -> + fs.readFileAsync('/mnt/fib_trie', 'utf8') + .then (fibtrie) -> + prevLine = '' + fibtrie.split('\n') + .map (line) -> + line = line.trim() + + # We only care about LOCAL routes (not UNICAST or BROADCAST) + if line.match(/LOCAL$/) + # Then we make sure the previous line was an ending branch (and hence contains an IP - 127.0.0.0 has BROADCAST and LOCAL entries) + if prevLine.match(/^\|--/) + # Then we remove the ending branch bit + maybeAddr = prevLine.replace(/^\|--/, '').trim() + # And ignore loopback/docker interfaces. + # TODO: Docker interface can technically be on another address range if 172.17 + if !maybeAddr.match(/^(127.0.0.1|172.17.)/) + ipAddr = maybeAddr + + prevLine = line + return ipAddr + .filter(Boolean)