zhangzengfei
2023-09-05 1b34d7bacad94933ad63fc0e199bd32ac49d9fa5
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
package service
 
import (
    "encoding/json"
    "errors"
 
    "basic.com/valib/bhomedbapi.git"
    "basic.com/valib/go-aiot.git/aiotProto/aiot"
    "basic.com/valib/logger.git"
)
 
// 返回结果
type Reply struct {
    Success bool        `json:"success"`
    Msg     string      `json:"msg"`
    Data    interface{} `json:"data"`
}
 
// 获取content-type字符串
func GetContentTypeString(contentType aiot.RequestContentType) string {
    switch contentType {
    case aiot.RequestContentType_ApplicationJson:
        // application/json 格式
        return bhomedbapi.CONTENT_TYPE_JSON
    case aiot.RequestContentType_ApplicationXWwwFormUrlencoded:
        // application/x-www-form-urlencoded 格式
        return bhomedbapi.CONTENT_TYPE_FORM
    case aiot.RequestContentType_MultipartFormData:
        // multipart/form-data 格式
        return bhomedbapi.CONTENT_TYPE_MULFORM
    case aiot.RequestContentType_ApplicationXml:
        // application/xml
        return "application/xml"
    default:
        // application/json 格式
        return bhomedbapi.CONTENT_TYPE_JSON
    }
}
 
// 单节点请求
func NodeReq(msg *aiot.Protocol, req *aiot.NodeReq, reply *aiot.BusinessReply) error {
    // 根据参数调用服务
    var data []byte
    param := make(map[string]interface{})
    err := json.Unmarshal(req.Req, &param)
    if err != nil {
        logger.Error("Fail to Unmarshal req.Req", req.Req, err)
        return err
    }
 
    var nodeId string
    if len(msg.DeviceProto.DeviceIds) == 1 {
        nodeId = msg.DeviceProto.DeviceIds[0]
    } else if msg.DeviceProto.MasterDeviceId != "" {
        // debug_test
        nodeId = msg.DeviceProto.MasterDeviceId
    } else {
        err = errors.New("the node can not be null for NodeReq")
        logger.Error("The node is null", err, msg)
        return err
    }
 
    logger.Debugf("bus return result nodeId=%v, topic=%v, Method=%v, DeviceProto=%v", nodeId, req.Topic, req.Method, msg.DeviceProto)
    data, err = DoBusReq(req.Topic, nodeId, req.Method, req.ContentType, param)
    dataReply := Reply{}
    _ = json.Unmarshal(data, &dataReply)
 
    reply.Code = 200
    if !dataReply.Success {
        reply.Code = 500
    }
    reply.Success = dataReply.Success
    reply.Msg = dataReply.Msg
    reply.Data, _ = json.Marshal(dataReply.Data)
 
    if err != nil {
        return err
    }
    return nil
}