### ItemMetadata Example Source: https://github.com/openhab/openhab-js/blob/main/_autodocs/types.md Demonstrates retrieving and replacing metadata for an Item. Shows how to get the 'unit' metadata and how to update the 'expire' metadata with a new value and configuration. ```javascript const metadata = item.getMetadata('unit'); // Returns: { value: '°C', configuration: {} } item.replaceMetadata('expire', '5m,command=ON', {}); ``` -------------------------------- ### PersistedItem Example Source: https://github.com/openhab/openhab-js/blob/main/_autodocs/types.md Example of retrieving historical Item data using PersistedItem. It shows how to get the maximum state of a 'Temperature' Item since yesterday and log the state and timestamp. ```javascript const yesterday = items.getItem('Temperature').lastStateChangeTimestamp?.minusDays(1); const maximum = items.getItem('Temperature').persistence.maximumSince(yesterday); console.log(`Max was ${maximum.state} at ${maximum.timestamp}`); ``` -------------------------------- ### ScriptExecution Actions: Timer Example Source: https://github.com/openhab/openhab-js/blob/main/_autodocs/actions.md Example demonstrating the creation, rescheduling, and cancellation of a timer using ScriptExecution actions. ```javascript const timer = actions.ScriptExecution.createTimer( time.toZDT().plusSeconds(10), () => { console.log('Timer executed!'); items.getItem('MyItem').sendCommand('ON'); } ); // Can reschedule or cancel timer.reschedule(time.toZDT().plusSeconds(20)); timer.cancel(); ``` -------------------------------- ### Install Dependencies Source: https://github.com/openhab/openhab-js/blob/main/CONTRIBUTING.md Run this command to install the necessary development dependencies for openHAB-JS. Ensure you are using the correct Node.js version as specified in .nvmrc. ```bash npm install ``` -------------------------------- ### ItemConfig Example Source: https://github.com/openhab/openhab-js/blob/main/_autodocs/types.md An example demonstrating how to define an ItemConfig object for a new light switch Item. This includes setting its type, name, label, category, group memberships, tags, and metadata. ```javascript const itemConfig = { type: 'Switch', name: 'BedroomLight', label: 'Bedroom Light', category: 'light', groups: ['AllLights', 'Bedroom'], tags: ['Light', 'Lightbulb'], metadata: { expire: '10m,command=OFF', stateDescription: { value: '', configuration: { pattern: '%d%%' } } } }; const newLight = items.addItem(itemConfig); ``` -------------------------------- ### Transformation Actions: Example Usage Source: https://github.com/openhab/openhab-js/blob/main/_autodocs/actions.md Examples of using the transform action for MAP, JSONPATH, and REGEX transformations. ```javascript // MAP transformation const translated = actions.Transformation.transform('MAP', 'en.map', 'OPEN'); // JSONPATH transformation const temp = actions.Transformation.transform('JSONPATH', '$.temperature', '{"temperature": 23.5}'); // REGEX transformation const extracted = actions.Transformation.transform('REGEX', '(\d+)', 'The answer is 42'); ``` -------------------------------- ### TimeSeries Example Source: https://github.com/openhab/openhab-js/blob/main/_autodocs/types.md Example of creating and populating a TimeSeries object to persist energy data. It uses the 'ADD' policy and adds two data points with timestamps and Quantity values before persisting to 'influxdb'. ```javascript const ts = new items.TimeSeries('ADD'); ts.add(time.toZDT('2024-01-01T12:00'), Quantity('100 kWh')); ts.add(time.toZDT('2024-01-02T12:00'), Quantity('110 kWh')); items.getItem('EnergyItem').persistence.persist(ts, 'influxdb'); ``` -------------------------------- ### ScriptExecution Actions: Named Timer Example Source: https://github.com/openhab/openhab-js/blob/main/_autodocs/actions.md Example of creating a named timer with parameters that will be passed to the executed function. ```javascript const timer = actions.ScriptExecution.createTimer( 'myTimer', time.toZDT().plusMinutes(5), (param1, param2) => { console.log(`Timer fired with params: ${param1}, ${param2}`); }, 'value1', 'value2' ); ``` -------------------------------- ### Ephemeris Actions: Example Usage Source: https://github.com/openhab/openhab-js/blob/main/_autodocs/actions.md Examples demonstrating how to use Ephemeris actions to check for weekends, bank holidays, and custom daysets. ```javascript // Check if today is weekend if (actions.Ephemeris.isWeekend()) { console.log('It is a weekend day'); } // Check if tomorrow is a bank holiday const holiday = actions.Ephemeris.getBankHolidayName(1); // offset 1 = tomorrow if (holiday) { console.log(`Tomorrow is ${holiday}`); } // Check if in custom dayset if (actions.Ephemeris.isInDayset('school_vacations')) { console.log('School is on vacation'); } ``` -------------------------------- ### Timer Object: Example Usage Source: https://github.com/openhab/openhab-js/blob/main/_autodocs/actions.md Demonstrates how to interact with a Timer object, checking its status, rescheduling, and cancelling it. ```javascript const timer = actions.ScriptExecution.createTimer( 'myTimer', time.toZDT().plusMinutes(5), () => { console.log('Done!'); } ); // Check status console.log(timer.isActive()); // true console.log(timer.getExecutionTime()); // ZonedDateTime // Reschedule timer.reschedule(time.toZDT().plusMinutes(10)); // Cancel const cancelled = timer.cancel(); console.log(timer.isCancelled()); // true ``` -------------------------------- ### Rule Builder Integration Example Source: https://github.com/openhab/openhab-js/blob/main/_autodocs/triggers.md Demonstrates how to use triggers within the openHAB rule builder to define rule logic. ```javascript const { rules } = require('openhab'); rules.when() .item('MyLight').changed() .then(event => { console.log('Light changed to:', event.newState); }) .build('My Light Rule', 'Rule triggered when light changes'); ``` -------------------------------- ### Import and Use German Locale for Date Formatting Source: https://github.com/openhab/openhab-js/blob/main/_autodocs/time.md Installs and applies a specific locale (German) for formatting dates and times. Requires installing the locale package. ```bash npm install @js-joda/locale_de-de ``` ```javascript const Locale = require('@js-joda/locale_de-de').Locale.GERMAN; const formatter = time.DateTimeFormatter.ofPattern('dd.MM.yyyy HH:mm').withLocale(Locale); const formatted = time.ZonedDateTime.now().format(formatter); ``` -------------------------------- ### GroupCommandTrigger Example Source: https://github.com/openhab/openhab-js/blob/main/_autodocs/triggers.md Creates a trigger that fires when any member of a group receives a command. ```javascript GroupCommandTrigger('AllLights'); ``` -------------------------------- ### Rule Trigger Example with EventObject Source: https://github.com/openhab/openhab-js/blob/main/_autodocs/types.md Demonstrates how to use the EventObject to access item state changes within a rule. ```javascript rules.when().item('MySwitch').changed().then(event => { console.log(`Item: ${event.itemName}`); console.log(`Old: ${event.oldState}, New: ${event.newState}`); }).build('My Rule'); ``` -------------------------------- ### ItemCommandTrigger Examples Source: https://github.com/openhab/openhab-js/blob/main/_autodocs/triggers.md Creates a trigger that fires when an Item receives a command. Can specify a particular command to match. ```javascript ItemCommandTrigger('MyLight'); ``` ```javascript ItemCommandTrigger('MyLight', 'ON'); ``` -------------------------------- ### Things Source: https://github.com/openhab/openhab-js/blob/main/README.md The Things namespace allows interacting with openHAB Things. You can retrieve individual things by their UID or get a list of all things. ```APIDOC ## Things ### Description The Things namespace allows interacting with openHAB Things. ### Methods - `getThing(uid)`: Returns a `Thing` object with the given UID, or `null` if not found. - `getThings()`: Returns an array of all `Thing` objects. ### Thing Object Properties - `bridgeUID`: The UID of the bridge the thing is connected to. - `label`: The human-readable label of the thing. - `location`: The location of the thing. - `status`: The current status of the thing. - `statusInfo`: Detailed status information. - `thingTypeUID`: The UID of the thing type. - `uid`: The unique identifier of the thing. - `isEnabled`: Boolean indicating if the thing is enabled. ### Thing Object Methods - `setLabel(label)`: Sets the label of the thing. - `setLocation(location)`: Sets the location of the thing. - `setProperty(name, value)`: Sets a specific property of the thing. - `setEnabled(enabled)`: Enables or disables the thing. ### Example ```javascript var thing = things.getThing('astro:moon:home'); console.log('Thing label: ' + thing.label); // Set Thing location thing.setLocation('living room'); // Disable Thing thing.setEnabled(false); ``` ``` -------------------------------- ### Get and Log Item State Source: https://github.com/openhab/openhab-js/blob/main/README.md Retrieves an item by its name and logs its current state to the console. Ensure the 'KitchenLight' item exists in your openHAB configuration. ```javascript var item = items.KitchenLight; console.log("Kitchen Light State", item.state); ``` -------------------------------- ### Get Item Source: https://github.com/openhab/openhab-js/blob/main/_autodocs/INDEX.md Retrieves a specific item by its name from the openHAB system. ```APIDOC ## Get Item ### Description Retrieves a specific item by its name from the openHAB system. ### Method `items.getItem(itemName)` ### Parameters #### Path Parameters - **itemName** (string) - Required - The name of the item to retrieve. ### Code ```javascript const item = items.getItem('ItemName'); ``` ``` -------------------------------- ### Create and Build a Basic Rule Source: https://github.com/openhab/openhab-js/blob/main/_autodocs/rules.md Creates a new rule that triggers when an item changes state and logs the new state. This is a fundamental example of rule creation and finalization. ```javascript rules.when() .item('MySwitch').changed() .then(event => { console.log('Switch changed to:', event.newState); }) .build('My Rule', 'My rule description'); ``` -------------------------------- ### ChannelEventTrigger Examples Source: https://github.com/openhab/openhab-js/blob/main/_autodocs/triggers.md Triggers that fire on channel events from Things. Supports specific events and wildcards for flexible matching. ```javascript ChannelEventTrigger('astro:sun:local:rise#event'); ``` ```javascript ChannelEventTrigger('astro:sun:local:rise#event', 'START'); ``` ```javascript ChannelEventTrigger('astro:*#event', 'START'); // All Astro Things ``` ```javascript ChannelEventTrigger('binding:device:*:channel', 'PRESSED'); ``` -------------------------------- ### RiemannSum Example Source: https://github.com/openhab/openhab-js/blob/main/_autodocs/types.md Demonstrates calculating the energy consumed from a 'PowerMeter' Item using the Riemann sum method. It specifies the time range, approximation type (TRAPEZOIDAL), and persistence service ('db'). ```javascript const power = items.getItem('PowerMeter'); const energy = power.persistence.riemannSumSince( yesterday, items.RiemannType.TRAPEZOIDAL, 'db' ); ``` -------------------------------- ### Get Current Time and Calculate Past Time Source: https://github.com/openhab/openhab-js/blob/main/README.md Demonstrates obtaining the current date and time and calculating a point in time 24 hours prior using the time namespace. It also shows how to access an item and get its average value since a specific time. ```javascript var now = time.ZonedDateTime.now(); var yesterday = time.ZonedDateTime.now().minusHours(24); var item = items.Kitchen; console.log("averageSince", item.persistence.averageSince(yesterday)); ``` -------------------------------- ### Getting an Item and Changing Its State Source: https://github.com/openhab/openhab-js/blob/main/_autodocs/README.md This common pattern shows how to retrieve an item by its name and then send a command to change its state, as well as logging its current state. ```APIDOC ## Getting an Item and Changing Its State ### Description Retrieves an openHAB Item and sends a command to change its state. It also demonstrates how to log the current state of the item. ### Usage ```javascript const { items } = require('openhab'); const light = items.getItem('BedroomLight'); light.sendCommand('ON'); console.log('Current state:', light.state); ``` ``` -------------------------------- ### Log Warnings for Optional Features Source: https://github.com/openhab/openhab-js/blob/main/_autodocs/errors.md Example of logging a warning when an optional feature (like notification sending) might not have succeeded due to missing configuration. ```javascript const ref = actions.notificationBuilder('Alert').send(); if (ref === null) { console.warn('Cloud Connector might not be installed'); } ``` -------------------------------- ### Get and Modify Thing Properties Source: https://github.com/openhab/openhab-js/blob/main/README.md Retrieves a Thing by its UID, logs its label, sets its location, and then disables the Thing. ```javascript var thing = things.getThing('astro:moon:home'); console.log('Thing label: ' + thing.label); // Set Thing location thing.setLocation('living room'); // Disable Thing thing.setEnabled(false); ``` -------------------------------- ### GroupStateUpdateTrigger Example Source: https://github.com/openhab/openhab-js/blob/main/_autodocs/triggers.md Creates a trigger that fires when any member of a group receives an update. ```javascript GroupStateUpdateTrigger('AllLights'); ``` -------------------------------- ### HTTP Request Source: https://github.com/openhab/openhab-js/blob/main/_autodocs/README.md Demonstrates how to make an HTTP GET request to an external API using the `HTTP.sendHttpGetRequest` action, including specifying a timeout. ```APIDOC ## HTTP Request ### Description Sends an HTTP GET request to a specified URL with a given timeout. The response from the server is returned. ### Usage ```javascript const { actions } = require('openhab'); const response = actions.HTTP.sendHttpGetRequest( 'https://api.example.com/data', 5000 // timeout ); if (response) { console.log(response); } ``` ``` -------------------------------- ### Sending Commands Within Rule Actions Source: https://github.com/openhab/openhab-js/blob/main/_autodocs/rules.md Send commands to items as part of a rule's execution logic. This example demonstrates sending 'ON' commands to multiple lights simultaneously. ```javascript rules.when() .item('Button').changed(undefined, 'ON') .then(() => { items.getItem('Light1').sendCommand('ON'); items.getItem('Light2').sendCommand('ON'); items.getItem('Light3').sendCommand('ON'); }) .build('Activate Lights'); ``` -------------------------------- ### ThingStatusChangeTrigger Examples Source: https://github.com/openhab/openhab-js/blob/main/_autodocs/triggers.md Triggers that fire when a Thing's status changes. Can be configured to trigger on any change or specific status transitions. ```javascript ThingStatusChangeTrigger('zwave:device:controller:node2', 'OFFLINE', 'ONLINE'); ``` ```javascript ThingStatusChangeTrigger('zwave:device:controller:node2'); ``` -------------------------------- ### GroupStateChangeTrigger Examples Source: https://github.com/openhab/openhab-js/blob/main/_autodocs/triggers.md Creates a trigger that fires when any member of a group changes state. Can specify old and new states to match. ```javascript GroupStateChangeTrigger('AllLights'); ``` ```javascript GroupStateChangeTrigger('AllLights', undefined, 'ON'); ``` -------------------------------- ### Channel Event Trigger Rule Source: https://github.com/openhab/openhab-js/blob/main/README.md Turns on the 'KitchenLight' at SUNSET by triggering on the 'START' event of the Astro binding's sun channel. ```javascript rules.when().channel('astro:sun:home:set#event').triggered('START').then().sendOn().toItem('KitchenLight').build('Sunset Rule', 'Turn on the kitchen light at SUNSET'); ``` -------------------------------- ### ItemStateChangeTrigger Examples Source: https://github.com/openhab/openhab-js/blob/main/_autodocs/triggers.md Creates a trigger that fires when an Item's state changes. Can specify old and new states to match. ```javascript ItemStateChangeTrigger('MyLight'); ``` ```javascript ItemStateChangeTrigger('MyLight', 'OFF', undefined); ``` ```javascript ItemStateChangeTrigger('MyLight', undefined, 'ON'); ``` ```javascript ItemStateChangeTrigger('MyLight', 'OFF', 'ON'); ``` ```javascript ItemStateChangeTrigger(items.getItem('MyLight'), 'OFF', 'ON'); ``` -------------------------------- ### Turn on Kitchen Light Source: https://github.com/openhab/openhab-js/blob/main/README.md Use this snippet to send an 'ON' command to a light item and log its state. Ensure the 'KitchenLight' item is defined in your openHAB configuration. ```javascript items.KitchenLight.sendCommand('ON'); console.log('Kitchen Light State', items.KitchenLight.state); ``` -------------------------------- ### Get Quantity Dimension Source: https://github.com/openhab/openhab-js/blob/main/_autodocs/quantity.md Retrieves the physical dimension of the Quantity. For example, '[L]' for length or '[Θ]' for temperature. ```javascript console.log(Quantity('5 m').dimension); // '[L]' console.log(Quantity('10 m²').dimension); // '[L]²' console.log(Quantity('50 km/h').dimension); // '[L]/[T]' ``` -------------------------------- ### isBetweenDateTimes(start, end) Source: https://github.com/openhab/openhab-js/blob/main/_autodocs/time.md Checks if this date and time is between start and end. ```APIDOC ## isBetweenDateTimes(start, end) ### Description Checks if this date and time is between start and end. ### Method ```javascript zdt.isBetweenDateTimes(start: ZonedDateTime | string, end: ZonedDateTime | string): boolean ``` ### Parameters * **start** (ZonedDateTime | string) - The start of the date-time range. * **end** (ZonedDateTime | string) - The end of the date-time range. ``` -------------------------------- ### Create a Toggleable Rule Source: https://github.com/openhab/openhab-js/blob/main/_autodocs/rules.md Creates a rule that can be toggled on or off, useful for managing automations that should be selectively active. This example demonstrates toggling a light's state. ```javascript rules.when(true) .item('Light').changed() .then(event => { items.getItem('AnotherLight').sendCommand(event.newState); }) .build('Copy Light State', 'Toggleable rule'); ``` -------------------------------- ### Dynamic Actions Source: https://github.com/openhab/openhab-js/blob/main/_autodocs/actions.md Allows access to additional actions provided by installed add-ons. These actions are available dynamically on the `actions` namespace by their class name. ```APIDOC ## Dynamic Actions ### Description Additional actions from installed add-ons are available dynamically on the `actions` namespace by their class name. ### Usage ```javascript // Access addon action by class name actions.ThingActions.doSomething(); actions.CustomAction.method(); ``` **Note:** Check add-on documentation for available methods. ``` -------------------------------- ### isBetweenDates(start, end) Source: https://github.com/openhab/openhab-js/blob/main/_autodocs/time.md Checks if this date is between start and end (ignoring time). ```APIDOC ## isBetweenDates(start, end) ### Description Checks if this date is between start and end (ignoring time). ### Method ```javascript zdt.isBetweenDates(start: ZonedDateTime | string, end: ZonedDateTime | string): boolean ``` ### Parameters * **start** (ZonedDateTime | string) - The start of the date range. * **end** (ZonedDateTime | string) - The end of the date range. ``` -------------------------------- ### Get Current Instant Source: https://github.com/openhab/openhab-js/blob/main/_autodocs/time.md Get the current moment in time as an Instant, represented by epoch milliseconds. ```javascript const now = time.Instant.now(); const epochMillis = now.toEpochMilli(); ``` -------------------------------- ### Get Item and Send Command Source: https://github.com/openhab/openhab-js/blob/main/_autodocs/README.md Retrieve an item by its name and send a command to change its state. Logs the current state to the console. ```javascript const { items } = require('openhab'); const light = items.getItem('BedroomLight'); light.sendCommand('ON'); console.log('Current state:', light.state); ``` -------------------------------- ### Get Current ZonedDateTime Source: https://github.com/openhab/openhab-js/blob/main/_autodocs/time.md Get the current date and time in the system's default timezone. ```javascript const now = time.ZonedDateTime.now(); console.log(now.toString()); ``` -------------------------------- ### Get all registered Things Source: https://github.com/openhab/openhab-js/blob/main/_autodocs/things.md Retrieves an array containing all Things currently managed by openHAB. Useful for iterating and displaying information about all devices. ```javascript const allThings = things.getThings(); console.log(`Total things: ${allThings.length}`); allThings.forEach(thing => { console.log(`${thing.label} (${thing.uid}) - Status: ${thing.status}`); }); ``` -------------------------------- ### Log Warning for Missing Cloud Connector Source: https://github.com/openhab/openhab-js/blob/main/_autodocs/errors.md This logs a warning if the Cloud Connector is not installed when attempting to send a notification. It returns null instead of throwing an error. ```javascript // This logs a warning if Cloud Connector not installed const ref = actions.notificationBuilder('Alert').send(); if (ref === null) { console.warn('Notification may not have been sent'); } ``` -------------------------------- ### isBetweenTimes(start, end) Source: https://github.com/openhab/openhab-js/blob/main/_autodocs/time.md Checks if this time is between start and end (ignoring date). Handles times spanning midnight. ```APIDOC ## isBetweenTimes(start, end) ### Description Checks if this time is between start and end (ignoring date). Handles times spanning midnight. ### Method ```javascript zdt.isBetweenTimes(start: ZonedDateTime | string, end: ZonedDateTime | string): boolean ``` ### Parameters * **start** (ZonedDateTime | string) - The start of the time range. * **end** (ZonedDateTime | string) - The end of the time range. ``` -------------------------------- ### Configure a Thing's Properties Source: https://github.com/openhab/openhab-js/blob/main/_autodocs/things.md Sets various properties for a Thing, including its label, location, and enabled state. Ensure the Thing is retrieved before configuration. ```javascript const thing = things.getThing('astro:sun:local'); thing.setLabel('Sun Position Calculator'); thing.setLocation('Local'); thing.setEnabled(true); ``` -------------------------------- ### Creating a Simple Rule Source: https://github.com/openhab/openhab-js/blob/main/_autodocs/README.md Illustrates the creation of a basic automation rule using the fluent builder API. The rule triggers when an item's state changes and then executes a defined action. ```APIDOC ## Creating a Simple Rule ### Description Defines a rule that is triggered by an item's state change. When the trigger condition is met, a specified action is executed. The rule is given a descriptive name. ### Usage ```javascript const { rules, items } = require('openhab'); rules.when() .item('MotionDetector').changed(undefined, 'MOTION') .then(() => { items.getItem('Light').sendCommand('ON'); }) .build('Motion Activated Light'); ``` ``` -------------------------------- ### Importing Modules Source: https://github.com/openhab/openhab-js/blob/main/_autodocs/README.md Demonstrates how to import specific modules or individual components from the openHAB-JS library. ```APIDOC ## Import Reference ### Standard Imports ```javascript // Import specific modules const { items, things, actions, triggers, rules, cache, time, Quantity } = require('openhab'); // Or import individually const items = require('openhab').items; const { Quantity } = require('openhab'); ``` ### Available Namespaces - `items` - Item operations - `things` - Thing operations - `actions` - System actions - `triggers` - Trigger factory functions - `rules` - Rule builder API - `cache` - Persistent caching (private/shared) - `time` - Date/time utilities (JS-Joda based) - `Quantity` - Units of measurement factory - `log` - Logging utilities - `utils` - Utility functions - `environment` - Runtime environment info - `osgi` - OSGI service access ``` -------------------------------- ### Send HTTP GET Request Source: https://github.com/openhab/openhab-js/blob/main/README.md Sends an HTTP GET request to a specified URL. Replace with the actual request URL. ```javascript // Example GET Request var response = actions.HTTP.sendHttpGetRequest(''); ``` -------------------------------- ### Load Third-Party Library Source: https://github.com/openhab/openhab-js/blob/main/README.md Use CommonJS require to load external JavaScript libraries. Ensure libraries are installed via npm in the 'automation/js' folder. ```javascript var myLibrary = require('my-library'); ``` -------------------------------- ### Send HTTP GET Request Source: https://github.com/openhab/openhab-js/blob/main/_autodocs/README.md Make an HTTP GET request to a specified URL with a given timeout. Logs the response if successful. ```javascript const { actions } = require('openhab'); const response = actions.HTTP.sendHttpGetRequest( 'https://api.example.com/data', 5000 // timeout ); if (response) { console.log(response); } ``` -------------------------------- ### Working with Quantities Source: https://github.com/openhab/openhab-js/blob/main/_autodocs/README.md Demonstrates how to create and manipulate Quantity objects, including converting units and comparing values. ```APIDOC ## Working with Quantities ### Description Shows how to create Quantity objects with units, convert them to different units, and perform comparisons. ### Usage ```javascript const { Quantity } = require('openhab'); const temperature = Quantity('20 °C'); const fahrenheit = temperature.toUnit('°F'); if (temperature.greaterThan('18 °C')) { console.log('Temperature is comfortable'); } ``` ``` -------------------------------- ### getItems() Source: https://github.com/openhab/openhab-js/blob/main/_autodocs/items.md Retrieves all openHAB Items currently in the system. ```APIDOC ## getItems() ### Description Retrieves all openHAB Items currently in the system. ### Method `getItems(): Item[]` ### Response #### Success Response - **Item[]** - An array of all `Item` objects in the system. ### Example ```javascript const allItems = items.getItems(); console.log(`Total items: ${allItems.length}`); allItems.forEach(item => { console.log(`${item.name}: ${item.state}`); }); ``` ``` -------------------------------- ### Perform Local Build and Versioning for NPM Publish Source: https://github.com/openhab/openhab-js/blob/main/DEPLOY.md This command performs a comprehensive local build, including linting, testing, webpack bundling, type definition updates, and JSDoc generation. Use `npm version` to bump the package version before publishing. ```bash npm run build # Perform a local build: Lint, run tests, bundle with webpack, update & test type definitions, build JSDoc npm version [major | minor | patch] --no-git-tag-version # Select one of the commands ``` -------------------------------- ### Send HTTP GET Request Source: https://github.com/openhab/openhab-js/blob/main/_autodocs/actions.md Performs an HTTP GET request to a specified URL. Supports optional timeout and custom headers for more advanced scenarios. ```javascript actions.HTTP.sendHttpGetRequest(url: string): string | null actions.HTTP.sendHttpGetRequest(url: string, timeout: number): string | null actions.HTTP.sendHttpGetRequest(url: string, headers: object, timeout: number): string | null ``` ```javascript // Simple GET request const response = actions.HTTP.sendHttpGetRequest('https://api.example.com/data'); if (response) { console.log(response); } ``` ```javascript // With custom headers const response = actions.HTTP.sendHttpGetRequest( 'https://api.example.com/secure', { 'Authorization': 'Bearer token123' }, 5000 ); ``` -------------------------------- ### Global State Management with Shared Cache Source: https://github.com/openhab/openhab-js/blob/main/_autodocs/cache.md Tracks state across multiple rules using the shared cache. This example shows how to check if the system is armed and then update the shared state to armed. ```javascript // Track state across multiple rules const isSystemArmed = cache.shared.get('systemArmed', () => false); if (!isSystemArmed) { console.log('System is not armed'); } // Update shared state cache.shared.put('systemArmed', true); ``` -------------------------------- ### Send HTTP GET Request with Timeout Source: https://github.com/openhab/openhab-js/blob/main/_autodocs/configuration.md Perform an HTTP GET request to a specified URL with an optional timeout in milliseconds. If no timeout is provided, the system default is used. ```javascript // No timeout (uses system default) actions.HTTP.sendHttpGetRequest('https://example.com'); // 5 second timeout actions.HTTP.sendHttpGetRequest('https://example.com', 5000); ``` -------------------------------- ### Send HTTP GET Request with Headers and Timeout Source: https://github.com/openhab/openhab-js/blob/main/_autodocs/configuration.md Execute an HTTP GET request including custom headers and a specified timeout. Useful for authenticated requests or setting specific content types. ```javascript // With custom headers and timeout actions.HTTP.sendHttpGetRequest( 'https://example.com', { 'Authorization': 'Bearer token', 'Accept': 'application/json' }, 5000 ); ``` -------------------------------- ### CoreUtil Actions Source: https://github.com/openhab/openhab-js/blob/main/_autodocs/actions.md Provides utility functions for color and unit conversions, such as HSB to RGB, HSB to XY, and XY to Kelvin conversions. ```APIDOC ## CoreUtil Actions ### Description Color and unit conversion utilities. ### Available Methods - **hsbToRgb(hsb: HSBType): int[]** Converts HSB color format to RGB. - **rgbToHsb(rgb: int[] | PercentType[]): HSBType** Converts RGB color format to HSB. - **hsbToXY(hsb: HSBType): double[]** Converts HSB color format to XY color space. - **xyToKelvin(xy: double[]): double** Converts XY color coordinates to color temperature in Kelvin. - **kelvinToXY(kelvin: double): double[]** Converts color temperature in Kelvin to XY color coordinates. ### Example Usage ```javascript // HSB to RGB conversion const rgb = actions.CoreUtil.hsbToRgb(items.getItem('ColorLight').rawState); // Color temperature conversion const kelvin = actions.CoreUtil.xyToKelvin([0.3, 0.4]); ``` ``` -------------------------------- ### Detailed String Item Configuration with Channels and Metadata Source: https://github.com/openhab/openhab-js/blob/main/README.md Adds or replaces a String item with advanced configurations including category, groups, tags, multiple channel links, and metadata like expire and stateDescription. ```javascript items.replaceItem({ type: 'String', name: 'Hallway_Light', label: 'Hallway Light', category: 'light', groups: ['Hallway', 'Light'], tags: ['Lightbulb'], channels: { 'binding:thing:device:hallway#light': {}, 'binding:thing:device:livingroom#light': { profile: 'system:follow' } }, metadata: { expire: '10m,command=1', stateDescription: { config: { pattern: '%d%%', options: '1=Red, 2=Green, 3=Blue' } } } }); ``` -------------------------------- ### Get Item Name Source: https://github.com/openhab/openhab-js/blob/main/_autodocs/items.md Access the unique `name` property of an Item. ```javascript console.log(item.name); ``` -------------------------------- ### getThings() Source: https://github.com/openhab/openhab-js/blob/main/_autodocs/things.md Retrieves all Things currently registered in openHAB. ```APIDOC ## getThings() ### Description Retrieves all Things currently registered in openHAB. ### Method GET (conceptual) ### Endpoint (Not applicable, this is an SDK method) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Returns - **Thing[]** - An array of all `Thing` objects. ### Example ```javascript const allThings = things.getThings(); console.log(`Total things: ${allThings.length}`); allThings.forEach(thing => { console.log(`${thing.label} (${thing.uid}) - Status: ${thing.status}`); }); ``` ``` -------------------------------- ### Get Item Metadata Source: https://github.com/openhab/openhab-js/blob/main/_autodocs/items.md Retrieves metadata for an item. Can fetch all metadata or metadata for a specific namespace. ```javascript // Get all metadata const allMeta = item.getMetadata(); ``` ```javascript // Get specific namespace const unitMeta = item.getMetadata('unit'); ``` -------------------------------- ### Get Item Tags Source: https://github.com/openhab/openhab-js/blob/main/_autodocs/items.md Access an array of tags assigned to the Item using the `tags` property. ```javascript console.log(item.tags); // ['Light', 'Lightbulb'] ``` -------------------------------- ### Smart Lighting Rule with Motion Detection and Timeout Source: https://github.com/openhab/openhab-js/blob/main/_autodocs/rules.md A complete example of a smart lighting rule that turns on a light when motion is detected at night and turns it off after a delay if no further motion is detected. It uses time-based conditions and setTimeout for delayed actions. ```javascript rules.when() .item('MotionDetector').changed(undefined, 'MOTION') .if(() => { // Only if evening/night return time.toZDT().isBetweenTimes('18:00', '08:00'); }) .then(event => { const light = items.getItem('CorridorLight'); light.sendCommand('ON'); // Turn off after 5 minutes setTimeout(() => { if (items.getItem('MotionDetector').state === 'NO_MOTION') { light.sendCommand('OFF'); } }, 5 * 60 * 1000); }) .build('Corridor Motion Light', 'Turns on light when motion detected at night'); ``` -------------------------------- ### Get Item Label Source: https://github.com/openhab/openhab-js/blob/main/_autodocs/items.md Retrieve the human-readable `label` for an Item. Returns `null` if the label is not set. ```javascript console.log(item.label); // 'Kitchen Light' ``` -------------------------------- ### Build Rule with Tags Source: https://github.com/openhab/openhab-js/blob/main/_autodocs/configuration.md Define a new automation rule with a name, description, and an array of tags for organization. Tags help categorize and group rules. ```javascript rules.when() .item('Switch').changed() .then(() => { /* ... */ }) .build( 'Rule Name', 'Rule Description', ['tag1', 'tag2', 'organizing-group'], // Tags array 'optional-rule-id' ); ``` -------------------------------- ### Retrieve All Items Source: https://github.com/openhab/openhab-js/blob/main/_autodocs/items.md Gets an array containing all Item objects currently present in the openHAB system. ```javascript const allItems = items.getItems(); console.log(`Total items: ${allItems.length}`); allItems.forEach(item => { console.log(`${item.name}: ${item.state}`); }); ``` -------------------------------- ### unit Source: https://github.com/openhab/openhab-js/blob/main/_autodocs/quantity.md Gets the unit name of the Quantity, like 'Metre' or 'Celsius', or null if the quantity is unit-less. ```APIDOC ## unit ### Description The unit name, e.g., `'Metre'`, `'Celsius'`, or `null` if unit-less. ### Properties - **unit** (string | null) ### Examples ```javascript const qty = Quantity('5 m'); console.log(qty.unit); // 'Metre' const unitless = Quantity('42'); console.log(unitless.unit); // null ``` ``` -------------------------------- ### Work with Quantities and Units Source: https://github.com/openhab/openhab-js/blob/main/_autodocs/README.md Create a quantity with a unit, convert it to another unit, and compare its value against a threshold. ```javascript const { Quantity } = require('openhab'); const temperature = Quantity('20 °C'); const fahrenheit = temperature.toUnit('°F'); if (temperature.greaterThan('18 °C')) { console.log('Temperature is comfortable'); } ``` -------------------------------- ### Handling Invalid Item Configuration Errors Source: https://github.com/openhab/openhab-js/blob/main/_autodocs/errors.md Demonstrates catching errors related to invalid item configurations, such as missing required fields or attempting to add an item that already exists. ```javascript try { // Missing required fields items.addItem({ type: 'Switch' }); // name is required } catch (e) { console.error('Invalid config:', e.message); } try { // Duplicate item name items.addItem({ type: 'Switch', name: 'ExistingItem' }); } catch (e) { console.error('Cannot add Item:', e.message); } ``` -------------------------------- ### Get Quantity Numeric Value (Float) Source: https://github.com/openhab/openhab-js/blob/main/_autodocs/quantity.md Retrieves the numeric value of the Quantity as a floating-point number. ```javascript const qty = Quantity('5.75 m'); console.log(qty.float); // 5.75 const int = Quantity('10'); console.log(int.float); // 10 ``` -------------------------------- ### Get Milliseconds Until a Future ZonedDateTime Source: https://github.com/openhab/openhab-js/blob/main/README.md Calculates the number of milliseconds from the current moment until a specified future ZonedDateTime. ```javascript var timestamp = time.ZonedDateTime.now().plusMinutes(5); console.log(timestamp.getMillisFromNow()); ``` -------------------------------- ### Get Quantity Numeric Value (Integer) Source: https://github.com/openhab/openhab-js/blob/main/_autodocs/quantity.md Retrieves the numeric value of the Quantity rounded to the nearest integer. ```javascript const qty = Quantity('5.75 m'); console.log(qty.int); // 6 const exact = Quantity('10 m'); console.log(exact.int); // 10 ``` -------------------------------- ### Create and Persist TimeSeries Source: https://github.com/openhab/openhab-js/blob/main/README.md Demonstrates creating a TimeSeries with the ADD policy, adding states with timestamps, and persisting it to the InfluxDB service for a specific item. ```javascript var timeSeries = new items.TimeSeries('ADD'); // Create a new TimeSeries with policy ADD timeSeries.add(time.toZDT('2024-01-01T14:53'), Quantity('5 m')).add(time.toZDT().minusMinutes(2), Quantity('0 m')).add(time.toZDT().plusMinutes(5), Quantity('5 m')); console.log(ts); // Let's have a look at the TimeSeries items.getItem('MyDistanceItem').persistence.persist(timeSeries, 'influxdb'); // Persist the TimeSeries for the Item 'MyDistanceItem' using the InfluxDB persistence service ``` -------------------------------- ### Import Individual Modules Source: https://github.com/openhab/openhab-js/blob/main/_autodocs/README.md Import individual modules from the openHAB library when only a few are needed. ```javascript // Or import individually const items = require('openhab').items; const { Quantity } = require('openhab'); ``` -------------------------------- ### Timer Management with Private Cache Source: https://github.com/openhab/openhab-js/blob/main/_autodocs/cache.md Demonstrates how to create, store, and later cancel a timer using the private cache. This is useful for managing scheduled actions within a script's lifecycle. ```javascript // Create and store a timer const timer = actions.ScriptExecution.createTimer('myTimer', time.toZDT().plusMinutes(5), () => { console.log('Action triggered!'); }); cache.private.put('myTimer', timer); // Later, cancel the timer const storedTimer = cache.private.remove('myTimer'); if (storedTimer) { storedTimer.cancel(); } ``` -------------------------------- ### Get Item Group Names Source: https://github.com/openhab/openhab-js/blob/main/_autodocs/items.md Retrieve an array of group names that the Item belongs to using the `groupNames` property. ```javascript console.log(item.groupNames); // ['AllLights', 'FirstFloor'] ``` -------------------------------- ### Get Item State as String Source: https://github.com/openhab/openhab-js/blob/main/_autodocs/items.md Access the current `state` of an Item as a string. Returns `null` if the state is unavailable. ```javascript console.log(item.state); // 'ON', '42', etc. ``` -------------------------------- ### Import Core openHAB JS Modules Source: https://github.com/openhab/openhab-js/blob/main/_autodocs/INDEX.md Import essential modules for interacting with openHAB. This is typically the first step in any openHAB JS script. ```javascript const { items, things, actions, triggers, rules, cache, time, Quantity } = require('openhab'); ``` -------------------------------- ### Scheduling a Timer Source: https://github.com/openhab/openhab-js/blob/main/_autodocs/README.md Explains how to schedule a script to run after a specified delay using the `ScriptExecution.createTimer` action. ```APIDOC ## Scheduling a Timer ### Description Schedules a function to be executed at a specific time in the future. This is useful for delayed actions or timeouts. ### Usage ```javascript const { actions, time } = require('openhab'); const timer = actions.ScriptExecution.createTimer( time.toZDT().plusMinutes(5), () => { console.log('5 minutes have passed'); } ); ``` ``` -------------------------------- ### Compare Temperature Quantities Source: https://github.com/openhab/openhab-js/blob/main/_autodocs/quantity.md Compares the current temperature with a threshold and sends commands to 'AC' or 'Heater' items. Uses greaterThan and lessThanOrEqual methods. ```javascript const threshold = Quantity('20 °C'); const currentTemp = items.getItem('Temperature').quantityState; if (currentTemp.greaterThan(threshold)) { console.log('Temperature is above threshold'); items.getItem('AC').sendCommand('ON'); } else if (currentTemp.lessThanOrEqual('18 °C')) { console.log('Temperature is below 18°C'); items.getItem('Heater').sendCommand('ON'); } ``` -------------------------------- ### CoreUtil Color and Unit Conversions Source: https://github.com/openhab/openhab-js/blob/main/_autodocs/actions.md Provides utility functions for converting between color formats (HSB, RGB, XY) and color temperatures (Kelvin). ```javascript actions.CoreUtil.hsbToRgb(hsb: HSBType): int[] ``` ```javascript actions.CoreUtil.rgbToHsb(rgb: int[] | PercentType[]): HSBType ``` ```javascript actions.CoreUtil.hsbToXY(hsb: HSBType): double[] ``` ```javascript actions.CoreUtil.xyToKelvin(xy: double[]): double ``` ```javascript actions.CoreUtil.kelvinToXY(kelvin: double): double[] ``` ```javascript // HSB to RGB conversion const rgb = actions.CoreUtil.hsbToRgb(items.getItem('ColorLight').rawState); ``` ```javascript // Color temperature conversion const kelvin = actions.CoreUtil.xyToKelvin([0.3, 0.4]); ``` -------------------------------- ### Get Group Item Descendants Source: https://github.com/openhab/openhab-js/blob/main/_autodocs/items.md For Group Items, retrieve a list of all descendant Items (recursively) using the `descendents` property. ```javascript const group = items.getItem('Lights'); group.descendents.forEach(item => { console.log(item.name); }); ``` -------------------------------- ### Accessing Items Safely Source: https://github.com/openhab/openhab-js/blob/main/_autodocs/types.md Shows how to retrieve an Item, avoiding an exception by using the nullIfMissing flag. ```javascript try { const item = items.getItem('NonExistent'); } catch (e) { // ItemNotFoundException } // Or avoid exception: const item = items.getItem('NonExistent', true); // returns null ``` -------------------------------- ### Get Group Item Members Source: https://github.com/openhab/openhab-js/blob/main/_autodocs/items.md For Group Items, retrieve a list of their direct child Items using the `members` property. ```javascript const group = items.getItem('Lights'); group.members.forEach(member => { console.log(member.name); }); ``` -------------------------------- ### Handling Incomplete Rule Configuration Errors Source: https://github.com/openhab/openhab-js/blob/main/_autodocs/errors.md Shows how to catch errors when building a rule with incomplete trigger or operation configurations using the rule builder. ```javascript try { // Missing trigger configuration rules.when().then(() => {}).build('Incomplete Rule'); } catch (e) { console.error('Rule configuration error:', e.message); } ``` -------------------------------- ### Get Item Type Source: https://github.com/openhab/openhab-js/blob/main/_autodocs/items.md Retrieve the type of an Item (e.g., 'Switch', 'String'). Use `getItem` to fetch the item by its name. ```javascript const item = items.getItem('MyItem'); console.log(item.type); // 'Switch' ``` -------------------------------- ### Get a specific Thing by UID Source: https://github.com/openhab/openhab-js/blob/main/_autodocs/things.md Retrieves a Thing object using its unique identifier. Returns null if the Thing is not found. ```javascript const thing = things.getThing('astro:moon:home'); if (thing) { console.log('Thing found:', thing.label); } const notFound = things.getThing('nonexistent:uid'); // notFound is null ``` -------------------------------- ### Configure Item Trigger for Any Change Source: https://github.com/openhab/openhab-js/blob/main/_autodocs/rules.md Sets up an item trigger to activate on any change in the item's state. This is the most basic configuration for item-based triggers. ```javascript .item('MyItem').changed() ``` -------------------------------- ### GenericCronTrigger Examples Source: https://github.com/openhab/openhab-js/blob/main/_autodocs/triggers.md Triggers that fire based on a cron schedule. Supports standard cron expressions for various scheduling needs. ```javascript GenericCronTrigger('0 * * * *'); // Every hour at minute 0 ``` ```javascript GenericCronTrigger('0 9 * * *'); // Daily at 9:00 AM ``` ```javascript GenericCronTrigger('0 8 * * 1'); // Every Monday at 8:00 AM ``` ```javascript GenericCronTrigger('*/5 * * * *'); // Every 5 minutes ``` -------------------------------- ### Execute Command Line Source: https://github.com/openhab/openhab-js/blob/main/README.md Executes a command line. Supports specifying a timeout and capturing the response. ```javascript // Execute command line. actions.Exec.executeCommandLine('echo', 'Hello World!'); ``` ```javascript // Execute command line with timeout. actions.Exec.executeCommandLine(time.Duration.ofSeconds(20), 'echo', 'Hello World!'); ``` ```javascript // Get response from command line with timeout. var response = actions.Exec.executeCommandLine(time.Duration.ofSeconds(20), 'echo', 'Hello World!'); ``` -------------------------------- ### Add a New Item Source: https://github.com/openhab/openhab-js/blob/main/_autodocs/items.md Creates and registers a new openHAB Item with specified configuration. Optionally persists the item in file-based scripts. ```javascript const newLight = items.addItem({ type: 'Switch', name: 'LivingRoomLight', label: 'Living Room Light', category: 'light', tags: ['Lightbulb'], groups: ['Lights'] }); console.log('Created item:', newLight.name); ``` -------------------------------- ### items.getItems Source: https://github.com/openhab/openhab-js/blob/main/README.md Retrieves all Items in openHAB. ```APIDOC ## items.getItems() ### Description Retrieves a list of all Items currently configured in openHAB. ### Method items.getItems ### Response #### Success Response (Array[Item]) - Returns an array of `Item` objects. ``` -------------------------------- ### Sending ON/OFF Commands with OnOffType Source: https://github.com/openhab/openhab-js/blob/main/_autodocs/types.md Shows how to send ON and OFF commands to an item using both string and Java enum forms. ```javascript const { ON, OFF } = require('@runtime'); item.sendCommand('ON'); // String form item.sendCommand(ON); // Java enum form ``` -------------------------------- ### Get Item State as Number Source: https://github.com/openhab/openhab-js/blob/main/_autodocs/items.md Retrieve the current state of an Item as a number using `numericState`. Returns `null` if the state is not numeric. ```javascript const temp = items.getItem('TemperatureSensor'); console.log(temp.numericState); // 23.5 ``` -------------------------------- ### Build Rule with Name, Description, Tags, and ID Source: https://github.com/openhab/openhab-js/blob/main/_autodocs/rules.md Finalizes the rule creation process by registering it with a unique name, an optional description, tags for categorization, and a custom ID. This provides comprehensive metadata for the rule. ```javascript rules.when() .item('LivingRoomLight').changed() .then(event => { console.log('Light changed:', event.newState); }) .build( 'LivingRoom Light Control', 'Controls the living room light', ['lighting', 'livingroom'], 'rule-living-room-light' ); ``` -------------------------------- ### Get Milliseconds Until a Specific Time Source: https://github.com/openhab/openhab-js/blob/main/_autodocs/time.md Calculates the number of milliseconds from the current time until a specified ZonedDateTime. Useful for scheduling future events. ```javascript const alarm = time.toZDT('06:30'); const msUntilAlarm = alarm.getMillisFromNow(); if (msUntilAlarm > 0) { console.log(`Alarm in ${Math.round(msUntilAlarm / 1000)} seconds`); } ``` -------------------------------- ### ScriptExecution Actions: Create Timer (Basic) Source: https://github.com/openhab/openhab-js/blob/main/_autodocs/actions.md Creates a timer that executes a function at a specific ZonedDateTime. The timer can be rescheduled or cancelled. ```javascript createTimer( zdt: time.ZonedDateTime, function: Function, ...params: any[] ): Timer ```