/
completer_deviceId_sigfox.go
52 lines (47 loc) · 1.36 KB
/
completer_deviceId_sigfox.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
package sorashell
import (
"encoding/json"
"fmt"
"github.com/c-bata/go-prompt"
"strings"
"time"
)
// naive cache which holds sigfox devices data for sigfoxDeviceIDFilterSuggestions
var sigfoxDevicesCache []prompt.Suggest
func (s *SoracomCompleter) sigfoxDeviceIDFilterSuggestions(word string) []prompt.Suggest {
c := make(chan []prompt.Suggest, 1024)
if len(sigfoxDevicesCache) == 0 {
go getSigfoxDevices(c, s.worker)
select {
case res := <-c:
sigfoxDevicesCache = res
case <-time.After(10 * time.Second):
return []prompt.Suggest{{
Text: "Downloading device information in background",
Description: "Hit space to see latest",
}}
}
}
return filterFunc(sigfoxDevicesCache, word, filterTextOrDescriptionFuzzy)
}
var getSigfoxDevices = func(c chan<- []prompt.Suggest, worker *SoracomWorker) {
var r []prompt.Suggest
result := worker.Execute("sigfox-devices list --fetch-all")
if err := json.NewDecoder(strings.NewReader(result)).Decode(&sigfoxDevices); err != nil {
c <- []prompt.Suggest{{
Text: "Error while running 'sigfox-devices list --fetch-all'",
Description: err.Error(),
}}
}
for _, device := range sigfoxDevices {
r = append(r, prompt.Suggest{
Text: device.DeviceID,
Description: fmt.Sprintf("%-24s | %-8s | %-8s",
trunc(device.Tags.Name, 24),
device.Status,
device.DeviceID,
),
})
}
c <- r
}