package controllers import ( "bytes" "encoding/json" "fmt" "io" "io/ioutil" "net/http" "os" "reflect" "strconv" "strings" "time" "dashoo.cn/business2/permission" "dashoo.cn/labsop" "dashoo.cn/utils" "github.com/axgle/mahonia" "github.com/nsqio/go-nsq" ) type blackboxddata struct { Code string Datapoint labsop.DatapointLabSop } type RandomOrderNumRequest struct { Id int64 `json:"id"` } // 保留两位小数 func Get2point(v float64) string { return strconv.FormatFloat(v, 'f', 2, 64) } //格式化时间 func FormatTime(timein time.Time) string { var timestring = timein.Format("2006-01-02") if strings.Contains("0001-01-01", timestring) { return "" } else { return timein.Format("2006-01-02") } } func Timeisnull(t time.Time) bool { var to time.Time return t.Equal(to) } func Apiget(str string) (body []byte) { str = strings.Replace(str, " ", "%20", -1) response, _ := http.Get(str) if response != nil { defer response.Body.Close() body, _ = ioutil.ReadAll(response.Body) } //json.Unmarshal(body, &devices) return } func Apipost(strUrl, method string, postDict interface{}) (body []byte) { strUrl = strings.Replace(strUrl, " ", "%20", -1) httpClient := &http.Client{ //Transport:nil, //CheckRedirect: nil, } var httpReq *http.Request b, _ := json.Marshal(postDict) postBytesReader := bytes.NewReader(b) httpReq, _ = http.NewRequest(method, strUrl, postBytesReader) httpReq.Header.Add("Content-Type", "application/json") response, _ := httpClient.Do(httpReq) body, _ = ioutil.ReadAll(response.Body) return } func ApiKeyRequest(strUrl, method, apikey string, postDict interface{}) (body []byte) { httpClient := &http.Client{ //Transport:nil, //CheckRedirect: nil, } var httpReq *http.Request b, _ := json.Marshal(postDict) postBytesReader := bytes.NewReader(b) httpReq, _ = http.NewRequest(method, strUrl, postBytesReader) httpReq.Header.Add("apikey", apikey) response, _ := httpClient.Do(httpReq) if response != nil { body, _ = ioutil.ReadAll(response.Body) } return } func SaveDirectory(path string) { os.MkdirAll(path, os.ModePerm) } // 上传图片 func UploadImage(typename, path string, r *http.Request) string { fn, _, _ := r.FormFile("file") defer fn.Close() var spit string if os.IsPathSeparator('\\') { //前边的判断是否是系统的分隔符 spit = "\\" } else { spit = "/" } var urlpath = path path = strings.Replace(path, "/", spit, -1) dir, _ := os.Getwd() //当前目录 path = dir + path + spit + utils.ToStr(time.Now().Year()) + spit + fmt.Sprintf("%s", time.Now().Format("1")) + spit os.MkdirAll(path, os.ModePerm) var name = utils.GetGuid() + "." + typename f, _ := os.Create(path + name) defer f.Close() io.Copy(f, fn) return urlpath + utils.ToStr(time.Now().Year()) + "/" + fmt.Sprintf("%s", time.Now().Format("1")) + "/" + name } //上传附件 func UploadFile(filename, path string, r *http.Request, fname ...string) string { filena := "upfile" if len(fname) > 0 { filena = fname[0] } fn, _, _ := r.FormFile(filena) defer fn.Close() var spit string if os.IsPathSeparator('\\') { //前边的判断是否是系统的分隔符 spit = "\\" } else { spit = "/" } var urlpath = path path = strings.Replace(path, "/", spit, -1) dir, _ := os.Getwd() //当前目录 path = dir + path + spit + utils.ToStr(time.Now().Year()) + spit + fmt.Sprintf("%s", time.Now().Format("1")) + spit os.MkdirAll(path, os.ModePerm) //var name = utils.GetGuid() + "." + typename f, _ := os.Create(path + filename) defer f.Close() io.Copy(f, fn) return urlpath + utils.ToStr(time.Now().Year()) + "/" + fmt.Sprintf("%s", time.Now().Format("1")) + "/" + filename } // 上传打印方案文件 func UploadPrintFile(filename, path string, r *http.Request) string { fn, _, _ := r.FormFile("file") defer fn.Close() var spit string if os.IsPathSeparator('\\') { //前边的判断是否是系统的分隔符 spit = "\\" } else { spit = "/" } var urlpath = path path = strings.Replace(path, "/", spit, -1) dir, _ := os.Getwd() //当前目录 path = dir + path os.MkdirAll(path, os.ModePerm) var name = filename f, _ := os.Create(path + name) defer f.Close() io.Copy(f, fn) return urlpath + name } func GetTriggerItemNameByItem(item int) (name string) { switch item { case 1: name = ">" case 2: name = ">=" case 3: name = "<" case 4: name = "<=" case 5: name = "=" } return } func GetChannelLast(code string) (lastdata labsop.DatapointLabSop, err error) { return labsop.GetBoxLastdata(strings.Replace(code, "c", "", 1)) } func GetChannelCacheLast(code string) (lastdata labsop.BoxCache, err error) { return labsop.GetBox(strings.Replace(code, "c", "", 1)) } func WriteAlertBindValue(code, value string) (err error) { key := strings.Replace(code, "c", "", 1) data := labsop.DatapointLabSop{Time: time.Now(), RequestData: value} err = labsop.UpdateBoxLastdata(key, data) if err == nil { cfg := nsq.NewConfig() Producernsq, _ := nsq.NewProducer(Nsqdtcpaddr, cfg) bdata, err := json.Marshal(blackboxddata{key, data}) if err == nil { err = Producernsq.Publish(Nsqtopic, bdata) } } return } func GetChannelInfov2(code, u, p string, ftype int, startandend ...int64) (ctype string, cols []string, arrs [][]interface{}) { client := labsop.GetLabSopClient("coldcloud", "cc@1qaz2wsx", "coldcloud", "121.42.244.202:9086") //bs03 sql := fmt.Sprintf("select * from %v ", code) if len(startandend) == 2 { sql = sql + fmt.Sprintf(" where time>%vs and time<%vs ", startandend[0], startandend[1]) } else { sql = sql + " order by time desc limit 1" } data, err := client.QueryOneResultByCommand(sql) if err == nil && len(data) > 0 && len(data[0].Values) > 0 { ctype = "value" cols, arrs = data[0].Columns, data[0].Values } return } func CodertoGBK(str string) string { dec := mahonia.NewDecoder("UTF-8") enc := mahonia.NewEncoder("GBK") return enc.ConvertString(dec.ConvertString(str)) } func CoderGBKtoUTF8(str string) string { dec := mahonia.FallbackDecoder(mahonia.NewDecoder("GBK"), mahonia.NewDecoder("UTF-8")) return dec.ConvertString(str) } //设备类型汇总 const ( Device_Box = "0" //设备,普通box Device_Alertor = "4" //设备,报警器 ChannelItem_Sensor = "0,6,7,9,10,13,14,15" //sensor,常温,深低温,o2,co2,特殊(隐藏湿度的常温),功率,外接设备1,外接液位设备 ChannelItem_Report = "0,6,7,9,10,14,15" //sensor报表使用,不需要功率,常温,深低温,o2,co2,特殊(隐藏湿度的常温),外接设备1,外接液位设备 ChannelItem_Box = "1" //sensor,box自身数据 ChannelItem_TAndH = "0,14" //sensor,常温,显示温湿度 ChannelItem_Temperature = "6,10" //sensor,深低温,特殊,显示温度 ChannelItem_Co2 = "9" //sensor,co2,显示温湿度,co2 ChannelItem_O2 = "7" //sensor,o2,显示温湿度,O2 ChannelItem_Power = "13" //sensor,功率插座,显示功率,市电 ChannelItem_LiquidLevel = "15" //sensor,外接液位设备,显示温度,液位 ChannelItem_HaveT = "0,6,7,9,10,15" //含温度数据 ChannelItem_HaveV = "0,6,7,9,10" //含电压数据 ChannelItem_HaveH = "0,7,9" //含湿度数据 ChannelItem_HaveCO2 = "9" //含二氧化碳数据,co2 ChannelItem_HaveO2 = "7" //含氧气数据,o2 ChannelItem_HaveLiquidLevel = "15" //含液位数据 Alertor_Alarm = "2,4,5,8,12" //报警器,普通,纯报警,纯正常,android,条屏 Alertor_AlarmBindData = "3" //报警器,绑定数据 Alertor_Alarm1 = "2" //报警器,普通 Alertor_Alarm3 = "4" //报警器,纯报警 Alertor_AlarmOnlyData = "5" //报警器,纯正常 Alertor_AlarmAndroid = "8" //报警器,android Alertor_AlarmBaoJing = "2,4,5,8" //报警器,报警 Alertor_AlarmLed = "12" //报警器,条屏 Alertor_NeedAction = "2,4,5,8" //报警器,需要添加动作 Alertor_NotNeedAction = "12" //报警器,不需要添加动作 ) //设备类型判断 func DeviceItemContain(itemenum, item string) bool { return utils.SliceContains(strings.Split(itemenum, ","), item) } func DeviceItemContainint(itemenum string, item int) bool { return utils.SliceContains(strings.Split(itemenum, ","), utils.ToStr(item)) } func StringIsContain(strs string, str ...interface{}) bool { if len(str) == 1 { return utils.SliceContains(strings.Split(strs, ","), utils.ToStr(str[0])) } else if len(str) == 2 { return utils.SliceContains(strings.Split(strs, ","), utils.ToStr(str[0])) || utils.SliceContains(strings.Split(strs, ","), utils.ToStr(str[1])) } return false } func IsAuthorized(uid string, permissionItemCode string) bool { svc := permission.GetPermissionService(utils.DBE) return svc.IsAuthorized(uid, permissionItemCode) } func Boxlinename(x int) string { switch x { case 1: return "A" case 2: return "B" case 3: return "C" case 4: return "D" case 5: return "E" case 6: return "F" case 7: return "G" case 8: return "H" case 9: return "I" case 10: return "J" case 11: return "K" case 12: return "L" case 13: return "M" case 14: return "N" case 15: return "O" case 16: return "P" case 17: return "Q" case 18: return "R" case 19: return "S" case 20: return "T" default: return "A" } } func NumtoUpChar(x int) string { return string(64 + x) } //截取字符串 start 起点下标 length 需要截取的长度 func Substr(str string, start int, length int) string { rs := []rune(str) rl := len(rs) end := 0 if start < 0 { start = rl - 1 + start } end = start + length if start > end { start, end = end, start } if start < 0 { start = 0 } if start > rl { start = rl } if end < 0 { end = 0 } if end > rl { end = rl } return string(rs[start:end]) } //截取字符串 start 起点下标 end 终点下标(不包括) func Substr2(str string, start int, end int) string { rs := []rune(str) length := len(rs) if start < 0 || start > length { panic("start is wrong") } if end < 0 || end > length { panic("end is wrong") } return string(rs[start:end]) } func GetKuoZhan(entity interface{}, filedname string) string { sfiledtype, _ := reflect.TypeOf(entity).FieldByName(filedname) objV := reflect.ValueOf(entity).FieldByName(filedname) switch sfiledtype.Type.Kind() { case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: return utils.ToStr(objV.Int()) case reflect.Float32, reflect.Float64: return utils.ToStr(objV.Float()) case reflect.String: return objV.String() } return "" } func GetRandomOrderNum() int64 { var model RandomOrderNumRequest strurl := utils.Cfg.MustValue("server", "orderurl") //获取配置文件中方法 json.Unmarshal(Apiget(strurl), &model) //json.Unmarshal(Apiget("http://uid.labsop.cn:8182/worker/2"), &model) return model.Id }