liveBook · Manning

Sensor API

As explained in Functional Design and Architecture: Examples in Haskell

A sensor API is the interface for reading measurements and otherwise interacting with a device sensor.

A sensor API is a service handle for interacting with native device sensors without exposing vendor-specific implementation details. The interface groups operations such as resetting a sensor, reading a measurement, and registering a callback. section 4.2.5 section 3.3.3

A Device can store a SensorAPI handler inside a vendor-specific sensor component. The client asks for a device part and invokes the sensor operation through the handler rather than depending on the vendor implementation. section 4.2.5 section 3.3.3

The interface currently exposes three operations:

  • reset performs sensor initialization or reset work through IO. section 4.2.5
  • readMeasurement obtains one Measurement value from the sensor. section 4.2.5
  • setCallback accepts a Period and an IO action for callback-based measurement handling. section 4.2.5

Reading a thermometer

A boosters device contains a thermometer at "nozzle1-t". Client code retrieves that part, passes it to withHandler, and verifies that readMeasurement returns Measurement Temperature 100.0. The test uses the SensorAPI contract while avoiding direct pattern matching on DevicePart internals. section 4.2.5 section 4.2.5

Directly unpacking DevicePart and extracting its handler works, but it violates the rule against interacting with internals directly. withHandler provides a safer boundary: SensorAPI and ControllerAPI each define how their matching component exposes a handler, while invalid component/API combinations fail explicitly. section 4.2.5 section 4.2.5

data SensorAPI = SensorAPI
 { reset           :: IO ()
 , readMeasurement :: IO Measurement
 , setCallback     :: Period -> IO Measurement -> IO ()
 }

Use the compact declaration to inspect the SensorAPI contract and its IO-based operations. section 4.2.5

How Functional Design and Architecture: Examples in Haskell covers it

How deep it goes
Defines three operations and demonstrates handler access and testing, while deferring a better domain redesign.
Examples
Uses a boosters thermometer, the "nozzle1-t" component index, a vendor handler, and a 100.0-temperature measurement assertion.
What it assumes
Assumes familiarity with Device and DevicePart, while introducing service handles, vendor handlers, and typed access patterns.
What you can do after
Apply it via SensorAPI to read measurements while preserving the Device abstraction and testing through a handler boundary.
How it connects
Connects service handles with Device, DevicePart, vendor components, abstract data types, and type classes.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Functional Design and Architecture: Examples in Haskell. The section links point to the parts of the book it draws on.