Gridsense Docs iconGridsense Docs

Send Your First Message

Learn how to send messages with your connected devices to the channels you configured

Preface

Although there are many ways to send messages, the underlying concepts remain the same, regardless of the device or programming language you are using. This tutorial assumes you have already provisioned a device and a channel.

To send messages, you will need the following:

The ID and secret of the device through which messages will be sent; the ID of the organization in which the device is provisioned; and lastly, the ID of the channel to which messages will be sent.

Types of connectivity

What sets Gridsense apart is the flexibility it provides when it commes to connectivity. Gridsense allows you to connect your devices through MQTT, CoAP, WebSockets, and HTTP to accomodate for the wide range of devices and use-cases.

In this tutorial, we'll cover all four types through an example.

Sending a message

MQTT

We'll be using Python and the Paho MQTT client library.

Prepare your credentials

Python
DEVICE_ID = "..."
DEVICE_SECRET = "..."
CHANNEL_ID = "..."
ORG_ID = "..."
HOST = "gridsense.cloud"

Construct the message topic

Python
DEVICE_ID = "..."
DEVICE_SECRET = "..."
CHANNEL_ID = "..."
ORG_ID = "..."
HOST = "gridsense.cloud"

topic = f"m/{ORG_ID}/c/{CHANNEL_ID}"

Initialize MQTT client

Python
import paho.mqtt.client as mqtt 

DEVICE_ID = "..."
DEVICE_SECRET = "..."
CHANNEL_ID = "..."
ORG_ID = "..."
HOST = "gridsense.cloud"

topic = f"m/{ORG_ID}/c/{CHANNEL_ID}"

client = mqtt.Client(client_id=DEVICE_ID, clean_session=True, callback_api_version=mqtt.CallbackAPIVersion.VERSION1) 
client.username_pw_set(DEVICE_ID, DEVICE_SECRET) 

Configure TLS/SSL

Python
import paho.mqtt.client as mqtt
import ssl 

DEVICE_ID = "..."
DEVICE_SECRET = "..."
CHANNEL_ID = "..."
ORG_ID = "..."
HOST = "gridsense.cloud"
CA_CERT_PATH = "..."


topic = f"m/{ORG_ID}/c/{CHANNEL_ID}"

client = mqtt.Client(client_id=DEVICE_ID, clean_session=True, callback_api_version=mqtt.CallbackAPIVersion.VERSION1)
client.username_pw_set(DEVICE_ID, DEVICE_SECRET)

# Configure TLS/SSL for server verification only
client.tls_set( 
    ca_certs=CA_CERT_PATH, 
    cert_reqs=ssl.CERT_REQUIRED, 
    tls_version=ssl.PROTOCOL_TLS, 
    ciphers=None, 
) 
client.tls_insecure_set(False)  # Don't skip certificate verification

Connect to the Gridsense MQTT broker

Python
import paho.mqtt.client as mqtt
import ssl

DEVICE_ID = "..."
DEVICE_SECRET = "..."
CHANNEL_ID = "..."
ORG_ID = "..."
HOST = "gridsense.cloud"
CA_CERT_PATH = "..."

topic = f"m/{ORG_ID}/c/{CHANNEL_ID}"

client = mqtt.Client(client_id=DEVICE_ID, clean_session=True, callback_api_version=mqtt.CallbackAPIVersion.VERSION1)
client.username_pw_set(DEVICE_ID, DEVICE_SECRET)

# Configure TLS/SSL for server verification only
client.tls_set(
    ca_certs=CA_CERT_PATH,
    cert_reqs=ssl.CERT_REQUIRED,
    tls_version=ssl.PROTOCOL_TLS,
    ciphers=None,
)
client.tls_insecure_set(False)  # Don't skip certificate verification

# 8883 is the MQTTS port. For MQTT (insecure), use 1883.
client.connect(HOST, 1883, keepalive=60) 

Construct the SenML message

Python
import paho.mqtt.client as mqtt
import ssl
import time 

DEVICE_ID = "..."
DEVICE_SECRET = "..."
CHANNEL_ID = "..."
ORG_ID = "..."
HOST = "gridsense.cloud"
CA_CERT_PATH = "..."

