-
Notifications
You must be signed in to change notification settings - Fork 1
Machine to Machine (M2M) communication
Nils Deckert edited this page Mar 6, 2019
·
6 revisions
To push the data collected by the Raspberry Pi Zero W (respectively the connected sensors) to the Raspberry Pi 2 where it gets processed I'm using mqtt, since it is very lightweight and allows a fast transfer of text data, which is what pretty much exactly what I need.
Below are some codesnippets to give you an idea what it needs to send data between to Raspis using mqtt:
Raspberry Pi 2 (subscriber):
import paho.mqtt.client as mqtt
import datetime
MQTT_SERVER = "localhost"
MQTT_PATH = "test_channel"
localtime = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
def on_connect(client, userdata, flags, rc):
print("Connected with result code " +str(rc))
client.subscribe(MQTT_PATH)
def on_message(client, userdata, msg):
msg.payload = msg.payload.decode("utf-8")
print("[" + msg.topic + "] " + localtime +" - " +str(msg.payload))
client = mqtt.Client()
client.on_connect = on_connect
client.on_message = on_message
client.connect(MQTT_SERVER, 1883, 60)
client.loop_forever()
Raspberry Pi Zero W (publisher):
In this case it sends time and date every 10 seconds, as example for data that gets collected in determined intervals
import paho.mqtt.publish as publish
import time
import datetime
MQTT_SERVER = "192.168.178.66"
MQTT_PATH = "test_channel"
while True:
#message = input()
localtime = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
publish.single(MQTT_PATH, str(localtime), hostname=MQTT_SERVER)
time.sleep(10)
This leads to the following output on the Raspberry Pi 2:
Connected with result code 0
[test_channel] 2019-03-05 18:58:28 - 2019-03-05 19:59:04
[test_channel] 2019-03-05 18:58:28 - 2019-03-05 19:59:04
[test_channel] 2019-03-05 18:58:28 - 2019-03-05 19:59:14
[test_channel] 2019-03-05 18:58:28 - 2019-03-05 19:59:24
[test_channel] 2019-03-05 18:58:28 - 2019-03-05 19:59:34