Build your own home automation system with Raspberry PI, NodeJS & MS-GPIO

Hi guys, I hope you all are doing well. Today I’m excited to present my first IOT adventure (smarthome) with you.

Why this post ?

I have worked on complete documentation of the Smarthome project, which will guide in building your own home automation system.
Smarthome project, is now available on github. This project contains both code and technical documentation (including circuit diagram). It will definitely help you to get started with your own IOT quest.

Code and Design Document :

Technical Documentation :

You can play with smarthome project, by cloning or downloading the code from github:

Working Demo :

Cayenne Low Power Payload


The Cayenne Low Power Payload (LPP) provides a convenient and easy way to send data over LPWAN networks such as LoRaWAN. The Cayenne LPP is compliant with the payload size restriction, which can be lowered down to 11 bytes, and allows the device to send multiple sensor data at one time.

Additionally, the Cayenne LPP allows the device to send different sensor data in different frames. In order to do that, each sensor data must be prefixed with two bytes:

  • Data Channel: Uniquely identifies each sensor in the device across frames, eg. “indoor sensor”
  • Data Type: Identifies the data type in the frame, eg. “temperature”.

Payload structure

1 Byte1 ByteN Bytes1 Byte1 ByteM Bytes
Data1 Ch.Data1 TypeData1Data2 Ch.Data2 TypeData2

Data Types

Data Types conform to the IPSO Alliance Smart Objects Guidelines, which identifies each data type with an “Object ID”. However, as shown below, a conversion is made to fit the Object ID into a single byte.


Each data type can use 1 or more bytes to send the data according to the following table.

TypeIPSOLPPHexData SizeData Resolution per bit
Digital Input32000011
Digital Output32011111
Analog Input32022220.01 Signed
Analog Output32033320.01 Signed
Illuminance Sensor33011016521 Lux Unsigned MSB
Presence Sensor33021026611
Temperature Sensor33031036720.1 °C Signed MSB
Humidity Sensor33041046810.5 % Unsigned
Accelerometer33131137160.001 G Signed MSB per axis
Barometer33151157320.1 hPa Unsigned MSB
Gyrometer33341348660.01 °/s Signed MSB per axis
GPS Location3336136889Latitude : 0.0001 ° Signed MSB
Longitude : 0.0001 ° Signed MSB
Altitude : 0.01 meter Signed MSB


Device with 2 temperature sensors

Payload (Hex)03 67 01 10 05 67 00 FF
Data ChannelTypeValue
03 ⇒ 367 ⇒ Temperature0110 = 272 ⇒ 27.2°C
05 ⇒ 567 ⇒ Temperature00FF = 255 ⇒ 25.5°C

Device with temperature and acceleration sensors

Frame N

Payload (Hex)01 67 FF D7
Data ChannelTypeValue
01 ⇒ 167 ⇒ TemperatureFFD7 = -41 ⇒ -4.1°C

Frame N+1

Payload (Hex)06 71 04 D2 FB 2E 00 00
Data ChannelTypeValue
06 ⇒ 671 ⇒ AccelerometerX: 04D2 = +1234 ⇒ +1.234G
Y: FB2E = -1234 ⇒ -1.234G
Z: 0000 = 0 ⇒ 0G

Device with GPS

Payload (Hex)01 88 06 76 5f f2 96 0a 00 03 e8
Data ChannelTypeValue
01 ⇒ 188 ⇒ GPSLatitude: 06765f ⇒ 42.3519
Longitude: F2960a ⇒ -87.9094
Altitude: 0003E8 ⇒ 10 meters

Source : https://github.com/myDevicesIoT/cayenne-docs/blob/master/docs/LORA.md#lora-cayenne-low-power-payload-data-types

LoRaWAN End Devices

End Devices

The LoRaWAN specification defines three device types. All LoRaWAN devices must implement Class A, whereas Class B and Class C are extensions to the specification of Class A devices.

Class A devices support bi-directional communication between a device and a gateway. Uplink messages (from the device to the server) can be sent at any time (randomly). The device then opens two receive windows at specified times (1s and 2s) after an uplink transmission. If the server does not respond in either of these receive windows (situation 1 in the figure), the next opportunity will be after the next uplink transmission from the device. The server can respond either in the first receive window, or in the second receive window, but should not use both windows.

Class A Receive Windows

Class B devices extend Class A by adding scheduled receive windows for downlink messages from the server. Using time-synchronized beacons transmitted by the gateway, the devices periodically open receive windows.

Class C devices extend Class A by keeping the receive windows open unless they are transmitting, as shown in the figure below. This allows for low-latency communication but is many times more energy consuming than Class A devices.

OSI Model


Layer 1: Physical Layer

The physical layer is responsible for the transmission and reception of unstructured raw data between a device and a physical transmission medium. It converts the digital bits into electrical, radio, or optical signals. Layer specifications define characteristics such as voltage levels, the timing of voltage changes, physical data rates, maximum transmission distances, modulation scheme, channel access method and physical connectors. This includes the layout of pinsvoltages, line impedance, cable specifications, signal timing and frequency for wireless devices. Bit rate control is done at the physical layer and may define transmission mode as simplexhalf duplex, and full duplex. The components of a physical layer can be described in terms of a network topologyBluetoothEthernet, and USB all have specifications for a physical layer.

