- Introduction
- Prerequisites
- Wiring scheme
- Programming the Raspberry Pi
- Application source code
- Data Visualization and Control
- See Also
- Your feedback
- Next steps
Introduction
IoT Hub Community Edition is an open-source server-side platform that allows you to monitor and control IoT devices. It is free for both personal and commercial usage and you can deploy it anywhere. If you are not familiar with the platform yet, we recommend to review what is thingsboard page and getting started guide at first and then proceed with this tutorial. Within this guide we use iothub.magenta.at.
This sample application will allow you to collect information from sensors and control Servo, Led of your Raspberry Pi device with Grove Base Hat PCB using IoT Hub web UI. The purpose of this application is to demonstrate IoT Hub and Grove Base Hat PCB integrations.
Raspberry Pi will use simple application written in Python for connecting to IoT Hub server via MQTT, sending information from sensors and listening to RPC commands. IoT Hub built-in dashboards will be used for data visualizing and controlling Servo and Led as well.
At the end we will get the following result:
Prerequisites
For the purpose of this tutorial you need IoT Hub server up and running. Within this guide we use iothub.magenta.at
Hardware and pinouts:
Raspberry Pi 3 model B (You can also use Raspberry Pi 4)
In our case we connect following modules:
- Analog Servo
- Mini PIR Motion Sensor v1.0
- Ultrasonic ranger v2.0
- RED Led Button v1.0
- Moisture Sensor v1.4
- Light sensor v1.2
- Temperature&Humidity Sensor v1.2
Wiring scheme
We use following wiring scheme:
1
2
3
4
5
6
7
8
9
Module Pinouts on Grove Base Hat
Analog Servo PWM(12)
Mini PIR Motion Sensor v1.0 D5
Ultrasonic ranger v2.0 D16
RED Led Button v1.0 D18
Moisture Sensor v1.4 A0
Light sensor v1.2 A2
Temperature&Humidity Sensor v1.2 D22
Programming the Raspberry Pi
By first we need to configure the Raspberry Pi. Please follow this article.
After the configuration we need to install libraries used in the script to the Raspberry Pi.
The following command will install thingsboard python client sdk, it is used for communication with IoT Hub server:
1
pip3 install tb-mqtt-client
Also we need to install Seeed-Studio library to be able to connect our modules:
1
git clone git@github.com:Seeed-Studio/grove.py.git
1
pip3 install ./grove.py/
At last if you use Temperature and Humidity sensor (DHTXX), you also need to install the Library for Temperature and Humidity Sensor:
1
git clone https://github.com/Seeed-Studio/Seeed_Python_DHT.git
1
sudo python3 ./Seeed_Python_DHT/setup.py install
Application source code
Our application consists of a single python script that is well documented. You will need to modify THINGSBOARD_HOST constant to match your IoT Hub server installation IP address or hostname.
Also we need say to IoT Hub that we want to connect this device and get the device ACCESS_TOKEN, which will be used in the script. Log in to your environment — Device groups — Add device group — Add new device (e.g. Device 1 with type grove) — Open device details — Copy access token.
After this you need to replace the THINGSBOARD_HOST and ACCESS_TOKEN in the script below, with your values. In case you use Live demo, populate iothub.magenta.at as THINGSBOARD_HOST
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
import logging
import time
from tb_device_mqtt import TBDeviceMqttClient, TBPublishInfo
from grove.grove_mini_pir_motion_sensor import GroveMiniPIRMotionSensor
from grove.grove_ultrasonic_ranger import GroveUltrasonicRanger
from Seeed_Python_DHT.seeed_dht import DHT
from grove.grove_moisture_sensor import GroveMoistureSensor
from grove.button import Button
from grove.grove_ryb_led_button import GroveLedButton
from grove.grove_light_sensor_v1_2 import GroveLightSensor
from grove.grove_servo import GroveServo
# Configuration of logger, in this case it will send messages to console
logging.basicConfig(level=logging.INFO,
format='%(asctime)s - %(levelname)s - %(module)s - %(lineno)d - %(message)s',
datefmt='%Y-%m-%d %H:%M:%S')
log = logging.getLogger(__name__)
thingsboard_server = 'THINGSBOARD_HOST'
access_token = 'ACCESS_TOKEN'
def main():
# Grove - Servo connected to PWM port
servo = GroveServo(12)
servo_angle = 90
# Grove - mini PIR motion pir_sensor connected to port D5
pir_sensor = GroveMiniPIRMotionSensor(5)
# Grove - Ultrasonic Ranger connected to port D16
ultrasonic_sensor = GroveUltrasonicRanger(16)
# Grove - LED Button connected to port D18
button = GroveLedButton(18)
# Grove - Moisture Sensor connected to port A0
moisture_sensor = GroveMoistureSensor(0)
# Grove - Light Sensor connected to port A2
light_sensor = GroveLightSensor(2)
light_state = False
# Grove - Temperature&Humidity Sensor connected to port D22
dht_sensor = DHT('11', 22)
# Callback for server RPC requests (Used for control servo and led blink)
def on_server_side_rpc_request(client, request_id, request_body):
log.info('received rpc: {}, {}'.format(request_id, request_body))
if request_body['method'] == 'getLedState':
client.send_rpc_reply(request_id, light_state)
elif request_body['method'] == 'setLedState':
light_state = request_body['params']
button.led.light(light_state)
elif request_body['method'] == 'setServoAngle':
servo_angle = float(request_body['params'])
servo.setAngle(servo_angle)
elif request_body['method'] == 'getServoAngle':
client.send_rpc_reply(request_id, servo_angle)
# Connecting to IoT Hub
client = TBDeviceMqttClient(thingsboard_server, access_token)
client.set_server_side_rpc_request_handler(on_server_side_rpc_request)
client.connect()
# Callback on detect the motion from motion sensor
def on_detect():
log.info('motion detected')
telemetry = {"motion": True}
client.send_telemetry(telemetry)
time.sleep(5)
# Deactivating the motion in Dashboard
client.send_telemetry({"motion": False})
log.info("Motion alert deactivated")
# Callback from button if it was pressed or unpressed
def on_event(index, event, tm):
if button._GroveLedButton__btn.is_pressed():
log.debug('button: single click')
telemetry = {"button_press": True}
client.send_telemetry(telemetry)
log.info("Pressed")
else:
log.debug('button: single click')
telemetry = {"button_press": False}
client.send_telemetry(telemetry)
log.info("Unpressed")
if event & Button.EV_SINGLE_CLICK:
button.led.light(True)
elif event & Button.EV_DOUBLE_CLICK:
button.led.blink()
elif event & Button.EV_LONG_PRESS:
button.led.light(False)
# Adding the callback to the motion sensor
pir_sensor.on_detect = on_detect
# Adding the callback to the button
button.on_event = on_event
try:
while True:
distance = ultrasonic_sensor.get_distance()
log.debug('distance: {} cm'.format(distance))
humidity, temperature = dht_sensor.read()
log.debug('temperature: {}C, humidity: {}%'.format(temperature, humidity))
moisture = moisture_sensor.moisture
log.debug('moisture: {}'.format(moisture))
log.debug('light: {}'.format(light_sensor.light))
# Formatting the data for sending to IoT Hub
telemetry = {'distance': distance,
'temperature': temperature,
'humidity': humidity,
'moisture': moisture,
'light': light_sensor.light}
# Sending the data
client.send_telemetry(telemetry).get()
time.sleep(.1)
except Exception as e:
raise e
finally:
client.disconnect()
if __name__ == '__main__':
main()
Data Visualization and Control
To configure dashboard you should login into IoT Hub environment.
To proceed with this step, please download a grove_seeed_studio.json file, which contains preconfigured dashboard for this script. Once logged in, open Dashboards, click on the plus button in the bottom right corner of the screen and select the “Import dashboard” icon. Select recently downloaded file of dashboard configuration. Now you must edit the alias of Grove widget you should do this by pressing on the pen icon. Select the Filter type parameter as “Single entity”, set Type as “Device” and from the list of devices - select your GROVE device.
Running the application
This simple command will launch the application:
1
python3 tb_grove.py
The results of script running - you can see on the dashboard.
Also from dashboard you can control the servo (by rotating the knob control with name “Servo”) or the led (by pressing the trigger “Button Led”).
See Also
Browse other samples or explore guides related to main IoT Hub features:
- Device attributes - how to use device attributes.
- Telemetry data collection - how to collect telemetry data.
- Using RPC capabilities - how to send commands to/from devices.
- Rule Engine - how to use rule engine to analyze data from devices.
- Data Visualization - how to visualize collected data.
Your feedback
Don’t hesitate to star IoT Hub on github to help us spread the word. If you have any questions about this sample - post it on the issues.
Next steps
- Getting started guides - These guides provide quick overview of main IoT Hub features. Designed to be completed in 15-30 minutes.
-
Connect your device - Learn how to connect devices based on your connectivity technology or solution.
-
Data visualization - These guides contain instructions how to configure complex IoT Hub dashboards.
-
Data processing & actions - Learn how to use IoT Hub Rule Engine.
-
IoT Data analytics - Learn how to use rule engine to perform basic analytics tasks.
-
Advanced features - Learn about advanced IoT Hub features.
-
Contribution and Development - Learn about contribution and development in IoT Hub.