/
main.go
92 lines (76 loc) · 1.7 KB
/
main.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
package main
import (
"flag"
"fmt"
"log"
"net"
"github.com/tarm/serial"
)
func main() {
bindAddress := flag.String("bind-address", "0.0.0.0", "A host name or ip address for the server to bind to")
port := flag.String("port", "9595", "A port for the server to listen on")
scopeDevice := flag.String("device", "", "The device that the telescope should connected to")
flag.Parse()
socketChan := make(chan []byte)
scopeChan := make(chan []byte)
c := &serial.Config{Name: *scopeDevice, Baud: 9600}
s, err := serial.OpenPort(c)
if err == nil {
defer s.Close()
go readFromTelescope(s, socketChan)
go writeToTelescope(s, scopeChan)
} else {
log.Fatal("Failed to connect to the telescope")
}
ln, err := net.Listen("tcp", *bindAddress+":"+*port)
if err == nil {
defer ln.Close()
for {
conn, err := ln.Accept()
if err == nil {
go readFromSocket(conn, scopeChan)
go writeToSocket(conn, socketChan)
}
}
} else {
log.Fatalf("Failed to connect to %s:%s", *bindAddress, *port)
}
}
func readFromSocket(c net.Conn, channel chan []byte) {
for {
buf := make([]byte, 1024)
bytesRead, err := c.Read(buf)
if err == nil {
channel <- buf[:bytesRead]
} else {
return
}
}
}
func writeToSocket(c net.Conn, channel chan []byte) {
for {
data := <-channel
_, err := c.Write(data)
if err != nil {
fmt.Println(err)
c.Close()
return
}
}
}
func readFromTelescope(s *serial.Port, channel chan []byte) {
for {
buf := make([]byte, 1024)
bytesRead, _ := s.Read(buf)
fmt.Println(buf[:bytesRead])
channel <- buf[:bytesRead]
}
}
func writeToTelescope(s *serial.Port, channel chan []byte) {
for {
data := <-channel
fmt.Println(data)
s.Write(data)
s.Flush()
}
}