outwest.dev

NodehapiMongoDBVueArchitecture

Taking Building Automation Out of the Control Program

· 10 min read

For most of this year I've been building a web dashboard for a group of large automated properties. Every one of them runs lighting, shades, fountains, fans, climate, TV and building systems through a control system, and until now, any change to how that equipment behaved meant calling a programmer.

I started the project in December 2020 and wrote the first commit. I owned the API, the data model and most of the architecture, and one other engineer worked with me on it. Eleven months later, the people who run the properties can rename a room, build a lighting scene, add a holiday schedule or move the evening lights back an hour from a browser.

This post walks through the parts I'd want to read about if I were starting a project like this, roughly in the order I ran into them.

The problem with configuration in the program

On a typical automated property, the control program holds everything. It knows which fixtures make up the "Evening" scene, which shades a keypad button moves, and what time the pool lights come on. That's fine until someone wants a change. Then a programmer has to open the project, edit it, compile it and load it onto the processor, often on site.

The staff asking for those changes weren't asking for anything complicated. They wanted the porch lights on at 6:30 instead of 7:00. They wanted the shades to close on the weekends they were away. Every request turned into a ticket and a wait.

So the core idea of the project was a split. The control program keeps doing what it's good at, which is talking to hardware. The dashboard owns the configuration, which is what the hardware should do and when, and the program reads it.

To make that work, the database and the program have to agree on what everything is called. Every fixture, shade, source, destination and touch panel in the dashboard stores its Crestron program ID next to its human-readable name. When staff build a scene in the browser, the program gets back IDs it already understands.

It also goes the other way. Touch panels report back to the dashboard over a WebSocket, so it shows what's actually happening on site, not just what was configured.

A data model for "turn the lights to 40%"

Once configuration lived in a database, the big question was how to model actions. A scene, or a scheduled event, is really a list of things to do: dim these lights to 40%, close those shades, turn on the fountain. Every type of equipment has its own controls, and the list of equipment kept growing while we built.

My first sketch had a model and a form per equipment type. That would have been dozens of forms, and every new device would have meant a new endpoint and a new screen. Neither of us wanted that.

What we built instead is a subsystem: a record that describes what one kind of equipment can do. Each subsystem has a list of attributes, and each attribute has one of three types:

  • Integer, with a minimum and a maximum, like a light level from 0 to 100.
  • Enum, with a fixed list of options, like open, closed or stop.
  • Query, which points at another collection, like "any lighting preset in this area".

Simplified, a couple of definitions look like this:

{
  key: 'area',
  name: 'Lighting area',
  attributes: [
    { key: 'level', type: 'integer', min: 0, max: 100 },
    { key: 'preset', type: 'query', collection: 'lightingPresets' },
  ],
}

{
  key: 'water',
  name: 'Water feature',
  attributes: [
    { key: 'state', type: 'enum', options: ['on', 'off'] },
  ],
}

Macros and events are then just lists of steps, and every step has the same shape no matter what it controls:

{ subsystem: 'area', attribute: 'level', value: 40, target: '<area id>' }

The API validates each definition by its type before saving it, so a min that's bigger than its max, or a query that points at a collection that doesn't exist, never gets as far as an event.

The payoff came later in the year. When climate control was added to the project, it was a new subsystem with a few attributes, not a new feature. The UI picked it up without a single new screen.

Scheduling in someone else's timezone

I underestimated this part. "Turn on the landscape lights at 7pm" sounds simple, but the properties aren't all in one timezone, the server is in another, and the person editing the schedule might be travelling.

Each property record stores its location: latitude, longitude and timezone. From there, we followed one rule everywhere. Times are stored in UTC, and they're entered and displayed in the property's timezone, never the browser's or the server's.

When an event is saved, the API looks up the property and converts the local time it was given:

const property = await Property.findById(payload.property)
const startsAt = toUtc(payload.startsAt, property.timezone)

When the calendar loads, every event goes back through the same conversion in the other direction before it's sent. Nobody using the dashboard ever sees UTC.

Storing the property's location turned out to matter even more than storing its timezone, because staff wanted exterior lights to follow the sun, not the clock. An event can be tied to sunrise or sunset in place of a fixed time, and the time is worked out from the property's coordinates for each day. The lights come on earlier in winter without anyone touching the schedule.

On top of that we added:

  • Repeat by day of the week, with start and end dates for seasonal schedules.
  • Lifestyles, which are named modes a property can be in, like occupied or away, so an event only runs in the modes it's meant for.
  • A calendar view, because that's how staff already think about a week.

Because every one of these goes through the same conversion, none of them needed their own timezone handling.

Thirty screens, three components

By the end of the project, the dashboard had more than thirty screens: properties, areas, zones, lighting fixtures and presets, shades, sources, destinations, switchers, TV tuners and channel lineups, water, fans, BACnet points, macros, events, users, logs and a few more. Most of them are a table and a form.

