So far we have everything we need to perform a successful motion detection, watch the stream online as well as to manipulate with the Raspberry externally. In this part, however, we will do a little bit of cosmetics in order to facillitate working with the camera externally. Until now, in order to activate or deactivate the program, we needed to log in to the Raspberry and invoke the specific command. Now, we will use Python in order to access Motion more easily.
The point is to create two python scripts to act as server and the client, hence making a tiny abstraction layer for to handle the connection. The scripts will talk to each other, in a way that
ssh'ing will be avoided. You can think of it as a starting point for expansion, if you'd like to, for example, enable other members of your family to use the system through an application.
In this simple version, we will use the two modules in both scripts:
socket- for the TCP/IP connection.
os- for letting Python "type" the terminal commands for us.
server.py is obviously going to be deployed on the Raspberry. Its task will be to listen for connection and depending on incoming command from the client, it will start or stop Motion. Before we begin, however, let us use
cron scheduler in order to ensure that this script is executed every single time Raspberry reboots.
In Raspberry's terminal execute:
and select your favourite text editor, when prompted to. Next, add the following line to the file:
The capital letters should, of course, be adapted to your case and the & sign is used to free the terminal.
Now, the body of the script:
I guess, you can deduct from the code that after the connection is made, the server waits for the client and responds to keywords. The
os.system() function is used to manipulate with Motion as if we did it through the terminal and
client_socket.send() transfers the commands between the devices.
client.py is to be deployed on a PC (or mobile device) that is used to connect to the camera. The body of the file is the following: