databridges_sio_server_lib 2.0.5
Databridges Python server Library
Keywords: optomate, databridges, pubsub, rpc, websocket, socket.io, ws, events, realtime, real-time

![](https://img.shields.io/badge/Licence-Apache%202.0-green.svg)![](https://shields.io/badge/python-+3.6-blue)

# Databridges Python server Library


DataBridges makes it easy for connected devices and applications to communicate with each other in realtime in an efficient, fast, reliable and trust-safe manner. Databridges Python server library allows you to easily add realtime capabilities to your applications in record time.

## Have you registered with dataBridges?

Registering allows you to access our production grade PlayGround network. You can take dataBridges for a spin and quickly create, test your proof of concepts without needing to create a payment account.

We would love to see what you build on dataBridges platform. We are available at tech@optomate.io to answer all your queries.

https://www.databridges.io/developers.html

## Usage Overview

The following topics are covered:
- [Supported platforms](#supported-platforms)
- [Installation](#installation)
- [Initialization](#initialization)
- [Global Configuration](#global-configuration)
  - [Required](#required)
  - [Optional](#optional)
- [Connection](#connection)
- [Objects](#objects)
- [object:ConnectionState](#objectconnectionstate)
  - [Properties](#properties)
  - [Bind to connectionstate events](#bind-to-connectionstate-events)
  - [Functions](#functions)
- [object:Channel](#objectchannel)
  - [Subscribe to Channel](#subscribe-to-channel)
  - [Channel Information](#channel-information)
  - [Publish to Channel](#publish-to-channel)
  - [Send Message to Members / sessionID](#send-message-to-members--sessionid)
  - [Binding to events](#binding-to-events)
  - [System events for channel object](#system-events-for-channel-object)
- [object: rpc (Remote Procedure Call)](#object-rpc-remote-procedure-call)
  - [Initialize rpc Server](#initialize-rpc-server)
  - [Register rpc functions](#register-rpc-functions)
  - [Register Server](#register-server)
  - [Unregister Server](#unregister-server)
  - [resetqueue()](#resetqueue)
  - [System events for rpc server registration.](#system-events-for-rpc-server-registration)
  - [Server Information](#server-information)
  - [Connect to Server](#connect-to-server)
  - [Execute Remote Procedure Call](#execute-remote-procedure-call)
- [object:Cf (Client Function)](#objectcf-client-function)
  - [Execute Client Functions](#execute-client-functions)
  - [Properties](#properties)
- [Rate Limit and Concurrent connection](#rate-limit-and-concurrent-connection)
- [Change Log](#change-log)
- [License](#license)

## Supported platforms

Supports Python versions  +3.6

## Installation

You can use pip package manager to install the package.

```bash
pip3 install databridges_sio_server_lib
```

> Note : Databridges library uses socket.io for websocket protocol management.

## Initialization

```python
from databridges_sio_server_lib import dBridges
from databridges_sio_server_lib.exceptions import dBError
dbridge = dBridges()
```

## Global Configuration

### Required

The following is the list of required connection properties before connecting to dataBridges network.

```python
dbridge.auth_url = 'URL'
dbridge.appkey = 'APP_KEY'
dbridge.appsecret = 'APP_SECRET'
```

You need to replace `URL` , `APP_KEY` and `APP_SECRET` with the actual URL ,Application Key and Application Secret.

| Properties  | Description                                                  | Exceptions                                               |
| ----------- | ------------------------------------------------------------ | -------------------------------------------------------- |
| `auth_url`  | *(string)* Authentication url from  [dataBridges dashboard](https://dashboard.databridges.io/). | `source: DBLIB_CONNECT` <br />`code: INVALID_URL`        |
| `appkey`    | *(string)* Application Key from  [dataBridges dashboard](https://dashboard.databridges.io/). | `source: DBLIB_CONNECT` <br />`code: INVALID_AUTH_PARAM` |
| `appsecret` | *(string)* Application Secret from  [dataBridges dashboard](https://dashboard.databridges.io/). | `source: DBLIB_CONNECT` <br />`code: INVALID_AUTH_PARAM` |

### Optional

The following is the list of optional connection properties before connecting to dataBridges network.

```python
dbridge.maxReconnectionRetries = 10
dbridge.maxReconnectionDelay = 120000 
dbridge.minReconnectionDelay = 1000 + (new Random()).NextDouble() * 4000
dbridge.reconnectionDelayGrowFactor = 1.3
dbridge.minUptime = 200  
dbridge.connectionTimeout = 10000
dbridge.autoReconnect = true 
dbridge.cf.enable = false 
```

| Properties                    | Default                       | Description                                                  |
| ----------------------------- | ----------------------------- | ------------------------------------------------------------ |
| `maxReconnectionDelay`        | `10`                          | *(integer)* The maximum delay between two reconnection attempts in seconds. |
| `minReconnectionDelay`        | `1000 + Math.random() * 4000` | *(integer)* The initial delay before reconnection in milliseconds (affected by the `reconnectionDelayGrowFactor` value). |
| `reconnectionDelayGrowFactor` | `1.3`                         | *(float)* The randomization factor used when reconnecting (so that the clients do not reconnect at the exact same time after a server crash). |
| `minUptime`                   | `200`                         | *(integer)* Uptime before `connected` event is triggered, value in milliseconds. |
| `connectionTimeout`           | `10000`                       | *(integer)* Number of milliseconds the library will wait for a connection to be established. If it fails it will emit a `connection_error` event. |
| `maxReconnectionRetries`      | `10`                          | *(integer)* The number of reconnection attempts before giving up. |
| `autoReconnect`               | `true`                        | *(boolean*) If false, library will not attempt reconnecting. |
| `cf.enable`                   | `false`                       | *(boolean)* Enable exposing *client function* for this connection. (Check *Client Function* section for details.) |

## Connection

Once the properties are set, use `connect()` function to connect to dataBridges Network.

```python
try:
    await dbridge.connect()
except Exception as e:
	print("source: {0} ,  code: {1}, message: {2}".format(e.source , e.code , e.message))
```

#### Exceptions: 

| Source        | Code                   | Message                         | Description                                                  |
| ------------- | ---------------------- | ------------------------------- | ------------------------------------------------------------ |
| DBLIB_CONNECT | INVALID_URL            |                                 | Value of `dbridge.auth_url` is not a valid dataBridges authentication URL. |
| DBLIB_CONNECT | INVALID_AUTH_PARAM     |                                 | Value of `dbridge.appkey` **or** `dbridge.appsecret`  is not a valid dataBridges application key. |
| DBLIB_CONNECT | ACCESSTOKEN_FAILED     |                                 | `dbridge.appsecret` validation failed.                       |
| DBLIB_CONNECT | HTTP_                  | HTTP protocol reported message. | HTTP Errors returned during authentication process. ***HTTP Error code*** will be concatenated with `HTTP_` in the `err.code`. `eg. HTTP_501` |
| DBLIB_CONNECT | INVALID_CLIENTFUNCTION |                                 | If *"callback function"* is not declared for client function **or** `typeof()` variable defined is not a *"function"*. This is applicable only if clientFunction is enabled. *(Check Client Function section for details.)* |

#### sessionid *(string)*

```python
print("sessionid: {0}".format( dbridge.sessionid))
```

Making a connection provides the application with a new `sessionid` that is assigned by the application. This can be used to distinguish the application's own events. A change of state might otherwise be duplicated in the application. It is also stored within the connection, and used as a token for generating signatures for private/presence/system channels/rpc functions.

#### disconnect *(function)*

To **close a connection** use disconnect function. When a connection has been closed explicitly, no automatic reconnection will happen.

```python
await dbridge.disconnect()
```

## Objects

| Object            | Description                                                  |
| ----------------- | ------------------------------------------------------------ |
| `connectionstate` | connectionstate object expose properties, functions and events to monitor and manage the health of  dataBridges network connection. |
| `channel`         | channel object exposes **trust-safe** flexible Pub/Sub messaging properties, functions and events to build realtime event messaging / event driven applications at scale. |
| `rpc`             | rpc object exposes **trust-safe** properties, functions and events to provide reliable two-way messaging between multiple endpoints allowing you to build sophisticated asynchronous interactions. |
| `cf`              | CF (Client-function) object is a special purpose RPC implementation to build command and control applications. CF object exposes properties, functions and events for command and control applications to send messages to devices and application using dataBridges client library in **trust-safe manner **, build smart update configuration system and implement **trust-safe ** actions for remote and automated management. |



## object:ConnectionState

Connectionstate object expose properties, functions and events to monitor and manage the health of dataBridges network connection.

### Properties

The following is the list of connection state properties.

```python
print(dbridge.connectionstate.state)
print(dbridge.connectionstate.isconnected)
print(dbridge.connectionstate.rttms)
print(dbridge.connectionstate.reconnect_attempt)
```

| Property                            | Description                                                  |
| ----------------------------------- | ------------------------------------------------------------ |
| `connectionstate.state`             | *(String)* Current state of dataBridges network connection . List of Return Values are detailed below. |
| `connectionstate.isconnected`       | *(Boolean)* To verify if the application is still connected to the dataBridges network. |
| `connectionstate.rttms`             | *(integer)* Latency in milliseconds between your application and the dataBridges router where your application is connected. |
| `connectionstate.reconnect_attempt` | (integer) Number of reconnection attempted as of now.        |

##### connectionstate.state

| Return Values      | Description                                                  |
| ------------------ | ------------------------------------------------------------ |
| *connecting*       | Your application is now attempting to connect to dataBridges network. |
| *connected*        | The connection to dataBridges network is open and authenticated with your `appkey`. |
| *connection_break* | Indicates a network disconnection between application and dataBridges network. The library will initiate an automatic reconnection, if the reconnection property is set as true. |
| *connect_error*    | This event will show system messages related to dataBridges network as well as Rate-limit exceptions (details in Rate-limit section). |
| *disconnected*     | The application is now disconnected from the dataBridges network. The application will than need to initiate fresh connection attempt again. |
| *reconnecting*     | Your application is now attempting to reconnect to dataBridges network as per properties set for reconnection. |
| *reconnect_error*  | Reconnection attempt has errored.                            |
| *reconnect_failed* | The application will enter reconnect_failed state when all the reconnection attempts have been exhausted unsuccessfully. The application is now disconnected from the dataBridges network. The application will than need to initiate fresh connection attempt again |
| *reconnected*      | *The application has successfully re-connected to the dataBridges network,* This state will follow `connect_error` **or** `reconnect_error`. |

### Bind to connectionstate events

Apart from retrieveing state of a dBrige connection, application can bind to connectionstate events.

You can use the following methods on connectionstate object to bind to events.

```python
dbridge.connectionstate.bind(eventName, callable)
dbridge.connectionstate.unbind(eventName)
dbridge.connectionstate.unbind()
```

`bind()` on `eventName` has callback functions to be defined where you can write your own code as per requirement.

To stop listening to events use `unbind(eventName)` function.

To stop listening to all events use `unbind()` *[without eventName]* function.

Below are library events which can be bind to receive information about dataBridges network.

#### System events for connectionstate object

```python
async def connecting():
    print("connecting")

async def reconnecting():
    print("reconnecting")

async def connection_break():
    print("connection_break")

async def state_change( data):
    print("state_change:", data)

async def connect_error( data):
    if isinstance(data, str):
        print("connect_error:" + str(data))
    if isinstance(data, dBError.dBError):
        print(data.code, data.source, data.message)

async def reconnect_error(data):
    if isinstance(data, str):
        print("connect_error:" + str(data))
    if isinstance(data, dBError.dBError):
        print(data.code, data.source, data.message)

async def reconnect_failed( data):
    print("reconnect_failed:", data)

async def reconnected():
    print("reconnected:")

async def rttpong(data=None):
    print("rttpong:", .dbridge.connectionstate.rttms)
    
async def disconnected():
    print("disconnected:")

async def connected():
    print("connected...")

try:
      dbridge.connectionstate.bind("connecting", connecting)
      dbridge.connectionstate.bind("reconnecting", reconnecting)
      dbridge.connectionstate.bind("connection_break", connection_break)
      dbridge.connectionstate.bind("state_change", state_change)
      dbridge.connectionstate.bind("connect_error", connect_error)
      dbridge.connectionstate.bind("reconnect_error", reconnect_error)
      dbridge.connectionstate.bind("reconnect_failed", reconnect_failed)
      dbridge.connectionstate.bind("reconnected", reconnected)
      dbridge.connectionstate.bind("rttpong", rttpong)
      dbridge.connectionstate.bind("connected", connected)
      dbridge.connectionstate.bind("disconnected", disconnected)
      
except Exception as e:
  	print(e.code, e.source, e.message)
```
###### payload: `(dberror object)`

```python
{
    "source": "DBLIB_CONNECT" , 			// (string) Error source
    "code": "RECONNECT_ATTEMPT_EXCEEDED",	// (string) Error code 
    "message": "" 							// (string) Error message if applicable.
}
```

| Events             | Parameters                                         | Description                                                  |
| ------------------ | -------------------------------------------------- | ------------------------------------------------------------ |
| `connecting`       |                                                    | This event is triggered when your application is attempting to connect to dataBridges network. |
| `connected`        |                                                    | This event is triggered when connection to dataBridges network is open and authenticated with your `appkey.` |
| `connection_break` | *payload*                                          | *(dberror object)* Indicates a network disconnection between application and dataBridges network. The library will initiate an automatic reconnection, if the reconnection property is set as true. |
| `connect_error`    | *payload*                                          | *(dberror object)* This event is triggered when the dataBridges network connection was previously connected and has now errored and closed. |
| `disconnected`     |                                                    | The application is now disconnected from the dataBridges network. The application will than need to initiate fresh connection attempt again. |
| `reconnecting`     |                                                    | This event is triggered when  application is now attempting to reconnect to dataBridges network as per properties set for reconnection. |
| `reconnect_error`  | *payload*                                          | *(dberror object)* This event is triggered when reconnection attempt has errored. |
| `reconnect_failed` | *payload*                                          | *(dberror object)* reconnect_failed event is triggered when all the reconnection attempts have been exhaused unsuccessfully. The application is now disconnected from the dataBridges network. The application will than need to initiate fresh connection attempt again. |
| `reconnected`      |                                                    | This event is triggered when the connection to dataBridges network is open and reconnected after `connect_error` **or** `reconnect_error`. |
| `state_change`     | *payload* with `payload.previous, payload.current` | *(dict)* This event is triggered whenever there is any state changes in dataBridges network connection. Payload will have previous and current state of connection. |
| `rttpong`          | `payload`                                          | *(integer)* In Response to `rttping()` function call to dataBridges network, payload has latency in milliseconds between your application and the dataBridges router where your application is connected. |

#### dberror: 

| Source        | Code                       | Message                         | Description                                                  |
| ------------- | -------------------------- | ------------------------------- | ------------------------------------------------------------ |
| DBLIB_CONNECT | RECONNECT_ATTEMPT_EXCEEDED |                                 | Triggered when `reconnect_failed` event is raised.           |
| DBNET_CONNECT | DISCONNECT_REQUEST         |                                 | Triggered when `connect_error` event is raised.              |
| DBNET_CONNECT | RECONNECT_REQUEST          |                                 | Triggered when `connect_error`, `connection_break`  event is raised. |
| DBLIB_CONNECT | NETWORK_DISCONNECTED       |                                 | Triggered when `connect_error`, `reconnect_error`  event is raised. |
| DBLIB_CONNECT | INVALID_URL                |                                 | Value of `dbridge.auth_url` is not a valid dataBridges authentication URL. |
| DBLIB_CONNECT | INVALID_AUTH_PARAM         |                                 | Value of `dbridge.appkey` **or** `dbridge.appsecret`  is not a valid dataBridges application key. |
| DBLIB_CONNECT | ACCESSTOKEN_FAILED         |                                 | `dbridge.appsecret` validation failed.                       |
| DBLIB_CONNECT | HTTP_                      | HTTP protocol reported message. | HTTP Errors returned during authentication process. ***HTTP Error code*** will be concatenated with `HTTP_` in the `err.code`. `eg. HTTP_501` |
| DBLIB_CONNECT | INVALID_CLIENTFUNCTION     |                                 | If *"callback function"* is not declared for client function **or** `typeof()` variable defined is not a *"function"*. *(Check Client Function section for details.)* |

#### Exceptions: 

| Source             | Code              | Description                                                  |
| ------------------ | ----------------- | ------------------------------------------------------------ |
| DBLIB_CONNECT_BIND | INVALID_EVENTNAME | Invalid Event name. Not in defined events as above.          |
| DBLIB_CONNECT_BIND | INVALID_CALLBACK  | If *"callback function"* is not declared **or** `typeof()` variable defined is not a *"function"*. |

### Functions

#### rttping()

This method is to understand the latency in milliseconds between your application and the dataBridges router where your application is connected. Event `rttpong` is triggered once response  is received from dataBridges network. Bind to event:`rttpong` to retrieve the latency in ms. 

```python
# To get the last known Latency in milliseconds between your application and the dataBridges router where your application is connected.
# The dataBridges library exchanges rttms during the initial dataBridges network connection routine.
print(dbridge.connectionstate.rttms);

# To get the latest Latency in milliseconds between your application and the dataBridges router where your application is connected.
try:
    dbridge.connectionstate.rttping();
    expect Exception as err:
        Console.WriteLine("{0} ,  {1} , {2}" , err.source, err.code, err.message);

# Bind to rttpong, to get notified about the latest Latency in milliseconds between your application and the dataBridges router where your application is connected.

def rttpong(payload):
    Console.WriteLine(payload);
    //payload is an integer value is in millisecond which is same as dbridge.connectionstate.rttms.

try:
	dbridge.connectionstate.bind("rttpong",rttpong);
    expect Exception as err:
 	Console.WriteLine("{0} ,  {1} , {2}" , err.source, err.code, err.message);
```

#### Exceptions: 

| Source        | Code                 | Description                                      |
| ------------- | -------------------- | ------------------------------------------------ |
| DBLIB_RTTPING | NETWORK_DISCONNECTED | Connection to dataBridges network is not active. |



------



## object:Channel

channel object exposes **trust-safe** flexible Pub/Sub messaging properties, functions and events to build realtime event messaging / event driven applications at scale.

Concepts

- A message is attached to an event
- Group similar events into a channel
- Subscribe to a channel to receive all channel event messages. 
- Publish event message to the channel and it will be sent to all the channel subscribers who are connected to dataBridges network and online.
- if you need to have an access controlled channel, prefix the channel name with pvt: , prs: and sys: .
  - **Note** dataBridges have 2 seprate libraries (client lib, server lib).  You are reading the server library api document.
    - Server lib uses app.key along with secret to get  access to all channels including pvt: , prs: and sys: channels linked to the application.
    - Whereas application using client library (client application) will always need to pass a trust-token to access restricted channels (pvt: prs: sys: ) . A trust-token is a JWT document created using a combination of channelname + sessionid + app.secret. Trust token can be created by application having access to app.key's secret.
      - you can use your existing access control,  authorization and session identification rule-set, process and methods to create a trust-token instructing the dataBridges router to accept the pvt: prs: and sys: channel subscription, connection of from client application.
      - Trust-tokens allows you to enable secured, access controlled and compliance driven realtime event driven messaging in your existing and new initiative applications.


dataBridges library supports **4** types of channel. The *namespace is the  4 characters* preceding the channelName (`pvt:,prs:,sys:`), identifying which type of channel the application is connecting to.

| Channel Type | Channel Name Style | Description                                                  |
| ------------ | ------------------ | ------------------------------------------------------------ |
| Public       | channelName        | Public channel is used to send and receive messages that are to be publicly available. This channel type does not require any trust authorization token to subscribe. <br />*e.g  channelName =* `mychannel` |
| Private      | **pvt:**channeName | Private channels is restricted channel. *e.g  channelName =* `mychannel` |
| Presence     | **prs:**channeName | Presence channels is a specialized private channel with additional feature of presence awareness. Subscribing to presence channel allows application to be notified of members joining / leaving the channel. *e.g  channelName =* `prs:mychannel` |
| System       | **sys:**channeName | System channel is a specialized Presence channel to build command and control applications. Using System channel to create command and control server applications to send messages to devices and application using dataBridges library in **trust-safe manner **, build smart update configuration system and implement **trust-safe ** actions for remote and automated management. System channel allows application to send and receive messages with the server application (using dataBridges server library). <br />*e.g  channelName =* `sys:systeminfo` |

### Subscribe to Channel

Application that subscribes to a channel will receive messages and can send messages.

#### subscribe()

The default method for subscribing to a channel involves invoking the `channel.subscribe` function of your dataBridges object:

```python
try:
    subscribed_channel =  await dbridge.channel.subscribe('mychannel')
except dBError as e:
  	print(e.code, e.source, e.message)
```

| Parameter | Rules                                                        | Description                                     |
| --------- | ------------------------------------------------------------ | ----------------------------------------------- |
| `string`  | `channelName` **OR**<br />`pvt:channelName` **OR**<br />`prs:channelName` **OR**<br />`sys:channelName`**OR**<br />`sys:*` | *channelName* to which subscription to be done. |

| Return Type | Description                                                  |
| ----------- | ------------------------------------------------------------ |
| `object`    | *channel* object which events and related functions can be bound to. |

Application can directly work with dataBridges object without using Channel object. 

```python
try {
    dbridge.channel.subscribe('mychannel')
} catch (dBError err) {
    Console.WriteLine("{0} ,  {1} , {2}" , err.source, err.code, err.message)
}
```

##### Exceptions: 

| Source                  | Code                       | Description                                                  |
| ----------------------- | -------------------------- | ------------------------------------------------------------ |
| DBLIB_CHANNEL_SUBSCRIBE | NETWORK_DISCONNECTED       | Connection to dataBridges network is not active.             |
| DBLIB_CHANNEL_SUBSCRIBE | INVALID_CHANNELNAME        | Applicable for below conditions <br />1. *channelName* is not defined.<br />2. *channelName* validation error, `typeof()`  *channelName*  is not type string<br />3. *channelName* validation error, *channelName* fails `a-zA-Z0-9\.:_-` validation. |
| DBLIB_CHANNEL_SUBSCRIBE | INVALID_CHANNELNAME_LENGTH | *channelName* validation error, length of *channelName*  greater than **64** |
| DBLIB_CHANNEL_SUBSCRIBE | CHANNEL_ALREADY_SUBSCRIBED | *channelName* is already subscribed.                         |

#### unsubscribe() 

To unsubscribe from a subscribed channel, invoke the `unsubscribe` function of your dataBridges object. `unsubscribe` cannot be done on channel object.

```python
try:
    dbridge.channel.unsubscribe('mychannel')
except dBError as e:
  	print(e.code, e.source, e.message)
```

| Parameter | Rules                                                        | Description                                        |
| --------- | ------------------------------------------------------------ | -------------------------------------------------- |
| `string`  | *channelName **OR**<br />**pvt:**channelName **OR**<br />**prs:**channelName **OR**<br />**sys:**channelName* | *channel*Name to which un-subscription to be done. |

| Return Type | Description |
| ----------- | ----------- |
| `NA`        |             |

##### Exceptions: 

| Source                    | Code                          | Description                                                  |
| ------------------------- | ----------------------------- | ------------------------------------------------------------ |
| DBLIB_CHANNEL_UNSUBSCRIBE | NETWORK_DISCONNECTED          | Connection to dataBridges network is not active.             |
| DBLIB_CHANNEL_UNSUBSCRIBE | CHANNEL_NOT_SUBSCRIBED        | *channelName* is not subscribed.                             |
| DBLIB_CHANNEL_UNSUBSCRIBE | UNSUBSCRIBE_ALREADY_INITIATED | unsubscription to the channel is already initiated and hence the current unsubscribe command exited with exception. |

### Channel Information

#### isOnline()

*<u>dBridgeObject</u>* as well as *<u>channelObject</u>* provides a function to check if the channel is online. The best practice is to check the channel is online before publishing any message.

```python
isonline = dbridge.channel.isOnline('mychannel')
```

```python
isonline = subscribed_channel.isOnline()
```

| Parameter | Rules                                                        | Description   |
| --------- | ------------------------------------------------------------ | ------------- |
| `string`  | *channelName **OR**<br />**pvt:**channelName **OR**<br />**prs:**channelName **OR**<br />**sys:**channelName* | *channel*Name |

| Return Values | Description                                         |
| ------------- | --------------------------------------------------- |
| `boolean`     | Is the current status of channel online or offline. |

#### list()

<u>*dBridgeObject*</u>  provides a function to get list of successfully subscribed or connected channel. 

```python
channels = dbridge.channel.list()
#=> [{"name":  "mychannel" , "type": "subscribed/connect" ,  "isonline": True/False }]
```

| Return Type     | Description                                |
| --------------- | ------------------------------------------ |
| `array of dict` | Array of channels subscribed or connected. |

Dictionary contains below information.

| Key        | Description                                                  |
| ---------- | ------------------------------------------------------------ |
| `name`     | *(string)* *channelName* of subscribed or connected channel. |
| `type`     | *(string)* `subscribed`                                      |
| `isonline` | *(boolean)* Is the current status of channel online or offline. |

#### getChannelName() 

*<u>channelObject</u>* provides a function to get the *channelName*. 

```python
chName = channelobject.getChannelName()
```

| Return Type | Description                          |
| ----------- | ------------------------------------ |
| `string`    | *channelName* of subscribed channel. |

### Publish to Channel 

Publish event-message using the `publish` function on an instance of the `channel` object.

A message is linked to an event and hence event-message. dataBridges allows you to bind to various events to create rich event processing flows. 

#### publish()

The default method for publishing user-defined events to a channel involves invoking the `channel.publish` function of your *channelObject*  for which it has connected to **OR** using *dbridgeObject* giving the *channelName* as parameter. 

**Note:** `channel.publish` is not allowed using *channelObject* subscribed to `sys:*` channel. 

```python
# Using dbridgeObject 
try:
    dbridge.channe.publish(channelName, event, payload, excludeSessionId, sourceId, seqno)
except dBError as e:
  print(e.code, e.source, e.message) 

# Using channelObject 
try:
    channelObject.publish(eventname, payload, excludeSessionId, sourceId, seqno)
except dBError as e:
  print(e.code, e.source, e.message)

#// Best practice is to check the channel is online before publishing any message.
if channelObject.isOnline():
    try:
        channelObject.publish(eventname, payload, excludeSessionId, sourceId, seqno)
    except dBError as e:
      print(e.code, e.source, e.message)
```

| Parameter          | Description                                                  |
| ------------------ | ------------------------------------------------------------ |
| `channelName`      | *(string)* Channel name for which details are required.      |
| `event`            | *(string)* *event* Name to which the message to be sent. *event* Name cannot start with `dbridges:` |
| `payload`          | *(string)* Payload to be sent with the event.                |
| `excludeSessionId` | *(string)* Excludes the event from being sent to a specific sessionid (connection).<br /><br />For example when a server application (example: chat server) sends event message on behalf of a specific session ( example: chat user) to a channel (example: chat group),  the sessionID (example: chat user) will be excluded to receive its own message. |
| `sourceId`         | *(string)* Required in case of *presence*(`prs:`) and *system* (`sys:`) channel. When sending a message to a *presence*(`prs:`) or *system* (`sys:`) channel, application need to specify a message source by using this sourceId.<br /><br />For example when a server application (example: chat server) sends event message on behalf of a specific session ( example: chat user) to a channel (example: chat group),  the sourceID (example: chat user information) can be attached usiing sourceID to the event message. This allows all message receipient to know who has sent the message. |
| `seqno`            | *(string) [optional]* Message sequence number. This is optional parameter. `seqno` can be used by applications to manage message queue processing by the subscribers. |

| Return Values | Description |
| ------------- | ----------- |
| `NA`          |             |

##### Exceptions: 

| Source                | Code                       | Description                                                  |
| --------------------- | -------------------------- | ------------------------------------------------------------ |
| DBLIB_CHANNEL_PUBLISH | NETWORK_DISCONNECTED       | Connection to dataBridges network is not active.             |
| DBLIB_CHANNEL_PUBLISH | INVALID_CHANNELNAME        | *Applicable for below conditions <br />1. channelName* validation error, `typeof()`  *channelName*  is not type string <br />2. *channelName* validation error, *channelName* fails `a-zA-Z0-9\.:_-` validation. <br />3. *channelName* is `sys:*`<br />4. *channelName* is not defined. |
| DBLIB_CHANNEL_PUBLISH | INVALID_CHANNELNAME_LENGTH | *channelName* validation error, length of *channelName*  greater than **64** |
| DBLIB_CHANNEL_PUBLISH | INVALID_SUBJECT            | Applicable for below conditions <br />1. *event* validation error,  *event*  is not defined<br />2. *event* validation error, `typeof()`  *event*  is not type string |

### Send Message to Members / sessionID

It's possible to send message to individual `sessionId` using the `channel.sendmsg` function on an instance of the *channelObject* or using *dbridgeObject*.

#### sendmsg()

The default method for send message user-defined events to a individual `sessionId` involves invoking the `channel.sendmsg` function of your *channelObject*  for which it has connected to **OR** using *dbridgeObject* giving the *channelName* as parameter. 

**Note:** `channel.sendmsg` is not allowed using *channelObject* subscribed to `sys:*` channel. 

```python
# Using dbridgeObject 
try:
    dbridge.channel.sendmsg(channelName, event, payload, toSessionId, sourceId, seqno)
except dBError as e:
    print(e.code, e.source, e.message) 

# Using channelObject 
try:
    channelObject.sendmsg( event, payload, toSessionId, sourceId, seqno)
except dBError as e:
    print(e.code, e.source, e.message) 

# Best practice is to check the channel is online before publishing any message.
if channelObject.isOnline():
    try:
        channelObject.sendmsg(event, payload, toSessionId, sourceId, seqno);
    except dBError as e:
    print(e.code, e.source, e.message) 
```

| Parameter     | Description                                                  |
| ------------- | ------------------------------------------------------------ |
| `channelName` | *(string)* Channel name for which details are required.      |
| `event`       | *(string)* *event* Name to which the message to be sent. *event* Name cannot start with `dbridges:` |
| `payload`     | *(string)* Payload to be sent with the event.                |
| `toSessionId` | *(string)* `sessionid` where the message  to be sent.        |
| `sourceId`    | *(string)* Required in case of *presence*(`prs:`) and *system* (`sys:`) channel. When sending a message to a *presence*(`prs:`) or *system* (`sys:`) channel, application need to specify a message source by using this sourceId. <br /><br />For example when a server application (example: chat server) sends event message on behalf of a specific session ( example: chat user) to a channel (example: chat group),  the sourceID (example: chat user information) can be attached usiing sourceID to the event message. This allows all message receipient to know who has sent the message. |
| `seqno`       | *(string) [optional]* Message sequence number. This is optional parameter. `seqno` can be used by applications to manage message queue processing by the subscribers. |

| Return Values | Description |
| ------------- | ----------- |
| `NA`          |             |

##### Exceptions: 

| Source                | Code                       | Description                                                  |
| --------------------- | -------------------------- | ------------------------------------------------------------ |
| DBLIB_CHANNEL_SENDMSG | NETWORK_DISCONNECTED       | Connection to dataBridges network is not active.             |
| DBLIB_CHANNEL_SENDMSG | INVALID_CHANNELNAME        | *Applicable for below conditions <br />1. channelName* validation error, `typeof()`  *channelName*  is not type string <br />2. *channelName* validation error, *channelName* fails `a-zA-Z0-9\.:_-` validation. <br />3. *channelName* is `sys:*`<br />4. *channelName* is not defined.<br />5. *channelType* is `prs:` and `sourceId` is not provided.<br />6. *channelName* contains `:` and first token is not `pvt,prs,sys` |
| DBLIB_CHANNEL_SENDMSG | INVALID_CHANNELNAME_LENGTH | *channelName* validation error, length of *channelName*  greater than **64** |

### Binding to events

A message is linked to an event and hence event-message. dataBridges allows you to bind to various events to create rich event processing flows. An application needs to bind to event to process the received message. 

You can use the following methods either on a *channelObject*, to bind to events on a particular channel; or on the *dbridgeObject*, to bind to events on all subscribed channels simultaneously.

#### `bind` and `unbind`

**Bind** to "event" on channel: payload and metadata is received.

```python
# Binding to channel events on channelObject  
def eventFunction(payload ,  metadata):
  	print(payload , metadata)

try:
    channelObject.bind('eventName',  eventFunction)
except dBError as e:
  	print(e.code, e.source, e.message) 

# Binding to channel events on dbridgeObject 
try {
    dbridge.channel.bind('eventName', eventFunction)
except dBError as e:
  	print(e.code, e.source, e.message) 
```

| Parameter | Description                                          |
| --------- | ---------------------------------------------------- |
| `event`   | *(string)* *event* Name to which binding to be done. |

##### Callback parameters

###### payload: