Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions backend/app/api/frames.py
Original file line number Diff line number Diff line change
Expand Up @@ -1106,6 +1106,7 @@ async def api_frame_import(
"controlCode": "control_code",
"network": "network",
"agent": "agent",
"palette": "palette",
"scenes": "scenes",
}
for src, dest in mapping.items():
Expand Down
3 changes: 3 additions & 0 deletions backend/app/models/frame.py
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,7 @@ class Frame(Base):
gpio_buttons = mapped_column(JSON, nullable=True)
network = mapped_column(JSON, nullable=True)
agent = mapped_column(JSON, nullable=True)
palette = mapped_column(JSON, nullable=True)

# not used
apps = mapped_column(JSON, nullable=True)
Expand Down Expand Up @@ -102,6 +103,7 @@ def to_dict(self):
'gpio_buttons': self.gpio_buttons,
'network': self.network,
'agent': self.agent,
'palette': self.palette,
'last_successful_deploy': self.last_successful_deploy,
'last_successful_deploy_at': self.last_successful_deploy_at.replace(tzinfo=timezone.utc).isoformat() if self.last_successful_deploy_at else None,
}
Expand Down Expand Up @@ -246,6 +248,7 @@ def get_frame_json(db: Session, frame: Frame) -> dict:
for button in (frame.gpio_buttons or [])
if int(button.get("pin", 0)) > 0
],
"palette": frame.palette or {},
"controlCode": {
"enabled": frame.control_code.get('enabled', 'true') == 'true',
"position": frame.control_code.get('position', 'top-right'),
Expand Down
2 changes: 2 additions & 0 deletions backend/app/schemas/frames.py
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,7 @@ class FrameBase(BaseModel):
gpio_buttons: Optional[List[Dict[str, Any]]]
network: Optional[Dict[str, Any]]
agent: Optional[Dict[str, Any]]
palette: Optional[Dict[str, Any]]
last_successful_deploy: Optional[Dict[str, Any]]
last_successful_deploy_at: Optional[datetime]
active_connections: Optional[int] = None
Expand Down Expand Up @@ -90,6 +91,7 @@ class FrameUpdateRequest(BaseModel):
gpio_buttons: Optional[List[Dict[str, Any]]] = None
network: Optional[Dict[str, Any]] = None
agent: Optional[Dict[str, Any]] = None
palette: Optional[Dict[str, Any]] = None
next_action: Optional[str] = None

class FrameLogsResponse(BaseModel):
Expand Down
28 changes: 28 additions & 0 deletions backend/migrations/versions/1a4ece62d617_palette.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
"""palette

Revision ID: 1a4ece62d617
Revises: d1257bdc91fd
Create Date: 2025-06-21 00:46:44.593367

"""
from alembic import op
import sqlalchemy as sa
from sqlalchemy.dialects import sqlite

# revision identifiers, used by Alembic.
revision = '1a4ece62d617'
down_revision = 'd1257bdc91fd'
branch_labels = None
depends_on = None


def upgrade():
# ### commands auto generated by Alembic - please adjust! ###
op.add_column('frame', sa.Column('palette', sqlite.JSON(), nullable=True))
# ### end Alembic commands ###


def downgrade():
# ### commands auto generated by Alembic - please adjust! ###
op.drop_column('frame', 'palette')
# ### end Alembic commands ###
21 changes: 19 additions & 2 deletions frameos/src/drivers/waveshare/waveshare.nim
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import pixie, json, times, locks
import pixie, json, times, locks, options, sequtils

import frameos/types
import frameos/utils/image
Expand All @@ -12,6 +12,7 @@ type Driver* = ref object of FrameOSDriver
height: int
lastImageData: seq[ColorRGBX]
lastRenderAt: float
palette: Option[seq[(int, int, int)]]

var
lastFloatImageLock: Lock
Expand Down Expand Up @@ -53,7 +54,23 @@ proc init*(frameOS: FrameOS): Driver =
logger: logger,
width: width,
height: height,
palette: none(seq[(int, int, int)]),
)

if waveshareDriver.colorOption == ColorOption.SpectraSixColor and len(frameOS.frameConfig.palette.colors) == 6:
let c = frameOS.frameConfig.palette.colors
result.palette = some(@[
(c[0][0], c[0][1], c[0][2]),
(c[1][0], c[1][1], c[1][2]),
(c[2][0], c[2][1], c[2][2]),
(c[3][0], c[3][1], c[3][2]),
(999, 999, 999),
(c[4][0], c[4][1], c[4][2]),
(c[5][0], c[5][1], c[5][2]),
])
else:
result.palette = some(spectra6ColorPalette)

