bitable/box/box.go
2020-11-26 16:12:55 +07:00

1930 lines
60 KiB
Go

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-----
`)