import "fmt"
import "net"
import "bufio"
+import "strings"
+import "os"
+import "io"
+
+var cmdHandler = map[string]func([]string,string,*bufio.ReadWriter ) {
+ "test":handleCmdTest,
+ "open":handleCmdController,
+ "close":handleCmdController,
+ "toggle":handleCmdController,
+}
+
func readLineSafe(rw *bufio.ReadWriter) (string, error) {
wasPrefix:=false
return line,nil
}
-func connToReadWriter(c net.Conn) (*bufio.ReadWriter) {
+func connToReadWriter(c io.Reader,cw io.Writer) (*bufio.ReadWriter) {
client_r := bufio.NewReaderSize(c,14)
- client_w := bufio.NewWriterSize(c,14)
+ client_w := bufio.NewWriterSize(cw,14)
return bufio.NewReadWriter(client_r,client_w)
}
func handleConnection(c net.Conn) () {
- client:=connToReadWriter(c)
+ client:=connToReadWriter(c,c)
fmt.Println("new connection")
for {
line,err:=readLineSafe(client)
if err != nil {
- fmt.Println(err.Error())
+ if err.Error() != "EOF" {
+ fmt.Printf("Error: readLineSafe returned %v\n",err.Error())
+ } else {
+ fmt.Printf("Connection closed by remote host\n");
+ }
c.Close()
return
}
if line == "" {
continue
}
- fmt.Printf("Received: %v\n", string(line))
+ fmt.Printf("Received: %v\n", line)
+ tokens:=strings.Fields(line)
+ remainStr:=strings.Join(tokens[1:]," ")
+ handleCmd(tokens,remainStr,client)
}
}
+func handleCmd(tokens []string, remainStr string,client * bufio.ReadWriter) {
+ cmd:=tokens[0]
+ func_ptr,present := cmdHandler[cmd]
+ if present {
+ func_ptr(tokens, remainStr,client)
+ } else {
+ fmt.Printf("Error: unknown Cmd: %v\n", cmd)
+ }
+}
+
+func handleCmdTest(tokens []string, remainStr string, client * bufio.ReadWriter) {
+ //cmd:=tokens[0]
+ fmt.Printf("Test: %v\n", remainStr)
+}
+
+func handleCmdController(tokens []string, remainStr string, client * bufio.ReadWriter) {
+ cmd:=tokens[0]
+ s_r:=strings.NewReader(cmd)
+ char := make([]byte,1)
+ s_r.Read(char)
+ fmt.Println(string(char))
+}
+
+
+func openTTY(name string) *bufio.ReadWriter{
+ file, err := os.OpenFile(name,os.O_RDWR ,0600) // For read access.
+ if err != nil {
+ fmt.Println(err.Error())
+ }
+ return connToReadWriter(file,file)
+}
func main() {
+ serial:=openTTY("tty")
+ serial.WriteString("foo")
+ serial.Flush()
ln, err := net.Listen("unix", "/tmp/test.sock")
if err != nil {
fmt.Printf("Error: %s\n",err.Error())