Skip to content

Commit

Permalink
Add config routes in server
Browse files Browse the repository at this point in the history
  • Loading branch information
alexwohlbruck committed May 1, 2022
1 parent 6dac68c commit 280eb0a
Show file tree
Hide file tree
Showing 7 changed files with 202 additions and 4,429 deletions.
12 changes: 6 additions & 6 deletions docs/websockets.md
Original file line number Diff line number Diff line change
Expand Up @@ -14,8 +14,8 @@ Payload:
}
```

### `SETTINGS`
Sends the config file to the server. This is called after the server sends `REQUEST_SETTINGS`.
### `CONFIG`
Sends the config file to the server. This is called after the server sends `REQUEST_CONFIG`.
```json
{
"deviceId": "xxxxxxxxxxxxxxxxxxxxxxxx",
Expand All @@ -29,7 +29,7 @@ Sends the config file to the server. This is called after the server sends `REQU
"brightness": 0.9,
"nightMode": true,
"minimumLightLevel": 0.2,
"readingLight_colorTemperature": 2700
"readingLightColorTemperature": 2700
}
```

Expand Down Expand Up @@ -59,8 +59,8 @@ Payload:
}
```

### 鈿涳笍馃捇 `UPDATE_SETTINGS`
Updates settings in the config file (config.json). Only the settings below are allowed to be updated.
### 鈿涳笍馃捇 `UPDATE_CONFIG`
Updates fields in the config file (config.json). Only the fields below are allowed to be updated.

Payload:
```json
Expand All @@ -72,7 +72,7 @@ Payload:
}
```

### 鈿涳笍馃捇 `REQUEST_SETTINGS`
### 鈿涳笍馃捇 `REQUEST_CONFIG`
Requests the board to send it's config file (config.json).

Payload:
Expand Down
36 changes: 33 additions & 3 deletions micro/app/server.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
import json
from time import sleep_ms
import app.uwebsockets.client as wsclient
from app.config import get_device_id, get_config_item
from app.config import get_device_id, get_config_item, load_config
from app.wifi import disconnect_wifi

MAX_RECONNECT_ATTEMPTS = 5
Expand Down Expand Up @@ -81,6 +81,12 @@ def on_message(self, message):
name = message.get('name')
data = message.get('data')

if name == 'REQUEST_CONFIG':
self.send_config()

if name == 'UPDATE_CONFIG':
self.update_config(data)

for callback in self.callbacks:
callback(name, data)

Expand All @@ -89,8 +95,6 @@ def subscribe(self, cb):
self.callbacks.append(cb)

def send_lamp_command(self, color, touching):

# TODO: Auto resolve lamp id
self.ws.send({
'name': 'SEND_LAMP_COMMAND',
'data': {
Expand All @@ -101,6 +105,32 @@ def send_lamp_command(self, color, touching):
}
}
})

def send_config(self):
config = load_config()
self.ws.send({
'name': 'CONFIG',
'data': config
})

def update_config(self, config):
brightness = config.get('brightness', None)
night_mode = config.get('nightMode', None)
minimum_light_level = config.get('minimumLightLevel', None)
reading_light_color_temperature = config.get('readingLightColorTemperature', None)

if brightness is not None:
add_config('brightness', brightness)

if night_mode is not None:
add_config('nightMode', night_mode)

if minimum_light_level is not None:
add_config('minimumLightLevel', minimum_light_level)

if reading_light_color_temperature is not None:
add_config('readingLightColorTemperature', reading_light_color_temperature)


def start_server():
try:
Expand Down
2 changes: 2 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -34,9 +34,11 @@
"express-session": "^1.17.2",
"express-ws": "^5.0.2",
"google-auth-library": "^7.14.0",
"mitt": "^3.0.0",
"mongoose": "^6.2.4",
"mongoose-autopopulate": "^0.16.0",
"mongoose-findorcreate": "^3.0.0",
"p-event": "^5.0.1",
"passport": "^0.5.2",
"passport-google-id-token": "^0.4.7",
"path": "^0.12.7",
Expand Down
25 changes: 23 additions & 2 deletions server/routes/lamps.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,16 @@
import express from 'express'
import { User } from '../models/user'
import { getLamps, getLamp, createLamp, moveLampToGroup, sendCommand, deleteLamp, renameLamp } from '../services/lamps'
import {
getLamps,
getLamp,
getLampConfig,
updateLampConfig,
createLamp,
moveLampToGroup,
sendCommand,
deleteLamp,
renameLamp,
} from '../services/lamps'
import { isAuthenticated } from '../middleware'

const router = express.Router()
Expand Down Expand Up @@ -37,6 +47,17 @@ router.post('/', isAuthenticated, async (req, res) => {
return res.status(200).json(lamp)
})

router.get('/:id/config', isAuthenticated, async (req, res) => {
const config = await getLampConfig(req.params.id)
return res.status(200).json(config)
})

router.patch('/:id/config', isAuthenticated, async (req, res) => {
// TODO: Wait for successful response using pEvent
updateLampConfig(req.params.id, req.body)
res.status(200).json({})
})

// Move a lamp to another group
router.put('/:id/group', isAuthenticated, async (req, res) => {
const { groupId, accessCode } = req.body
Expand All @@ -50,7 +71,7 @@ router.put('/:id/group', isAuthenticated, async (req, res) => {
return res.status(200).json(lamp)
})

router.put('/:id/name', isAuthenticated, async(req, res) => {
router.put('/:id/name', isAuthenticated, async (req, res) => {
const { name } = req.body

const lamp = await renameLamp(
Expand Down
29 changes: 25 additions & 4 deletions server/services/lamps.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,8 @@ import { toKebab } from '../helpers'
import { LampModel, LampState } from '../models/lamp'
import { GroupModel } from '../models/group'
import { updateGroupState } from './groups'
import { broadcast, broadcastToDevices, broadcastToUsers, WSPayload } from '../websockets'
import { broadcast, broadcastToDevices, broadcastToUsers, WSPayload, eventEmiter } from '../websockets'
import { pEvent } from 'p-event'

// Send a message to all the members of a group with the given lamp ID
const broadcastToGroup = async (groupId: string, payload: WSPayload) => {
Expand Down Expand Up @@ -108,16 +109,13 @@ export const createLamp = async (
// Get populated lamp
const res = await LampModel.findById(lamp._id)

console.log('created')
if (groupExists) {
console.log('group exists', res.group._id)
broadcastToGroup(res.group._id, {
name: 'ADD_LAMP',
data: res
})
}
else {
console.log('group does not exist', [userId])
broadcastToUsers([userId], {
name: 'ADD_LAMP',
data: res,
Expand All @@ -127,6 +125,29 @@ export const createLamp = async (
return res
}

export const getLampConfig = async (id: string) => {
broadcastToDevices([id], {
name: 'REQUEST_CONFIG',
data: {},
})
// Wait for data from CONFIG event, timeout after 10 seconds
return await pEvent(eventEmiter, 'CONFIG', { timeout: 10 * 1000 })
}

type LampConfig = {
brightness?: number
nightMode?: boolean
minimumLightLevel?: number
readingLightColorTemperature?: number
}
export const updateLampConfig = async (id: string, config: LampConfig) => {
// TODO: Wait for successful response using pEvent
broadcastToDevices([id], {
name: 'UPDATE_CONFIG',
data: config,
})
}

export const moveLampToGroup = async (id: string, groupId: string, accessCode: string) => {

if (!id) throw new RequestException(400, 'Lamp ID is required.')
Expand Down
10 changes: 9 additions & 1 deletion server/websockets/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,9 @@ import { User } from '../models/user'
import WebSocket from 'ws'
import { sendCommand } from '../services/lamps'
import { LampModel } from '../models/lamp'
import mitt from 'mitt'

export const eventEmiter = mitt()

const router = express.Router()

Expand Down Expand Up @@ -55,11 +58,14 @@ export const broadcastToDevices = (deviceIds: string[], payload: WSPayload) => {
// Client to server events
const events = {
SEND_LAMP_COMMAND: async (data: any) => {
console.log('SEND_LAMP_COMMAND', data)
const { lampId, state } = data
if (lampId && state)
await sendCommand(lampId, state)
},

CONFIG: async (data: any) => {
// TODO: Send config to the client who requested it
}
}

// Ping clients on an interval
Expand Down Expand Up @@ -115,6 +121,8 @@ router.ws('/', async (ws: WebSocket, req: express.Request) => {
const { name, data } = JSON.parse(message)
const handler = (events as any)[name]

eventEmiter.emit(name, data)

if (handler) {
handler(data)
}
Expand Down
Loading

0 comments on commit 280eb0a

Please sign in to comment.