Using Tuya Link SDK to build water level monitoring system.
Tags: python, raspberrypi, iot, monitoring
Published: 2022-01-04 05:22:22

## Hardware devices required
- Raspberry Pi
- Ultrasonic sensor
- Jumper wires

## Software required
- Tuya IoT platform
- Link SDK python package
- Tuya Smart app (mobile app)


## Getting started with Tuya IoT platform

### Create an account in the platform.
If you already have an account, go on login [here](https://auth.tuya.com/?_source=f8ce204fc51d1a7082c9e80206711660) or if you don't have an account, then create one in this [link](https://auth.tuya.com/?_source=f8ce204fc51d1a7082c9e80206711660).

If you are registered or login successfully, then you'll see this dashboard:

![008.png](https://cdn.hashnode.com/res/hashnode/image/upload/v1640774667217/oIe2FMj6U.png)

Then open  **Product** > **Development** > **Create** then scroll down and you'll see **Can't find the category?** in the left bottom corner. Open up and fill the information like below then **Create**:

![004.png](https://cdn.hashnode.com/res/hashnode/image/upload/v1639814305995/nKoYZNW86.png)

By creating the Product we mean, the project which will exist in the Tuya platform to receive data from the sensors and monitored remotely from the phone or your PC. The information we filled in the platform tries to mimic our hardware devices which we will use in the circuit.

### Create custom functions
Here we specify some metrics about the sensor (Ultrasonic sensor) so as it may link correctly as how we want it to be. These metrics including, `Data Point (DP)`, `Identifier`,`Data Transfer Type`, `Data Type` and `Value`

Open up our **Product** and then click ** Function Definition**  > **Custom Function** > **Add**, you'll see the form to fill the metrics above. Go ahead and fill like this:

![005.png](https://cdn.hashnode.com/res/hashnode/image/upload/v1639815308278/YmDrzqGfSm.png)


### Obtain credentials for your project
Credentials which are needed in `tuyalinksdk` are `PID`, `AUTHKEY` and `UUID`. Once you create a Product in the platform, you automatically obtain the PID (aka, Product ID).

![006.png](https://cdn.hashnode.com/res/hashnode/image/upload/v1639816092846/1hJhzi5YO.png)

But for AUTKEY and UUID, you'll have to apply for a license. The license comes with these two credentials. Follow these steps to get the license. Navigate to **Purchase** > **Material & License** then click **Buy Now** the **Generic License** 2 free licenses for each developer account, you need to buy when you use up.

![007.png](https://cdn.hashnode.com/res/hashnode/image/upload/v1639817006071/9bobxx7tZ.png)

Click **Buy Now **, another window will open then **Select Product** and **Delivery Mode** as License.
The order process will take some time to complete. Just relax and worry out meanwhile, get a cup of coffee :)


## The Circuit (Hardware part)
In this section, we're going to build our circuit. Connect the Raspberry Pi on the power source and the keyboard. Mount Ultrasonic sensor on the Raspberry Pi. We use Ultrasonic sensor to measure the level of water calculating the distance from the sensor to the water surface in the tank.

![image.png](https://cdn.hashnode.com/res/hashnode/image/upload/v1639824560292/ONIJyXUFj.png)


![circuit.jpg](https://cdn.hashnode.com/res/hashnode/image/upload/v1640838988178/19Rj9Hpom.jpeg)


## Project in Tuya IoT platform (Software part)
In this section, we're going to setup our project in the Tuya IoT platform. We already have the credentials which we got in the above steps (by credentials i mean, PID, UUID and AUTHKEY). We will use these credentials in the `tuyalinksdk` to setup a link connection between the circuit and platform. 


### Link Tuya SDK python library
`tuyalinksdk` is a Python library which makes the connection between the circuit and the Tuya IoT platform.
We'll install this package in our Raspberry Pi in order to link and upload data from the sensor (in the circuit) to the platform. In the directory of your project in Raspberry Pi, run:

```
# install the package
$ pip install tuyalinksdk
```
or install from the github repository:
```
$ git clone https://github.com/tuya/tuyaos-link-sdk-python.git
$ python3 -m pip install ./tuyaos-link-sdk-python
```

Next thing is to write the codes which establish connection by using this package.
```
from tuyalinksdk.client import TuyaClient

client = TuyaClient(productid='PID', uuid='UUID', authkey='AUTHKEY')

def on_connected():
    print('Connected.')

def on_dps(dps):
    print('DataPoints:', dps)
    client.push_dps(dps)

client.on_connected = on_connected
client.on_dps = on_dps
client.connect()
client.loop_start()
```

`on_connected` is the method which checks if the connection is well setup. If everything is okay the print statement will run.

`on_dps` is a method which receives the datapoints (values of the sensor) and upload them to the platform so that we can monitor the process from our devices (phones and PC), ie IoT itself. Data are uploaded through `client.push_dps()` method.

Write the codes for the Raspberry Pi codes for the ultrasonic sensor alongside the above codes. This is the complete codes:
```
#!/usr/bin/python
import RPi.GPIO as GPIO
import time
import coloredlogs
from tuyalinksdk.client import TuyaClient
from tuyalinksdk.console_qrcode import qrcode_generate
from time import sleep

GPIO.setmode(GPIO.BCM)
coloredlogs.install(level='DEBUG')

client = TuyaClient(
    productid='44apXXXXXXXXXXX',
     uuid='tuya19dXXXXXXXXXXX',
      authkey='uFjw3VqrrfXXXXXXXXXXXXXX')

TRIG = 2
ECHO = 3
i=0

GPIO.setup(TRIG ,GPIO.OUT)
GPIO.setup(ECHO,GPIO.IN)
GPIO.setup(4 ,GPIO.OUT)

GPIO.output(TRIG, False)
print("Starting.....")
sleep(2)

while True:
   GPIO.output(TRIG, True)
   sleep(0.00001)
   GPIO.output(TRIG, False)

   while GPIO.input(ECHO)==0:
      pulse_start = time.time()

   while GPIO.input(ECHO)==1:
      pulse_stop = time.time()

   pulse_time = pulse_stop - pulse_start
   water_level = pulse_time * 17150
   print(round(water_level, 2))

   time.sleep(1)

   if water_level < 4:
       print("Water will overflow")
       GPIO.output(4, True)
       time.sleep(0.5)
       GPIO.output(4, False)
       time.sleep(0.5)
       GPIO.output(4, True)
       time.sleep(0.5)
       GPIO.output(4, False)
       time.sleep(0.5)
   else:
       GPIO.output(4, False)

def on_connected():
    print('Connected.')

def on_qrcode(url):
    qrcode_generate(url)

def on_reset(data):
    print('Reset:', data)

def on_dps(dps):
    print('DataPoints:', dps)
    dps = {'101':True}
    dps['101'] = data
    client.push_dps(dps)

client.on_connected = on_connected
client.on_qrcode = on_qrcode
client.on_reset = on_reset
client.on_dps = on_dps
client.connect()
client.loop_start()

while True:
    data = water_level
    time.sleep(1)

``` 
You can get the starter codes from Tuya's page in Github and edit the codes by adding Raspberry Pi configuration codes. Run these commands:
```
 $ git clone https://github.com/tuya/tuyaos-link-sdk-python.git
 $ cd examples
# view the starter codes here
 $ cat outlet.py
```
Reference is [here](https://pypi.org/project/tuyalinksdk/#tuyaos-link-sdk-for-python) and the codes can be found  [here](git)

Running the codes at first time will create a connection between your project in Tuya platform and the Tuya mobile application which will enable you to send commands from the application to your Raspberry Pi remotely through the platform. To allow the connection, you'll need to scan the qrcode by using your mobile phone generated once you run the `outlets.py`. 


![WhatsApp Image 2021-12-29 at 14.51.41.jpeg](https://cdn.hashnode.com/res/hashnode/image/upload/v1640779236637/HkqwA_U4E.jpeg)


Now lets design a monitoring dashboard in the platform which will receive data from our sensor and display visuals and monitoring. Then after, we will connect a smartphone to view this dashboard just like how we view in the platform (in the platform, a web based)

### Monitoring dashboard
In the platform, navigate to **Product** > **Development**, it will open the product we've just created in the above steps. Open up that Product (aka, the project) and you'll see something like this:

![001.png](https://cdn.hashnode.com/res/hashnode/image/upload/v1639800632724/KsTdmxDBq.png)

Open the **Device Panel** and select a blank screen where it will open up a new page for designing the mobile view screen for your dashboard. Make the UI design of your choice, this is what i came up with:

![002.png](https://cdn.hashnode.com/res/hashnode/image/upload/v1639802552711/xZBzsPTba.png)

When you're done with the design, **Preview** to check if its okay then **Save As** and finally **Release** your design. Up to this point, the dashboard is ready. We can visualize this design from the smartphone by using [Tuya Smart App](https://play.google.com/store/apps/details?id=com.tuya.smart&hl=en&gl=US)


Up to this point, the project is ready for testing and using. You can monitor the water level of your tank remotely from your device (phone for example).

## Output
If you follow along up to this point, you should be able to send values directly from your phone remotely to the platform.

![device.png](https://cdn.hashnode.com/res/hashnode/image/upload/v1640837937509/JLmTAV3ee.png)


![dps.png](https://cdn.hashnode.com/res/hashnode/image/upload/v1640837950212/G5-dTuA7a.png)

[Video demo](https://www.youtube.com/watch?v=oxfzzZoUqGk)



### References

- [Project examples from Tuya](https://github.com/tuya/tuyaos-link-sdk-python)
- [Source codes](https://github.com/maen08/tuya-linksdk-with-raspberry-pi)
- [Tuya blog](https://blog.tuya.com/blog)
- [Tuya github page](https://github.com/tuya/)