12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697 |
- package main
- import (
- "encoding/json"
- "fmt"
- "log"
- "net/url"
- "time"
- "github.com/gorilla/websocket"
- )
- type Request struct {
- Type string `json:"type"`
- UUID string `json:"uuid"`
- CommandID string `json:"commandId"`
- Parameter interface{} `json:"parameter"`
- }
- type Response struct {
- CommandID string `json:"commandId"`
- ErrorCode string `json:"errorCode"`
- Results map[string]string `json:"results"`
- Status string `json:"status"`
- Time int64 `json:"time"`
- Type string `json:"type"`
- UUID string `json:"uuid"`
- }
- func SendWebsocketRequest(serverURL, path string, request Request) (string, error) {
-
- u := url.URL{Scheme: "ws", Host: serverURL, Path: path}
-
- dialer := websocket.Dialer{
- ReadBufferSize: 1024,
- WriteBufferSize: 1024,
-
- HandshakeTimeout: 5 * time.Second,
- }
-
- conn, _, err := dialer.Dial(u.String(), nil)
- if err != nil {
- return "", fmt.Errorf("dial: %w", err)
- }
- defer conn.Close()
-
- requestJSON, err := json.Marshal(request)
- if err != nil {
- return "", fmt.Errorf("marshal request: %w", err)
- }
-
- err = conn.WriteMessage(websocket.TextMessage, requestJSON)
- if err != nil {
- return "", fmt.Errorf("write: %w", err)
- }
-
- _, responseBytes, err := conn.ReadMessage()
- if err != nil {
- return "", fmt.Errorf("read: %w", err)
- }
-
- var response Response
- err = json.Unmarshal(responseBytes, &response)
- if err != nil {
- return "", fmt.Errorf("unmarshal response: %w", err)
- }
-
- return response.Results["sn"], nil
- }
- func main() {
-
- serverURL := "192.168.1.104:9002"
- path := "/"
- request := Request{
- Type: "request",
- UUID: "",
- CommandID: "getRobotBaseInfo",
- Parameter: nil,
- }
- sn, err := SendWebsocketRequest(serverURL, path, request)
- if err != nil {
- log.Fatal(err)
- }
- log.Printf("SN: %s", sn)
- }
|