Skip to content
This repository has been archived by the owner on Feb 3, 2021. It is now read-only.

Commit

Permalink
feat(connect): use stable prot for builtin server
Browse files Browse the repository at this point in the history
  • Loading branch information
coderbyheart committed Jul 18, 2019
1 parent 81fa7fd commit 9175a81
Show file tree
Hide file tree
Showing 3 changed files with 19 additions and 1 deletion.
5 changes: 5 additions & 0 deletions scripts/connect.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,10 @@ import { uiServer } from './device/ui-server'
*/
const main = async (args: { deviceId: string }) => {
const clientId = args.deviceId
if (!clientId || !clientId.length) {
throw new Error('Must provide a device id!')
}
console.log(chalk.magenta('Fetching IoT endpoint address ...'))
const { endpointAddress } = await new Iot({
region: process.env.AWS_DEFAULT_REGION,
})
Expand Down Expand Up @@ -54,6 +58,7 @@ const main = async (args: { deviceId: string }) => {

connection.register(clientId, {}, async () => {
await uiServer({
deviceId: clientId,
onUpdate: update => {
console.log({ clientId, state: { state: { reported: update } } })
connection.update(clientId, { state: { reported: update } })
Expand Down
11 changes: 11 additions & 0 deletions scripts/device/portForDevice.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
/**
* Calculates a stable port number based on the device id
*/
export const portForDevice = ({ deviceId }: { deviceId: string }): number => {
let hash = 0
for (let i = 0; i < deviceId.length; i++) {
hash = (hash << 5) - hash + deviceId.charCodeAt(i)
hash |= 0 // Convert to 32bit integer
}
return 1024 + Math.round((hash / Math.pow(2, 31)) * (65535 - 1024))
}
4 changes: 3 additions & 1 deletion scripts/device/ui-server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,13 @@ import * as path from 'path'
import * as http from 'http'
import { promises as fs } from 'fs'
import chalk from 'chalk'
import { portForDevice } from './portForDevice'

export const uiServer = async (args: {
deviceId: string
onUpdate: (update: object) => void
}) => {
const port = 1024 + Math.round(Math.random() * (65535 - 1024))
const port = portForDevice({ deviceId: args.deviceId })
const uiPage = await fs.readFile(
path.resolve(process.cwd(), 'data', 'device-ui.html'),
'utf-8',
Expand Down

0 comments on commit 9175a81

Please sign in to comment.