/
display.go
146 lines (123 loc) · 2.5 KB
/
display.go
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
package device
import (
"github.com/sirupsen/logrus"
"image"
_ "image/png"
"log"
"periph.io/x/conn/v3/i2c/i2creg"
"periph.io/x/devices/v3/ssd1306"
"periph.io/x/host/v3"
)
func NewDisplay(simulationMode bool) *Display {
if _, err := host.Init(); err != nil {
log.Fatal(err)
}
device := Display{
simulationMode: simulationMode,
askDone: make(chan bool),
askImg: make(chan image.Image),
done: make(chan bool),
}
return &device
}
func (d *Display) Start() {
logrus.Infof("Start display device")
d.on = true
if d.simulationMode {
d.startSimulation()
} else {
var err error
// Open a handle to the first available I²C bus:
d.i2cBus, err = i2creg.Open("")
if err != nil {
logrus.Fatalf("Unable to open i2c bus: %v\n", err)
}
// Open a handle to a ssd1306 connected on the I²C bus:
d.oledDisplay, err = ssd1306.NewI2C(d.i2cBus, &ssd1306.DefaultOpts)
if err != nil {
logrus.Fatalf("Unable to initialize oled display: %v\n", err)
}
d.oledDisplay.SetContrast(1)
go func() {
for loop := true; loop; {
select {
case <-d.askDone:
loop = false
case newImg := <-d.askImg:
d.oledLock.Lock()
d.oledDisplay.Draw(d.oledDisplay.Bounds(), newImg, image.Point{})
d.oledLock.Unlock()
}
}
d.oledLock.Lock()
d.i2cBus.Close()
d.oledLock.Unlock()
d.done <- true
}()
}
}
func (d *Display) Stop() {
logrus.Infof("Stop display device")
if d.simulationMode {
d.closeSimulationWindow()
} else {
d.askDone <- true
<-d.done
}
}
func (d *Display) SetOff() {
d.lock.Lock()
defer d.lock.Unlock()
d.setOff()
}
func (d *Display) setOff() {
d.on = false
if !d.simulationMode {
d.oledLock.Lock()
d.oledDisplay.Halt()
d.oledLock.Unlock()
}
}
func (d *Display) SetOn() {
d.lock.Lock()
defer d.lock.Unlock()
d.setOn()
}
func (d *Display) setOn() {
d.on = true
if d.simulationMode {
d.invalidateSimulationWindow()
} else {
d.oledLock.Lock()
d.oledDisplay.SetContrast(1) // Hack to force display on (calling Draw() is not enough)
d.oledLock.Unlock()
d.askImg <- d.lastImg
}
}
func (d *Display) Switch() bool {
d.lock.Lock()
defer d.lock.Unlock()
if d.on {
d.setOff()
} else {
d.setOn()
}
return d.on
}
func (d *Display) IsOn() bool {
d.lock.RLock()
defer d.lock.RUnlock()
return d.on
}
func (d *Display) ShowImage(img image.Image) {
d.lock.Lock()
defer d.lock.Unlock()
d.lastImg = img
if d.on {
if d.simulationMode {
d.invalidateSimulationWindow()
} else {
d.askImg <- img
}
}
}