### Install node-gyp Source: https://github.com/momenso/node-dht-sensor/blob/master/README.md Install the node-gyp build tool globally if it is not already present. This is a prerequisite for manual compilation. ```sh sudo npm install -g node-gyp ``` -------------------------------- ### Default Mode Read Example Source: https://github.com/momenso/node-dht-sensor/blob/master/_autodocs/api-reference/read.md Demonstrates reading sensor data using default settings after initialization. This example first initializes the sensor and then calls `read()` without parameters. ```javascript const sensor = require('node-dht-sensor'); sensor.initialize(22, 4); // Set defaults // Later, read without specifying sensor/pin const readout = sensor.read(); console.log(`Temperature: ${readout.temperature.toFixed(1)}°C`); ``` -------------------------------- ### Install node-dht-sensor with libgpiod and verbose output Source: https://github.com/momenso/node-dht-sensor/blob/master/_autodocs/configuration.md Install the module with both libgpiod support and verbose debug output enabled. This is useful for diagnosing sensor communication issues. ```bash npm install node-dht-sensor --use_libgpiod=true --dht_verbose=true ``` -------------------------------- ### Build Command for Node DHT Sensor Source: https://github.com/momenso/node-dht-sensor/blob/master/_autodocs/architecture.md Example commands to configure and build the Node DHT Sensor project using Node-gyp, resulting in a .node file. ```bash node-gyp configure --use_libgpiod=false node-gyp build # Produces: build/Release/node_dht_sensor.node ``` -------------------------------- ### Install with Verbose Logging Source: https://github.com/momenso/node-dht-sensor/blob/master/README.md Install the node-dht-sensor package with verbose logging enabled. This flag provides detailed output during installation. ```sh npm install node-dht-sensor --dht_verbose=true ``` -------------------------------- ### Install node-dht-sensor with libgpiod Source: https://github.com/momenso/node-dht-sensor/blob/master/README.md Installs the module using the libgpiod API, recommended for modern Raspberry Pi models like Pi 5. ```sh npm install node-dht-sensor --use_libgpiod=true ``` -------------------------------- ### Install Node DHT Sensor Source: https://github.com/momenso/node-dht-sensor/blob/master/_autodocs/README.md Install the library using npm. For Raspberry Pi 5 or modern Debian, use the --use_libgpiod=true flag. ```bash npm install node-dht-sensor ``` ```bash npm install node-dht-sensor --use_libgpiod=true ``` -------------------------------- ### Initialize DHT Sensor using libgpiod Source: https://github.com/momenso/node-dht-sensor/blob/master/_autodocs/configuration.md Initialize the sensor after installing with libgpiod support. This code snippet utilizes the libgpiod backend. ```javascript const sensor = require('node-dht-sensor'); sensor.initialize(22, 4); // Uses libgpiod backend ``` -------------------------------- ### Install node-dht-sensor via npm Source: https://github.com/momenso/node-dht-sensor/blob/master/README.md Standard installation for most Linux systems and older Raspberry Pi models. ```sh npm install node-dht-sensor ``` -------------------------------- ### Install Node.js using NodeSource Repository Source: https://github.com/momenso/node-dht-sensor/blob/master/README.md Install Node.js version 20.x on Raspberry Pi using the official NodeSource package repository. This method ensures the correct architecture build is installed. ```sh curl -fsSL https://deb.nodesource.com/setup_20.x | sudo -E bash - sudo apt-get install -y nodejs ``` -------------------------------- ### Synchronous Read Example Source: https://github.com/momenso/node-dht-sensor/blob/master/_autodocs/api-reference/read.md Demonstrates how to perform a synchronous read and handle the returned data, checking for validity before logging temperature and humidity. This is suitable for simple scripts or when precise timing is not critical. ```javascript const sensor = require('node-dht-sensor'); const readout = sensor.read(22, 4); if (readout.isValid) { console.log(`Temperature: ${readout.temperature.toFixed(1)}°C`); console.log(`Humidity: ${readout.humidity.toFixed(1)}%`); } else { console.log(`Read failed after ${readout.errors} retries`); } ``` -------------------------------- ### Complete Sensor Monitoring Example (Promises API) Source: https://github.com/momenso/node-dht-sensor/blob/master/_autodocs/api-reference/promises-api.md This snippet demonstrates how to initialize and continuously monitor a DHT sensor using the Promises API with async/await. It reads sensor data every 2 seconds and includes basic error handling. ```javascript const sensor = require('node-dht-sensor').promises; async function monitorSensor() { // Initialize sensor sensor.setMaxRetries(10); sensor.initialize(22, 17); try { // Read every 2 seconds while (true) { const reading = await sensor.read(22, 17); console.log(`${new Date().toISOString()}`); console.log(` Temperature: ${reading.temperature.toFixed(1)}°C`); console.log(` Humidity: ${reading.humidity.toFixed(1)}%`); // Wait 2 seconds before next read await new Promise(resolve => setTimeout(resolve, 2000)); } } catch (err) { console.error('Sensor monitoring failed:', err); } } monitorSensor(); ``` -------------------------------- ### Install libgpiod dependencies on Debian Source: https://github.com/momenso/node-dht-sensor/blob/master/README.md Installs the necessary development headers and pkg-config for libgpiod on Debian-based systems. ```sh sudo apt-get update sudo apt-get install -y libgpiod-dev pkg-config ``` -------------------------------- ### Asynchronous Read Example Source: https://github.com/momenso/node-dht-sensor/blob/master/_autodocs/api-reference/read.md Shows how to use the asynchronous read method with a callback to handle sensor data. It logs temperature and humidity on success or an error message if the read fails. ```javascript const sensor = require('node-dht-sensor'); sensor.read(22, 4, function(err, temperature, humidity) { if (err) { console.error('Failed to read sensor:', err); } else { console.log(`Temperature: ${temperature.toFixed(1)}°C`); console.log(`Humidity: ${humidity.toFixed(1)}%`); } }); ``` -------------------------------- ### Example GPIO Pin Assignments Source: https://github.com/momenso/node-dht-sensor/blob/master/_autodocs/types.md Illustrates how to connect the DHT sensor to different GPIO pins using the sensor.read() method. Ensure you use the correct GPIO pin number for your Raspberry Pi model. ```javascript const sensor = require('node-dht-sensor'); // Connect sensor to GPIO pin 4 sensor.read(22, 4); // Connect sensor to GPIO pin 17 sensor.read(22, 17); ``` -------------------------------- ### Synchronous Sensor Read Usage Source: https://github.com/momenso/node-dht-sensor/blob/master/_autodocs/types.md Example of performing a synchronous sensor read and checking the validity of the results. Requires importing the 'node-dht-sensor' module. ```javascript const sensor = require('node-dht-sensor'); const readout = sensor.read(22, 4); if (readout.isValid) { console.log(`Temperature: ${readout.temperature}°C`); console.log(`Humidity: ${readout.humidity}%`); } ``` -------------------------------- ### Documentation Statistics Table Source: https://github.com/momenso/node-dht-sensor/blob/master/_autodocs/INDEX.md Presents key metrics about the documentation, including the number of files, lines of code, examples, and more. ```markdown | Metric | Value | |--------|-------| | Total Files | 11 markdown documents | | Total Lines | 2,568 | | Code Examples | 40+ | | Data Tables | 25+ | | Source References | 50+ | | Headings | 175 | | Section Hierarchy | 5 levels | ``` -------------------------------- ### Initialize DHT Sensor on Raspberry Pi 1-4 Source: https://github.com/momenso/node-dht-sensor/blob/master/_autodocs/configuration.md Use this for Raspberry Pi 1-4. The module uses direct memory access to the BCM2835 chip for GPIO control without extra setup. ```javascript const sensor = require('node-dht-sensor'); sensor.initialize(22, 4); // Works on Pi 1-4 without extra setup ``` -------------------------------- ### Configure node-gyp for verbose output Source: https://github.com/momenso/node-dht-sensor/blob/master/_autodocs/configuration.md Manually configure node-gyp to enable verbose debug output. This is an alternative to the npm install flag for enabling detailed logging. ```bash node-gyp configure -- -Ddht_verbose=true node-gyp build ``` -------------------------------- ### Read Multiple DHT Sensors Source: https://github.com/momenso/node-dht-sensor/blob/master/README.md Queries multiple DHT sensors (DHT11 on GPIO 17, DHT22 on GPIO 4) and logs their readings every 2 seconds. This example demonstrates handling multiple sensors with different types and pins. ```javascript var sensorLib = require("node-dht-sensor"); var app = { sensors: [ { name: "Indoor", type: 11, pin: 17, }, { name: "Outdoor", type: 22, pin: 4, }, ], read: function () { for (var sensor in this.sensors) { var readout = sensorLib.read( this.sensors[sensor].type, this.sensors[sensor].pin, ); console.log( `[${this.sensors[sensor].name}] ` + `temperature: ${readout.temperature.toFixed(1)}°C, ` + `humidity: ${readout.humidity.toFixed(1)}%`, ); } setTimeout(function () { app.read(); }, 2000); }, }; app.read(); ``` -------------------------------- ### Read DHT Sensor Data with Promises Source: https://github.com/momenso/node-dht-sensor/blob/master/README.md Uses the Promises API of the node-dht-sensor library to read data from a DHT22 sensor connected to GPIO 17. This example demonstrates asynchronous operations using .then() and .catch(). ```javascript var sensor = require("node-dht-sensor").promises; // You can use `initialize` and `setMaxTries` just like before sensor.setMaxRetries(10); sensor.initialize(22, 17); // You can still use the synchronous version of `read`: // var readout = sensor.readSync(22, 4); sensor.read(22, 17).then( function (res) { console.log( `temp: ${res.temperature.toFixed(1)}°C, ` + `humidity: ${res.humidity.toFixed(1)}%`, ); }, function (err) { console.error("Failed to read sensor data:", err); }, ); ``` -------------------------------- ### Initialize Sensor (Test Mode) Source: https://github.com/momenso/node-dht-sensor/blob/master/_autodocs/README.md Sets up the sensor in test mode with fake temperature and humidity values. ```APIDOC ## initialize({test: {fake: {...}}}) ### Description Configures the sensor for test mode, allowing you to provide fake temperature and humidity values for testing purposes. ### Method Synchronous function call ### Parameters #### Request Body - **test** (object) - Required - Configuration object for test mode. - **fake** (object) - Required - Object containing fake sensor readings. - **temperature** (number) - Required - Fake temperature in Celsius. - **humidity** (number) - Required - Fake humidity percentage (0-100). ``` -------------------------------- ### Configure and Build with libgpiod Source: https://github.com/momenso/node-dht-sensor/blob/master/README.md Configure the project to use libgpiod and then build the component manually. This enables automatic detection of libgpiod. ```sh node-gyp configure --use_libgpiod=true node-gyp build ``` -------------------------------- ### Configure Build with Verbose Tracing Source: https://github.com/momenso/node-dht-sensor/blob/master/README.md Enable verbose tracing when building the module directly from source by passing a flag to the node-gyp configure command. ```sh node-gyp configure -- -Ddht_verbose=true ``` -------------------------------- ### initialize(sensorType, gpioPin, maxRetries) Source: https://github.com/momenso/node-dht-sensor/blob/master/_autodocs/api-reference/promises-api.md Configures default sensor and GPIO settings, or enables test mode. This method is identical to the main module's `initialize()` function. ```APIDOC ## initialize(sensorType, gpioPin, maxRetries) ### Description Configures default sensor and GPIO settings, or enables test mode. This method is identical to the main module's `initialize()` function. ### Method `initialize` ### Parameters #### Path Parameters * **sensorType** (number) - Required - Sensor model: `11` for DHT11, `22` for DHT22/AM2302. * **gpioPin** (number) - Required - GPIO pin number where sensor is connected. * **maxRetries** (number) - Optional - Maximum retry attempts on read failure. ### Example ```javascript const sensor = require('node-dht-sensor').promises; sensor.initialize(22, 17); sensor.setMaxRetries(5); // or test mode: sensor.initialize({ test: { fake: { temperature: 21, humidity: 60 } } }); ``` ``` -------------------------------- ### Initialize Sensor with Promises API Source: https://github.com/momenso/node-dht-sensor/blob/master/_autodocs/api-reference/promises-api.md Configure the default sensor and GPIO settings using the Promise-based API. Supports direct initialization or test mode. ```javascript sensor.initialize(22, 17); sensor.setMaxRetries(5); ``` ```javascript sensor.initialize({ test: { fake: { temperature: 21, humidity: 60 } } }); ``` -------------------------------- ### Read DHT11 Sensor Data Source: https://github.com/momenso/node-dht-sensor/blob/master/README.md Reads data from a DHT11 sensor connected to GPIO pin 4 and logs the temperature and humidity to the console. Ensure the 'node-dht-sensor' library is installed. ```javascript var sensor = require("node-dht-sensor"); sensor.read(11, 4, function (err, temperature, humidity) { if (!err) { console.log(`temp: ${temperature}°C, humidity: ${humidity}%`); } }); ``` -------------------------------- ### Default Initialization with Sensor Type and GPIO Pin Source: https://github.com/momenso/node-dht-sensor/blob/master/_autodocs/api-reference/initialize.md Use this snippet to configure the sensor with a specific model and GPIO pin. It attempts to initialize the GPIO hardware and returns a boolean indicating success. Subsequent reads will use these defaults. ```javascript sensor.initialize(sensorType, gpioPin); ``` ```javascript const sensor = require('node-dht-sensor'); const success = sensor.initialize(22, 4); if (success) { const readout = sensor.read(); // Uses initialized defaults console.log(`Temperature: ${readout.temperature.toFixed(1)}°C`); } else { console.error('Failed to initialize sensor'); } ``` -------------------------------- ### Read DHT22/AM2302 Sensor Data Source: https://github.com/momenso/node-dht-sensor/blob/master/_autodocs/configuration.md Example of reading data from a DHT22 or AM2302 sensor connected to GPIO pin 4. The sensor type identifier `22` must be passed as the first argument. ```javascript const sensor = require('node-dht-sensor'); // DHT22 or AM2302 sensor sensor.read(22, 4, callback); ``` -------------------------------- ### Initialize DHT Sensor (Legacy Mode) Source: https://github.com/momenso/node-dht-sensor/blob/master/_autodocs/api-reference/module.md Initialize the DHT sensor using legacy parameters for sensor type, GPIO pin, and optionally maximum retries. ```javascript sensor.initialize(sensorType, gpioPin); sensor.initialize(sensorType, gpioPin, maxRetries); ``` -------------------------------- ### sensor.initialize() Source: https://github.com/momenso/node-dht-sensor/blob/master/_autodocs/api-reference/module.md Initializes the sensor library, either in legacy mode with sensor type and pin, or in test mode with fake data. ```APIDOC ## sensor.initialize() ### Description Initializes the DHT sensor library. This can be done in legacy mode by specifying the sensor type and GPIO pin, or in test mode by providing a configuration object with fake sensor values for development purposes. ### Method Legacy mode: `sensor.initialize(sensorType, gpioPin)` or `sensor.initialize(sensorType, gpioPin, maxRetries)` Test mode: `sensor.initialize({ test: { fake: { temperature: number, humidity: number } } })` ### Parameters #### Legacy Mode (Optional) - **sensorType** (number) - The type of DHT sensor (e.g., 11, 22). - **gpioPin** (number) - The GPIO pin number the sensor is connected to. - **maxRetries** (number) - The maximum number of retries for sensor readings. #### Test Mode (Required) - **configuration object** (object) - **test** (object) - **fake** (object) - **temperature** (number) - Fake temperature value in Celsius. - **humidity** (number) - Fake humidity value in percentage. ### Request Example (Legacy Mode) ```javascript sensor.initialize(22, 4); ``` ### Request Example (Test Mode) ```javascript sensor.initialize({ test: { fake: { temperature: 23.5, humidity: 65 } } }); ``` ``` -------------------------------- ### Read DHT Sensor Data (Synchronous) Source: https://github.com/momenso/node-dht-sensor/blob/master/_autodocs/api-reference/module.md Perform a synchronous read operation to get temperature and humidity data from a DHT sensor. This method can be called with or without specifying sensor type and pin. ```javascript const readout = sensor.read(); const readout = sensor.read(sensorType, gpioPin); ``` -------------------------------- ### Default Initialization Source: https://github.com/momenso/node-dht-sensor/blob/master/_autodocs/MANIFEST.md Initializes the DHT sensor with default settings. This is typically the first step before reading data. ```APIDOC ## `initialize(type, pin, retries?)` ### Description Initializes the DHT sensor with default settings. This is typically the first step before reading data. ### Method Function call ### Parameters #### Path Parameters - **type** (number) - Required - The type of the DHT sensor (e.g., DHT11, DHT22). - **pin** (number) - Required - The GPIO pin number the sensor is connected to. - **retries** (number) - Optional - The number of retries to attempt during initialization. ``` -------------------------------- ### Initialize DHT Sensor with Defaults Source: https://github.com/momenso/node-dht-sensor/blob/master/_autodocs/configuration.md Use this snippet to initialize the sensor with default retry settings. Specify the sensor type and GPIO pin. ```javascript const sensor = require('node-dht-sensor'); // Basic initialization with defaults sensor.initialize(22, 4); ``` -------------------------------- ### initialize() Source: https://github.com/momenso/node-dht-sensor/blob/master/_autodocs/api-reference/module.md Initializes the sensor settings or enables test mode. This function is primarily for configuration. ```APIDOC ## initialize() ### Description Configures sensor settings or enables test mode for the DHT sensor. ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Returns - **boolean** (legacy) - Indicates success or failure in older versions. - **undefined** (test mode) - Returned when test mode is enabled. ``` -------------------------------- ### On-Demand GPIO Initialization Source: https://github.com/momenso/node-dht-sensor/blob/master/_autodocs/architecture.md Initializes GPIO on demand for both synchronous and asynchronous reads if not already initialized. The initialization is sticky and called only once. ```c if (!initialized) { initialized = initialize() == 0; if (!initialized) { // Throw "failed to initialize" } } ``` -------------------------------- ### Handle DHT Sensor Initialization Errors Source: https://github.com/momenso/node-dht-sensor/blob/master/_autodocs/errors.md This snippet demonstrates how to handle potential errors during DHT sensor initialization. It checks for a successful initialization and logs specific error messages if GPIO access is denied or other initialization failures occur. ```javascript const sensor = require('node-dht-sensor'); try { const success = sensor.initialize(22, 4); if (!success) { console.error('GPIO initialization failed'); console.error('Ensure the process has GPIO access (may need sudo on RPi)'); process.exit(1); } } catch (err) { console.error('Initialize threw:', err.message); } ``` -------------------------------- ### Test Mode Initialization with Fake Data Source: https://github.com/momenso/node-dht-sensor/blob/master/_autodocs/api-reference/initialize.md Enable test mode by providing an options object with fake temperature and humidity values. All subsequent sensor reads will return these predefined values, bypassing hardware interaction. ```javascript sensor.initialize({ test: { fake: { temperature: 21.5, humidity: 60 } } }); ``` ```javascript const sensor = require('node-dht-sensor'); // Enable test mode with fixed values sensor.initialize({ test: { fake: { temperature: 22, humidity: 55 } } }); // All subsequent reads return the fake values sensor.read(22, 4, function(err, temperature, humidity) { if (!err) { console.log(`Simulated - Temperature: ${temperature}°C, Humidity: ${humidity}%`); // Output: Simulated - Temperature: 22°C, Humidity: 55% } }); ``` -------------------------------- ### InitializeOptions Source: https://github.com/momenso/node-dht-sensor/blob/master/_autodocs/types.md Configuration object for test mode initialization. When test mode is enabled, all sensor reads will return fixed values instead of actual sensor data. ```APIDOC ## InitializeOptions Configuration object for test mode initialization. ```javascript { test: { fake: { temperature: number, humidity: number } } } ``` **Fields:** | Field | Type | Required | Description | |-------|------|----------|-------------| | test | object | Yes | Container for test mode configuration | | test.fake | object | Yes | Fake sensor data values | | test.fake.temperature | number | Yes | Simulated temperature in Celsius (float) | | test.fake.humidity | number | Yes | Simulated humidity percentage (float) | **Usage:** ```javascript const sensor = require('node-dht-sensor'); sensor.initialize({ test: { fake: { temperature: 22.5, humidity: 55 } } }); // All reads now return these fixed values sensor.read(22, 4, (err, temp, humidity) => { console.log(`Temperature: ${temp}°C, Humidity: ${humidity}%`); // Always outputs: Temperature: 22.5°C, Humidity: 55% }); ``` ``` -------------------------------- ### Initialize Sensor in Test Mode Source: https://github.com/momenso/node-dht-sensor/blob/master/_autodocs/types.md Configure the sensor to use fake temperature and humidity values for testing. All subsequent reads will return these fixed values. ```javascript const sensor = require('node-dht-sensor'); sensor.initialize({ test: { fake: { temperature: 22.5, humidity: 55 } } }); // All reads now return these fixed values sensor.read(22, 4, (err, temp, humidity) => { console.log(`Temperature: ${temp}°C, Humidity: ${humidity}%`); // Always outputs: Temperature: 22.5°C, Humidity: 55% }); ``` -------------------------------- ### Sensor Initialization Source: https://github.com/momenso/node-dht-sensor/blob/master/_autodocs/INDEX.md Initializes the sensor with specific pin and type, or with a test configuration. Also shows how to set the maximum number of retries. ```javascript // Configuration sensor.initialize(22, 4, 5); sensor.initialize({test: {fake: {temperature: 22, humidity: 55}}}); sensor.setMaxRetries(5); ``` -------------------------------- ### Test Mode Initialization Options Source: https://github.com/momenso/node-dht-sensor/blob/master/_autodocs/README.md This object structure is used to configure the sensor library for test mode, allowing you to provide fake temperature and humidity values. ```javascript { test: { fake: { temperature: number, // Celsius humidity: number // Percentage (0-100) } } } ``` -------------------------------- ### Fix: Initialize with Numeric Arguments (Legacy Mode) Source: https://github.com/momenso/node-dht-sensor/blob/master/_autodocs/errors.md When using legacy mode, ensure that sensor type and pin are provided as numbers, not strings. Incorrectly passing strings can lead to a Type Error. ```javascript // Wrong sensor.initialize("22", "4"); // Strings instead of numbers ``` ```javascript // Correct sensor.initialize(22, 4); // Use numbers ``` -------------------------------- ### Initialize DHT Sensor in Test Mode Source: https://github.com/momenso/node-dht-sensor/blob/master/README.md Initializes the DHT sensor library in test mode with predefined temperature and humidity values. This is useful for development without a physical sensor. ```javascript sensor.initialize({ test: { fake: { temperature: 21, humidity: 60, }, }, }); ``` -------------------------------- ### Test Mode Initialization Logic Source: https://github.com/momenso/node-dht-sensor/blob/master/_autodocs/architecture.md Sets the initialized flag to true and enables test mode without performing actual GPIO initialization. Fake temperature and humidity values are set. ```c if (test mode requested) { initialized = 1; // Skip GPIO initialization _test_fake_enabled = true; _fake_temperature = ...; _fake_humidity = ...; } ``` -------------------------------- ### Fix: Initialize with Supported Sensor Type (Legacy Mode) Source: https://github.com/momenso/node-dht-sensor/blob/master/_autodocs/errors.md Ensure the sensor type provided in legacy mode is supported by the library. Using an unsupported type, like 33, will result in an error. ```javascript // Wrong sensor.initialize(33, 4); // 33 is not valid ``` ```javascript // Correct - use 11 or 22 sensor.initialize(22, 4); ``` -------------------------------- ### Test Mode Initialization Source: https://github.com/momenso/node-dht-sensor/blob/master/_autodocs/MANIFEST.md Initializes the DHT sensor in test mode, allowing for simulation without hardware. Useful for development and testing. ```APIDOC ## `initialize({test: {...}})` ### Description Initializes the DHT sensor in test mode, allowing for simulation without hardware. Useful for development and testing. ### Method Function call with configuration object ### Parameters #### Request Body - **test** (object) - Required - Configuration object for test mode. - **{...}** - Specific test mode parameters (details not provided in source). ``` -------------------------------- ### Import Node DHT Sensor Module Source: https://github.com/momenso/node-dht-sensor/blob/master/_autodocs/api-reference/module.md Import the main module of the node-dht-sensor library. This is the first step before using any sensor functionalities. ```javascript const sensor = require('node-dht-sensor'); ``` -------------------------------- ### Initialize Sensor (Legacy) Source: https://github.com/momenso/node-dht-sensor/blob/master/_autodocs/README.md Legacy function to initialize the DHT sensor. Returns a boolean indicating success or failure. ```APIDOC ## initialize(type, pin, retries?) ### Description Initializes the DHT sensor with the specified type and pin. This is a legacy initialization method. ### Method Synchronous function call ### Parameters #### Path Parameters - **type** (number) - Required - The type of DHT sensor (e.g., DHT11, DHT22). - **pin** (number) - Required - The GPIO pin number the sensor is connected to. - **retries** (number) - Optional - The number of retries to attempt during initialization. ### Returns - **boolean** - True if initialization was successful, false otherwise. ``` -------------------------------- ### Default Initialization Source: https://github.com/momenso/node-dht-sensor/blob/master/_autodocs/api-reference/initialize.md Configures the sensor type and GPIO pin for subsequent reads. This mode attempts to initialize the GPIO hardware. ```APIDOC ## initialize(sensorType, gpioPin, maxRetries) ### Description Configures the default sensor type and GPIO pin for subsequent reads. This method attempts to initialize the GPIO hardware. ### Method `initialize` ### Parameters #### Path Parameters - **sensorType** (number) - Required - Sensor model: `11` for DHT11, `22` for DHT22/AM2302 - **gpioPin** (number) - Required - GPIO pin number for the sensor - **maxRetries** (number) - Optional - Maximum read retry attempts on failure. Defaults to 3. ### Response #### Success Response - **boolean** - `true` if GPIO was initialized successfully, `false` otherwise. ### Request Example ```javascript const sensor = require('node-dht-sensor'); const success = sensor.initialize(22, 4); if (success) { const readout = sensor.read(); // Uses initialized defaults console.log(`Temperature: ${readout.temperature.toFixed(1)}°C`); } else { console.error('Failed to initialize sensor'); } ``` ``` -------------------------------- ### Read DHT Sensor Data with Async/Await Source: https://github.com/momenso/node-dht-sensor/blob/master/README.md Demonstrates reading DHT sensor data using the Promises API with async/await syntax. This provides a more modern and readable way to handle asynchronous operations. ```javascript const sensor = require("node-dht-sensor").promises; async function exec() { try { const res = await sensor.read(22, 4); console.log( `temp: ${res.temperature.toFixed(1)}°C, ` + `humidity: ${res.humidity.toFixed(1)}%`, ); } catch (err) { console.error("Failed to read sensor data:", err); } } exec(); ``` -------------------------------- ### Read Sensor Data with Async/Await Source: https://github.com/momenso/node-dht-sensor/blob/master/_autodocs/api-reference/promises-api.md Asynchronously read temperature and humidity data using async/await syntax. This provides a cleaner way to handle asynchronous operations and errors. ```javascript const sensor = require('node-dht-sensor').promises; async function readSensor() { try { const result = await sensor.read(22, 4); console.log(`Temperature: ${result.temperature.toFixed(1)}°C`); console.log(`Humidity: ${result.humidity.toFixed(1)}%`); } catch (err) { console.error('Read failed:', err); } } readSensor(); ``` -------------------------------- ### Asynchronous Read Flow Diagram Source: https://github.com/momenso/node-dht-sensor/blob/master/_autodocs/architecture.md Illustrates the step-by-step process of an asynchronous read operation from the sensor, including C++ and JavaScript interactions. ```text JavaScript call: sensor.read(22, 4, callback) ↓ lib/index.js exports.read (pass-through) ↓ src/node-dht-sensor.cpp Read() (dispatcher) ├─ Check argument count → 3 params = asynchronous ↓ src/node-dht-sensor.cpp ReadAsync() ├─ Extract parameters: │ ├─ sensor_type = arg[0] │ ├─ gpio_pin = arg[1] │ └─ callback = arg[2] ├─ Create ReadWorker instance │ └─ Store callback and parameters ├─ Queue worker to libuv thread pool ↓ [Execute in separate thread:] ReadWorker::Execute() ├─ Lock mutex (sensorMutex) ├─ Call Init(): │ ├─ If not initialized: initialize GPIO │ └─ Check init success ├─ Call Read(): │ ├─ Validate sensor type │ ├─ Retry loop (up to max_retries): │ │ ├─ Call readSensor() │ │ ├─ If success: break │ │ └─ If fail && retries: usleep(450000), retry │ └─ Set failed flag if result != 0 ├─ Unlock mutex ↓ [Back on main thread via libuv event loop:] ReadWorker::OnOK() ├─ Check initialization status ├─ If failed: call callback with error └─ Else: call callback with (null, temperature, humidity) ↓ JavaScript callback invoked ``` -------------------------------- ### Initialize DHT Sensor with Custom Retries Source: https://github.com/momenso/node-dht-sensor/blob/master/_autodocs/configuration.md Initialize the sensor with a specific maximum number of retry attempts for read failures. Specify the sensor type, GPIO pin, and max retries. ```javascript const sensor = require('node-dht-sensor'); // With custom retry count sensor.initialize(22, 4, 5); ``` -------------------------------- ### read() Source: https://github.com/momenso/node-dht-sensor/blob/master/_autodocs/api-reference/module.md Reads temperature and humidity from the DHT sensor. This is a synchronous operation. ```APIDOC ## read() ### Description Reads temperature and humidity from the DHT sensor synchronously. ### Parameters #### Path Parameters - **type** (number) - Required - The type of DHT sensor (e.g., 22). - **pin** (number) - Required - The GPIO pin number the sensor is connected to. #### Query Parameters None #### Request Body None ### Returns - **object** - An object containing sensor readings. - **isValid** (boolean) - True if the read was successful, false otherwise. - **temperature** (number) - The temperature in Celsius if the read was valid. - **humidity** (number) - The humidity in percentage if the read was valid. - **errors** (number) - The number of retries performed if the read failed. ``` -------------------------------- ### Async/Await Pattern for Reading Sensor Data Source: https://github.com/momenso/node-dht-sensor/blob/master/_autodocs/api-reference/module.md Implement asynchronous sensor reading using the async/await syntax, which provides a more readable way to handle promises. This pattern is ideal for modern JavaScript development. ```javascript const sensor = require('node-dht-sensor').promises; async function main() { try { const result = await sensor.read(22, 4); console.log(`Temperature: ${result.temperature.toFixed(1)}°C`); } catch (err) { console.error('Read failed:', err); } } main(); ``` -------------------------------- ### Node-gyp Configuration for Node DHT Sensor Source: https://github.com/momenso/node-dht-sensor/blob/master/_autodocs/architecture.md This configuration file defines build variables, source files, and conditional compilation flags for the Node DHT Sensor project using Node-gyp. ```gyp variables: use_libgpiod: false (default) dht_verbose: false (default) sources: 4 files (conditionally) defines: NAPI_DISABLE_CPP_EXCEPTIONS, VERBOSE (if enabled) cflags: -O3 optimization, warnings disabled conditions: if use_libgpiod: add libgpiod define, link -lgpiod if dht_verbose: add VERBOSE define ``` -------------------------------- ### Test Mode Initialization Source: https://github.com/momenso/node-dht-sensor/blob/master/_autodocs/api-reference/initialize.md Enables test mode with fake sensor data, bypassing hardware initialization. All subsequent reads will return the configured fake values. ```APIDOC ## initialize(options) ### Description Enables test mode with fake sensor data, bypassing all GPIO hardware. All subsequent `read()` calls will return the configured fake values regardless of parameters. ### Method `initialize` ### Parameters #### Path Parameters - **options** (object) - Required - Configuration object containing test settings. - **test** (object) - Required - Test mode container. - **fake** (object) - Required - Fake sensor data configuration. - **temperature** (number) - Required - Simulated temperature in Celsius. - **humidity** (number) - Required - Simulated humidity percentage. ### Response #### Success Response - **undefined** - This method does not return a value in test mode. ### Request Example ```javascript const sensor = require('node-dht-sensor'); // Enable test mode with fixed values sensor.initialize({ test: { fake: { temperature: 22, humidity: 55 } } }); // All subsequent reads return the fake values sensor.read(22, 4, function(err, temperature, humidity) { if (!err) { console.log(`Simulated - Temperature: ${temperature}°C, Humidity: ${humidity}%`); // Output: Simulated - Temperature: 22°C, Humidity: 55% } }); ``` ``` -------------------------------- ### Basic Synchronous Read Source: https://github.com/momenso/node-dht-sensor/blob/master/_autodocs/README.md Perform a synchronous read of temperature and humidity from a DHT sensor. Ensure the sensor type and GPIO pin are correctly specified. ```javascript const sensor = require('node-dht-sensor'); const readout = sensor.read(22, 4); // DHT22 on GPIO 4 if (readout.isValid) { console.log(`Temperature: ${readout.temperature.toFixed(1)}°C`); console.log(`Humidity: ${readout.humidity.toFixed(1)}%`); } ``` -------------------------------- ### promises.read() Source: https://github.com/momenso/node-dht-sensor/blob/master/_autodocs/api-reference/module.md Asynchronously reads temperature and humidity from the DHT sensor using Promises. ```APIDOC ## promises.read() ### Description Asynchronously reads temperature and humidity from the DHT sensor using a Promise-based API. ### Parameters #### Path Parameters - **type** (number) - Required - The type of DHT sensor (e.g., 22). - **pin** (number) - Required - The GPIO pin number the sensor is connected to. #### Query Parameters None #### Request Body None ### Returns - **Promise** - A promise that resolves with an object containing sensor readings. - **temperature** (number) - The temperature in Celsius. - **humidity** (number) - The humidity in percentage. ``` -------------------------------- ### Fix: Initialize Test Mode with Object Argument Source: https://github.com/momenso/node-dht-sensor/blob/master/_autodocs/errors.md When initializing in test mode, the argument must be an object. Providing a string or using legacy mode with two arguments will trigger an 'Invalid argument: an object is expected' error. ```javascript // Wrong sensor.initialize(22, 4); // Using legacy mode with 2 args sensor.initialize("test"); // String instead of object ``` ```javascript // Correct sensor.initialize({ test: { fake: { temperature: 22, humidity: 55 } } }); ``` -------------------------------- ### Fix: Initialize with Numeric Max Retries (Legacy Mode) Source: https://github.com/momenso/node-dht-sensor/blob/master/_autodocs/errors.md The maxRetries parameter in legacy mode must be a number. Passing it as a string will cause an 'Invalid maxRetries parameter' error. ```javascript // Wrong sensor.initialize(22, 4, "5"); // String instead of number ``` ```javascript // Correct sensor.initialize(22, 4, 5); // Use number ``` -------------------------------- ### Import Promises API Source: https://github.com/momenso/node-dht-sensor/blob/master/_autodocs/api-reference/promises-api.md Import the Promise-based API from the node-dht-sensor library. ```javascript const sensor = require('node-dht-sensor').promises; ``` -------------------------------- ### Read Multiple Sensors with Different Types and Pins Source: https://github.com/momenso/node-dht-sensor/blob/master/_autodocs/configuration.md Demonstrates reading from two different sensors simultaneously: an indoor DHT11 on pin 17 and an outdoor DHT22 on pin 4. The readings are then logged to the console. ```javascript const sensor = require('node-dht-sensor'); // Indoor sensor (DHT11 on pin 17) const indoorReading = sensor.read(11, 17); // Outdoor sensor (DHT22 on pin 4) const outdoorReading = sensor.read(22, 4); console.log(`Indoor: ${indoorReading.temperature}°C`); console.log(`Outdoor: ${outdoorReading.temperature}°C`); ``` -------------------------------- ### Develop with DHT Sensor Test Mode Source: https://github.com/momenso/node-dht-sensor/blob/master/_autodocs/api-reference/module.md Enable test mode for development without physical hardware. This allows all sensor reads to return predefined fake values. ```javascript const sensor = require('node-dht-sensor'); // Enable test mode - useful for development without hardware sensor.initialize({ test: { fake: { temperature: 23.5, humidity: 65 } } }); // All reads return the fake values sensor.read(22, 4, (err, temp, hum) => { console.log(`Temperature: ${temp}°C, Humidity: ${hum}%`); // Output: Temperature: 23.5°C, Humidity: 65% }); ``` -------------------------------- ### Handling 'failed to read sensor' with Async/Await Source: https://github.com/momenso/node-dht-sensor/blob/master/_autodocs/errors.md Demonstrates error handling for the 'failed to read sensor' error using the async/await syntax with a try-catch block. ```javascript const sensor = require('node-dht-sensor').promises; async function readSensor() { try { const result = await sensor.read(22, 4); console.log(`Success: ${result.temperature}°C, ${result.humidity}%`); } catch (err) { console.error('Read failed:', err.message); } } ``` -------------------------------- ### read(sensorType, gpioPin) Source: https://github.com/momenso/node-dht-sensor/blob/master/_autodocs/api-reference/promises-api.md Asynchronously reads temperature and humidity data, returning a Promise. This method supports both Promise chain `.then().catch()` and `async/await` patterns. ```APIDOC ## read(sensorType, gpioPin) ### Description Asynchronously reads temperature and humidity data, returning a Promise. This method supports both Promise chain `.then().catch()` and `async/await` patterns. ### Method `read` ### Parameters #### Path Parameters * **sensorType** (number) - Required - Sensor model: `11` for DHT11, `22` for DHT22/AM2302. * **gpioPin** (number) - Required - GPIO pin number where sensor is connected. ### Returns Promise resolving to object: * **temperature** (number) - Temperature reading in Celsius. * **humidity** (number) - Relative humidity percentage. ### Promise Rejection Rejects with Error on read failure with message "failed to read sensor". ### Request Example (Promise Chain) ```javascript const sensor = require('node-dht-sensor').promises; sensor.read(22, 4) .then(function(result) { console.log(`Temperature: ${result.temperature.toFixed(1)}°C`); console.log(`Humidity: ${result.humidity.toFixed(1)}%`); }) .catch(function(err) { console.error('Read failed:', err); }); ``` ### Request Example (Async/Await) ```javascript const sensor = require('node-dht-sensor').promises; async function readSensor() { try { const result = await sensor.read(22, 4); console.log(`Temperature: ${result.temperature.toFixed(1)}°C`); console.log(`Humidity: ${result.humidity.toFixed(1)}%`); } catch (err) { console.error('Read failed:', err); } } readSensor(); ``` ``` -------------------------------- ### Read Sensor Data with Promise Chain Source: https://github.com/momenso/node-dht-sensor/blob/master/_autodocs/api-reference/promises-api.md Asynchronously read temperature and humidity data using a Promise chain. Handles successful reads and errors gracefully. ```javascript const sensor = require('node-dht-sensor').promises; sensor.read(22, 4) .then(function(result) { console.log(`Temperature: ${result.temperature.toFixed(1)}°C`); console.log(`Humidity: ${result.humidity.toFixed(1)}%`); }) .catch(function(err) { console.error('Read failed:', err); }); ``` -------------------------------- ### Correct Usage of read() Method Source: https://github.com/momenso/node-dht-sensor/blob/master/_autodocs/errors.md The read() method expects either two arguments for synchronous reads, two arguments and a callback for asynchronous reads, or no arguments to use default settings. Providing an incorrect number of arguments (1, 4, or 5+) will cause a TypeError. ```javascript // Wrong sensor.read(22); // 1 param sensor.read(22, 4, callback, extra); // 4 params ``` ```javascript // Correct - sync with params sensor.read(22, 4); ``` ```javascript // Correct - async with callback sensor.read(22, 4, function(err, temp, hum) { }); ``` ```javascript // Correct - no params (uses defaults) sensor.read(); ``` -------------------------------- ### File Organization Structure Source: https://github.com/momenso/node-dht-sensor/blob/master/_autodocs/INDEX.md Illustrates the directory structure and the purpose of each markdown file within the library's documentation. ```markdown output/ ├── README.md # Start here — overview and getting started ├── MANIFEST.md # Detailed guide to all files and topics ├── INDEX.md # This file ├── types.md # All data types and interfaces ├── configuration.md # Configuration options and platforms ├── errors.md # Error catalog and handling patterns ├── architecture.md # Internal design and implementation └── api-reference/ ├── module.md # Main module overview ├── read.md # read() function (sync and async) ├── initialize.md # initialize() function ├── setMaxRetries.md # setMaxRetries() function └── promises-api.md # promises namespace (Promise and async/await) ``` -------------------------------- ### Asynchronous Sensor Read with Callback Source: https://github.com/momenso/node-dht-sensor/blob/master/_autodocs/INDEX.md Reads sensor data asynchronously using a callback function. The callback receives error, temperature, and humidity. ```javascript // Asynchronous read sensor.read(22, 4, (err, temp, hum) => { }); // Callback: (err, temperature, humidity) ``` -------------------------------- ### Fix: Provide 'fake' Object in Test Mode Configuration Source: https://github.com/momenso/node-dht-sensor/blob/master/_autodocs/errors.md In test mode, the 'options.test' object must contain a 'fake' property that is itself an object. Missing or incorrectly typed 'fake' will cause an error. ```javascript // Wrong sensor.initialize({ test: {} // Missing 'fake' }); sensor.initialize({ test: { fake: "test" // Not an object } }); ``` ```javascript // Correct sensor.initialize({ test: { fake: { temperature: 22, humidity: 55 } } }); ``` -------------------------------- ### Promise Wrapper for Sensor Read Source: https://github.com/momenso/node-dht-sensor/blob/master/_autodocs/architecture.md Wraps the native asynchronous read function to provide a Promise-based interface. Use this for cleaner async/await syntax. ```javascript // From lib/index.js lines 9-19 read(type, pin) { return new Promise(function(resolve, reject) { sensor.read(type, pin, function(err, temperature, humidity) { if (err) { reject(err); } else { resolve({ temperature, humidity }); } }); }); } ``` -------------------------------- ### sensor.read() Source: https://github.com/momenso/node-dht-sensor/blob/master/_autodocs/api-reference/module.md Reads temperature and humidity data from a DHT sensor. It can be called synchronously or asynchronously. ```APIDOC ## sensor.read() ### Description Reads temperature and humidity data from a DHT sensor. This method can be used synchronously by providing the sensor type and GPIO pin, or asynchronously with a callback function. ### Method Synchronous: `sensor.read()` or `sensor.read(sensorType, gpioPin)` Asynchronous: `sensor.read(sensorType, gpioPin, callback)` ### Parameters #### Synchronous (Optional) - **sensorType** (number) - The type of DHT sensor (e.g., 11, 22). - **gpioPin** (number) - The GPIO pin number the sensor is connected to. #### Asynchronous (Required) - **sensorType** (number) - The type of DHT sensor (e.g., 11, 22). - **gpioPin** (number) - The GPIO pin number the sensor is connected to. - **callback** (function) - A function to be called with the error, temperature, and humidity. - **err** (Error) - An error object if the read fails. - **temperature** (number) - The temperature reading in Celsius. - **humidity** (number) - The humidity reading in percentage. ### Response #### Success Response (Synchronous) - **readout** (object) - An object containing the sensor readings. - **temperature** (object) - **toFixed(digits)** (function) - Returns the temperature formatted to a specified number of decimal places. - **humidity** (object) - **toFixed(digits)** (function) - Returns the humidity formatted to a specified number of decimal places. - **isValid** (boolean) - Indicates if the sensor reading is valid. - **errors** (number) - The number of retries attempted if the read failed. #### Success Response (Asynchronous) - **temperature** (number) - The temperature reading in Celsius. - **humidity** (number) - The humidity reading in percentage. ### Request Example (Synchronous) ```javascript const readout = sensor.read(22, 4); if (readout.isValid) { console.log(`Temperature: ${readout.temperature.toFixed(1)}°C, Humidity: ${readout.humidity.toFixed(1)}%`); } else { console.log(`Read failed (${readout.errors} retries)`); } ``` ### Request Example (Asynchronous) ```javascript sensor.read(22, 4, (err, temp, hum) => { if (err) { console.error('Failed to read sensor data:', err); return; } console.log(`Temperature: ${temp}°C, Humidity: ${hum}%`); }); ``` ``` -------------------------------- ### Fix: Define Temperature in Test Mode Fake Configuration Source: https://github.com/momenso/node-dht-sensor/blob/master/_autodocs/errors.md The 'temperature' field is mandatory within the 'options.test.fake' object for test mode. Omitting it will cause an error. ```javascript // Wrong sensor.initialize({ test: { fake: { humidity: 55 // Missing temperature } } }); ``` ```javascript // Correct sensor.initialize({ test: { fake: { temperature: 22, // Add temperature humidity: 55 } } }); ``` -------------------------------- ### Asynchronous Error Handling (C++) Source: https://github.com/momenso/node-dht-sensor/blob/master/_autodocs/architecture.md Illustrates setting an error message for asynchronous operations in a C++ addon. The error is then passed to the JavaScript callback, either as a null first argument (for success) or as an error object. ```cpp // Sets error string (queued for callback) SetError("failed to read sensor"); // In OnOK(): Callback().Call({env.Null()}); // error mode: first arg is null // OR Callback().Call({error_object}); // success: first arg is error message ```