Quellcode durchsuchen

fit: 单点位增加SetValue方法

gaoyagang vor 11 Monaten
Ursprung
Commit
e9bee032cc
4 geänderte Dateien mit 168 neuen und 4 gelöschten Zeilen
  1. 138 0
      envitem/func.go
  2. 12 4
      envitem/func_test.go
  3. 17 0
      envitem/types.go
  4. 1 0
      envitem/vars.go

+ 138 - 0
envitem/func.go

@@ -1,12 +1,20 @@
 package envitem
 
 import (
+	"bytes"
+	"compress/gzip"
 	"context"
+	"crypto/md5"
 	"database/sql/driver"
+	"encoding/hex"
 	"encoding/json"
 	"errors"
 	"fmt"
+	"io"
 	"metawant.greentech.com.cn/gaoyagang/gt-common/httplib"
+	"net"
+	"net/http"
+	"net/url"
 	"strconv"
 	"strings"
 	"sync"
@@ -24,6 +32,7 @@ func SetOptions(options Options) {
 
 	fetchMultiItem = options.FetchMultiItem
 	adjustValue = options.AdjustValue
+	plcItemSecret = options.PlcItemSecret
 }
 
 func (m MultiEnvItem) GetProjectId() int64 {
@@ -417,6 +426,40 @@ func (e *EnvItem) IncreAdjust(expire time.Duration) (int64, error) {
 	return intCmd.Val(), nil
 }
 
+func (e *EnvItem) SetValue(o, v string) error {
+	ts := time.Now().Unix()
+	data := make(SetCurrentsReq, 1)
+	data[0] = SetCurrentReq{
+		ProjectId: e.ProjectId,
+		Item:      e.Item,
+		OldValue:  o,
+		NewValue:  v,
+	}
+
+	sign := data.Sign(plcItemSecret, ts)
+
+	jsonByte, _ := json.Marshal(data)
+	requestBuf := bytes.NewBuffer(jsonByte)
+	headers := http.Header{}
+	headers.Add("Content-Type", "application/json")
+	resp, err := _sendRequest(ctlUrl, "POST", fmt.Sprintf("sign=%s&timestamp=%d", sign, ts), headers, requestBuf)
+	if err != nil {
+		return fmt.Errorf("设置点位数据失败参数,%s,%s", string(jsonByte), err.Error())
+	}
+
+	respData := &SetCurrentResp{}
+	err = json.Unmarshal(resp.Bytes(), respData)
+	if err != nil {
+		return fmt.Errorf("设置点位数据失败参数,%s,%s,%s", string(jsonByte), err.Error(), resp)
+	}
+
+	if respData.Code != http.StatusOK {
+		return fmt.Errorf("设置点位数据失败参数,%s,%s", string(jsonByte), resp)
+	}
+
+	return nil
+}
+
 // WaitValue 等待点位的值, 变为指定值
 // v: 等待的值
 // op: -1: 小于, 0: 等于, 1: 大于
@@ -525,6 +568,15 @@ func getAdjustStringVal(projectId int64, item string) (string, error) {
 	return scmd.String(), nil
 }
 
+func (s SetCurrentsReq) Sign(secret string, ts int64) string {
+	jsonByte, _ := json.Marshal(s)
+	requestBuf := bytes.NewBuffer(jsonByte)
+
+	hasher := md5.New()
+	hasher.Write([]byte(fmt.Sprintf("%s%s%d", requestBuf.Bytes(), secret, ts)))
+	return strings.ToUpper(hex.EncodeToString(hasher.Sum(nil)))
+}
+
 func (v *VirtualPlcItem) GetVirtualPlcItems() (*VirtualPlcItemResp, error) {
 
 	tmpPlcItemUrl := fmt.Sprintf("%s%d", plcItemUrl, v.ProjectId)
@@ -555,3 +607,89 @@ func (v *VirtualPlcItem) GetVirtualPlcItems() (*VirtualPlcItemResp, error) {
 
 	return nil, errors.New(fmt.Sprintf("request statusCode: %d", r.StatusCode))
 }
+
+func _sendRequest(urlStr, method, queryParam string, headers http.Header, postData io.Reader) (buffer *bytes.Buffer, err error) {
+	client := &http.Client{
+		Transport: &http.Transport{
+			Proxy: http.ProxyFromEnvironment,
+			DialContext: (&net.Dialer{
+				Timeout:   3 * time.Second,
+				KeepAlive: 10 * time.Second,
+			}).DialContext,
+			MaxIdleConns:        10,
+			MaxIdleConnsPerHost: 10,
+			IdleConnTimeout:     10 * time.Second,
+		},
+		Timeout: 10 * time.Second,
+	}
+
+	URL := urlStr
+	Method := method
+	if len(Method) == 0 {
+		Method = "GET"
+	}
+	if len(queryParam) != 0 {
+		//reqQueryParam = queryParam
+		queryParam = strings.Replace(queryParam, " ", "%20", -1) //转义请求参数中所有的空格
+		queryParam = strings.Replace(queryParam, "/", "%2F", -1) //转义请求参数中所有的斜线
+		queryParam = strings.Replace(queryParam, "(", "%28", -1) //转义请求参数中所有的左括号
+		queryParam = strings.Replace(queryParam, ")", "%29", -1) //转义请求参数中所有的右括号
+		queryParam = strings.Replace(queryParam, ",", "%2C", -1) //转义请求参数中所有的逗号
+		queryParam = strings.Replace(queryParam, ";", "%3B", -1) //转义请求参数中所有的分号
+		l, err := url.Parse("?" + queryParam)
+		if err != nil {
+			//log.Errorf(err, "parse http url error")
+			return nil, err
+		}
+		param := l.Query().Encode()
+		URL = fmt.Sprintf("%s?%s", URL, param)
+	}
+	reqBuffer := &bytes.Buffer{}
+	if postData != nil {
+		reqBuffer.ReadFrom(postData)
+	}
+
+	req, err := http.NewRequest(Method, URL, reqBuffer)
+
+	if len(headers) > 0 {
+		for s, header := range headers {
+			if len(header) > 0 {
+				req.Header.Add(s, header[0])
+			}
+		}
+	}
+
+	if nil != err {
+		return nil, err
+	}
+
+	resp, err := client.Do(req)
+	if nil != err {
+		//log.Errorf(err, "request failed:%v")
+		return nil, err
+	}
+
+	var data io.ReadCloser
+	switch resp.Header.Get("Content-Encoding") {
+	case "gzip":
+		data, err = gzip.NewReader(resp.Body)
+		if nil != err {
+			return nil, err
+		}
+	default:
+		data = resp.Body
+	}
+	defer func() {
+		if resp != nil && resp.Body != nil {
+			resp.Body.Close()
+		}
+	}()
+
+	buffer = &bytes.Buffer{}
+	_, err = buffer.ReadFrom(data)
+	if nil != err {
+		return nil, err
+	}
+
+	return buffer, nil
+}

+ 12 - 4
envitem/func_test.go

@@ -149,12 +149,20 @@ func TestEnvItem_GetValueForAdjust(t *testing.T) {
 }
 
 func TestEnvItem_WaitEqValue(t *testing.T) {
-	SetOptions(Options{GtServerIp: "47.96.12.136:8788", Cache: cache, AdjustValue: false})
+	SetOptions(Options{GtServerIp: "47.96.12.136:8788", Cache: cache, AdjustValue: false, PlcItemSecret: "237c92d2-8795-1094-11ef-00e2e48fce4a"})
 	e := &EnvItem{
 		ProjectId: 92,
-		Item:      "C.M.UF1_DB@time_production_display",
+		Item:      "C.M.UF4_DB@cycle_sp",
 	}
-	c := e.WaitValue("2755", -1, 3*time.Second, 20)
 
-	t.Log(<-c)
+	t.Log(e.GetItemInt64Val())
+
+	err := e.SetValue(fmt.Sprintf("%d", e.Value), "72")
+	if err != nil {
+		t.Log(err)
+	} else {
+		c := e.WaitValue("72", 0, 3*time.Second, 20)
+
+		t.Log(<-c)
+	}
 }

+ 17 - 0
envitem/types.go

@@ -9,6 +9,8 @@ type (
 		AdjustValue bool
 		// 批量获取点位值
 		FetchMultiItem bool
+		// 设备点位值的secret
+		PlcItemSecret string
 	}
 
 	EnvItem struct {
@@ -49,6 +51,21 @@ type (
 		ProjectId   int64  `json:"project_id"`
 	}
 
+	SetCurrentReq struct {
+		ProjectId int64  `json:"project_id"`
+		Item      string `json:"item"`
+		OldValue  string `json:"old_value"`
+		NewValue  string `json:"new_value"`
+	}
+
+	SetCurrentsReq []SetCurrentReq
+
+	SetCurrentResp struct {
+		Code int         `json:"code"`
+		Msg  string      `json:"msg"`
+		Data interface{} `json:"data"`
+	}
+
 	VirtualPlcItem struct {
 		ProjectId int `json:"ProjectId"`
 		PageSize  int `json:"pageSize"`

+ 1 - 0
envitem/vars.go

@@ -20,4 +20,5 @@ var (
 	fetchMultiItem = false
 	adjustValue    = false
 	plcItemUrl     = ""
+	plcItemSecret  = ""
 )