diff options
Diffstat (limited to 'src/subprocess.go')
-rw-r--r-- | src/subprocess.go | 102 |
1 files changed, 102 insertions, 0 deletions
diff --git a/src/subprocess.go b/src/subprocess.go new file mode 100644 index 0000000..d16d4fe --- /dev/null +++ b/src/subprocess.go @@ -0,0 +1,102 @@ +// vim: shiftwidth=4 tabstop=4 noexpandtab + +package main + +import ( + "log" + "os" + "os/exec" + "path/filepath" + "net" + "net/textproto" + "bufio" +) + +type IpcServer struct { + connections map[string]net.Conn + listener net.Listener +} + +func NewIpcServer() IpcServer { + return IpcServer{ + connections: make(map[string]net.Conn), + } +} + +func (ipc *IpcServer) Run(ipcSocket string) { + log.Println("Running IPC server") + var err error + ipc.listener,err = net.Listen("unix", ipcSocket) + if err != nil { + log.Fatal(err) + } + for { + connection,err := ipc.listener.Accept() + if err != nil { + log.Print(err) + } + bufioreader := bufio.NewReader(connection) + tpreader := textproto.NewReader(bufioreader) + line,err := tpreader.ReadLine() + log.Printf("IPC: '%s'", line) + ipc.connections[line] = connection + go ipc.HandleConnection(line) + } +} + +func (ipc *IpcServer) HandleConnection(connection string) { + for { + msg := ipc.ReadLineFrom(connection) + if msg != "" { + log.Printf("Got IPC message '%s' from '%s'", msg, connection) + if connection == "picamera" { + camera.statemachine.SendEvent(msg) + } + } + } +} + +func (ipc *IpcServer) WriteLineTo(connection string, line string) { + conn := ipc.connections[connection] + _,err := conn.Write([]byte(line)) + if err != nil { + log.Print(err) + } +} + +func (ipc *IpcServer) ReadLineFrom(connection string) string { + conn := ipc.connections[connection] + bufioreader := bufio.NewReader(conn) + tpreader := textproto.NewReader(bufioreader) + line,_ := tpreader.ReadLine() + return line +} + +func (ipc *IpcServer) Cleanup() { + log.Println("Releasing IPC socket ...") + for _,connection := range ipc.connections { + connection.Close() + } + ipc.listener.Close() +} + +func PicameraSubprocess(ipcSocket string) { + var cmd *exec.Cmd + if config.Flag.Debug { + pwd,err := os.Getwd() + if err != nil { + log.Fatal(err) + } + repoDir := filepath.Dir(pwd) + pythonPackage := repoDir + "/python/birdscan" + cmd = exec.Command("python3", pythonPackage, "--debug", "-s", ipcSocket) + } else { + cmd = exec.Command("python3", "/usr/lib/python3.9/site-packages/birdscan/", "-s", ipcSocket) + } + log.Println("Starting picamera service") + err := cmd.Run() + log.Println("picamera service terminated!") + if err != nil { + log.Print(err) + } +} |