The front end is Vue 2, and rather than build thirty tables and thirty forms, we built three components:

  • A table that handles server-side paging, sorting, search and filters. A page tells it which columns to show and which endpoint to call.
  • A form that renders inputs from a list (text, number, select, multi-select), loads any options a field needs, like the list of areas for a dropdown, and maps validation errors from the API back onto the right field.
  • A step builder for macros and events. It reads the subsystem definition and renders a number input for an integer, a dropdown for an enum, or a live search for a query.

Shared behavior lives in mixins, so a typical screen is mostly configuration:

export default {
  mixins: [resourceList],
  data: () => ({
    endpoint: '/fixtures',
    columns: [
      { key: 'name', label: 'Name', sortable: true },
      { key: 'programId', label: 'Program ID', sortable: true },
      { key: 'area.name', label: 'Area' },
    ],
    filters: ['area', 'zone'],
  }),
}

The best part was how fixes spread. When we added a clone button to the table, every screen had one the same afternoon.

Why hapi

For the API I picked hapi over Express. The main reason was that hapi wants you to describe a route, not just handle it. Validation, auth, response shape and docs all sit in the route definition, so everything about an endpoint is in one place:

{
  method: 'POST',
  path: '/events',
  options: {
    tags: ['api'],
    auth: { scope: ['admin', 'facilities'] },
    validate: { payload: Event.createSchema },
    response: { schema: Event.responseSchema },
    handler: (request) =>
      request.server.methods.events.create(request.payload, request.auth.credentials),
  },
}

That definition does a lot of work:

  • Joi checks the request and the response. Bad input is rejected before the handler runs, and a response that doesn't match its schema fails in tests, not in front of a user.
  • Swagger docs come from the routes, so the docs can't drift from the real API.
  • Errors all have the same shape. Validation errors, database errors and missing records all come back with the same status code, error and message fields, so the front end only handles errors one way.
  • Handlers are thin. The logic lives in server methods, so the same code serves the API and the exportable reports.

The whole server, with its plugins, models and route groups, is put together from one manifest, which made it easy to see what was running.

We also wrote tests for every resource from the start, with factories for realistic fake data and a fresh database for each run. It felt slow in the first month. By the summer it was the reason we could change the data model without being nervous about it.

Access and the change log

Different staff need different access, so every user has a scope, from admin down to the people who run a property day to day. Every route lists the scopes that can call it, as in the example above, and hapi checks it before the handler runs. Each request also checks that the token's user still exists, so removing someone locks them out right away, not when their token expires.

Property staff also needed to know who changed what. I didn't want to add logging to every handler and hope nobody forgot one, so it's a single server extension that runs before every response:

server.ext('onPreResponse', async (request, h) => {
  await AuditLog.create({
    method: request.method,
    path: request.path,
    user: request.auth.credentials?.id,
    payload: request.payload,
    params: request.params,
    status: request.response.statusCode ?? request.response.output?.statusCode,
    ip: request.info.remoteAddress,
  })
  return h.continue
})

The logs page in the dashboard reads straight from this. Records expire after 30 days through a TTL index, so the collection never grows out of control:

auditLogSchema.index({ createdAt: 1 }, { expireAfterSeconds: 60 * 60 * 24 * 30 })

Living with MongoDB

We used MongoDB, and for this data it fit well. An event and its steps, a subsystem and its attributes, a macro and its actions are always read together, so they're stored together. There are no join tables for lists that only ever belong to one parent.

What MongoDB doesn't do is look after relationships, and with equipment on the other end, a broken reference is a real problem. These are the rules we added ourselves:

  • Check every ID. Any ID in a request is validated as an object ID before it gets near a query.
  • Clean up on delete. Model hooks remove references when a linked record is deleted. Deleting a TV channel takes it out of every lineup and preset that used it.
  • Sort IDs the way people read them. Device and program IDs are stored as strings so they can be searched, which means a plain sort puts device 10 before device 9. Every list query uses numeric collation to fix that:
    Fixture.find(query)
      .collation({ locale: 'en', numericOrdering: true })
      .sort({ programId: 1 })
    
  • Only populate when asked. List endpoints return flat records unless the client asks for related names, which keeps the big lists fast.

None of these were in the first version. Each one went in after we'd hit the problem it fixes at least once.

Where it ended up

After eleven months, the dashboard handles lighting and shade presets, macros, sunrise and sunset schedules, TV lineups from a listings provider, building system points, touch panel logs, a full change log, role-based access and exportable reports. The people who run the properties manage all of it themselves.

If I had to pick one thing to take into the next project, it's the first decision: work out what the people using the system actually change, and make sure they can change it without a developer. Most of the rest followed from that.