Layer 2: Data Link Layer

The data link layer provides node-to-node data transfer—a link between two directly connected nodes. It detects and possibly corrects errors that may occur in the physical layer. It defines the protocol to establish and terminate a connection between two physically connected devices. It also defines the protocol for flow control between them.

IEEE 802 divides the data link layer into two sublayers:[7]

  • Medium access control (MAC) layer – responsible for controlling how devices in a network gain access to a medium and permission to transmit data.
  • Logical link control (LLC) layer – responsible for identifying and encapsulating network layer protocols, and controls error checking and frame synchronization.

The MAC and LLC layers of IEEE 802 networks such as 802.3 Ethernet802.11 Wi-Fi, and 802.15.4 ZigBee operate at the data link layer.

The Point-to-Point Protocol (PPP) is a data link layer protocol that can operate over several different physical layers, such as synchronous and asynchronous serial lines.

The ITU-T G.hn standard, which provides high-speed local area networking over existing wires (power lines, phone lines and coaxial cables), includes a complete data link layer that provides both error correction and flow control by means of a selective-repeat sliding-window protocol.

Layer 3: Network Layer

The network layer provides the functional and procedural means of transferring variable length data sequences (called packets) from one node to another connected in “different networks”. A network is a medium to which many nodes can be connected, on which every node has an address and which permits nodes connected to it to transfer messages to other nodes connected to it by merely providing the content of a message and the address of the destination node and letting the network find the way to deliver the message to the destination node, possibly routing it through intermediate nodes. If the message is too large to be transmitted from one node to another on the data link layer between those nodes, the network may implement message delivery by splitting the message into several fragments at one node, sending the fragments independently, and reassembling the fragments at another node. It may, but does not need to, report delivery errors.

Message delivery at the network layer is not necessarily guaranteed to be reliable; a network layer protocol may provide reliable message delivery, but it need not do so.

A number of layer-management protocols, a function defined in the management annex, ISO 7498/4, belong to the network layer. These include routing protocols, multicast group management, network-layer information and error, and network-layer address assignment. It is the function of the payload that makes these belong to the network layer, not the protocol that carries them.[8]

Layer 4: Transport Layer

The transport layer provides the functional and procedural means of transferring variable-length data sequences from a source to a destination host, while maintaining the quality of service functions.

The transport layer controls the reliability of a given link through flow control, segmentation/desegmentation, and error control. Some protocols are state- and connection-oriented. This means that the transport layer can keep track of the segments and re-transmit those that fail delivery. The transport layer also provides the acknowledgement of the successful data transmission and sends the next data if no errors occurred. The transport layer creates segments out of the message received from the application layer. Segmentation is the process of dividing a long message into smaller messages.

OSI defines five classes of connection-mode transport protocols ranging from class 0 (which is also known as TP0 and provides the fewest features) to class 4 (TP4, designed for less reliable networks, similar to the Internet). Class 0 contains no error recovery, and was designed for use on network layers that provide error-free connections. Class 4 is closest to TCP, although TCP contains functions, such as the graceful close, which OSI assigns to the session layer. Also, all OSI TP connection-mode protocol classes provide expedited data and preservation of record boundaries. Detailed characteristics of TP0-4 classes are shown in the following table:[9]

Feature name TP0 TP1 TP2 TP3 TP4
Connection-oriented network Yes Yes Yes Yes Yes
Connectionless network No No No No Yes
Concatenation and separation No Yes Yes Yes Yes
Segmentation and reassembly Yes Yes Yes Yes Yes
Error recovery No Yes Yes Yes Yes
Reinitiate connectiona No Yes No Yes No
Multiplexing / demultiplexing over single virtual circuit No No Yes Yes Yes
Explicit flow control No No Yes Yes Yes
Retransmission on timeout No No No No Yes
Reliable transport service No Yes No Yes Yes
a If an excessive number of PDUs are unacknowledged.

An easy way to visualize the transport layer is to compare it with a post office, which deals with the dispatch and classification of mail and parcels sent. A post office inspects only the outer envelope of mail to determine its delivery. Higher layers may have the equivalent of double envelopes, such as cryptographic presentation services that can be read by the addressee only. Roughly speaking, tunneling protocols operate at the transport layer, such as carrying non-IP protocols such as IBM‘s SNA or Novell‘s IPX over an IP network, or end-to-end encryption with IPsec. While Generic Routing Encapsulation (GRE) might seem to be a network-layer protocol, if the encapsulation of the payload takes place only at the endpoint, GRE becomes closer to a transport protocol that uses IP headers but contains complete Layer 2 frames or Layer 3 packets to deliver to the endpoint. L2TP carries PPP frames inside transport segments.

