DEV Community

Alfredo De Miguel Soldado
Alfredo De Miguel Soldado

Posted on

PLUG-IN CONTROLLED FROM YOUR OWN API-REST SERVER

Alt Text

Version en español: https://dev.to/alfredodemiguel/enchufe-controlado-desde-tu-propio-servidor-api-rest-1mi3

Building from scratch, a socket, which can be managed from your own wifi or from the internet, is a job, which requires knowledge of many things. If you decide to join me, you'll see:

  • How to design a pcb with KiCad.
  • How to design a box with FreeCAD.
  • Arduino programming of a Wemos D1 mini.
  • Programming an API server.
  • Programming a web for administration from Internet.
  • Putting the applications in Docker containers and uploading the applications to Heroku.

The plug that we are going to make, is a plug, that takes the electricity from the network, and internally transforms it from 220v to 5v, to be able to feed a Wemos D1 mini, and a small relay, that is the one in charge to let pass the 220v according to our indications. In addition, the plug, has two additional and optional capacities. The first one is to send an email, when it is activated. And the second is to start in case of detecting movement. The initial configuration is done from your own wifi, and the administration of this plug can be done from your own wifi or from a public website, which we will also create.

There are many topics to be discussed, and therefore I will not go into any depth, but I will try to give the main keys, so you can make your own version of the plug, or if you prefer to copy mine. All the designs and the code you have in: https://github.com/alfredodemiguel/Proyectos/tree/master/smartplug

HARWARE DESIGN

With the KiCad program, you have to follow the following steps, in order to design a pcb that you can have manufactured, by one of the many manufacturers

  • The first is to create the scheme. This point is where you decide how you will take the electricity from the network, to power the plug, when appropriate, and to power the Wemos D1 mini, next to the relay, and a motion sensor and some leds. The list of all the elements used and the links to Amazon are in the file ListaComponentes.txt

Alt Text

The design of the first part of this pcb is inspired by the following post (https://randomnerdtutorials.com/esp8266-hi-link-hlk-pm03/) . The rest of the design is to put the different connections between the D1 mini, the relay, the leds, and the motion sensor.

  • The second step is to make the design of the board, but as it will be once you send it to manufacture. That's why in this part it's necessary that all the pieces are referenced by their fingerprints. The fingerprints are the drawings of the pieces, but with their dimensions and capacities.

Alt Text

  • The third and last step is to generate the gerber files, which are the ones you have to send to one of the many companies that advertise on the internet, and for about 20.00 euros they will send you 6 copies of the plaque you have designed.

BOX DESIGN

Alt Text

This part is super fun. To design objects in FreeCad you have to put geometrical figures, and then empty them with their complements, inside the part

For example to make a turret, where you will then fix the base plate, what you do is drag a big cylinder, and then you drag another smaller cylinder in the same place and you do a subtraction operation.

To make the letters you must go to the draft panel.

In my case I chose to take a Thingiverse box as a base and customize it, because it has details like rounded edges or a frame around the cover for a better fit.

PROGRAMMING OF THE D1 MINI WEMOS

Alt Text

As you can see, the program is divided into 12 files, but don't be afraid, because each one has a simple purpose.

  • Plug: This is the first one in charge of initializing the variables, with the data that it has saved in its flash memory, such as the user, access password and the data to access the wifi. And secondly, like all arduous programs, it has an infinite loop, in which it attends to its own wifi, connects to the api-rest server and behaves according to the data obtained.

  • Ap_Wifi: The plug, gives service to a wifi that is called smartplug and that in the ip 192.168.4.1 service to a web from where you can configure the plug and manage it.

  • Base64,cpp, Base64.h, EMailSender.cpp and EMailSender.h, are libraries for encrypting and decrypting passwords and for sending email respectively. You have to put these libraries in order to use their functions.

  • Behavior: Depending on the data received from the internal web and the api-rest server, it modifies the behavior of the plug, turning it on or off, activating or deactivating the presence sensor or the sending of email.

  • Config: Initializes the global variables of the program.

  • EEprom_IO: The functions of writing and reading in the flash memory of the Wemos D1 Mini.

  • Email: The function in charge of sending the email.

  • Index: The different web pages that are served from the plug. They are made in html with css responsive, so they can be seen well from computers or mobile phones.

Alt Text

  • Wifi: Communication is established with the api-rest server by means of a get and post.

As I said at the beginning, you can copy my design, but the interesting thing is that you could make your own version by changing the presence sensor for a temperature sensor, or anything else you can imagine.

API-REST SERVER

Alt Text

To be able to manage the plug from the internet we need a server, and this way the plug only must push or get to a url, to communicate the status or get new instructions. For which you only need to be connected to a wifi network, and you forget to open ports to establish communication.

The server that I leave as an example, has more functionalities than needed and some tests with Chai Http. And when you make your own version, you will discover in case you don't already know, that the tests are very useful, to make changes in the program, and that not everything is dismantled when you add a new functionality.

I'm just going to talk about the first part of the code, where you call the modules to be used, and initialize them.

  • Express: Is the most popular web framework of Node
  • Morgan: It is a middleware that writes in the console the requests to the server.
  • BodyParser along with json: It's used to handle json-type data.
  • Cors: It is used to access to our server from other domains than our own.

const express = require('express');
const morgan = require ('morgan');
const bodyParser = require('body-parser');
var cors = require('cors-express');
const app = express();
const port = process.env.PORT || 3017;

app.use (morgan('dev'));
app.use(express.static('.'));
app.use(bodyParser.json());

options = {
allow : {
origin: '*',
methods: 'GET,PUT,POST,DELETE,HEAD,OPTIONS',
headers: 'Content-Type, Authorization, Content-Length,
X-Requested-With, X-HTTP-Method-Override'
}
};

app.use(cors(options));

The functions that continue in the code are very simple and as you will see they can be easily customized according to the needs.

WEBPAGE FOR THE HANDLING OF THE PLUGS

Alt Text

In order to be able to manage the plug from anywhere, a website is needed. In this web, the user and the password that has been given to the plug is requested, during the initial configuration that is carried out from the web that the same one serves (The plug in a wifi access point).

In my case I have used React, to make the web, but the truth is that you can do it in the language that you feel more comfortable, there are a lot of tutorials on how to make CRUD (create, read, update, delete), although in this case we are left only with the R and U, since the create, makes the plug when connecting to the server that we have created previously. And there is no delete.

As you can see in the code, I have used axios, for the communication part of the plug with the server.

UPLOAD TO THE CLOUD THE API-REST SERVER AND THE ADMINISTRATION WEB

We almost have it, now we just need to upload to the cloud our api-rest server and our website.

For this, I have chosen, the combination of docker and Heroku.

Docker allows us that our application is not affected by its environment, and thus, that it always works the same regardless of the operating systems, patches, and different versions of the programs that compose it.
Heroku, today has a free plan, ideal for testing, and if you like, there is a Hobby plan. But with the Free one, it's enough for the project at hand.

If we already have correctly installed, npm, node, docker and the free Heroku account.

What we must do to upload the api-rest server to the cloud is to create a dockerfile with the following content:

FROM node:12
WORKDIR /app
COPY package*.json ./
RUN npm install
COPY . .
CMD ["npm","start"]

And then we execute the following commands from the terminal window:

heroku login
heroku container:login
heroku create miapp
heroku container:push web -a miapp
heroku container:release web -a miapp

And in the case of the React application what we do is a build and then we create a small express server that serves the page. From this point on, everything is the same as in the API-REST server.

Top comments (0)