Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Sensor disable only works once. #1839

Open
Tsteinroesland opened this issue Dec 29, 2023 · 3 comments
Open

Sensor disable only works once. #1839

Tsteinroesland opened this issue Dec 29, 2023 · 3 comments

Comments

@Tsteinroesland
Copy link

Original bug posted in 2019: #1520

I'm also seeing this issue with a very simple approach using setTimeouts.

Code to reproduce:


const board = new Board({
  port: 'COM3',
})

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

  moistureSensor.on('data', value => {
    console.log(value)
  })

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

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

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

Console:

413
413
413
413
413
413
413
413
413
Disable
Enable
413
413
413
413
413
413
413
413
413
Disable
413
414
[.... Keeps logging forever until program is exited]

@R-holmes10
Copy link

R-holmes10 commented Jan 1, 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);
});

@Tsteinroesland
Copy link
Author

@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]

@R-holmes10
Copy link

R-holmes10 commented Jan 2, 2024 via email

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants