-
Notifications
You must be signed in to change notification settings - Fork 0
/
camera.go
102 lines (83 loc) · 1.94 KB
/
camera.go
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
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
package camera
import (
"bytes"
"encoding/json"
"fmt"
"io"
"net/http"
)
const api = "http://192.168.122.1:8080/sony/camera"
// Camera Remote API
type Camera struct {
client Client
}
// Action sends Request to Camera
func (c *Camera) Action(req Request) (Response, error) {
var res Response
bs, err := json.Marshal(&req)
if err != nil {
return res, err
}
reader, err := c.client.Send(bytes.NewReader(bs))
if err != nil {
return res, err
}
defer reader.Close()
decoder := json.NewDecoder(reader)
err = decoder.Decode(&res)
if err != nil {
return res, err
}
if len(res.Error) == 2 {
return res, fmt.Errorf("response: %.f %s", res.Error[0], res.Error[1])
}
return res, nil
}
// NewCamera with a client and default API URL
func NewCamera() Camera {
return Camera{Client{api}}
}
// Response from Camera
type Response struct {
ID int `json:"id"`
Result []interface{} `json:"result"`
Error []interface{} `json:"error"`
}
// Params of Request
type Params []interface{}
// Request to Camera
type Request struct {
ID int `json:"id"`
Version string `json:"version"`
Method string `json:"method"`
Params interface{} `json:"params"`
}
// NewRequest ...
func NewRequest(method string) Request {
params := make(Params, 0)
return NewParamsRequest(method, params)
}
// NewParamsRequest ...
func NewParamsRequest(method string, params interface{}) Request {
return Request{id, version, method, params}
}
// Client for HTTP calls
type Client struct {
URL string
}
// Send request
func (c *Client) Send(reader io.Reader) (io.ReadCloser, error) {
req, err := http.NewRequest(http.MethodPost, api, reader)
if err != nil {
return nil, err
}
res, err := http.DefaultClient.Do(req)
if err != nil {
return nil, err
}
if res.StatusCode != http.StatusOK {
defer res.Body.Close()
return nil, fmt.Errorf("unexpected HTTP response: status %s code %d", res.Status, res.StatusCode)
}
return res.Body, nil
}