/
gamepadblock.go
256 lines (228 loc) · 7.58 KB
/
gamepadblock.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
package commands
import (
"bufio"
"errors"
"fmt"
"io/ioutil"
"log"
"net/http"
"os"
"os/exec"
"runtime"
"strings"
"time"
"github.com/codegangsta/cli"
"github.com/jacobsa/go-serial/serial"
)
// GamepadBlock function returns the CLI commands for pbupdater gamepadblock
func GamepadBlock() cli.Command {
return cli.Command{
Name: "gamepadblock",
Usage: "Installs avrdude, read firmware version, and update firmware of your GamepadBlock",
Action: func(c *cli.Context) {
valid := false
for _, s := range []string{"readversion", "prepare", "update", "memdump"} {
if s == c.Args().First() {
valid = true
}
}
usage := func() {
fmt.Println("Invalid/no subcommand supplied.")
fmt.Println()
fmt.Println("Usage:")
fmt.Println(" petrockutil scan serial")
fmt.Println(" # List all serial device ports")
fmt.Println()
fmt.Println(" petrockutil gamepadblock readversion <port>")
fmt.Println(" # Reads the version number of the current firmware on the GamepadBlock at given port")
fmt.Println()
fmt.Println(" petrockutil gamepadblock prepare")
fmt.Println(" # Installs avrdude to allow uploading of firmware .hex files to GamepadBlock.")
fmt.Println(" # Console needs to be run as administrator.")
fmt.Println()
fmt.Println(" petrockutil gamepadblock update <port>")
fmt.Println(" # Updates firmware of GamepadBlock at provided port to most recent version")
fmt.Println()
fmt.Println(" petrockutil gamepadblock memdump <port>")
fmt.Println(" # Dumps the firmware of the GamepadBlock into the local file gamepadblock_memdump.bin")
fmt.Println()
}
if valid == false {
usage()
return
}
switch c.Args().First() {
case "readversion":
if len(c.Args()) < 2 {
fmt.Println("Invalid number of arguments.")
usage()
return
}
portPath := c.Args()[1]
// Set up options.
options := serial.OpenOptions{
PortName: portPath,
BaudRate: 115200,
DataBits: 8,
StopBits: 1,
MinimumReadSize: 0,
InterCharacterTimeout: 1000,
}
// Open the port.
port, err := serial.Open(options)
if err != nil {
log.Fatalf("serial.Open: %v", err)
}
defer port.Close() // Make sure to close it later.
b := []byte{0x76} // "v"
_, err = port.Write(b)
if err != nil {
log.Fatalf("port.Write: %v", err)
}
buf := make([]byte, 16)
numBytes, err := port.Read(buf)
if err != nil {
fmt.Println("Could not read firmware version on port " + portPath)
return
}
versionString := buf[:numBytes]
fmt.Println("Found GamepadBlock at", portPath, ". The firmware version of it is", string(versionString))
case "prepare":
switch runtime.GOOS {
case "linux":
fmt.Println("Attempting to install avrdude with apt-get...")
cmd := exec.Command("sudo", "apt-get", "-y", "install", "avrdude")
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
if err := cmd.Run(); err != nil {
log.Fatal(err)
}
case "darwin":
fmt.Println("Attempting to install avrdude with Homebrew...")
cmd := exec.Command("brew", "install", "avrdude")
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
if err := cmd.Run(); err != nil {
fmt.Println("Something went wrong. Is brew (https://brew.sh) installed?")
log.Fatal(err)
}
case "windows":
_, err := exec.Command("NET", "SESSION").Output()
if err != nil {
fmt.Println("Please run cmd.exe as administrator and try again")
os.Exit(1)
}
fmt.Println("Installing AVR Tools ...")
fmt.Printf("Initial value for $PATH: %s\n", os.Getenv("PATH"))
dirName, _ := createPetrockblockDirectory()
exeFile := "https://downloads.petrockblock.com/petrockutil/MHV_AVR_Tools_20131101.exe"
fileName := downloadFromUrl(dirName, exeFile)
cmd := exec.Command(petrockblockDirName() + "\\" + fileName)
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
if err := cmd.Run(); err != nil {
log.Fatal(err)
}
fmt.Println("Installation successful. Please restart the console.")
default:
fmt.Println("OS not yet supported.")
}
case "update":
if len(c.Args()) < 2 {
fmt.Println("Invalid number of arguments.")
usage()
return
}
port := c.Args()[1]
file, _ := ioutil.TempFile(os.TempDir(), "")
defer file.Close()
defer os.Remove(file.Name())
fmt.Println("Downloading the latest firmware")
filename := downloadLatestFirmware()
defer os.Remove(filename)
fmt.Println("Downloaded firmware file", filename)
fmt.Println("Press the RESET button on the GameapadBlock to activate its update mode.")
fmt.Print("Press 'Enter' to continue...")
bufio.NewReader(os.Stdin).ReadBytes('\n')
duration := time.Duration(3) * time.Second
time.Sleep(duration)
switch runtime.GOOS {
case "darwin", "linux", "windows":
cmd := exec.Command("avrdude", "-pm32u2", "-cavr109", fmt.Sprintf("-P%v", port), "-D", fmt.Sprintf("-Uflash:w:%v:a", filename))
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
if err := cmd.Run(); err != nil {
log.Fatal(err)
fmt.Println("An error occurred during the firmware update process. Is the port correct?")
}
fmt.Println("Finished firmware update on port", port)
default:
fmt.Println("OS not yet supported.")
}
case "memdump":
if len(c.Args()) < 2 {
fmt.Println("Invalid number of arguments.")
usage()
return
}
port := c.Args()[1]
fmt.Println("Press the RESET button on the GameapadBlock to activate its memory dump mode.")
fmt.Print("Press 'Enter' to continue...")
bufio.NewReader(os.Stdin).ReadBytes('\n')
duration := time.Duration(3) * time.Second
time.Sleep(duration)
filename := "gamepadblock_memdump.bin"
switch runtime.GOOS {
case "darwin", "linux", "windows":
cmd := exec.Command("avrdude", "-pm32u2", "-cavr109", fmt.Sprintf("-P%v", port), "-D", fmt.Sprintf("-Uflash:r:%v:r", filename))
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
if err := cmd.Run(); err != nil {
log.Fatal(err)
fmt.Println("An error occurred during the firmware update process. Is the port correct?")
}
fmt.Println("Finished memory dump on port", port, "to file", filename)
default:
fmt.Println("OS not yet supported.")
}
}
},
}
}
func downloadLatestFirmware() string {
req, err := http.NewRequest("GET", "https://github.com/petrockblog/GamepadBlockUpdater/releases/latest", nil)
if err != nil {
panic(err)
}
client := new(http.Client)
client.CheckRedirect = func(req *http.Request, via []*http.Request) error {
return errors.New("Redirect")
}
response, err := client.Do(req)
currentVersion := ""
if err != nil {
if response.StatusCode == http.StatusFound { //status code 302
tempurl, _ := response.Location()
s := strings.Split(tempurl.Path, "tag/")
_, currentVersion = s[0], s[1]
if currentVersion != "" {
fmt.Println("Most current firmware version is", currentVersion)
downloadURL := tempurl.Scheme + "://" + tempurl.Host + tempurl.Path
fmt.Println(downloadURL)
downloadURL = strings.Replace(downloadURL, "releases/tag", "releases/download", 1)
downloadURL += "/firmware.hex"
downloadedFile := downloadFromUrl(".", downloadURL)
if downloadedFile == "" {
panic("Could not download latest firmware file.")
} else {
return downloadedFile
}
} else {
fmt.Println("Could not determine most recent firmware version")
}
} else {
panic(err)
}
}
return ""
}