Sending data from Python app to Oracle IoT Cloud Service

If you read my blog post “Send data from Raspberry Pi to Oracle IoT Cloud Service“, you learned how to use the CPOSIX SDK to send data from Raspberry Pi to Oracle IoT Cloud Service. Oracle provides SDKs for many programming languages, but if you don’t find a SDK for your favourite programming language (e.g., python), you can use the REST API.

In this blog post, you will learn how to send humidity and temperature data from Raspberry Pi to Oracle IoT Cloud Service using Python and REST API. You can clone this project from here: https://github.com/waslleysouza/oraclecloud_iotcs_DHT.

To make the things easier, I created a simple Python Package using REST API for Oracle IoT Cloud Service, and you can learn more here: https://github.com/waslleysouza/oraclecloud.

First of all, you need to install the required Python Packages.

pip install oraclecloud Adafruit_DHT

Create the formats.json file.
This file has the JSON format of message.

[
    {
        "name": "Message",
        "urn": "urn:com:oracle:iot:device:camera:message",
        "type": "DATA",
        "fields": [
            {
                "name": "license_plate",
                "optional": "False",
                "type": "STRING"
            },
            {
                "name": "confidence",
                "optional": "False",
                "type": "NUMBER"
            },
            {
                "name": "picture_url",
                "optional": "False",
                "type": "URI"
            }
        ]
    }
]

Create the app.py file.
This is the main file of the application.

#!/usr/bin/python3
# Waslley Souza (waslleys@gmail.com)
# 2018

import Adafruit_DHT
import time
import json
import os
import platform
from oraclecloud import Iot


USER = 'iot'
PASS = 'welcome1'
URL  = 'https://192.168.0.177:10443'
SHARED_SECRET = 'Welcome_1'

DEVICE_MODEL_URN = "urn:com:oracle:iot:device:temp_hum"
DEVICE_MODEL_FORMAT_URN = DEVICE_MODEL_URN + ":message"


sensor = Adafruit_DHT.DHT11
#sensor = Adafruit_DHT.DHT22

# GPIO pin
pino_sensor = 14


def main():
    print('Running...')
    
    while True:
      humidity, temperature = Adafruit_DHT.read_retry(sensor, pino_sensor)

      if humidity is not None and temperature is not None:
          print("Temperature = {0:0.1f} C  Humidity = {1:0.1f} %".format(temperature, humidity))
          data = {'humidity':humidity,'temperature':temperature}
          iot.send_message(device, DEVICE_MODEL_FORMAT_URN, data)
          time.sleep(1)
      
      else:
          print("Error !!!")


def _open_file(file_name):
    f = open(file_name, 'r')
    text = f.read()
    f.close()
    return text


def _create_file(file_name, text):
    f = open(file_name, 'w')
    f.write(text)
    f.close()


if __name__ == "__main__":
    iot = Iot(USER, PASS, URL, False)

    if os.path.isfile('device.txt'):
        device_id = _open_file('device.txt')
        device = iot.get_device(device_id)  
        iot.set_shared_secret(SHARED_SECRET)

    else:
        device_model = iot.get_device_model(DEVICE_MODEL_URN)
        if not device_model:
            formats = json.loads(_open_file('formats.json'))
            device_model = iot.create_device_model("TemperatureHumidity", DEVICE_MODEL_URN, formats)

        device_name = platform.node() + "_DHT"
        device = iot.create_device(device_name, SHARED_SECRET, hardware_id=device_name)
        iot.activate_device(device, DEVICE_MODEL_URN)

        _create_file('device.txt', device['id'])
    
    main()

Don’t forget to change this part of code with your environment information.

USER = 'iot'
PASS = 'welcome1'
URL  = 'https://192.168.0.177:10443'

Execute the following command to start your app.

python app.py

Now, you can monitor the humidity and temperature using Oracle IoT Cloud Service.

Have a good time!

Author: Waslley Souza

Consultor Oracle com foco em tecnologias Oracle Fusion Middleware e SOA. Certificado Oracle WebCenter Portal, Oracle ADF e Java.

Leave a Reply

Your email address will not be published. Required fields are marked *