Skip to content

Commit

Permalink
feat: add LED configuration to card
Browse files Browse the repository at this point in the history
  • Loading branch information
coderbyheart committed May 31, 2024
1 parent 6a50d28 commit 52fb1d6
Show file tree
Hide file tree
Showing 6 changed files with 363 additions and 102 deletions.
57 changes: 26 additions & 31 deletions src/components/DeviceHeader.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -26,39 +26,34 @@ import { Slash, ThermometerIcon } from 'lucide-preact'
import { CountryFlag } from './CountryFlag.js'
import './DeviceHeader.css'

export const DeviceHeader = ({ device }: { device: Device }) => {
const type = device.model

return (
<header>
<h1>
<small class="text-muted" style={{ fontSize: '16px' }}>
Your model:{' '}
<a href={`/model/${encodeURIComponent(type.name)}`}>{type.name}</a>
</small>
</h1>
<div class="mt-md-4">
<div class="d-flex flex-wrap">
<div class="me-4 mb-2 mb-lg-4">
<NetworkModeInfo />
</div>
<div class="me-4 mb-2 mb-lg-4">
<SignalQualityInfo />
</div>
<div class="me-4 mb-2 mb-lg-4">
<SIMInfo />
</div>
<div class="me-4 mb-2 mb-lg-4">
<BatteryInfo />
</div>
<div class="me-4 mb-2 mb-lg-4">
<EnvironmentInfo />
</div>
export const DeviceHeader = ({ device }: { device: Device }) => (
<header>
<h1>
<small class="text-muted" style={{ fontSize: '16px' }}>
Your device: {device.id}
</small>
</h1>
<div class="mt-md-4">
<div class="d-flex flex-wrap">
<div class="me-4 mb-2 mb-lg-4">
<NetworkModeInfo />
</div>
<div class="me-4 mb-2 mb-lg-4">
<SignalQualityInfo />
</div>
<div class="me-4 mb-2 mb-lg-4">
<SIMInfo />
</div>
<div class="me-4 mb-2 mb-lg-4">
<BatteryInfo />
</div>
<div class="me-4 mb-2 mb-lg-4">
<EnvironmentInfo />
</div>
</div>
</header>
)
}
</div>
</header>
)

const SignalQualityInfo = () => {
const { reported } = useDevice()
Expand Down
124 changes: 55 additions & 69 deletions src/context/Device.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -17,19 +17,17 @@ import {
import { type Static } from '@sinclair/typebox'
import { isObject } from 'lodash-es'
import { createContext, type ComponentChildren } from 'preact'
import {
useCallback,
useContext,
useEffect,
useRef,
useState,
} from 'preact/hooks'
import { useContext, useEffect, useRef, useState } from 'preact/hooks'

export type Device = {
id: string
model: Model
}

type UpdateResult = Promise<
{ success: true } | { problem: Static<typeof ProblemDetail> }
>

export const DeviceContext = createContext<{
device?: Device | undefined
lastSeen?: Date
Expand All @@ -44,14 +42,12 @@ export const DeviceContext = createContext<{
remove: () => void
}
desired: Record<string, LwM2MObjectInstance>
send?: (message: LwM2MObjectInstance) => void
update: (instance: LwM2MObjectInstance) => UpdateResult
configuration: Partial<{
desired: Configuration
reported: Configuration
}>
configure: (
config: Configuration,
) => Promise<{ success: true } | { problem: Static<typeof ProblemDetail> }>
configure: (config: Configuration) => UpdateResult
debug: boolean
setDebug: (debug: boolean) => void
hasLiveData: boolean
Expand All @@ -69,6 +65,7 @@ export const DeviceContext = createContext<{
connectionFailed: false,
configuration: {},
configure: async () => Promise.reject(new Error('Not implemented')),
update: async () => Promise.reject(new Error('Not implemented')),
debug: false,
setDebug: () => undefined,
hasLiveData: false,
Expand Down Expand Up @@ -217,22 +214,6 @@ export const Provider = ({ children }: { children: ComponentChildren }) => {
}
}, [fingerprint])

const send =
ws === undefined
? undefined
: useCallback(
(message: LwM2MObjectInstance) => {
console.log(`[WS] >`, message)
ws.send(
JSON.stringify({
message: 'message',
payload: message,
}),
)
},
[ws],
)

let hasLiveData = lastSeen !== undefined
if (
lastSeen !== undefined &&
Expand All @@ -243,6 +224,40 @@ export const Provider = ({ children }: { children: ComponentChildren }) => {
reportedConfig?.updateIntervalSeconds * 1000
}

const update = async (instance: LwM2MObjectInstance): UpdateResult =>
new Promise((resolve) => {
onParameters(async ({ helloApiURL }) => {
if (device === undefined) return
if (fingerprint === null) return
try {
await fetch(
new URL(
`./device/${device.id}/state?${new URLSearchParams({ fingerprint }).toString()}`,
helloApiURL,
),
{
method: 'PATCH',
mode: 'cors',
body: JSON.stringify({
'@context': Context.lwm2mObjectUpdate.toString(),
...instance,
}),
},
)
resolve({ success: true })
} catch (err) {
console.error('[DeviceContext]', 'Configuration update failed', err)
resolve({
problem: {
'@context': Context.problemDetail.toString(),
title: 'Failed to update configuration!',
detail: (err as Error).message,
},
})
}
})
})

return (
<DeviceContext.Provider
value={{
Expand Down Expand Up @@ -274,55 +289,26 @@ export const Provider = ({ children }: { children: ComponentChildren }) => {
},
desired,
connectionFailed,
send,
disconnected,
configuration: {
reported: reportedConfig,
desired: desiredConfig,
},
configure: async (config) =>
new Promise((resolve) => {
onParameters(async ({ helloApiURL }) => {
if (device === undefined) return
if (fingerprint === null) return
try {
await fetch(
new URL(
`./device/${device.id}/state?${new URLSearchParams({ fingerprint }).toString()}`,
helloApiURL,
),
{
method: 'PATCH',
mode: 'cors',
body: JSON.stringify({
'@context': Context.lwm2mObjectUpdate.toString(),
ObjectID: LwM2MObjectID.ApplicationConfiguration_14301,
Resources: {
'0': config.updateIntervalSeconds,
'1': config.gnssEnabled,
'99': Date.now(),
},
}),
},
)
setDesiredConfig(config)
resolve({ success: true })
} catch (err) {
console.error(
'[DeviceContext]',
'Configuration update failed',
err,
)
resolve({
problem: {
'@context': Context.problemDetail.toString(),
title: 'Failed to update configuration!',
detail: (err as Error).message,
},
})
}
})
update({
ObjectID: LwM2MObjectID.ApplicationConfiguration_14301,
Resources: {
'0': config.updateIntervalSeconds,
'1': config.gnssEnabled,
'99': Date.now(),
},
}).then((res) => {
if (!('problem' in res)) {
setDesiredConfig(config)
}
return res
}),
update,
debug,
setDebug,
hasLiveData,
Expand Down
Loading

0 comments on commit 52fb1d6

Please sign in to comment.