diff --git a/cmd/start.go b/cmd/start.go index d04f99c..0857a5a 100644 --- a/cmd/start.go +++ b/cmd/start.go @@ -17,26 +17,25 @@ package cmd import ( "fmt" - "it2000.com.cn/tele-recv/utils" "log" "os" "os/signal" "syscall" + "it2000.com.cn/tele-recv/utils" + "github.com/spf13/cobra" ) // startCmd represents the start command var startCmd = &cobra.Command{ Use: "start", - Short: "A brief description of your command", - Long: `A longer description that spans multiple lines and likely contains examples -and usage of using your command. For example: - -Cobra is a CLI library for Go that empowers applications. -This application is a tool to generate the needed files -to quickly create a Cobra application.`, - Run: start, + Short: "start telegram receive service", + Long: `open serial port + start a tcp server for processing`, + Run: func(cmd *cobra.Command, args []string) { + start() + }, } func init() { @@ -53,7 +52,7 @@ func init() { // startCmd.Flags().BoolP("toggle", "t", false, "Help message for toggle") } -func start(cmd *cobra.Command, args []string) { +func start() { // Go signal notification works by sending `os.Signal` // values on a channel. We'll create a channel to // receive these notifications (we'll also make one to @@ -74,6 +73,7 @@ func start(cmd *cobra.Command, args []string) { fmt.Println() fmt.Println(sig) utils.ServerRunning = false + utils.StopSocketServer() done <- true }() @@ -82,7 +82,7 @@ func start(cmd *cobra.Command, args []string) { // above sending a value on `done`) and then exit. fmt.Println("awaiting signal") _ = utils.InitDb(dbFile, dbInit) - utils.Listen(socketAddress) + go utils.Listen(socketAddress) for utils.ServerRunning { if !utils.IsPortOpen() { log.Println("try to open port") diff --git a/cmd/test.go b/cmd/test.go index 754a9a1..18c2391 100644 --- a/cmd/test.go +++ b/cmd/test.go @@ -28,10 +28,12 @@ var testCmd = &cobra.Command{ Long: `loading config file Test serial port Test load sqlite database and init table`, - Run: test, + Run: func(cmd *cobra.Command, args []string) { + test() + }, } -func test(cmd *cobra.Command, args []string) { +func test() { log.Println("Testing environment") _ = utils.OpenPort(device, baudrate, bytesize) diff --git a/utils/serial.go b/utils/serial.go index 8c8feb1..06c1855 100644 --- a/utils/serial.go +++ b/utils/serial.go @@ -1,27 +1,28 @@ package utils import ( - "github.com/tarm/serial" "io" "log" "time" + + "github.com/tarm/serial" ) -var( - device string - baudrate int - bytesize byte - port *serial.Port - portOpened bool +var ( + device string + baudrate int + bytesize byte + port *serial.Port + portOpened = false ) func OpenPort(device string, baudrate int, bytesize byte) error { - log.Println("opening port device:", device, ", baudrate=", baudrate, ", bytesize=",bytesize) + log.Println("opening port device:", device, ", baudrate=", baudrate, ", bytesize=", bytesize) config := &serial.Config{Name: device, Baud: baudrate, Size: bytesize, ReadTimeout: time.Second * 1} var err error port, err = serial.OpenPort(config) - if err!=nil { - log.Fatalln("error in open serial port ", err) + if err != nil { + log.Fatalln("error in open serial port ", err) return err } log.Println("opened port ", port) @@ -29,9 +30,12 @@ func OpenPort(device string, baudrate int, bytesize byte) error { return nil } -func ReadPort() ([]byte, int){ +func ReadPort() ([]byte, int) { buffer := make([]byte, 256) - count,err := port.Read(buffer) + if !ServerRunning { + return buffer, 0 + } + count, err := port.Read(buffer) if err != nil && err != io.EOF { log.Println("error in read port ", err) //TODO: 3 time fail try to @@ -42,4 +46,3 @@ func ReadPort() ([]byte, int){ func IsPortOpen() bool { return portOpened } - diff --git a/utils/socket.go b/utils/socket.go index d5b9d57..c369228 100644 --- a/utils/socket.go +++ b/utils/socket.go @@ -1,17 +1,21 @@ package utils import ( + "io" "log" "net" + "time" ) const ServerType = "tcp" var ServerRunning = false var client net.Conn +var server net.Listener func Listen(address string) { - server, err := net.Listen(ServerType, address) + var err error + server, err = net.Listen(ServerType, address) if err != nil { log.Fatal("error in create server ", err) } @@ -25,22 +29,51 @@ func Listen(address string) { } if client == nil { client = conn + log.Println("client connected ", client.RemoteAddr()) + } else { log.Println("client already connected, close") + client.Close() + client = nil conn.Close() } + if IsClientConnected() { + connCheck() + } + time.Sleep(2 * time.Second) } } -func Write(data string) { - defer func() { - client.Close() - client = nil - }() - _, err := client.Write([]byte(data)) +func WriteToClient(data string) error { + _, err := client.Write([]byte(data + "\r\n")) if err != nil { log.Println("error in write data to client socket ", err) client.Close() client = nil } + return err +} + +func connCheck() bool { + _, err := client.Read(make([]byte, 0)) + if err != nil && err != io.EOF { + // this connection is invalid + log.Println("conn closed....", err) + client = nil + return false + } + return true +} + +func IsClientConnected() bool { + return client != nil +} + +func StopSocketServer() { + if IsClientConnected() { + client.Close() + } + if server != nil { + server.Close() + } } diff --git a/utils/sqlite.go b/utils/sqlite.go index 90753d1..86bff42 100644 --- a/utils/sqlite.go +++ b/utils/sqlite.go @@ -2,10 +2,11 @@ package utils import ( "database/sql" - _ "github.com/mattn/go-sqlite3" "log" "os" "time" + + _ "github.com/mattn/go-sqlite3" ) const ( @@ -18,7 +19,8 @@ const ( [tele_text] TEXT NOT NULL ) ` - TableInsert = "insert into telegram (tele_text) values (?)" + InsertNew = "insert into telegram (tele_text) values (?)" + InsertOld = "insert into telegram (tele_text, tele_processed) values (?, 1)" ) var ( @@ -58,9 +60,9 @@ func InitDb(file string, init bool) error { func InsertTelegram(teleString string) { count := 0 - for isWriting && count < 5 { + for isWriting && count < 10 { log.Println("waiting for write ") - time.Sleep(3 * time.Second) + time.Sleep(5 * time.Second) count++ } if count >= 5 { @@ -69,7 +71,13 @@ func InsertTelegram(teleString string) { isWriting = true db := getDb() defer db.Close() - stmt, err := db.Prepare(TableInsert) + var insertSQL string + if IsClientConnected() && WriteToClient(teleString) == nil { + insertSQL = InsertOld + } else { + insertSQL = InsertNew + } + stmt, err := db.Prepare(insertSQL) if err != nil { log.Fatal(err) } @@ -80,6 +88,10 @@ func InsertTelegram(teleString string) { isWriting = false log.Fatalln("error in write telegram") } - log.Println("telegram insert ", id) isWriting = false + if insertSQL == InsertOld { + log.Println("telegram processed ", id) + } else { + log.Println("telegram saved ", id) + } }