### Initialize and Use Prediction Service (JavaScript) Source: https://context7.com/asterics/asterics-grid/llms.txt Demonstrates how to initialize, use, and learn from the prediction service. It covers getting predictions, learning from user input, applying predictions, and retrieving available dictionary keys. Dependencies include the predictionService module. ```javascript import { predictionService } from './src/js/service/predictionService'; // Initialize the prediction service await predictionService.init(); // Get predictions based on input predictionService.predict('hel', 'myDictionary'); // Fills prediction elements with: "hello", "help", "helicopter", etc. // Learn from user input predictionService.learnFromInput('Hello, how are you today?', 'myDictionary'); // Apply a prediction (for collect element integration) const result = predictionService.applyPrediction('hel', 'hello', 'myDictionary'); console.log('Applied prediction:', result); // Output: hello // Get available dictionary keys const dictKeys = predictionService.getDictionaryKeys(); console.log('Dictionaries:', dictKeys); // Output: ['default_en', 'myDictionary', 'medical_terms'] // Use current content language dictionary predictionService.predict('wor', GridActionPredict.USE_DICTIONARY_CURRENT_LANG); ``` -------------------------------- ### Configure Input Methods for AsTeRICS Grid (JavaScript) Source: https://context7.com/asterics/asterics-grid/llms.txt Provides an example structure for input configuration in AsTeRICS Grid, showcasing settings for mouse/touch, scanning, direction input, Huffman coding, and sequential input. It also defines input event types. ```javascript // Example InputConfig structure from MetaData const inputConfig = { // Mouse/Touch settings mouseclickEnabled: true, hoverEnabled: true, hoverTimeMs: 1000, hoverHideCursor: false, // Scanning settings scanEnabled: false, scanVertical: true, scanBinary: false, scanAutostart: true, scanTimeoutMs: 1000, scanTimeoutFirstElementFactor: 1.5, // Direction input settings dirEnabled: false, dirWrapAround: true, dirResetToStart: true, // Huffman input settings huffEnabled: false, huffShowNumbers: true, huffShowColors: true, huffColors: ['#E69F00', '#56B4E9', '#009E73', '#F0E442'], // Sequential input settings seqEnabled: false, seqAutostart: false, seqTimeoutMs: 2000, // Global settings globalMinPauseCollectSpeak: 500 }; // Input event types const inputEventTypes = { KEYPRESS: 'InputEventKey', // Keyboard, mouse, touch MICROPHONE: 'InputEventAudio', // Sound/voice activation ASTERICS: 'InputEventARE' // AsTeRICS Framework events }; ``` -------------------------------- ### Load and Process AsTeRICS Grid Data (JavaScript) Source: https://github.com/asterics/asterics-grid/blob/master/app/simple/index.html This JavaScript code fetches grid data from a specified URL, parses the JSON response, and dynamically generates UI elements like titles and buttons. It handles user interactions by sending data to input ports and includes keyboard shortcuts for button activation. Dependencies include the `getData`, `parseJson`, `createTitle`, `createButton`, `sendDataToInputPort`, `appendElement`, `removeElement`, `log` functions, and potentially `i18n` for internationalization. ```javascript getData('webapps/simple/examples/default.grd', gotDataCallback); function gotDataCallback(data) { data = parseJson(data); data = data.grids; removeElement('loading'); for (var i = 0; i < data.length; i++) { var grid = data[i]; var gridLabel = grid.label; var elements = grid.gridElements; var first = true; for (var j = 0; j < elements.length; j++) { var element = elements[j]; var actions = element.actions; if (actions && actions.length > 0) { for (var k = 0; k < actions.length; k++) { var action = actions[k]; if (action.modelName == "GridActionARE") { if (first) { first = false; var titleElem = createTitle(gridLabel, 'row col-xs-12'); appendElement(titleElem); } var button = createButton(element.label, "", "sendDataToInputPort('" + action.componentId + "', '" + action.dataPortId + "', '" + action.dataPortSendData + "')"); appendElement(button); } } } } } } function appendElement(element) { document.getElementById("controls").appendChild(element); } function log(string) { if (!MODE_COMPATIBILITY) { console.log(string); } } if (!MODE_COMPATIBILITY) { i18n.translatePage(); window.onkeydown = function(e) { var key = e.keyCode ? e.keyCode : e.which; if (e.ctrlKey && e.altKey && key >= 49 && key <= 57) { var num = key - 48; var button = document.getElementsByClassName('action-button')[num - 1]; if (button) { button.click(); } } } } ``` -------------------------------- ### Manage Grids and Metadata with Data Service (JavaScript) Source: https://context7.com/asterics/asterics-grid/llms.txt Provides methods for managing grids, metadata, and dictionaries. Supports local storage and optional cloud synchronization. Functions include getting, saving, and deleting grids, managing user settings (metadata), and importing/exporting configurations. ```javascript import { dataService } from './src/js/service/data/dataService'; // Get a single grid by ID const grid = await dataService.getGrid('grid-data-abc123'); console.log('Grid label:', grid.label.en); // Get all grids (short version for performance) const allGrids = await dataService.getGrids(false, false); console.log('Total grids:', allGrids.length); // Save a new or updated grid await dataService.saveGrid(myGrid); // Delete a grid await dataService.deleteGrid('grid-data-old123'); // Get and save metadata (user settings) const metadata = await dataService.getMetadata(); metadata.locked = true; metadata.fullscreen = false; await dataService.saveMetadata(metadata); // Export configuration to file const gridIds = allGrids.map(g => g.id); await dataService.downloadToFile(gridIds, { exportGlobalGrid: true, exportDictionaries: true, exportUserSettings: true, filename: 'my-backup', obzFormat: false // Set true for OpenBoard format }); // Import from backup file const importData = await dataService.convertFileToImportData(file); await dataService.importBackupData(importData, { progressFn: (percent, message) => console.log(`${percent}%: ${message}`) }); ``` -------------------------------- ### Bundle Javascript Modules with Webpack Source: https://github.com/asterics/asterics-grid/wiki/Javascript-Development-Concept Shows the command to initiate the webpack bundling process. This command processes ES6 modules from the 'src' folder and outputs ES5 compatible bundles to 'build' and 'build_legacy' directories. ```bash npm start build ``` -------------------------------- ### Control openHAB Devices with JavaScript Source: https://context7.com/asterics/asterics-grid/llms.txt Integrates with the openHAB smart home platform to control environmental devices. It requires the openHAB REST API URL and allows fetching items, sending commands (ON/OFF, custom values, colors), and managing device states. Ensure the openHAB instance is accessible and the item names are correct. ```javascript import { openHABService } from './src/js/service/openHABService'; // Get REST URL for openHAB instance const restUrl = openHABService.getRestURL('http://192.168.1.50:8080'); console.log('openHAB REST URL:', restUrl); // Output: http://192.168.1.50:8080/rest/items/ // Fetch available items from openHAB const items = await openHABService.fetchItems(restUrl); items.forEach(item => { console.log(`${item.name} (${item.type}): ${item.state}`); }); // Output: Living_Room_Light (Switch): ON // Output: Bedroom_Dimmer (Dimmer): 50 // Send command to openHAB item await openHABService.sendAction({ openHABUrl: restUrl, itemName: 'Living_Room_Light', actionType: 'ON' }); // Control dimmer with custom value await openHABService.sendAction({ openHABUrl: restUrl, itemName: 'Bedroom_Dimmer', actionType: 'CUSTOM_VALUE', actionValue: '75' }); // Set color light (HSV format) await openHABService.sendAction({ openHABUrl: restUrl, itemName: 'Color_Light', actionType: 'CUSTOM_COLOR', actionValue: '#FF5733' // Converted to HSV internally }); ``` -------------------------------- ### Create and Configure GridData Model in JavaScript Source: https://context7.com/asterics/asterics-grid/llms.txt Demonstrates how to create a new communication grid using the GridData model. It shows setting grid properties like dimensions and background color, adding grid elements, and checking grid status. This is useful for initializing and managing the overall structure of a communication board. ```javascript import { GridData } from './src/js/model/GridData'; import { GridElement } from './src/js/model/GridElement'; // Create a new grid with custom dimensions const myGrid = new GridData({ label: { en: 'My Communication Board', de: 'Mein Kommunikationsbrett' }, rowCount: 4, minColumnCount: 6, backgroundColor: '#f0f0f0', showGlobalGrid: true }); // Add a grid element with speak action const element = myGrid.getNewGridElement({ label: { en: 'Hello', de: 'Hallo' }, width: 1, height: 1, backgroundColor: '#4CAF50' }); myGrid.gridElements.push(element); // Check if grid is full console.log('Grid is full:', myGrid.isFull()); // Output: Grid is full: false // Get grid dimensions console.log('Grid width:', myGrid.getWidth()); console.log('Grid height:', myGrid.getHeight()); ``` -------------------------------- ### Configure TV Artlab Actions with IR Commands Source: https://github.com/asterics/asterics-grid/blob/master/docs/ircodes_devices.txt This snippet defines actions for the 'TV Artlab' device, utilizing the HW_IRTRANS_USB type. Each action (on/off, input, volume control, mute, channel change) is associated with a specific hexadecimal IR command string. These commands are used to control the TV via an IR transmitter. ```json { "title":"onoff", "translatedTitle":"onoff", "faIcon":"wifi", "type":"HW_IRTRANS_USB", "disabled":false, "active":false, "visible":true, "code":"IRTRANS-USB@IRTRANS:sndhex H5E010000000032260300E5004200AD2504000000000000000001B0002F002B002F00000000000000000383885330313030303030303030303030313030303030303030303130303030303030303130313131313030313031313131303130", "class":"action-button" }, { "title":"input", "translatedTitle":"input", "faIcon":"wifi", "type":"HW_IRTRANS_USB", "disabled":false, "active":false, "visible":true, "code":"IRTRANS-USB@IRTRANS:sndhex H5E010000000032260300E3004200AB2502000000000000000001B1002F002D003000000000000000000382835330313030303030303030303030313030303030303030303130303030303030303130313030303030313031303030303130", "class":"action-button" }, { "title":"vol up", "translatedTitle":"vol up", "faIcon":"wifi", "type":"HW_IRTRANS_USB", "disabled":false, "active":false, "visible":true, "code":"IRTRANS-USB@IRTRANS:sndhex H5E010000000032260300E3004200AD2505000000000000000001B10030002D0030000000000000000003828253303130303030303030303030303130303030303030303031303030303030303030303030313030303030303031303130", "class":"action-button" }, { "title":"vol down", "translatedTitle":"vol down", "faIcon":"wifi", "type":"HW_IRTRANS_USB", "disabled":false, "active":false, "visible":true, "code":"IRTRANS-USB@IRTRANS:sndhex H5E010000000032260300E4003E00AC2505000000000000000001B000300030003000000000000000000383825330313030303030303030303030313030303030303030303130303030303030303130303030313030313030303031303130", "class":"action-button" }, { "title":"vol mute", "translatedTitle":"vol mute", "faIcon":"wifi", "type":"HW_IRTRANS_USB", "disabled":false, "active":false, "visible":true, "code":"IRTRANS-USB@IRTRANS:sndhex H5E010000000032260300E5003E00AD2504000000000000000001B00030002F003000000000000000000382845330313030303030303030303030313030303030303030303130303030303030303031303031313030303130303131303130", "class":"action-button" }, { "title":"ch up", "translatedTitle":"ch up", "faIcon":"wifi", "type":"HW_IRTRANS_USB", "disabled":false, "active":false, "visible":true, "code":"IRTRANS-USB@IRTRANS:sndhex H5E010000000032260300E3004200AD2505000000000000000001B10030002D0030000000000000000003828253303130303030303030303030303130303030303030303031303030303030303030303030313030303030303031303130", "class":"action-button" } ``` -------------------------------- ### ResponsiveVoice Integration and Logging Control in JavaScript Source: https://github.com/asterics/asterics-grid/blob/master/index.html Integrates the ResponsiveVoice text-to-speech library by managing console log output to filter out specific messages related to ResponsiveVoice initialization and status. It also includes code to measure the performance of JSON.parse and JSON.stringify operations. ```javascript var rvApiKey="zGuJFLIV"; var rvApiEndpoint = "https://texttospeech.responsivevoice.org/v1/text:synthesize"; if (Function.bind) { //remove RV log messages without altering RV source (forbidden by license) window.originalLog = console.log.bind(console); console.log = function () { if (['ResponsiveVoice r1.6.5', 'isHidden: false', 'Prerender: false', 'Configuring'].indexOf(arguments[0]) !== -1) { return; } else if (arguments[0] === 'RV: Voice support ready') { console.log = window.originalLog; } else { window.originalLog.apply(null, arguments); } } //determine time needed for JSON.parse/stringify window.originalJSONParse = JSON.parse; window.originalJSONStringify = JSON.stringify; window.parseTime = 0; JSON.parse = function (arguments) { let start = new Date().getTime(); let result = window.originalJSONParse(arguments); window.parseTime += (new Date().getTime() - start); console.warn(window.parseTime / 1000); return result; } JSON.stringify = function (arguments) { let start = new Date().getTime(); let result = window.originalJSONStringify(arguments); window.parseTime += (new Date().getTime() - start); console.warn(window.parseTime / 1000); return result; } } ``` -------------------------------- ### openHAB Service Integration Source: https://context7.com/asterics/asterics-grid/llms.txt Integrates with openHAB smart home platform for environmental control. Allows fetching items, sending commands, and controlling various device types. ```APIDOC ## openHAB Service ### Description The openHABService integrates with openHAB smart home platform for environmental control. It allows fetching available items, sending commands to items, and controlling various device types like switches, dimmers, and color lights. ### Methods - **getRestURL(openHABUrl)**: Gets the REST URL for a given openHAB instance. - **fetchItems(restUrl)**: Fetches all available items from the openHAB instance. - **sendAction(options)**: Sends a command or action to a specific openHAB item. ### Parameters for `sendAction` - **openHABUrl** (string) - Required - The base REST URL of the openHAB instance. - **itemName** (string) - Required - The name of the openHAB item to control. - **actionType** (string) - Required - The type of action to perform (e.g., 'ON', 'OFF', 'CUSTOM_VALUE', 'CUSTOM_COLOR'). - **actionValue** (string) - Optional - The value for the action (e.g., '75' for dimmer, '#FF5733' for color). ### Request Example for `sendAction` ```json { "openHABUrl": "http://192.168.1.50:8080/rest/items/", "itemName": "Living_Room_Light", "actionType": "ON" } ``` ### Response Example (Success) (No specific response body is detailed, typically an empty success or status code.) ``` -------------------------------- ### Create and Configure GridElement Model in JavaScript Source: https://context7.com/asterics/asterics-grid/llms.txt Illustrates the creation and configuration of individual grid elements using the GridElement model. It covers setting element properties such as labels, position, size, background color, and defining actions like speaking text or navigating to other grids. This is essential for defining the interactive components within a communication board. ```javascript import { GridElement } from './src/js/model/GridElement'; import { GridActionSpeak } from './src/js/model/GridActionSpeak'; import { GridActionNavigate } from './src/js/model/GridActionNavigate'; import { GridImage } from './src/js/model/GridImage'; // Create a basic element with speak action const speakElement = new GridElement({ label: { en: 'Water', es: 'Agua' }, x: 0, y: 0, width: 1, height: 1, backgroundColor: '#2196F3', actions: [new GridActionSpeak()] }); // Create a navigation element const navElement = new GridElement({ label: { en: 'Go to Food' }, x: 1, y: 0, actions: [new GridActionNavigate({ toGridId: 'grid-data-food-123' })] }); // Get the navigation target console.log('Navigates to:', navElement.getNavigateGridId()); // Output: Navigates to: grid-data-food-123 // Element types available console.log('Element types:', [ GridElement.ELEMENT_TYPE_NORMAL, // Standard grid element GridElement.ELEMENT_TYPE_COLLECT, // Collect bar element GridElement.ELEMENT_TYPE_PREDICTION, // Word prediction element GridElement.ELEMENT_TYPE_YT_PLAYER, // YouTube player element GridElement.ELEMENT_TYPE_LIVE // Live data display element ]); ``` -------------------------------- ### Control Toy with Puck.js FET via UART Source: https://github.com/asterics/asterics-grid/blob/master/docs/documentation_user/tutorials/02_uart-action-tutorials.md This snippet shows how to control a battery-powered toy using the FET pin on a Puck.js device via a UART action. It requires a Puck.js device and a battery-powered toy with a battery interrupter. The commands 'FET.set()' and 'FET.reset()' are used to turn the toy on and off, respectively. ```javascript FET.set(); ``` ```javascript FET.reset(); ``` -------------------------------- ### Execute Grid Actions with Action Service (JavaScript) Source: https://context7.com/asterics/asterics-grid/llms.txt Facilitates the execution of grid element actions, including speech, navigation, HTTP requests, media control, and smart home integrations. Allows for testing specific actions and retrieving predefined action templates. ```javascript import { actionService } from './src/js/service/actionService'; // Execute actions for a grid element await actionService.doAction('grid-data-123', 'grid-element-456'); // Test a specific action without triggering full flow import { GridActionHTTP } from './src/js/model/GridActionHTTP'; const httpAction = new GridActionHTTP({ restUrl: 'http://192.168.1.100:8080/api/light', method: 'POST', contentType: 'application/json', body: '{"state": "on", "brightness": 100}' }); const result = await actionService.testAction(gridElement, httpAction); console.log('HTTP response:', result); // Get predefined action templates const predefinedActions = await actionService.getPredefinedActionInfos(); predefinedActions.forEach(action => { console.log(`${action.name}: ${action.description}`); }); // Output: Shelly Plug Toggle: Toggle Shelly smart plug on/off // Output: HomeAssistant Light: Control HomeAssistant lights ```