### Usage Example Source: https://developer.electricimp.com/libraries/hardware/bg96-gps A simple example demonstrating how to enable GNSS and poll for location fixes. ```APIDOC ## Usage Example This is a very simple example that enables GNSS on the BG96 and then polls and prints out the fix every ten seconds: ``` #require "BG96_GPS.device.lib.nut:1.0.2" function onLocation(result) { if ("fix" in result) { server.log("Got fix:"); foreach (key, value in result) { server.log(key + ": " + value); if ((typeof value) == "table") { foreach (k, v in value) { server.log(" " + k + ": " + v); } } } } else { server.error(result.error); } } server.log("Enabling GNSS and getting fix..."); BG96_GPS.enableGNSS({ // NOTE Non-assist cold fix time can be up to 12.5 mins // if new almanacs and ephemerides need to be fetched "maxPosTime" : 90, "checkFreq" : 10, "onLocation" : onLocation }); ``` ``` -------------------------------- ### Installation Source: https://developer.electricimp.com/libraries/hardware/bg96-gps Include this library in your device code by adding the following line. ```APIDOC ## Installation To include this library to your project, add the following line to the top of your device code: ``` #require "BG96_GPS.device.lib.nut:1.0.2" ``` ``` -------------------------------- ### Online Request Parameters Example Source: https://developer.electricimp.com/libraries/cloudservices/ubloxassistnowagent This example shows how to configure parameters for an online request, specifying data types, GNSS systems, and approximate location. Using strings for location and accuracy parameters is recommended for precision. ```nut local reqParams = { datatype = {"eph", "alm"}, gnss = {"gps", "gal"}, lat = "37.7749", lon = "-122.4194", alt = "70.0", pacc = "10.0", tacc = "3600" }; ``` -------------------------------- ### Configure Murano Product Settings Source: https://developer.electricimp.com/libraries/cloudservices/exosite Example settings object for connecting to a Murano Product. ```Squirrel local settings = {}; settings.productId = "c449gfcd11ky00002"; settings.deviceId = "device0001"; ``` -------------------------------- ### Enable GNSS and Get Location Fix Source: https://developer.electricimp.com/libraries/hardware/bg96-gps This example enables GNSS on the BG96 module and then polls for and prints the GPS fix every ten seconds. Ensure the `onLocation` callback is defined to handle the results. ```nut #require "BG96_GPS.device.lib.nut:1.0.2" function onLocation(result) { if ("fix" in result) { server.log("Got fix:"); foreach (key, value in result) { server.log(key + ": " + value); if ((typeof value) == "table") { foreach (k, v in value) { server.log(" " + k + ": " + v); } } } } else { server.error(result.error); } } server.log("Enabling GNSS and getting fix..."); BG96_GPS.enableGNSS({ // NOTE Non-assist cold fix time can be up to 12.5 mins // if new almanacs and ephemerides need to be fetched "maxPosTime" : 90, "checkFreq" : 10, "onLocation" : onLocation }); ``` -------------------------------- ### Full GPSUARTDriver Implementation Source: https://developer.electricimp.com/libraries/hardware/gpsuartdriver Example demonstrating library initialization, callback handling for GPS data, and usage of location methods. ```Squirrel #require "GPSParser.device.lib.nut:1.0.0" #require "GPSUARTDriver.device.lib.nut:1.2.0" // Create GPS variable local gps = null; // GPS callback function gpsHandler(hasLocation, data) { // Log location or GPS sentence if (hasLocation) { server.log(format("Latitude: %s, Longitude: %s", gps.getLatitude(), gps.getLongitude())); } else { server.log(gps.getGPSSentence()); } // If we don't have a fix log number of satellites in view if (!gps.hasFix() && "numSatellites" in data) { server.log(format("Number of satellites: %s", data.numSatellites)); } } // GPS options local gpsOpts = {"gpsDataReady" : gpsHandler, "parseData" : true}; // Initialize GPS UART driver gps = GPSUARTDriver(hardware.uart1, gpsOpts); ``` -------------------------------- ### Chained Method Example Source: https://developer.electricimp.com/libraries/hardware/ht16k33segmentbig Demonstrates chaining of methods for setting the display to :--:--. This allows for more concise code when performing multiple operations. ```squirrel // Set the display to :--:-- led.clearBuffer(17).setColon(0x0E).updateDisplay(); ``` -------------------------------- ### Example Usage Source: https://developer.electricimp.com/libraries/hardware/gpsparser Demonstrates how to use the GPSParser library to parse a GLL sentence and log location data. ```APIDOC ## EXAMPLE USAGE ### Description This example shows how to parse a GLL sentence and extract latitude and longitude. ### Code ```lua local sentence = "$GPGLL,4916.45,N,12311.12,W,225444,A,*1D\r\n"; local gpsData = GPSParser.getGPSDataTable(sentence); if gpsData.sentenceId == GPS_PARSER_GLL) { server.log("GLL message received."); if (gpsData.status == "A" && "latitude" in gpsData && "longitude" in gpsData) { server.log(format("Latitude %s, Longitude %s", gpsData.latitude, gpsData.longitude)); } else { server.log("Location data not available."); } } ``` ``` -------------------------------- ### Initialize and Connect Bayeux Client Source: https://developer.electricimp.com/libraries/cloudservices/bayeuxclient Demonstrates how to configure, instantiate, and connect a Bayeux client with connection and disconnection callbacks. ```Squirrel #require "BayeuxClient.agent.lib.nut:1.0.0" function onConnected(error) { if (error != null) { server.error("Сonnection failed"); server.error(format("Error type: %d, details: %s", error.type, error.details.tostring())); return; } server.log("Connected!"); // Here is a good place to make required subscriptions } function onDisconnected(error) { if (error != null) { server.error("Disconnected unexpectedly with error:"); server.error(format("Error type: %d, details: %s", error.type, error.details.tostring())); // Reconnect if disconnection is not initiated by application client.connect(); } else { server.log("Disconnected by application"); } } config <- { "url" : "yourBayeuxServer.com", "requestHeaders": { "Authorization" : "YOUR_AUTHORIZATION_HEADER"} }; // Instantiate and connect a client client <- Bayeux.Client(config, onConnected, onDisconnected); client.connect(); ``` -------------------------------- ### Method: init Source: https://developer.electricimp.com/libraries/hardware/ht16k33matrix Initializes the matrix settings including brightness and rotation. ```APIDOC ## Method: init([brightness][, angle]) ### Description Sets the matrix's initial brightness and rotation settings. ### Parameters - **brightness** (integer) - Optional - LED intensity from 0 to 15 (default: 15). - **angle** (integer) - Optional - Rotation angle (0, 90, 180, 270 degrees or internal values 0-3). ``` -------------------------------- ### Initialize FramStore Source: https://developer.electricimp.com/libraries/hardware/framstore Configure the I2C bus and instantiate the FramStore with an array of FRAM chip objects. ```Squirrel #require "FramStore.class.nut:1.0.0" #require "MB85RC.class.nut:1.0.0" // Configure I2C bus local i2c = hardware.i2c89; i2c.configure(CLOCK_SPEED_400_KHZ); local f1 = MB85RC(i2c, 0xA0, 256); local f2 = MB85RC(i2c, 0xA2, 256); // Configure FRAM array with four devices local store = FramStore([f1, f2]); ``` -------------------------------- ### Initialize Exosite Library Source: https://developer.electricimp.com/libraries/cloudservices/exosite Instantiate the Exosite class using the required mode and settings table. ```squirrel const PRODUCT_ID = ; local settings = {}; settings.productId <- PRODUCT_ID; exositeAgent <- Exosite(EXOSITE_MODES.MURANO_PRODUCT, settings); ``` -------------------------------- ### Get Temperature Data Source: https://developer.electricimp.com/libraries/hardware/lps25h Retrieve the current temperature in degrees Celsius. ```squirrel server.log("Current Temperature: " + pressure.getTemp() + "C"); ``` -------------------------------- ### deleteAssistData(_[mode]_) API Source: https://developer.electricimp.com/libraries/hardware/bg96-gps Deletes any installed assist data and disables GNSS. ```APIDOC ## deleteAssistData(_[mode]_) ### Description Delete any installed assist data. **Note** This call will also disable GNSS. ### Method `deleteAssistData(_[mode]_)` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters Parameter | Type | Required? | Description ---|---|---|--- _mode_ | Integer | No | The desired reset mode (see **gnss-session.assist.reset()**) ### Return Value Nothing. ``` -------------------------------- ### Get Device ID Source: https://developer.electricimp.com/libraries/hardware/lps22hb Retrieves the device ID register value, which should be 0xB1. ```squirrel pressureSensor.getDeviceID(); ``` -------------------------------- ### GoogleIoTCore.Client Constructor Source: https://developer.electricimp.com/libraries/cloudservices/googleiotcore Initializes a new GoogleIoTCore.Client instance with project details and optional configuration settings. ```APIDOC ## Constructor: GoogleIoTCore.Client(_projectId, cloudRegion, registryId, deviceId, privateKey[, onConnected][, onDisconnected][, transport][, options]_) ### Description Creates a new instance of the GoogleIoTCore client to manage device connectivity and communication. ### Parameters - **projectId** (String) - Required - The Project ID - **cloudRegion** (String) - Required - The Cloud region - **registryId** (String) - Required - The Registry ID - **deviceId** (String) - Required - The Device ID - **privateKey** (String) - Required - The private key - **onConnected** (Function) - Optional - Callback executed on connection - **onDisconnected** (Function) - Optional - Callback executed on disconnection - **transport** (Object) - Optional - Transport instance - **options** (Table) - Optional - Additional settings including maxPendingSetStateRequests, maxPendingPublishTelemetryRequests, tokenTTL, and tokenAutoRefresh ``` -------------------------------- ### Get Sensor Resolution Source: https://developer.electricimp.com/libraries/hardware/hts221 Retrieve the current temperature and humidity resolution settings. ```squirrel local res = tempHumid.getResolution(); server.log("Number of temperature samples: " + res.temperatureResolution); server.log(" Number of humidity samples: " + res.humidityResolution); ``` -------------------------------- ### Initialize Matrix Settings Source: https://developer.electricimp.com/libraries/hardware/ht16k33matrix Configure brightness and rotation settings for the display. ```Squirrel // Set matrix to max brightness and to // rotate all characters by 180 degrees led.init(15, 2); ``` ```Squirrel // Set matrix to mid brightness and to // rotate all characters 90 degrees anticlockwise led.init(8, -90); ``` -------------------------------- ### Device Initialization and Management Source: https://developer.electricimp.com/libraries/cloudservices/losant This snippet demonstrates how to initialize device information, check for existing devices, and create a new device if it doesn't exist. It uses agent and device IDs to uniquely identify the device. ```squirrel lsntDeviceId <- null; agentId <- split(http.agenturl(), "/").top(); impDeviceId <- imp.configparams.deviceid; deviceInfo <- { "name" : format("Tracker_%s", agentId), "description" : "Electric Imp Asset Tracker", "deviceClass" : "standalone", "tags" : [ { "key" : "agentId", "value" : agentId }, { "key" : "impDevId", "value" : impDeviceId } ], "attributes" : [ { "name" : "location", "dataType" : "gps" }, { "name" : "temperature", "dataType" : "number" }, { "name" : "humidity", "dataType" : "number" }, { "name" : "magnitude", "dataType" : "number" }, { "name" : "alertTemperature", "dataType" : "string" }, { "name" : "alertHumidity", "dataType" : "string" }, { "name" : "alertMovement", "dataType" : "string" } ] } // Get all devices lsntTrackerApp.getDevices(function(response) { server.log("Status Code: " + response.statuscode); server.log(response.body); }); // Create filter for tags matching this device, use the tags set up as unique ids - agent and device id combo local qparams = lsntTrackerApp.createTagFilterQueryParams(deviceInfo.tags); // Look for this device lsntTrackerApp.getDevices(function(response) { local body = http.jsondecode(response.body); if (response.statuscode == 200 && "count" in body) { // Successful request switch (body.count) { case 0: // No devices found, create device lsntTrackerApp.createDevice(deviceInfo, function(resp) { local bdy = http.jsondecode(resp.body); lsntDeviceId = bdy.deviceId; }); break; case 1: // We found the device, store the lsntDeviceId lsntDeviceId = body.items[0].deviceId; break; default: // We have multiple matches, log results of filtered query server.error("Found " + body.count + "devices matching the device tags."); // TODO: Delete multiples } } else { server.error("List device request failed with status code: " + response.statuscode); } }, qparams); ``` -------------------------------- ### Get Magnetometer Range Source: https://developer.electricimp.com/libraries/hardware/lsm9dS0 Retrieve the currently set full-scale range for the magnetometer in Gauss. ```APIDOC ## GET /api/magnetometer/range ### Description Returns the currently set full-scale range for the magnetometer in gauss. ### Method GET ### Endpoint /api/magnetometer/range ### Parameters None ### Request Example None ### Response #### Success Response (200) - **current_range_gauss** (integer) - The currently set full-scale range in Gauss. #### Response Example ```json { "current_range_gauss": 4 } ``` ``` -------------------------------- ### Get Temperature Source: https://developer.electricimp.com/libraries/hardware/lps25h Retrieves the current temperature reading from the LPS25H sensor in degrees Celsius. ```APIDOC ## Get Temperature ### Description This method retrieves the current temperature reading from the LPS25H sensor. ### Method `getTemp()` ### Response Example ``` 25.5 ``` ### Request Example ```javascript server.log("Current Temperature: " + pressure.getTemp() + "C"); ``` ``` -------------------------------- ### Manage Reference Pressure Source: https://developer.electricimp.com/libraries/hardware/lps25h Set or get the reference pressure used for differential measurements. ```squirrel server.log("Internal Reference Pressure Offset = " + pressure.getReferencePressure()); ``` ```squirrel server.log("Internal Reference Pressure Offset = " + pressure.getReferencePressure()); ``` -------------------------------- ### HTS221 Get Sensor Mode Source: https://developer.electricimp.com/libraries/hardware/hts221 Retrieve the current operating mode of the HTS221 sensor. ```APIDOC ## getMode() ### Description This method indicates which mode the sensor has been set to: _HTS221_MODE.POWER_DOWN_ , _HTS221_MODE.ONE_SHOT_ or _HTS221_MODE.CONTINUOUS_. ### Return Value Integer — The sensor’s current mode. ### Request Example ``` local mode = tempHumid.getMode(); if (mode == HTS221_MODE.ONE_SHOT) { server.log("In one shot mode"); } if (mode == HTS221_MODE.CONTINUOUS) { server.log("In continuous mode with a data rate of " + tempHumid.getDataRate() + "Hz"); } if (mode == HTS221_MODE.POWER_DOWN) { server.log("In power down mode"); } ``` ``` -------------------------------- ### Get Output Data Rate Source: https://developer.electricimp.com/libraries/hardware/hts221 Retrieve the current output data rate in Hertz. ```squirrel local dataRate = tempHumid.getDataRate(); server.log(dataRate); ``` -------------------------------- ### Instantiate Google IoT Core Client Source: https://developer.electricimp.com/libraries/cloudservices/googleiotcore Instantiate the GoogleIoTCore.Client class with your Google IoT Core credentials. Ensure all prerequisite information is correctly provided. ```nut #require "GoogleIoTCore.agent.lib.nut:1.0.0" const GOOGLE_IOT_CORE_PROJECT_ID = ""; const GOOGLE_IOT_CORE_CLOUD_REGION = ""; const GOOGLE_IOT_CORE_REGISTRY_ID = ""; const GOOGLE_IOT_CORE_DEVICE_ID = ""; const GOOGLE_IOT_CORE_PRIVATE_KEY = ""; // Instantiate a client client <- GoogleIoTCore.Client(GOOGLE_IOT_CORE_PROJECT_ID, GOOGLE_IOT_CORE_CLOUD_REGION, GOOGLE_IOT_CORE_REGISTRY_ID, GOOGLE_IOT_CORE_DEVICE_ID, GOOGLE_IOT_CORE_PRIVATE_KEY); ``` -------------------------------- ### provision Source: https://developer.electricimp.com/libraries/cloudservices/exosite Provisions the device with ExoSense using settings provided in the constructor. ```APIDOC ## provision(callback) ### Description Provisions the device with ExoSense. A successful request returns the CIK Auth token in the response body. ### Parameters #### Request Body - **callback** (Function) - Required - A function to be executed to handle the response. ``` -------------------------------- ### GET /devices Source: https://developer.electricimp.com/libraries/cloudservices/losant Fetches a list of devices associated with the Losant application, with optional filtering. ```APIDOC ## GET /devices ### Description Fetches a list of application devices from the Losant platform. ### Method GET ### Parameters #### Query Parameters - **queryParams** (String) - Optional - Query parameters used to filter the results. - **callback** (Function) - Required - A function executed when the server responds, receiving a table with statuscode, headers, and body. ``` -------------------------------- ### Send Data to ExoSense Source: https://developer.electricimp.com/libraries/cloudservices/exosite Example of sending a temperature reading to an ExoSense channel using agent.send. ```Squirrel local conditions = {}; conditions.temp <- reading.temperature; agent.send("reading.sent", conditions); ``` -------------------------------- ### Initialize the LSM9DS0 Library Source: https://developer.electricimp.com/libraries/hardware/lsm9dS0 Include the library and initialize the I2C bus and sensor instance. ```Squirrel #require "LSM9DS0.class.nut:1.1.0" i2c <- hardware.i2c89; i2c.configure(CLOCK_SPEED_400_KHZ); imu <- LSM9DS0(i2c); ``` -------------------------------- ### Implement Bluetooth Firmware Storage and Initialization Source: https://developer.electricimp.com/libraries/hardware/bt-firmware This script initializes the SPI Flash file system, handles firmware storage and retrieval, and manages the Bluetooth boot process. ```Squirrel #require "SPIFlashFileSystem.device.lib.nut:2.0.0" const BT_FIRMWARE_FILE_NAME = "btFirmware"; // Store Bluetooth firmware in SPI Flash function storeBTFirmware(firmware) { server.log("Storing bluetooth firmware to SPI flash"); // We only want one version of firmware stored at a time, so // erase if we already have stored firmware if (haveStoredFirmware) sffs.eraseFile(BT_FIRMWARE_FILE_NAME); local file = sffs.open(BT_FIRMWARE_FILE_NAME, "w"); file.write(firmware); file.close(); // Make sure we update stored firmware flag haveStoredFirmware <- sffs.fileExists(BT_FIRMWARE_FILE_NAME); } // Retrieve Bluetooth firmware from SPI Flash function getBTFirmware() { server.log("Retrieving stored bluetooth firmware"); if (!haveStoredFirmware) return null; local file = sffs.open(BT_FIRMWARE_FILE_NAME, "r"); local firmware = file.read(); file.close(); return firmware; } // Use stored firmware to boot bluetooth function bootBT() { server.log("Booting Bluetooth with stored firmware"); bt_lpo_in.configure(DIGITAL_OUT, 0); bt_reg_on.configure(DIGITAL_OUT, 1); // Pause to ensure pins are in the newly // configured state before proceeding imp.sleep(0.05); try { // Instantiate BT bt = hardware.bluetooth.open(bt_uart, getBTFirmware()); server.log("BLE initialized"); } catch (err) { server.log("BLE failed: " + err); } } // Configure global imp004m bluetooth hardware variables bt <- null; bt_uart <- hardware.uartFGJH; bt_lpo_in <- hardware.pinE; bt_reg_on <- hardware.pinJ; // Configure SPI flash storage sffs <- SPIFlashFileSystem(0x000000, 0x020000); sffs.init(); haveStoredFirmware <- sffs.fileExists(BT_FIRMWARE_FILE_NAME); // Create listener for firmware message from agent agent.on("set.firmware", function(firmware) { server.log("Received bluetooth firmware from agent"); storeBTFirmware(firmware); bootBT(); }); server.log("DEVICE RUNNING..."); imp.enableblinkup(true); server.log(imp.getsoftwareversion()); if (haveStoredFirmware) { // Boot bluetooth with stored firmware bootBT(); } else { // Get bluetooth firmware from agent server.log("No stored Bluetooth firmware. Requesting firmware from agent..."); agent.send("get.firmware", null); } ``` -------------------------------- ### Set and Get Accelerometer Range Source: https://developer.electricimp.com/libraries/hardware/lsm9dS0 Configures the full-scale range for the accelerometer and retrieves the current setting. ```Squirrel local newRange = setRange_A(4); server.log(format("Set Accelerometer full-scale range to +/- %d g", newRange)); ``` ```Squirrel local range = getRange_A(); server.log(format("Accelerometer full-scale range is +/- %d g", range)); ``` -------------------------------- ### Get Accelerometer Measurement Range Source: https://developer.electricimp.com/libraries/hardware/lis3dh Retrieves the currently set measurement range of the sensor in Gs. ```squirrel server.log(format("Current Sensor Range is +/- %dG", accel.getRange())); ``` -------------------------------- ### init() Source: https://developer.electricimp.com/libraries/hardware/lis3mdl Synchronizes the object’s data-reading scale with that stored on the device. ```APIDOC ## init() ### Description Synchronizes the object’s data-reading scale with that stored on the device. This method is automatically called by the constructor and `reset()` functions. ``` -------------------------------- ### Get Device ID Source: https://developer.electricimp.com/libraries/hardware/lps25h Retrieves the device ID register value, which should be `0xBD` for the LPS25H sensor. ```squirrel pressureSensor.getDeviceID(); ``` -------------------------------- ### Instantiate LPDeviceManager with Callbacks Source: https://developer.electricimp.com/libraries/hardware/lp-device-manager Instantiates the LPDeviceManager, providing callbacks for specific wake reasons like timer events or general boot-ups. Ensure ConnectionManager is also instantiated. ```javascript // Wake up on timer flow function onScheduledWake() { // Do something } // Wake up (not on timer) flow function onBoot(wakereason) { server.log("Device booted"); // Do something } local cm = ConnectionManager({"blinkupBehavior": CM_BLINK_ALWAYS}); local lpm = LPDeviceManager(cm, {"onTimer" : onScheduledWake.bindenv(this), "defaultOnWake" : onBoot.bindenv(this)}); ``` -------------------------------- ### Initialize and Listen for BlinkUp Connections Source: https://developer.electricimp.com/libraries/hardware/bt-blinkup Initializes the BTLEBlinkUp library and sets up a callback function to log connection events. The callback receives connection data including the device address and connection state. ```squirrel local bt = BTLEBlinkUp(); bt.listenForBlinkUp(null, function(data) { server.log("Device " + data.address + " has " + data.state); }); ``` -------------------------------- ### HTS221 Get Resolution Source: https://developer.electricimp.com/libraries/hardware/hts221 Retrieve the current temperature and humidity resolution settings of the HTS221 sensor. ```APIDOC ## getResolution() ### Description This method retrieves the sensor’s current temperature and humidity resolution in terms of the number of samples of each value that are taken and then averaged when a reading is requested. ### Return Value Table — the applied resolutions, accessed via the keys _temperatureResolution_ and _humidityResolution_. ### Request Example ``` local res = tempHumid.getResolution(); server.log("Number of temperature samples: " + res.temperatureResolution); server.log(" Number of humidity samples: " + res.humidityResolution); ``` ``` -------------------------------- ### Method Chaining Source: https://developer.electricimp.com/libraries/hardware/button Demonstrates how to chain method calls for concise initialization and event handling. ```APIDOC ## Method Chaining All methods return `this`, the instance of the instantiated object. This allows method chaining as shown below: ### Request Example ``` Button(hardware.pin1, DIGITAL_IN_WAKEUP) .onPress(function() { server.log("Pressed"); }).onRelease(function() { server.log("Released.. going to sleep"); imp.onidle(function() { server.sleepfor(3600); }); }); ``` ``` -------------------------------- ### configureInterrupt Source: https://developer.electricimp.com/libraries/hardware/lps25h Configures the interrupt pin driver, threshold, and sources. The device starts with this disabled by default. ```APIDOC ## configureInterrupt(_enable[, threshold][, options]_) ### Description This method configures the interrupt pin driver, threshold, and sources. The device starts with this disabled by default. ### Method POST (or equivalent for method configuration) ### Endpoint /websites/developer_electricimp_libraries/configureInterrupt ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **enable** (boolean) - Required - Set `true` to enable the interrupt pin. - **threshold** (Integer) - Optional - Interrupts are generated on differential pressure events; a high differential pressure interrupt occurs if (Absolute Pressure - Reference Pressure) > Threshold; a low differential pressure interrupt occurs if (Absolute Pressure - Reference Pressure) < (-1.0 * Threshold). The threshold is expressed in hectopascals (hPa). - **options** (Bitfield) - Optional - Configuration options combined with the bitwise OR operator. See the ‘Options’ table below. Default is 0x00. ### Options Table - **INT_ACTIVELOW**: Interrupt pin is active-high by default. Use to set interrupt to active-low. - **INT_OPENDRAIN**: Interrupt pin driver push-pull by default. Use to set interrupt to open-drain. - **INT_LATCH**: Interrupt latching mode is disabled by default. Use to enable interrupt latching mode. To clear a latched interrupt pin call _getInterruptSrc(). - **INT_LOW_PRESSURE**: Interrupt is disabled by default. Use to enable interrupt when pressure below threshold. - **INT_HIGH_PRESSURE**: Interrupt is disabled by default. Use to enable interrupt when pressure above threshold. ### Request Example ```lua pressureSensor.configureInterrupt(true, 10, LPS25H.INT_LATCH | LPS25H.INT_HIGH_PRESSURE); pressureSensor.configureInterrupt(true, 20, LPS25H.INT_ACTIVELOW | LPS25H.INT_OPENDRAIN | LPS25H.INT_LATCH | LPS25H.INT_LOW_PRESSURE); ``` ### Response #### Success Response (200) - **status** (string) - Indicates success or failure of the operation. #### Response Example ```json { "status": "success" } ``` ``` -------------------------------- ### Configuration Methods Source: https://developer.electricimp.com/libraries/hardware/ht16k33segment Methods for adjusting display brightness and flashing behavior. ```APIDOC ## setBrightness([brightness]) ### Description Sets the LED duty cycle (0-15). ## setDisplayFlash(flashInHertz) ### Description Sets the flash rate of the display. Supported values: 0 (disabled), 0.5, 1, or 2 Hz. ``` -------------------------------- ### Initialize CFAx33KL Source: https://developer.electricimp.com/libraries/hardware/cfax33kl Include the library and instantiate the class using a hardware UART object. ```squirrel #require "CFAx33KL.device.lib.nut:2.0.0" lcd <- CFAx33KL(hardware.uart6E); ``` -------------------------------- ### Get LPS22HB Sensor Mode Source: https://developer.electricimp.com/libraries/hardware/lps22hb Retrieves the current operating mode of the LPS22HB sensor (one-shot or continuous). ```squirrel local mode = pressureSensor.getMode(); if (mode == LPS22HB_MODE.ONE_SHOT) { server.log("In one shot mode"); } if (mode == LPS22HB_MODE.CONTINUOUS) { server.log("In continuous mode with a data rate of " + pressureSensor.getDataRate() + "Hz"); } ``` -------------------------------- ### Set and Get Data Rate Source: https://developer.electricimp.com/libraries/hardware/lps25h Configures and retrieves the output data rate (ODR) for the pressure sensor. ```APIDOC ## Set and Get Data Rate ### Description These methods allow you to set and retrieve the output data rate (ODR) of the pressure sensor. The ODR determines how frequently the sensor takes measurements. Supported rates are 0 (one-shot), 1, 7, 12.5, and 25 Hz. When setting the data rate, the library uses the nearest supported rate less than or equal to the requested value. ### Methods - `setDataRate(_dataRate_)` - `getDataRate()` ### Parameters - **_dataRate_** (number) - Required - The desired data rate in Hz. Supported values: 0, 1, 7, 12.5, 25. ### Response Example (getDataRate) ``` 7 ``` ### Request Example (setDataRate) ```javascript local dataRate = pressureSensor.setDataRate(7); server.log(dataRate); // Logs the actual data rate set (e.g., 7) ``` ### Request Example (getDataRate) ```javascript local dataRate = pressureSensor.getDataRate(); server.log(dataRate); // Logs the current data rate (e.g., 7) ``` ``` -------------------------------- ### Load Mnubo Libraries Source: https://developer.electricimp.com/libraries/cloudservices Include both the Mnubo agent and promise class libraries. ```nut #require "mnubo.agent.nut:1.0.0" #require "promise.class.nut:3.0.1" ``` -------------------------------- ### Set and Get Reference Pressure Source: https://developer.electricimp.com/libraries/hardware/lps25h Allows setting and retrieving the reference pressure for differential measurements and interrupts. ```APIDOC ## Set and Get Reference Pressure ### Description These methods are used to configure and retrieve the reference pressure, which is utilized for differential pressure measurements and interrupt configurations. The pressure is measured in hectopascals (hPa), and the range is ± 2046hPa. ### Methods - `setReferencePressure(_pressure_)` - `getReferencePressure()` ### Parameters - **_pressure_** (number) - Required - The reference pressure value in hPa. ### Response Example (getReferencePressure) ``` 1013.25 ``` ### Request Example (Set Reference Pressure) ```javascript pressureSensor.setReferencePressure(1015.0); ``` ### Request Example (Get Reference Pressure) ```javascript server.log("Internal Reference Pressure Offset = " + pressure.getReferencePressure()); ``` ``` -------------------------------- ### Get points per reading Source: https://developer.electricimp.com/libraries/hardware/apds9007 Retrieve the current number of data points used for internal averaging. ```squirrel server.log(lightsensor.getPointsPerReading()); ``` -------------------------------- ### Instantiate HT16K33Matrix Source: https://developer.electricimp.com/libraries/hardware/ht16k33matrix Initialize the library and configure the I2C bus before creating the matrix object. ```Squirrel #require "HT16K33Matrix.class.nut:1.2.0" hardware.i2c89.configure(CLOCK_SPEED_400_KHZ); matrix <- HT16K33Matrix(hardware.i2c89); ``` ```Squirrel #require "HT16K33Matrix.class.nut:1.2.0" // With debugging hardware.i2c89.configure(CLOCK_SPEED_400_KHZ); led <- HT16K33Matrix(hardware.i2c89, 0x70, true); ``` -------------------------------- ### Get LPS22HB Data Rate Source: https://developer.electricimp.com/libraries/hardware/lps22hb Retrieves the current output data rate (ODR) of the LPS22HB sensor in Hertz. ```squirrel local dataRate = pressureSensor.getDataRate(); server.log(dataRate); ``` -------------------------------- ### HTS221 Get Data Rate Source: https://developer.electricimp.com/libraries/hardware/hts221 Retrieve the current output data rate (ODR) of the HTS221 sensor in Hertz. ```APIDOC ## getDataRate() ### Description This method indicates the sensor’s current output data rate (ODR) in Hertz. ### Return Value Integer — The sensor’s current ODR. ### Request Example ``` local dataRate = tempHumid.getDataRate(); server.log(dataRate); ``` ``` -------------------------------- ### Instantiate Button Class Source: https://developer.electricimp.com/libraries/hardware/button Initialize the Button object with a pin, pull configuration, polarity, and optional callbacks. ```nut #require "Button.class.nut:1.2.0" // Button on pin7 button <- Button(hardware.pin7, DIGITAL_IN_PULLUP, Button.NORMALLY_HIGH, function() { server.log("Button pressed"); } ); ``` -------------------------------- ### Load Exosite Library Source: https://developer.electricimp.com/libraries/cloudservices Use this directive to include the Exosite library in your agent code. ```nut #require "Exosite.agent.lib.nut:1.1.0" ``` -------------------------------- ### Configure LIS3MDL Interrupts Source: https://developer.electricimp.com/libraries/hardware/lis3mdl Use these examples to enable or disable interrupt monitoring on specific axes or to disable the feature entirely. ```Squirrel // Enable interrupt monitoring on the X- and Y-axes with a threshold of 3 gauss magnetometer.configureInterrupt(true, 3, LIS3MDL.AXIS_X | LIS3MDL.AXIS_Y); ``` ```Squirrel // Disable interrupt monitoring magnetometer.configureInterrupt(false); ``` -------------------------------- ### Load Conctr Libraries Source: https://developer.electricimp.com/libraries/cloudservices Include both the agent and device class libraries for Conctr. ```nut #require "conctr.agent.class.nut:2.1.0" #require "conctr.device.class.nut:2.1.0" ``` -------------------------------- ### Retrieve multiple items with AWS_DYNAMO_DB_ACTION_BATCH_GET_ITEM Source: https://developer.electricimp.com/libraries/cloudservices/awsdynamodb Uses the batch get item action to fetch specific keys from a DynamoDB table. ```squirrel local getParams = { "RequestItems": { "testTable2": { "Keys": [ { "deviceId": {"S": imp.configparams.deviceid}, "time": {"S": itemTime1} }, { "deviceId": {"S": imp.configparams.deviceid}, "time": {"S": itemTime2} } ] } } }; db.action(AWS_DYNAMO_DB_ACTION_BATCH_GET_ITEM, getParams, function(response) { local arrayOfReturnedItems = http.jsondecode(response.body).Responses.testTable2; }) ``` -------------------------------- ### Connect to Google IoT Core Source: https://developer.electricimp.com/libraries/cloudservices/googleiotcore Initializes the GoogleIoTCore client with credentials and defines connection/disconnection callbacks. ```Squirrel const GOOGLE_IOT_CORE_PROJECT_ID = ""; const GOOGLE_IOT_CORE_CLOUD_REGION = ""; const GOOGLE_IOT_CORE_REGISTRY_ID = ""; const GOOGLE_IOT_CORE_DEVICE_ID = ""; const GOOGLE_IOT_CORE_PRIVATE_KEY = ""; function onConnected(err) { if (err != 0) { server.error("Connect failed: " + err); return; } server.log("Connected"); // Here is a good place to enable configuration reception } function onDisconnected(err) { if (err != 0) { server.error("Disconnected unexpectedly with code: " + err); // Reconnect if disconnection was not initiated by the application client.connect(); } else { server.log("Disconnected by application"); } } // Instantiate and connect a client client <- GoogleIoTCore.Client(GOOGLE_IOT_CORE_PROJECT_ID, GOOGLE_IOT_CORE_CLOUD_REGION, GOOGLE_IOT_CORE_REGISTRY_ID, GOOGLE_IOT_CORE_DEVICE_ID, GOOGLE_IOT_CORE_PRIVATE_KEY, onConnected, onDisconnected); client.connect(); ``` -------------------------------- ### listenForBlinkUp Source: https://developer.electricimp.com/libraries/hardware/bt-blinkup Boots the Bluetooth LE radio, sets up GATT services, and advertises availability for BlinkUp. ```APIDOC ## listenForBlinkUp(advert, callback) ### Description Boots up the imp’s Bluetooth LE radio; sets up and serves two GATT services: BlinkUp and the standard Device Information service; prepares the imp to receive connections from the mobile app; and advertises the imp’s availability. ### Parameters #### Parameters - **advert** (String or blob) - Optional - The imp’s Bluetooth LE advertisement payload, up to 31 bytes. - **callback** (Function) - Optional - A function triggered when a remote device connects or disconnects. ``` -------------------------------- ### Get Device ID Source: https://developer.electricimp.com/libraries/hardware/hts221 Retrieves the device ID register value of the sensor. For the HTS221 sensor, this value is expected to be 0xBC. ```squirrel getDeviceID() ``` -------------------------------- ### Constructor: APDS9007(_inputPin, rLoad[, enablePin]_) and Initialization Source: https://developer.electricimp.com/libraries/hardware/apds9007 Demonstrates how to instantiate a new APDS9007 object and initialize the sensor. ```APIDOC ## Constructor and Initialization ### Description Instantiates a new APDS9007 object and initializes the sensor with the provided analog input pin, load resistor value, and an optional digital output enable pin. ### Method Constructor ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```javascript #require "APDS9007.class.nut:3.0.0" // Value of load resistor on ALS const RLOAD = 47000.0; // Use pin 5 as analog input analogInputPin <- hardware.pin5; analogInputPin.configure(ANALOG_IN); // Use pin 7 as enable pin enablePin <- hardware.pin7; enablePin.configure(DIGITAL_OUT, 0); // Initialize driver class lightsensor <- APDS9007(analogInputPin, RLOAD , enablePin); // Enable sensor lightsensor.enable(true); ``` ### Response N/A (Constructor) #### Success Response (200) N/A #### Response Example N/A ``` -------------------------------- ### Get Interrupt Status Source: https://developer.electricimp.com/libraries/hardware/hts221 Checks which interrupts are active. This method should be called after an interrupt has occurred to determine the source and clear the latched interrupt. ```squirrel local intSrc = tempHumid.getInterruptStatus(); // Log if new data is available if (intSrc.humidity_data_available) server.log("New humidity data available"); if (intSrc.temp_data_available) server.log("New temperature data available"); ``` -------------------------------- ### getPointsPerReading() - Get Samples Per Reading Source: https://developer.electricimp.com/libraries/hardware/apds9007 Retrieves the number of readings (data points) internally averaged for each light level result. ```APIDOC ## getPointsPerReading() ### Description Returns the number of readings (data points) taken and internally averaged to produce a light level result. By default, this value is ten. ### Method `getPointsPerReading()` ### Endpoint N/A (Class Method) ### Parameters None ### Request Example ```javascript server.log(lightsensor.getPointsPerReading()); ``` ### Response #### Success Response (200) - **points** (number) - The number of data points averaged per reading. #### Response Example ```javascript 10 ``` ``` -------------------------------- ### LPDeviceManager Constructor Source: https://developer.electricimp.com/libraries/hardware/lp-device-manager Instantiates a new LPDeviceManager object. This class should be treated as a singleton. ```APIDOC ## LPDeviceManager(_cm[, wakeReasonCallbacks][, isDebug]_) ### Description This method returns a new LPDeviceManager instance. ### Parameters #### Path Parameters - **_cm_** (Object) - Required - An instance of ConnectionManager 3.1.0 or above - **_wakeReasonCallbacks_** (Table) - Optional - A table of optional wake reason callbacks. Default: an empty table - **_isDebug_** (Boolean) - Optional - Controls the debug output of the library. Set to `true` for extra output. Default: `false` #### Wake Reason Callbacks LPDeviceManager allows you to set code to be executed when the device wakes for a specific reason. All of the following keys are optional. Their values are callback functions that will be triggered in the event of the wake reasons for which the keys are named. - **_onColdBoot_** (Callback) - Callback to be executed on a cold boot. The callback takes no parameters - **_onSwReset_** (Callback) - Callback to be executed on a software reset. The callback takes no parameters - **_onTimer_** (Callback) - Callback to be executed after a deep sleep timer fires. The callback takes no parameters - **_onInterrupt_** (Callback) - Callback to be triggered when a wakeup pin is asserted. The callback takes no parameters - **_onPowerRestored_** (Callback) - Callback to be triggered when the imp's VBAT is powered during a cold start. The callback takes no parameters. Note: This wake reason is only available on impOS™ 40 and above - **_defaultOnWake_** (Callback) - Callback that catches all other wake reasons, and takes the impOS wake reason constant as its argument ### Request Example ```lua // Wake up on timer flow function onScheduledWake() { // Do something } // Wake up (not on timer) flow function onBoot(wakereason) { server.log("Device booted"); // Do something } local cm = ConnectionManager({"blinkupBehavior": CM_BLINK_ALWAYS}); local lpm = LPDeviceManager(cm, {"onTimer" : onScheduledWake.bindenv(this), "defaultOnWake" : onBoot.bindenv(this)}); ``` ``` -------------------------------- ### getLocation(_[options]_) API Source: https://developer.electricimp.com/libraries/hardware/bg96-gps Starts polling for location data or makes a single request for location data. Requires GNSS to be enabled. ```APIDOC ## getLocation(_[options]_) ### Description This method can be used to start polling for location data or to make a single request for location data. While most of the keys you can include in the table passed into _options_ , you **must** include _onLocation_ and a suitable callback function. This method will not enable GNSS or the BG96 modem. If GNSS is not turned on this request will return an error. ### Method `getLocation(_[options]_)` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters Parameter | Type | Required? | Description ---|---|---|--- _options_ | Table | No | Configuration options for the location request, see **Location Options**, below, for details. If no table is passed in, or a partial table is provided, default values will be used ### Location Options Key | Value Type | Description ---|---|--- _mode_ | Integer | No | Latitude and longitude display formats. See **Location Mode Values**, above, for more details. Default: 2 _poll_ | Boolean | No | If `false`, a single location request will be triggered, otherwise a location polling loop will be started. Default: `true` _waitFix_ | Boolean | No | If `true` and the modem reports it is waiting for a fix, this will not be treated as an error, otherwise an error will be issued. Default: `false` _checkFreq_ | Integer | No | If configured to poll, how often in seconds to check for fix data. Default: 1 _onLocation_ | Function | Yes | Callback to be triggered when GNSS location data is ready. This function has one parameter, a table, that may contain the keys _error_ or _fix_ ### Request Example ```json { "options": { "mode": 2, "poll": true, "waitFix": false, "checkFreq": 1, "onLocation": function(locationData) { /* handle location data */ } } } ``` ### Response #### Success Response (200) Nothing. #### Response Example ```json {} ``` ``` -------------------------------- ### Instantiate BTLEBlinkUp for imp004m Source: https://developer.electricimp.com/libraries/hardware/bt-blinkup Initialize the library for the imp004m module using the CYW_43438 firmware. ```Squirrel // For imp004m local bt = BTLEBlinkUp(serviceUUIDs, BT_FIRMWARE.CYW_43438); ``` -------------------------------- ### Instantiate the BQ24295 Source: https://developer.electricimp.com/libraries/hardware/bq24295 Initialize the I2C bus and create a BQ24295 object. The I2C bus must be pre-configured before instantiation. ```Squirrel #require "BQ24295.device.lib.nut:1.0.0" // Alias and configure an impC001 I2C bus local i2c = hardware.i2cKL; i2c.configure(CLOCK_SPEED_400_KHZ); // Instantiate a BQ24295 object batteryCharger <- BQ24295(i2c); ``` -------------------------------- ### POST /devices Source: https://developer.electricimp.com/libraries/cloudservices/losant Creates a new device on the Losant platform using the provided device information table. ```APIDOC ## POST /devices ### Description Creates a new device on the Losant platform. ### Method POST ### Parameters #### Request Body - **deviceInfo** (Table) - Required - A table containing device configuration details such as name, description, deviceClass, tags, and attributes. - **callback** (Function) - Required - A function executed when the server responds, receiving a table with statuscode, headers, and body. ### Response #### Success Response (200) - **deviceId** (String) - The unique identifier of the newly created device. ``` -------------------------------- ### Get Device ID Source: https://developer.electricimp.com/libraries/hardware/lis3dh Retrieves the one-byte device ID from the sensor's WHO_AM_I register. This is useful for verifying a correct sensor connection. ```squirrel server.log(format("Device ID: 0x%02X", accel.getDeviceId())); ``` -------------------------------- ### Get Wake Reason Description Source: https://developer.electricimp.com/libraries/hardware/lp-device-manager Retrieves a human-readable string describing the reason the imp most recently woke up. This helps in debugging wake-up events. ```javascript server.log("Wake reason: " + lpm.wakeReasonDesc()); ``` -------------------------------- ### Instantiate BTLEBlinkUp for imp006 Source: https://developer.electricimp.com/libraries/hardware/bt-blinkup Initialize the library for the imp006 module using the CYW_43455 firmware. ```Squirrel // For imp006 local bt = BTLEBlinkUp(serviceUUIDs, BT_FIRMWARE.CYW_43455); ``` -------------------------------- ### Get Device Information Source: https://developer.electricimp.com/libraries/cloudservices/losant Retrieves information for a specified Losant device ID. Requires the device ID and a callback function to handle the response. ```squirrel lsntTrackerApp.getDeviceInfo(lsntDeviceId, function(response) { server.log("Status Code: " + response.statuscode); // Log device info server.log(response.body); }); ```