except Exception as e:
logger.log(%*{"event": "driver:waveshare",
"error": "Failed to initialize driver", "exception": e.msg,
Expand Down Expand Up @@ -136,7 +153,7 @@ proc renderSevenColor*(self: Driver, image: Image) =
waveshareDriver.renderImage(pixels)

proc renderSpectraSixColor*(self: Driver, image: Image) =
let pixels = ditherPaletteIndexed(image, spectra6ColorPalette)
let pixels = ditherPaletteIndexed(image, if self.palette.isSome(): self.palette.get() else: spectra6ColorPalette)
setLastPixels(pixels)
self.notifyImageAvailable()
waveshareDriver.renderImage(pixels)
Expand Down
19 changes: 19 additions & 0 deletions frameos/src/frameos/config.nim
Original file line number Diff line number Diff line change
Expand Up @@ -69,6 +69,24 @@ proc loadNetwork*(data: JsonNode): NetworkConfig =
wifiHostpotTimeoutSeconds: data{"wifiHotspotTimeoutSeconds"}.getFloat(600),
)

proc loadPalette*(data: JsonNode): PaletteConfig =
if data == nil or data.kind != JObject or data["colors"] == nil or data["colors"].kind != JArray:
result = PaletteConfig(colors: @[])
else:
result = PaletteConfig(colors: @[])
for color in data["colors"].items:
try:
let color = parseHtmlColor(color.getStr())
result.colors.add((
int(color.r * 255),
int(color.g * 255),
int(color.b * 255),
))
except:
echo "Warning: Invalid color in palette: ", color.getStr()
result.colors = @[]
return result

proc loadAgent*(data: JsonNode): AgentConfig =
if data == nil or data.kind != JObject:
result = AgentConfig(agentEnabled: false)
Expand Down Expand Up @@ -106,6 +124,7 @@ proc loadConfig*(filename: string = "frame.json"): FrameConfig =
gpioButtons: loadGPIOButtons(data{"gpioButtons"}),
controlCode: loadControlCode(data{"controlCode"}),
network: loadNetwork(data{"network"}),
palette: loadPalette(data{"palette"}),
)
if result.assetsPath.endswith("/"):
result.assetsPath = result.assetsPath.strip(leading = false, trailing = true, chars = {'/'})
Expand Down
2 changes: 1 addition & 1 deletion frameos/src/frameos/frameos.nim
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,7 @@ proc start*(self: FrameOS) {.async.} =
"logToFile": self.frameConfig.logToFile,
"debug": self.frameConfig.debug,
"timeZone": self.frameConfig.timeZone,
"gpioButtons": self.frameConfig.gpioButtons,
"gpioButtons": self.frameConfig.gpioButtons
}}
self.logger.log(message)
netportal.setLogger(self.logger)
Expand Down
4 changes: 4 additions & 0 deletions frameos/src/frameos/types.nim
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@ type
controlCode*: ControlCode
network*: NetworkConfig
agent*: AgentConfig
palette*: PaletteConfig

GPIOButton* = ref object
pin*: int
Expand Down Expand Up @@ -56,6 +57,9 @@ type
agentRunCommands*: bool
agentSharedSecret*: string

PaletteConfig* = ref object
colors*: seq[(int, int, int)]

FrameSchedule* = ref object
events*: seq[ScheduledEvent]

Expand Down
61 changes: 61 additions & 0 deletions frontend/src/devices.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { Option } from './components/Select'
import { Palette } from './types'

// To generate a new version:
// cd backend && python3 list_devices.py
Expand Down Expand Up @@ -98,3 +99,63 @@ export const devices: Option[] = [
{ value: 'waveshare.EPD_13in3k', label: 'Waveshare 13.3" (K) 960x680 Black/White' },
{ value: 'waveshare.EPD_13in3e', label: 'Waveshare 13.3" (E) 1600x1200 Spectra 6 Color' },
]

const colorNames = ['Black', 'White', 'Yellow', 'Red', 'Blue', 'Green']
export const spectraPalettes: Palette[] = [
{
name: 'Default',
colorNames,
colors: [
'#000000', // Black
'#ffffff', // White
'#fff338', // Yellow
'#bf0000', // Red
'#6440ff', // Blue
'#438a1c', // Green
],
},
{
name: 'Desaturated',
colorNames,
colors: [
'#000000', // Black
'#ffffff', // White
'#ffff00', // Yellow
'#ff0000', // Red
'#0000ff', // Blue
'#00ff00', // Green
],
},
{
name: 'Pimoroni Saturated',
colorNames,
colors: [
'#000000', // Black
'#a1a4a5', // Gray
'#d0be47', // Yellow
'#9c484b', // Red
'#3d3b5e', // Blue
'#3a5b46', // Green
],
},
{
name: 'Measured',
colorNames,
colors: [
'#3C3542', // Black
'#DCDDD4', // White
'#EDD600', // Yellow
'#C12117', // Red
'#2461C5', // Blue
'#548B79', // Green
],
},
]

// SATURATED_PALETTE = [

