While waiting for the parts from china to arrive, I started to build the main software for my raspberry pi. I wanted to write it in Java, so I started by using the bundled http server com.sun.net.httpserver.HttpServer. With this, it is really simple to get a simple server up and running, but for my needs it was not stable enough. So I moved on to apache tomcat, combined with an apache derby database. The application is split into four parts. One part are the servlets, which allow the program to answer requests from other devices. These requests can be:
- data to be stored as an event in the database (e.g. a PIR detected some motion)
- a command to perform some action (e.g. turn on lights in room X)
- a request to get some data (current status of the lights in room X)
Each request contains a room id, a command/event type (e.g. light, motion, ...) and an optional value.
This leads to the next part, the database. As mentioned above, it is implemented by using apache derby. Each event type is stored in its own table, combined with the room id of the room it occurred in and a timestamp. To deliver the requested data, the newest entry with matching room id in the corresponding table is selected.
Because the database keeps every event with its timestamp, it is possible to visualize the data over a specific time period (e.g. a diagram of the temperature in a room), but this is not implemented yet.
The third important part is the logic to perform actions. Because every room has different actors, each gets its own room handler. Each handler implements a common interface, so the parameters from the command request can be passed to the corresponding handler. The actual commands are executed by sending http requests to the corresponding esp. This already works with my servo lightswitch.
Because there are tasks, which are independent from server requests (e.g. ping my smartphone and trigger events when I leave/arrive), I added a class which runs parallel to the server, but in the same JVM. To achieve this, the class implements the ServletContextListener interface, so it starts and ends with the main app and it can share the same in memory database.
As interface for me to this system, I made a simple webapp, which is also hosted on tomcat and is served as static content, so it is independent from the main war file.