Repository navigation
Expand file tree
/
Copy pathcontroller.go
More file actions
3051 lines (2831 loc) · 112 KB
/
Copy pathcontroller.go
File metadata and controls
3051 lines (2831 loc) · 112 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Package controller is the reusable host API for a controller board.
//
// It owns authenticated serial discovery, the native framed protocol, live
// status, settings, learned RF records, and the same command engine used by the
// CLI and TUI. Applications can embed this package without starting a terminal
// UI or a subprocess.
package controller
import (
"context"
"crypto/rand"
"encoding/hex"
"encoding/json"
"errors"
"fmt"
"io"
"sort"
"strconv"
"strings"
"sync"
"time"
"pccontroller.local/controller/internal/appconfig"
"pccontroller.local/controller/internal/control"
"pccontroller.local/controller/internal/discovery"
"pccontroller.local/controller/internal/hostos"
"pccontroller.local/controller/internal/link"
"pccontroller.local/controller/internal/native"
"pccontroller.local/controller/internal/ports"
"pccontroller.local/controller/internal/programmer"
"pccontroller.local/controller/internal/shell"
)
// Protocol, configuration, and host-service aliases form the embeddable API's
// shared data model without duplicating their wire or validation definitions.
type (
Hello = native.Hello
Status = native.Status
Settings = native.Settings
BoardName = native.BoardName
RFEntry = native.RFEntry
BoardAutomationRecord = native.AutomationRecord
BoardAutomationReadback = native.AutomationRecordReadback
BoardAutomationSnapshot = control.BoardAutomationSnapshot
OfflineEEPROMDecode = programmer.OfflineEEPROMDecode
OfflineAutomationDecode = programmer.OfflineAutomationDecode
OfflineAutomationBank = programmer.OfflineAutomationBank
OfflineAutomationRecord = programmer.OfflineAutomationRecord
RFConfig = appconfig.RFConfig
RFCategory = appconfig.RFCategory
RFCodeKey = appconfig.RFCodeKey
RFMetadata = appconfig.RFMetadata
TemperatureSensor = native.TemperatureSensor
DeviceEvent = native.DeviceEvent
PWMValues = native.PWMValues
FrontPanel = native.FrontPanel
Melody = appconfig.Melody
MelodyNote = appconfig.MelodyNote
StatusLEDEffect = appconfig.StatusLEDEffect
StatusLEDState = native.StatusLEDState
StatusProfile = native.StatusProfile
StatusEffectOptions = native.StatusEffectOptions
StatusLEDPolicy = appconfig.StatusLEDPolicy
StatusLEDVisual = appconfig.StatusLEDVisual
RGBColor = appconfig.RGBColor
MotionSideState = control.MotionSideState
MotionSnapshot = control.MotionSnapshot
OutputStreamState = control.OutputStreamState
StatusSample = control.StatusSample
TimelineEntry = control.TimelineEntry
HardwareProblem = ports.HardwareProblem
HistoryOptions = control.HistoryOptions
RFLearnMode = control.RFLearnMode
RFLearnOptions = control.RFLearnOptions
RFLearnState = control.RFLearnState
MenuPageInfo = control.MenuPageInfo
MenuCatalog = control.MenuCatalog
MenuLayout = control.MenuLayout
HostMenuDirectory = native.HostMenuDirectory
HostMenuDirectoryEntry = native.HostMenuDirectoryEntry
HostMenuContent = native.HostMenuContent
HostMenuState = native.HostMenuState
HostMenuContentRequest = native.HostMenuContentRequest
I2CTransferResult = native.I2CTransferResult
LCDPresentationOptions = control.LCDPresentationOptions
LCDPresentationState = control.LCDPresentationState
DisplayRepeat = control.DisplayRepeat
DisplayRequest = control.DisplayRequest
DisplayResult = control.DisplayResult
OSPolicy = hostos.Policy
VirtualKeyPolicy = hostos.VirtualKeyPolicy
PowerPolicy = hostos.PowerPolicy
VirtualKeyRequest = hostos.VirtualKeyRequest
PowerRequest = hostos.PowerRequest
OSActionResult = hostos.ActionResult
SystemStatus = hostos.SystemStatus
CommandDescriptor = shell.CommandDescriptor
ToolchainSyncOptions = programmer.ToolchainSyncOptions
ToolchainSyncStep = programmer.ToolchainSyncStep
ToolchainSyncReport = programmer.ToolchainSyncReport
ToolchainProfile = programmer.ToolchainProfile
ToolchainPolicy = programmer.ToolchainPolicy
ToolchainLock = programmer.ToolchainLock
ToolchainCanary = programmer.ToolchainCanary
ToolchainResolution = programmer.ToolchainResolution
ToolchainChange = programmer.ToolchainChange
ToolchainResolveOptions = programmer.ToolchainResolveOptions
ToolchainBootstrapOptions = programmer.ToolchainBootstrapOptions
ToolchainBootstrapReport = programmer.ToolchainBootstrapReport
ProgramMode = control.ProgramMode
ProgramStateOwner = control.ProgramStateOwner
ProgramStateSnapshot = control.ProgramStateSnapshot
ProgramStateLease = control.ProgramStateLease
EmergencyStopState = control.EmergencyStopState
PortProcessSnapshot = control.PortProcessSnapshot
DiscoveryInstance = discovery.Instance
DiscoveryOptions = discovery.Options
)
// RF learning modes select indefinite multi-code or bounded timer operation.
const (
RFLearnIndefinite = control.RFLearnIndefinite
RFLearnTimer = control.RFLearnTimer
)
const (
DisplayRepeatOnce = control.DisplayRepeatOnce
DisplayRepeatLoop = control.DisplayRepeatLoop
DisplayRepeatInterval = control.DisplayRepeatInterval
)
// ParseRFLearnMode accepts the canonical RF learning mode and documented aliases.
func ParseRFLearnMode(value string) (RFLearnMode, error) {
return control.ParseRFLearnMode(value)
}
// RFAction identifies the peripheral domain invoked by a learned RF code.
type RFAction byte
// RFBehavior selects press, toggle, momentary, or motion behavior.
type RFBehavior byte
// RelayMotion selects the requested state of one interlocked motion side.
type RelayMotion byte
// RF mapping, motion, settings, and program-state constants mirror the native API.
const (
RFActionNone RFAction = RFAction(native.RFActionNone)
RFActionKey RFAction = RFAction(native.RFActionKey)
RFActionMenu RFAction = RFAction(native.RFActionMenu)
RFActionRelay RFAction = RFAction(native.RFActionRelay)
RFActionSide RFAction = RFAction(native.RFActionSide)
RFActionPWM RFAction = RFAction(native.RFActionPWM)
RFBehaviorPress RFBehavior = RFBehavior(native.RFBehaviorPress)
RFBehaviorToggle RFBehavior = RFBehavior(native.RFBehaviorToggle)
RFBehaviorMomentary RFBehavior = RFBehavior(native.RFBehaviorMomentary)
RFBehaviorUp RFBehavior = RFBehavior(native.RFBehaviorUp)
RFBehaviorDown RFBehavior = RFBehavior(native.RFBehaviorDown)
RFBehaviorStop RFBehavior = RFBehavior(native.RFBehaviorStop)
RelayMotionStop RelayMotion = 0
RelayMotionUp RelayMotion = 1
RelayMotionDown RelayMotion = 2
SettingsSaveLastPage byte = native.SettingsSaveLastPage
SettingsStatusColorMask byte = native.SettingsStatusColorMask
SettingsVoltageDecimalMask byte = native.SettingsVoltageDecimalMask
SettingsCurrentDecimalMask byte = native.SettingsCurrentDecimalMask
SettingsDefaultDecimals byte = native.SettingsDefaultDecimals
MotionDoorAlways byte = native.MotionDoorAlways
MotionDoorClosedOnly byte = native.MotionDoorClosedOnly
MotionDoorOpenOnly byte = native.MotionDoorOpenOnly
MotionDoorNever byte = native.MotionDoorNever
ProgramIdle = control.ProgramIdle
ProgramRunning = control.ProgramRunning
BoardAutomationAllocateID = native.AutomationAllocateID
BoardAutomationEnabled = native.AutomationEnabled
BoardAutomationEventDoor = native.AutomationEventDoor
BoardAutomationEventBluetooth = native.AutomationEventBluetooth
BoardAutomationEventHost = native.AutomationEventHost
BoardAutomationEventRelay = native.AutomationEventRelay
BoardAutomationEventLearnedRF = native.AutomationEventLearnedRF
BoardAutomationEventKey = native.AutomationEventKey
BoardAutomationEventAlert = native.AutomationEventAlert
BoardAutomationEventBoot = native.AutomationEventBoot
BoardAutomationActionSafeStop = native.AutomationActionSafeStop
BoardAutomationActionMotionStop = native.AutomationActionMotionStop
BoardAutomationActionRelay = native.AutomationActionRelay
BoardAutomationActionPWM = native.AutomationActionPWM
BoardAutomationActionStatusCue = native.AutomationActionStatusCue
BoardAutomationActionBuzzer = native.AutomationActionBuzzer
BoardAutomationActionRFTransmit = native.AutomationActionRFTransmit
BoardAutomationActionHostMacro = native.AutomationActionHostMacroRequest
)
// ValidateBoardAutomation applies the same bounded safety contract as the
// firmware without contacting a board.
func ValidateBoardAutomation(record BoardAutomationRecord) error {
return native.ValidateAutomationRecord(record)
}
// DecodeOfflineEEPROMHex performs read-only forensic decoding of settings,
// learned RF, reset history, and an optional automation-profile tail.
func DecodeOfflineEEPROMHex(path string) (OfflineEEPROMDecode, error) {
return programmer.DecodeOfflineEEPROMHex(path)
}
// RFMapping binds a learned record to one board action and behavior.
type RFMapping struct {
Action RFAction `json:"action"`
Value byte `json:"value"`
Behavior RFBehavior `json:"behavior"`
}
// OutputOperation tracks an asynchronous melody or status-LED effect.
type OutputOperation struct {
ID uint64 `json:"id"`
Kind string `json:"kind"`
Name string `json:"name"`
Done <-chan error `json:"-"`
}
// StatusUpdate contains one subscribed telemetry result or its polling error.
type StatusUpdate struct {
HostInstanceID string `json:"host_instance_id,omitempty"`
ConnectionGeneration uint64 `json:"connection_generation"`
BoardConnected bool `json:"board_connected"`
HaveStatus bool `json:"have_status"`
Time time.Time `json:"time"`
Status Status `json:"status"`
Error string `json:"error,omitempty"`
}
func (client *Client) CachedStatusObservation() StatusUpdate {
status, have, stamp, generation, connected := client.runtime.ObservedStatus()
return StatusUpdate{Status: status, HaveStatus: have, Time: stamp, ConnectionGeneration: generation, BoardConnected: connected}
}
// Options configures discovery, transport, tooling, automation, and host policy.
type Options struct {
Port string `json:"port,omitempty"`
VID string `json:"vid,omitempty"`
PID string `json:"pid,omitempty"`
Name string `json:"name,omitempty"`
PreferredDevice *PortInfo `json:"preferred_device,omitempty"`
BaudRate int `json:"baud_rate,omitempty"`
StartupWait time.Duration `json:"startup_wait,omitempty"`
RequestTimeout time.Duration `json:"request_timeout,omitempty"`
HelloAttempts int `json:"hello_attempts,omitempty"`
ResetOnReconnect bool `json:"reset_on_reconnect,omitempty"`
ReconnectInitialDelay time.Duration `json:"reconnect_initial_delay,omitempty"`
ReconnectMaximumDelay time.Duration `json:"reconnect_maximum_delay,omitempty"`
ProjectPath string `json:"project_path,omitempty"`
FQBN string `json:"fqbn,omitempty"`
FirmwareFeatures []string `json:"firmware_features,omitempty"`
ToolchainCLI string `json:"toolchain_cli,omitempty"`
ToolchainConfig string `json:"toolchain_config,omitempty"`
Avrdude string `json:"avrdude,omitempty"`
AvrdudeConf string `json:"avrdude_conf,omitempty"`
AvrdudeBackend string `json:"avrdude_backend,omitempty"`
AvrdudeAdapter string `json:"avrdude_adapter,omitempty"`
Programmer string `json:"programmer,omitempty"`
Macros []Macro `json:"macros,omitempty"`
StripEffects []StripEffect `json:"strip_effects,omitempty"`
Melodies []Melody `json:"melodies,omitempty"`
StatusEffects []StatusLEDEffect `json:"status_effects,omitempty"`
Scripts map[string]string `json:"scripts,omitempty"`
Automations []Automation `json:"automations,omitempty"`
MotionDoorPolicy string `json:"motion_door_policy,omitempty"`
LCDPresentation LCDPresentationOptions `json:"lcd_presentation,omitempty"`
RF RFConfig `json:"rf"`
OSActions OSPolicy `json:"os_actions"`
}
// Macro describes a host-owned sequence of peripheral operations. Mode chooses
// host-clocked alpha playback or the stricter MCU timing engine.
type Macro struct {
ID byte `json:"id"`
Name string `json:"name"`
Mode string `json:"mode,omitempty"`
Category string `json:"category,omitempty"`
Color string `json:"color,omitempty"`
Label string `json:"label,omitempty"`
LCDMessage string `json:"lcd_message,omitempty"`
TimingToleranceUS uint32 `json:"timing_tolerance_us,omitempty"`
KeepOutputsOnCancel bool `json:"keep_outputs_on_cancel,omitempty"`
BoardProfileKey string `json:"board_profile_key,omitempty"`
BoardProfileMode string `json:"board_profile_mode,omitempty"`
Steps []MacroStep `json:"steps"`
RepeatCount *uint16 `json:"repeat_count,omitempty"`
RepeatIntervalMS uint32 `json:"repeat_interval_ms,omitempty"`
}
// MacroStep describes one timestamped operation within a Macro.
type MacroStep struct {
AtUS uint32 `json:"at_us,omitempty"`
Kind string `json:"kind"`
Target byte `json:"target,omitempty"`
Value uint16 `json:"value,omitempty"`
DurationMS uint16 `json:"duration_ms,omitempty"`
ToValue *uint16 `json:"to_value,omitempty"`
Easing string `json:"easing,omitempty"`
SampleRateHz byte `json:"sample_rate_hz,omitempty"`
FrequencyHz uint16 `json:"frequency_hz,omitempty"`
Text string `json:"text,omitempty"`
Destination string `json:"destination,omitempty"`
Code uint32 `json:"code,omitempty"`
Bits byte `json:"bits,omitempty"`
Protocol byte `json:"protocol,omitempty"`
PulseUS uint16 `json:"pulse_us,omitempty"`
Red byte `json:"red,omitempty"`
Green byte `json:"green,omitempty"`
Blue byte `json:"blue,omitempty"`
Brightness byte `json:"brightness,omitempty"`
ToRed *byte `json:"to_red,omitempty"`
ToGreen *byte `json:"to_green,omitempty"`
ToBlue *byte `json:"to_blue,omitempty"`
ToBrightness *byte `json:"to_brightness,omitempty"`
Opcode byte `json:"opcode,omitempty"`
PayloadHex string `json:"payload_hex,omitempty"`
ActionIDs []string `json:"action_ids,omitempty"`
}
// StripEffect is a PCController-owned, user-editable declarative light program.
type StripEffect struct {
ID string `json:"id"`
Name string `json:"name"`
Category string `json:"category,omitempty"`
Description string `json:"description,omitempty"`
Program StripProgram `json:"program"`
DefaultFPS int `json:"default_fps"`
DefaultDurationMS int `json:"default_duration_ms"`
DefaultPixels int `json:"default_pixels,omitempty"`
}
type StripColor struct {
Red byte `json:"red"`
Green byte `json:"green"`
Blue byte `json:"blue"`
}
type StripEnvelopePoint struct {
AtMS int `json:"at_ms"`
Intensity byte `json:"intensity"`
}
type StripProgram struct {
Primitive string `json:"primitive"`
Primary StripColor `json:"primary"`
Secondary StripColor `json:"secondary,omitempty"`
PeriodMS int `json:"period_ms"`
StepMS int `json:"step_ms,omitempty"`
SwapAfterSteps int `json:"swap_after_steps,omitempty"`
DimIntensity byte `json:"dim_intensity,omitempty"`
TailPixels int `json:"tail_pixels,omitempty"`
Envelope []StripEnvelopePoint `json:"envelope,omitempty"`
}
// Automation maps an event match to one or more host-side actions.
type Automation struct {
Name string `json:"name"`
Enabled bool `json:"enabled"`
CooldownMS int `json:"cooldown_ms,omitempty"`
Match AutomationMatch `json:"match"`
Actions []AutomationAction `json:"actions"`
}
// AutomationMatch selects the event properties that trigger an automation.
type AutomationMatch struct {
Kind string `json:"kind"`
Lifecycle string `json:"lifecycle,omitempty"`
State string `json:"state,omitempty"`
Contains string `json:"contains,omitempty"`
Key byte `json:"key,omitempty"`
Gesture string `json:"gesture,omitempty"`
Source string `json:"source,omitempty"`
RFID *byte `json:"rf_id,omitempty"`
RFCode *uint32 `json:"rf_code,omitempty"`
RFProtocol byte `json:"rf_protocol,omitempty"`
RFBits byte `json:"rf_bits,omitempty"`
}
// AutomationAction describes one command, macro, integration, or OS action.
type AutomationAction struct {
Type string `json:"type"`
Command string `json:"command,omitempty"`
Macro string `json:"macro,omitempty"`
Executable string `json:"executable,omitempty"`
Detached bool `json:"detached,omitempty"`
Args []string `json:"args,omitempty"`
Script string `json:"script,omitempty"`
Event string `json:"event,omitempty"`
RF *RFTransmit `json:"rf,omitempty"`
VirtualKey string `json:"virtual_key,omitempty"`
HoldMS int `json:"hold_ms,omitempty"`
Power string `json:"power,omitempty"`
Confirm string `json:"confirm,omitempty"`
AppKind string `json:"app_kind,omitempty"`
AppValue string `json:"app_value,omitempty"`
AppTarget string `json:"app_target,omitempty"`
ActionID string `json:"action_id,omitempty"`
}
// RFTransmit contains the complete waveform metadata for one 433 MHz send action.
type RFTransmit struct {
Code uint32 `json:"code"`
Bits byte `json:"bits"`
Protocol byte `json:"protocol"`
PulseUS uint16 `json:"pulse_us,omitempty"`
Repeats byte `json:"repeats,omitempty"`
}
// RFEntryView combines one MCU record with host-owned display metadata.
type RFEntryView struct {
ID byte `json:"id"`
Code uint32 `json:"code"`
CodeDisplay string `json:"code_display"`
Bits byte `json:"bits"`
Protocol byte `json:"protocol"`
PulseUS uint16 `json:"pulse_us"`
ActionKind byte `json:"action_kind"`
ActionValue byte `json:"action_value"`
Behavior byte `json:"behavior"`
Name string `json:"name,omitempty"`
Category string `json:"category,omitempty"`
}
// PortInfo identifies one serial candidate with stable USB metadata when available.
type PortInfo struct {
Name string `json:"name"`
DisplayName string `json:"display_name,omitempty"`
VID string `json:"vid,omitempty"`
PID string `json:"pid,omitempty"`
Product string `json:"product,omitempty"`
Manufacturer string `json:"manufacturer,omitempty"`
SerialNumber string `json:"serial_number,omitempty"`
FriendlyName string `json:"friendly_name,omitempty"`
InstanceID string `json:"instance_id,omitempty"`
}
// IlluminationState combines the persisted enclosure-light policy with the
// authoritative PWM value currently applied to the dedicated channel. Values
// ending in Brightness use the board's 0..255 settings scale; PWM values use
// the PCA controller's native logical 0..4095 scale.
type IlluminationState struct {
Available bool `json:"available"`
Mode byte `json:"mode"`
OnBrightness byte `json:"on_brightness"`
OffBrightness byte `json:"off_brightness"`
DoorOpen bool `json:"door_open"`
TargetBrightness byte `json:"target_brightness"`
TargetPWM uint16 `json:"target_pwm"`
AppliedBrightness byte `json:"applied_brightness"`
AppliedPWM uint16 `json:"applied_pwm"`
AtTarget bool `json:"at_target"`
Persisted bool `json:"persisted"`
UpdatedAt time.Time `json:"updated_at,omitempty"`
}
// Snapshot is a point-in-time view of connection, board, and front-panel state.
type Snapshot struct {
HostInstanceID string `json:"host_instance_id,omitempty"`
Connected bool `json:"connected"`
Paused bool `json:"paused"`
Port PortInfo `json:"port"`
Hello Hello `json:"hello"`
BoardName BoardName `json:"board_name"`
HaveBoardName bool `json:"have_board_name"`
Status Status `json:"status"`
Settings Settings `json:"settings"`
HaveStatus bool `json:"have_status"`
HaveSettings bool `json:"have_settings"`
StatusUpdated time.Time `json:"status_updated,omitempty"`
ConnectionState string `json:"connection_state"`
ConnectionReason string `json:"connection_reason,omitempty"`
ConnectionUpdated time.Time `json:"connection_updated,omitempty"`
ConnectionPhase string `json:"connection_phase"`
ConnectionAttempt uint64 `json:"connection_attempt,omitempty"`
ConnectionGeneration uint64 `json:"connection_generation,omitempty"`
ConnectionAttemptStarted time.Time `json:"connection_attempt_started,omitempty"`
ConnectionNextRetry time.Time `json:"connection_next_retry,omitempty"`
ConnectionRetryDelayMS int64 `json:"connection_retry_delay_ms,omitempty"`
ConnectionCandidate PortInfo `json:"connection_candidate"`
ResetLinesAvailable bool `json:"reset_lines_available"`
ResetLinesPort PortInfo `json:"reset_lines_port"`
ResetLinesReason string `json:"reset_lines_reason,omitempty"`
ProgramState ProgramStateSnapshot `json:"program_state"`
Programming control.ProgrammingSnapshot `json:"programming"`
EmergencyStop EmergencyStopState `json:"emergency_stop"`
RFLearning RFLearnState `json:"rf_learning"`
Macros control.MacroSnapshot `json:"macros"`
Effects []control.EffectDescriptor `json:"effects"`
EffectGroups []control.EffectGroupDescriptor `json:"effect_groups"`
HardwareProblems []HardwareProblem `json:"hardware_problems,omitempty"`
FrontPanel FrontPanel `json:"front_panel"`
HaveFrontPanel bool `json:"have_front_panel"`
HaveFrontPanelSegments bool `json:"have_front_panel_segments"`
FrontPanelUpdated time.Time `json:"front_panel_updated,omitempty"`
StatusLED StatusLEDState `json:"status_led"`
HaveStatusLED bool `json:"have_status_led"`
StatusLEDUpdated time.Time `json:"status_led_updated,omitempty"`
StatusLEDRevision uint64 `json:"status_led_revision,omitempty"`
PWMValues *PWMValues `json:"pwm_values,omitempty"`
PWMRevision uint64 `json:"pwm_revision,omitempty"`
PWMUpdated time.Time `json:"pwm_updated,omitempty"`
PWMRecall [16]control.PWMRecallValue `json:"pwm_recall"`
Motion MotionSnapshot `json:"motion"`
Outputs OutputStreamState `json:"outputs"`
StripEffects []control.StripEffectDescriptor `json:"strip_effects,omitempty"`
Illumination IlluminationState `json:"illumination"`
PortProcess PortProcessSnapshot `json:"port_process"`
}
// Unknown offline settings are not an EEPROM write payload. Decode their
// presence flag first so an initial pushed offline snapshot remains usable.
func (snapshot *Snapshot) UnmarshalJSON(data []byte) error {
type fields Snapshot
var result Snapshot
wire := struct {
*fields
Settings json.RawMessage `json:"settings"`
}{fields: (*fields)(&result)}
if err := json.Unmarshal(data, &wire); err != nil {
return err
}
if result.HaveSettings {
if err := json.Unmarshal(wire.Settings, &result.Settings); err != nil {
return err
}
}
*snapshot = result
return nil
}
// Event is the normalized event envelope shared by embedders and bridge clients.
type Event struct {
ID uint64 `json:"id"`
Time time.Time `json:"time"`
Kind string `json:"kind"`
Stream string `json:"stream"`
Text string `json:"text"`
Opcode byte `json:"opcode,omitempty"`
Seq byte `json:"seq,omitempty"`
Payload []byte `json:"payload,omitempty"`
Device *DeviceEvent `json:"device,omitempty"`
Lifecycle string `json:"lifecycle,omitempty"`
Port PortInfo `json:"port,omitempty"`
Reason string `json:"reason,omitempty"`
State string `json:"state,omitempty"`
Key byte `json:"key,omitempty"`
Gesture string `json:"gesture,omitempty"`
Source string `json:"source,omitempty"`
Target string `json:"target,omitempty"`
Targets []string `json:"targets,omitempty"`
MessageType string `json:"message_type,omitempty"`
Action string `json:"action,omitempty"`
Severity string `json:"severity,omitempty"`
Correlation string `json:"correlation,omitempty"`
Delivery string `json:"delivery,omitempty"`
Metadata map[string]string `json:"metadata,omitempty"`
Programming *control.ProgrammingSnapshot `json:"programming,omitempty"`
SourceID *byte `json:"source_id,omitempty"`
RFID *byte `json:"rf_id,omitempty"`
RFCode uint32 `json:"rf_code,omitempty"`
RFBits byte `json:"rf_bits,omitempty"`
RFProtocol byte `json:"rf_protocol,omitempty"`
RFPulseUS uint16 `json:"rf_pulse_us,omitempty"`
ResetCause byte `json:"reset_cause,omitempty"`
ResetCount uint32 `json:"reset_count,omitempty"`
}
// FirmwareBuildRequest is the strict, typed alternative to sending a raw
// shell command to a remote host. An empty request uses the host's configured
// firmware feature profile.
type FirmwareBuildRequest struct {
FirmwareFeatures []string `json:"firmware_features,omitempty"`
NoFirmwareFeatures bool `json:"no_firmware_features,omitempty"`
}
// FirmwareBuildResult correlates the final normalized log with the ordered
// program.* events that WebSocket, Socket.IO, TUI, and long-poll clients see.
type FirmwareBuildResult struct {
OperationID string `json:"operation_id"`
Output string `json:"output"`
}
// OpcodeFrame is the raw, versionless UART exchange result. Payload is kept
// opaque so clients can query firmware additions before the host understands
// their schema.
type OpcodeFrame struct {
Opcode byte `json:"opcode"`
Name string `json:"name"`
Sequence byte `json:"sequence"`
Payload []byte `json:"payload,omitempty"`
PayloadHex string `json:"payload_hex,omitempty"`
}
// TextMessage is a typed envelope shared by IPC, WebSocket, webhooks, the host
// bridge, and LCD presentation. Action is descriptive; it is never executed
// implicitly. Remote command execution uses the authenticated execute method.
type TextMessage struct {
Source string `json:"source"`
Targets []string `json:"targets"`
Type string `json:"type"`
Text string `json:"text"`
Line1 string `json:"line1,omitempty"`
Line2 string `json:"line2,omitempty"`
Action string `json:"action,omitempty"`
Severity string `json:"severity,omitempty"`
Correlation string `json:"correlation,omitempty"`
Delivery string `json:"delivery,omitempty"`
Metadata map[string]string `json:"metadata,omitempty"`
}
// Client owns one controller runtime, command engine, and host integration state.
type Client struct {
runtime *control.Runtime
runtimeClose func() error
shutdownMu sync.Mutex
engine *shell.Engine
engineMu sync.Mutex
optionsMu sync.RWMutex
commandOptions control.CommandOptions
macroMu sync.RWMutex
macros []appconfig.Macro
outputMu sync.RWMutex
melodies []appconfig.Melody
statusEffects []appconfig.StatusLEDEffect
stripEffects []appconfig.StripEffect
outputs *control.OutputScheduler
hostMu sync.RWMutex
scripts map[string]string
automations []appconfig.Automation
safety appconfig.Safety
rfConfig appconfig.RFConfig
osPolicy hostos.Policy
events chan Event
done chan struct{}
doneOnce sync.Once
statusHub statusSubscriptionHub
statusFetch func(context.Context) (Status, error)
illuminationMu sync.RWMutex
illumination IlluminationState
illuminationPollAt time.Time
}
type statusSubscriber struct {
interval time.Duration
next time.Time
updates chan StatusUpdate
}
type statusSubscriptionHub struct {
mu sync.Mutex
subscribers map[uint64]*statusSubscriber
nextID uint64
wake chan struct{}
running bool
}
// New creates a client that owns its serial and background-service lifecycle.
func New(options Options) *Client {
baud := options.BaudRate
if baud == 0 {
baud = link.DefaultBaudRate
}
fqbn := options.FQBN
if fqbn == "" {
fqbn = programmer.DefaultFQBN()
}
firmwareFeatures, firmwareFeaturesErr := programmer.NormalizeFirmwareFeatures(
options.FirmwareFeatures,
)
runtime := control.New(control.Options{
Filter: ports.Filter{
Port: options.Port,
VID: options.VID,
PID: options.PID,
Name: options.Name,
Preferred: internalPortIdentity(options.PreferredDevice),
},
BaudRate: baud,
StartupWait: options.StartupWait,
RequestTimeout: options.RequestTimeout,
HelloAttempts: options.HelloAttempts,
ResetOnReconnect: options.ResetOnReconnect,
ReconnectInitialDelay: options.ReconnectInitialDelay,
ReconnectMaximumDelay: options.ReconnectMaximumDelay,
})
client := &Client{
runtime: runtime,
runtimeClose: runtime.Close,
macros: toAppMacros(options.Macros),
melodies: cloneMelodies(options.Melodies),
statusEffects: append(
[]appconfig.StatusLEDEffect(nil),
options.StatusEffects...,
),
stripEffects: toAppStripEffects(options.StripEffects),
scripts: cloneStringMap(options.Scripts),
automations: toAppAutomations(options.Automations),
safety: appconfig.Safety{
MotionDoorPolicy: normalizedMotionDoorPolicy(options.MotionDoorPolicy),
},
rfConfig: cloneRFConfigOrDefault(options.RF),
osPolicy: cloneOSPolicyOrDefault(options.OSActions),
events: make(chan Event, 256),
done: make(chan struct{}),
}
client.outputs = control.NewOutputScheduler(runtime)
_ = runtime.LCDPresenter().Configure(options.LCDPresentation)
client.commandOptions = control.CommandOptions{
ProjectPath: options.ProjectPath,
FQBN: fqbn,
FirmwareFeatures: firmwareFeatures,
FirmwareFeaturesError: firmwareFeaturesErr,
ArduinoCLI: options.ToolchainCLI,
ArduinoConfig: options.ToolchainConfig,
Avrdude: options.Avrdude,
AvrdudeConf: options.AvrdudeConf,
AvrdudeBackend: options.AvrdudeBackend, AvrdudeAdapter: options.AvrdudeAdapter,
Programmer: options.Programmer,
HostConfig: client.currentHostConfig,
UpdateHostConfig: client.updateHostConfig,
Outputs: client.outputs,
}
client.engine = control.NewCommandEngine(runtime, control.CommandOptions{
ProjectPath: options.ProjectPath,
FQBN: fqbn,
FirmwareFeatures: firmwareFeatures,
FirmwareFeaturesError: firmwareFeaturesErr,
Macros: client.currentMacros,
ArduinoCLI: options.ToolchainCLI,
ArduinoConfig: options.ToolchainConfig,
Avrdude: options.Avrdude,
AvrdudeConf: options.AvrdudeConf,
AvrdudeBackend: options.AvrdudeBackend, AvrdudeAdapter: options.AvrdudeAdapter,
Programmer: options.Programmer,
HostConfig: client.currentHostConfig,
UpdateHostConfig: client.updateHostConfig,
Resolve: client.currentCommandOptions,
Outputs: client.outputs,
})
automationContext, cancelAutomations := context.WithCancel(context.Background())
go func() {
<-client.done
cancelAutomations()
}()
go control.RunAutomations(
automationContext,
runtime,
client.engine,
client.currentHostConfig,
)
go client.forwardEvents()
return client
}
// AttachSharedRuntime creates an API/IPC facade around a runtime and command
// engine that are already owned by the current process. It lets an interactive
// TUI or shell be the one and only serial owner while secondary processes use
// JSON-RPC. The caller remains responsible for closing the runtime.
//
// This constructor is intended for sibling packages in this module. External
// embedders should normally use New, which owns its complete lifecycle.
func AttachSharedRuntime(
runtime *control.Runtime,
engine *shell.Engine,
) *Client {
if runtime == nil {
panic("controller: shared runtime is nil")
}
if engine == nil {
panic("controller: shared command engine is nil")
}
return &Client{
runtime: runtime,
runtimeClose: runtime.Close,
engine: engine,
outputs: runtime.EnsureOutputScheduler(),
events: make(chan Event),
done: make(chan struct{}),
}
}
// ApplyHostOptions atomically refreshes runtime and host-owned configuration.
func (client *Client) ApplyHostOptions(options Options) bool {
baud := options.BaudRate
if baud == 0 {
baud = link.DefaultBaudRate
}
changed := client.runtime.ApplyOptions(control.Options{
Filter: ports.Filter{
Port: options.Port,
VID: options.VID,
PID: options.PID,
Name: options.Name,
Preferred: internalPortIdentity(options.PreferredDevice),
},
BaudRate: baud, StartupWait: options.StartupWait,
RequestTimeout: options.RequestTimeout,
HelloAttempts: options.HelloAttempts,
ResetOnReconnect: options.ResetOnReconnect,
ReconnectInitialDelay: options.ReconnectInitialDelay,
ReconnectMaximumDelay: options.ReconnectMaximumDelay,
})
client.SetMacros(options.Macros)
client.SetOutputDefinitions(options.Melodies, options.StatusEffects)
_ = client.ConfigureLCDPresentation(options.LCDPresentation)
client.hostMu.Lock()
client.scripts = cloneStringMap(options.Scripts)
client.automations = toAppAutomations(options.Automations)
client.safety.MotionDoorPolicy = normalizedMotionDoorPolicy(
options.MotionDoorPolicy,
)
client.rfConfig = cloneRFConfigOrDefault(options.RF)
client.osPolicy = cloneOSPolicyOrDefault(options.OSActions)
client.hostMu.Unlock()
fqbn := options.FQBN
if fqbn == "" {
fqbn = programmer.DefaultFQBN()
}
firmwareFeatures, firmwareFeaturesErr := programmer.NormalizeFirmwareFeatures(
options.FirmwareFeatures,
)
client.optionsMu.Lock()
client.commandOptions = control.CommandOptions{
ProjectPath: options.ProjectPath, FQBN: fqbn,
FirmwareFeatures: firmwareFeatures,
FirmwareFeaturesError: firmwareFeaturesErr,
ArduinoCLI: options.ToolchainCLI, Avrdude: options.Avrdude,
ArduinoConfig: options.ToolchainConfig,
AvrdudeConf: options.AvrdudeConf,
AvrdudeBackend: options.AvrdudeBackend, AvrdudeAdapter: options.AvrdudeAdapter,
Programmer: options.Programmer,
HostConfig: client.currentHostConfig,
UpdateHostConfig: client.updateHostConfig,
Outputs: client.outputs,
}
client.optionsMu.Unlock()
return changed
}
func internalPortIdentity(info *PortInfo) ports.Identity {
if info == nil {
return ports.Identity{}
}
return ports.Identity{
Port: info.Name, VID: info.VID, PID: info.PID,
SerialNumber: info.SerialNumber,
Name: firstNonempty(info.FriendlyName, info.Product),
InstanceID: info.InstanceID,
}
}
func firstNonempty(values ...string) string {
for _, value := range values {
if strings.TrimSpace(value) != "" {
return value
}
}
return ""
}
func cloneOSPolicyOrDefault(value hostos.Policy) hostos.Policy {
if value.VirtualKeys.MinIntervalMS == 0 && value.VirtualKeys.HoldMS == 0 &&
len(value.VirtualKeys.Allowed) == 0 && len(value.Power.Allowed) == 0 {
return hostos.DefaultPolicy()
}
return hostos.ClonePolicy(value)
}
func (client *Client) currentHostConfig() appconfig.Config {
client.hostMu.RLock()
scripts := cloneStringMap(client.scripts)
automations := cloneAppAutomations(client.automations)
safety := client.safety
rfConfig := cloneRFConfigOrDefault(client.rfConfig)
osPolicy := hostos.ClonePolicy(client.osPolicy)
client.hostMu.RUnlock()
config := appconfig.Defaults()
config.Programming.FirmwareFeatures = append(
[]programmer.FirmwareFeature(nil),
client.currentCommandOptions().FirmwareFeatures...,
)
config.Macros = client.currentMacros()
config.StripEffects = client.currentStripEffects()
config.Scripts = scripts
config.Automations = automations
config.Melodies = client.currentMelodies()
config.StatusEffects = client.currentStatusEffects()
config.Safety = safety
config.RF = rfConfig
config.OSActions = osPolicy
return config
}
func (client *Client) updateHostConfig(
change func(*appconfig.Config) error,
) error {
if change == nil {
return errors.New("host configuration update callback is nil")
}
config := client.currentHostConfig()
if err := change(&config); err != nil {
return err
}
if err := config.Validate(); err != nil {
return err
}
client.SetOutputDefinitions(config.Melodies, config.StatusEffects)
client.macroMu.Lock()
client.macros = cloneAppMacros(config.Macros)
client.macroMu.Unlock()
client.outputMu.Lock()
client.stripEffects = append([]appconfig.StripEffect(nil), config.StripEffects...)
client.outputMu.Unlock()
client.hostMu.Lock()
client.scripts = cloneStringMap(config.Scripts)
client.automations = cloneAppAutomations(config.Automations)
client.safety = config.Safety
client.rfConfig = cloneRFConfigOrDefault(config.RF)
client.osPolicy = hostos.ClonePolicy(config.OSActions)
client.hostMu.Unlock()
client.optionsMu.Lock()
client.commandOptions.FirmwareFeatures = append(
[]programmer.FirmwareFeature(nil),
config.Programming.FirmwareFeatures...,
)
client.commandOptions.FirmwareFeaturesError = nil
client.optionsMu.Unlock()
return nil
}
func (client *Client) currentCommandOptions() control.CommandOptions {
client.optionsMu.RLock()
defer client.optionsMu.RUnlock()
return client.commandOptions
}
// SetMacros replaces the host-owned macro catalog with a defensive copy.
func (client *Client) SetMacros(macros []Macro) {
client.macroMu.Lock()
client.macros = toAppMacros(macros)
client.macroMu.Unlock()
}
// SetOutputDefinitions replaces the host-owned melody and LED-effect catalogs.
func (client *Client) SetOutputDefinitions(
melodies []Melody,
effects []StatusLEDEffect,
) {
client.outputMu.Lock()
client.melodies = cloneMelodies(melodies)
client.statusEffects = append(
[]appconfig.StatusLEDEffect(nil),
effects...,
)
client.outputMu.Unlock()
}
func (client *Client) currentMelodies() []appconfig.Melody {
client.outputMu.RLock()
defer client.outputMu.RUnlock()
return cloneMelodies(client.melodies)
}
func (client *Client) currentStatusEffects() []appconfig.StatusLEDEffect {
client.outputMu.RLock()
defer client.outputMu.RUnlock()
return append(
[]appconfig.StatusLEDEffect(nil),
client.statusEffects...,
)
}
func (client *Client) currentStripEffects() []appconfig.StripEffect {
client.outputMu.RLock()
defer client.outputMu.RUnlock()
return append([]appconfig.StripEffect(nil), client.stripEffects...)
}
func toAppStripEffects(source []StripEffect) []appconfig.StripEffect {
if source == nil {
return appconfig.DefaultStripEffects()
}
result := make([]appconfig.StripEffect, len(source))
for index, effect := range source {
result[index] = appconfig.StripEffect{
ID: effect.ID, Name: effect.Name, Category: effect.Category,
Description: effect.Description, Program: toAppStripProgram(effect.Program),
DefaultFPS: effect.DefaultFPS, DefaultDurationMS: effect.DefaultDurationMS,
DefaultPixels: effect.DefaultPixels,
}
}
return result
}
func toAppStripProgram(source StripProgram) appconfig.StripProgram {