-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
112 lines (94 loc) · 2.8 KB
/
index.js
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
const WiFi = require('wifi').WiFi;
const http = require('http');
const { PicoCYW43 } = require('pico_cyw43');
const wifiConfig = require('./wifi.json');
const { LED } = require('led');
const led = new LED(15);
const pico_cyw43 = new PicoCYW43();
connectToNetwork(wifiConfig);
function connectToNetwork(wifiConfig) {
console.log(`Connecting to Wi-Fi network: ${wifiConfig.ssid}`);
setLed(true);
const wifi = new WiFi();
wifi.connect(wifiConfig, (err) => {
setLed(false);
if (err) {
console.error(err);
} else {
console.log('Connected to Wi-Fi');
sendRequest();
}
});
}
function sendRequest() {
console.log('Sending request');
setLed(true);
const host = 'example.com';
const port = 80;
const options = {
host,
port,
path: '/',
method: 'GET',
headers: {
'Host': host,
}
};
const decoder = new TextDecoder();
let responseContentLength = 0;
let body = '';
const checkFinished = () => {
let percent = 0;
if (responseContentLength > 0) {
percent = Math.round(body.length / responseContentLength * 100);
}
console.log(`Body length: ${body.length} / ${responseContentLength} (${percent}%)`);
if (body.length < responseContentLength) {
return;
}
console.log('Response finished');
setLed(false);
console.log(body);
}
const req = http.request(options, (res) => {
console.log(`STATUS: ${res.statusCode} ${res.statusMessage}`);
console.log(`HEADERS: ${JSON.stringify(res.headers)}`);
responseContentLength = parseInt(res.headers['content-length'], 10);
res.on('data', (chunk) => {
try {
console.log(`Received ${chunk.length} bytes of data.`);
const decoded = decoder.decode(chunk);
body += decoded;
// console.log(`BODY: ${chunk}`);
checkFinished();
} catch (e) {
console.error(e);
}
});
res.on('close', () => {
console.log('Response closed.');
});
res.on('end', () => {
console.log('No more data in response.');
});
res.on('error', (e) => {
console.error('Response error.', e);
});
});
req.on('error', (e) => {
console.error(`problem with request: ${e.message}`);
});
req.on('response', (res) => {
console.log(`response event: ${res.statusCode} ${res.statusMessage}`);
});
// Finish the request
req.end();
console.log('Request sent');
}
/**
* @param {boolean} state
*/
function setLed(state) {
//pico_cyw43.putGpio(0, state);
state ? led.on() : led.off();
}