Client-side implementation

Now that the server side is completed, the client-side script needs to be modified to accommodate the new functionality that has been added:

    /**
     * First, define a function that will initialize the 
socket connection and add listeners * to the required events */
const addSocketListeners = () => { /** * The "io" constructor is available to us after
including the socket.io library script in the "index.html" file * Initializing the socket connection is as easy as the
statement below */
const socket = io() /** * An event listener is attached to the "new-
temperature" event * The handler is similar to the handler that was attached
to the GET /temperature API, so in essence, we are
replacing the API call with the socket event notification */
socket.on('new-temperature', data => { const now = new Date() const timeNow = now.getHours() + ':' + now.getMinutes() + ':' + now.getSeconds() pushData(temperatureChartConfig.data.labels, timeNow,
10) pushData(temperatureChartConfig.data.datasets[0].data,
data.value, 10) temperatureChart.update() temperatureDisplay.innerHTML = '<strong>' +
data.value + '</strong>' }) /** * Similarly, we add the handler for the "new-humidity"
event */
socket.on('new-humidity', data => { const now = new Date() const timeNow = now.getHours() + ':' + now.getMinutes() + ':' +
now.getSeconds() pushData(humidityChartConfig.data.labels, timeNow,
10) pushData(humidityChartConfig.data.datasets[0].data,
data.value, 10) humidityChart.update() humidityDisplay.innerHTML = '<strong>' + data.value +
'</strong>' }) } if (!getParameterByName('start') && !getParameterByName('end')) { /** * Finally, the fetchHumidity and fetchTemperature
functions, that used to call the APIs at regular intervals, are removed. * In their place, the addSocketListeners function is
called (and only needs to be called once this time) */
addSocketListeners() // setInterval(() => { // fetchTemperature() // fetchHumidity() // }, 2000) fetchHumidityHistory() fetchTemperatureHistory() } else { fetchHumidityRange() fetchTemperatureRange() }

Once this is done, open your browser, and you should see a subtle but significant change: the charts and dashboard values update only once the value of a reading has changed. Furthermore, the temperature and humidity charts now update independently and only if their own individual values change. This is because the client is only notified if the server detects a change in temperature or humidity. This might not look like much visually, but it is a huge change under the hood, which can be observed by looking at the network tab in your browser's inspector:

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.137.172.68