DEV Community

zhuyue
zhuyue

Posted on

How to design the IOT gateway in cloud based on swoole

Only two PHP files are needed implement the IoT communication gateway on a cloud server.

Allow users to program, control and view the status of the controller from any corner of the world where they have access to the Internet.

I used swoole network communication engine as the framework of the gateway and created a tcp server as well as a websocket server.

The controller and 3rd party software connect to the tcp server as a tcp client, while the web page opened by the user connects to the websocket server as a websocket client, and both maintain a long connection.

The PHP code of the gateway creates a table to store the connection information of the controller, web page, host software and other clients, including the client ID, the file descriptor fd of the socket and so on;

The controller establishes a tcp connection with the tcp server on the cloud server and sends a heartbeat message to the tcp server at regular intervals. The tcp server parses out the source address in the message after receiving it, and saves the fd of the tcp connection as well as the source address to the table.

After the user opens the web page, the javascript script connects the tcp connection with the websocket server, and at the same time generates a random uuid as the source address from the controller code entered on the web page as the destination address, and generates a control message to send to the websocket server, which, after receiving it, analyzes the source address and destination address of the message, and then sends a heartbeat message to the tcp server according to the destination address and the source address. After receiving the message, websocket server parses the source address and destination address in the message, finds the tcp connection corresponding to the destination address from the table according to the destination address, and forwards the message to the controller through this connection.

At the same time, the uuid of the cloud server is defined, which is used for the controller, web page and other interactions with the server, to synchronize the time from the cloud server, as well as to save the state to the mysql database and other functions.

The two PHP files, totaling about 500 lines of code, are fairly simple.

Image description

Image description

Top comments (0)