-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathaxon.go
266 lines (219 loc) · 9.61 KB
/
axon.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
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
/*
* Copyright (c) Clinton Freeman 2013
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of this software and
* associated documentation files (the "Software"), to deal in the Software without restriction,
* including without limitation the rights to use, copy, modify, merge, publish, distribute,
* sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all copies or
* substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT
* NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
* DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
package main
import (
"bytes"
"encoding/binary"
"fmt"
"github.com/huin/goserial"
"io"
"io/ioutil"
"net/http"
"strings"
"time"
)
const (
waitLength = 90.0
waitTimeout = 180.0
startupLength = 63.0
cooldownLength = 20.0
powerupLength = 26.0
nanoToSeconds = 1000000000.0
)
type Neurone struct {
energy float32
deltaE chan float32
duration float64
start int64
config Configuration
}
type stateFn func(neurone Neurone, serialPort io.ReadWriteCloser) (sF stateFn, newNeurone Neurone)
// sendArduinoCommand transmits a new command over the numonated serial port to the arduino. Returns an
// error on failure. Each command is identified by a single byte and may take one argument (a float).
func sendArduinoCommand(command byte, argument float32, serialPort io.ReadWriteCloser) error {
if serialPort == nil {
return nil
}
// Package argument for transmission
bufOut := new(bytes.Buffer)
err := binary.Write(bufOut, binary.LittleEndian, argument)
if err != nil {
return err
}
// Transmit command and argument down the pipe.
for _, v := range [][]byte{[]byte{command}, bufOut.Bytes()} {
_, err = serialPort.Write(v)
if err != nil {
return err
}
}
return nil
}
// updateArduinoEnergy transmits a new energy level over the nominated serial port to the arduino. Returns an error
// on failure, nil otherwise. Arduino code takes the energy level and turns it into a lighting sequence.
func updateArduinoEnergy(energy float32, serialPort io.ReadWriteCloser) error {
return sendArduinoCommand('e', energy, serialPort)
}
// cooldownArduino transmits updates the cooldown lighting sequence on the arduino. Returns an error on failure, nil
// otherwise.
func cooldownArduino(energy float32, serialPort io.ReadWriteCloser) error {
return sendArduinoCommand('c', energy, serialPort)
}
// powerupArduino puts the arduino into a short powerup animation, indicating that the neurone has recieved a
// large burst of energy. Returns an error on failure, nil otherwise.
func powerupArduino(serialPort io.ReadWriteCloser) error {
return sendArduinoCommand('p', 0.0, serialPort)
}
// findArduino looks for the file that represents the arduino serial connection. Returns the fully qualified path
// to the device if we are able to find a likely candidate for an arduino, otherwise an empty string if unable to
// find an arduino device.
func findArduino() string {
contents, _ := ioutil.ReadDir("/dev")
// Look for the arduino device
for _, f := range contents {
if strings.Contains(f.Name(), "tty.usbserial") ||
strings.Contains(f.Name(), "ttyUSB") {
return "/dev/" + f.Name()
}
}
// Have not been able to find the device.
return ""
}
// wait puts the neurone in a holding state untill all the raspberry pi's have started up. Then
// puts all the neurones through a non-interactive animated sequence.
func wait(neurone Neurone, serialPort io.ReadWriteCloser) (sF stateFn, newNeurone Neurone) {
// Calculate how many seconds have elapsed since this cooldown state started.
dt := float64(time.Now().UnixNano()-neurone.start) / nanoToSeconds
if neurone.config.MasterNeurone {
// Drain off an ignore energy from the dendrites.
select {
case <-neurone.deltaE:
case <-time.After(5 * time.Millisecond):
}
if dt >= neurone.duration {
for _, adjacent := range neurone.config.AllNeurones {
buf := new(bytes.Buffer)
fmt.Fprintf(buf, "%s?e=%f", adjacent.Address, adjacent.Transfer)
address := buf.String()
go http.Get(address)
fmt.Printf("INFO: S[" + address + "]\n")
}
return startup, Neurone{0.0, neurone.deltaE, startupLength, time.Now().UnixNano(), neurone.config}
}
} else {
// Neurone is not the master, wait to be notified by the master before startup.
de := <-neurone.deltaE
if de < -0.5 {
return startup, Neurone{0.0, neurone.deltaE, startupLength, time.Now().UnixNano(), neurone.config}
} else if dt >= waitTimeout {
// If for some reason we don't get notified by the master neurone to enter the animation, just jump
// straight to interactive mode.
return accumulate, Neurone{0.0, neurone.deltaE, 0.0, time.Now().UnixNano(), neurone.config}
}
}
return wait, Neurone{-2.0, neurone.deltaE, neurone.duration, neurone.start, neurone.config}
}
// startup puts the neurone through a non-interactive animated sequence before entering the animated
// mode.
func startup(neurone Neurone, serialPort io.ReadWriteCloser) (sF stateFn, newNeurone Neurone) {
// The startup animation and cooldown animation are the same, just over different durations.
return cooldown(neurone, serialPort)
}
// accumulate pulls energy off the dendrites and accumulates it within the neurone. When the neurone reaches
// critical it fires into the axon (the web dendrites of adjacent neurones) and enters the cooldown state.
func accumulate(neurone Neurone, serialPort io.ReadWriteCloser) (sF stateFn, newNeurone Neurone) {
de := <-neurone.deltaE
newEnergy := neurone.energy + de
// Neurone has reached threshold. Fire axon.
if newEnergy > 1.0 {
// Axon fires into the web dendrites of adjacent neurones.
for _, adjacent := range neurone.config.AdjacentNeurones {
buf := new(bytes.Buffer)
fmt.Fprintf(buf, "%s?e=%f", adjacent.Address, adjacent.Transfer)
address := buf.String()
go http.Get(address)
fmt.Printf("INFO: a[" + address + "]\n")
}
fmt.Printf("INFO: cooldown!\n")
return cooldown, Neurone{newEnergy, neurone.deltaE, cooldownLength, time.Now().UnixNano(), neurone.config}
}
// If the energy level jumps by a large amount, another neuron has fired. Run a power
// up flash animation.
if de > neurone.config.PowerUpThreshold {
fmt.Printf("INFO: powerup!\n")
powerupArduino(serialPort)
return powerup, Neurone{newEnergy, neurone.deltaE, powerupLength, time.Now().UnixNano(), neurone.config}
}
// Slowly decay the energy of the neurone over time.
dt := float64(time.Now().UnixNano()-neurone.start) / nanoToSeconds
newEnergy = newEnergy - float32(dt*neurone.config.DecayPerSecond)
// Ensure the energy of the neurone is never below zero.
if newEnergy < 0.0 {
newEnergy = 0.0
}
updateArduinoEnergy(newEnergy, serialPort)
return accumulate, Neurone{newEnergy, neurone.deltaE, 0.0, time.Now().UnixNano(), neurone.config}
}
// calcDt calculates the change in seconds since an animation was started.
func calcDt(neurone Neurone) float64 {
// Drain off and ignore changes in energy from the dendrites.
select {
case <-neurone.deltaE:
case <-time.After(250 * time.Millisecond):
}
// Calculate how many seconds have elapsed since this cooldown state started.
return float64(time.Now().UnixNano()-neurone.start) / nanoToSeconds
}
// powerup allows the neurone to display a large jump in energy to the neurone. It pauses the accumlation
// by the nominated duration before starting accumulation of energy from the dendrites again.
func powerup(neurone Neurone, serialPort io.ReadWriteCloser) (sF stateFn, newNeurone Neurone) {
dt := calcDt(neurone)
if dt >= neurone.duration {
return accumulate, Neurone{neurone.energy, neurone.deltaE, 0.0, time.Now().UnixNano(), neurone.config}
}
return powerup, neurone
}
// cooldown allows the neurone to cooldown after firing into the axon, it pauses accumulation by the
// nominated duration before starting accumulation of energy from the dendrites again.
func cooldown(neurone Neurone, serialPort io.ReadWriteCloser) (sF stateFn, newNeurone Neurone) {
dt := calcDt(neurone)
// LERP neurone energy from -1.0 to 0.0 over the duration of the cooldown.
newEnergy := float32(dt / neurone.duration)
// If the time elapsed is longer than the duration of the cooldown, enter the accumulate state.
if dt >= neurone.duration {
return accumulate, Neurone{0.0, neurone.deltaE, 0.0, time.Now().UnixNano(), neurone.config}
}
cooldownArduino(newEnergy, serialPort)
return cooldown, Neurone{newEnergy, neurone.deltaE, neurone.duration, neurone.start, neurone.config}
}
// Axon listens to the dentrites on the deltaE channel, and embodies an artificial neurone. When the energy
// of the neurone reaches a maximum, it fires into the axon (the web dendites of adjacent neurones).
func axon(deltaE chan float32, config Configuration) {
// Find the device that represents the arduino serial connection.
c := &goserial.Config{Name: findArduino(), Baud: 9600}
s, _ := goserial.OpenPort(c)
// When connecting to an older revision arduino, you need to wait a little while it resets.
time.Sleep(1 * time.Second)
neurone := Neurone{-2.0, deltaE, waitLength, time.Now().UnixNano(), config}
state := wait
for {
state, neurone = state(neurone, s)
fmt.Printf("INFO: e[%f]\n", neurone.energy)
}
}