export const withCustomPalette: Record<string, Palette> = {
'waveshare.EPD_13in3e': spectraPalettes[0],
'waveshare.EPD_7in3e': spectraPalettes[0],
'waveshare.EPD_4in0e': spectraPalettes[0],
}
4 changes: 2 additions & 2 deletions frontend/src/scenes/frame/Frame.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -29,8 +29,8 @@ export function Frame(props: FrameSceneProps) {
restartAgent,
} = useActions(frameLogic(frameLogicProps))
const { openLogs } = useActions(panelsLogic(frameLogicProps))
const canDeployAgent = !!(frame.agent && frame.agent.agentEnabled && frame.agent.agentSharedSecret)
const agentExtra = canDeployAgent ? (frame.agent?.agentRunCommands ? ' (via agent)' : ' (via ssh)') : ''
const canDeployAgent = !!(frame?.agent && frame.agent.agentEnabled && frame.agent.agentSharedSecret)
const agentExtra = canDeployAgent ? (frame?.agent?.agentRunCommands ? ' (via agent)' : ' (via ssh)') : ''

return (
<BindLogic logic={frameLogic} props={frameLogicProps}>
Expand Down
1 change: 1 addition & 0 deletions frontend/src/scenes/frame/frameLogic.ts
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,7 @@ const FRAME_KEYS: (keyof FrameType)[] = [
'gpio_buttons',
'network',
'agent',
'palette',
]

const FRAME_KEYS_REQUIRE_RECOMPILE: (keyof FrameType)[] = ['device', 'scenes', 'reboot']
Expand Down
72 changes: 71 additions & 1 deletion frontend/src/scenes/frame/panels/FrameSettings/FrameSettings.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ import { Select } from '../../../../components/Select'
import { frameLogic } from '../../frameLogic'
import { downloadJson } from '../../../../utils/downloadJson'
import { Field } from '../../../../components/Field'
import { devices } from '../../../../devices'
import { devices, spectraPalettes, withCustomPalette } from '../../../../devices'
import { secureToken } from '../../../../utils/secureToken'
import { appsLogic } from '../Apps/appsLogic'
import { frameSettingsLogic } from './frameSettingsLogic'
Expand All @@ -19,6 +19,7 @@ import { PlusIcon, TrashIcon } from '@heroicons/react/24/solid'
import { panelsLogic } from '../panelsLogic'
import { Switch } from '../../../../components/Switch'
import { NumberTextInput } from '../../../../components/NumberTextInput'
import { Palette } from '../../../../types'

export interface FrameSettingsProps {
className?: string
Expand All @@ -33,6 +34,8 @@ export function FrameSettings({ className }: FrameSettingsProps) {
const { buildCacheLoading } = useValues(frameSettingsLogic({ frameId }))
const { openLogs } = useActions(panelsLogic({ frameId }))

const palette = withCustomPalette[frame.device || '']

return (
<div className={className}>
{!frame ? (
Expand Down Expand Up @@ -147,6 +150,7 @@ export function FrameSettings({ className }: FrameSettingsProps) {
)}
</Field>
</div>

<H6>Connection</H6>
<div className="pl-2 @md:pl-8 space-y-2">
<Field name="frame_host" label="Frame host">
Expand Down Expand Up @@ -431,6 +435,7 @@ export function FrameSettings({ className }: FrameSettingsProps) {
)}
</Group>
</div>

<H6>Defaults</H6>
<div className="pl-2 @md:pl-8 space-y-2">
<Field name="width" label="Width">
Expand Down Expand Up @@ -467,6 +472,71 @@ export function FrameSettings({ className }: FrameSettingsProps) {
/>
</Field>
</div>

<H6>Palette</H6>
{frame.device && withCustomPalette[frame.device] ? (
<div className="pl-2 @md:pl-8 space-y-2">
<Field name="palette" label="Color palette">
{({ value, onChange }: { value: Palette; onChange: (v: Palette) => void }) => (
<div className="space-y-2 w-full">
<div className="flex items-center gap-2">
<span>Set&nbsp;to</span>
<Select
name="palette"
value={''}
onChange={(v) => {
const selectedPalette = spectraPalettes.find((p) => p.name === v)
if (selectedPalette) {
onChange(selectedPalette)
}
}}
options={[
{ value: '', label: '' },
...spectraPalettes.map((palette) => ({
value: palette.name || '',
label: palette.name || 'Custom',
})),
]}
/>
</div>
{palette?.colors.map((color, index) => (
<div className="flex items-center gap-2" key={index}>
<TextInput
type="color"
theme="node"
className="!w-24"
name={`colors.${index}`}
value={value?.colors?.[index] ?? color}
onChange={(_value) => {
const newColors = palette.colors.map((c, i) =>
i === index ? _value : value?.colors?.[i] ?? c ?? '#000000'
)
onChange({ colors: newColors })
}}
/>
<TextInput
type="text"
className="!w-24"
name={`colors.${index}`}
value={value?.colors?.[index] ?? color}
onChange={(_value) => {
const newColors = palette.colors.map((c, i) =>
i === index ? _value : value?.colors?.[i] ?? c ?? '#000000'
)
onChange({ colors: newColors })
}}
/>
<span>{palette?.colorNames?.[index]}</span>
</div>
))}
</div>
)}
</Field>
</div>
) : (
<div>This frame does not support changing the palette</div>
)}

<H6>QR Control Code</H6>
<div className="pl-2 @md:pl-8 space-y-2">
<Group name="control_code">
Expand Down
Loading