Interfacing with external hardware

In the previous section, we were talking about how the client communicates with the server in order to get the latest readings about the temperature and humidity. In this section, we are going to discuss how the server gets these readings in the first place.

If you were using a regular old laptop or computer, you would be hard pressed to find a way to measure the world outside directly. You would either need to get a pre-assembled USB device, or you would have to be smart enough to mess around with the computer circuitry. Either way, none of these are pragmatic.

The Raspberry Pi, however, excels in this area. One of its key features is its GPIO pins:

These pins allow us to directly connect any sensor and read its output. This is done through native system calls, which are exposed through convenient command-line utilities (which we will be discussing in detail in the later chapters). Our server can make these calls, read their output, and pass on the result to the client-side application. In this way, the server layer acts as a middleman between the sensor and client-side interfaces (hence the name middleware)

It is possible that the language we write our server in could be different from the language that is used to interface with some sensors. For example, the DTH11 temperature and humidity sensors have good support in Python libraries, but not much else. In this situation, in order to make communication between the server program and the sensor program easier, we can use two different methods.

The first method involves communication through subprocesses. The server, which is a process itself, spawns the sensor process as its own child process. It gives input to this child process and receives any of the output.

The downside of this is that the sensor service is entirely within the Server application, which means that any other application will not be able to make use of it unless the server allows it to (through its APIs).

If we want our sensor service to be available to other applications as well, an alternative approach is to have it occupy another port and communicate with other services through its own APIs:

The Sensor application is now its own server. This way, it is now open to be reused by any other application through its APIs. The trade-off is that it takes additional resources and occupies another port. Additionally, it's much simpler to write a simple program that gives us output as STDOUT rather than a full-fledged server. In our application, we are going to use the first method because we only need to have the server communicating with the sensor, but you can expand into the second method if your architecture gets more complex.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.137.220.120