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
|
package main
import (
"bufio"
"encoding/json"
"fmt"
"log"
"net"
"os"
"os/exec"
"path/filepath"
"strconv"
"strings"
"sync"
"time"
)
// Brightness mappings - perceptual curves, as a percentage of the panel's
// maximum. Percentages (rather than raw sysfs values) because the kernel's
// max_brightness is not stable: the amdgpu driver reports 255 on some
// versions and 65535 on others, and a curve of raw values silently becomes
// a curve of near-black once the scale changes underneath it.
var (
brightnessMappingInternal = []int{0, 1, 2, 2, 4, 5, 8, 14, 20, 33, 47, 58, 78, 100}
brightnessMappingExternal = []int{0, 0, 0, 0, 0, 0, 12, 24, 36, 48, 60, 72, 84, 100}
maxBrightnessVal = len(brightnessMappingInternal) - 1
)
// VarlinkCall represents a Varlink method call (request)
type VarlinkCall struct {
Method string `json:"method"`
Parameters map[string]any `json:"parameters,omitempty"`
More bool `json:"more,omitempty"`
}
// VarlinkReply represents a Varlink method reply (response)
type VarlinkReply struct {
Parameters map[string]any `json:"parameters,omitempty"`
Continues bool `json:"continues,omitempty"`
Error string `json:"error,omitempty"`
}
// ParameterSchema describes a parameter's type and purpose
type ParameterSchema struct {
Type string `json:"type"`
Description string `json:"description"`
}
// ActionSuggestion represents one way to invoke a method with specific parameters
type ActionSuggestion struct {
ID string `json:"id,omitempty"`
Description string `json:"description"`
Parameters map[string]any `json:"parameters"`
}
// Action represents a method with its parameter schema and suggested invocations (HATEOAS)
type Action struct {
Method string `json:"method"`
ParameterSchema map[string]ParameterSchema `json:"parameter_schema"`
Suggestions []ActionSuggestion `json:"suggestions"`
}
// BrightnessController manages display brightness
type BrightnessController struct {
currentBrightness int
mu sync.Mutex
externalQueue chan int
}
func NewBrightnessController() (*BrightnessController, error) {
brightness, err := getInitialInternalMonitorBrightness()
if err != nil {
log.Printf("Warning: failed to get initial brightness: %v\n", err)
brightness = 7 // default to middle value
}
bc := &BrightnessController{
currentBrightness: brightness,
externalQueue: make(chan int, 10),
}
// Start external monitor brightness updater
go bc.externalBrightnessWorker()
return bc, nil
}
// blightGetInt runs `blight get <what>` and parses the result.
func blightGetInt(what string) (int, error) {
out, err := exec.Command("blight", "get", what).Output()
if err != nil {
return 0, fmt.Errorf("failed to get %s: %w", what, err)
}
value, err := strconv.Atoi(strings.TrimSpace(string(out)))
if err != nil {
return 0, fmt.Errorf("failed to parse %s: %w", what, err)
}
return value, nil
}
// getInitialInternalMonitorBrightness reads current brightness from blight and
// maps it back onto our curve. `blight get` only reports raw sysfs values, so
// the reading is converted to a percentage of max_brightness first.
func getInitialInternalMonitorBrightness() (int, error) {
brightness, err := blightGetInt("brightness")
if err != nil {
return 0, err
}
maxBrightness, err := blightGetInt("max-brightness")
if err != nil {
return 0, err
}
if maxBrightness <= 0 {
return 0, fmt.Errorf("nonsensical max-brightness %d", maxBrightness)
}
percent := brightness * 100 / maxBrightness
// Find corresponding brightness value in mapping
for i, val := range brightnessMappingInternal {
if val >= percent {
return i, nil
}
}
return maxBrightnessVal, nil
}
// setBrightnessAllMonitors sets brightness for all monitors
func (bc *BrightnessController) setBrightnessAllMonitors(brightnessVal int) error {
bc.mu.Lock()
bc.currentBrightness = brightnessVal
bc.mu.Unlock()
// Clamp value
if brightnessVal < 0 {
brightnessVal = 0
}
if brightnessVal > maxBrightnessVal {
brightnessVal = maxBrightnessVal
}
// Set internal monitor. `blight` scales a percentage against the panel's
// own max_brightness, so this stays correct whatever scale the kernel
// reports.
internalBrightness := brightnessMappingInternal[brightnessVal]
log.Printf("Setting internal monitor brightness to %d%%\n", internalBrightness)
internalErr := exec.Command("blight", "set", strconv.Itoa(internalBrightness)+"%").Run()
if internalErr != nil {
log.Printf("Warning: failed to set internal brightness: %v\n", internalErr)
}
// Queue external monitor update (debounced)
externalBrightness := brightnessMappingExternal[brightnessVal]
select {
case bc.externalQueue <- externalBrightness:
default:
// Channel full, replace last value
select {
case <-bc.externalQueue:
default:
}
bc.externalQueue <- externalBrightness
}
if internalErr == nil {
log.Printf("Successfully set brightness to level %d\n", brightnessVal)
}
return nil
}
// externalBrightnessWorker handles debounced external monitor updates
func (bc *BrightnessController) externalBrightnessWorker() {
for brightness := range bc.externalQueue {
// Debounce: wait 250ms to collect any additional changes
time.Sleep(250 * time.Millisecond)
// Drain all pending values from the queue, keeping only the last one
lastBrightness := brightness
drainedCount := 0
for {
select {
case newBrightness := <-bc.externalQueue:
lastBrightness = newBrightness
drainedCount++
default:
// No more values in queue
goto done
}
}
done:
if drainedCount > 0 {
log.Printf("Drained %d brightness updates, using final value: %d\n", drainedCount, lastBrightness)
}
if err := setExternalBrightness(lastBrightness); err != nil {
log.Printf("Warning: failed to set external brightness: %v\n", err)
}
}
}
// setExternalBrightness sets brightness for external monitors via ddcutil
func setExternalBrightness(brightness int) error {
// Try to read ddcci devices
devices, err := os.ReadDir("/dev/bus/ddcci")
if err != nil {
log.Printf("Info: /dev/bus/ddcci not found, using ddcutil auto-detect\n")
return setDdcciBrightness("", brightness)
}
log.Printf("Found %d ddcci device(s)\n", len(devices))
for _, device := range devices {
if err := setDdcciBrightness(device.Name(), brightness); err != nil {
log.Printf("Warning: failed to set brightness for device %s: %v\n", device.Name(), err)
}
}
return nil
}
// setDdcciBrightness sets brightness for a specific ddcci device
func setDdcciBrightness(device string, brightness int) error {
deviceName := "all devices"
if device != "" {
deviceName = fmt.Sprintf("device %s", device)
}
log.Printf("Setting external monitor brightness to %d for %s\n", brightness, deviceName)
args := []string{"--sleep-multiplier", "0.20", "setvcp", "0x10", strconv.Itoa(brightness)}
if device != "" {
args = append([]string{"--bus", device}, args...)
}
cmd := exec.Command("ddcutil", args...)
out, err := cmd.CombinedOutput()
if err != nil {
outStr := string(out)
if strings.Contains(outStr, "No monitor detected on bus") {
log.Printf("External monitor on bus %s is gone, ignoring\n", deviceName)
return nil
}
return fmt.Errorf("ddcutil failed: %w: %s", err, outStr)
}
return nil
}
// buildAvailableActions generates HATEOAS-style action suggestions based on current brightness
func buildAvailableActions(currentBrightness int) []Action {
actions := []Action{}
// Absolute brightness action
actions = append(actions, Action{
Method: "de.profpatsch.DisplayBrightness.SetBrightnessAllMonitors",
ParameterSchema: map[string]ParameterSchema{
"brightness": {
Type: "int",
Description: "Brightness level (0-13)",
},
},
Suggestions: []ActionSuggestion{
{
ID: "brightness_absolute",
Description: fmt.Sprintf("Set brightness to level %d", currentBrightness),
Parameters: map[string]any{
"brightness": currentBrightness,
},
},
},
})
// Relative brightness adjustments
relativeAction := Action{
Method: "de.profpatsch.DisplayBrightness.SetBrightnessAllMonitorsRelative",
ParameterSchema: map[string]ParameterSchema{
"direction": {
Type: "string",
Description: "Amount to adjust brightness (+ or -, with optional step count)",
},
},
Suggestions: []ActionSuggestion{},
}
// Add decrease suggestions if not at minimum
if currentBrightness > 0 {
relativeAction.Suggestions = append(relativeAction.Suggestions, ActionSuggestion{
ID: "brightness_dec_1",
Description: "Decrease brightness by 1 level",
Parameters: map[string]any{"direction": "-"},
})
if currentBrightness >= 5 {
relativeAction.Suggestions = append(relativeAction.Suggestions, ActionSuggestion{
ID: "brightness_dec_5",
Description: "Decrease brightness by 5 levels",
Parameters: map[string]any{"direction": "-5"},
})
}
}
// Add increase suggestions if not at maximum
if currentBrightness < maxBrightnessVal {
relativeAction.Suggestions = append(relativeAction.Suggestions, ActionSuggestion{
ID: "brightness_inc_1",
Description: "Increase brightness by 1 level",
Parameters: map[string]any{"direction": "+"},
})
if currentBrightness <= maxBrightnessVal-5 {
relativeAction.Suggestions = append(relativeAction.Suggestions, ActionSuggestion{
ID: "brightness_inc_5",
Description: "Increase brightness by 5 levels",
Parameters: map[string]any{"direction": "+5"},
})
}
}
// Only add relative action if there are suggestions
if len(relativeAction.Suggestions) > 0 {
actions = append(actions, relativeAction)
}
return actions
}
// VarlinkServer handles Varlink protocol
type VarlinkServer struct {
bc *BrightnessController
}
func NewVarlinkServer(bc *BrightnessController) *VarlinkServer {
return &VarlinkServer{bc: bc}
}
func (vs *VarlinkServer) handleConnection(conn net.Conn) {
defer conn.Close()
log.Println("Varlink client connected")
scanner := bufio.NewScanner(conn)
scanner.Split(func(data []byte, atEOF bool) (advance int, token []byte, err error) {
// Split on null byte
if i := strings.IndexByte(string(data), 0); i >= 0 {
return i + 1, data[0:i], nil
}
if atEOF && len(data) > 0 {
return len(data), data, nil
}
return 0, nil, nil
})
for scanner.Scan() {
msg := scanner.Bytes()
log.Printf("Received: %s\n", msg)
var request VarlinkCall
if err := json.Unmarshal(msg, &request); err != nil {
log.Printf("Failed to parse request: %v\n", err)
continue
}
response := vs.handleMethod(request)
responseBytes, _ := json.Marshal(response)
responseBytes = append(responseBytes, 0) // Add null terminator
if _, err := conn.Write(responseBytes); err != nil {
log.Printf("Failed to write response: %v\n", err)
return
}
}
if err := scanner.Err(); err != nil {
log.Printf("Scanner error: %v\n", err)
}
log.Println("Varlink client disconnected")
}
func (vs *VarlinkServer) handleMethod(request VarlinkCall) VarlinkReply {
switch request.Method {
case "org.varlink.service.GetInfo":
return VarlinkReply{
Parameters: map[string]any{
"vendor": "Profpatsch",
"product": "Display Brightness Control",
"version": "0.1",
"url": "none",
"interfaces": []string{"de.profpatsch.DisplayBrightness"},
},
}
case "org.varlink.service.GetInterfaceDescription":
iface, _ := request.Parameters["interface"].(string)
// Strip method name if provided (e.g., "de.profpatsch.DisplayBrightness.SetBrightness" -> "de.profpatsch.DisplayBrightness")
if idx := strings.LastIndex(iface, "."); idx != -1 {
baseIface := iface[:idx]
if baseIface == "de.profpatsch.DisplayBrightness" {
iface = baseIface
}
}
if iface == "de.profpatsch.DisplayBrightness" {
return VarlinkReply{
Parameters: map[string]any{
"description": `# Display brightness controller for ThinkPad T14s
# Controls brightness for both internal (via blight) and external monitors (via ddcutil)
# Uses hardware-specific brightness curves optimized for this device
interface de.profpatsch.DisplayBrightness
# Parameter schema describes a parameter's type and purpose
type ParameterSchema (
type: string,
description: string
)
# Action suggestion represents one way to invoke a method
type ActionSuggestion (
id: string,
description: string,
parameters: object
)
# Action represents a method with its schema and suggested invocations
type Action (
method: string,
parameter_schema: [string]ParameterSchema,
suggestions: []ActionSuggestion
)
# Set absolute brightness level for all monitors
# brightness: integer from 0-13 representing brightness level (mapped to hardware-specific values)
# Returns current brightness and available actions for HATEOAS navigation
method SetBrightnessAllMonitors(brightness: int) -> (current_brightness: int, available_actions: []Action)
# Adjust brightness relative to current level
# direction: "+" or "-" for single step, "+N" or "-N" for N steps (saturates at 0-13 range)
# Examples: "+", "-", "+5", "-3", "5" (treated as +5)
# Returns current brightness and available actions for HATEOAS navigation
method SetBrightnessAllMonitorsRelative(direction: string) -> (current_brightness: int, available_actions: []Action)
`,
},
}
}
return VarlinkReply{Error: "UnknownInterface"}
case "de.profpatsch.DisplayBrightness.SetBrightnessAllMonitors":
brightness, ok := request.Parameters["brightness"].(float64)
if !ok {
return VarlinkReply{Error: "InvalidParameter"}
}
log.Printf("SetBrightnessAllMonitors called with %d\n", int(brightness))
if err := vs.bc.setBrightnessAllMonitors(int(brightness)); err != nil {
return VarlinkReply{Error: err.Error()}
}
// Get updated brightness and build available actions
vs.bc.mu.Lock()
finalBrightness := vs.bc.currentBrightness
vs.bc.mu.Unlock()
actions := buildAvailableActions(finalBrightness)
return VarlinkReply{
Parameters: map[string]any{
"current_brightness": finalBrightness,
"available_actions": actions,
},
}
case "de.profpatsch.DisplayBrightness.SetBrightnessAllMonitorsRelative":
direction, ok := request.Parameters["direction"].(string)
if !ok {
return VarlinkReply{Error: "InvalidParameter"}
}
log.Printf("SetBrightnessAllMonitorsRelative called with %s\n", direction)
vs.bc.mu.Lock()
currentBrightness := vs.bc.currentBrightness
vs.bc.mu.Unlock()
// Parse direction parameter - supports:
// "+" or "-" for single step (backwards compatible)
// "+N" or "-N" for N steps
// "N" (positive number) for +N steps
var delta int
switch direction {
case "+":
delta = 1
case "-":
delta = -1
default:
// Try parsing as integer
parsedDelta, err := strconv.Atoi(direction)
if err != nil {
return VarlinkReply{Error: "InvalidDirection"}
}
delta = parsedDelta
}
// Apply delta with saturation
newBrightness := max(currentBrightness+delta, 0)
if newBrightness > maxBrightnessVal {
newBrightness = maxBrightnessVal
}
if err := vs.bc.setBrightnessAllMonitors(newBrightness); err != nil {
return VarlinkReply{Error: err.Error()}
}
// Get updated brightness and build available actions
vs.bc.mu.Lock()
finalBrightness := vs.bc.currentBrightness
vs.bc.mu.Unlock()
actions := buildAvailableActions(finalBrightness)
return VarlinkReply{
Parameters: map[string]any{
"current_brightness": finalBrightness,
"available_actions": actions,
},
}
default:
log.Printf("Unknown method: %s\n", request.Method)
return VarlinkReply{Error: "UnknownMethod"}
}
}
func main() {
socketPath := filepath.Join("/run/user", strconv.Itoa(os.Getuid()), "de.Profpatsch.DisplayBrightness")
// Remove existing socket
os.Remove(socketPath)
// Create brightness controller
bc, err := NewBrightnessController()
if err != nil {
log.Fatalf("Failed to create brightness controller: %v\n", err)
}
log.Printf("Current brightness: %d\n", bc.currentBrightness)
// Create Varlink server
server := NewVarlinkServer(bc)
// Listen on Unix socket
listener, err := net.Listen("unix", socketPath)
if err != nil {
log.Fatalf("Failed to listen on socket: %v\n", err)
}
defer listener.Close()
log.Printf("Listening on %s\n", socketPath)
for {
conn, err := listener.Accept()
if err != nil {
log.Printf("Accept error: %v\n", err)
continue
}
go server.handleConnection(conn)
}
}
|