### Install node-web-gpio using npm Source: https://github.com/chirimen-oh/node-web-gpio/blob/master/README.md This command installs the node-web-gpio package using npm, making it available for use in your Node.js project. ```bash npm i node-web-gpio ``` -------------------------------- ### Node.js GPIO Access Example Source: https://github.com/chirimen-oh/node-web-gpio/blob/master/docs/index.html Demonstrates how to request GPIO access, export a port for output, and toggle its state with a 1-second delay. Requires the node-web-gpio package. ```javascript const { requestGPIOAccess } = require("node-web-gpio"); const { promisify } = require("util"); const sleep = promisify(setTimeout); async function main() { const gpioAccess = await requestGPIOAccess(); const port = gpioAccess.ports.get(26); await port.export("out"); for (;; ) { await port.write(1); await sleep(1000); await port.write(0); await sleep(1000); } } main(); ``` -------------------------------- ### Retrieve Event Listeners (Node.js) Source: https://github.com/chirimen-oh/node-web-gpio/blob/master/docs/classes/GPIOAccess.html Provides an example of how to get a copy of the array containing all listeners registered for a specific event. This is useful for introspection or debugging. ```javascript import util from 'util'; // Assuming 'server' is an EventEmitter instance: // server.on('connection', (stream) => { // console.log('someone connected!'); // }); // console.log(util.inspect(server.listeners('connection'))); // Expected Output: // [ [Function] ] ``` -------------------------------- ### get Source: https://github.com/chirimen-oh/node-web-gpio/blob/master/docs/classes/GPIOPortMap.html Returns a specified element from the Map object. If the value associated with the provided key is an object, a reference to that object is returned. ```APIDOC ## get ### Description Returns a specified element from the Map object. If the value that is associated to the provided key is an object, then you will get a reference to that object and any change made to that object will effectively modify it inside the Map. ### Method GET (or similar, depending on underlying implementation if this is a method on an object) ### Endpoint Not applicable for method calls directly on an object instance. ### Parameters #### Path Parameters None #### Query Parameters * **key** (number) - Required - The key of the element to retrieve. #### Request Body None ### Request Example ```javascript const port = gpioMap.get(17); if (port) { console.log('GPIO port found:', port); } else { console.log('GPIO port not found.'); } ``` ### Response #### Success Response (undefined | GPIOPort) Returns the element associated with the specified key. If no element is associated with the specified key, undefined is returned. #### Response Example ```json // If found: { "value": "// GPIOPort object representation//" } // If not found: undefined ``` -------------------------------- ### Get GPIO Port Information (TypeScript) Source: https://github.com/chirimen-oh/node-web-gpio/blob/master/docs/classes/GPIOAccess.html Retrieves the current information about GPIO ports. This method returns a GPIOPortMap object containing the status and configuration of all available GPIO ports. ```typescript /** * Retrieves the current GPIO port information. * @returns {GPIOPortMap} The current port information. */ get ports(): GPIOPortMap; ``` -------------------------------- ### Get Raw Listeners (rawListeners) - Node.js Source: https://github.com/chirimen-oh/node-web-gpio/blob/master/docs/classes/GPIOAccess.html Retrieves a copy of the array containing all listeners for a given event, including any wrappers. This allows inspection of the listeners, even those added with methods like .once(). ```javascript import { EventEmitter } from 'node:events'; const emitter = new EventEmitter(); emitter.once('log', () => console.log('log once')); // Returns a new Array with a function `onceWrapper` which has a property // `listener` which contains the original listener bound above const listeners = emitter.rawListeners('log'); const logFnWrapper = listeners[0]; // Logs "log once" to the console and does not unbind the `once` event logFnWrapper.listener(); // Logs "log once" to the console and removes the listener logFnWrapper(); emitter.on('log', () => console.log('log persistently')); // Will return a new Array with a single function bound by `.on()` above const newListeners = emitter.rawListeners('log'); // Logs "log persistently" twice newListeners[0](); emitter.emit('log'); ``` -------------------------------- ### GPIOPortMap Methods - Map Operations Source: https://github.com/chirimen-oh/node-web-gpio/blob/master/docs/classes/GPIOPortMap.html Details the core Map operations available on the GPIOPortMap class, such as 'clear', 'delete', 'entries', 'forEach', 'get', 'has', 'keys', and 'values'. These methods allow for efficient management of the GPIO port mappings. ```typescript clear(): void delete(key: number): boolean entries(): MapIterator<[number, GPIOPort]> forEach(callbackfn: (value: GPIOPort, key: number, map: GPIOPortMap) => void, thisArg?: any): void get(key: number): GPIOPort | undefined has(key: number): boolean keys(): MapIterator values(): MapIterator ``` -------------------------------- ### Get Maximum Listeners (Node.js) Source: https://github.com/chirimen-oh/node-web-gpio/blob/master/docs/classes/GPIOAccess.html Shows how to retrieve the current maximum number of listeners allowed for an EventEmitter. This value can be set using setMaxListeners or defaults to a predefined value. ```javascript // Assuming 'server' is an EventEmitter instance: // console.log(server.getMaxListeners()); ``` -------------------------------- ### keys: Get an Iterable of GPIOPort Keys Source: https://github.com/chirimen-oh/node-web-gpio/blob/master/docs/classes/GPIOPortMap.html Returns an iterable object that contains the keys for each element in the Map of GPIO ports, in insertion order. ```typescript keys(): MapIterator; ``` -------------------------------- ### Get Event Names (Node.js) Source: https://github.com/chirimen-oh/node-web-gpio/blob/master/docs/classes/GPIOAccess.html Illustrates how to retrieve an array of all event names for which an EventEmitter has registered listeners. This includes string and Symbol event names. ```javascript import { EventEmitter } from 'node:events'; const myEE = new EventEmitter(); myEE.on('foo', () => {}); myEE.on('bar', () => {}); const sym = Symbol('symbol'); myEE.on(sym, () => {}); console.log(myEE.eventNames()); // Expected Output: // [ 'foo', 'bar', Symbol(symbol) ] ``` -------------------------------- ### Get Event Listeners (Node.js) Source: https://github.com/chirimen-oh/node-web-gpio/blob/master/docs/classes/GPIOPort.html Retrieves a copy of the array of listeners registered for a specific event. This is useful for inspecting which functions are currently set to handle an event. It takes the event name as a string or symbol and returns an array of functions. ```javascript const util = require('util'); server.on('connection', (stream) => { console.log('someone connected!'); }); console.log(util.inspect(server.listeners('connection'))); // Prints: [ [Function] ] ``` -------------------------------- ### Get Event Listeners for Emitter or Target (Node.js) Source: https://github.com/chirimen-oh/node-web-gpio/blob/master/docs/classes/GPIOAccess.html Retrieves a copy of the array of listeners for a specified event name on either an EventEmitter or an EventTarget. This function is invaluable for debugging and inspecting event handling configurations. ```typescript import { getEventListeners, EventEmitter } from 'node:events'; // For EventEmitter const ee = new EventEmitter(); const listener = () => console.log('Events are fun'); ee.on('foo', listener); console.log(getEventListeners(ee, 'foo')); // [ [Function: listener] ] // For EventTarget const et = new EventTarget(); const listener2 = () => console.log('Events are fun'); et.addEventListener('foo', listener2); console.log(getEventListeners(et, 'foo')); // [ [Function: listener2] ] ``` -------------------------------- ### get: Retrieve a GPIOPort by Key Source: https://github.com/chirimen-oh/node-web-gpio/blob/master/docs/classes/GPIOPortMap.html Returns a specified GPIO port from the Map object using its key. If the value associated with the key is an object, a reference to that object is returned. Returns undefined if no element is associated with the key. ```typescript get(key: number): undefined | GPIOPort; ``` -------------------------------- ### Get Raw Event Listeners (Node.js EventEmitter) Source: https://github.com/chirimen-oh/node-web-gpio/blob/master/docs/classes/GPIOPort.html Returns a copy of the array of listeners for a specified event, including any wrappers. This can be useful for introspection or advanced listener management. The returned array contains functions, and each function may have a 'listener' property pointing to the original callback. ```javascript import { EventEmitter } from 'node:events'; const emitter = new EventEmitter(); emitter.once('log', () => console.log('log once')); // Returns a new Array with a function `onceWrapper` which has a property // `listener` which contains the original listener bound above const listeners = emitter.rawListeners('log'); const logFnWrapper = listeners[0]; // Logs "log once" to the console and does not unbind the `once` event logFnWrapper.listener(); // Logs "log once" to the console and removes the listener logFnWrapper(); emitter.on('log', () => console.log('log persistently')); // Will return a new Array with a single function bound by `.on()` above const newListeners = emitter.rawListeners('log'); // Logs "log persistently" twice newListeners[0](); emitter.emit('log'); ``` -------------------------------- ### Get and Set Max Event Listeners (Node.js) Source: https://github.com/chirimen-oh/node-web-gpio/blob/master/docs/classes/GPIOAccess.html Allows retrieving the current maximum number of listeners allowed for an EventEmitter or EventTarget and setting a new limit. Exceeding this limit typically results in a warning. This is useful for managing potential memory leaks and controlling listener counts. ```typescript import { getMaxListeners, setMaxListeners, EventEmitter } from 'node:events'; // For EventEmitter const ee = new EventEmitter(); console.log(getMaxListeners(ee)); // 10 setMaxListeners(11, ee); console.log(getMaxListeners(ee)); // 11 // For EventTarget const et = new EventTarget(); console.log(getMaxListeners(et)); // 10 setMaxListeners(11, et); console.log(getMaxListeners(et)); // 11 ``` -------------------------------- ### Initialize Theme and Display (JavaScript) Source: https://github.com/chirimen-oh/node-web-gpio/blob/master/docs/modules.html This snippet initializes the theme of the application based on local storage or OS default, hides the body content temporarily, and then shows the main application or removes the display property after a delay. It's used for setting up the initial UI state. ```javascript document.documentElement.dataset.theme = localStorage.getItem("tsd-theme") || "os"; document.body.style.display="none"; setTimeout(() => app?app.showPage():document.body.style.removeProperty("display"),500) ``` -------------------------------- ### GPIOAccess Constructor Source: https://github.com/chirimen-oh/node-web-gpio/blob/master/docs/classes/GPIOAccess.html Initializes a new instance of the GPIOAccess class, optionally accepting a map of GPIO ports. ```APIDOC ## new GPIOAccess(ports?) ### Description Creates an instance of GPIOAccess. ### Method Constructor ### Parameters #### Path Parameters - **ports** (GPIOPortMap) - Optional - ポート番号 ### Response #### Success Response (200) - **GPIOAccess** (GPIOAccess) - An instance of the GPIOAccess class. ### Request Example ```json { "ports": { "GPIO17": {"mode": "output", "value": 0} } } ``` ### Response Example ```json { "instance": "GPIOAccess" } ``` ``` -------------------------------- ### values: Get an Iterable of GPIOPort Values Source: https://github.com/chirimen-oh/node-web-gpio/blob/master/docs/classes/GPIOPortMap.html Returns an iterable object that contains the values for each element in the Map of GPIO ports, in insertion order. ```typescript values(): MapIterator; ``` -------------------------------- ### Initialize GPIOAccess Instance (TypeScript) Source: https://github.com/chirimen-oh/node-web-gpio/blob/master/docs/classes/GPIOAccess.html Demonstrates how to create a new instance of the GPIOAccess class. This constructor can optionally accept a GPIOPortMap to pre-configure ports. It inherits from EventEmitter and is defined in index.ts. ```typescript import { GPIOAccess, GPIOPortMap } from "./index"; // Example usage: const gpioAccess = new GPIOAccess(); // Example with optional ports: const portMap: GPIOPortMap = { // Define ports here if needed }; const gpioAccessWithPorts = new GPIOAccess(portMap); ``` -------------------------------- ### GPIOAccess Properties Source: https://github.com/chirimen-oh/node-web-gpio/blob/master/docs/classes/GPIOAccess.html Details the properties of the GPIOAccess class, including event handlers and static properties inherited from EventEmitter. ```APIDOC ## GPIOAccess Properties ### onchange #### Description GPIO change event handler. #### Type `undefined | GPIOChangeEventHandler` ### `Static` captureRejections #### Description Changes the default `captureRejections` option on all new `EventEmitter` objects. #### Type `boolean` #### Since `v13.4.0`, `v12.16.0` ### `Static` `Readonly` captureRejectionSymbol #### Description Symbol for custom rejection handlers on `EventEmitter`. #### Type `typeof captureRejectionSymbol` #### Value `Symbol.for('nodejs.rejection')` #### Since `v13.4.0`, `v12.16.0` ``` -------------------------------- ### GPIO Access - Ports Information Source: https://github.com/chirimen-oh/node-web-gpio/blob/master/docs/classes/GPIOAccess.html Retrieves the current information about all available GPIO ports. ```APIDOC ## GET /ports ### Description Retrieves the current information about all available GPIO ports. ### Method GET ### Endpoint /ports ### Parameters #### Query Parameters None #### Request Body None ### Response #### Success Response (200) - **ports** (GPIOPortMap) - An object containing the current state and configuration of each GPIO port. #### Response Example ```json { "ports": { "0": { "mode": "output", "value": 0, "activeHigh": true }, "1": { "mode": "input", "value": 1, "activeHigh": true } } } ``` ``` -------------------------------- ### Get Listener Count for an Event (Node.js) Source: https://github.com/chirimen-oh/node-web-gpio/blob/master/docs/classes/GPIOPort.html The listenerCount method returns the number of listeners registered for a specified event on an EventEmitter. It takes the emitter and the event name as arguments. ```javascript import { EventEmitter, listenerCount } from 'node:events'; const myEmitter = new EventEmitter(); myEmitter.on('event', () => {}); myEmitter.on('event', () => {}); console.log(listenerCount(myEmitter, 'event')); // Prints: 2 ``` -------------------------------- ### prependOnceListener API Source: https://github.com/chirimen-oh/node-web-gpio/blob/master/docs/classes/GPIOAccess.html Adds a one-time listener function to the beginning of the listeners array for a specified event. ```APIDOC ## prependOnceListener ### Description Adds a **one-time** `listener` function for the event named `eventName` to the _beginning_ of the listeners array. The next time `eventName` is triggered, this listener is removed, and then invoked. Returns a reference to the `EventEmitter`, so that calls can be chained. ### Method prependOnceListener ### Parameters #### Path Parameters - **eventName** (string | symbol) - Required - The name of the event. - **listener** ((...args: any[]) => void) - Required - The callback function ### Request Example ```javascript server.prependOnceListener('connection', (stream) => { console.log('Ah, we have our first user!'); }); ``` ### Response #### Success Response (200) - **this** (EventEmitter) - A reference to the EventEmitter instance. #### Response Example ```javascript // Returns a reference to the EventEmitter ``` ``` -------------------------------- ### Emit Events with Listeners (Node.js) Source: https://github.com/chirimen-oh/node-web-gpio/blob/master/docs/classes/GPIOAccess.html Demonstrates how to emit events and register multiple listeners in Node.js using the EventEmitter class. It shows synchronous invocation of listeners with arguments and returning a boolean indicating if listeners were present. ```javascript import { EventEmitter } from 'node:events'; const myEmitter = new EventEmitter(); // First listener myEmitter.on('event', function firstListener() { console.log('Helloooo! first listener'); }); // Second listener myEmitter.on('event', function secondListener(arg1, arg2) { console.log(`event with parameters ${arg1}, ${arg2} in second listener`); }); // Third listener myEmitter.on('event', function thirdListener(...args) { const parameters = args.join(', '); console.log(`event with parameters ${parameters} in third listener`); }); console.log(myEmitter.listeners('event')); myEmitter.emit('event', 1, 2, 3, 4, 5); // Expected Output: // [ // [Function: firstListener], // [Function: secondListener], // [Function: thirdListener] // ] // Helloooo! first listener // event with parameters 1, 2 in second listener // event with parameters 1, 2, 3, 4, 5 in third listener ``` -------------------------------- ### Add One-Time Listener to Beginning (prependOnceListener) - Node.js Source: https://github.com/chirimen-oh/node-web-gpio/blob/master/docs/classes/GPIOAccess.html Adds a one-time listener function to the beginning of the listeners array for a specified event. The listener will be invoked the next time the event is triggered and then automatically removed. It returns the EventEmitter instance for chaining. ```javascript server.prependOnceListener('connection', (stream) => { console.log('Ah, we have our first user!'); }); ``` -------------------------------- ### prependListener API Source: https://github.com/chirimen-oh/node-web-gpio/blob/master/docs/classes/GPIOAccess.html Adds a listener function to the beginning of the listeners array for a specified event. ```APIDOC ## prependListener ### Description Adds the `listener` function to the _beginning_ of the listeners array for the event named `eventName`. No checks are made to see if the `listener` has already been added. Multiple calls passing the same combination of `eventName` and `listener` will result in the `listener` being added, and called, multiple times. Returns a reference to the `EventEmitter`, so that calls can be chained. ### Method prependListener ### Parameters #### Path Parameters - **eventName** (string | symbol) - Required - The name of the event. - **listener** ((...args: any[]) => void) - Required - The callback function ### Request Example ```javascript server.prependListener('connection', (stream) => { console.log('someone connected!'); }); ``` ### Response #### Success Response (200) - **this** (EventEmitter) - A reference to the EventEmitter instance. #### Response Example ```javascript // Returns a reference to the EventEmitter ``` ``` -------------------------------- ### Add Listener to Beginning (prependListener) - Node.js Source: https://github.com/chirimen-oh/node-web-gpio/blob/master/docs/classes/GPIOAccess.html Adds a listener function to the beginning of the listeners array for a specified event. This method is useful for ensuring a listener is called before others. It returns the EventEmitter instance for chaining. ```javascript server.prependListener('connection', (stream) => { console.log('someone connected!'); }); ``` -------------------------------- ### Event Handling with `once` Source: https://github.com/chirimen-oh/node-web-gpio/blob/master/docs/classes/GPIOAccess.html The `once` method creates a Promise that resolves when an EventEmitter emits a specified event. It also handles potential errors during the event emission process and supports cancellation via AbortSignal. ```APIDOC ## `once` ### Description Creates a `Promise` that is fulfilled when the `EventEmitter` emits the given event or that is rejected if the `EventEmitter` emits `'error'` while waiting. The `Promise` will resolve with an array of all the arguments emitted to the given event. ### Method `once(emitter, eventName, options?)` ### Parameters #### Path Parameters - **emitter** (EventEmitter | EventTarget) - Required - The event emitter or event target. - **eventName** (string | symbol) - Required - The name of the event to listen for. - **options** (StaticEventEmitterOptions) - Optional - Configuration options, including `signal` for aborting. ### Request Example ```javascript import { once, EventEmitter } from 'node:events'; const ee = new EventEmitter(); process.nextTick(() => { ee.emit('myevent', 42); }); const [value] = await once(ee, 'myevent'); console.log(value); // Example with error handling try { await once(ee, 'myevent'); } catch (err) { console.error('error happened', err); } // Example with AbortSignal const ac = new AbortController(); async function foo(emitter, event, signal) { try { await once(emitter, event, { signal }); console.log('event emitted!'); } catch (error) { if (error.name === 'AbortError') { console.error('Waiting for the event was canceled!'); } else { console.error('There was an error', error.message); } } } foo(ee, 'foo', ac.signal); ac.abort(); // Abort waiting for the event ``` ### Response #### Success Response (Promise) Resolves with an array containing all arguments emitted with the event. #### Response Example ```json [42] ``` ``` -------------------------------- ### Get Event Listeners (Node.js Events) Source: https://github.com/chirimen-oh/node-web-gpio/blob/master/docs/classes/GPIOPort.html Retrieves a copy of the array of listeners for a given event name from an EventEmitter or EventTarget. This function is useful for debugging and diagnostic purposes, especially for EventTargets where direct listener access is not available. ```typescript import { getEventListeners, EventEmitter } from 'node:events'; // Example with EventEmitter const ee = new EventEmitter(); const listener = () => console.log('Events are fun'); ee.on('foo', listener); console.log(getEventListeners(ee, 'foo')); // [ [Function: listener] ] // Example with EventTarget const et = new EventTarget(); const listener2 = () => console.log('Events are fun'); et.addEventListener('foo', listener2); console.log(getEventListeners(et, 'foo')); // [ [Function: listener] ] ``` -------------------------------- ### Control GPIO Pin 26 using Node.js Source: https://github.com/chirimen-oh/node-web-gpio/blob/master/README.md This JavaScript code snippet demonstrates how to request GPIO access, export a specific GPIO pin (port 26) for output, and then toggle it on and off every second. It utilizes the 'node-web-gpio' library and Node.js timers for asynchronous operations. ```javascript import { requestGPIOAccess } from "node-web-gpio"; import { setTimeout as sleep } from "node:timers/promises"; const gpioAccess = await requestGPIOAccess(); const port = gpioAccess.ports.get(26); await port.export("out"); while (true) { await port.write(1); await sleep(1000); await port.write(0); await sleep(1000); } ``` -------------------------------- ### forEach Source: https://github.com/chirimen-oh/node-web-gpio/blob/master/docs/classes/GPIOPortMap.html Executes a provided function once for each key/value pair in the Map, in insertion order. ```APIDOC ## forEach ### Description Executes a provided function once per each key/value pair in the Map, in insertion order. ### Method GET (or similar, depending on underlying implementation if this is a method on an object) ### Endpoint Not applicable for method calls directly on an object instance. ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```javascript // Example usage: gpioMap.forEach((port, key) => { console.log(`Key: ${key}, Port Value: ${port.read()}`); }); ``` ### Response #### Success Response (void) This method does not return a value. #### Response Example None ``` -------------------------------- ### prependListener Source: https://github.com/chirimen-oh/node-web-gpio/blob/master/docs/classes/GPIOPort.html Adds a listener function to the beginning of the listeners array for a given event. Multiple calls with the same event and listener will add the listener multiple times. ```APIDOC ## prependListener ### Description Adds the `listener` function to the beginning of the listeners array for the event named `eventName`. No checks are made to see if the `listener` has already been added. Multiple calls passing the same combination of `eventName` and `listener` will result in the `listener` being added, and called, multiple times. Returns a reference to the `EventEmitter`, so that calls can be chained. ### Method `prependListener` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **eventName** (string | symbol) - Required - The name of the event. - **listener** (() => void) - Required - The callback function to add. ### Request Example ```javascript server.prependListener('connection', (stream) => { console.log('someone connected!');}); ``` ### Response #### Success Response (200) Returns a reference to the `EventEmitter`. #### Response Example ```json { "message": "Listener added successfully." } ``` ``` -------------------------------- ### Get and Set Max Listeners (Node.js Events) Source: https://github.com/chirimen-oh/node-web-gpio/blob/master/docs/classes/GPIOPort.html Allows retrieval and modification of the maximum number of event listeners allowed for an EventEmitter or EventTarget. Exceeding this limit typically triggers a warning. This provides a way to manage potential memory leaks or excessive event handling. ```typescript import { getMaxListeners, setMaxListeners, EventEmitter } from 'node:events'; // Example with EventEmitter const ee = new EventEmitter(); console.log(getMaxListeners(ee)); // 10 setMaxListeners(11, ee); console.log(getMaxListeners(ee)); // 11 // Example with EventTarget const et = new EventTarget(); console.log(getMaxListeners(et)); // 10 setMaxListeners(11, et); console.log(getMaxListeners(et)); // 11 ``` -------------------------------- ### rawListeners API Source: https://github.com/chirimen-oh/node-web-gpio/blob/master/docs/classes/GPIOAccess.html Returns a copy of the array of listeners for a specified event. ```APIDOC ## rawListeners ### Description Returns a copy of the array of listeners for the event named `eventName`, including any wrappers (such as those created by `.once()`). ### Method rawListeners ### Parameters #### Path Parameters - **eventName** (string | symbol) - Required - The name of the event. ### Request Example ```javascript import { EventEmitter } from 'node:events'; const emitter = new EventEmitter(); emitter.once('log', () => console.log('log once')); const listeners = emitter.rawListeners('log'); ``` ### Response #### Success Response (200) - **Function[]** - An array of listener functions. #### Response Example ```javascript // Returns a new Array with a function `onceWrapper` which has a property `listener` which contains the original listener bound above // const logFnWrapper = listeners[0]; // Logs "log once" to the console and does not unbind the `once` event // logFnWrapper.listener(); // Logs "log once" to the console and removes the listener // logFnWrapper(); ``` ``` -------------------------------- ### unexportAll Source: https://github.com/chirimen-oh/node-web-gpio/blob/master/docs/classes/GPIOAccess.html Unexports all currently exported GPIO ports, effectively releasing them. ```APIDOC ## unexportAll ### Description Unexports all exported GPIO ports. This action releases all the ports that were previously made available. ### Method N/A (This is a method of the GPIOAccess class, not a direct HTTP endpoint) ### Endpoint N/A ### Parameters #### Path Parameters N/A #### Query Parameters N/A #### Request Body N/A ### Request Example ```javascript // Assuming 'gpioAccess' is an instance of GPIOAccess gpioAccess.unexportAll(); ``` ### Response #### Success Response (Promise) This method returns a Promise that resolves when all ports have been successfully unexported. #### Response Example ```json // Upon successful execution, the promise resolves with no specific value. ``` ### Details - Returns: `Promise` - A promise that indicates the completion of the unexport operation. ``` -------------------------------- ### Initialize GPIOPort in TypeScript Source: https://github.com/chirimen-oh/node-web-gpio/blob/master/docs/classes/GPIOPort.html Demonstrates the constructor for the GPIOPort class, which initializes a new GPIOPort instance. It takes a port number as an argument and inherits from EventEmitter. ```typescript /** * Creates an instance of GPIOPort. * @param portNumber ポート番号 * @returns GPIOPort * @inheritdoc */ constructor(portNumber: number) { // ... implementation details ... } ``` -------------------------------- ### Event Handling - Once Source: https://github.com/chirimen-oh/node-web-gpio/blob/master/docs/classes/GPIOPort.html The `once` method creates a Promise that resolves when an EventEmitter emits a specified event. It can also be rejected if an 'error' event occurs. The promise resolves with an array of arguments emitted with the event. This method is designed to work with the web platform's EventTarget interface. ```APIDOC ## POST /events/once ### Description Creates a Promise that is fulfilled when the EventEmitter emits the given event or that is rejected if the EventEmitter emits 'error' while waiting. The Promise will resolve with an array of all the arguments emitted to the given event. ### Method POST ### Endpoint /events/once ### Parameters #### Request Body - **emitter** (EventEmitter | EventTarget) - Required - The event emitter or event target. - **eventName** (string | symbol) - Required - The name of the event to listen for. - **options** (object) - Optional - Options for the listener, such as an AbortSignal. - **signal** (AbortSignal) - Optional - An AbortSignal to cancel the waiting. ### Request Example ```json { "eventName": "data", "options": { "signal": "abortSignalId" } } ``` ### Response #### Success Response (200) - **value** (any[]) - An array containing the arguments emitted with the event. #### Response Example ```json { "value": [42] } ``` ``` -------------------------------- ### read Source: https://github.com/chirimen-oh/node-web-gpio/blob/master/docs/classes/GPIOPort.html Reads the input value from the GPIO. ```APIDOC ## read ### Description 入力値読み取り処理 ### Method `read` ### Endpoint `/read` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```javascript // Assuming 'gpio' is an initialized GPIO object gpio.read().then(value => { console.log('GPIO value:', value); }).catch(err => { console.error('Error reading GPIO:', err); }); ``` ### Response #### Success Response (200) - **GPIOValue** (Promise) - The result of the read operation. #### Response Example ```json { "value": 1 } ``` ``` -------------------------------- ### EventEmitter Static Properties Source: https://github.com/chirimen-oh/node-web-gpio/blob/master/docs/classes/GPIOPort.html Details about static properties inherited from EventEmitter, such as defaultMaxListeners and errorMonitor. ```APIDOC ## Static Properties (EventEmitter) ### defaultMaxListeners - **Type**: `number` - **Description**: Specifies the default maximum number of listeners for any single event. This can be overridden for individual EventEmitter instances. - **Default Value**: `10` ### errorMonitor - **Type**: `typeof errorMonitor` - **Description**: A symbol used to monitor 'error' events. Listeners added using this symbol are invoked before regular 'error' listeners. - **Availability**: Since v13.6.0, v12.17.0 ``` ```APIDOC ## Static Properties (EventEmitter) ### defaultMaxListeners - **Type**: `number` - **Description**: Specifies the default maximum number of listeners for any single event. This can be overridden for individual EventEmitter instances. - **Default Value**: `10` ### errorMonitor - **Type**: `typeof errorMonitor` - **Description**: A symbol used to monitor 'error' events. Listeners added using this symbol are invoked before regular 'error' listeners. - **Availability**: Since v13.6.0, v12.17.0 ``` -------------------------------- ### on Source: https://github.com/chirimen-oh/node-web-gpio/blob/master/docs/classes/GPIOPort.html Creates an AsyncIterator that iterates over events emitted by an EventEmitter. ```APIDOC ## on ### Description Returns an `AsyncIterator` that iterates `eventName` events. It will throw if the `EventEmitter` emits an 'error' event. It removes all listeners when exiting the loop. The `value` returned by each iteration is an array composed of the emitted event arguments. An `AbortSignal` can be used to cancel waiting on events. Use the `close` option to specify an array of event names that will end the iteration. ### Method STATIC ### Parameters #### Path Parameters * **emitter** (EventEmitter | EventTarget) - Required - The emitter to query * **eventName** (string | symbol) - Required - The event name * **options** (StaticEventEmitterIteratorOptions) - Optional - Configuration options for the iterator. ### Request Example ```javascript import { on, EventEmitter } from 'node:events'; import process from 'node:process'; const ee = new EventEmitter(); // Emit later on process.nextTick(() => { ee.emit('foo', 'bar'); ee.emit('foo', 42); }); for await (const event of on(ee, 'foo')) { // The execution of this inner block is synchronous and it // processes one event at a time (even with await). Do not use // if concurrent execution is required. console.log(event); // prints ['bar'] [42] } // Unreachable here ``` ### Response #### Success Response (200) * **AsyncIterableIterator** - An `AsyncIterator` that iterates `eventName` events emitted by the `emitter`. #### Response Example ```json [["bar"]] [ [42] ] ``` ``` -------------------------------- ### GPIOPort Class Source: https://github.com/chirimen-oh/node-web-gpio/blob/master/docs/classes/GPIOPort.html Documentation for the GPIOPort class, which represents a GPIO port and provides methods for controlling and reading its state. ```APIDOC ## Class GPIOPort GPIO ポート #### Hierarchy * EventEmitter * GPIOPort * Defined in [index.ts:139](https://github.com/chirimen-oh/node-web-gpio/blob/cd50093ae2cf0e031ddcb907d12da5122d1b7fa2/index.ts#L139) ### Constructors #### constructor * `new GPIOPort(portNumber: number)` * Creates an instance of GPIOPort. #### Parameters * **portNumber** (number) - Required - ポート番号 #### Returns * [GPIOPort](GPIOPort.html) Overrides EventEmitter.constructor * Defined in [index.ts:161](https://github.com/chirimen-oh/node-web-gpio/blob/cd50093ae2cf0e031ddcb907d12da5122d1b7fa2/index.ts#L161) ### Properties #### onchange * `onchange`: undefined | GPIOChangeEventHandler GPIO チェンジイベントハンドラ * Defined in [index.ts:155](https://github.com/chirimen-oh/node-web-gpio/blob/cd50093ae2cf0e031ddcb907d12da5122d1b7fa2/index.ts#L155) #### `Static` captureRejections * `captureRejections`: boolean Change the default `captureRejections` option on all new `EventEmitter` objects. #### Since v13.4.0, v12.16.0 Inherited from EventEmitter.captureRejections * Defined in node_modules/@types/node/events.d.ts:459 #### `Static` `Readonly` captureRejectionSymbol * `captureRejectionSymbol`: typeof [captureRejectionSymbol](GPIOAccess.html#captureRejectionSymbol) Value: `Symbol.for('nodejs.rejection')` See how to write a custom `rejection handler`. #### Since v13.4.0, v12.16.0 Inherited from EventEmitter.captureRejectionSymbol * Defined in node_modules/@types/node/events.d.ts:452 ### Accessors #### direction Gets or sets the direction of the GPIO pin. #### exported Gets a value indicating whether the GPIO pin is exported. #### pinName Gets the name of the GPIO pin. #### portName Gets the name of the GPIO port. #### portNumber Gets the number of the GPIO port. ### Methods #### `[captureRejectionSymbol]?` Handler for capture rejections. #### addAbortListener Adds an abort listener. #### addListener Adds a listener to an event. #### emit Emits an event. #### export Exports the GPIO pin. #### getEventListeners Returns all listeners for an event. #### getMaxListeners Gets the maximum number of listeners for an event. #### getEventListeners Returns all listeners for an event. #### listenerCount Returns the number of listeners for an event. #### listenerCount Returns the number of listeners for an event. #### off Removes a listener from an event. #### on Adds a listener to an event. #### on Adds a listener to an event. #### once Adds a one-time listener for an event. #### once Adds a one-time listener for an event. #### prependListener Adds a listener to the beginning of the listeners array for an event. #### prependOnceListener Adds a one-time listener to the beginning of the listeners array for an event. #### rawListeners Returns all listeners for an event. #### read Reads the value of the GPIO pin. #### removeAllListeners Removes all listeners for an event. #### removeListener Removes a listener from an event. #### setMaxListeners Sets the maximum number of listeners for an event. #### setMaxListeners Sets the maximum number of listeners for an event. #### unexport Unexports the GPIO pin. #### write Writes a value to the GPIO pin. ``` -------------------------------- ### rawListeners Source: https://github.com/chirimen-oh/node-web-gpio/blob/master/docs/classes/GPIOPort.html Returns a copy of the array of listeners for a specified event, including any wrappers. ```APIDOC ## rawListeners ### Description Returns a copy of the array of listeners for the event named `eventName`, including any wrappers (such as those created by `.once()`). ### Method `rawListeners` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **eventName** (string | symbol) - Required - The name of the event. ### Request Example ```javascript const listeners = emitter.rawListeners('log'); ``` ### Response #### Success Response (200) - **listeners** (Function[]) - A copy of the array of listeners for the specified event. #### Response Example ```json [ "function() { ... }" ] ``` ``` -------------------------------- ### prependOnceListener Source: https://github.com/chirimen-oh/node-web-gpio/blob/master/docs/classes/GPIOPort.html Adds a one-time listener function to the beginning of the listeners array for a given event. The listener is removed after it is invoked the first time. ```APIDOC ## prependOnceListener ### Description Adds a **one-time** `listener` function for the event named `eventName` to the _beginning_ of the listeners array. The next time `eventName` is triggered, this listener is removed, and then invoked. Returns a reference to the `EventEmitter`, so that calls can be chained. ### Method `prependOnceListener` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **eventName** (string | symbol) - Required - The name of the event. - **listener** (() => void) - Required - The callback function to add. ### Request Example ```javascript server.prependOnceListener('connection', (stream) => { console.log('Ah, we have our first user!');}); ``` ### Response #### Success Response (200) Returns a reference to the `EventEmitter`. #### Response Example ```json { "message": "One-time listener added successfully." } ``` ``` -------------------------------- ### Add Event Listener with 'on' - Node.js Source: https://github.com/chirimen-oh/node-web-gpio/blob/master/docs/classes/GPIOAccess.html The 'on' method adds a listener function to be executed when an event is emitted. Listeners are called in the order they were added. This method is inherited from the EventEmitter class. ```typescript server.on('connection', (stream) => { console.log('someone connected!'); }); ``` ```typescript import { EventEmitter } from 'node:events'; const myEE = new EventEmitter(); myEE.on('foo', () => console.log('a')); myEE.prependListener('foo', () => console.log('b')); myEE.emit('foo'); ``` -------------------------------- ### EventEmitter Methods Source: https://github.com/chirimen-oh/node-web-gpio/blob/master/docs/classes/GPIOPort.html Details about methods inherited from EventEmitter, specifically for handling captured rejections. ```APIDOC ## EventEmitter Methods ### [captureRejectionSymbol] - **Description**: Handles captured rejections for events. - **Type Parameters**: `K` - **Parameters**: - `error` (Error) - The error object. - `event` (string | symbol) - The event name or symbol. - `...args` (AnyRest) - Additional arguments passed to the event. - **Returns**: `void` - **Inherited from**: `EventEmitter` ``` -------------------------------- ### GPIOPortMap Constructor Source: https://github.com/chirimen-oh/node-web-gpio/blob/master/docs/classes/GPIOPortMap.html Demonstrates the constructor for the GPIOPortMap class, which is inherited from the Map constructor. It allows initialization with an optional iterable of key-value pairs, where keys are port numbers and values are GPIOPort objects. ```typescript new GPIOPortMap(entries?: null | readonly (readonly [number, GPIOPort])[]) new GPIOPortMap(iterable?: null | Iterable) ``` -------------------------------- ### addAbortListener API Source: https://github.com/chirimen-oh/node-web-gpio/blob/master/docs/classes/GPIOAccess.html Safely adds an abort listener to an AbortSignal, ensuring proper resource management and handling of potential propagation issues. ```APIDOC ## addAbortListener ### Description Safely listens once to the `abort` event on a provided `signal`. This method addresses potential resource leaks and simplifies listener management by returning a disposable. ### Method Static ### Endpoint N/A (Functionality is part of the library, not a REST endpoint) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```javascript import { addAbortListener } from 'node:events'; function example(signal) { let disposable; try { signal.addEventListener('abort', (e) => e.stopImmediatePropagation()); disposable = addAbortListener(signal, (e) => { // Do something when signal is aborted. }); } finally { disposable?.[Symbol.dispose](); } } ``` ### Response #### Success Response (Disposable) - **Disposable** (object) - A disposable object that allows for easy unsubscription of the `abort` listener. #### Response Example (The response is a disposable object, not a typical JSON response) #### Since v20.5.0 ``` -------------------------------- ### Count Listeners for an Event (Node.js) Source: https://github.com/chirimen-oh/node-web-gpio/blob/master/docs/classes/GPIOAccess.html Demonstrates how to count the number of listeners for a specific event. It also supports counting occurrences of a particular listener function if provided. ```javascript // Assuming 'myEE' is an EventEmitter instance: // myEE.on('data', handler); // console.log(myEE.listenerCount('data')); // Returns 1 // console.log(myEE.listenerCount('data', handler)); // Returns 1 ``` -------------------------------- ### GPIO Port Accessors Source: https://github.com/chirimen-oh/node-web-gpio/blob/master/docs/classes/GPIOPort.html Getters for accessing GPIO port properties like direction, export status, pin name, and port details. ```APIDOC ## GPIO Port Accessors ### direction - **Description**: Gets the current GPIO input/output direction. - **Returns**: `DirectionMode` - The current direction mode. ### exported - **Description**: Checks if the GPIO pin is exported. - **Returns**: `boolean` - `true` if exported, `false` otherwise. ### pinName - **Description**: Gets the name of the GPIO pin. - **Returns**: `string` - The current pin name. ### portName - **Description**: Gets the name of the GPIO port. - **Returns**: `string` - The current port name. ### portNumber - **Description**: Gets the number of the GPIO port. - **Returns**: `number` - The current port number. ``` -------------------------------- ### EventEmitter Static Properties (TypeScript) Source: https://github.com/chirimen-oh/node-web-gpio/blob/master/docs/classes/GPIOAccess.html Illustrates the static properties 'captureRejections' and 'captureRejectionSymbol' inherited by GPIOAccess from EventEmitter. These relate to handling promise rejections within event emitters. ```typescript // Accessing static properties (example, actual usage depends on context): // Check if captureRejections is enabled for new EventEmitters const captureRejectionsEnabled = GPIOAccess.captureRejections; console.log(`Default captureRejections: ${captureRejectionsEnabled}`); // Accessing the symbol for custom rejection handling const rejectionSymbol = GPIOAccess.captureRejectionSymbol; console.log(`Capture rejection symbol: ${rejectionSymbol}`); ``` -------------------------------- ### set Source: https://github.com/chirimen-oh/node-web-gpio/blob/master/docs/classes/GPIOPortMap.html Adds or updates an element with a specified key and value to the Map. ```APIDOC ## set ### Description Adds a new element with a specified key and value to the Map. If an element with the same key already exists, the element will be updated. ### Method POST or PUT (or similar, depending on underlying implementation if this is a method on an object) ### Endpoint Not applicable for method calls directly on an object instance. ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body * **key** (number) - Required - The key of the element to add or update. * **value** (GPIOPort) - Required - The GPIOPort object to associate with the key. ### Request Example ```javascript // Assuming 'newPort' is a GPIOPort object gpioMap.set(18, newPort); console.log('GPIO port set for key 18.'); ``` ### Response #### Success Response (this) Returns the Map instance itself, allowing for chaining. #### Response Example ```json { "value": "// Map object representation//" } ``` ```