diff --git a/Check_engine/Check_engine b/Check_engine/Check_engine new file mode 100644 index 0000000..c988109 Binary files /dev/null and b/Check_engine/Check_engine differ diff --git a/Check_engine/Check_engine.go b/Check_engine/Check_engine.go new file mode 100644 index 0000000..351ef64 --- /dev/null +++ b/Check_engine/Check_engine.go @@ -0,0 +1,725 @@ +package main + +import ( + "Bitable/file" + "fmt" + "io" + + //"log" + "io/ioutil" + "os" + "os/exec" + "strings" + "time" + + //"path/filepath" + "encoding/json" + "strconv" // convert string to int +) + +// scp -P 2224 -r -o 'ProxyJump dh.duyhai@ssh_tunnel.beetai.com' Check_engine root@localhost:/root/monitor/check/ +var name_dir_engine string = "" +var state_read_ecf bool = false + +var path_base = "/root/monitor" + +// var path_base string = "/home/admin/monitor" +var Path_base_engine string = path_base + "/engine/" + name_dir_engine //"count_people_face" // Name dir engine +var Path_log_engine string = path_base + "/log/log_engine" +var Path_log_luncher string = path_base + "/log/log_launcher" +var Path_engine_config string = path_base + "/setup/engine.json" // dia chi duoi file Config.txt +var Path_config string = Path_base_engine + "/data/Config.txt" + +// var path = "/root/monitor/log/log_engine.txt" + +//var time_sts int = 0 +//var cam_sts int = 0 + +//var Path_config string = "/root/monitor/face_recognition/data/Config.txt" + +//engine +var engine_status int = 0 + +var Path_time string = path_base + "/setup/time_run.txt" +var time_start int = 0 +var time_end int = 0 +var time_start_defaut int = 5 +var time_end_defaut int = 23 +var Debug int = 1 + +var number_run int = 0 // Check so lan run lai engine khi engine loi + +var message Message + +type Message struct { + Error_code int `json:"error_code"` + Data Datas `json:"data"` + SD_CARD int `json:"sd_card"` +} + +// User struct which contains a name +// a type and a list of social links +type Datas struct { + Box_id int `json:"box_id"` + //Box_name string `json:"box_name"` + Engines []Engine `json:"engines"` +} + +type Engine struct { + IsConfig string `json:"isConfig,omitempty"` + Active int `json:"active"` + Engine_id int `json:"engine_id"` + Id int `json:"id"` + Link string `json:"link"` + Name string `json:"name"` + Path string `json:"path"` + Version string `json:"version"` + Time_run string `json:"time_run,omitempty"` +} + +//============================> Main <========================== + +func main() { + fmt.Println("------------------ Start --------------------") + //GetDir() // Check thu muc + fmt.Println("--------------------------") + file.Check_path(Path_log_engine) + file.Write_log("Begin Check, Restart program\n", Path_log_engine) + fmt.Printf("Begin Check, Restart program\n") + ReadEngineConfig(Path_engine_config) // Pharse engine.json to struct Message + // Loop: + for { + fmt.Println("Path base:" + path_base) + fmt.Println("-------------------- 0 ---------------------") + //Check_dir_engine() // Check directory engine , Create Path_base engine + // ReadTimeRun() + //CheckCam() + //CheckTime() + ActionEngine() + fmt.Println("-------------------- 1 ---------------------") + Sleep_ms(5000) + + } +} + +//========================> END MAIN <==================== +//------------------ Function ---------------------------- +// func Check_dir_engine() { +// if Debug == 1 { +// fmt.Println("Function Check_dir_engine ()") +// } + +// name_dir_engine = strings.Replace(message.Data.Engines[0].Path, ".zip", "", -1) + +// Path_base_engine = path_base + "/engine/" + name_dir_engine +// Path_config = Path_base_engine + "/data/Config.txt" +// Path_log_engine = path_base + "/log/log_engine" +// Path_log_luncher = path_base + "/log/log_launcher" +// Path_engine_config = path_base + "/setup/engine.json" // dia chi duoi file Config.txt +// Path_config = Path_base_engine + "/data/Config.txt" +// if Debug == 1 { +// fmt.Printf("Name_dir_engine :" + name_dir_engine + "\t") +// fmt.Println("Path_base_engine :" + Path_base_engine) +// } + +// } + +func GetDir() { + if file.ReadFile("/root/ver_sys.txt") == "1" { + path_base = "/home/aibox/Documents/monitor" + } +} +func ReadEngineConfig(path string) { + if Debug == 1 { + fmt.Println("Function ReadEngineConfig ()") + } + + // Open our jsonFile + jsonFile, err := os.Open(path) + // if we os.Open returns an error then handle it + if err != nil { + fmt.Println(err) + file.Write_log("ReadEngineConfig 1 () "+err.Error(), Path_log_engine) + } + if Debug == 1 { + fmt.Println("Successfully Opened engine.json") + } + + defer jsonFile.Close() + + byteValue, err := ioutil.ReadAll(jsonFile) + if err != nil { + fmt.Println(err) + file.Write_log("ReadEngineConfig 2 () "+err.Error(), Path_log_engine) + } + json.Unmarshal(byteValue, &message) + state_read_ecf = true + + file.Println("\nError_code: " + strconv.Itoa(message.Error_code)) + file.Println("Box_id: " + strconv.Itoa(message.Data.Box_id)) + // file.Println("---------------------------------------------") + // List engine + for i := 0; i < len(message.Data.Engines); i++ { + file.Println("Isconfig: " + message.Data.Engines[i].IsConfig) + file.Println("Active: " + strconv.Itoa(message.Data.Engines[i].Active)) + file.Println("Engine_id: " + strconv.Itoa(message.Data.Engines[i].Engine_id)) + file.Println("Id: " + strconv.Itoa(message.Data.Engines[i].Id)) + file.Println("Link: " + message.Data.Engines[i].Link) + file.Println("Name: " + message.Data.Engines[i].Name) + file.Println("Path: " + message.Data.Engines[i].Path) + file.Println("Version: " + message.Data.Engines[i].Version) + file.Println("Time_run: " + message.Data.Engines[i].Time_run) + file.Println("---------------------------------------------") + } +} + +func ReadTimeRun(time string) (int, int) { + var t_start int + var t_end int + if Debug == 1 { + fmt.Println("Function ReadTimeRun ()") + } + // var value = message.Data.Engines[i].Time_run + fmt.Println("\nTime_run:" + time) + var list = strings.Split(time, ":") + if Debug == 1 { + fmt.Println(list) + for i := 0; i < 2; i++ { + fmt.Print(i) + fmt.Print("_") + fmt.Printf("%T", list[i]) + fmt.Print("_") + fmt.Printf("%v\n", list[i]) + } + } + + var x, _ = strconv.Atoi(list[0]) + t_start = x + if t_start < 0 { + t_start = 0 + } else if t_start > 23 { + t_start = 23 + } + var z, _ = strconv.Atoi(list[1]) + t_end = z + if t_end < 0 { + t_end = 0 + } else if t_end > 23 { + t_end = 23 + } + return t_start, t_end +} +func ActionEngine() { + if Debug == 1 { + fmt.Println("Function ActionEngine ()") + } + for i := 0; i < len(message.Data.Engines); i++ { + var t_stt = CheckTime(message.Data.Engines[i].Time_run) + //var cam_sts = CheckCam(message.Data.Engines[i].Path + "/data/Config.txt") + var cam_sts = 1 + var enable, _ = strconv.Atoi(message.Data.Engines[i].IsConfig) + if cam_sts*t_stt*enable == 1 { + STTServerFR() + if stt_serverlocal == 1 { + fmt.Println("Run Status_engine()") + Status_engine() + } + + fmt.Println(" Setup Run Engine") + } else { + fmt.Println("Setup off Engine") + + if message.Data.Engines[i].Active == 1 { + //var cmd string = "ps -A | grep " + message.Data.Engines[i].Name + + var cmd string = "pidof " + message.Data.Engines[i].Name + out2, err := exec.Command("sh", "-c", cmd).Output() + if err != nil { + fmt.Println(err) + //file.Write_log("ActionEngine () "+err.Error(), Path_log_engine) + } + fmt.Println("Lengh :"+cmd+"%v", len(out2)) + if len(out2) != 0 { + // sudo kill $(pgrep FaceRecognition) + + //var cmd string = "sudo kill $(pgrep " + message.Data.Engines[i].Name + ")" + //var cmd string = "pidof " + message.Data.Engines[i].Name + var cmd string = "sudo kill -9 $(pidof " + message.Data.Engines[i].Name + ")" + fmt.Println("CMD Kill_engine:" + cmd) + _, err := exec.Command("sh", "-c", cmd).Output() // kill $(pgrep FaceRecognition) + //log.Fatal(err) + if err != nil { + file.Write_log("sudo kill engine of ActionEngine() Error \n", Path_log_engine) + fmt.Println("sudo kill engine of ActionEngine() Error") + } + + } else { + fmt.Println("Engine kill") + } + out1, _ := exec.Command("sh", "-c", "ps -A | grep loop_run").Output() + if len(out1) != 0 { + _, err := exec.Command("sh", "-c", " sudo kill $(pgrep loop_run)").Output() + if err != nil { + file.Write_log("sudo kill $(pgrep loop_run) of CheckActionEngine() \n", Path_log_engine) + } + //log.Fatal(err) sudo systemctl restart S905X_BI rm /root/monitor/launcher/S905X_BI + } else { + fmt.Println("loop_run kill") + } + } else { + fmt.Println("Engine setting off on engine.json") + } + } + } +} +func CheckTime(time_run string) int { + var time_sts = 0 + if Debug == 1 { + fmt.Println("Function CheckTime ()") + } + //ReadTimeRun(time string) (int, int) + + t_start, t_end := ReadTimeRun(time_run) + var time_now = time.Now().Hour() + if Debug == 1 { + //fmt.Printf("Kieu time : %T\n", time) + fmt.Printf("time = %v\n", time_now) + } + if time_now >= t_start && time_now <= t_end { + time_sts = 1 + //Status_engine() + fmt.Println(" Time Engine's running") + } else { + time_sts = 0 + } + return time_sts +} +func FloatToString(input_num float64) string { + fmt.Println("Function FloatToString ()") + // to convert a float number to a string + return strconv.FormatFloat(input_num, 'f', 3, 64) +} +func KillFaceDedect() { + fmt.Println("Function KillFaceDedect()") + var cmd string = "pidof " + message.Data.Engines[0].Name + //out1, err := exec.Command("sh", "-c", "ps -A | grep "+message.Data.Engines[0].Name).Output() + out1, err := exec.Command("sh", "-c", cmd).Output() + if err != nil { + fmt.Println(err) + file.Write_log("KillFaceDedect() "+err.Error(), Path_log_engine) + } + if len(out1) != 0 { + _, err := exec.Command("sh", "-c", "sudo kill $("+cmd+")").Output() // kill $(pgrep FaceRecognition) + //log.Fatal(err) + if err != nil { + file.Write_log("sudo kill "+message.Data.Engines[0].Name+" of KillFaceDedect() \n", Path_log_engine) + } + file.Write_log("KillFaceDedect()\n", Path_log_engine) + Sleep_ms(500) + } + fmt.Printf("KillFaceDedect run and Run engine\n") + +} +func Status_engine() { + if Debug == 1 { + fmt.Println("Function Status_engine ()") + } + for i := 0; i < len(message.Data.Engines); i++ { + if message.Data.Engines[i].Active == 1 { + //var cmd string = "ps -A | grep " + message.Data.Engines[i].Name + var cmd string = "pidof " + message.Data.Engines[i].Name + out, err := exec.Command("sh", "-c", cmd).Output() + if err != nil { + fmt.Println(err) + file.Write_log("Status_engine () "+err.Error(), Path_log_engine) + } + if len(out) == 0 { + fmt.Printf(message.Data.Engines[i].Name + "isn't running\n") + file.Write_log(message.Data.Engines[i].Name+"isn't running\n", Path_log_engine) + //KillLoopRun() + RunEngine(message.Data.Engines[i].Name) + } else { + number_run = 0 + fmt.Printf(message.Data.Engines[i].Name + " is running\n") + } + } else { + fmt.Println("Engine setting off on engine.json") + } + + } +} + +func CheckCam(path string) int { + var cam_sts int + if Debug == 1 { + fmt.Println("Function CheckCam ()") + } + for i := 0; i < len(message.Data.Engines); i++ { + var ip string = "" + ip = GetIPCam(path) + fmt.Println("Ip camera: " + ip) + out, err := exec.Command("ping", ip, "-c 5", "-i 0.2", "-w 5").Output() + if err != nil { + fmt.Println(err) + file.Write_log("CheckCam () "+err.Error(), Path_log_engine) + cam_sts = 0 + } else { + + } + if strings.Contains(string(out), "Destination Host Unreachable") { + fmt.Println("Disconnect camera...") + file.Write_log("Disconnect camera", Path_log_engine) + cam_sts = 0 + } else { + fmt.Println("Connected camera...") + cam_sts = 1 + } + + } + return cam_sts + //fmt.Println("End Function CheckCam") +} + +func GetIPCam(path string) string { + if Debug == 1 { + fmt.Println("Function GetIPCam ()") + } + + var ip string = "" + str := ReadFile(path) + j := strings.Index(str, "@") + if j > -1 { + fmt.Println(j) + index := str[j+1 : j+20] + t := strings.Index(index, "@") + if t > -1 { + index := str[t+1 : t+15] + fmt.Println(index) + list_0 := strings.Split(index, ":") + ip = list_0[0] + } else { + fmt.Println(index) + list_0 := strings.Split(index, ":") + ip = list_0[0] + } + + } else { + i := strings.Index(str, "192") + + //fmt.Println("Index: ", i) + if i > -1 { + if Debug == 1 { + fmt.Println(str[i : i+15]) + } + + index := str[i : i+15] + list := strings.Split(index, ".") + //fmt.Println(list) + k := strings.Index(list[3], "\n") + if k > -1 { + x := strings.Split(list[3], "\n") + list[3] = x[0] + } else { + j := strings.Index(list[3], "/") + if j > -1 { + x := strings.Split(list[3], "/") + list[3] = x[0] + } else { + t := strings.Index(list[3], ":") + if t > -1 { + x := strings.Split(list[3], ":") + list[3] = x[0] + } + } + } + + ip = list[0] + for i := 1; i < 4; i++ { + if Debug == 1 { + fmt.Printf("%v_", list[i]) + } + + ip = ip + "." + list[i] + } + + } else { + file.Write_log("cam_id not found", Path_log_engine) + fmt.Println("cam_id not found") + } + } + return ip +} + +var stt_serverlocal = 0 +var number_run_fr = 0 + +func STTServerFR() { + if Debug == 1 { + fmt.Println("Function STTServerSocket ()") + } + for i := 0; i < len(message.Data.Engines); i++ { + if message.Data.Engines[i].Active == 1 { + //var cmd string = "ps -A | grep " + message.Data.Engines[i].Name + var cmd string = "pidof node" // message.Data.Engines[i].Name + + // var cmd string = "ps -ax | grep socket.js" + + out, err := exec.Command("sh", "-c", cmd).Output() + fmt.Println(out) + if err != nil { + fmt.Println(err) + file.Write_log("STTServerSocket () "+err.Error(), Path_log_engine) + } + if len(out) == 0 { + fmt.Printf("STTServerSocket isn't running\n") + file.Write_log("STTServerSocket isn't running\n", Path_log_engine) + KillFaceDedect() + RunServerFR(message.Data.Engines[i].Name) + } else { + number_run_fr = 0 + fmt.Printf("STTServerSocket is running\n") + } + } else { + fmt.Println("Engine setting off on engine.json") + } + + } +} + +func RunServerFR(name string) { + fmt.Println("Function RunEngine ()") + number_run_fr = number_run_fr + 1 + if number_run_fr > 25 { + time.Sleep(10000) + // RebootBox() + number_run_fr = 0 + file.Write_log(" number_run_fr engine > 25 ----> reset count_number=0 && not reset ", Path_log_engine) + } else { + //while true; do /home/beetsoft/Desktop/face_recognition_20190308/build/FaceRecognition/FaceRecognition ;done + // FaceRecognition/FaceRecognition ../data/Config.txt > /dev/null 2>&1 & + //var cmd = "cd " + path_base + "/engine/" + name + "/build/ && " + "screen -dm -S Engine " + name + "/" + name + " ../data/Config.txt > /dev/null 2>&1 &" + //var cmd = "export DISPLAY=:0&&export OPENBLAS_NUM_THREADS=1&&cd " + path_base + "/engine/" + name + "/build/ " + "&& " + name + "/" + name + " " + name + "/data/Config.txt > /dev/null 2>&1 &" + var cmd = "export DISPLAY=:0&&export OPENBLAS_NUM_THREADS=1&&cd " + path_base + "/engine/" + name + "/sever_socket/" + "&&node ./socket.js > /dev/null 2>&1 &" + if Debug == 1 { + fmt.Println("cmd run RunServerFR", cmd) + } + out, err := exec.Command("sh", "-c", cmd).Output() + if err != nil { + //log.Fatal(err) + stt_serverlocal = 0 + file.Write_log("RunServerFR () "+err.Error(), Path_log_engine) + fmt.Printf("RunServerFR() not run \n") + } else { + fmt.Printf("RunServerFR() ok \n") + file.Write_log("RunServerFR() ok \n", Path_log_engine) + stt_serverlocal = 1 + //RunEngine(name) + var out1 = string(out) + fmt.Printf(out1) + } + } +} +func RunEngine(name string) { + fmt.Println("Function RunEngine ()") + number_run = number_run + 1 + if number_run > 25 { + time.Sleep(10000) + // RebootBox() + number_run = 0 + file.Write_log(" Number run engine > 25 ----> reset count_number=0 && not reset ", Path_log_engine) + } else { + //while true; do /home/beetsoft/Desktop/face_recognition_20190308/build/FaceRecognition/FaceRecognition ;done + // FaceRecognition/FaceRecognition ../data/Config.txt > /dev/null 2>&1 & + //var cmd = "cd " + path_base + "/engine/" + name + "/build/ && " + "screen -dm -S Engine " + name + "/" + name + " ../data/Config.txt > /dev/null 2>&1 &" + //var cmd = "export DISPLAY=:0&&export OPENBLAS_NUM_THREADS=1&&cd " + path_base + "/engine/" + name + "/build/ " + "&& " + name + "/" + name + " " + name + "/data/Config.txt > /dev/null 2>&1 &" + var cmd = "export DISPLAY=:0&&export OPENBLAS_NUM_THREADS=1&&cd " + path_base + "/engine/" + name + "/build/ " + "&& " + name + "/" + name + " ../data/Config.txt > /dev/null 2>&1 &" + //var cmd = "export DISPLAY=:0&&export OPENBLAS_NUM_THREADS=1&&cd " + path_base + "/engine/" + name + "/build/ " + "&& " + name + "/" + name + " ../data/Config.txt > /home/admin/monitor/log/logEngine.txt &" + if Debug == 1 { + fmt.Println("cmd run engine", cmd) + } + out, err := exec.Command("sh", "-c", cmd).Output() + if err != nil { + //log.Fatal(err) + engine_status = 1 + file.Write_log("RunEngine () "+err.Error(), Path_log_engine) + fmt.Printf("RunEngine() not run \n") + } else { + fmt.Printf("RunEngine() ok \n") + file.Write_log("RunEngine() ok \n", Path_log_engine) + engine_status = 0 + var out1 = string(out) + fmt.Printf(out1) + } + } + +} +func RebootBox() { + fmt.Println("Function RebootBox()") + _, err := exec.Command("sh", "-c", "reboot").Output() + if err == nil { + file.Write_log("RebootBox()", Path_log_luncher) + } + fmt.Println("End Function RebootBox()") +} + +func Sleep_ms(ms time.Duration) { + time.Sleep(time.Millisecond * ms) // sleep(nano second) +} + +// Thao tac file +func CreateLogfile(path string) { + fmt.Println("Function CreateLogfile ()") + // detect if file exists + var _, err = os.Stat(path) + + // create file if not exists + if os.IsNotExist(err) { + var file, err = os.Create(path) + if err != nil { + fmt.Println(err) + //file.Write_log("CreateLogfile() "+err.Error(), Path_log_engine) + } + defer file.Close() + } + + fmt.Println("==> done creating file", path) +} + +// func file.file.Write_log(msg string, path string) { +// fmt.Println("Function file.Write_log ()") +// // open file using READ & WRITE permission +// // fmt.Println("==>begin writting ") +// var file, err = os.OpenFile(path, os.O_RDWR|os.O_APPEND, 0777) +// if err != nil { +// fmt.Println(err) +// file.Write_log("file.Write_log 1 () "+err.Error(), Path_log_engine) +// } +// defer file.Close() + +// _, err = file.WriteString(time.Now().String()) +// if err != nil { +// fmt.Println(err) +// file.Write_log("file.Write_log 2 () "+err.Error(), Path_log_engine) +// } +// // write some text line-by-line to file +// _, err = file.WriteString("\n") +// if err != nil { +// fmt.Println(err) +// file.Write_log("file.Write_log 3 () "+err.Error(), Path_log_engine) +// } +// _, err = file.WriteString("Service Check_engine : " + msg) +// if err != nil { +// fmt.Println(err) +// file.Write_log("file.Write_log 4 () "+err.Error(), Path_log_engine) +// } +// _, err = file.WriteString("\n") +// if err != nil { +// fmt.Println(err) +// file.Write_log("file.Write_log 5 () "+err.Error(), Path_log_engine) +// } + +// // save changes +// err = file.Sync() +// if err != nil { +// fmt.Println(err) +// file.Write_log("file.Write_log 6 () "+err.Error(), Path_log_engine) +// } + +// //fmt.Println("==> done writing to file") +// } + +// func readFile(path string) string { +// if Debug == 1 { +// fmt.Println("Function readFile ()") +// } + +// // re-open file +// var msg string = "" +// var file, err = os.OpenFile(path, os.O_RDWR, 0644) +// if err != nil { +// //file.Write_log("readFile 1 () "+err.Error(), Path_log_engine) +// time_start = time_start_defaut +// time_end = time_end_defaut +// } else { +// defer file.Close() +// // read file, line by line +// var text = make([]byte, 1024) +// for { +// _, err = file.Read(text) +// // break if finally arrived at end of file +// if err == io.EOF { +// //file.Write_log("readFile 2() "+err.Error(), Path_log_engine) +// //break + +// } + +// // break if error occured +// if err != nil && err != io.EOF { +// //file.Write_log("readFile 3() "+err.Error(), Path_log_engine) +// //break +// } +// } +// //fmt.Println(string(text)) +// msg = string(text) +// } +// fmt.Println(time_start) +// fmt.Println(time_end) +// fmt.Println("read file done") +// return msg +// } + +func DeleteFile(path string) { + fmt.Println("Function DeleteFile ()") + // delete file + var err = os.Remove(path) + if err != nil { + fmt.Println(err) + file.Write_log("DeleteFile () "+err.Error(), Path_log_engine) + } + + fmt.Println("==> done deleting file") +} + +func IsError(err error) bool { + //fmt.Println("Function IsError ()") + if err != nil { + fmt.Println(err.Error()) + } + + return (err != nil) +} + +func ReadFile(path string) string { + if Debug == 1 { + fmt.Println("Function ReadFile ()") + } + + // re-open file + var msg string = "" + var file, err = os.OpenFile(path, os.O_RDWR, 0644) + if err != nil { + fmt.Println(" Open file error") + //file.Write_log("ReadFile 1 () "+err.Error(), Path_log_engine) + + } + defer file.Close() + // read file, line by line + var text = make([]byte, 2048) + for { + _, err = file.Read(text) + // break if finally arrived at end of file + if err == io.EOF { + //file.Write_log("ReadFile 2 () "+err.Error(), Path_log_engine) + break + } + + // break if error occured + if err != nil && err != io.EOF { + //file.Write_log("ReadFile 3 () "+err.Error(), Path_log_engine) + break + } + } + msg = string(text) + //fmt.Println(msg) + return msg +} diff --git a/Check_engine/build_arm.bat b/Check_engine/build_arm.bat new file mode 100644 index 0000000..b111ce7 --- /dev/null +++ b/Check_engine/build_arm.bat @@ -0,0 +1,5 @@ +set GOOS=linux +set GOARCH=arm +set GOARM=5 +go build +pause \ No newline at end of file diff --git a/Check_engine/build_latte.bat b/Check_engine/build_latte.bat new file mode 100644 index 0000000..5298110 --- /dev/null +++ b/Check_engine/build_latte.bat @@ -0,0 +1,4 @@ +set GOOS=linux +set GOARCH=amd64 +go build +pause \ No newline at end of file diff --git a/Check_engine/root@192.168.2.35 b/Check_engine/root@192.168.2.35 new file mode 100644 index 0000000..cfb8a83 Binary files /dev/null and b/Check_engine/root@192.168.2.35 differ diff --git a/Check_engine/scp.txt b/Check_engine/scp.txt new file mode 100644 index 0000000..9d07fdb --- /dev/null +++ b/Check_engine/scp.txt @@ -0,0 +1 @@ +scp -P 2359 -r -o 'ProxyJump dh.duyhai@ssh_tunnel.beetai.com' Check_engine root@localhost:/root/monitor/launcher/ \ No newline at end of file diff --git a/S905X_BI/S905X_BI b/S905X_BI/S905X_BI new file mode 100644 index 0000000..3949189 Binary files /dev/null and b/S905X_BI/S905X_BI differ diff --git a/S905X_BI/S905X_BI.go b/S905X_BI/S905X_BI.go new file mode 100644 index 0000000..942ef21 --- /dev/null +++ b/S905X_BI/S905X_BI.go @@ -0,0 +1,597 @@ +package main + +import ( + _ "Bitable/action_engine" + "Bitable/box" + "Bitable/file" + "bytes" + "encoding/json" + "fmt" + "os/exec" + "strconv" + "strings" + "time" + + mqtt "github.com/eclipse/paho.mqtt.golang" +) + +// AutoServer : Bat che do update engine tu dong +var AutoServer = 1 + +// MqttCmsBi : Khoi tao doi tuong mqtt +var MqttCmsBi mqtt.Client + +// CmsHostBi : host MQTT +const CmsHostBi string = "tcp://broker.beetai.com:21883" + +// CmsAccessTokenBi : User +const CmsAccessTokenBi = "beeetai" + +// CmsPassBi : Password +const CmsPassBi = "5ige8TdfTEHoTgJz" + +const mqtt_disconnect_timeout uint = 5000 +const mqtt_connect_timeout time.Duration = 5 + +var idBox = "" + +// CmsTopicIn : Server to Box +var CmsTopicIn = "v1/devices/" + idBox + "/telemetry" + +// CmsTopicOut : Box to Server +var CmsTopicOut = "v1/devices/" + idBox + "/request/+" + +// StatusSSH : Cho phep bat tat ssh tu xa +var StatusSSH = 0 + +var SttNetwork = false + +// SttUpdateEngine : Trang thai update engine +// var SttUpdateEngine = false + +// MqttStt : Conect mqtt server yes? no +var MqttStt = false + +// SttUpdate: Quyet dinh dung gui message len server mqtt broker +var SttUpdate = false +var SttPub = true + +// Counter number reconnect publish +var number_repub = 0 + +// Counter number reconnect subcriber +var number_resub = 0 + +// Pwd : Password +type Pwd struct { + Password string `json:"password"` +} +type Ports struct { + Port string `json:"port"` +} + +var port Ports +var STT_test bool + +//============================> Main <========================== + +func main() { + // mqtt.DEBUG = log.New(os.Stderr, "DEBUG ", log.Ltime) // | log.Lshortfile) + //box.GetDir() // Check thu muc goc + fmt.Println("FUC......U") + file.Check_path(box.Path_log_luncher) + file.Check_path(box.Path_log_engine) + file.Write_log("<------------------------------------------------------->", box.Path_log_luncher) + file.Write_log("<-------------------- START MAIN ----------------------->", box.Path_log_luncher) + file.Write_log("<------------------------------------------------------->", box.Path_log_luncher) + + box.Stop_check_engine() + box.Stop_engine() + box.Stop_Server_Engine() + go MqttServer() // Check connect tới server MQTT 5p 1 lần + + // Loop: + for { + + if AutoServer == 1 { + // Đã được khai báo trên trang quan lý chưa + if box.Check_dir(box.Path_engine_config) == 0 { // Chưa được khai báo + if box.SetUp() == false { + file.Println("Box not register on CMS") + time.Sleep(7 * time.Second) // Waitting 7 second for next request + } else { + if SttNetwork == true { + // KHoi tao connect MQTT cms.beetai.com + if MqttStt == false { + // if CheckConnectionMQTT() == true { // Server mqtt running ? + CreateTopic() + MqttBegin() + //MqttCmsBi.Subscribe(CmsTopicOut, 1, MqttMessageHandler) + MqttStt = true + // } + } + if MqttStt == true && SttUpdate == false && SttPub == true { + PublishData() + //go Ping_broker_sub() + // if STT_test == false { + // // time.Sleep(10) + // Ping_broker_sub() + // STT_test = true + // } + + } + } else { + MqttStt = false + } + + if SttUpdate == false { + + box.RunCheck() // Check Check_engine running ??? + } + //file.Println("Publish data done") + } + } else { // Đã đươc khai báo trên cms + if SttNetwork == true { + + // KHoi tao connect MQTT cms.beetai.com + if MqttStt == false { // Chưa connect đến MQTT or mất connect mqtt + //if CheckConnectionMQTT() == true { // Server mqtt running ? + CreateTopic() + MqttBegin() + //MqttCmsBi.Subscribe(CmsTopicOut, 1, MqttMessageHandler) + MqttStt = true + //} + } + if MqttStt == true && SttUpdate == false && SttPub == true { // Check khởi tạo done mqtt and no update and cho phép publish message + box.RunCheck() + PublishData() + //go Ping_broker_sub() + // if STT_test == false { + // // time.Sleep(10) + // Ping_broker_sub() + // STT_test = true + // } + + } + } else { + MqttStt = false + } + if SttUpdate == false { + + box.RunCheck() // Check Check_engine running ??? + } + //file.Println("Publish data done") + } + box.Sleep_ms(3000) + } + } + +} + +// CreateTopic : Function +//***********************************************// +//------------------ Function --------------------- +var count = 0 + +func Ping_broker_sub() { + //for { + fmt.Println("Ping thu den sub broker") + count = count + 1 + if count > 10000 { + count = 0 + } + payload := `{"method":"sub_begin","status":` + strconv.Itoa(count) + `}` + //playload_json := json.NewDecoder(strings.NewReader(payload)) + Token1 := MqttCmsBi.Publish(CmsTopicOut, 0, false, payload) + if Token1.Wait() && Token1.Error() != nil { + fmt.Printf("Error Publish message CMS BI: %v\n", Token1.Error()) + file.Write_log("Error Publish Ping_broker_sub()", box.Path_log_luncher) + } else { + fmt.Println("Ping_broker_sub() OKIE ") + file.Write_log("Ping_broker_sub() OKIE", box.Path_log_luncher) + //file.Write _log("Send message CMS BI", box.Path_log_luncher) + } + // time.Sleep(2 * time.Hour) + //} + +} + +// CreateTopic : Function +func CreateTopic() { + //idBox = box.Get_id() + idBox = box.Get_idBox() + CmsTopicIn = "v1/devices/" + idBox + "/telemetry" + CmsTopicOut = "v1/devices/" + idBox + "/request/+" + file.Println("idBox: " + idBox) + file.Println("TOPIC IN :" + CmsTopicIn) + file.Println("TOPIC OUT :" + CmsTopicOut) + +} + +// PublishData : Function +func PublishData() { + + //var payload string = "{" + "\"ip_private\":" + "\"" + ip + "\"" + "," + "\"box_id\":" + "\"" + id_cam + "\"" + "," + "\"engine_status\":" + "\"" + sts_engine + "\"" + "," + "\"temperature\":" + "\"" + temp + "\"" + "," + "\"ip_public\":" + "\"" + ip_public + "\"" + "," + "\"mac_address\":" + "\"" + ether + "\"" + "," + "\"boot_storage\":" + "\"" + sum_boot_stg + "\"" + "," + "\"boot_storage_usage\":" + "\"" + boot_stg + "\"" + "," + "\"memory\":" + "\"" + sum_mem + "\"" + "," + "\"memory_usage\":" + "\"" + mem + "\"" + "," + "\"cpu_usage\":" + "\"" + FloatToString(avg) + "\"" + "," + "\"storage_usage\":" + "\"" + box_stg + "\"" + "," + "\"storage\":" + "\"" + sum_storage + "\"" + "}" + var payload = box.Message_pub() + //file.Println(payload) + //file.Printf("Payload = %v\n\n", payload) + Token1 := MqttCmsBi.Publish(CmsTopicIn, 1, false, payload) + if Token1.Wait() && Token1.Error() != nil { + //fmt.Printf("Error Publish message CMS BI: %v\n", Token1.Error()) + file.Write_log("Error Publish message CMS BI", box.Path_log_luncher) + } else { + file.Println("Send message CMS BI") + //file.Write_log("Send message CMS BI", box.Path_log_luncher) + } + +} + +// MqttBegin : Khoi tao MQTT +func MqttBegin() { + + OptsCmsBI := mqtt.NewClientOptions() + OptsCmsBI.AddBroker(CmsHostBi) + OptsCmsBI.SetUsername(CmsAccessTokenBi) + OptsCmsBI.SetPassword(CmsPassBi) + OptsCmsBI.SetCleanSession(true) + OptsCmsBI.SetConnectionLostHandler(MQTTLostConnectHandler) + OptsCmsBI.SetOnConnectHandler(MQTTOnConnectHandler) + + MqttCmsBi = mqtt.NewClient(OptsCmsBI) + if Token1 := MqttCmsBi.Connect(); Token1.Wait() && Token1.Error() == nil { + fmt.Println("MQTT CMS Beetsoft Connected\n") + file.Write_log("MQTT CMS BeetsoftConnected\n", box.Path_log_luncher) + MqttCmsBi.Subscribe(CmsTopicOut, 0, MqttMessageHandler) + } else { + file.Write_log("MQTT CMS Beetsoft cant not Connected\n", box.Path_log_luncher) + MqttStt = false + fmt.Println("MQTT CMS Beetsoft cant not Connect\n") + // fmt.Printf("Loi CMS Beetsoft : %v \n", Token1.Error()) + file.Println("-------------------\n") + } +} + +/************************************************************************/ +func mosquitto_LostConnect_Handler(c mqtt.Client, err error) { + fmt.Printf("Mosquitto LostConnect, reason: %v\n", err) +} + +func mosquitto_OnConnect_Handler(c mqtt.Client) { + fmt.Println("OnConnect Mosquitto") + c.Subscribe(CmsTopicOut, 0, DomoticzSubscribe_CallBack) +} + +func DomoticzSubscribe_CallBack(c mqtt.Client, message mqtt.Message) { + fmt.Printf("TOPIC: %s\n", message.Topic()) + fmt.Printf("MSG:\n %s\n", message.Payload()) +} // end function + +/************************************************************************/ + +func MqttBegin_test() { + OptsCmsBI := mqtt.NewClientOptions() + OptsCmsBI.AddBroker(CmsHostBi) + OptsCmsBI.SetUsername(CmsAccessTokenBi) + OptsCmsBI.SetPassword(CmsPassBi) + OptsCmsBI.SetCleanSession(true) + OptsCmsBI.SetConnectionLostHandler(mosquitto_LostConnect_Handler) + OptsCmsBI.SetOnConnectHandler(mosquitto_OnConnect_Handler) + + if MqttCmsBi != nil && MqttCmsBi.IsConnected() { + MqttCmsBi.Disconnect(mqtt_disconnect_timeout) + } + MqttCmsBi = mqtt.NewClient(OptsCmsBI) + Token1 := MqttCmsBi.Connect().WaitTimeout(mqtt_connect_timeout * time.Second) + if Token1 == true { + file.Println("MQTT CMS Beetsoft Connected\n") + file.Write_log("MQTT CMS BeetsoftConnected\n", box.Path_log_luncher) + MqttCmsBi.Subscribe(CmsTopicOut, 0, MqttMessageHandler) + } else { + file.Write_log("MQTT CMS Beetsoft cant not Connected\n", box.Path_log_luncher) + MqttStt = false + file.Println("MQTT CMS Beetsoft cant not Connected\n") + // fmt.Printf("Loi CMS Beetsoft : %v \n", Token1.Error()) + file.Println("-------------------\n") + } + +} + +// Check lost connect mqtt server - can't publish msg +func MQTTLostConnectHandler(c mqtt.Client, err error) { + //c.Disconnect(10) + //MqttStt = false + number_repub = number_repub + 1 + file.Write_log("MQTT CMS Beetsoft Lost Connect\n", box.Path_log_luncher) + file.Write_log("Number reconnect publish msg: "+strconv.Itoa(number_repub)+"\n", box.Path_log_luncher) + fmt.Printf("Mosquitto LostConnect, reason: %v\n", err) + //file.Println(err) +} + +// Check lost connect mqtt server - can't subcriber msg from cms +func MQTTOnConnectHandler(client mqtt.Client) { + fmt.Println("MQTTOnConnectHandler()") + number_resub = number_resub + 1 + file.Write_log("Lostconnect chanel subcriber: MQTT_OnConnectHandler\n", box.Path_log_luncher) + file.Write_log("Number reconnect subcriber msg: "+strconv.Itoa(number_resub)+"\n", box.Path_log_luncher) + //client.Unsubscribe(CmsTopicOut) + //time.Sleep(10) + //client.Subscribe(CmsTopicOut, 0, MqttMessageHandler) + if token := client.Subscribe(CmsTopicOut, 0, MqttMessageHandler); token.Wait() && token.Error() != nil { + fmt.Println(token.Error()) + file.Write_log("Subscriber Error MQTT\n", box.Path_log_luncher) + + } else { + fmt.Println("Subcriber is MQTTOnConnectHandler () OKIE ") + file.Write_log("Subcriber is MQTTOnConnectHandler () OKIE\n ", box.Path_log_luncher) + } + STT_test = false + // file.Write_log("Recall function Subscribe MQTT\n", box.Path_log_luncher) +} + +func MqttServer() { + // fmt.Println("Check Network") + for { + if CheckConnectionMQTT() == true { + // fmt.Println("CheckConnectionMQTT == true") + SttNetwork = true + } else { + MqttStt = false + SttNetwork = false + file.Write_log("============>>Network not Foud ! <==========\n ", box.Path_log_luncher) + // fmt.Println("============>>Network not Foud ! <==========\n") + } + time.Sleep(1 * time.Minute) + } +} + +// CheckConnectionMQTT: Check connection to MQTT server Beetsoft +func CheckConnectionMQTT() bool { + // fmt.Println("-----------------------------") + var SttMQTTServer = false // Biến trang thái kết nối MQTT với server + out, err := exec.Command("ping", "broker.beetai.com", "-c 5", "-i 0.2", "-w 5").Output() + if err != nil { + // fmt.Println("Loi ham CheckConnectionMQTT() ") + fmt.Println(err) + file.Write_log("Ping broker.beetai.com timeout ---> recall Mqttbegin() \n", box.Path_log_luncher) + SttMQTTServer = false + } else { + // fmt.Println("out of CheckConnectionMQTT() ") + // fmt.Println(out) + if strings.Contains(string(out), "Destination Host Unreachable") { + file.Println("Destination Host Unreachable MQTT") + file.Write_log("Destination Host Unreachable MQTT\n", box.Path_log_luncher) + SttMQTTServer = false + } else { + file.Println("Ping broker.beetai.com OKIE...") + SttMQTTServer = true + } + + } + + // fmt.Println(SttMQTTServer) + // fmt.Println("-----------------------------") + return SttMQTTServer +} + +/************************************************************************/ + +// MqttMessageHandler : mqtt callback server beetswoft +func MqttMessageHandler(MqttBI mqtt.Client, message mqtt.Message) { + fmt.Println("=================== MqttMessageHandler ====================") + fmt.Printf("Message %s\n", message) + fmt.Printf("TOPIC: %s\n", message.Topic()) + fmt.Printf("MSG:\n %s\n", message.Payload()) + fmt.Println("=========================== + = + ==========================") + dec := json.NewDecoder(bytes.NewReader(message.Payload())) + var list map[string]interface{} + if err := dec.Decode(&list); err != nil { + //file.Printf("Error:%v\n", err) + file.Write_log("Message:Loi form message\n", box.Path_log_luncher) + } else { + //***********************************************// + if list["method"] == "change_passwd" { // {"method" : "change_passwd","params": {"password": "123456@"}} + file.Println("Changing password \n") + s, err := json.Marshal(list["params"]) + if err != nil { + //file.Println(err) + } + var pwd Pwd + json.Unmarshal([]byte(string(s)), &pwd) + topic := strings.Replace(message.Topic(), "request", "response", 1) + //pass := pwd.Password + // fmt.Print(topic, "\n\n") + // fmt.Printf("New password:%v\n", pass) + //box.Set_passwd(pass) + msg := `{"method":"change_passwd","status": ` + strconv.Itoa(1) + `}` + file.Write_log("Message:"+msg+" \n", box.Path_log_luncher) + CmsResponse(MqttBI, topic, msg) + + } else if list["method"] == "open_ssh" { + file.Println("Open port ssh\n") + topic := strings.Replace(message.Topic(), "request", "response", 1) + p, err := json.Marshal(list["params"]) + if err != nil { + //file.Println(err) + } + var pVal = port.Port + if StatusSSH == 0 { + json.Unmarshal([]byte(string(p)), &port) + pVal = port.Port + file.Println(pVal) + file.Println("Bat ssh") + file.Println("Out ssh") + msg := `{"method":"open_ssh","status": ` + strconv.Itoa(1) + `,"params": {"port": "` + pVal + `"}}` + file.Write_log("Message response cms:"+msg+" \n", box.Path_log_luncher) + CmsResponse(MqttBI, topic, msg) + box.Ssh_open(pVal) + file.Println("chay lenh xong") + } + StatusSSH = 1 + // file.Println("Out ssh") + // msg := `{"method":"open_ssh","status": ` + strconv.Itoa(1) + `,"params": {"port": "` + pVal + `"}}` + // file.Write_log("Message response:"+msg+" \n", box.Path_log_luncher) + // CmsResponse(MqttBI, topic, msg) + file.Println("Open Done ssh\n") + + } else if list["method"] == "close_ssh" { + file.Println("Close port ssh\n") + topic := strings.Replace(message.Topic(), "request", "response", 1) + if StatusSSH == 1 { + box.Ssh_close() + StatusSSH = 0 + } + msg := `{"method":"close_ssh","status": ` + strconv.Itoa(1) + `}` + file.Write_log("Message:"+msg+" \n", box.Path_log_luncher) + CmsResponse(MqttBI, topic, msg) + file.Println("Close Done ssh\n") + + } else if list["method"] == "update_engine" { + file.Println("Update engine\n") + UpdateEngine() + topic := strings.Replace(message.Topic(), "request", "response", 1) + msg := `{"method":"update_engine","status": ` + strconv.Itoa(1) + `}` + file.Write_log("Message:"+msg+" \n", box.Path_log_luncher) + CmsResponse(MqttBI, topic, msg) + file.Println("Update engine done\n") + + } else if list["method"] == "sub_begin" { // Test subcriber + file.Write_log("======>> Subcriber is OKIE <========== \n", box.Path_log_luncher) + + } else if list["method"] == "update_model" { // {"method":"update_model","status": 1} + file.Println("Update_model \n") + fmt.Printf("%v--%T", list["id_box_engine"], list["id_box_engine"]) + msg := `{"method":"update_model","status": ` + strconv.Itoa(1) + `}` + file.Write_log("Message:"+msg+" \n", box.Path_log_luncher) + if SttUpdate == false { + UpdateModule((int)((list["id_box_engine"]).(float64))) + topic := strings.Replace(message.Topic(), "request", "response", 1) + + // file.Write_log("Message:"+msg+" \n", box.Path_log_luncher) + CmsResponse(MqttBI, topic, msg) + file.Println("UpdateModule done\n") + } + + } else if list["method"] == "inactive_box" { + file.Println("Inactive Box\n") + SttPub = false + topic := strings.Replace(message.Topic(), "request", "response", 1) + msg := `{"method":"inactive_box","status": ` + strconv.Itoa(1) + `}` + file.Write_log("Message:"+msg+" \n", box.Path_log_luncher) + CmsResponse(MqttBI, topic, msg) + file.Println("Inactive Box done\n") + + } else if list["method"] == "active_box" { + file.Println("Active Box\n") + SttPub = true + topic := strings.Replace(message.Topic(), "request", "response", 1) + msg := `{"method":"active_box","status": ` + strconv.Itoa(1) + `}` + file.Write_log("Message:"+msg+" \n", box.Path_log_luncher) + CmsResponse(MqttBI, topic, msg) + file.Println("Active Box done\n") + + } else if list["method"] == "delete_box" { + file.Println("Delete box\n") + SttPub = false + topic := strings.Replace(message.Topic(), "request", "response", 1) + msg := `{"method":"delete_box","status": ` + strconv.Itoa(1) + `}` + file.Write_log("Message:"+msg+" \n", box.Path_log_luncher) + CmsResponse(MqttBI, topic, msg) + file.Println("Delete box done\n") + + } else if list["method"] == "getVersion" { + topic := strings.Replace(message.Topic(), "request", "response", 1) + //msg := `{"version":` + box.Get_version() + `}` + msg := `{"method":"getVersion","params":` + box.Get_version() + `}` + file.Write_log("Message:"+msg+" \n", box.Path_log_luncher) + CmsResponse(MqttBI, topic, msg) + file.Println("Get version done\n") + } else if list["method"] == "reboot" { + file.Write_log("Message:reboot\n", box.Path_log_luncher) + //file.Println("=======================>> Reboot BOX <<=====================") + box.Reboot_box() + } else if list["method"] == "cmd" { + topic := strings.Replace(message.Topic(), "request", "response", 1) + msg := `{"method":"cmd","status": ` + strconv.Itoa(1) + `}` + //file.Println(topic) + file.Write_log("Message:"+msg+" \n", box.Path_log_luncher) + //CmsResponse(MqttBI, topic, msg) + //file.Printf("%T_%v", list["params"], list["params"]) + m, _ := list["params"].(string) + var out string + k := strings.Index(m, "nano") + if k > -1 { + if strings.Index(m, "Config.txt") > -1 { + path := m[k+5:] + file.Println(path) + out = file.ReadFile(path) + file.Println("0") + } else { + out = box.Cmd_Box(m) + file.Println("1") + } + + } else { + out = box.Cmd_Box(m) + file.Println("2") + } + //file.Println(out) + // out := box.Cmd_Box(m) + mg := `{"method":"cmd","status": "` + "\n" + out + "\n" + `"}` + file.Println(mg) + CmsResponse(MqttBI, topic, mg) + } else if list["method"] == "upgrade_engine" { + file.Println(`list["method"] == "upgrade_engine"`) + s, err := json.Marshal(list["params"]) + if err != nil { + //fmt.Println(err) + } + topic := strings.Replace(message.Topic(), "request", "response", 1) + msg := `{"method":"upgrade_engine","status":` + strconv.Itoa(1) + `}` + //file.Println(topic) + file.Write_log("Message:"+msg+" \n", box.Path_log_luncher) + CmsResponse(MqttBI, topic, msg) + params := string(s) + UpgradeEngine(params) + } else { + //fmt.Println(list) + } + } + +} +func UpdateModule(id_engine int) { + file.Write_log("-------- START UPDATE MODULE ----------", box.Path_log_luncher) + SttUpdate = true + // box.Stop_check_engine() + // box.Stop_Server_Engine() + box.RequestUpdate_Module(box.Url_module, id_engine) + SttUpdate = false + file.Write_log("---------------------------------------", box.Path_log_luncher) +} +func UpdateEngine() { + SttUpdate = true + box.Stop_check_engine() + box.Stop_engine() + box.RequestUpdate(box.Url) + SttUpdate = false +} + +// CmsResponse : Phan hoi message tu box to Server +func CmsResponse(c mqtt.Client, topic string, msg string) { + c.Publish(topic, 0, false, msg) + file.Println("Publish message done") +} + +// UpgradeEngine : Nang cap engine +func UpgradeEngine(params string) { + //file.Println("0") + box.Check_path(box.Path_upgrade) + //file.Println("1") + file.Create_file(box.Path_engine_update) + file.Write_file(params, box.Path_engine_update) + //file.Println("2") + SttUpdate = true + box.Stop_check_engine() + //file.Println("3") + box.Stop_engine() + //file.Println("4") +} diff --git a/S905X_BI/aibox@gitlab.beetsoft.com.vn b/S905X_BI/aibox@gitlab.beetsoft.com.vn new file mode 100644 index 0000000..63213d2 Binary files /dev/null and b/S905X_BI/aibox@gitlab.beetsoft.com.vn differ diff --git a/S905X_BI/backup/S905X_BI b/S905X_BI/backup/S905X_BI new file mode 100644 index 0000000..20957f2 Binary files /dev/null and b/S905X_BI/backup/S905X_BI differ diff --git a/S905X_BI/build_arm.bat b/S905X_BI/build_arm.bat new file mode 100644 index 0000000..b111ce7 --- /dev/null +++ b/S905X_BI/build_arm.bat @@ -0,0 +1,5 @@ +set GOOS=linux +set GOARCH=arm +set GOARM=5 +go build +pause \ No newline at end of file diff --git a/S905X_BI/build_latte.bat b/S905X_BI/build_latte.bat new file mode 100644 index 0000000..5298110 --- /dev/null +++ b/S905X_BI/build_latte.bat @@ -0,0 +1,4 @@ +set GOOS=linux +set GOARCH=amd64 +go build +pause \ No newline at end of file diff --git a/S905X_BI/scp.txt b/S905X_BI/scp.txt new file mode 100644 index 0000000..ede9548 --- /dev/null +++ b/S905X_BI/scp.txt @@ -0,0 +1,2 @@ + +scp -P 2466 -r -o 'ProxyJump dh.duyhai@ssh_tunnel.beetai.com' S905X_BI root@localhost:/root/monitor/check/ \ No newline at end of file diff --git a/action_engine/action_engine.go b/action_engine/action_engine.go new file mode 100644 index 0000000..4157a26 --- /dev/null +++ b/action_engine/action_engine.go @@ -0,0 +1,124 @@ +package action_engine + +import ( + // "bytes" + // "encoding/json" + + "fmt" + // "github.com/eclipse/paho.mqtt.golang" + //"io" + // "log" + // "net" + // "os" + "os/exec" + // "time" + //"io/ioutil" + //"path/filepath" + // "strconv" // convert string to int + //"strings" +) + +var debug int = 1 + +func Kill_engine() { + if debug == 1 { + fmt.Printf("Kill_engine()\n") + } + out1, _ := exec.Command("sh", "-c", "ps -A | grep loop_run").Output() + if len(out1) != 0 { + _, err := exec.Command("sh", "-c", " kill $(pgrep loop_run)").Output() + if err != nil { + //log.Fatal(err) + } + } + out2, _ := exec.Command("sh", "-c", "ps -A | grep FaceRecognition").Output() + if len(out2) != 0 { + _, err := exec.Command("sh", "-c", " kill $(pgrep FaceRecognition)").Output() // kill $(pgrep FaceRecognition) + if err != nil { + //log.Fatal(err) + } + } + +} +func Stop_check_engine() { + fmt.Println("Kill Check_engine") + if debug == 1 { + fmt.Printf("Stop_check_engine()\n") + } + _, err := exec.Command("sh", "-c", "kill $(pgrep Check_engine)").Output() + if err != nil { + //log.Fatal(err) + } +} + +func Tranfer_engine() { + if debug == 1 { + fmt.Printf("Tranfer_engine()\n") + fmt.Printf("Begin backup engine\n") + } + _, err := exec.Command("sh", "-c", "cd /root/monitor/backup").Output() + if err != nil { + _, err1 := exec.Command("sh", "-c", "mkdir /root/monitor/backup").Output() + if err1 != nil { + //log.Fatal(err) + fmt.Printf(" Backup engine Error\n") + } + } + + if debug == 1 { + fmt.Printf("Create forder backup\n") + } + // Xoa file engine cu trong backup + _, err0 := exec.Command("sh", "-c", "cd /root/monitor/backup/monitor/").Output() + if err0 == nil { + _, err1 := exec.Command("sh", "-c", "rm -rf /root/monitor/backup/monitor/").Output() + if err1 != nil { + //log.Fatal(err1) + fmt.Printf(" Xoa file engine cu trong backup Error\n") + } + } + _, err2 := exec.Command("sh", "-c", "mv /root/monitor/face_recognition/ /root/monitor/backup/").Output() + if err2 != nil { + //log.Fatal(err2) + fmt.Printf("Move mv /root/monitor/face_recognition/ /root/monitor/backup/ error\n") + + } + // fmt.Printf("Done copy\n") +} +func Backup_engine() { + if debug == 1 { + fmt.Printf("Backup_engine()\n") + } + _, err := exec.Command("sh", "-c", "rm -rf /root/monitor/face_recognition/").Output() + if err != nil { + //log.Fatal(err) + } else { + _, err1 := exec.Command("sh", "-c", "mv /root/monitor/backup/face_recognition/ /root/monitor/").Output() + if err1 != nil { + //log.Fatal(err1) + } else { + _, err2 := exec.Command("sh", "-c", "sudo chmod +x /root/monitor/face_recognition/build/FaceRecognition/FaceRecognition").Output() + if err2 != nil { + //log.Fatal(err2) + } else { + //Start_engine() + } + } + } + //fmt.Printf("Done Backup_engine \n") +} +func Download_engine() { + if debug == 1 { + fmt.Printf("Download_engine()\n") + } + +} +func Upgrade_engine() { + if debug == 1 { + fmt.Printf("Upgrade_engine()\n") + } + Stop_check_engine() + Kill_engine() + Tranfer_engine() + //Start_engine() +} diff --git a/box/box.go b/box/box.go new file mode 100644 index 0000000..b04ac0f --- /dev/null +++ b/box/box.go @@ -0,0 +1,1929 @@ +package box + +import ( + "Bitable/file" + "bufio" + "bytes" + "encoding/json" + "errors" + "fmt" + + //"github.com/eclipse/paho.mqtt.golang" + "io" + // "log" + "crypto/rand" + "crypto/rsa" + "crypto/x509" + "encoding/base64" + "encoding/pem" + "io/ioutil" + "net" + "net/http" + "os" + "os/exec" + "time" + + //"path/filepath" + "strconv" // convert string to int + "strings" + + "github.com/dustin/go-humanize" +) + +// go.lintOnSave": "off" +// scp -P 2224 -r -o 'ProxyJump dh.duyhai@ssh_tunnel.beetai.com' a.txt admin@localhost:/admin/monitor/1/ + +var Debug = 1 +var Key = "V7kls@&@IP*fl7R" +var Setup_stt = false + +// var last_msg_time = time.Now().UnixNano() / 1000000 + +var state_read_ecf = false + +//Khai bao +//IP +var ip = "" +var ip_public = "" +var ether = "" + +//Mem +var mem = "" +var sum_mem = "" + +// Cpu +var user = 0 +var system = 0 +var idle = 0 +var avg = 0 + +// Storage +var box_stg = "" +var sum_storage = "" + +//Boot_storage +var boot_stg = "" +var sum_boot_stg = "" + +//temp +var temp = "" + +//engine +var sts_engine = 0 + +// var pass string = "" +// var passwd_str string = "echo -e " + pass + "\n" + pass + "| passwd admin" + +// id camera +var id_cam = "" + +const SD_CARD_DEFAULT = 0 + +// Ver_Ubuntu_ : 0 - Server / 1 - Desktop +// const VER_UBUNTU_DEFAUT = 0 + +var name_dir_engine = "" + +var path_base = "/root/monitor" + +// var path_base = "/home/admin/monitor" +var Path_base_engine = path_base + "/engine/" + name_dir_engine //"count_people_face" // Name dir engine +var Path_log_engine = path_base + "/log/log_engine" +var Path_log_luncher = path_base + "/log/log_launcher" +var Path_engine_config = path_base + "/setup/engine.json" // dia chi duoi file Config.txt +var Path_config = Path_base_engine + "/data/Config.txt" +var Path_backup = path_base + "/backup" +var Path_upgrade = path_base + "/upgrade" +var Path_engine_update = Path_upgrade + "/engine_update.json" +var time_run = "5:23:" + +// Server +// var Url = "http://api.cms_dev.beetai.com/api/box/getConfig" //"http://www.mocky.io/v2/5cdd0a163000000f25e2343e" +var Url = "http://192.168.0.9:5030/api/box/getConfig" + +// API update modules +var Url_module = "/api/model/get_model/" + +//---------------------------------------------------- +// Create struct file config engine.json +// message : Cho engine.json confix +var message Message + +// messageUpdate : Cho message update engine +var messageUpdate Message + +type Message struct { + Error_code int `json:"error_code"` + Data Datas `json:"data"` + SD_CARD int `json:"sd_card"` +} + +// message.Data.Engines[i].IsConfig +// User struct which contains a name +// a type and a list of social links +type Datas struct { + Box_id int `json:"box_id"` + QrCode string `json:"qrcode"` + License string `json:"license"` + Engines []Engine `json:"engines"` +} + +type Engine struct { + IsConfig string `json:"isConfig,omitempty"` + Active int `json:"active"` + Engine_id int `json:"engine_id"` + Threshold float32 `json:"threshold"` //"threshold" + Id int `json:"id"` + Url string `json:"url"` + Link string `json:"link"` + Name string `json:"name"` + Path string `json:"path"` + Version string `json:"version"` + //PortStream int `json:"portstream,omitempty"` + Time_run string `json:"time_run,omitempty"` +} + +//---------------------------------------------------- + +// Create struct Message Payload pub MQTT +var payload Payload + +type Payload struct { + Box_id int `json:"box_id"` + Ip_private string `json:"ip_private"` + Ip_public string `json:"ip_public"` + Mac_address string `json:"mac_address"` + Boot_storage string `json:"boot_storage"` + Boot_storage_usage string `json:"boot_storage_usage"` + Memory string `json:"memory"` + Memory_usage string `json:"memory_usage"` + Storage string `json:"storage"` + Storage_usage string `json:"storage_usage"` + Cpu_usage string `json:"cpu_usage"` + Temperature string `json:"temperature"` + Engines_pub []Engine_pub `json:"engines_pub"` +} +type Engine_pub struct { + Name string `json:"name"` + Status int `json:"status"` + Engine_id int `json:"engine_id"` +} + +// Check size of file download +type WriteCounter struct { + Total uint64 +} + +//==================== FUNCTION ============================== +// Down load file Url +func (wc *WriteCounter) Write(p []byte) (int, error) { + n := len(p) + wc.Total += uint64(n) + wc.PrintProgress() + return n, nil +} + +func (wc WriteCounter) PrintProgress() { + // Clear the line by using a character return to go back to the start and remove + // the remaining characters by filling it with spaces + fmt.Printf("\r%s", strings.Repeat(" ", 35)) + + // Return again and print current status of download + // We use the humanize package to print the bytes in a meaningful way (e.g. 10 MB) + fmt.Printf("\rDownloading... %s complete", humanize.Bytes(wc.Total)) +} +func DownloadFile(filepath string, url string) error { + + // Create the file, but give it a tmp file extension, this means we won't overwrite a + // file until it's downloaded, but we'll remove the tmp extension once downloaded. + out, err := os.Create(filepath + ".tmp") + if err != nil { + return err + } + + // Get the data + resp, err := http.Get(url) + if err != nil { + out.Close() + return err + } + defer resp.Body.Close() + + // Create our progress reporter and pass it to be used alongside our writer + counter := &WriteCounter{} + if _, err = io.Copy(out, io.TeeReader(resp.Body, counter)); err != nil { + out.Close() + return err + } + + // The progress use the same line so print a new line once it's finished downloading + fmt.Print("\n") + + // Close the file without defer so it can happen before Rename() + out.Close() + + if err = os.Rename(filepath+".tmp", filepath); err != nil { + return err + } + return nil +} + +//--------------------------------------------------------------------------------- + +func GetDir() { + if file.ReadFile("/admin/ver_sys.txt") == "1" { + path_base = "/home/aibox/Documents/monitor" + } +} +func RunCheck() { + if Status_Checkengine() == 0 { + file.Println("Function RunCheck ()") + //cmd := "sudo " + path_base + "/check/run_check.sh" + //chmod 777 /var/run/screen && + cmd := "sudo " + path_base + "/check/Check_engine >/dev/null 2>&1 &" + fmt.Println("CMD run check_engine:" + cmd) + _, err := exec.Command("sh", "-c", cmd).Output() + if err != nil { + file.Write_log("RunCheck () "+err.Error(), Path_log_luncher) + file.Println("RunCheck() error ") + } else { + file.Println("RunCheck() ok ") + file.Write_log("RunCheck() ok ", Path_log_luncher) + } + } else { + //file.Println("===>Check_engine is running<====") + } + +} +func Status_Checkengine() int { + file.Println("Function Status_Checkengine ()") + var stt int = 0 + var cmd string = "ps -A | grep Check_engine" + out, err := exec.Command("sh", "-c", cmd).Output() + if err != nil { + //file.Println(err) + file.Write_log("Status_Checkengine () "+err.Error(), Path_log_luncher) + } + if len(out) == 0 { + stt = 0 + file.Println("====>>>>Check_engine not run\n") + file.Write_log("====>>>>Check_engine not run\n", Path_log_luncher) + } else { + file.Println("===>Check_engine is running<====") + file.Println("\n") + stt = 1 + } + return stt +} +func SetUp() bool { + fmt.Println("Link Getrequest:" + Url) + Request_msg(Url) // Request down load engine, tạo engine.json + file.Println("Request_msg done") + LoadConfig(Path_engine_config) // Get thong tin tu file engine.json luu thong so vao struct, add them truong time run + //UpdateDirEngine() + file.Println("LoadConfig done") + if message.Error_code == 10000 { + Dowload_engine() // Down load cac engine duoc respon tu server tra ve + UpdateConfig(Path_engine_config) // Cap nhat thong tin name engine cho engine.json + file.Println("Dowload_engine done") + file.Println("Replace_id done") + namebox := "BITABLE_" + strconv.Itoa(message.Data.Box_id) + RenameBox(namebox) + //Set_autorun() // Thiet lap engine auto run sau khi reset(Set up thong so Url, do phan giai, ) + file.Write_log("AIBOX Reset\n", Path_log_luncher) + Setup_stt = true + } else { + Setup_stt = false + file.DeleteFile(Path_engine_config) + } + return Setup_stt +} +func Set_autorun() { + _, err := exec.Command("sh", "-c", "sed -i -e '$i \\sudo "+path_base+"/run_cms.sh > dev/null 2>&1 &\n' /etc/rc.local").Output() + if err != nil { + file.Println("Error Set Auto run CMS Local") + } else { + file.Println("Done Set Auto run CMS Local") + } + // For Check_engine + _, err_1 := exec.Command("sh", "-c", "sed -i -e '$i \\screen -dm -S Check_engine sudo "+path_base+"/Check_engine >/dev/null 2>&1 &\n' /etc/rc.local").Output() + if err_1 != nil { + file.Println("Error Set Auto run Check_engine") + } else { + file.Println("Done Set Auto run Check_engine") + } +} +func GetIndex(message Message, value string) int { + var k = -1 + for i := 0; i < len(message.Data.Engines); i++ { + if message.Data.Engines[i].Name == value { + k = i + } + } + return k +} +func DowloadEngineUpdate(name string, link string, version string, id int) { + file.Println("Name: " + name) + file.Println("Version: " + version) + file.Println("Link: " + link) + var index = GetIndex(message, name) + if index != -1 { + if link != "" { + var cmd_link string = "wget -O " + "" + path_base + "/engine/" + name + ".tar.gz " + link + file.Println(cmd_link) + _, err := exec.Command("sh", "-c", cmd_link).Output() + if err != nil { + file.Println("Dowload_engine: " + name + ":" + version + "Faild.!") + file.Println("-------------------------------") + } + } + //var list = strings.Split(message.Data.Engines[i].Link, "/") + //var name_engine = list[len(list)-1] + var cmd = "tar zxvf " + "" + path_base + "/engine/" + name + ".tar.gz " + " --one-top-level=" + path_base + "/engine/" + name + "_" + strconv.Itoa(id) + file.Println(cmd) + _, err := exec.Command("sh", "-c", cmd).Output() + if err != nil { + file.Println("Giai nen Error") + file.Println("-------------------------------") + } else { + file.Println("Giai nen thanh cong") + file.Println("-------------------------------") + } + var cmd1 = "mv " + "" + path_base + "/engine/" + name + "_" + strconv.Itoa(id) + "/build/" + name + " " + path_base + "/engine/" + name + "_" + strconv.Itoa(id) + "/build/" + name + "_" + strconv.Itoa(id) + file.Println(cmd1) + _, err1 := exec.Command("sh", "-c", cmd1).Output() + if err1 != nil { + file.Println("Loi doi ten thu muc con ") + file.Println("-------------------------------") + } else { + file.Println("Doi ten thu muc con thanh cong") + file.Println("-------------------------------") + } + var cmd2 = "mv " + "" + path_base + "/engine/" + name + "_" + strconv.Itoa(id) + "/build/" + name + "_" + strconv.Itoa(id) + "/" + name + " " + path_base + "/engine/" + name + "_" + strconv.Itoa(id) + "/build/" + name + "_" + strconv.Itoa(id) + "/" + name + "_" + strconv.Itoa(id) + file.Println(cmd2) + _, err2 := exec.Command("sh", "-c", cmd2).Output() + if err2 != nil { + file.Println("Loi doi ten engine ") + file.Println("-------------------------------") + } else { + file.Println("Doi ten engine thanh cong") + file.Println("-------------------------------") + } + // Remove file nen + _, err_1 := exec.Command("sh", "-c", "rm "+path_base+"/engine/*.tar.gz").Output() + if err_1 != nil { + file.Println("Error Clear file .tar.gz ") + } else { + file.Println("Done Clear file .tar.gz") + } + // Update path engine and replace id_cam on file config + file.Println("Update path engine and replace id_cam on file config") + + message.Data.Engines[index].Name = name + "_" + strconv.Itoa(id) + message.Data.Engines[index].Path = "" + path_base + "/engine/" + message.Data.Engines[index].Name + file.Println(message.Data.Engines[index].Name) + file.Println(message.Data.Engines[index].Path) + var id_val = strconv.Itoa(message.Data.Engines[index].Id) + var path_val = message.Data.Engines[index].Path + "/data/Config.txt" + fmt.Println("ID new: ", id_val) + fmt.Println("Path config:", path_val) + threshold := fmt.Sprintf("%.2f", message.Data.Engines[index].Threshold) + Replace_id(path_val, id_val, threshold, message.Data.Engines[index].Url) // Cap nhap ID BOX cho file config.txt trong engine + path := message.Data.Engines[index].Path + "/data/license.bin" + fmt.Println("Path save license:", path) + SaveLicense(message.Data.License, path) + // Do cap nhat chua biet port dang nao la bao nhieu len ko set dc + //ChangePort(path_val, port) // Change portstream local cho cac engine thanh khac nhau + fmt.Println("---------------------------------------------------") + file.Println("---------------------------------------------------") + } +} // End for array engine + +func Dowload_engine() { + file.Println("Function Dowload_engine----11-1-1-11-1") + for i := 0; i < len(message.Data.Engines); i++ { + file.Println("Name: " + message.Data.Engines[i].Name) + file.Println("Version: " + message.Data.Engines[i].Version) + file.Println("Link: " + message.Data.Engines[i].Link) + if message.Data.Engines[i].Link != "" { + var link string = "wget -c -O " + "" + path_base + "/engine/" + message.Data.Engines[i].Name + ".tar.gz " + message.Data.Engines[i].Link + file.Println(link) + _, err := exec.Command("sh", "-c", link).Output() + if err != nil { + file.Println("Dowload_engine: " + message.Data.Engines[i].Name + ":" + message.Data.Engines[i].Version + "Faild.!") + file.Println("-------------------------------") + } + } + //var list = strings.Split(message.Data.Engines[i].Link, "/") + //var name_engine = list[len(list)-1] + var cmd = "tar zxvf " + "" + path_base + "/engine/" + message.Data.Engines[i].Name + ".tar.gz " + " --one-top-level=" + path_base + "/engine/" + message.Data.Engines[i].Name + "_" + strconv.Itoa(message.Data.Engines[i].Id) + file.Println(cmd) + _, err := exec.Command("sh", "-c", cmd).Output() + if err != nil { + file.Println("Giai nen Error") + file.Println("-------------------------------") + } else { + file.Println("Giai nen thanh cong") + file.Println("-------------------------------") + } + var cmd1 = "mv " + "" + path_base + "/engine/" + message.Data.Engines[i].Name + "_" + strconv.Itoa(message.Data.Engines[i].Id) + "/build/" + message.Data.Engines[i].Name + " " + path_base + "/engine/" + message.Data.Engines[i].Name + "_" + strconv.Itoa(message.Data.Engines[i].Id) + "/build/" + message.Data.Engines[i].Name + "_" + strconv.Itoa(message.Data.Engines[i].Id) + file.Println(cmd1) + _, err1 := exec.Command("sh", "-c", cmd1).Output() + if err1 != nil { + file.Println("Loi doi ten thu muc con ") + file.Println("-------------------------------") + } else { + file.Println("Doi ten thu muc con thanh cong") + file.Println("-------------------------------") + } + var cmd2 = "mv " + "" + path_base + "/engine/" + message.Data.Engines[i].Name + "_" + strconv.Itoa(message.Data.Engines[i].Id) + "/build/" + message.Data.Engines[i].Name + "_" + strconv.Itoa(message.Data.Engines[i].Id) + "/" + message.Data.Engines[i].Name + " " + path_base + "/engine/" + message.Data.Engines[i].Name + "_" + strconv.Itoa(message.Data.Engines[i].Id) + "/build/" + message.Data.Engines[i].Name + "_" + strconv.Itoa(message.Data.Engines[i].Id) + "/" + message.Data.Engines[i].Name + "_" + strconv.Itoa(message.Data.Engines[i].Id) + file.Println(cmd2) + _, err2 := exec.Command("sh", "-c", cmd2).Output() + if err2 != nil { + file.Println("Loi doi ten engine ") + file.Println("-------------------------------") + } else { + file.Println("Doi ten engine thanh cong") + file.Println("-------------------------------") + } + // Remove file nen + _, err_1 := exec.Command("sh", "-c", "rm "+path_base+"/engine/*.tar.gz").Output() + if err_1 != nil { + file.Println("Error Clear file .tar.gz ") + } else { + file.Println("Done Clear file .tar.gz") + } + // Update path engine and replace id_cam on file config + file.Println("Update path engine and replace id_cam on file config") + message.Data.Engines[i].Name = message.Data.Engines[i].Name + "_" + strconv.Itoa(message.Data.Engines[i].Id) + message.Data.Engines[i].Path = "" + path_base + "/engine/" + message.Data.Engines[i].Name + file.Println(message.Data.Engines[i].Name) + file.Println(message.Data.Engines[i].Path) + var id_val = strconv.Itoa(message.Data.Engines[i].Id) + var path_val = message.Data.Engines[i].Path + "/data/Config.txt" + fmt.Println("ID new: ", id_val) + fmt.Println("Path config:", path_val) + threshold := fmt.Sprintf("%.2f", message.Data.Engines[i].Threshold) + Replace_id(path_val, id_val, threshold, message.Data.Engines[i].Url) // Cap nhap ID BOX cho file config.txt trong engine + // message.Data.Engines[i].PortStream = ChangePort(path_val, i) + path := message.Data.Engines[i].Path + "/data/.bin" + fmt.Println("Path save license:", path) + SaveLicense(message.Data.License, path) + + fmt.Println(ChangePort(path_val, i)) + // Change portstream local cho cac engine thanh khac nhau + file.Println("---------------------------------------------------") + } // End for array engine1612 + // Cap nhat name engine trong file engine.json +} +func FormRequest(Url string) string { + // var ip_s string = "" + // var ip_ps string = "" + var mac_s string = "" + var respon_msg string = "" + file.Create_file(Path_engine_config) + GetOutboundIP() + mac_s = Get_mac() + // fmt.Println(mac_s) + // mac_s = "c4:2a:fe:37:35:11" + fmt.Println(mac_s) + // `{" private_key": "V7kls@&@IP*fl7R", "mac_address":"c4:6e:00:02:cb:14 "}` + + // encode, err := RsaEncrypt([]byte(mac_s), publicKey) + encode, err := RsaEncrypt([]byte(mac_s), publicKey) + if err != nil { + panic(err) + } + + fmt.Println("-----------------MA HOA---------------------") + // s := []byte("hai") + // s1 := Base64Enc(encode) + s1 := base64.StdEncoding.EncodeToString(encode) + // s1 = strings.Replace(s1, "\n", "\n", -1) + fmt.Printf("Payload encode base 64:%v Type: %T\n", s1, s1) + + // var msg string = "{" + "\"data\":" + "\"" + s1 + "\"" + "}" + // var msg string = "{\"data\":\"" + s1 + "\"}" + var msg string = `{"data":"` + s1 + `"}` + // var b bytes.Buffer + // b.WriteString("{\"data\":\"") + // b.WriteString(s1) + // b.WriteString("\"}") + + fmt.Println("\nPAYLOAD:" + msg) + + payload := []byte(msg) + resp, err := http.Post(Url, "application/json", bytes.NewBuffer(payload)) + if err != nil { + file.Write_log("Request_msg() Faild", Path_log_luncher) + //file.Println("Request_msg() Faild") + + } else { + defer resp.Body.Close() + } + body, err := ioutil.ReadAll(resp.Body) + if err != nil { + file.Write_log("ioutil.ReadAll(resp.Body) Faild", Path_log_luncher) + fmt.Println("ioutil.ReadAll(resp.Body) Faild") + } + respon_msg = string(body) + fmt.Println(respon_msg) + return respon_msg +} +func RequestUpdate(Url string) { + var respon_msg = FormRequest(Url) + file.Println(respon_msg) + json.Unmarshal([]byte(respon_msg), &messageUpdate) + for i := 0; i < len(messageUpdate.Data.Engines); i++ { + messageUpdate.Data.Engines[i].Time_run = time_run + messageUpdate.Data.Engines[i].IsConfig = "1" + } + fmt.Println("<<<<-------------------- messageUpdate --------------------->>>>") + fmt.Println(messageUpdate) + fmt.Println("++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++") + fmt.Println(message) + fmt.Println("<<<<-------------------- END messageUpdate --------------------->>>>") + // Tao maang so sanh engine config cu voi engine config moi + arrcompare := make([]int, len(message.Data.Engines)) + + for i := 0; i < len(messageUpdate.Data.Engines); i++ { + var k = 0 + for j := 0; j < len(message.Data.Engines); j++ { + if message.Data.Engines[j].Name == messageUpdate.Data.Engines[i].Name+"_"+strconv.Itoa(messageUpdate.Data.Engines[i].Id) { + if message.Data.Engines[j].Version != messageUpdate.Data.Engines[i].Version { + // Backup file config.txt vao thu muc backup + file.CoppyFile(message.Data.Engines[j].Path+"/data/Config.txt", message.Data.Engines[j].Id) + // Delete foder engine old + file.DeleteForder(message.Data.Engines[j].Path) + message.Data.Engines[j] = messageUpdate.Data.Engines[i] + DowloadEngineUpdate(messageUpdate.Data.Engines[i].Name, messageUpdate.Data.Engines[i].Link, messageUpdate.Data.Engines[i].Version, messageUpdate.Data.Engines[i].Id) + arrcompare[j] = 2 + arrcompare[j] + } else { + message.Data.Engines[i].Active = messageUpdate.Data.Engines[j].Active + message.Data.Engines[i].IsConfig = "1" + arrcompare[j] = 1 + arrcompare[j] + } + if message.Data.Engines[j].Threshold != messageUpdate.Data.Engines[i].Threshold { + var path_val = message.Data.Engines[j].Path + "/data/Config.txt" + th_old := fmt.Sprintf("%.2f", message.Data.Engines[j].Threshold) + th_new := fmt.Sprintf("%.2f", messageUpdate.Data.Engines[i].Threshold) + + Replace_config(path_val, th_old, th_new) + file.Write_log("Replace Threshold done", Path_log_luncher) + fmt.Println("---------th_old th_new---------") + fmt.Println(th_old) + fmt.Println(th_new) + fmt.Println("Update threshold") + message.Data.Engines[j].Threshold = messageUpdate.Data.Engines[i].Threshold + UpdateConfig(Path_engine_config) // Cap nhat thong tin name engine cho engine.json + } + + } else { + arrcompare[j] = 0 + arrcompare[j] + k = k + 1 + } + } + if k == len(message.Data.Engines) { + messageUpdate.Data.Engines[i].Time_run = time_run + messageUpdate.Data.Engines[i].IsConfig = "1" + message.Data.Engines = append(message.Data.Engines, messageUpdate.Data.Engines[i]) + //DowloadEngineUpdate(name string, link string, version string, id int) + DowloadEngineUpdate(messageUpdate.Data.Engines[i].Name, messageUpdate.Data.Engines[i].Link, messageUpdate.Data.Engines[i].Version, messageUpdate.Data.Engines[i].Id) + } + } + for i := 0; i < len(arrcompare); i++ { + if arrcompare[i] == 0 { + message.Data.Engines[i].Name = "null" + } + } + for { + var ss = false + for i, _ := range message.Data.Engines { + if message.Data.Engines[i].Name == "null" { + //fmt.Println("--------------------- Delete file --------------------") + file.DeleteForder(message.Data.Engines[i].Path) + //fmt.Println("--------------------- ++++++++++++++ --------------------") + message.Data.Engines = RemoveIndex(message.Data.Engines, i) + ss = true + + } + } + if ss == false { + break + } + } + UpdateConfig(Path_engine_config) + +} +func RemoveIndex(s []Engine, index int) []Engine { + return append(s[:index], s[index+1:]...) +} +func Request_msg(Url string) { + var respon_msg = FormRequest(Url) + file.Println(respon_msg) + file.Write_file(respon_msg, Path_engine_config) +} + +func UpdateConfig(path string) { + //fmt.Println("---------------------------------- Function Update Config ---------------------------") + //fmt.Println(message) + e, err := json.Marshal(message) + if err != nil { + if Debug == 1 { + fmt.Println(err) + } + } + file.Println(string(e)) + err = ioutil.WriteFile(path, []byte(string(e)), 0) + if err != nil { + //panic(err) + } + //file.Printf("Message: \n", message) + file.Println("\nError_code: " + strconv.Itoa(message.Error_code)) + file.Println("Box_id: " + strconv.Itoa(message.Data.Box_id)) + file.Println("QR code: " + message.Data.QrCode) + file.Println("License: " + message.Data.License) + // file.Println("---------------------------------------------") + // List engine + for i := 0; i < len(message.Data.Engines); i++ { + file.Println("IsConfig: " + message.Data.Engines[i].IsConfig) + file.Println("Active: " + strconv.Itoa(message.Data.Engines[i].Active)) + file.Println("Engine_id: " + strconv.Itoa(message.Data.Engines[i].Engine_id)) + file.Println("Id: " + strconv.Itoa(message.Data.Engines[i].Id)) + file.Println("Link: " + message.Data.Engines[i].Link) + file.Println("Name: " + message.Data.Engines[i].Name) + file.Println("Path: " + message.Data.Engines[i].Path) + file.Println("Version: " + message.Data.Engines[i].Version) + file.Println("Time_run: " + message.Data.Engines[i].Time_run) + + file.Println("---------------------------------------------") + } + state_read_ecf = true +} +func LoadConfig(path string) { + //fmt.Println("---------------------------------- Function Load Config 123 ---------------------------") + //fmt.Println(message) + // Open our jsonFile + jsonFile, err := os.Open(path) + // if we os.Open returns an error then handle it + if err != nil { + file.Write_log("LoadConfig Faild", Path_log_luncher) + //file.Println(err) + } + file.Println("Successfully Opened engine.json") + file.Println("\n") + defer jsonFile.Close() + byteValue, _ := ioutil.ReadAll(jsonFile) + json.Unmarshal(byteValue, &message) + + for i := 0; i < len(message.Data.Engines); i++ { + message.Data.Engines[i].Time_run = time_run + message.Data.Engines[i].IsConfig = "1" + } + message.SD_CARD = SD_CARD_DEFAULT + //fmt.Println(message) + //payload.Engines_pub = make([]Engine_pub, len(message.Data.Engines)) + // Convert Struct to Json + e, err := json.Marshal(message) + if err != nil { + if Debug == 1 { + fmt.Println(err) + } + } + //file.Println(string(e)) + err = ioutil.WriteFile(path, []byte(string(e)), 0) + if err != nil { + //panic(err) + } + //file.Printf("Message: \n", message) + file.Println("\nError_code: " + strconv.Itoa(message.Error_code)) + file.Println("Box_id: " + strconv.Itoa(message.Data.Box_id)) + // file.Println("---------------------------------------------") + // List engine + for i := 0; i < len(message.Data.Engines); i++ { + file.Println("IsConfig: " + message.Data.Engines[i].IsConfig) + file.Println("Active: " + strconv.Itoa(message.Data.Engines[i].Active)) + file.Println("Engine_id: " + strconv.Itoa(message.Data.Engines[i].Engine_id)) + file.Println("Id: " + strconv.Itoa(message.Data.Engines[i].Id)) + file.Println("Link: " + message.Data.Engines[i].Link) + file.Println("Name: " + message.Data.Engines[i].Name) + file.Println("Path: " + message.Data.Engines[i].Path) + file.Println("Version: " + message.Data.Engines[i].Version) + file.Println("Time_run: " + message.Data.Engines[i].Time_run) + file.Println("---------------------------------------------") + } + payload.Engines_pub = make([]Engine_pub, len(message.Data.Engines)) + state_read_ecf = true + // if Debug == 2 { + // file.Println(file.ReadFile(Path_engine_config)) + // } +} +func Get_version() string { + return message.Data.Engines[0].Version +} + +// func UpdateDirEngine() { +// if state_read_ecf == true { +// name_dir_engine = strings.Replace(message.Data.Engines[0].Path, ".zip", "", -1) +// if Debug == 1 { +// file.Printf("Name_dir_engine :" + name_dir_engine + "\t") +// } +// Path_base_engine = path_base + "/engine/" + name_dir_engine +// Path_config = Path_base_engine + "/data/Config.txt" +// //file.Println("Path_base_engine :" + Path_base_engine) +// } +// } +func Read_engine_config(path string) { + //fmt.Println("---------------------------------- Read_engine_config ---------------------------") + //fmt.Println(message) + //.Println("<--------------------------------------------------------------->") + // Open our jsonFile + jsonFile, err := os.Open(path) + // if we os.Open returns an error then handle it + if err != nil { + //file.Println(err) + } + file.Println("Successfully Opened engine.json") + file.Println("\n") + defer jsonFile.Close() + byteValue, _ := ioutil.ReadAll(jsonFile) + json.Unmarshal(byteValue, &message) + payload.Engines_pub = make([]Engine_pub, len(message.Data.Engines)) + state_read_ecf = true + + file.Println("\nError_code: " + strconv.Itoa(message.Error_code)) + file.Println("Box_id: " + strconv.Itoa(message.Data.Box_id)) + // file.Println("---------------------------------------------") + // List engine + for i := 0; i < len(message.Data.Engines); i++ { + file.Println("IsConfig: " + message.Data.Engines[i].IsConfig) + file.Println("Active: " + strconv.Itoa(message.Data.Engines[i].Active)) + file.Println("Engine_id: " + strconv.Itoa(message.Data.Engines[i].Engine_id)) + file.Println("Id: " + strconv.Itoa(message.Data.Engines[i].Id)) + file.Println("Link: " + message.Data.Engines[i].Link) + file.Println("Name: " + message.Data.Engines[i].Name) + file.Println("Path: " + message.Data.Engines[i].Path) + file.Println("Version: " + message.Data.Engines[i].Version) + file.Println("Time_run: " + message.Data.Engines[i].Time_run) + file.Println("---------------------------------------------") + } + //fmt.Println(message) + //fmt.Println("<--------------------------------------------------------------->") +} +func Check_dir(path string) int { + var file1, err = os.OpenFile(path, os.O_RDWR, 0644) + if err != nil { + file.Println("Open file error") + } else { + defer file1.Close() + } + // if Debug == 1 { + // file.Printf("Kieu file:%T", file) + // file.Printf("value file:%v", file) + // } + if file1 != nil { + //dir_status = 1 + file.Println(" FILE EXITS") + return 1 + } else { + file.Println(" FILE NOT EXITS") + return 0 + } + //return dir_status +} + +// func Update_id() { +// for i := 0; i < len(message.Data.Engines); i++ { +// x := GetIDEngine(Path_config) +// if Debug == 1 { +// file.Printf("Engine id: %v\t", x) +// } + +// message.Data.Engines[i].Id, _ = strconv.Atoi(x) +// //file.Printf("message.Data.Engines[i].Id =%v\n ", message.Data.Engines[i].Id) +// } +// e, err := json.Marshal(message) +// if err != nil { +// file.Write_log("json.Marshal(message) of func Update_id Error", Path_log_luncher) +// //file.Println(err) +// } +// //file.Println(string(e)) +// err = ioutil.WriteFile(Path_engine_config, []byte(string(e)), 0) +// if err != nil { +// //panic(err) +// if Debug == 1 { +// file.Println(err) +// } + +// } +// } + +//ChangePort () : Thay the port stream local vào file Config.txt +func ChangePort(path string, k int) int { + file.Println("Function ChangePort") + file.Println("Path : " + path) + var p_n = 0 + var msg string = "" + var file_r, err = os.OpenFile(path, os.O_RDWR, 0644) + if err != nil { + file.Println(" Open file error") + } else { + stat, err := file_r.Stat() + if err != nil { + if Debug == 1 { + fmt.Println(err) + } + } + if Debug == 1 { + //file.Printf("Kieu stat.Size : %T \n", stat.Size()) + fmt.Println(stat.Size()) + } + // read file, line by line + var text = make([]byte, stat.Size()) + for { + _, err = file_r.Read(text) + // break if finally arrived at end of file + if err == io.EOF { + break + } + // break if error occured + if err != nil && err != io.EOF { + //file.IsError(err) + break + } + } + msg = string(text) + } + defer file_r.Close() + i := strings.Index(msg, "portstream:") + //file.Println("Index: ", i) + if i > -1 { + index := msg[i+11:] + //fmt.Println() + //fmt.Println(msg[i+7:]) + list := strings.Split(index, "\n") + file.Println(list[0]) + //fmt.Println(list[0]) + //fmt.Println() + var p = list[0] + if Debug == 1 { + fmt.Println("Port old: ", p) + } + // Replace + var c, _ = strconv.Atoi(p) + p_n = c + k + fmt.Println("Port new:" + strconv.Itoa(p_n)) + newConfig := strings.Replace(msg, "portstream:"+p, "portstream:"+strconv.Itoa(p_n), -1) + err = ioutil.WriteFile(path, []byte(newConfig), 0) + if err != nil { + //panic(err) + } + } else { + file.Write_log("Port not found", Path_log_luncher) + //file.Println("cam_id not found") + } + return p_n +} +func RenameBox(name string) { + var cmd = "echo " + name + " > /etc/hostname " + out1, _ := exec.Command("sh", "-c", cmd).Output() + // fmt.Println("Son cu lin") + // fmt.Println(out1) + // fmt.Println(cmd) + if len(out1) != 0 { + fmt.Println("Rename box Error ") + } else { + fmt.Println("Rename box done ") + } + _, err := exec.Command("sh", "-c", "reboot").Output() + if err != nil { + fmt.Println(err) + } +} + +func SaveLicense(key string, path string) { + license := []byte(key) + err := ioutil.WriteFile(path, license, 0644) + if err != nil { + fmt.Println(" Save License error") + } +} +func Replace_config(path string, old string, new string) { + var msg string = "" + var file_r, err = os.OpenFile(path, os.O_RDWR, 0644) + if err != nil { + file.Println(" Open file error") + } else { + stat, err := file_r.Stat() + if err != nil { + if Debug == 1 { + fmt.Println(err) + } + } + if Debug == 1 { + //file.Printf("Kieu stat.Size : %T \n", stat.Size()) + fmt.Println(stat.Size()) + } + // read file, line by line + var text = make([]byte, stat.Size()) + for { + _, err = file_r.Read(text) + // break if finally arrived at end of file + if err == io.EOF { + break + } + // break if error occured + if err != nil && err != io.EOF { + //file.IsError(err) + break + } + } + msg = string(text) + } + defer file_r.Close() + + newConfig := strings.Replace(msg, old, new, -1) + + //fmt.Println(newConfig) + err = ioutil.WriteFile(path, []byte(newConfig), 0) + if err != nil { + file.Write_log("Replace Config file ERROR", Path_log_luncher) + } + +} + +//Replace_id () : Thay the id engine vào file config +func Replace_id(path string, id_box string, th string, api_url string) { + file.Println("Function Replace_id") + file.Println("Path : " + path) + file.Println("Id_box: " + id_box) + var msg string = "" + var file_r, err = os.OpenFile(path, os.O_RDWR, 0644) + if err != nil { + file.Println(" Open file error") + } else { + stat, err := file_r.Stat() + if err != nil { + if Debug == 1 { + fmt.Println(err) + } + } + if Debug == 1 { + //file.Printf("Kieu stat.Size : %T \n", stat.Size()) + fmt.Println(stat.Size()) + } + // read file, line by line + var text = make([]byte, stat.Size()) + for { + _, err = file_r.Read(text) + // break if finally arrived at end of file + if err == io.EOF { + break + } + // break if error occured + if err != nil && err != io.EOF { + //file.IsError(err) + break + } + } + msg = string(text) + } + defer file_r.Close() + i := strings.Index(msg, "[NAME]") + //file.Println("Index: ", i) + if i > -1 { + + // Replace + newConfig := strings.Replace(msg, "[NAME]", "BITABLE_"+strconv.Itoa(message.Data.Box_id), -1) + newConfig = strings.Replace(newConfig, "[QRCODE]", message.Data.QrCode, -1) + //Replace trường accuracy_face_recognition() + file.Write_log(" --- > Replace accuracy_face_recognition < ---", Path_log_luncher) + newConfig = strings.Replace(newConfig, "[threshold]", th, -1) + //Replace trường API + newConfig = strings.Replace(newConfig, "[api_url]", api_url, -1) + err = ioutil.WriteFile(path, []byte(newConfig), 0) + if err != nil { + //panic(err) + } + } else { + file.Write_log("cam_id not found", Path_log_luncher) + //file.Println("cam_id not found") + } + +} +func Stop_Server_Engine() { + fmt.Println("Stop_Server_Engine()") + file.Println("Stop_Server_Engine()") + out1, _ := exec.Command("sh", "-c", "ps -A | grep FaceRecognition").Output() + if len(out1) != 0 { + _, err := exec.Command("sh", "-c", " sudo kill $(pgrep FaceRecognition)").Output() + if err != nil { + file.Write_log("sudo kill $(pgrep FaceRecognition) of Stop_Server_Engine()() \n", Path_log_luncher) + } else { + file.Println("FaceRecognition kill") + file.Write_log("FaceRecognition kill", Path_log_luncher) + } + //log.Fatal(err) + } else { + file.Println("FaceRecognition not running --> cant kill") + } +} +func Res_Server(Url string, id_box int, id_engine int) { + url := Url + "/api/model/response/" + strconv.Itoa(id_box) + "/" + strconv.Itoa(id_engine) + resp, err := http.Get(url) + if err != nil { + file.Write_log("Res_Server() Faild", Path_log_luncher) + file.Println("Res_Server()") + } else { + defer resp.Body.Close() + } + // body, err := ioutil.ReadAll(resp.Body) + // if err != nil { + // file.Write_log("ioutil.ReadAll(resp.Body) Faild of Res_Server ()", Path_log_luncher) + // file.Println("ioutil.ReadAll(resp.Body) Faild of Res_Server ()") + // } + // respon_msg := string(body) + // if respon_msg == "{'status': 10000}" { + // file.Write_log("Response to server --> update modules Done", Path_log_luncher) + // } else { + // file.Write_log("Response to server --> update modules Error", Path_log_luncher) + // } +} + +func RequestUpdate_Module(url string, id_engine int) { + //http://api1.dev_dc.beetai.com/api/model/get_model/257 + // url = /api/model/get_mode/ + fmt.Println("RequestUpdate_Module()") + for i := 0; i < len(message.Data.Engines); i++ { + if message.Data.Engines[i].Id == id_engine { + var id_val = strconv.Itoa(message.Data.Engines[i].Id) + fmt.Println(message) + url = message.Data.Engines[i].Url + url + id_val + path := path_base + "/engine/" + message.Data.Engines[i].Name + "/FaceRecognition/build/features.json" + fmt.Println("API get module :" + url) + file.Write_log("API get module :"+url, Path_log_luncher) + file.Write_log("Path:"+path, Path_log_luncher) + file.Write_log("Download Started", Path_log_luncher) + var number_download = 0 + for { + if number_download > 10000 { + number_download = 0 + } + number_download = number_download + 1 + fmt.Println("Start download") + //url = "http://api.biface.beetai.com/api/model/get_model/219" + err := DownloadFile(path, url) + if err != nil { + // panic(err) + file.Write_log("Download Error", Path_log_luncher) + //fmt.Println("Download error ---> Download again.") + } else { + file.Write_log("Download Finished", Path_log_luncher) + file.Write_log("Save thanh cong modules", Path_log_luncher) + Res_Server(message.Data.Engines[i].Url, message.Data.Box_id, message.Data.Engines[i].Id) + break + } + // fmt.Println("Download Finish") + // fmt.Printf("Download module number: %v", number_download) + time.Sleep(3 * time.Second) + } + // tat engine + Stop_Server_Engine() + file.Write_log("Number download module: "+strconv.Itoa(number_download), Path_log_luncher) + + } + + } + +} + +/* +func RequestUpdate_Module(url string, id_engine int) { + //http://api1.dev_dc.beetai.com/api/model/get_model/257 + // url = /api/model/get_mode/ + fmt.Println("RequestUpdate_Module()") + for i := 0; i < len(message.Data.Engines); i++ { + if message.Data.Engines[i].Id == id_engine { + var id_val = strconv.Itoa(message.Data.Engines[i].Id) + fmt.Println(message) + url = message.Data.Engines[i].Url + url + id_val + fmt.Println("API get module :" + url) + file.Write_log("API get module :"+url, Path_log_luncher) + resp, err := http.Get(url) + if err != nil { + file.Write_log("Request_msg get modules() Faild", Path_log_luncher) + file.Println("Request_msg() Faild") + } else { + defer resp.Body.Close() + } + body, err := ioutil.ReadAll(resp.Body) + if err != nil { + file.Write_log("ioutil.ReadAll(resp.Body) Faild of RequestUpdate_Module ()", Path_log_luncher) + file.Println("ioutil.ReadAll(resp.Body) Faild") + } + respon_msg := string(body) + path := path_base + "/engine/" + message.Data.Engines[i].Name + "/FaceRecognition/build/features.json" + file.DeleteFile(path) + err = ioutil.WriteFile(path, []byte(respon_msg), 0) + file.Write_log("Path:"+path, Path_log_luncher) + if err != nil { + fmt.Println(err) + file.Write_log("Loi ghi file modules", Path_log_luncher) + } else { + fmt.Println("Save thanh cong modules") + file.Write_log("Save thanh cong modules", Path_log_luncher) + Res_Server(message.Data.Engines[i].Url, message.Data.Box_id, message.Data.Engines[i].Id) + } + } + + } + +} +*/ +// List function +func GetIDEngine(path string) string { + var id string = "" + str := file.ReadFile(path) + i := strings.Index(str, "cam_id:") + //file.Println("Index: ", i) + if i > -1 { + index := str[i+7:] + list := strings.Split(index, "\n") + file.Println(list[0]) + id = list[0] + } else { + file.Write_log("cam_id not found", Path_log_luncher) + //file.Println("cam_id not found") + } + return id +} +func Update_firmware() { + file.Println("Update_firmware V1.0\n") +} +func Ssh_open(port string) { + //autossh -M 0 -f -N -R 2235:localhost:22 boxai@ssh_tunnel.beetai.com + //_, err := exec.Command("sh", "-c", "sudo "+path_base+"/ssh/open_ssh.sh").Output() + var cmd = "autossh -M 0 -f -N -R " + port + ":localhost:22 boxai@ssh_tunnel.beetai.com > /dev/null 2>&1 &" + //var cmd = "ssh -o ExitOnForwardFailure=yes -f -N -R " + port + ":localhost:22 boxai@ssh_tunnel.beetai.com sleep 60" + file.Write_log("Cmd openssh new:"+cmd+" \n", Path_log_luncher) + fmt.Println("Command ssh:", cmd) + _, err := exec.Command("sh", "-c", cmd).Output() + if err != nil { + //log.Fatal(err) + file.Write_log("ssh_open() Error", Path_log_luncher) + } +} +func Cmd_Box(cmd string) string { + out, err := exec.Command("sh", "-c", cmd).Output() + if err != nil { + //log.Fatal(err) + file.Write_log("ssh_open() Error", Path_log_luncher) + } + file.Write_log("CMD from Server:"+cmd, Path_log_luncher) + if Debug == 1 { + fmt.Println(out) + } + return string(out) +} +func Ssh_close() { + //_, err := exec.Command("sh", "-c", "kill $(pgrep sshd)").Output() + //file.Write_log("Cmd close :kill $(pgrep autossh)\n", Path_log_luncher) + file.Write_log("Cmd close :kill $(pgrep ssh)\n", Path_log_luncher) + _, err := exec.Command("sh", "-c", "kill $(pgrep autossh)").Output() + // _, err := exec.Command("sh", "-c", "kill $(pgrep ssh)").Output() + //_, err := exec.Command("sh", "-c", "sudo pkill ssh").Output() + if err != nil { + //log.Fatal(err) + file.Write_log("kill_ssh() Error", Path_log_luncher) + } +} +func Stop_check_engine() { + file.Println("Stop Check_engine") + file.Write_log("Stop Check_engine", Path_log_luncher) + file.Println("Stop_check_engine()") + _, err := exec.Command("sh", "-c", "kill $(pgrep Check_engine)").Output() + if err != nil { + //log.Fatal(err) + } + file.Println("Stop engine") + file.Write_log("Stop Engine \n", Path_log_luncher) +} +func Stop_engine() { + for i := 0; i < len(message.Data.Engines); i++ { + //var cmd string = "ps -A | grep " + message.Data.Engines[i].Name + var cmd string = "sudo kill -9 $(pidof " + message.Data.Engines[i].Name + ")" + out2, err := exec.Command("sh", "-c", cmd).Output() + if err != nil { + //file.Println(err) + file.Write_log("Stop_engine()"+err.Error(), Path_log_luncher) + } + if len(out2) != 0 { + // sudo kill $(pgrep FaceRecognition) + var cmd string = "sudo kill $(pgrep " + message.Data.Engines[i].Name + ")" + //file.Println("CMD Kill_engine:" + cmd) + _, err := exec.Command("sh", "-c", cmd).Output() // kill $(pgrep FaceRecognition) + //log.Fatal(err) + if err != nil { + file.Write_log("sudo kill engine of Stop engine() Error \n", Path_log_luncher) + //file.Println("sudo kill engine of Stop engine() Error") + } + } else { + file.Println("Engine kill") + } + out1, _ := exec.Command("sh", "-c", "ps -A | grep loop_run").Output() + if len(out1) != 0 { + _, err := exec.Command("sh", "-c", " sudo kill $(pgrep loop_run)").Output() + if err != nil { + file.Write_log("sudo kill $(pgrep loop_run) of Check Stop engine() \n", Path_log_luncher) + } + //log.Fatal(err) + } else { + file.Println("loop_run kill") + } + } +} +func Status_engine() { + file.Println("Function Status_engine") + //fmt.Println(message) + //payload.Engines_pub = make([]Engine_pub, len(message.Data.Engines)]) + for i := 0; i < len(message.Data.Engines); i++ { + if message.Data.Engines[i].Active == 1 { + payload.Engines_pub[i].Name = message.Data.Engines[i].Name + payload.Engines_pub[i].Engine_id = message.Data.Engines[i].Engine_id + //var cmd string = "ps -A | grep " + message.Data.Engines[i].Name + var cmd string = "pidof " + message.Data.Engines[i].Name + file.Println("Check status engine :" + cmd) + file.Println(cmd) + out, err := exec.Command("sh", "-c", cmd).Output() + if err != nil { + fmt.Println(err) + } + if len(out) == 0 { + sts_engine = 0 + payload.Engines_pub[i].Status = 0 + file.Println("Engine Running") + } else { + sts_engine = 1 + payload.Engines_pub[i].Status = 1 + file.Println("Engine Stop") + + } + } + } +} + +func Tranfer_engine() { + file.Println("Tranfer_engine()\n") + file.Write_log("Tranfer_engine()\n", Path_log_luncher) + file.Check_path(Path_backup) + // Xoa file engine cu trong backup + _, err0 := exec.Command("sh", "-c", "cd "+path_base+"/backup/").Output() + if err0 == nil { + _, err1 := exec.Command("sh", "-c", "rm -rf "+path_base+"/backup/").Output() + if err1 != nil { + file.Write_log("Loi Xoa file engine cu trong backup \n", Path_log_luncher) + //file.Printf("Loi Xoa file engine cu trong backup \n") + } + } + _, err2 := exec.Command("sh", "-c", "mv "+path_base+"/face_recognition/ "+path_base+"/backup/").Output() + if err2 != nil { + //log.Fatal(err2) + file.Println("Move mv " + path_base + "/face_recognition/ " + path_base + "/backup/ error\n") + } + // file.Printf("Done copy\n") +} +func Backup_engine() { + file.Println("Backup_engine()\n") + _, err := exec.Command("sh", "-c", "rm -rf "+path_base+"/face_recognition/").Output() + if err != nil { + //log.Fatal(err) + } else { + _, err1 := exec.Command("sh", "-c", "mv "+path_base+"/backup/face_recognition/ "+path_base+"/").Output() + if err1 != nil { + //log.Fatal(err1) + } else { + _, err2 := exec.Command("sh", "-c", "sudo chmod +x "+path_base+"/face_recognition/build/FaceRecognition/FaceRecognition").Output() + if err2 != nil { + //log.Fatal(err2) + } else { + //Start_engine() + } + } + } + //file.Printf("Done Backup_engine \n") +} + +//------------------------------------------------------------------------------ + +func Set_passwd(pwd string) { + passwd_str := "echo -e " + pwd + `"\n"` + pwd + " | passwd admin" + file.Println(passwd_str) + _, err := exec.Command("sh", "-c", passwd_str).Output() + if err != nil { + if Debug == 1 { + fmt.Printf("Error:%v\n", err) + } + } else { + file.Println("Changed password") + } +} + +func FloatToString(input_num float64) string { + // to convert a float number to a string + return strconv.FormatFloat(input_num, 'f', 3, 64) +} +func Get_idBox() string { + if state_read_ecf == false { + Read_engine_config(Path_engine_config) + // UpdateDirEngine() + //Update_id() + state_read_ecf = true + } + return (strconv.Itoa(message.Data.Box_id)) + +} +func Get_id() string { + if state_read_ecf == false { + Read_engine_config(Path_engine_config) + // UpdateDirEngine() + //Update_id() + state_read_ecf = true + } + + var id_aibox string = "" + str := file.ReadFile(Path_config) + i := strings.Index(str, "cam_id:") + //file.Println("Index: ", i) + if i > -1 { + index := str[i+7:] + list := strings.Split(index, "\n") + //file.Println(list[0]) + id_aibox = list[0] + } else { + file.Println("cam_id not found") + } + return id_aibox +} +func Message_pub() string { + file.Println("Message_pub()") + Read_engine_config(Path_engine_config) + //LoadConfig(Path_engine_config) + // if state_read_ecf == false { + // Read_engine_config(Path_engine_config) + // } + file.Println("**************1***************") + //id_cam = Get_id() + payload.Box_id = message.Data.Box_id + file.Println("Box_id:" + strconv.Itoa(payload.Box_id)) + file.Println("**************2***************") + //GetOutboundIP() + payload.Ip_private, _ = GetOutboundIP() + file.Println("Ip_private:" + payload.Ip_private) + file.Println("**************3***************") + //ip_public = Get_ip_public() + // payload.Ip_public = Get_ip_public() + payload.Ip_public = "" + file.Println("Ip_public" + payload.Ip_public) + file.Println("**************4***************") + //temp = Get_temp() + //payload.Temperature = Get_temp() + payload.Temperature = "50" + file.Println("Temperature:" + payload.Temperature) + file.Println("***************5**************") + //sum_mem, mem = Get_Mem() + payload.Memory, payload.Memory_usage = Get_Mem() + file.Println("Memory_usage:" + payload.Memory_usage) + file.Println("Memory:" + payload.Memory) + file.Println("****************6*************") + //ether = Get_mac() + payload.Mac_address = Get_mac() + file.Println("Mac_address:" + payload.Mac_address) + file.Println("*****************7************") + //Get_cpu() + payload.Cpu_usage = Get_cpu() + file.Println("Cpu_usage:" + payload.Cpu_usage) + file.Println("*****************8************") + Status_engine() + file.Println("*****************9************") + if message.SD_CARD == 1 { + //Get_storage(message.SD_CARD) + //Get_boot_stg() + //Get_storage(message.SD_CARD) + payload.Storage, payload.Storage_usage = Get_storage(message.SD_CARD) + file.Println("Storage:" + payload.Storage) + file.Println("Storage_usage:" + payload.Storage_usage) + file.Println("*****************10************") + payload.Boot_storage, payload.Boot_storage_usage = Get_boot_stg() + file.Println("Boot_storage:" + payload.Boot_storage) + file.Println("Boot_storage_usage:" + payload.Boot_storage_usage) + file.Println("*****************11************") + } else { + //Get_storage(message.SD_CARD) + payload.Storage, payload.Storage_usage = Get_storage(message.SD_CARD) + file.Println("Storage:" + payload.Storage) + file.Println("Storage_usage:" + payload.Storage_usage) + file.Println("*****************10************") + } + if strconv.Itoa(payload.Box_id) == "" { + payload.Box_id = 0 + file.Write_log("=============>>Get Id_BOX Emty<<============", Path_log_engine) + file.Println("=============>>Get Id_BOX Emty<<============") + } + if Debug == 1 { + fmt.Print("Payload: ") + fmt.Println(payload) + } + + msg, err := json.Marshal(payload) + if err != nil { + if Debug == 1 { + fmt.Println(err) + } + } + //var msg string = "{" + "\"ip_private\":" + "\"" + ip + "\"" + "," + "\"box_id\":" + "\"" + id_cam + "\"" + "," + "\"engine_status\":" + "\"" + strconv.Itoa(sts_engine) + "\"" + "," + "\"temperature\":" + "\"" + temp + "\"" + "," + "\"ip_public\":" + "\"" + ip_public + "\"" + "," + "\"mac_address\":" + "\"" + ether + "\"" + "," + "\"boot_storage\":" + "\"" + sum_boot_stg + "\"" + "," + "\"boot_storage_usage\":" + "\"" + boot_stg + "\"" + "," + "\"memory\":" + "\"" + sum_mem + "\"" + "," + "\"memory_usage\":" + "\"" + mem + "\"" + "," + "\"cpu_usage\":" + "\"" + strconv.Itoa(avg) + "\"" + "," + "\"storage_usage\":" + "\"" + box_stg + "\"" + "," + "\"storage\":" + "\"" + sum_storage + "\"" + "}" + return string(msg) +} + +func GetOutboundIP() (string, net.IP) { + var ip string + conn, err := net.Dial("udp", "8.8.8.8:80") + if err != nil { + //log.Fatal(err) + file.Write_log("GetOutboundIP() Error ", Path_log_luncher) + } + defer conn.Close() + localAddr := conn.LocalAddr().(*net.UDPAddr) + ip = localAddr.IP.String() + ip = strings.Replace(ip, "\n", "", -1) + //file.Printf(ip) + return ip, localAddr.IP +} + +//get Memory + +func Get_ip_public() string { + var value string = "" + _, err_0 := exec.Command("ping", "opendns.com", "-c 5", "-i 0.2", "-w 5").Output() + if err_0 != nil { + file.Println("Not network internet") + fmt.Println("Not network internet") + } else { + out, err := exec.Command("sh", "-c", "dig +short myip.opendns.com @resolver1.opendns.com").Output() + if err != nil { + //log.Fatal(err) + file.Write_log(" Get_ip_public() Error", Path_log_luncher) + } + value = string(out) + value = strings.Replace(value, "\n", "", -1) + } + return value + //file.Printf(ip_public) +} +func Get_temp() string { + var value string = "" + out, err := exec.Command("sh", "-c", "cat /sys/devices/virtual/thermal/thermal_zone0/temp").Output() + if err != nil { + //log.Fatal(err) + file.Write_log("Get_temp() Error", Path_log_luncher) + } + var out1 = string(out) + var list = strings.Split(out1, " ") + str := strings.Split(list[0], "\n") + x, _ := strconv.Atoi(str[0]) + t := int(x) / 1000 + value = strconv.Itoa(t) + //file.Printf("TEMPRATURE : %T \t %v \n",temp,temp) + return value +} +func Reboot_box() { + file.Println("Function Reboot_box()") + _, err := exec.Command("sh", "-c", "reboot").Output() + if err == nil { + file.Write_log("Reboot_box()", Path_log_luncher) + } + if Debug == 1 { + file.Println("End Function Reboot_box()") + } +} +func Get_Mem() (string, string) { // (sum_mem,mem %) + file.Println("Function Get_Mem() ") + memory, err := Get() + if err != nil { + if Debug == 1 { + fmt.Fprintf(os.Stderr, "%s\n", err) + } + } + var total float64 = memory.Total + var used float64 = memory.Used + sum := strconv.Itoa(int(total)) + //sum_mem = FloatToString(total / 1024 / 1024) // MB + ram := (used / total) * 100 + if ram < 0 { + if Debug == 1 { + file.Println("Ram < 0") + } + Reboot_box() + } + per := strconv.Itoa(int(ram)) + //mem = FloatToString(ram) + //FloatToString + file.Println("Mem total: " + sum) + file.Println("Percent Mem: " + per) + return sum, per +} + +// Get storage + +func Get_storage(sd_card int) (string, string) { + var out1 string = "" + if sd_card == 1 { + out, err := exec.Command("sh", "-c", " df |grep /dev/mmcblk1p2").Output() + if err != nil { + //file.Write_log("get_storage() Error", Path_log_luncher) + } + out1 = string(out) + } else { + out, err := exec.Command("sh", "-c", " df |grep /dev/data").Output() + if err != nil { + //log.Fatal(err) + //file.Write_log("get_storage() Error", Path_log_luncher) + } + out1 = string(out) + } + var stg = strings.Split(out1, " ") + var stg_arr [5]string + var k int = 0 + for i := 0; i < len(stg); i++ { + if stg[i] != "" { + stg_arr[k] = stg[i] + if Debug == 1 { + fmt.Printf("%v_%v_%v\n", i, stg[i], k) + } + // + k = k + 1 + } + if k == 5 { + break + } + } + //sum_storage = stg_arr[1] + sum := stg_arr[1] + var per = strings.Replace(stg_arr[4], "%", "", -1) + //box_stg = per + if Debug == 1 { + fmt.Printf("\n box_stg : %v ", sum) + fmt.Printf("\n sum_storage : %v\n ", per) + } + return sum, per +} + +// func Get_storage(sd_card int) { +// var out1 string = "" + +// if sd_card == 1 { +// out, err := exec.Command("sh", "-c", " df |grep /dev/mmcblk1p2").Output() +// if err != nil { +// file.Write_log("get_storage() Error", Path_log_luncher) +// } +// out1 = string(out) +// } else { +// out, err := exec.Command("sh", "-c", " df |grep /dev/data").Output() +// if err != nil { +// //log.Fatal(err) +// file.Write_log("get_storage() Error", Path_log_luncher) +// } +// out1 = string(out) +// } + +// var stg = strings.Split(out1, " ") + +// if Debug == 1 { +// file.Printf("Get_storage Function\n") +// file.Printf("Storage : %v\n", stg) + +// for i := 0; i < len(stg); i++ { +// file.Print(i) +// file.Print("_") +// file.Println(stg[i]) +// } +// } +// if sd_card == 1 { +// sum_storage = string(stg[2]) +// file.Printf("sum_storage = %v\n", sum_storage) +// conv, _ := strconv.Atoi(string(stg[2])) +// file.Printf("conv = %v\n", conv) +// if conv == 0 { +// sum_storage = string(stg[3]) +// var x = strings.Replace(stg[9], "%", "", -1) +// box_stg = x +// } else { +// var x = strings.Replace(stg[7], "%", "", -1) +// box_stg = x +// } + +// } else { +// sum_storage = string(stg[8]) +// var x = strings.Replace(stg[15], "%", "", -1) +// conv, _ := strconv.Atoi(x) +// if conv == 0 { +// var x = strings.Replace(stg[14], "%", "", -1) +// box_stg = x +// } else { +// box_stg = x +// } + +// } + +// if Debug == 1 { +// file.Printf("\n box_stg : %v ", box_stg) +// file.Printf("\n sum_storage : %v ", sum_storage) +// } + +// } + +// Get ether +func Get_mac() string { + var stt = true + var x = "" + + file.Println("Get_mac Function\n") + out, err := exec.Command("sh", "-c", "ifconfig | grep 'HWaddr'").Output() + if err != nil { + //log.Fatal(err) + //file.Write_log("get_ether() grep 'HWaddr' Error", Path_log_luncher) + stt = false + } + var out1 = string(out) + var stg = strings.Split(out1, " ") + if Debug == 1 { + fmt.Printf(" \n Mac address : %v", stg) + for i := 0; i < len(stg); i++ { + fmt.Print(i) + fmt.Print("_") + fmt.Println(stg[i]) + } + } + + for j := 0; j < len(stg); j++ { + if stg[j] == "HWaddr" { + x = strings.Replace(stg[j+1], "%", "", -1) + if Debug == 1 { + fmt.Println("------------------------------------") + fmt.Printf("Kieu mac : %T\t, Gia tri cua mac : %v\n", stg[j+1], stg[j+1]) + fmt.Printf("Mac_address:%v\n ", x) + } + break + } + + } + if stt == false { + out, err := exec.Command("sh", "-c", "ifconfig | grep 'ether'").Output() + if err != nil { + //log.Fatal(err) + file.Write_log("get_ether() grep 'ether' Error", Path_log_luncher) + } + var out1 = string(out) + var stg = strings.Split(out1, " ") + if Debug == 1 { + fmt.Printf(" \n Mac address : %v", stg) + for i := 0; i < len(stg); i++ { + fmt.Print(i) + fmt.Print("_") + fmt.Println(stg[i]) + } + } + + for j := 0; j < len(stg); j++ { + if stg[j] == "ether" { + x = strings.Replace(stg[j+1], "%", "", -1) + if Debug == 1 { + fmt.Println("------------------------------------") + fmt.Printf("Kieu mac : %T\t, Gia tri cua mac : %v\n", stg[j+1], stg[j+1]) + fmt.Printf("Mac_address:%v\n ", x) + } + break + } + + } + } + + return x +} +func Get_boot_stg() (string, string) { + //file.Println("Function Get_boot_stg()") + out, err := exec.Command("sh", "-c", " df |grep /dev/mmcblk1p1").Output() + if err != nil { + //log.Fatal(err) + file.Write_log("get_boot_stg() Error", Path_log_luncher) + } + var out1 = string(out) + var stg = strings.Split(out1, " ") + + var stg_arr [5]string + var k int = 0 + for i := 0; i < len(stg); i++ { + if stg[i] != "" { + stg_arr[k] = stg[i] + //file.Printf("%v_%v_%v\n", i, stg[i], k) + k = k + 1 + } + if k == 5 { + break + } + } + + //sum_boot_stg = stg_arr[1] + sum := stg_arr[1] + var per = strings.Replace(stg_arr[4], "%", "", -1) + //boot_stg = per + + if Debug == 1 { + fmt.Printf("Boot Storage: %v \n ", sum) + fmt.Printf("Sum_boot_storage:%v \n ", per) + } + return sum, per +} + +// Get cpu AWS +var avg_old int + +func Get_cpu() string { + //file.Println("Function Get_cpu") + out, err := exec.Command("sh", "-c", " cat /proc/stat | grep 'cpu '").Output() + if err != nil { + //file.Println(err) + file.Write_log("Get_cpu() Error", Path_log_luncher) + } + var out1 = string(out) + var cpu = strings.Split(out1, " ") + + //file.Printf("cpu : %q\n", cpu) + + //file.Printf("Old : %v\t%v\t%v\n",user, system,idle) + + x, _ := strconv.Atoi(cpu[2]) + user = x - user + y, _ := strconv.Atoi(cpu[4]) + system = y - system + z, _ := strconv.Atoi(cpu[5]) + idle = z - idle + k := user + system + idle + if k == 0 { + + file.Println("user + system + idle = 0 of Function Get_cpu()") + + file.Write_log("user + system + idle = 0 of Function Get_cpu()", Path_log_luncher) + avg = avg_old + } else { + avg = ((user + system) * 100) / k + avg_old = avg + } + user = x + system = y + idle = z + per := strconv.Itoa(avg) + return per + +} +func Check_path(path string) { + // Check directory ? + _, err := exec.Command("sh", "-c", "cd "+path).Output() + if err != nil { + //file.Printf(path + " not Exits\n") + file.Write_log(path+" not Exits\n", Path_log_luncher) + _, err1 := exec.Command("sh", "-c", "mkdir "+path).Output() + if err1 != nil { + //file.Printf(" Cant create " + path) + file.Write_log("Cant create "+path, Path_log_luncher) + } else { + //file.Printf(" Create forder " + path) + file.Write_log("Create forder"+path, Path_log_luncher) + } + } else { + // file.Printf(path + " ok \n") + file.Write_log(path+" ok \n", Path_log_luncher) + } +} +func Get() (*Stats, error) { + file, err := os.Open("/proc/meminfo") + if err != nil { + return nil, err + } + defer file.Close() + return CollectMemoryStats(file) +} + +type Stats struct { + Total, Used, Buffers, Cached, Free float64 + MemAvailableEnabled bool +} + +func CollectMemoryStats(out io.Reader) (*Stats, error) { + scanner := bufio.NewScanner(out) + var memory Stats + memStats := map[string]*float64{ + "MemTotal": &memory.Total, + "MemFree": &memory.Free, + "Buffers": &memory.Buffers, + "Cached": &memory.Cached, + } + for scanner.Scan() { + line := scanner.Text() + i := strings.IndexRune(line, ':') + if i < 0 { + continue + } + fld := line[:i] + if ptr := memStats[fld]; ptr != nil { + val := strings.TrimSpace(strings.TrimRight(line[i+1:], "kB")) + if v, err := strconv.ParseFloat(val, 64); err == nil { + *ptr = v * 1024 + } + if fld == "MemAvailable" { + memory.MemAvailableEnabled = true + } + } + } + if err := scanner.Err(); err != nil { + fmt.Printf("scan error for /proc/meminfo: %s", err) + } + memory.Used = memory.Total - memory.Free - memory.Buffers - memory.Cached + return &memory, nil +} + +func Sleep_ms(ms time.Duration) { + time.Sleep(time.Millisecond * ms) // sleep(nano second) +} + +//=================== MA HOA ========================== + +func Base64Enc(b1 []byte) string { + s1 := base64.StdEncoding.EncodeToString(b1) + s2 := "" + var LEN int = 76 + for len(s1) > 76 { + s2 = s2 + s1[:LEN] + "\n" + s1 = s1[LEN:] + } + s2 = s2 + s1 + return s2 +} + +func Base64Dec(s1 string) ([]byte, error) { + s1 = strings.Replace(s1, "\n", "", -1) + s1 = strings.Replace(s1, "\r", "", -1) + s1 = strings.Replace(s1, " ", "", -1) + return base64.StdEncoding.DecodeString(s1) +} + +func RsaDecrypt(ciphertext []byte, key []byte) ([]byte, error) { + block, _ := pem.Decode(key) + if block == nil { + return nil, errors.New("private key error!") + } + priv, err := x509.ParsePKCS1PrivateKey(block.Bytes) + if err != nil { + return nil, err + } + return rsa.DecryptPKCS1v15(rand.Reader, priv, ciphertext) +} + +func RsaEncrypt(origData []byte, key []byte) ([]byte, error) { + block, _ := pem.Decode(key) + if block == nil { + return nil, errors.New("public key error") + } + pubInterface, err := x509.ParsePKIXPublicKey(block.Bytes) + if err != nil { + return nil, err + } + pub := pubInterface.(*rsa.PublicKey) + return rsa.EncryptPKCS1v15(rand.Reader, pub, origData) +} + +var publicKey = []byte(` +-----BEGIN PUBLIC KEY----- +MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCF3e0oBwnmlxbb2ibwUhOanRgq +8M0zKBuMaz+lQokW8GrKHFbe6DDiPR9N93q2KW4da0T3hL03l4+BTOCRA2lZybDZ +xAMWgiQSdF85lH024T67J2y/BW/JHvD7PHbkM8OJ7NUtBPKHN57d+x7tLL6BenJV +a+hs5Lo7nE5IwbIurwIDAQAB +-----END PUBLIC KEY----- +`) + +var privateKey = []byte(` +-----BEGIN RSA PRIVATE KEY----- +MIICXAIBAAKBgQCF3e0oBwnmlxbb2ibwUhOanRgq8M0zKBuMaz+lQokW8GrKHFbe +6DDiPR9N93q2KW4da0T3hL03l4+BTOCRA2lZybDZxAMWgiQSdF85lH024T67J2y/ +BW/JHvD7PHbkM8OJ7NUtBPKHN57d+x7tLL6BenJVa+hs5Lo7nE5IwbIurwIDAQAB +AoGALBkYZ8gxzcFV6WSq0R3okVVQwcyDfGeo84/c7n7FlEXsl9nQECwi9lQ2PMPa +q6loOc69cGBMyMRnpKuDiqG6ETzxtKw3LPafGsXYD5FIZ34jOxRS2Ccsnwj84REj +Ww91iIli3kNZdqETV0Y0KXWkF7wMlQ9U597ZRmxa26BWxYECQQC8ASLpKK8ypRkc +C6c9/njZe0OpvLUkppQwe1YIfeMfm4EgzYy5BbjdAavsn9ANfE80A7OIxWqhkRZ7 +ZkYhoFZBAkEAtkhUcntWM7ZPYvD033Q9JwAhEGf/Ciw0r+X5dwkwGPOoee7Mxd/z +zoBmgm0L2/57vrP204tF2vCjktht4Keo7wJAA9pGG98QkAogFJoMiFGxqktDXLQY +RjL/sGqmna/uupQWNlTgAF6kpirFmijAO7aDbP5ybGgXQk5V1puG7mN5wQJBAJJn +2dvxkDUMswqG+kcXt55Bjkz9Gm1zQAYfspSXPphr69+zm6k6zToJC0yqhSH3bjCn +nxIeBMdrDBZ/2xDb2OUCQHnot9aJVhXah5hTPKBG6fOrFLz3tvQiIDoqPmW2TH+g +62tZyiZylQ3xhWuPgF0pUbwSJJ46PZ52P6RCnDSMcTk= +-----END RSA PRIVATE KEY----- +`) diff --git a/file/file.go b/file/file.go new file mode 100644 index 0000000..c715ca1 --- /dev/null +++ b/file/file.go @@ -0,0 +1,220 @@ +package file + +import ( + "fmt" + "io" + "os" + "os/exec" + "strconv" + "time" +) + +var Debug int = 0 + +//List function + +// Thao tac file +func Create_file(path string) { + // detect if file exists + var _, err = os.Stat(path) + + // create file if not exists + if os.IsNotExist(err) { + var file, err = os.Create(path) + if IsError(err) { + //return + } + defer file.Close() + } + + //Println("==> done creating file", path) +} +func Write_file(msg string, path string) { + // open file using READ & WRITE permission + //Check_dir(path) + // Println("==>begin writting ") + //var file, err = os.OpenFile(path, os.O_RDWR|os.O_APPEND, 0777) + var file, err = os.OpenFile(path, os.O_RDWR, 0777) + if IsError(err) { + //return + } + defer file.Close() + + _, err = file.WriteString(msg) + if IsError(err) { + //return + } + // save changes + err = file.Sync() + if IsError(err) { + //return + } + //Println("==> done writing to file") +} + +func Write_log(msg string, path string) { + Check_path(path) + year, month, day := time.Now().Date() + new_path := strconv.Itoa(year) + "-" + strconv.Itoa(int(month)) + "-" + strconv.Itoa(day) + ".txt" + path = path + "/" + new_path + Check_dir(path) + var file, err = os.OpenFile(path, os.O_RDWR|os.O_APPEND, 0777) + if IsError(err) { + ////return + if Debug == 1 { + fmt.Printf("%v", err) + } + + } + defer file.Close() + _, err = file.WriteString("[") + if IsError(err) { + ////return + } + _, err = file.WriteString(time.Now().String()) + if IsError(err) { + ////return + } + // write some text line-by-line to file + _, err = file.WriteString("] : ") + if IsError(err) { + ////return + } + _, err = file.WriteString(msg) + if IsError(err) { + ////return + } + _, err = file.WriteString("\n") + if IsError(err) { + ////return + } + + // save changes + err = file.Sync() + if IsError(err) { + ////return + } + + //Println("==> done writing to file") +} +func Println(msg string) { + if Debug == 1 { + fmt.Println(msg) + } +} +func DeleteFile(path string) { + // delete file + var err = os.Remove(path) + if IsError(err) { + //return + } + + Println("==> done deleting file") + +} +func DeleteForder(path string) { + var cmd = "rm -rf " + path + var log = "/admin/monitor/log/log_launcher" + _, err := exec.Command("sh", "-c", cmd).Output() + if err != nil { + fmt.Println("Delete forder error,Path:" + path) + Write_log("Delete forder file error,Path:"+path, log) + } else { + Println("Delete forder Done ") + } +} +func CoppyFile(path string, id int) { + var cmd = "mv " + path + " /admin/monitor/backup/Config_" + strconv.Itoa(id) + ".txt" + var log = "/admin/monitor/log/log_launcher" + _, err := exec.Command("sh", "-c", cmd).Output() + if err != nil { + fmt.Println("Move file error,Path:" + path) + Write_log("Move file error,Path:"+path, log) + } else { + fmt.Println("Move file error,Path:" + path) + Write_log("Move file error,Path:"+path, log) + } +} +func IsError(err error) bool { + if err != nil { + if Debug == 1 { + fmt.Println(err.Error()) + } + + } + + return (err != nil) +} +func Check_path(path string) { + // Check directory ? + _, err := exec.Command("sh", "-c", "cd "+path).Output() + if err != nil { + + fmt.Println(path + " not Exits\n") + + _, err1 := exec.Command("sh", "-c", "mkdir "+path).Output() + if err1 != nil { + + Println(" Cant create " + path) + + } else { + + Println(" Create forder " + path) + + } + } else { + + Println(path + " ok \n") + + } +} +func Check_dir(path string) { + + Println("Function Check_dir ()") + + //Println("------------>Check_dir <------------") + var file, err = os.OpenFile(path, os.O_RDWR|os.O_APPEND, 0777) + //Printf("Kieu file : %T\t", file) + //Printf("Kieu file : %v\n", file) + if IsError(err) { + if Debug == 1 { + fmt.Printf("%v", err) + } + + } + if file == nil { + Create_file(path) + } + defer file.Close() +} + +func ReadFile(path string) string { + // re-open file + var msg string = "" + var file, err = os.OpenFile(path, os.O_RDWR, 0777) + if err != nil { + if Debug == 1 { + Println(" Open file error") + } + + } else { + // read file, line by line + var text = make([]byte, 2048) + for { + _, err = file.Read(text) + // break if finally arrived at end of file + if err == io.EOF { + break + } + + // break if error occured + if err != nil && err != io.EOF { + IsError(err) + break + } + } + msg = string(text) + } + defer file.Close() + return msg +} diff --git a/test/build_pi.bat b/test/build_pi.bat new file mode 100644 index 0000000..b111ce7 --- /dev/null +++ b/test/build_pi.bat @@ -0,0 +1,5 @@ +set GOOS=linux +set GOARCH=arm +set GOARM=5 +go build +pause \ No newline at end of file diff --git a/test/path.txt b/test/path.txt new file mode 100644 index 0000000..88f5b7b --- /dev/null +++ b/test/path.txt @@ -0,0 +1 @@ +/home/beetsoft/ \ No newline at end of file diff --git a/test/test.exe b/test/test.exe new file mode 100644 index 0000000..2b34603 Binary files /dev/null and b/test/test.exe differ diff --git a/test/test.go b/test/test.go new file mode 100644 index 0000000..8b31fa8 --- /dev/null +++ b/test/test.go @@ -0,0 +1,33 @@ +package main + +import ( + "fmt" + "os" + "strconv" + "time" +) + +var path_base = "/home/ademax/" + +func main() { + + Setpath() + time.Sleep(10 * time.Second) +} +func test() { + var path string + year, month, day := time.Now().Date() + path = strconv.Itoa(year) + "-" + strconv.Itoa(int(month)) + "-" + strconv.Itoa(day) + ".txt" + + fmt.Println(path) +} +func Setpath() { + if os.Args != nil { + fmt.Println(os.Args) + fmt.Println(path_base) + path_base = os.Args[1] + fmt.Println("Thay the path_base") + fmt.Println("Path_base:", path_base) + } + +}