Giter Site home page Giter Site logo

Comments (3)

R-holmes10 avatar R-holmes10 commented on May 26, 2024

The unexpected behavior in your code could be due to the asynchronous nature of the setTimeout functions and the fact that the sensor's data event is still being processed after you disable it. This might lead to an interference where the sensor is disabled, but the event handler continues to log values.

To address this, you can use a flag to track the sensor's state and prevent logging data when it's disabled. Here's an updated version of your code:

const { Board, Sensor } = require('johnny-five');
const board = new Board({ port: 'COM3' });

board.on('ready', () => {
  const moistureSensor = new Sensor({
    pin: 'A0',
    freq: 100,
  });

  // Flag to track the sensor state
  let isSensorEnabled = true;

  moistureSensor.on('data', (value) => {
    // Log the value only if the sensor is enabled
    if (isSensorEnabled) {
      console.log(value);
    }
  });

  setTimeout(() => {
    console.log('Disable');
    isSensorEnabled = false;
    moistureSensor.disable();
  }, 1000);

  setTimeout(() => {
    console.log('Enable');
    isSensorEnabled = true;
    moistureSensor.enable();
  }, 2000);

  setTimeout(() => {
    console.log('Disable');
    isSensorEnabled = false;
    moistureSensor.disable();
  }, 3000);
});

from johnny-five.

Tsteinroesland avatar Tsteinroesland commented on May 26, 2024

@R-holmes10 Thanks for replying!

I do agree that it's easy to circumvent this bug, but I truly believe that it is a bug.

I'll provide another example, attempting to prove that this is not a problem with the asynchronous nature of the setTimeout function, and that there's reason to believe it's not due to the event still being processed.

In this example I'm using a web socket to communicate between an HTML-page and the node server running johny-five, using the "ws" library (https://www.npmjs.com/package/ws)

The html page has a simple button, which sends a toggle signal to the server using the web socket.
The server responds by enabling or disabling the sensor.

Node server:

const { Board, Sensor } = require("johnny-five");
const WebSocket = require("ws");
const http = require("http");

const board = new Board({
  port: "COM4",
});

board.on("ready", () => {
  const moistureSensor = new Sensor({
    pin: "A0",
    freq: 250,
  });

  moistureSensor.on("data", (value) => {
    // Log the value only if the sensor is enabled
    console.log(value);
  });

  // Create an HTTP server
  const server = http.createServer((req, res) => {
    res.writeHead(200, { "Content-Type": "text/plain" });
    res.end("WebSocket server is running");
  });

  const PORT = 3001;
  server.listen(PORT, () => {
    console.log(`Server is listening on port ${PORT}`);
  });

  // Create a WebSocket server by passing the HTTP server object
  const wss = new WebSocket.Server({ server });
  wss.on("connection", (ws) => {
    console.log("Client connected");

    ws.on("message", (message) => {
      message = JSON.parse(message);
      console.log("Received message: ", message);

      if (message.topic === "sensor") {
        if (message.enabled) {
          console.log("Enabling sensor");
          moistureSensor.enable();
        } else {
          console.log("Disabling sensor");
          moistureSensor.disable();
        }
      }
    });

    // Event handler for WebSocket connection closing
    ws.on("close", () => {
      console.log("Client disconnected");
    });
  });
});

HTML file:

<!DOCTYPE html>
<html lang="en">
  <script>
    let toggle = true;
    const socket = new WebSocket("ws://localhost:3001");
    const buttonClicked = function () {
      toggle = !toggle;
      socket.send(JSON.stringify({ topic: "sensor", enabled: toggle }));
    };
  </script>
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
  </head>
  <body>
    <button onclick="buttonClicked()">Toggle!</button>
  </body>
</html>

Here's the resulting console log:

40
40
Client connected
40
39
39
39
39
39
39
39
Received message: { topic: 'sensor', enabled: false }
Disabling sensor
Received message: { topic: 'sensor', enabled: true }
Enabling sensor
38
37
37
37
37
36
Received message: { topic: 'sensor', enabled: false }
Disabling sensor
36
36
36
[... Keeps running the callback function]

from johnny-five.

R-holmes10 avatar R-holmes10 commented on May 26, 2024

from johnny-five.

Related Issues (20)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.