This repository has been archived by the owner on Jul 30, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
simulator.go
190 lines (155 loc) · 4.26 KB
/
simulator.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
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
package main
import (
"bytes"
"context"
"encoding/pem"
"flag"
"fmt"
"io"
"os"
"strings"
"time"
piondtlsv2 "github.com/pion/dtls/v2"
piondtls "github.com/pion/dtls/v3"
"github.com/pion/dtls/v3/examples/util"
"github.com/plgd-dev/go-coap/v3/dtls"
"github.com/plgd-dev/go-coap/v3/message"
"github.com/plgd-dev/go-coap/v3/message/codes"
"github.com/plgd-dev/go-coap/v3/message/pool"
udpClient "github.com/plgd-dev/go-coap/v3/udp/client"
"crypto/ecdsa"
"log"
"github.com/golang-jwt/jwt"
senMLCodec "github.com/farshidtz/senml/v2/codec"
"encoding/hex"
)
func check(e error) {
if e != nil {
panic(e)
}
}
func loadPrivateKey(privateKeyPath string) (*ecdsa.PrivateKey, error) {
privateKeyBytes, err := os.ReadFile(privateKeyPath)
if err != nil {
return nil, err
}
// Strip params
_, rest := pem.Decode(privateKeyBytes)
privateKey, err := jwt.ParseECPrivateKeyFromPEM(rest)
if err != nil {
return nil, err
}
return privateKey, nil
}
func createJWTToken(privateKeyPath string, deviceID string) (string, error) {
privateKey, err := loadPrivateKey(privateKeyPath)
if err != nil {
log.Fatalf("Failed to load private key: %v", err)
}
expirationTime := time.Now().Add(10 * time.Minute).Unix()
token := jwt.NewWithClaims(jwt.SigningMethodES256, jwt.StandardClaims{
Subject: deviceID,
ExpiresAt: expirationTime,
})
tokenString, err := token.SignedString(privateKey)
if err != nil {
return "", err
}
return tokenString, nil
}
func main() {
deviceId := flag.String("deviceId", "", "The client ID.")
privateKeyPath := flag.String("privateKey", "", "The private key file")
flag.Parse()
if *deviceId == "" {
log.Fatal("Must provide a deviceId!")
}
log.Println("DeviceID:", *deviceId)
token, err := createJWTToken(*privateKeyPath, *deviceId)
if err != nil {
log.Fatalf("Failed to create JWT token: %v", err)
}
log.Println("JWT Token:", token)
// Connect to a DTLS server
co, err := dtls.Dial("coap.nrfcloud.com:5684", &piondtlsv2.Config{
InsecureSkipVerify: true,
ConnectionIDGenerator: piondtls.OnlySendCIDGenerator(),
})
util.Check(err)
defer func() {
util.Check(co.Close())
}()
log.Println("Connected.")
// Authenticate
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
defer cancel()
resp, err := co.Post(ctx, "/auth/jwt", message.TextPlain, strings.NewReader(token))
check(err)
checkResponse(resp, codes.Created)
// assertEquals(Code.C201_CREATED, resp.code)
// assertTrue(resp.options().maxAge > 0)
log.Println("Authenticated.")
getState(co)
publishSenML(co)
}
func checkResponse(resp *pool.Message, expected codes.Code) {
if resp.Code() != expected {
panic(fmt.Sprintf(`Request failed: %d`, resp.Code()))
}
}
func getState(co *udpClient.Conn) {
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
defer cancel()
// accept
opts := message.Options{
{
ID: message.Accept,
Value: []byte{byte(message.AppCBOR)},
},
{
ID: message.URIQuery,
Value: []byte("delta=false"),
},
}
log.Printf("> Option %d: %d\n", opts[0].ID, opts[0].Value)
log.Printf("> Option %d: %s\n", opts[1].ID, opts[1].Value)
// Get the state
stateResp, err := co.Get(ctx, "/state", opts...)
check(err)
checkResponse(stateResp, codes.Content)
data, err := io.ReadAll(stateResp.Body())
if err != nil {
log.Fatal(err)
}
log.Printf("< State: %s\n", data)
}
func publishSenML(co *udpClient.Conn) {
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
defer cancel()
// Read JSON from stdin
senMLJSON, err := io.ReadAll(os.Stdin)
if err != nil {
panic(err) // handle the error
}
senMLPayload, err := senMLCodec.DecodeJSON([]byte(senMLJSON))
if err != nil {
panic(err) // handle the error
}
// validate the SenML Pack
err = senMLPayload.Validate()
if err != nil {
panic(err) // handle the error
}
// encode the normalized SenML Pack to CBOR
dataOut, err := senMLCodec.EncodeCBOR(senMLPayload)
if err != nil {
panic(err) // handle the error
}
// Convert dataOut to hex string
dataOutHex := hex.EncodeToString(dataOut)
log.Printf("> /msg/d2c/raw: %s (hex encoded)\n", dataOutHex)
log.Printf("> %s", senMLJSON)
rawResp, err := co.Post(ctx, "/msg/d2c/raw", message.AppCBOR, bytes.NewReader(dataOut))
check(err)
checkResponse(rawResp, codes.Created)
}