topic = f"m/{ORG_ID}/c/{CHANNEL_ID}"

client = mqtt.Client(client_id=DEVICE_ID, clean_session=True, callback_api_version=mqtt.CallbackAPIVersion.VERSION1)
client.username_pw_set(DEVICE_ID, DEVICE_SECRET)

# Configure TLS/SSL for server verification only
client.tls_set(
    ca_certs=CA_CERT_PATH,
    cert_reqs=ssl.CERT_REQUIRED,
    tls_version=ssl.PROTOCOL_TLS,
    ciphers=None,
)
client.tls_insecure_set(False)  # Don't skip certificate verification

# 8883 is the MQTTS port. For MQTT (insecure), use 1883.
client.connect(HOST, 1883, keepalive=60)

data = [ 
    { 
        "bn": "org/lighting/SmartLight/", 
        "bt": time.time(), 
        "n": "brightness", 
        "u": "lm", 
        "v": round(random.uniform(100, 3000), 2) 
    }, 
    { 
        "n": "power", 
        "u": "W", 
        "v": round(random.uniform(6.7, 200), 2) 
    } 
] 

Send the messaage

Python
import paho.mqtt.client as mqtt
import ssl
import time

DEVICE_ID = "..."
DEVICE_SECRET = "..."
CHANNEL_ID = "..."
ORG_ID = "..."
HOST = "gridsense.cloud"
CA_CERT_PATH = "..."

topic = f"m/{ORG_ID}/c/{CHANNEL_ID}"

client = mqtt.Client(client_id=DEVICE_ID, clean_session=True, callback_api_version=mqtt.CallbackAPIVersion.VERSION1)
client.username_pw_set(DEVICE_ID, DEVICE_SECRET)


# Configure TLS/SSL for server verification only
client.tls_set(
    ca_certs=CA_CERT_PATH,
    cert_reqs=ssl.CERT_REQUIRED,
    tls_version=ssl.PROTOCOL_TLS,
    ciphers=None,
)
client.tls_insecure_set(False)  # Don't skip certificate verification

# 8883 is the MQTTS port. For MQTT (insecure), use 1883.
client.connect(HOST, 1883, keepalive=60)

data = [
    {
        "bn": "org/lighting/SmartLight/",
        "bt": time.time(),
        "n": "brightness",
        "u": "lm",
        "v": round(random.uniform(100, 3000), 2)
    },
    {
        "n": "power",
        "u": "W",
        "v": round(random.uniform(6.7, 200), 2)
    }
]

payload = json.dumps(data) 
client.publish(topic, payload) 

WebSockets

We will use the websocket-client library. Make sure to install it before running the script.

Prepare your credentials

Python
DEVICE_ID = "..."
DEVICE_SECRET = "..."
CHANNEL_ID = "..."
ORG_ID = "..."
HOST = "api.gridsense.cloud"

Construct the connection URL

Python
DEVICE_ID = "..."
DEVICE_SECRET = "..."
CHANNEL_ID = "..."
ORG_ID = "..."
HOST = "api.gridsense.cloud"

# 443 is the secure WSS port
url = f"wss://{HOST}:{443}/ws/m/{ORG_ID}/c/{CHANNEL_ID}"
headers = { 
    "Authorization": f"Client {DEVICE_SECRET}"
} 

Configure SSL for a secure connection

Python
import ssl 

DEVICE_ID = "..."
DEVICE_SECRET = "..."
CHANNEL_ID = "..."
ORG_ID = "..."
HOST = "api.gridsense.cloud"

# 443 is the secure WSS port
url = f"wss://{HOST}:{443}/ws/m/{ORG_ID}/c/{CHANNEL_ID}"
headers = {
    "Authorization": f"Client {DEVICE_SECRET}"
}

ssl_context = ssl.create_default_context() 
ssl_context.check_hostname = True
ssl_context.verify_mode = ssl.CERT_REQUIRED

Initialize the WebSockets object

Python
from contextlib import closing 
from websocket import create_connection 
import ssl

DEVICE_ID = "..."
DEVICE_SECRET = "..."
CHANNEL_ID = "..."
ORG_ID = "..."
HOST = "api.gridsense.cloud"

