'Data sending between js file and esp32 sketch
I want to use an esp32 as a web server to display information within a browser. I have an esp32 sketch that processes some data from sensors and i want to stream them into the js file so that i can display them on the web page as a graph that updates periodically. My problem is that no matter what i try, i just can't figure out how to funnel the data between the two files. Any help, please? Thanks for all responses in advance!
Solution 1:[1]
sorry for posting an answer, i don't have the required level to comment
first, I am sorry to tell you that even if you update the javascript file in real time, its content will not load on the web.
but you can send the updated sensor data via WebSocket server to the javascript client and then update your interface
this is a little WS library i have done before, its simple but functional
export const ws = (url) => {
let ws = null
let connectListeners = []
let receiveListeners = []
let retryCount = 1
const api = {
connect(newUrl, attemps = -1) {
if (ws != null) {
ws.onmessage = null
ws.onerror = null
ws.onclose = null
ws.onopen = null
}
return new Promise((resolve, reject) => {
ws = new WebSocket(newUrl || url)
ws.onopen = (e) => {
connectListeners.forEach(cbk => {
cbk(e)
})
resolve(api)
}
ws.onmessage = (e) => {
let data = e.data
try {
data = JSON.parse(data)
} catch (e) {}
receiveListeners.forEach(cbk => {
cbk(data)
})
}
ws.onerror = (e) => {
if (attemps > 0 && retryCount < attemps) {
retryCount++
api.connect(newUrl, attemps)
} else if (attemps < 0) {
api.connect(newUrl, attemps)
} else {
reject(e)
}
}
})
},
onconnect(e) {
connectListeners.push(e)
},
onreceive(e) {
receiveListeners.push(e)
},
send(data) {
if (ws.readyState == WebSocket.OPEN) {
ws.send(JSON.stringify(data))
}
return this;
},
close(forced = false) {
if (forced) {
this.connect()
} else {
ws.close()
}
return this;
}
}
return api;
}
and then you can use it as follow
const wsClient = ws('ws://your-esp32-ip/')
wsClient.onreceive(function(data){
console.log(data)
})
wsClient.connect() // you can pass a new connection url and number of connection attemps
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Monstermash |
