fostrom 0.0.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/config.js +115 -0
- package/index.js +30 -0
- package/license.md +21 -0
- package/mqtt.js +130 -0
- package/package.json +29 -0
- package/readme.md +5 -0
package/config.js
ADDED
|
@@ -0,0 +1,115 @@
|
|
|
1
|
+
/* DEVICE CONFIG */
|
|
2
|
+
|
|
3
|
+
const id_regex = RegExp(/[^a-zA-Z0-9]/)
|
|
4
|
+
const device_secret_regex = RegExp(/FOS-[^a-zA-Z0-9]/)
|
|
5
|
+
|
|
6
|
+
/* Callbacks */
|
|
7
|
+
const on_connect = () => console.log('[Fostrom] Connected')
|
|
8
|
+
const on_disconnect = () => console.log('[Fostrom] Disconnected')
|
|
9
|
+
|
|
10
|
+
const on_error = error => console.error(
|
|
11
|
+
`\n[Fostrom] Error:\n ${error.message}\n\n Pass an \`on_error()\` callback in the config to handle errors.\n See https://docs.fostrom.io/libs/js for more info.`
|
|
12
|
+
)
|
|
13
|
+
|
|
14
|
+
const on_fatal_error = error => {
|
|
15
|
+
console.error(
|
|
16
|
+
`\n[Fostrom] Fatal Error:\n ${error.message}\n\n Exiting. The default \`on_fatal_error\` handler calls \`process.exit(1)\`.\n If you don't want the process to exit, pass an \`on_fatal_error()\` callback in the config.\n See https://docs.fostrom.io/libs/js for more info.`
|
|
17
|
+
)
|
|
18
|
+
|
|
19
|
+
process.exit(1)
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
const on_msg = async (id, msg, pl) => {
|
|
23
|
+
console.log(`[Fostrom] Received Message: ID-${id}: ${msg} with payload: ${JSON.stringify(pl)}`)
|
|
24
|
+
return true
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
/* Validation Functions */
|
|
28
|
+
|
|
29
|
+
function validate_fleet_id(fleet_id) {
|
|
30
|
+
if (!fleet_id) throw '[Fostrom] Fleet ID is required.'
|
|
31
|
+
if (fleet_id.length != 8) throw '[Fostrom] Fleet ID is invalid. Must be 8 characters long.'
|
|
32
|
+
if (id_regex.test(fleet_id)) throw '[Fostrom] Fleet ID is invalid. Must be alphanumeric.'
|
|
33
|
+
return fleet_id.toUpperCase()
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
function validate_device_id(device_id) {
|
|
37
|
+
if (!device_id) throw '[Fostrom] Device ID is required.'
|
|
38
|
+
if (device_id.length != 10) throw '[Fostrom] Device ID is invalid. Must be 10 characters long.'
|
|
39
|
+
if (id_regex.test(device_id)) throw '[Fostrom] Device ID is invalid. Must be alphanumeric.'
|
|
40
|
+
return device_id.toUpperCase()
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
function validate_device_secret(device_secret) {
|
|
44
|
+
if (!device_secret) throw '[Fostrom] Device Secret is required.'
|
|
45
|
+
|
|
46
|
+
if (device_secret.length != 36)
|
|
47
|
+
throw '[Fostrom] Device Secret is invalid. Must be 36 characters long and starts with `FOS-`.'
|
|
48
|
+
|
|
49
|
+
if (device_secret_regex.test(device_secret))
|
|
50
|
+
throw '[Fostrom] Device Secret is invalid. Must be 36 characters long and starts with `FOS-`.'
|
|
51
|
+
|
|
52
|
+
return device_secret.toUpperCase()
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
/* Default Config Functions */
|
|
56
|
+
|
|
57
|
+
function get_puback_timeout(puback_timeout) {
|
|
58
|
+
if (!puback_timeout) return 30
|
|
59
|
+
if (puback_timeout > 60) return 60
|
|
60
|
+
if (puback_timeout < 10) return 10
|
|
61
|
+
if (!Number.isInteger(puback_timeout)) return 30
|
|
62
|
+
return puback_timeout
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
function get_transport(transport) {
|
|
66
|
+
if (!transport) return 'both'
|
|
67
|
+
if (transport == 'tcp') return 'tcp'
|
|
68
|
+
if (transport == 'ws') return 'ws'
|
|
69
|
+
return 'both'
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
function get_callbacks(config) {
|
|
73
|
+
return {
|
|
74
|
+
connected: config.on_connect || on_connect,
|
|
75
|
+
disconnected: config.on_disconnect || on_disconnect,
|
|
76
|
+
handle_error: config.on_error || on_error,
|
|
77
|
+
fatal_error: config.on_fatal_error || on_fatal_error,
|
|
78
|
+
handle_msg: config.on_msg || on_msg
|
|
79
|
+
}
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
function get_connect_urls(config) {
|
|
83
|
+
const fleet_id = config.fleet_id
|
|
84
|
+
let tcp_url = `mqtts://${fleet_id.toLowerCase()}.fleets.fostrom.dev:8883`
|
|
85
|
+
let ws_url = `wss://${fleet_id.toLowerCase()}.fleets.fostrom.dev/v1/mqtt`
|
|
86
|
+
let host = '127.0.0.1'
|
|
87
|
+
|
|
88
|
+
if (!!process.env.FOS_DEV_MODE) {
|
|
89
|
+
host = !!process.env.CONNECT_HOST ? process.env.CONNECT_HOST : '127.0.0.1'
|
|
90
|
+
tcp_url = `mqtt://${host}:8883`
|
|
91
|
+
ws_url = `ws://${host}:9999/v1/mqtt`
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
return { tcp_url, ws_url }
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
/* Exported Function */
|
|
98
|
+
|
|
99
|
+
export function get_config(config) {
|
|
100
|
+
const { tcp_url, ws_url } = get_connect_urls(config)
|
|
101
|
+
|
|
102
|
+
return {
|
|
103
|
+
fleet_id: validate_fleet_id(config.fleet_id),
|
|
104
|
+
device_id: validate_device_id(config.device_id),
|
|
105
|
+
device_secret: validate_device_secret(config.device_secret),
|
|
106
|
+
keep_alive: !!config.keep_alive || true,
|
|
107
|
+
fetch_msgs: !!config.fetch_msgs || true,
|
|
108
|
+
require_puback: !!config.require_puback || true,
|
|
109
|
+
puback_timeout: get_puback_timeout(config.puback_timeout),
|
|
110
|
+
transport: get_transport(config.transport),
|
|
111
|
+
callbacks: get_callbacks(config),
|
|
112
|
+
tcp_url: tcp_url,
|
|
113
|
+
ws_url: ws_url
|
|
114
|
+
}
|
|
115
|
+
}
|
package/index.js
ADDED
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
import { pack } from 'msgpackr'
|
|
2
|
+
import { get_config } from './config.js'
|
|
3
|
+
import { start } from './mqtt.js'
|
|
4
|
+
|
|
5
|
+
class Fostrom {
|
|
6
|
+
constructor(config) {
|
|
7
|
+
this.config = get_config(config)
|
|
8
|
+
this.reconnect = true
|
|
9
|
+
}
|
|
10
|
+
|
|
11
|
+
async connect() {
|
|
12
|
+
this.client = await start(this, this.config)
|
|
13
|
+
return true
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
async close() {
|
|
17
|
+
this.reconnect = false
|
|
18
|
+
await this.client.endAsync()
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
async send_data(data) {
|
|
22
|
+
await this.client.publishAsync('d', pack(data), { qos: 1 })
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
async send_msg(msg, payload) {
|
|
26
|
+
await this.client.publishAsync('m', pack([msg, payload]), { qos: 1 })
|
|
27
|
+
}
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
export default Fostrom
|
package/license.md
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2024 HeadOn Labs LLP
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/mqtt.js
ADDED
|
@@ -0,0 +1,130 @@
|
|
|
1
|
+
import mqtt from 'mqtt'
|
|
2
|
+
import { unpack, pack } from 'msgpackr'
|
|
3
|
+
|
|
4
|
+
const invalid_device_creds_error = new Error(
|
|
5
|
+
'Invalid Device Credentials. Please re-check the device credentials.'
|
|
6
|
+
)
|
|
7
|
+
|
|
8
|
+
const network_error_msg = `[Fostrom] Failed to connect to Fostrom. Retrying in ${Math.round(retry_interval / 1000)} seconds...`
|
|
9
|
+
|
|
10
|
+
function sleep(ms) {
|
|
11
|
+
return new Promise(resolve => setTimeout(resolve, ms))
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
function get_mqtt_opts(config) {
|
|
15
|
+
return {
|
|
16
|
+
username: `${config.fleet_id}::${config.device_id}`,
|
|
17
|
+
password: config.device_secret,
|
|
18
|
+
clientId: 'MSGPACK',
|
|
19
|
+
keepalive: config.keep_alive == true ? 30 : 0,
|
|
20
|
+
reconnectPeriod: 0,
|
|
21
|
+
rejectUnauthorized: false
|
|
22
|
+
}
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
function backoff(interval) {
|
|
26
|
+
if (interval < 3000) { return 3000 }
|
|
27
|
+
if (interval == 3000) { return 5000 }
|
|
28
|
+
if (interval == 5000) { return 10000 }
|
|
29
|
+
if (interval == 10000) { return 15000 }
|
|
30
|
+
if (interval == 15000) { return 30000 }
|
|
31
|
+
return 30000
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
async function try_single_connect(config) {
|
|
35
|
+
try {
|
|
36
|
+
const url = config.transport == 'ws' ? config.ws_url : config.tcp_url
|
|
37
|
+
let client = await mqtt.connectAsync(url, get_mqtt_opts(config))
|
|
38
|
+
return client
|
|
39
|
+
} catch (e) {
|
|
40
|
+
return e.code == 5 ? 'unauthorized' : 'network_error'
|
|
41
|
+
}
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
async function try_fallback_connect(config) {
|
|
45
|
+
try {
|
|
46
|
+
let client = await mqtt.connectAsync(config.tcp_url, get_mqtt_opts(config))
|
|
47
|
+
return client
|
|
48
|
+
} catch (e) {
|
|
49
|
+
if (e.code == 5) {
|
|
50
|
+
return 'unauthorized'
|
|
51
|
+
} else {
|
|
52
|
+
await sleep(100)
|
|
53
|
+
|
|
54
|
+
try {
|
|
55
|
+
let client = await mqtt.connectAsync(config.ws_url, get_mqtt_opts(config))
|
|
56
|
+
return client
|
|
57
|
+
} catch (e) {
|
|
58
|
+
return e.code == 5 ? 'unauthorized' : 'network_error'
|
|
59
|
+
}
|
|
60
|
+
}
|
|
61
|
+
}
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
async function connect(config, retry_count = 0, retry_interval = 3000) {
|
|
65
|
+
const client_or_error = await config.transport == 'both' ?
|
|
66
|
+
try_fallback_connect(config) : try_single_connect(config)
|
|
67
|
+
|
|
68
|
+
if (client_or_error == 'unauthorized') {
|
|
69
|
+
config.callbacks.fatal_error(invalid_device_creds_error)
|
|
70
|
+
} else if (client_or_error == 'network_error') {
|
|
71
|
+
console.error(network_error_msg)
|
|
72
|
+
await sleep(retry_interval)
|
|
73
|
+
retry_count = retry_count + 1
|
|
74
|
+
retry_interval = retry_count <= 3 ? retry_interval : backoff(retry_interval)
|
|
75
|
+
return await connect(config, retry_count, retry_interval)
|
|
76
|
+
} else {
|
|
77
|
+
const client = client_or_error
|
|
78
|
+
return client
|
|
79
|
+
}
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
async function subscribe(config, client) {
|
|
83
|
+
if (config.fetch_msgs == true) {
|
|
84
|
+
try {
|
|
85
|
+
await client.subscribeAsync('m', { qos: 1 })
|
|
86
|
+
return true
|
|
87
|
+
} catch (e) {
|
|
88
|
+
let failed = new Error('Failed to subscribe to messages.')
|
|
89
|
+
failed.code = 2
|
|
90
|
+
config.callbacks.handle_error(failed)
|
|
91
|
+
return false
|
|
92
|
+
}
|
|
93
|
+
} else { return true }
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
function attachHooks(instance, config, client) {
|
|
97
|
+
client.on('close', async () => {
|
|
98
|
+
config.callbacks.disconnected()
|
|
99
|
+
|
|
100
|
+
if (instance.reconnect) {
|
|
101
|
+
console.error('[Fostrom] Disconnected. Reconnecting...')
|
|
102
|
+
await sleep(500)
|
|
103
|
+
instance.client = await start(instance, config)
|
|
104
|
+
}
|
|
105
|
+
})
|
|
106
|
+
|
|
107
|
+
client.on('message', async (_topic, message) => {
|
|
108
|
+
message = unpack(message)
|
|
109
|
+
const [id, msg, pl] = message
|
|
110
|
+
|
|
111
|
+
if (msg.startsWith('fos:') || msg.startsWith('fostrom:')) {
|
|
112
|
+
// Fostrom Internal Control Message
|
|
113
|
+
} else {
|
|
114
|
+
const ok = await config.callbacks.handle_msg(id, msg, pl)
|
|
115
|
+
|
|
116
|
+
if (ok !== false) {
|
|
117
|
+
await client.publishAsync('a', pack([id]), { qos: 1 })
|
|
118
|
+
} else {
|
|
119
|
+
// The message is not to be removed from the mailbox yet.
|
|
120
|
+
}
|
|
121
|
+
}
|
|
122
|
+
})
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
export async function start(instance, config) {
|
|
126
|
+
let client = await connect(config)
|
|
127
|
+
attachHooks(instance, config, client)
|
|
128
|
+
if (await subscribe(config, client)) { config.callbacks.connected() }
|
|
129
|
+
return client
|
|
130
|
+
}
|
package/package.json
ADDED
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "fostrom",
|
|
3
|
+
"version": "0.0.1",
|
|
4
|
+
"description": "Fostrom's Official Device SDK for JS. Fostrom is an IoT Cloud Platform. Check it out on fostrom.io",
|
|
5
|
+
"keywords": [
|
|
6
|
+
"fostrom",
|
|
7
|
+
"device",
|
|
8
|
+
"sdk",
|
|
9
|
+
"iot",
|
|
10
|
+
"cloud",
|
|
11
|
+
"fleet",
|
|
12
|
+
"mqtt",
|
|
13
|
+
"websockets"
|
|
14
|
+
],
|
|
15
|
+
"homepage": "https://docs.fostrom.io/libs/js",
|
|
16
|
+
"license": "MIT",
|
|
17
|
+
"author": "Fostrom <support@fostrom.io> (https://fostrom.io)",
|
|
18
|
+
"main": "index.js",
|
|
19
|
+
"type": "module",
|
|
20
|
+
"files": [
|
|
21
|
+
"index.js",
|
|
22
|
+
"mqtt.js",
|
|
23
|
+
"config.js"
|
|
24
|
+
],
|
|
25
|
+
"dependencies": {
|
|
26
|
+
"mqtt": "^5.5.0",
|
|
27
|
+
"msgpackr": "^1.10.1"
|
|
28
|
+
}
|
|
29
|
+
}
|