-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathmain.go
275 lines (231 loc) · 6.3 KB
/
main.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
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
//This example opens a TCP connection using a device with WiFiNINA firmware
//and sends a HTTP request to retrieve a webpage, based on the following
//Arduino example:
//
///~https://github.com/arduino-libraries/WiFiNINA/blob/master/examples/WiFiWebClientRepeating/
//
//This example will not work with samd21 or other systems with less than 32KB
//of RAM. Use the following if you want to run wifinina on samd21, etc.
//
//examples/wifinina/webclient
//examples/wifinina/tlsclient
package main
import (
"device/arm"
"fmt"
"log"
"machine"
"time"
"tinygo.org/x/drivers/dht"
"tinygo.org/x/drivers/net"
"tinygo.org/x/drivers/wifinina"
)
// access point info
const (
ssid = "NETGEAR0E635F"
pass = "blacktuba577"
// IP address of the server aka "hub". Replace with your own info.
// Can specify a URL starting with http or https
url = "http://192.168.1.127/measure"
//server = "192.168.1.127"
server = "10.0.0.177"
)
// these are the default pins for the Arduino Nano33 IoT.
// change these to connect to a different UART or pins for the ESP8266/ESP32
var (
// these are the default pins for the Arduino Nano33 IoT.
spi = machine.NINA_SPI
// this is the ESP chip that has the WIFININA firmware flashed on it
adaptor *wifinina.Device
//buf [0x46a]byte
lastRequestTime time.Time
conn net.Conn
buf [256]byte
)
// measure holds the temperature and the humidity of the sensor
// NB: json fields are useless for the moment cause the type.Name() is unimplemented for the moment
type measure struct {
Temp int16 `json:"temperature"`
Hum uint16 `json:"humidity"`
}
func setup() {
// Configure SPI for 8Mhz, Mode 0, MSB First
spi.Configure(machine.SPIConfig{
Frequency: 8 * 1e6,
SDO: machine.NINA_SDO,
SDI: machine.NINA_SDI,
SCK: machine.NINA_SCK,
})
adaptor = wifinina.New(spi,
machine.NINA_CS,
machine.NINA_ACK,
machine.NINA_GPIO0,
machine.NINA_RESETN)
adaptor.Configure()
}
func main() {
// setup the device
setup()
//http.SetBuf(buf[:])
//waitSerial()
connectToAP()
// configure the data pin
pin := machine.D6
dhtSensor := dht.New(pin, dht.DHT22)
// get measurements and send them to the server
cnt := 0
for {
fmt.Printf("-------- %d --------\r\n", cnt)
readConnection()
temp, hum, err := measurements(dhtSensor.(dht.DummyDevice))
if err != nil {
fmt.Printf("Measurements failed: %s\n", err.Error())
} else {
makeHTTPRequest(measure{temp, hum})
}
cnt++
time.Sleep(10 * time.Second)
}
}
// Wait for user to open serial console
func waitSerial() {
for !machine.Serial.DTR() {
time.Sleep(100 * time.Millisecond)
}
}
func message(msg string) {
println(msg, "\r")
}
func readConnection() {
if conn != nil {
for n, err := conn.Read(buf[:]); n > 0; n, err = conn.Read(buf[:]) {
if err != nil {
println("Read error: " + err.Error())
} else {
print(string(buf[0:n]))
}
}
}
}
func makeHTTPRequest(m measure) {
var err error
if conn != nil {
conn.Close()
}
// make TCP connection
ip := net.ParseIP(server)
raddr := &net.TCPAddr{IP: ip, Port: 80}
laddr := &net.TCPAddr{Port: 8080}
message("--- Dialing TCP connection ---")
conn, err := net.DialTCP("tcp", laddr, raddr)
cnt := 0
for ; err != nil; conn, err = net.DialTCP("tcp", laddr, raddr) {
message("Connection failed: " + err.Error())
if err == wifinina.ErrConnectionTimeout {
connectToAP()
}
if cnt == 10 {
connectToAP()
}
cnt++
time.Sleep(5 * time.Second)
}
println("Connected!\r")
body := fmt.Sprintf(`{"temperature":%02d.%d,"humidity":%02d.%d}`, m.Temp/10, m.Temp%10, m.Hum/10, m.Hum%10)
bodyInBytes := []byte(body)
contentLength := len(bodyInBytes)
print("Sending HTTP request...")
fmt.Fprintln(conn, "POST /measure HTTP/1.1")
fmt.Fprintln(conn, "Host:", server)
fmt.Fprintln(conn, "Content-Type: application/json")
fmt.Fprintln(conn, fmt.Sprintf("Content-Length: %d", contentLength))
fmt.Fprintf(conn, "\n")
fmt.Fprintln(conn, body)
fmt.Fprintln(conn, "\n")
println("Sent!")
lastRequestTime = time.Now()
}
// measurements sends a command to get temperature and humidity to the sensor
// and returns the values
func measurements(dhtSensor measurable) (int16, uint16, error) {
temp, hum, err := dhtSensor.Measurements()
if err != nil {
fmt.Printf("Measurements failed: %s\n", err.Error())
} else {
// print data with current time
now := time.Now()
fmt.Printf("%02d:%02d:%02d, ", now.Hour(), now.Minute(), now.Second())
// received data is times 10
fmt.Printf("Temperature: %02d.%d°C, ", temp/10, temp%10)
fmt.Printf("Humidity: %02d.%d%%\n", hum/10, hum%10)
}
return temp, hum, err
}
type measurable interface {
Measurements() (int16, uint16, error)
}
// connect to access point
func connectToAP() {
time.Sleep(2 * time.Second)
for {
err := adaptor.ConnectToAccessPoint(ssid, pass, 30*time.Second)
if err == nil {
log.Println("connected to access point")
break
}
log.Println("let's retry to connect to access point", err.Error())
//message(err.Error())
}
//time.Sleep(2 * time.Second)
//println("Connecting to " + ssid)
//err := adaptor.ConnectToAccessPoint(ssid, pass, 2*time.Minute)
//if err != nil { // error connecting to AP
// message(err.Error())
// err = adaptor.ConnectToAccessPoint(ssid, pass, 2*time.Minute)
// if err != nil {
// message(err.Error())
// forceAbort()
// }
//}
println("Connected.")
ip, _, _, err := adaptor.GetIP()
for ; err != nil; ip, _, _, err = adaptor.GetIP() {
message(err.Error())
}
message(ip.String())
}
var ResetOnAbort = true
func forceAbort() {
if ResetOnAbort {
fmt.Println("system reset")
arm.SystemReset()
}
// lock up forever
for {
arm.Asm("wfi")
}
}
func makeHTTPRequestGet() {
var err error
if conn != nil {
conn.Close()
}
// make TCP connection
ip := net.ParseIP(server)
raddr := &net.TCPAddr{IP: ip, Port: 80}
laddr := &net.TCPAddr{Port: 8080}
message("\r\n---------------\r\nDialing TCP connection")
conn, err := net.DialTCP("tcp", laddr, raddr)
for ; err != nil; conn, err = net.DialTCP("tcp", laddr, raddr) {
message("Connection failed: " + err.Error())
time.Sleep(5 * time.Second)
}
println("Connected!\r")
print("Sending HTTP request...")
fmt.Fprintln(conn, "GET /hi HTTP/1.1")
fmt.Fprintln(conn, "Host:", server)
fmt.Fprintln(conn, "Content-Type: application/json")
fmt.Fprintln(conn)
println("Sent!")
lastRequestTime = time.Now()
}