# 443 is the secure WSS port
url = f"wss://{HOST}:{443}/ws/m/{ORG_ID}/c/{CHANNEL_ID}"
headers = {
    "Authorization": f"Client {DEVICE_SECRET}"
}

ssl_context = ssl.create_default_context()
ssl_context.check_hostname = True
ssl_context.verify_mode = ssl.CERT_REQUIRED

with closing( 
    create_connection( 
        url=url, 
        header=[f"{k}: {v}" for k, v in headers.items()], 
        sslopt={ 
            "cert_reqs": ssl.CERT_REQUIRED,  
            "ca_certs": "/etc/ssl/cert.pem", # default CA certificates path on Linux/macOS
        }, 
    ), 
) as ws: 
    pass

Send a message

Python
from contextlib import closing
from websocket import create_connection
import ssl
import json 
import random 
import time 

DEVICE_ID = "..."
DEVICE_SECRET = "..."
CHANNEL_ID = "..."
ORG_ID = "..."
HOST = "api.gridsense.cloud"

# 443 is the secure WSS port
url = f"wss://{HOST}:{443}/ws/m/{ORG_ID}/c/{CHANNEL_ID}"
headers = {
    "Authorization": f"Client {DEVICE_SECRET}"
}

ssl_context = ssl.create_default_context()
ssl_context.check_hostname = True
ssl_context.verify_mode = ssl.CERT_REQUIRED

with closing(
    create_connection(
        url=url,
        header=[f"{k}: {v}" for k, v in headers.items()],
        sslopt={
            "cert_reqs": ssl.CERT_REQUIRED,
            "ca_certs": "/etc/ssl/cert.pem", # default CA certificates path on Linux/macOS
        },
    ),
) as ws:
    pass
    data = json.dumps( 
        [ 
            { 
                "bn": "org/lighting/SmartLight/", 
                "bt": time.time(), 
                "n": "brightness", 
                "u": "lm", 
                "v": round(random.uniform(100, 3000), 2), 
            }, 
            {"n": "power", "u": "W", "v": round(random.uniform(6.7, 200), 2)}, 
        ] 
    ) 
    ws.send(data) 

HTTP

We will use the requests library. Make sure to install it before running the script.

Prepare your credentials

Python
DEVICE_ID = "..."
DEVICE_SECRET = "..."
CHANNEL_ID = "..."
ORG_ID = "..."
HOST = "api.gridsense.cloud"

Construct the connection URL

Python
DEVICE_ID = "..."
DEVICE_SECRET = "..."
CHANNEL_ID = "..."
ORG_ID = "..."
HOST = "api.gridsense.cloud"

url = f"https://{HOST}/http/m/{ORG_ID}/c/{CHANNEL_ID}/"
headers = { 
    "Authorization": f"Client {DEVICE_SECRET}", 
    "Content-Type": "application/json", 
} 

Send a message

Python
import requests 
import json     
import time     
import random   

DEVICE_ID = "..."
DEVICE_SECRET = "..."
CHANNEL_ID = "..."
ORG_ID = "..."
HOST = "api.gridsense.cloud"

url = f"https://{HOST}/http/m/{ORG_ID}/c/{CHANNEL_ID}/"
headers = {
    "Authorization": f"Client {DEVICE_SECRET}",
    "Content-Type": "application/json",
}

data = json.dumps( 
    [ 
        { 
            "bn": "org/lighting/SmartLight/", 
            "bt": time.time(), 
            "n": "brightness", 
            "u": "lm", 
            "v": round(random.uniform(100, 3000), 2), 
        }, 
        {"n": "power", "u": "W", "v": round(random.uniform(6.7, 200), 2)}, 
    ] 
) 
response = requests.post(url=url, data=data, headers=headers) 

Wrapping up

Congratulations! You've sent your first message to Gridsense

This only serves as a very basic tutorial on how to send a message. You can build upon this tutorial to automate the process of getting data from your devices, processing that data, and sending it to Gridsense.

Of course, you can use any programming language and MQTT library you wish, and you're not restricted to Python and/or Paho MQTT.

For more details, refer to the respective device APIs:

On this page