Although not developed under the OSI Reference Model and not strictly conforming to the OSI definition of the transport layer, the Transmission Control Protocol (TCP) and the User Datagram Protocol (UDP) of the Internet Protocol Suite are commonly categorized as layer-4 protocols within OSI.

Layer 5: Session Layer

The session layer controls the dialogues (connections) between computers. It establishes, manages and terminates the connections between the local and remote application. It provides for full-duplexhalf-duplex, or simplex operation, and establishes procedures for checkpointing, suspending, restarting, and terminating a session. In the OSI model, this layer is responsible for gracefully closing a session, which is handled in the Transmission Control Protocol at the transport layer in the Internet Protocol Suite. This layer is also responsible for session checkpointing and recovery, which is not usually used in the Internet Protocol Suite. The session layer is commonly implemented explicitly in application environments that use remote procedure calls.

Layer 6: Presentation Layer

The presentation layer establishes context between application-layer entities, in which the application-layer entities may use different syntax and semantics if the presentation service provides a mapping between them. If a mapping is available, presentation protocol data units are encapsulated into session protocol data units and passed down the protocol stack.

This layer provides independence from data representation by translating between application and network formats. The presentation layer transforms data into the form that the application accepts. This layer formats data to be sent across a network. It is sometimes called the syntax layer.[10] The presentation layer can include compression functions.[11] The Presentation Layer negotiates the Transfer Syntax.

The original presentation structure used the Basic Encoding Rules of Abstract Syntax Notation One (ASN.1), with capabilities such as converting an EBCDIC-coded text file to an ASCII-coded file, or serialization of objects and other data structures from and to XML. ASN.1 effectively makes an application protocol invariant with respect to syntax.

Layer 7: Application Layer

The application layer is the OSI layer closest to the end user, which means both the OSI application layer and the user interact directly with the software application. This layer interacts with software applications that implement a communicating component. Such application programs fall outside the scope of the OSI model. Application-layer functions typically include identifying communication partners, determining resource availability, and synchronizing communication. When identifying communication partners, the application layer determines the identity and availability of communication partners for an application with data to transmit. The most important distinction in the application layer is the distinction between the application-entity and the application. For example, a reservation website might have two application-entities: one using HTTP to communicate with its users, and one for a remote database protocol to record reservations. Neither of these protocols have anything to do with reservations. That logic is in the application itself. The application layer per se has no means to determine the availability of resources in the network.

Git : Skipping the Staging Area

Although it can be amazingly useful for crafting commits exactly how you want them, the staging area is sometimes a bit more complex than you need in your workflow. If you want to skip the staging area, Git provides a simple shortcut. Adding the -a option to the git commit command makes Git automatically stage every file that is already tracked before doing the commit, letting you skip the git add part

$ git status
On branch master
Your branch is up-to-date with 'origin/master'.
Changes not staged for commit:
  (use "git add <file>..." to update what will be committed)
  (use "git checkout -- <file>..." to discard changes in working directory)

    modified:   CONTRIBUTING.md

no changes added to commit (use "git add" and/or "git commit -a")
$ git commit -a -m 'added new benchmarks'
[master 83e38c7] added new benchmarks
 1 file changed, 5 insertions(+), 0 deletions(-)

What is CQRS ?

Command and Query Responsibility Segregation (CQRS) is a pattern that segregates the operations that read data (queries) from the operations that update data (commands) by using separate interfaces

What is BoundedContext ?

Bounded Context is a central pattern in Domain-Driven Design. It is the focus of DDD’s strategic design section which is all about dealing with large models and teams. DDD deals with large models by dividing them into different Bounded Contexts and being explicit about their interrelationships

What is Containerization ?

Containerization is an approach to software development in which an application or service, its dependencies, and its configuration (abstracted as deployment manifest files) are packaged together as a container image. The containerized application can be tested as a unit and deployed as a container image instance to the host operating system (OS).

Just as shipping containers allow goods to be transported by ship, train, or truck regardless of the cargo inside, software containers act as a standard unit of software that can contain different code and dependencies. Containerizing software this way enables developers and IT professionals to deploy them across environments with little or no modification.

Containers also isolate applications from each other on a shared OS. Containerized applications run on top of a container host that in turn runs on the OS (Linux or Windows). Containers therefore have a significantly smaller footprint than virtual machine (VM) images.

MS-GPIO : API for controlling Raspberry PI GPIO pins

MS-GPIO is a NodeJS API for controlling Raspberry PI GPIO pins.

MS-GPIO provides various operations, those are listed below :

  1. Reading a GPIO pin
  2. Writing to a GPIO pin
  3. Teardown all the exported GPIO pin


Raspbian OS must be preloaded/installed on Raspberry PI device. For installation refer this page

Latest version of node be installed on your Raspberry PI device, follow below steps to update node to latest version:

sudo apt-get install node

ms-gpio module can then be installed with npm:

npm install ms-gpio

Technical documentation and code can be found below :



« Older posts

© 2021 Objectgyan

Theme by Anders NorenUp ↑