-
Notifications
You must be signed in to change notification settings - Fork 0
/
test.go
78 lines (61 loc) · 1.56 KB
/
test.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
package main
import (
"encoding/json"
"log"
"net/http"
"time"
"github.com/goburrow/modbus"
"github.com/tarm/serial"
)
type yanit struct {
Veri []int16 `json:"data"`
}
func main() {
seriPortKonfig := &serial.Config{
Name: "COM3",
Baud: 19200,
Parity: serial.ParityNone,
StopBits: serial.Stop1,
Size: 8,
}
yonetici := modbus.NewRTUClientHandler(seriPortKonfig.Name)
yonetici.BaudRate = seriPortKonfig.Baud
yonetici.Parity = string(seriPortKonfig.Parity)
yonetici.Timeout = 10 * time.Second
istemci := modbus.NewClient(yonetici)
ustID := byte(10)
adresi := uint16(9)
miktar := uint16(10)
yonetici.SlaveId = ustID
http.HandleFunc("/data", func(w http.ResponseWriter, r *http.Request) {
sonuclar, err := istemci.ReadHoldingRegisters(adresi, miktar)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
if len(sonuclar) < int(miktar)*2 {
http.Error(w, "deger gelmedi", http.StatusInternalServerError)
return
}
var veri []int16
for i := 0; i < len(sonuclar); i += 2 {
deger := int16(sonuclar[i])<<8 | int16(sonuclar[i+1])
veri = append(veri, deger)
}
yanit := yanit{Veri: []int16{}}
if len(veri) > 0 {
yanit.Veri = append(yanit.Veri, veri[0])
}
if len(veri) > 4 {
yanit.Veri = append(yanit.Veri, veri[4])
}
jsonyanit, err := json.Marshal(yanit)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
w.Header().Set("Content-Type", "application/json")
w.Write(jsonyanit)
})
log.Fatal(http.ListenAndServe(":8080", nil))
}