### STN1110: Execute AT Command (Squirrel) Source: https://github.com/electricimp/stn1110/blob/master/README.md This example shows how to use the STN1110 class to execute a low-level AT command (AT@1) and log the device description string returned by the command. It includes error handling for command execution. ```squirrel stn1110 <- STN1110(hardware.uart57) stn1110.execute("AT@1", 1, function(result) { // AT@1 command returns device description string if ("err" in result) { server.error("Error executing command") return } server.log("Device description: " + result["msg"]) }) ``` -------------------------------- ### STN1110 Class: Get ELM Version Source: https://context7.com/electricimp/stn1110/llms.txt Returns the ELM emulator version string that the STN1110 reported during initialization or last reset. ```squirrel stn1110 <- STN1110(hardware.uart57) local version = stn1110.getElmVersion() server.log("ELM Version: " + version) ``` -------------------------------- ### STN1110 Class: Get Current Baud Rate Source: https://context7.com/electricimp/stn1110/llms.txt Returns the current UART baud rate being used for communication with the STN1110. ```squirrel stn1110 <- STN1110(hardware.uart57) local baud = stn1110.getBaudRate() server.log("Current baud rate: " + baud) ``` -------------------------------- ### Initialize VehicleInterface and Access PID Constants Source: https://context7.com/electricimp/stn1110/llms.txt Demonstrates how to instantiate the VehicleInterface class using a hardware UART port and lists the available built-in PID constants for common vehicle metrics. ```squirrel car <- VehicleInterface(hardware.uart57); // Available PID constants: // car.ENGINE_RPM // car.VEHICLE_SPEED // car.THROTTLE_POSITION // car.COOLANT_TEMPERATURE // car.FUEL_PRESSURE // car.INTAKE_AIR_TEMPERATURE // car.ENGINE_RUNTIME ``` -------------------------------- ### VehicleInterface Class - Constructor Source: https://github.com/electricimp/stn1110/blob/master/README.md Instantiates the VehicleInterface class, configuring a specified UART for communication with the STN1110. Optionally sets a custom baud rate. ```APIDOC ## VehicleInterface Class Usage ## ### Constructor(*uart[, baud]*) ### To instantiate the class, pass in the [imp UART](https://developer.electricimp.com/api/hardware/uart/) that the STN1110 is connected to. The UART will be reconfigured by the constructor for communication with the STN1110. This is a blocking call that will return when the STN1110 interface is ready to use. This method may throw an exception if initializing the device fails or times out. The optional baud parameter can be used for initial connection if the STN1110 has a baud rate other than the default 9600 stored in its EEPROM. ``` -------------------------------- ### STN1110 Class - Constructor Source: https://github.com/electricimp/stn1110/blob/master/README.md Initializes the STN1110 class by configuring a specified UART for communication. Supports an optional baud rate for initial connection. ```APIDOC ## STN1110 Class Usage ## ### Constructor(*uart[, baud]*) ### To instantiate the class, pass in the [imp UART](https://developer.electricimp.com/api/hardware/uart/) that the STN1110 is connected to. The UART will be reconfigured by the constructor for communication with the STN1110. This is a blocking call that will return when the STN1110 interface is ready to use. This method may throw an exception if initializing the device fails or times out. The optional baud parameter can be used for initial connection if the STN1110 has a baud rate other than the default 9600 stored in it's EEPROM. ``` -------------------------------- ### VehicleInterface Class: Initialize High-Level Interface Source: https://context7.com/electricimp/stn1110/llms.txt Creates a new VehicleInterface instance extending STN1110 with high-level vehicle data access. Initializes UART communication and sets up data transformations for supported PIDs. ```squirrel car <- VehicleInterface(hardware.uart57) server.log("Vehicle interface initialized") ``` -------------------------------- ### VehicleInterface: Log Vehicle Speed (Squirrel) Source: https://github.com/electricimp/stn1110/blob/master/README.md This snippet demonstrates how to use the VehicleInterface class to subscribe to and log the vehicle's speed every second. It handles potential errors during data retrieval and logs the current speed in km/h. ```squirrel car <- VehicleInterface(hardware.uart57); // logs vehicle speed once per second car.subscribe(car.VEHICLE_SPEED, function(result) { if ("err" in result) { server.error("Error getting vehicle speed"); return; } server.log("Current speed: " + result["msg"] + "km/h") }, 1); ``` -------------------------------- ### STN1110 Constructor: Initialize UART Communication Source: https://context7.com/electricimp/stn1110/llms.txt Creates a new STN1110 instance by initializing UART communication with the STN1110 chip. This is a blocking call that configures the UART, resets the device, and disables echo mode. An exception is thrown if initialization fails or times out. ```squirrel stn1110 <- STN1110(hardware.uart57) stn1110 <- STN1110(hardware.uart57, 115200) ``` -------------------------------- ### STN1110 Class: Execute AT/OBD-II Commands Source: https://context7.com/electricimp/stn1110/llms.txt Executes an arbitrary AT or OBD-II command string with a specified timeout and callback. Commands are queued and executed in order. The callback receives a table with either an 'err' key (on error/timeout) or a 'msg' key containing the response. ```squirrel stn1110 <- STN1110(hardware.uart57) stn1110.execute("AT@1", 1, function(result) { if ("err" in result) { server.error("Error executing command: " + result["err"]) return } server.log("Device description: " + result["msg"]) }) stn1110.execute("010C", 1, function(result) { if ("err" in result) { server.error("Error: " + result["err"]) return } server.log("Raw RPM response: " + result["msg"]) }) ``` -------------------------------- ### STN1110 Class - execute() Source: https://github.com/electricimp/stn1110/blob/master/README.md Executes a given command string on the STN1110 with a specified timeout. The result is returned via a callback function, indicating success with a message or failure with an error description. ```APIDOC ### STN1110.execute(*command, timeout, callback*) ### Executes the command string *command* with timeout *timeout* seconds and calls *callback* with the result. Callback is called with one parameter that is a table containing either an *err* key or a *msg* key. If the *err* key is present in the table an error occured during command execution and the corresponding value describes the error. If the *err* key is not present in the table the *msg* value will contain the output of the command. ``` -------------------------------- ### Subscribe to PID Updates Source: https://context7.com/electricimp/stn1110/llms.txt Subscribes to a PID value, reading it at regular intervals and calling a callback function with each result. The subscription continues until explicitly unsubscribed. ```APIDOC ## subscribe Subscribes to a PID value, reading it at regular intervals and calling the callback with each result. The callback continues to be called every `period` seconds until unsubscribed. ### Method `subscribe` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```squirrel car <- VehicleInterface(hardware.uart57) // Subscribe to vehicle speed, reading every 1 second car.subscribe(car.VEHICLE_SPEED, function(result) { if ("err" in result) { server.error("Error getting vehicle speed") return } server.log("Current speed: " + result["msg"] + " km/h") }, 1) // Subscribe to engine RPM, reading every 2 seconds car.subscribe(car.ENGINE_RPM, function(result) { if ("err" in result) { server.error("Error getting RPM") return } server.log("Engine RPM: " + result["msg"]) }, 2) // Subscribe to multiple parameters for dashboard display car.subscribe(car.THROTTLE_POSITION, function(result) { if (!("err" in result)) { server.log("Throttle: " + result["msg"] + "%") } }, 1) car.subscribe(car.COOLANT_TEMPERATURE, function(result) { if (!("err" in result)) { server.log("Coolant: " + result["msg"] + "°C") } }, 5) ``` ### Response #### Success Response (200) - **msg** (string) - The PID value, automatically converted to appropriate units. - **err** (string, optional) - An error message if the read operation failed. #### Response Example ```json { "msg": "65" } ``` ```json { "err": "Failed to subscribe to PID" } ``` ``` -------------------------------- ### VehicleInterface Class - subscribe() Source: https://github.com/electricimp/stn1110/blob/master/README.md Periodically reads a specified OBD-II PID at a given interval and executes a callback with the data. Supports both supported PIDs with unit conversion and raw data for unsupported PIDs. ```APIDOC ### subscribe(*pid, callback, period*) ### Reads a PID every 'period' seconds and executes callback with the resulting data. If the PID is in the list of supported PIDs, the callback will be called with a single value in the correct units. If the PID is not supported the callback will be called with a byte array containing the raw result of the request. ``` -------------------------------- ### VehicleInterface Class - Supported PIDs Source: https://github.com/electricimp/stn1110/blob/master/README.md Lists the predefined OBD-II PIDs supported by the VehicleInterface class, along with their units. ```APIDOC #### Supported PIDs #### - *VehicleInterface.ENGINE_RPM* — The engine's RPM in units RPM. - *VehicleInterface.VEHICLE_SPEED* — Get the vehicle speed in units km/h. - *VehicleInterface.THROTTLE_POSITION* — The throttle position as a percentage. - *VehicleInterface.COOLANT_TEMPERATURE* — The engine coolant temperature in degrees celsius. - *VehicleInterface.FUEL_PRESSURE* — The fuel pressure in kPa. - *VehicleInterface.INTAKE_AIR_TEMPERATURE* — The intake air temperature in degrees celsius. - *VehicleInterface.ENGINE_RUNTIME* — The runtime since engine start in minutes. ``` -------------------------------- ### Subscribe to Periodic PID Updates Source: https://context7.com/electricimp/stn1110/llms.txt Uses the subscribe method to poll a PID at a specified interval in seconds. The provided callback is executed repeatedly until the subscription is cancelled. ```squirrel car.subscribe(car.VEHICLE_SPEED, function(result) { if ("err" in result) { server.error("Error getting vehicle speed"); return; } server.log("Current speed: " + result["msg"] + " km/h"); }, 1); ``` -------------------------------- ### VehicleInterface Class - read() Source: https://github.com/electricimp/stn1110/blob/master/README.md Reads a specified OBD-II PID once and returns the data via a callback function. If the PID is supported, it returns the value in correct units; otherwise, it returns raw byte data. ```APIDOC ### read(*pid, callback*) ### Reads a PID once and executes callback with the resulting data. If the PID is in the list of supported PIDs, the callback will be called with a single value in the correct units. If the PID is not supported the callback will be called with a byte array containing the raw result of the request. ``` -------------------------------- ### STN1110 Class: Register Global Error Handler Source: https://context7.com/electricimp/stn1110/llms.txt Registers a callback function to handle errors that occur after initialization when no command callback is available to receive the error. ```squirrel stn1110 <- STN1110(hardware.uart57) stn1110.onError(function(errorMessage) { server.error("STN1110 Error: " + errorMessage) }) ``` -------------------------------- ### Log Vehicle Data with BatchLogger in Squirrel Source: https://context7.com/electricimp/stn1110/llms.txt This Squirrel code defines a BatchLogger class to collect multiple vehicle parameters (like RPM, speed, temperature) and send them together to an agent. It subscribes to various vehicle data points and updates them at a specified interval, handling asynchronous updates and ensuring all data is logged before sending. ```squirrel // BatchLogger class - collects multiple PID values and sends them together class BatchLogger { _log = null _logUpdated = null constructor() { this._log = {} this._logUpdated = {} } // Returns a callback function for a specific parameter function subscribe(key) { _logUpdated[key] <- false return (function(value) { if (!("err" in value)) { this._log[key] <- value["msg"] } this._logUpdated[key] = true this._checkAndLog() }).bindenv(this) } // Check if all parameters updated, then send to agent function _checkAndLog() { foreach(k, v in _logUpdated) { if (v == false) { return } } agent.send("log", _log) foreach(k, v in _logUpdated) { _logUpdated[k] = false } } } // Initialize vehicle interface and logger car <- VehicleInterface(hardware.uart57) logger <- BatchLogger() // Subscribe to all vehicle parameters, updating every 5 seconds car.subscribe(car.ENGINE_RPM, logger.subscribe("rpm"), 5) car.subscribe(car.VEHICLE_SPEED, logger.subscribe("speed"), 5) car.subscribe(car.THROTTLE_POSITION, logger.subscribe("throttle"), 5) car.subscribe(car.ENGINE_RUNTIME, logger.subscribe("runtime"), 5) car.subscribe(car.COOLANT_TEMPERATURE, logger.subscribe("coolant_temp"), 5) car.subscribe(car.INTAKE_AIR_TEMPERATURE, logger.subscribe("intake_temp"), 5) car.subscribe(car.FUEL_PRESSURE, logger.subscribe("fuel_pressure"), 5) // Expected output every 5 seconds (sent to agent): // { // "rpm": 2500, // "speed": 65, // "throttle": 25, // "runtime": 1800, // "coolant_temp": 90, // "intake_temp": 35, // "fuel_pressure": 300 // } ``` -------------------------------- ### Supported PIDs Source: https://context7.com/electricimp/stn1110/llms.txt Lists the built-in supported OBD-II PIDs available through the VehicleInterface, including their units. ```APIDOC ## Supported PIDs VehicleInterface includes built-in support for common OBD-II PIDs with automatic unit conversion. ```squirrel car <- VehicleInterface(hardware.uart57) // Available PID constants: // car.ENGINE_RPM - Engine RPM (units: RPM) // car.VEHICLE_SPEED - Vehicle speed (units: km/h) // car.THROTTLE_POSITION - Throttle position (units: percentage 0-100) // car.COOLANT_TEMPERATURE - Engine coolant temperature (units: degrees Celsius) // car.FUEL_PRESSURE - Fuel pressure (units: kPa) // car.INTAKE_AIR_TEMPERATURE - Intake air temperature (units: degrees Celsius) // car.ENGINE_RUNTIME - Engine runtime since start (units: seconds) ``` ``` -------------------------------- ### STN1110 Class: Reset Device Source: https://context7.com/electricimp/stn1110/llms.txt Performs a soft reset of the STN1110 device. This is a blocking call that sends the ATZ command, waits for the device to be ready, and disables echo mode. Throws an exception if the reset fails or times out. ```squirrel stn1110 <- STN1110(hardware.uart57) try { stn1110.reset() server.log("STN1110 reset successful") } catch (error) { server.error("Reset failed: " + error) } ``` -------------------------------- ### STN1110 Class - reset() Source: https://github.com/electricimp/stn1110/blob/master/README.md Performs a soft reset of the STN1110 device. This is a blocking operation that returns once the device is ready. ```APIDOC ### reset() ### Performs a soft reset of the STN1110. This is a blocking call that will return when the STN1110 interface is ready to use. This method may throw an exception if initializing the device fails or times out. ``` -------------------------------- ### Read OBD-II PID Values Once Source: https://context7.com/electricimp/stn1110/llms.txt Uses the read method to fetch a single PID value. The callback function receives a result object containing either the converted value or an error message. ```squirrel car.read(car.ENGINE_RPM, function(result) { if ("err" in result) { server.error("Error reading RPM: " + result["err"]); return; } server.log("Engine RPM: " + result["msg"]); }); ``` -------------------------------- ### VehicleInterface Class - unsubscribe() Source: https://github.com/electricimp/stn1110/blob/master/README.md Stops the periodic reading of a specified OBD-II PID, effectively unsubscribing from updates. ```APIDOC ### unsubcribe(*pid*) ### Unsubscribes the callback, if any, for PID *pid* and stops requesting the PID. ``` -------------------------------- ### STN1110 Class: Change Baud Rate Source: https://context7.com/electricimp/stn1110/llms.txt Changes the UART baud rate for communication with the STN1110. This is a blocking call that configures both the STN1110 and the imp UART to the new rate. Throws an exception if commands are currently executing, the baud rate is invalid, or the change fails. ```squirrel stn1110 <- STN1110(hardware.uart57) try { stn1110.setBaudRate(115200) server.log("Baud rate changed to 115200") } catch (error) { server.error("Failed to change baud rate: " + error) } ``` -------------------------------- ### Read PID Value Source: https://context7.com/electricimp/stn1110/llms.txt Reads a specific OBD-II Parameter ID (PID) value once and executes a callback function with the result. Automatic unit conversion is applied for supported PIDs. ```APIDOC ## read Reads a PID value once and executes the callback with the transformed result. For supported PIDs, the value is automatically converted to the appropriate units. ### Method `read` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```squirrel car <- VehicleInterface(hardware.uart57) // Read engine RPM once car.read(car.ENGINE_RPM, function(result) { if ("err" in result) { server.error("Error reading RPM: " + result["err"]) return } server.log("Engine RPM: " + result["msg"]) }) // Read vehicle speed once car.read(car.VEHICLE_SPEED, function(result) { if ("err" in result) { server.error("Error reading speed") return } server.log("Vehicle speed: " + result["msg"] + " km/h") }) // Read coolant temperature once car.read(car.COOLANT_TEMPERATURE, function(result) { if ("err" in result) { server.error("Error reading temperature") return } server.log("Coolant temp: " + result["msg"] + "°C") }) ``` ### Response #### Success Response (200) - **msg** (string) - The PID value, automatically converted to appropriate units. - **err** (string, optional) - An error message if the read operation failed. #### Response Example ```json { "msg": "2500" } ``` ```json { "err": "Unable to retrieve PID" } ``` ``` -------------------------------- ### Unsubscribe from PID Updates Source: https://context7.com/electricimp/stn1110/llms.txt Stops the periodic reading of a previously subscribed PID. Note that the method name in the library is 'unsubcribe' (missing an 's'). ```squirrel car.subscribe(car.VEHICLE_SPEED, function(result) { server.log("Speed: " + result["msg"] + " km/h"); }, 1); // Stop receiving updates car.unsubcribe(car.VEHICLE_SPEED); ``` -------------------------------- ### Unsubscribe from PID Updates Source: https://context7.com/electricimp/stn1110/llms.txt Stops the periodic reading of a PID and removes its associated callback function. Note: The method name has a typo in the original library (missing 's'). ```APIDOC ## unsubcribe Stops the periodic reading of a PID and removes its callback. Note: The method name has a typo in the original library (missing 's'). ### Method `unsubcribe` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```squirrel car <- VehicleInterface(hardware.uart57) // Subscribe to speed updates car.subscribe(car.VEHICLE_SPEED, function(result) { server.log("Speed: " + result["msg"] + " km/h") }, 1) // Later, stop receiving speed updates car.unsubcribe(car.VEHICLE_SPEED) server.log("Unsubscribed from vehicle speed") ``` ### Response #### Success Response (200) Indicates that the unsubscription request was processed successfully. No specific data is returned. #### Response Example (No specific response body for success, typically an acknowledgement or no response) #### Error Response - **err** (string) - An error message if the unsubscription failed (e.g., PID not subscribed). ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.