Introduction to the idea of Multi threading
In the diagram, Raspberry Pi acts as a mailbox for messages that are sent to it and then it dutifully delivers them towards the intended destinations.
Let me first tell you the medium through which each of the devices are connected to RPi (I will be using RPi as a shorthand for Raspberry Pi).
Nexus 7 Android tablet is exchanging messages with RPi over RFCOMM protocol via Bluetooth. That’s why you see a Bluetooth dongle attached to RPi.
Arduino is exchanging messages with RPi over Serial via USB cable.
Your laptop/desktop computer is exchanging messages over IP protocol with RPi configured as a Wireless Access Point. That’s why you see a Wifi dongle attached to RPi.
The main idea is to allow messages to be passed around between Arduino, Android and PC with Raspberry Pi acting as a bridge.
Defining the threads
The software running on Raspberry Pi to handle this type of communication must ensure that data exchange happens independently between Raspberry Pi and three other devices.
One option is to use a multithreaded technique. Let’s say you have Read_from_Bluetooth and Write_to_Bluetooth functions. What you need to do is to run them as separate threads. So for every read and write for a particular device, you have two threads. So for the three device shown in Fig 1 (Arduino, Android via Bluetooth and PC/Laptop), you have a total of six threads running independently in a continuous loop.
It is a good practice to declare these threads as daemons such that when the main thread terminates, these threads also get terminated.
Inventing a Protocol for Data Exchange
Besides that, another crucial piece in this communication protocol is to have a header such that when the message is passed from any of the three devices to any other two, the RPi can strip the header off and then pass the message to the intended destination.
As an example, let’s say you want to pass a message to Arduino from either Laptop or Bluetooth and make it move forward by a grid. You could use a header such as aF1. When the RPi receives this message, it will the header which off which is a and pass F1 over Serial Communication to Arduino.
Partial Code segment above shows the code for passing data from PC to either Android or Arduino.
Having an extended period to allow sufficient time for initializing connections
The idea is to use signalling module in python and then wait for 15 seconds before the user links all the three devices to RPi.
They are implemented in the separated files that contain codes for Bluetooth Communication, Serial Communication and PC Communication. A chunk is shown in Fig 6 below inside the PC Communication file.
The complete code can be found on GitHub: https://github.com/oo92/Raspberry-Pi-Server-Code-
Feel free to improve the code.
Anything else: Just GOOGLE ;)