Package: databridges_sio_server_lib
Databridges Python server LibraryDataBridges 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.Usage OverviewThe following topics are covered:Supported platformsInstallationInitializationGlobal ConfigurationRequiredOptionalConnectionObjectsobject:ConnectionStatePropertiesBind to connectionstate eventsFunctionsobject:ChannelSubscribe to ChannelChannel InformationPublish to ChannelSend Message to Members / sessionIDBinding to eventsSystem events for channel objectobject: rpc (Remote Procedure Call)Initialize rpc ServerRegister rpc functionsRegister ServerUnregister Serverresetqueue()System events for rpc server registration.Server InformationConnect to ServerExecute Remote Procedure Callobject:Cf (Client Function)Execute Client FunctionsPropertiesChange LogLicenseSupported platformsSupports Python versions  +3.6InstallationYou can use pip package manager to install the package.pip3installdatabridges_sio_server_libNote : Databridges library uses socket.io for websocket protocol management.Initializationfromdatabridges_sio_server_libimportdBridgesfromdatabridges_sio_server_lib.exceptionsimportdBErrordbridge=dBridges()Global ConfigurationRequiredThe following is the list of required connection properties before connecting to dataBridges network.dbridge.auth_url='URL'dbridge.appkey='APP_KEY'dbridge.appsecret='APP_SECRET'You need to replaceURL,APP_KEYandAPP_SECRETwith the actual URL ,Application Key and Application Secret.PropertiesDescriptionExceptionsauth_url(string)Authentication url fromdataBridges dashboard.source: DBLIB_CONNECTcode: INVALID_URLappkey(string)Application Key fromdataBridges dashboard.source: DBLIB_CONNECTcode: INVALID_AUTH_PARAMappsecret(string)Application Secret fromdataBridges dashboard.source: DBLIB_CONNECTcode: INVALID_AUTH_PARAMOptionalThe following is the list of optional connection properties before connecting to dataBridges network.dbridge.maxReconnectionRetries=10dbridge.maxReconnectionDelay=120000dbridge.minReconnectionDelay=1000+(newRandom()).NextDouble()*4000dbridge.reconnectionDelayGrowFactor=1.3dbridge.minUptime=200dbridge.connectionTimeout=10000dbridge.autoReconnect=truedbridge.cf.enable=falsePropertiesDefaultDescriptionmaxReconnectionDelay10(integer)The maximum delay between two reconnection attempts in seconds.minReconnectionDelay1000 + Math.random() * 4000(integer)The initial delay before reconnection in milliseconds (affected by thereconnectionDelayGrowFactorvalue).reconnectionDelayGrowFactor1.3(float)The randomization factor used when reconnecting (so that the clients do not reconnect at the exact same time after a server crash).minUptime200(integer)Uptime beforeconnectedevent is triggered, value in milliseconds.connectionTimeout10000(integer)Number of milliseconds the library will wait for a connection to be established. If it fails it will emit aconnection_errorevent.maxReconnectionRetries10(integer)The number of reconnection attempts before giving up.autoReconnecttrue(boolean) If false, library will not attempt reconnecting.cf.enablefalse(boolean)Enable exposingclient functionfor this connection. (CheckClient Functionsection for details.)ConnectionOnce the properties are set, useconnect()function to connect to dataBridges Network.try:awaitdbridge.connect()exceptExceptionase:print("source:{0},  code:{1}, message:{2}".format(e.source,e.code,e.message))Exceptions:SourceCodeMessageDescriptionDBLIB_CONNECTINVALID_URLValue ofdbridge.auth_urlis not a valid dataBridges authentication URL.DBLIB_CONNECTINVALID_AUTH_PARAMValue ofdbridge.appkeyordbridge.appsecretis not a valid dataBridges application key.DBLIB_CONNECTACCESSTOKEN_FAILEDdbridge.appsecretvalidation failed.DBLIB_CONNECTHTTP_HTTP protocol reported message.HTTP Errors returned during authentication process.HTTP Error codewill be concatenated withHTTP_in theerr.code.eg. HTTP_501DBLIB_CONNECTINVALID_CLIENTFUNCTIONIf"callback function"is not declared for client functionortypeof()variable defined is not a"function". This is applicable only if clientFunction is enabled.(Check Client Function section for details.)sessionid(string)print("sessionid:{0}".format(dbridge.sessionid))Making a connection provides the application with a newsessionidthat 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)Toclose a connectionuse disconnect function. When a connection has been closed explicitly, no automatic reconnection will happen.awaitdbridge.disconnect()ObjectsObjectDescriptionconnectionstateconnectionstate object expose properties, functions and events to monitor and manage the health of  dataBridges network connection.channelchannel object exposestrust-safeflexible Pub/Sub messaging properties, functions and events to build realtime event messaging / event driven applications at scale.rpcrpc object exposestrust-safeproperties, functions and events to provide reliable two-way messaging between multiple endpoints allowing you to build sophisticated asynchronous interactions.cfCF (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:ConnectionStateConnectionstate object expose properties, functions and events to monitor and manage the health of dataBridges network connection.PropertiesThe following is the list of connection state properties.print(dbridge.connectionstate.state)print(dbridge.connectionstate.isconnected)print(dbridge.connectionstate.rttms)print(dbridge.connectionstate.reconnect_attempt)PropertyDescriptionconnectionstate.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.stateReturn ValuesDescriptionconnectingYour application is now attempting to connect to dataBridges network.connectedThe connection to dataBridges network is open and authenticated with yourappkey.connection_breakIndicates a network disconnection between application and dataBridges network. The library will initiate an automatic reconnection, if the reconnection property is set as true.connect_errorThe dataBridges network connection was previously connected and has now errored and closed.disconnectedThe application is now disconnected from the dataBridges network. The application will than need to initiate fresh connection attempt again.reconnectingYour application is now attempting to reconnect to dataBridges network as per properties set for reconnection.reconnect_errorReconnection attempt has errored.reconnect_failedThe 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 againreconnectedThe application has successfully re-connected to the dataBridges network,This state will followconnect_errororreconnect_error.Bind to connectionstate eventsApart 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.dbridge.connectionstate.bind(eventName,callable)dbridge.connectionstate.unbind(eventName)dbridge.connectionstate.unbind()bind()oneventNamehas callback functions to be defined where you can write your own code as per requirement.To stop listening to events useunbind(eventName)function.To stop listening to all events useunbind()[without eventName]function.Below are library events which can be bind to receive information about dataBridges network.System events for connectionstate objectasyncdefconnecting():print("connecting")asyncdefreconnecting():print("reconnecting")asyncdefconnection_break():print("connection_break")asyncdefstate_change(data):print("state_change:",data)asyncdefconnect_error(data):ifisinstance(data,str):print("connect_error:"+str(data))ifisinstance(data,dBError.dBError):print(data.code,data.source,data.message)asyncdefreconnect_error(data):ifisinstance(data,str):print("connect_error:"+str(data))ifisinstance(data,dBError.dBError):print(data.code,data.source,data.message)asyncdefreconnect_failed(data):print("reconnect_failed:",data)asyncdefreconnected():print("reconnected:")asyncdefrttpong(data=None):print("rttpong:",.dbridge.connectionstate.rttms)asyncdefdisconnected():print("disconnected:")asyncdefconnected():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)exceptExceptionase:print(e.code,e.source,e.message)payload:(dberror object){"source":"DBLIB_CONNECT",//(string)Errorsource"code":"RECONNECT_ATTEMPT_EXCEEDED",//(string)Errorcode"message":""//(string)Errormessageifapplicable.}EventsParametersDescriptionconnectingThis event is triggered when your application is attempting to connect to dataBridges network.connectedThis event is triggered when connection to dataBridges network is open and authenticated with yourappkey.connection_breakpayload(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_errorpayload(dberror object)This event is triggered when the dataBridges network connection was previously connected and has now errored and closed.disconnectedThe application is now disconnected from the dataBridges network. The application will than need to initiate fresh connection attempt again.reconnectingThis event is triggered when  application is now attempting to reconnect to dataBridges network as per properties set for reconnection.reconnect_errorpayload(dberror object)This event is triggered when reconnection attempt has errored.reconnect_failedpayload(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.reconnectedThis event is triggered when the connection to dataBridges network is open and reconnected afterconnect_errororreconnect_error.state_changepayloadwithpayload.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.rttpongpayload(integer)In Response torttping()function call to dataBridges network, payload has latency in milliseconds between your application and the dataBridges router where your application is connected.dberror:SourceCodeMessageDescriptionDBLIB_CONNECTRECONNECT_ATTEMPT_EXCEEDEDTriggered whenreconnect_failedevent is raised.DBNET_CONNECTDISCONNECT_REQUESTTriggered whenconnect_errorevent is raised.DBNET_CONNECTRECONNECT_REQUESTTriggered whenconnect_error,connection_breakevent is raised.DBLIB_CONNECTNETWORK_DISCONNECTEDTriggered whenconnect_error,reconnect_errorevent is raised.DBLIB_CONNECTINVALID_URLValue ofdbridge.auth_urlis not a valid dataBridges authentication URL.DBLIB_CONNECTINVALID_AUTH_PARAMValue ofdbridge.appkeyordbridge.appsecretis not a valid dataBridges application key.DBLIB_CONNECTACCESSTOKEN_FAILEDdbridge.appsecretvalidation failed.DBLIB_CONNECTHTTP_HTTP protocol reported message.HTTP Errors returned during authentication process.HTTP Error codewill be concatenated withHTTP_in theerr.code.eg. HTTP_501DBLIB_CONNECTINVALID_CLIENTFUNCTIONIf"callback function"is not declared for client functionortypeof()variable defined is not a"function".(Check Client Function section for details.)Exceptions:SourceCodeDescriptionDBLIB_CONNECT_BINDINVALID_EVENTNAMEInvalid Event name. Not in defined events as above.DBLIB_CONNECT_BINDINVALID_CALLBACKIf"callback function"is not declaredortypeof()variable defined is not a"function".Functionsrttping()This method is to understand the latency in milliseconds between your application and the dataBridges router where your application is connected. Eventrttpongis triggered once response  is received from dataBridges network. Bind to event:rttpongto retrieve the latency in ms.# 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();expectExceptionaserr: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.defrttpong(payload):Console.WriteLine(payload);//payloadisanintegervalueisinmillisecondwhichissameasdbridge.connectionstate.rttms.try:dbridge.connectionstate.bind("rttpong",rttpong);expectExceptionaserr:Console.WriteLine("{0},{1},{2}",err.source,err.code,err.message);Exceptions:SourceCodeDescriptionDBLIB_RTTPINGNETWORK_DISCONNECTEDConnection to dataBridges network is not active.object:Channelchannel object exposestrust-safeflexible Pub/Sub messaging properties, functions and events to build realtime event messaging / event driven applications at scale.ConceptsA message is attached to an eventGroup similar events into a channelSubscribe 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: .NotedataBridges 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 supports4types of channel. Thenamespace is the  4 characterspreceding the channelName (pvt:,prs:,sys:), identifying which type of channel the application is connecting to.Channel TypeChannel Name StyleDescriptionPublicchannelNamePublic 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.e.g  channelName =mychannelPrivate**pvt:**channeNamePrivate channels is restricted channel.e.g  channelName =mychannelPresence**prs:**channeNamePresence 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:mychannelSystem**sys:**channeNameSystem 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).e.g  channelName =sys:systeminfoSubscribe to ChannelApplication that subscribes to a channel will receive messages and can send messages.subscribe()The default method for subscribing to a channel involves invoking thechannel.subscribefunction of your dataBridges object:try:subscribed_channel=awaitdbridge.channel.subscribe('mychannel')exceptdBErrorase:print(e.code,e.source,e.message)ParameterRulesDescriptionstringchannelNameORpvt:channelNameORprs:channelNameORsys:channelNameORsys:*channelNameto which subscription to be done.Return TypeDescriptionobjectchannelobject which events and related functions can be bound to.Application can directly work with dataBridges object without using Channel object.try{dbridge.channel.subscribe('mychannel')}catch(dBErrorerr){Console.WriteLine("{0},{1},{2}",err.source,err.code,err.message)}Exceptions:SourceCodeDescriptionDBLIB_CHANNEL_SUBSCRIBENETWORK_DISCONNECTEDConnection to dataBridges network is not active.DBLIB_CHANNEL_SUBSCRIBEINVALID_CHANNELNAMEApplicable for below conditions1.channelNameis not defined.2.channelNamevalidation error,typeof()channelNameis not type string3.channelNamevalidation error,channelNamefailsa-zA-Z0-9\.:_-validation.DBLIB_CHANNEL_SUBSCRIBEINVALID_CHANNELNAME_LENGTHchannelNamevalidation error, length ofchannelNamegreater than64DBLIB_CHANNEL_SUBSCRIBECHANNEL_ALREADY_SUBSCRIBEDchannelNameis already subscribed.unsubscribe()To unsubscribe from a subscribed channel, invoke theunsubscribefunction of your dataBridges object.unsubscribecannot be done on channel object.try:dbridge.channel.unsubscribe('mychannel')exceptdBErrorase:print(e.code,e.source,e.message)ParameterRulesDescriptionstring*channelNameOR**pvt:**channelNameOR**prs:**channelNameOR**sys:*channelNamechannelName to which un-subscription to be done.Return TypeDescriptionNAExceptions:SourceCodeDescriptionDBLIB_CHANNEL_UNSUBSCRIBENETWORK_DISCONNECTEDConnection to dataBridges network is not active.DBLIB_CHANNEL_UNSUBSCRIBECHANNEL_NOT_SUBSCRIBEDchannelNameis not subscribed.DBLIB_CHANNEL_UNSUBSCRIBEUNSUBSCRIBE_ALREADY_INITIATEDunsubscription to the channel is already initiated and hence the current unsubscribe command exited with exception.Channel InformationisOnline()dBridgeObjectas well aschannelObjectprovides a function to check if the channel is online. The best practice is to check the channel is online before publishing any message.isonline=dbridge.channel.isOnline('mychannel')isonline=subscribed_channel.isOnline()ParameterRulesDescriptionstring*channelNameOR**pvt:**channelNameOR**prs:**channelNameOR**sys:*channelNamechannelNameReturn ValuesDescriptionbooleanIs the current status of channel online or offline.list()dBridgeObjectprovides a function to get list of successfully subscribed or connected channel.channels=dbridge.channel.list()#=> [{"name":  "mychannel" , "type": "subscribed/connect" ,  "isonline": True/False }]Return TypeDescriptionarray of dictArray of channels subscribed or connected.Dictionary contains below information.KeyDescriptionname(string)channelNameof subscribed or connected channel.type(string)subscribedisonline(boolean)Is the current status of channel online or offline.getChannelName()channelObjectprovides a function to get thechannelName.chName=channelobject.getChannelName()Return TypeDescriptionstringchannelNameof subscribed channel.Publish to ChannelPublish event-message using thepublishfunction on an instance of thechannelobject.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 thechannel.publishfunction of yourchannelObjectfor which it has connected toORusingdbridgeObjectgiving thechannelNameas parameter.Note:channel.publishis not allowed usingchannelObjectsubscribed tosys:*channel.# Using dbridgeObjecttry:dbridge.channe.publish(channelName,event,payload,excludeSessionId,sourceId,seqno)exceptdBErrorase:print(e.code,e.source,e.message)# Using channelObjecttry:channelObject.publish(eventname,payload,excludeSessionId,sourceId,seqno)exceptdBErrorase:print(e.code,e.source,e.message)#// Best practice is to check the channel is online before publishing any message.ifchannelObject.isOnline():try:channelObject.publish(eventname,payload,excludeSessionId,sourceId,seqno)exceptdBErrorase:print(e.code,e.source,e.message)ParameterDescriptionchannelName(string)Channel name for which details are required.event(string)eventName to which the message to be sent.eventName cannot start withdbridges:payload(string)Payload to be sent with the event.excludeSessionId(string)Excludes the event from being sent to a specific sessionid (connection).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 ofpresence(prs:) andsystem(sys:) channel. When sending a message to apresence(prs:) orsystem(sys:) channel, application need to specify a message source by using this sourceId.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.seqnocan be used by applications to manage message queue processing by the subscribers.Return ValuesDescriptionNAExceptions:SourceCodeDescriptionDBLIB_CHANNEL_PUBLISHNETWORK_DISCONNECTEDConnection to dataBridges network is not active.DBLIB_CHANNEL_PUBLISHINVALID_CHANNELNAMEApplicable for below conditions1. channelNamevalidation error,typeof()channelNameis not type string2.channelNamevalidation error,channelNamefailsa-zA-Z0-9\.:_-validation.3.channelNameissys:*4.channelNameis not defined.DBLIB_CHANNEL_PUBLISHINVALID_CHANNELNAME_LENGTHchannelNamevalidation error, length ofchannelNamegreater than64DBLIB_CHANNEL_PUBLISHINVALID_SUBJECTApplicable for below conditions1.eventvalidation error,eventis not defined2.eventvalidation error,typeof()eventis not type stringSend Message to Members / sessionIDIt's possible to send message to individualsessionIdusing thechannel.sendmsgfunction on an instance of thechannelObjector usingdbridgeObject.sendmsg()The default method for send message user-defined events to a individualsessionIdinvolves invoking thechannel.sendmsgfunction of yourchannelObjectfor which it has connected toORusingdbridgeObjectgiving thechannelNameas parameter.Note:channel.sendmsgis not allowed usingchannelObjectsubscribed tosys:*channel.# Using dbridgeObjecttry:dbridge.channel.sendmsg(channelName,event,payload,toSessionId,sourceId,seqno)exceptdBErrorase:print(e.code,e.source,e.message)# Using channelObjecttry:channelObject.sendmsg(event,payload,toSessionId,sourceId,seqno)exceptdBErrorase:print(e.code,e.source,e.message)# Best practice is to check the channel is online before publishing any message.ifchannelObject.isOnline():try:channelObject.sendmsg(event,payload,toSessionId,sourceId,seqno);exceptdBErrorase:print(e.code,e.source,e.message)ParameterDescriptionchannelName(string)Channel name for which details are required.event(string)eventName to which the message to be sent.eventName cannot start withdbridges:payload(string)Payload to be sent with the event.toSessionId(string)sessionidwhere the message  to be sent.sourceId(string)Required in case ofpresence(prs:) andsystem(sys:) channel. When sending a message to apresence(prs:) orsystem(sys:) channel, application need to specify a message source by using this sourceId.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.seqnocan be used by applications to manage message queue processing by the subscribers.Return ValuesDescriptionNAExceptions:SourceCodeDescriptionDBLIB_CHANNEL_SENDMSGNETWORK_DISCONNECTEDConnection to dataBridges network is not active.DBLIB_CHANNEL_SENDMSGINVALID_CHANNELNAMEApplicable for below conditions1. channelNamevalidation error,typeof()channelNameis not type string2.channelNamevalidation error,channelNamefailsa-zA-Z0-9\.:_-validation.3.channelNameissys:*4.channelNameis not defined.5.channelTypeisprs:andsourceIdis not provided.6.channelNamecontains:and first token is notpvt,prs,sysDBLIB_CHANNEL_SENDMSGINVALID_CHANNELNAME_LENGTHchannelNamevalidation error, length ofchannelNamegreater than64Binding to eventsA 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 achannelObject, to bind to events on a particular channel; or on thedbridgeObject, to bind to events on all subscribed channels simultaneously.bindandunbindBindto "event" on channel: payload and metadata is received.# Binding to channel events on channelObjectdefeventFunction(payload,metadata):print(payload,metadata)try:channelObject.bind('eventName',eventFunction)exceptdBErrorase:print(e.code,e.source,e.message)# Binding to channel events on dbridgeObjecttry{dbridge.channel.bind('eventName',eventFunction)exceptdBErrorase:print(e.code,e.source,e.message)ParameterDescriptionevent(string)eventName to which binding to be done.Callback parameterspayload:(string)Payload data sent by the publisher.metadata(dict):{"channelname":"channelName",//(string)channelNametowhichsubscriptionisdone."eventname":"event",//(string)eventName"sourcesysid":"",//(string)Sendersystemidentity,applicableonlyforpresenceorsystemchannel."sqnum":"1",//(string)userdefined,sentduringpublishfunction."sessionid":"",//(string)Sendersessionid,applicableonlyforpresenceorsystemchannel."intime":1645554960732//(string)EPOCtimeofthesenderattimeofpublish.}Exceptions:SourceCodeDescriptionDBLIB_CONNECT_BINDINVALID_EVENTNAMEInvalid Event name. Not in user-defined events or default events.DBLIB_CONNECT_BINDINVALID_CALLBACKIf"callback function"is not declaredortypeof()variable defined is not a"function".Unbindbehavior varies depending on which parameters you provide it with. For example:# Remove just `handler` of the `event` in the subscribed/connected channelchannelObject.unbind('event',handler)# Remove all `handler` of the `event` in the subscribed/connected channelchannelObject.unbind('event')# Remove all handlers for the all event in the subscribed/connected channelchannelObject.unbind()# Remove `handler` of the `event` for all events across all subscribed/connected channelsdbridge.channel.unbind('event',handler)# Remove all handlers of the `event` for all events across all subscribed/connected channelsdbridge.channel.unbind('event')# Remove all handlers for all events across all subscribed/connected channelsdbridge.channel.unbind()bind_allandunbind_allbind_allandunbind_allwork much likebindandunbind, but instead of only firing callbacks on a specific event, they fire callbacks on any event, and provide that event in the metadata  to the handler along with the payload.# Binding to channel events on channelObjectdefeventFunction(payload,metadata):print(payload,metadata)try:channelObject.bind_all('event',eventFunction)exceptdBErrorase:print(e.code,e.source,e.message)# Binding to channel events on dbridgeObjecttry{dbridge.channel.bind_all('event',eventFunction)exceptdBErrorase:print(e.code,e.source,e.message)Callback out parameterpayload, metadatadetails are explained with each event below in this document.Exceptions:SourceCodeDescriptionDBLIB_CONNECT_BINDINVALID_CALLBACKIf"callback function"is not declaredortypeof()variable defined is not a"function".unbind_allworks similarly tounbind.# Remove just `handler` across the channelchannelObject.unbind_all(handler)#Remove all handlers for the all event in the subscribed/connected channelchannelObject.unbind_all()# Remove `handler` across the subscribed/connected channelsdbridge.channel.unbind_all(handler)# Remove all handlers for all events across all subscribed/connected channelsdbridge.channel.unbind_all()System events for channel objectThere are a number of events which are triggered internally by the library, but can also be of use elsewhere. Below are the list of all events triggered by the library.Below syntax is same for all system events.# Binding to systemevent on channelObjectdefeventFunction(payload,metadata):print(payload,metadata)try:channelObject.bind_all('dbridges:subscribe.success',eventFunction)exceptdBErrorase:print(e.code,e.source,e.message)# Binding to systemevent on dbridgeObjecttry:dbridge.channel.bind_all('dbridges:subscribe.success',eventFunction)exceptdBErrorase:print(e.code,e.source,e.message)dbridges:subscribe.successCallback parameterspayload:nullmetadata(dict):{"channelname":"channelName",//(string)channelNametowhichsubscriptionisdone."eventname":"dbridges:subscribe.success",//(string)eventName"sourcesysid":"",//(string)Sendersystemidentity,applicableonlyforpresenceorsystemchannel."sqnum":"1",//(string)userdefined,sentduringpublishfunction."sessionid":"",//(string)Sendersessionid,applicableonlyforpresenceorsystemchannel."intime":1645554960732//(string)EPOCtimeofthesenderattimeofpublish.}dbridges:subscribe.failCallback parameterspayload:(dberror object){"source":"dberror.Source",//(string)Errorsource,Referdberror:fordetails"code":"dberror.Code",//(string)Errorcode,Referdberror:fordetails"message":""//(string)Errormessageifapplicable.}metadata(dict):{"channelname":"channelName",//(string)channelNametowhichsubscriptionisdone."eventname":"dbridges:subscribe.fail",//(string)eventName"sourcesysid":"",//(string)"sqnum":"",//(string)"sessionid":"",//(string)"intime"://(string)}dbridges:channel.onlineCallback parameterspayload:nullmetadata(dict):{"channelname":"channelName",//(string)channelNametowhichsubscriptionisdone."eventname":"dbridges:channel.online",//(string)eventName"sourcesysid":"",//(string)"sqnum":"",//(string)"sessionid":"",//(string)"intime"://(string)}dbridges:channel.offlineCallback parameterspayload:nullmetadata(dict):{"channelname":"channelName",//(string)channelNametowhichsubscriptionisdone."eventname":"dbridges:channel.offline",//(string)eventName"sourcesysid":"",//(string)"sqnum":"",//(string)"sessionid":"",//(string)"intime"://(string)}dbridges:channel.removedCallback parameterspayload:nullmetadata(dict):{"channelname":"channelName",//(string)channelNametowhichsubscriptionisdone."eventname":"dbridges:channel.removed",//(string)eventName"sourcesysid":"",//(string)"sqnum":"",//(string)"sessionid":"",//(string)"intime"://(string)}dbridges:unsubscribe.successCallback parameterspayload:nullmetadata(dict):{"channelname":"channelName",//(string)channelNametowhichsubscriptionisdone."eventname":"dbridges:unsubscribe.success",//(string)eventName"sourcesysid":"",//(string)"sqnum":"",//(string)"sessionid":"",//(string)"intime"://(string)}dbridges:unsubscribe.failCallback parameterspayload:(dberror object){"source":"dberror.Source",//(string)Errorsource,Referdberror:fordetails"code":"dberror.Code",//(string)Errorcode,Referdberror:fordetails"message":""//(string)Errormessageifapplicable.}metadata(dict):{"channelname":"channelName",//(string)channelNametowhichsubscriptionisdone."eventname":"dbridges:unsubscribe.fail",//(string)eventName"sourcesysid":"",//(string)"sqnum":"",//(string)"sessionid":"",//(string)"intime"://(string)}dbridges:resubscribe.successCallback parameterspayload:nullmetadata(dict):{"channelname":"channelName",//(string)channelNametowhichsubscriptionisdone."eventname":"dbridges:resubscribe.success",//(string)eventName"sourcesysid":"",//(string)"sqnum":"",//(string)"sessionid":"",//(string)"intime"://(string)}dbridges:resubscribe.failCallback parameterspayload:(dberror object){"source":"dberror.Source",//(string)Errorsource,Referdberror:fordetails"code":"dberror.Code",//(string)Errorcode,Referdberror:fordetails"message":""//(string)Errormessageifapplicable.}metadata(dict):{"channelname":"channelName",//(string)channelNametowhichsubscriptionisdone."eventname":"dbridges:resubscribe.fail",//(string)eventName"sourcesysid":"",//(string)"sqnum":"",//(string)"sessionid":"",//(string)"intime"://(string)}dbridges:participant.joinedThis will be triggered only forpresence(prs:)andsystem(sys:)channel subscription.Callback parameterspayload:(dict){"sessionid":"ydR27s3Z92yQw7wjGY2lX",//(string)Sessionidofthememberwhohassubscribed/connectedtochannel"libtype":"nodejs",//(string)LibraryLangofthememberwhohassubscribed/connectedtochannel"sourceipv4":"0.0.0.0",//(string)IPv4ofthememberwhohassubscribed/connectedtochannel"sourceipv6":"::1",//(string)NotApplicableinthisversion"sysinfo":'{"sysid":"nameofcaller"}'//(string)SystemInfoofthememberwhohassubscribed/connectedtochannel}metadata(dict):{"channelname":"prs:channelName",//(string)channelNametowhichsubscriptionisdone."eventname":"dbridges:participant.joined",//(string)eventName"sourcesysid":"nameofcaller",//(string)Sysidofthememberwhohassubscribed/connectedtochannel"sqnum":null,//(string)"sessionid":"ydR27s3Z92yQw7wjGY2lX",//(string)Sessionidofthememberwhohassubscribed/connectedtochannel"intime":null//(string)}dbridges:participant.leftThis will be triggered only forpresence(prs:)andsystem(sys:)channel subscription.Callback parameterspayload:(dict){"sessionid":"ydR27s3Z92yQw7wjGY2lX",//(string)Sessionidofthememberwhohassubscribed/connectedtochannel"libtype":"nodejs",//(string)LibraryLangofthememberwhohassubscribed/connectedtochannel"sourceipv4":"0.0.0.0",//(string)IPv4ofthememberwhohassubscribed/connectedtochannel"sourceipv6":"::1",//(string)NotApplicableinthisversion"sysinfo":'{"sysid":"nameofcaller"}'//(string)SystemInfoofthememberwhohassubscribed/connectedtochannel}metadata(dict):{"channelname":"prs:channelName",//(string)channelNametowhichsubscriptionisdone."eventname":"dbridges:participant.left",//(string)eventName"sourcesysid":"nameofcaller",//(string)Sysidofthememberwhohassubscribed/connectedtochannel"sqnum":null,//(string)"sessionid":"ydR27s3Z92yQw7wjGY2lX",//(string)Sessionidofthememberwhohassubscribed/connectedtochannel"intime":null//(string)}System events - payload (dberror object) - details:SourceCodeDescriptionDBNET_CHANNEL_SUBSCRIBEERR_FAIL_ERRORdataBridges network encountered error when subscribing to the channel.DBNET_CHANNEL_SUBSCRIBEERR_ACCESS_DENIEDdBrdige network reportedaccess violationwithaccess_tokenfunction during subscription of this channel.DBNET_CHANNEL_UNSUBSCRIBEERR_FAIL_ERRORdataBridges network encountered error when unsubscribing to the channel.DBNET_CHANNEL_UNSUBSCRIBEERR_ACCESS_DENIEDdataBridges network reportedaccess violationwithaccess_tokenfunction during unsubscribing of this channel.object: rpc (Remote Procedure Call)rpc object exposestrust-safeproperties, functions and events to provide reliable two-way messaging (request-response) between multiple endpoints allowing you to build sophisticated asynchronous interactions.ConceptsRPC endpoint / server (CALLEE)Application using dataBridges server library can expose callback function(s) as a dataBridges rpc function.Multiple callback function(s), can be exposed as rpc functions grouped together as an rpc endpoint / server.To deploy access-controlled, trust-safe rpc endpoint / server, prefix the rpc server namespace with pvt: or prs:NotedataBridges 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 rpc endpoint/server including pvt: , prs:  access controlled rpc endpoint/server.Whereas application using client library (client application) will always need to pass a trust-token to access restricted rpc endpoint/server  (prefixed with pvt: prs:) . 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: rpc call() client application.Trust-tokens allows you to enable secured, access controlled and compliance driven two-way messaging (request-response) between multiple endpoints allowing you to build sophisticated asynchronous interactions in your existing and new initiative applications.RPC clients (CALLER)Both dataBridges client and server api's allow you to execute rpc function(s) exposed by rpc endpoint / server.Appication consuming rpc function(s) is called CALLEE and the rpc endpoint/server application is called CALLER.CALLEE application will execute a remote function by passing IN.paramter, and a timeoutThe CALLER application's corresponding function will be invoked with the IN.parameter and it will respond with response() or exception() which will be delivered back to the CALLEE application by dataBridges network completing the request-response communication.CALLEE application need not be aware about RPC servers (CALLER) identity and will only interact with RPC server (CALLER) namespace. The dataBridges network will intelligently route and load balance RPC call() to the RPC server application. The dataBridges network will automatically load balance multiple instance of server application exposing the same RPC endpoints.To expose rpc functions the  application needs to register an rpc server and register callback functions to rpc server as rpc functions.The steps involved are :Initialize rpc endpoint/server usinginit().Register all rpc functions usingregfn().Register rpc endpoint/server with dataBridges network usingregister()Initialize rpc ServerInitialize the server usingrpc.initfunction of your dataBridges object. This will return an object to which all properties, functions and events are available.Note: Application can havemultiplerpc endpoint/server against a dataBridges object.# lets create an rpc endpoint/server named missionControl and expose 2 functions called nasa and isro.try:missionControl=dbridge.rpc.init('missionControl')exceptdBErrorase:print(e.code,e.source,e.message)ParameterRulesDescriptionstring*serverNameOR**pvt:**serverNameOR**prs:*serverNameInitialize arpcServerwithserverName .Return TypeDescriptionobjectrpcObjectwhich events, properties and related functions can be bound to.Exceptions:SourceCodeDescriptionDBLIB_RPC_INITINVALID_SERVERNAMEApplicable for below conditions1.serverNameis not defined.2.serverNamealready exists3.serverNameis blank.4.serverNamevalidation error, length ofserverNamegreater than645.serverNamevalidation error,serverNamefailsa-zA-Z0-9\.:_-validation.6.serverNamecontains:and first token is notpvt,prs.Register rpc functionsApplication can expose callback function(s) as rpc functions. Application using dataBridges client/server library can remotely execute the rpc functions. Each function needs to be registered with the library as a rpc function, usingrpc.regfn()where you can link the functionName to rpcFunctionName.The server application that exposes the rpc function is called a CALLEE.The client/server application that executes the rpc function is called a CALLER.Functions can be defined either inside the property callback function or anywhere in the scope of application. Below code exhibits both ways of exposing the function.# function is exposed outside the property callback function, but in the scope of application.asyncdefrpcFunOutside(inparameter,response):try:response.tracker=Trueprint("iparameter = ",inparameter.inparama)print("extra info  = ",inparameter.sysinfo)response.next('This is Houston')response.end('message received by Houston')response.exception('INVALID_PARAM','Wrong parameter')exceptdBErrorase:print(e.code,e.source,e.message)# function is exposed inside the property callback function.asyncdefrpcFunctionBinder():# function is exposed inside the property callback function, but in the scope of application.asyncdefrpcFunInside(inparameter,response):response.tracker=Truetry:response.tracker=Trueprint("iparameter = ",inparameter.inparama)print("extra info  = ",inparameter.sysinfo)response.next('This is Hassan')response.end('message received by Hassan')response.exception('INVALID_PARAM','Wrong parameter')exceptdBErrorase:print(e.code,e.source,e.message)try:#// registering function to be exposed by rpcServermissionControl.regfn("nasa",rpcFunInside)missionControl.regfn("isro",rpcFunOutside)exceptdBErrorase:print(e.code,e.source,e.message)missionControl.functions=rpcFunctionBinder# unbinding of function exposed by rpc functionsmissionControl.unregfn("rpcFunOutside",ifunctionoutside)Below areparametersof the callback function which is exposed torpcServer.ParameterDescriptionpayload(object)Input payload from the caller.response(object)Response object havingpropertiesandfunctionto return execution results of the function back to caller.payload:(object)Properties/FunctionDescriptioninparam(string)Input parameters received to execute the function.sessionid(string)Session id of the member who has requested to execute the function.libtype(string)Library Lang of the member who has requested to execute the function.sourceipv4(string)IPv4 of the member who has who has requested to execute the function.sourceipv6(string)IPv6 of the member who has who has requested to execute the function.info(string)System Info of the member who has who has requested to execute the function.response:(object)Properties/FunctionDescriptiontracker(boolean)This will enable  response tracker, and eventrpc.response.trackerwill be fired if any issue happens in sending back response to caller. Enable this property if your function needs a confirmation of response delivered to the caller.id(string)(readonly)Each rpc function execution is assigned a unique ID by the library.  when the response tracker is enabled, the application can bind to an eventrpc.response.trackerto get the delivery notification. The event will indicate the delivery notification linked to this ID. Caller application will need to maintain this ID to track the delivery notification.next(function)dataBridges rpc supports mult-part response. Application can useresponse.nextto send multi-part response to the caller.end(function)response.endis to send the final response to the caller. Onceendis called, the object isclosedand no more response can be sent.exception(function)Two parameter, returnerrorCode(string),errorMessage(string)is sent to caller. This will raise an exception at the caller library.Exceptions:Below exceptions are raised in therpc.regfn.SourceCodeDescriptionDBLIB_RPC_REGFNINVALID_FUNCTION_NAMEInvalid Function name.DBLIB_RPC_REGFNINVALID_CALLBACKCallback is not a function or is not defined.Below exceptions are raised onresponseobject inside the registered function.SourceCodeDescriptionDBNET_RPC_CALLNETWORK_DISCONNECTEDConnection to dataBridges network is not active.DBLIB_RPC_CALLRESPONSE_OBJECT_CLOSEDReturn response object is closed. Thus the function is unable to respond back to the call.Register ServerRegister rpc endpoint/server with dataBridges network usingregister().try:missionControl.register()exceptdBErrorase:print(e.code,e.source,e.message)# Best practice is to check the channel is online before publishing any message.ifdbridge.connectionstate.isconnected():try:missionControl.register()exceptdBErrorase:print(e.code,e.source,e.message)Exceptions:SourceCodeDescriptionDBLIB_RPC_REGISTERRPC_INVALID_FUNCTIONSApplicable for below conditions1. If"callback function"is not declared for rpc server2.typeof()variable defined is not a"function".DBLIB_RPC_REGISTERNETWORK_DISCONNECTEDConnection to dataBridges network is not active.Unregister ServerrpcServer can be unregistered from dataBridges server library  usingunregisterfunction of yourrpcServerObject.missionControl.unregister()resetqueue()dbridgeObjectThe dataBridges network maintains in-process rpc function execution status. resetqueue() informs the dataBridges network that all in-process rpc function execution will be dropped by the application and response to be invalidated. Resetqueue() use case is intended to be used by application in its self health status management. Sometime due to the application process flow, the application can identify situation where it would like to ease its load by resettiing the rpc function execution queue by sending resetqueue() message to dataBridges network and than closing all in-process rpc function execution.try:awaitmissionControl.resetqueue();exceptdBErrorase:print(e.code,e.source,e.message)Exceptions:SourceCodeDescriptionDBLIB_RPC_CALLNETWORK_DISCONNECTEDConnection to dataBridges network is not active.System events for rpc server registration.There are a number of events which are triggered internally by the library, but can also be of use elsewhere. Below are the list of all events triggered by the library.Below syntax is same for all system events.#  Binding to systemevents on rpcObjectasyncdefeventCallback(payload,metadata):print(payload,metadata)try:rpcSvrObject.bind('eventName',eventCallback)exceptdBErrorase:print(e.code,e.source,e.message)# Binding to systemevents on dbridgeObjecttry:dbridge.rpc.bind('eventName',eventCallback)exceptdBErrorase:print(e.code,e.source,e.message)Callback out parameterpayload, metadatadetails are explained with each event below in this document.Exceptions:SourceCodeDescriptionDBLIB_RPC_BINDINVALID_EVENTNAMEInvalid Event name. Not in default events.DBLIB_RPC_BINDINVALID_CALLBACKCallback is not a function or is not defined.bind_allandunbind_allbind_allandunbind_allwork much likebindandunbind, but instead of only firing callbacks on a specific event, they fire callbacks on any event, and provide that event in the metadata  to the handler along with the payload.# Binding to rpc events on rpcObjectdefeventFunction(payload,metadata):print(payload,metadata)try:rpcSvrObject.bind_all('eventName',eventFunction)exceptdBErrorase:print(e.code,e.source,e.message)# Binding to rpc events on dbridgeObjecttry{dbridge.rpc.bind_all('eventName',eventFunction)exceptdBErrorase:print(e.code,e.source,e.message)Callback out parameterpayload, metadatadetails are explained with each event below in this document.Exceptions:SourceCodeDescriptionDBLIB_CONNECT_BINDINVALID_CALLBACKIf"callback function"is not declaredortypeof()variable defined is not a"function".unbind_allworks similarly tounbind.# Remove just `handler` connected rpc serverrpcClient.unbind_all(handler)# Remove all handlers for the all event in the connected rpc serverrpcClient.unbind_all()# Remove `handler` across the connected rpc serversdbridge.rpc.unbind_all(handler)# Remove all handlers for all events across all connected rpc serversdbridge.rpc.unbind_all()dbridges:rpc.server.registration.successCallback parameterspayload:nullmetadata(dict):{"servername":"serverName",//(string)serverNametowhichconnectionisdone."eventname":"dbridges:rpc.server.registration.success",//(string)eventName}dbridges:rpc.server.registration.failCallback parameterspayload:(dberror object){"source":"DBNET_RPC_REGISTER",//(string)Errorsource"code":"ERR_ACCESS_DENIED",//(string)Errorcode"message":""//(string)Errormessageifapplicable.}metadata(dict):{"servername":"serverName",//(string)serverNametowhichconnectionisdone."eventname":"dbridges:rpc.server.registration.fail",//(string)eventName}dbridges:rpc.server.unregistration.successCallback parameterspayload:nullmetadata(dict):{"servername":"serverName",//(string)serverNametowhichconnectionisdone."eventname":"dbridges:rpc.server.unregistration.success",//(string)eventName}dbridges:rpc.server.unregistration.failCallback parameterspayload:(dberror object){"source":"DBNET_RPC_REGISTER",//(string)Errorsource"code":"ERR_ACCESS_DENIED",//(string)Errorcode"message":""//(string)Errormessageifapplicable.}metadata(dict):{"servername":"serverName",//(string)serverNametowhichconnectionisdone."eventname":"dbridges:rpc.server.unregistration.fail",//(string)eventName}dbridges:rpc.server.onlineCallback parameterspayload:nullmetadata(dict):{"servername":"serverName",//(string)serverNametowhichconnectionisdone."eventname":"dbridges:rpc.server.online",//(string)eventName}dbridges:rpc.server.offlineCallback parameterspayload:nullmetadata(dict):{"servername":"serverName",//(string)serverNametowhichconnectionisdone."eventname":"dbridges:rpc.server.offline",//(string)eventName}dbridges:rpc.response.trackerOnly available withrpcObject.Callback parametersReturn ValuesDescriptionpayload(string)Tracker identifier. which is same asresponse.idmetadata(string)Refer below tableError IdentifierDescriptionRE_18326rpc caller is disconnected from dataBridges network and hence cannot process response tracking.RE_19219rpc caller is disconnected from dataBridges network and hence cannot process response tracking.RE_22184rpc caller is disconnected from dataBridges network and hence cannot process response tracking.RE_22454The cf callee is disconnected from dataBridges networkRE_23101The cf callee is disconnected from dataBridges networkRE_29623The cf callee is disconnected from dataBridges networkRE_29753The cf callee is disconnected from dataBridges networkdbridges:rpc.callee.queue.exceededOnly available withrpcObject.Callback parameterspayload:(dberror object){"source":"DBNET_RPC_CALL",//(string)Errorsource"code":"ERR_CALLEE_QUEUE_EXCEEDED",//(string)Errorcode"message":""//(string)Errormessageifapplicable.}metadata:nulldberror:SourceCodeDescriptionDBLIB_RPC_REGISTERNETWORK_DISCONNECTEDConnection to dataBridges network is not active.DBNET_RPC_REGISTERERR_ACCESS_DENIEDdataBridges network reportedaccess violationwithaccess_tokenfunction during current operation.DBNET_RPC_REGISTERERR_FAIL_ERRORdataBridges network encountered error during current operation.DBNET_RPC_CALLERR_CALLEE_QUEUE_EXCEEDEDNo new rpc calls are being routed by the dataBridges network to the application because the application's current rpc processing queue has already exceeded.Each application connection cannot exceed rpc.queue.maximum. Refer to management console documentation for rpc.queue.maximum details.Server InformationisOnline()rpcObjectprovides a function to check if the channel is online.rpcServer_isonline=rpcObject.isOnline()ParameterRulesDescriptionstring*serverNameOR**pvt:**serverNameOR**prs:*serverNameserverName to which subscription to be done.Return ValuesDescriptionbooleanIs the current status of server connection online or offline.getServerName()rpcObjectprovides a function to get theserverName.rpcServerName=rpcObject.getServerName()Return TypeDescriptionstringserverNameof connected rpcServer.Connect to ServerTo use rpc functions, the application has to connect to the rpc endpoint/server. This is done usingconnect()function explained below.connect()The default method for connecting to a rpc endpoint/server involves invoking therpc.connectfunction of your dataBridges object.try:rpcSvrClient=dbridge.rpc.connect('rpcServer')# name of the rpc endpoint/server that app wants to connect to. In our above example missionControl.exceptdBErrorase:print(e.code,e.source,e.message)ParameterRulesDescriptionstring*serverNameOR**pvt:**serverNameOR**prs:*serverNameserverName to which connection to be done.Return TypeDescriptionobjectrpcObjectwhich events and related functions can be bound to.Exceptions:SourceCodeMessageDescriptionDBLIB_RPC_CONNECTINVALID_SERVERNAMEApplicable for below conditions1.serverNameis not defined.2.serverNamevalidation error, length ofserverNamegreater than643.serverNamevalidation error,serverNamefailsa-zA-Z0-9\.:_-validation.4.serverNamecontains:and first token is notpvt,prs.DBLIB_RPC_CONNECTNETWORK_DISCONNECTEDConnection to dataBridges network is not active.DBNET_RPC_CONNECTERR_FAIL_ERRORdataBridges network encountered error during current operation.DBNET_RPC_CONNECTERR_ACCESS_DENIEDdataBridges network reportedaccess violationwithaccess_tokenfunction during current operation.Execute Remote Procedure Callcall()rpcObjectcall() function allows you to execute a remote function hosted by RPC endpoint / server using dataBridges librarypassing function parameter as parameterwhile setting an time to live (TTL) for the responseThe RPC call() functions supports multipart response (where the RPC function can send back multiple responses to a single RPC function call) along with exception routine.defprogress(response):print("multipart: ",response)defonResult(response):print("response: ",response)defonError(error):print(error.code,error.source,error.message)try:p=awaitrpcClient.call("functionName",parameter,10000,progress)p.then(onResult).catch(onError)exceptdBErrorase:print(e.code,e.source,e.message)# Below example how a application can connect to a RPC endpoint / Server called mathServer and use add, multiply functions.try:myMathServer=dbridge.rpc.connect('mathServer');exceptdBErrorase:print(e.code,e.source,e.message)obj={"num1":44.5,"num2":30};inparam=json.dumps(obj);try:p=awaitmyMathServer.call(add,inparam,10000,progress)p.then(onResult).catch(onError)q=awaitmyMathServer.call(multiply,inparam,10000,progress)q.then(onResult).catch(onError)exceptdBErrorase:print(e.code,e.source,e.message)ParameterExpected ValueDescriptionfunctionNamefunctionname(string)Function name as defined inrpc endpoint/ Server.Note - RPC endpoint / server can expose multiple rpc functions.parameterfunction parameter(string)if multiple parameters to be passed, This can be done by putting it into array or json and stringify the object.ttlms1000(integer)Time to live in millisecond, timeout value before the call() function throws error timeout.Return ValuesDescriptionstringMultipart or final response. in case of error, dberror object is returned.Exceptions:SourceCodeDescriptionDBNET_RPC_CALLNETWORK_DISCONNECTEDConnection to dataBridges network is not active.DBNET_RPC_CALLRESPONSE_TIMEOUTResponse not received from dataBridges network within definedttlms. This may be due to dataBridges network or late response fromrpcServerDBLIB_RPC_CALLID_GENERATION_FAILEDInternal Library error.DBNET_RPC_CALLERR_ACCESS_DENIEDdataBridges network reportedaccess violationduring current operation.DBRPCCALLEE_RPC_CALLERR_error_messageThis indicates an exception encountered by the remote RPC function. ERR_error_code will have the details.DBNET_RPC_CALLCLE_NR_10865rpc endpoint / server disconnected from dataBridges network. Try again.DBNET_RPC_CALLCLE_NR_30391rpc endpoint / server disconnected from dataBridges network. Try again.DBNET_RPC_CALLCLE_QX_41074Cannot process the call() because the RPC server (in this case CALLEE) has exceeded outstanding pending rpc call() queue limit.DBNET_RPC_CALLCLE_QX_49467Cannot process the call() because the RPC server (in this case CALLEE) has exceeded outstanding pending rpc call() queue limit.DBNET_RPC_CALLCLR_QX_39305Cannot process the call() because the RPC server (in this case CALLEE) has exceeded outstanding pending rpc call() queue limit.DBNET_RPC_CALLCLR_QX_39824Cannot process the call() because the RPC server (in this case CALLEE) has exceeded outstanding pending rpc call() queue limit.DBNET_RPC_CALLRE_28710rpc endpoint / server disconnected from dataBridges network. Try again.DBNET_RPC_CALLAD_48621Application does not have access to execute rpc functions.System events for rpc callThere are a number of events which are triggered internally by the library, but can also be of use elsewhere. Below are the list of all events triggered by the library.Below syntax is same for all system events.#  Binding to systemevent on rpcObjectasyncdefeventCallback(payload,metadata):print(payload,metadata)try:rpcClient.bind("eventName",eventCallback)exceptdBErrorase:print(e.code,e.source,e.message)#  Binding to systemevent on dbridgeObjecttry:dbridge.rpc.bind("eventName",eventCallback)exceptdBErrorase:print(e.code,e.source,e.message)Exceptions:SourceCodeDescriptionDBLIB_RPC_CALLERINVALID_EVENTNAMEInvalid Event name. Not in default events.DBLIB_RPC_CALLERINVALID_CALLBACKCallback is not a function or is not defined.bind_allandunbind_allbind_allandunbind_allwork much likebindandunbind, but instead of only firing callbacks on a specific event, they fire callbacks on any event, and provide that event in the metadata  to the handler along with the payload.# Binding to rpc events on rpcObjectdefeventFunction(payload,metadata):print(payload,metadata)try:rpcSvrObject.bind_all('eventName',eventFunction)exceptdBErrorase:print(e.code,e.source,e.message)# Binding to rpc events on dbridgeObjecttry{dbridge.rpc.bind_all('eventName',eventFunction)exceptdBErrorase:print(e.code,e.source,e.message)Callback out parameterpayload, metadatadetails are explained with each event below in this document.Exceptions:SourceCodeDescriptionDBLIB_CONNECT_BINDINVALID_CALLBACKIf"callback function"is not declaredortypeof()variable defined is not a"function".unbind_allworks similarly tounbind.# Remove just `handler` connected rpc serverrpcClient.unbind_all(handler)# Remove all handlers for the all event in the connected rpc serverrpcClient.unbind_all()# Remove `handler` across the connected rpc serversdbridge.rpc.unbind_all(handler)# Remove all handlers for all events across all connected rpc serversdbridge.rpc.unbind_all()dridges:rpc.server.connect.successCallback parameterspayload:nullmetadata(dict):{"servername":"serverName",//(string)serverNametowhichconnectionisdone."eventname":"dbridges:rpc.server.connect.success",//(string)eventName}dbridges:rpc.server.connect.failCallback parameterspayload:(dberror object){"source":"DBLIB_RPC_CONNECT",//(string)Errorsource"code":"ACCESS_TOKEN_FAIL",//(string)Errorcode"message":""//(string)Errormessageifapplicable.}metadata(dict):{"servername":"serverName",//(string)serverNametowhichconnectionisdone."eventname":"dbridges:rpc.server.connect.fail",//(string)eventName}dbridges:rpc.server.onlineCallback parameterspayload:nullmetadata(dict):{"servername":"serverName",//(string)serverNametowhichconnectionisdone."eventname":"dbridges:rpc.server.online",//(string)eventName}dbridges:rpc.server.offlineCallback parameterspayload:nullmetadata(dict):{"servername":"serverName",//(string)serverNametowhichconnectionisdone."eventname":"dbridges:rpc.server.offline",//(string)eventName}dberror:SourceCodeDescriptionDBNET_RPC_CONNECTERR_FAIL_ERRORdataBridges network encountered error during current operation.DBNET_RPC_CONNECTERR_ACCESS_DENIEDdataBridges network reportedaccess violationduring current operation.object:Cf (Client Function)CF (Client-function) object is a special purpose RPC | request-response implementation to build command and control applications. CF object exposes properties, functions and events for 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.CF REDUCES HUGE ENGINEERING TIME EFFORT REQUIRED TO DESIGN, BUILD AND MAINTAIN A ROBUST COMMAND-CONTROL INFRASTRUCTURE.A client function(s)  is a callback function exposed by the client library as a RPC (remote procedure call).Server application (using dataBridges server library), can execute the CF function remotely.ConceptsCF (client-function) simplifies the comand and control type application design and maintenance.iOT and large distributed system requires a standard, secured and compliant method to send reliable  request-response communication to the managed devices from authenticated and authorized Command-and-Control server applications. dataBridges CF allows you you to expose device functions and capabilities in a easy, secured manner allowing only authoirized dataBridges server applications to communicate with the devices, remote applications.Only server application using dataBridges server library + application key secret can execute CF functions exposed by remote devices.The server application is called CALLER (the one executing cf.call() function)The server application needs to know the sessionID of the device to which it needs to communicate.The device application exposing command functions is called CALLEE. Only authenticated and authorized server application will be allowed to communicate with the device application for device / application management.Execute Client Functionscall()dbridgeObjectcall() function allows you to execute client function(s) exposed by applications using dataBridges server/client library.Note- cf.call() is available only with server library and not with client library.sessionidwhere the function to be executed.clientFunction name.passing function parameter as parameterwhile setting an time to live (TTL) for the responseThe cf call() functions supports multipart response (where the cf function can send back multiple responses to a single cf function call) along with exception routine.defprogress(response):print("multipart: ",response)defonResult(response):print("response: ",response)defonError(error):print(error.code,error.source,error.message)try:p=awaitdbridge.cf.call(sessionId,functionName,parameter,10000,progress)p.then(onResult).catch(onError)exceptdBErrorase:print(e.code,e.source,e.message)ParameterExpected ValueDescriptionsessionIdsessionid(string)sessionidwhere the function to be executed.functionNamefunctionname(string)cf Function name.parameterfunctionparameters(string)if multiple parameters to be passed, This can be done by putting it into array or json and stringify the object.ttlms1000(integer)Time to live in millisecond, timeout value before the library throws error timeout.Return ValuesDescriptionstringMultipart or final response. in case of error, dberror object is returned.Exceptions:SourceCodeDescriptionDBLIB_CF_CALLNETWORK_DISCONNECTEDConnection to dataBridges network is not active.DBLIB_CF_CALLRESPONSE_TIMEOUTResponse not received from dataBridges network within definedttlms. This may be due to dataBridges network or late response fromcfClientDBLIB_CF_CALLID_GENERATION_FAILEDInternal Library error.DBCFCALLEE_CF_CALLERR_error_codeException received fromcfClientfunction execution. This is sent directly fromcfClientfunction.DBNET_CF_CALLCLR_QX_38361Cannot process the call() because thecfClient(in this case CALLEE) has exceeded outstanding pending cf call() queue limit.DBNET_CF_CALLCLR_QX_39179Cannot process the call() because thecfClient(in this case CALLEE) has exceeded outstanding pending cf call() queue limit.DBNET_CF_CALLCLE_NR_10464cfClientdisconnected from dataBridges network. Try again.DBNET_CF_CALLCLE_NR_10558cfClientdisconnected from dataBridges network. Try again.DBNET_CF_CALLRE_26886cfClientdisconnected from dataBridges network. Try again.DBNET_CF_CALLRE_27968cfClientdisconnected from dataBridges network. Try again.DBNET_CF_CALLRE_28402cfClientdisconnected from dataBridges network. Try again.PropertiesServer library can also expose client functions.The following is the list ofcfproperties. These properties has to be set beforedbridge.connect()PropertyDescriptionenable(boolean)(default:false)If application wants to enableclientFunctionfunctionality, this needs to betrueelsefalse.functions(function)A client function  is a callback function exposed by the library as a RPC (remote procedure call).enable:You need to enable cf in the connection property.dbridge.cf.enable=Truefunctions:Application can expose callback function(s) as Client function (special case RPC | Request-Response). Server application using dataBridges server library can remotely execute the client functions. Each function needs to be registered with the library as a client function (CF), usingdbridge.cf.regfn()where you can link the functionName to ClientFunctionName.The client application that exposes the client function is called a CALLEE.The server application that executes the client function is called a CALLER.Functions can be defined either inside the property callback function or anywhere in the scope of application. Below code exhibits both ways of exposing the function.# function is exposed outside the property callback function, but in the scope of application.asyncdefcfFunOutside(inparameter,response):try:response.tracker=TrueupTime={"uptime":"13:34:30 up 8 days,  3:10,  1 user,  load average: 0.03, 0.11, 0.21"};response.next('retrieving system uptime')response.end(json,dumps(upTime))response.exception('INVALID_PARAM','Wrong parameter')exceptdBErrorase:print(e.code,e.source,e.message)asyncdefcfFunctionBinder():asyncdefcfFunInside(inparameter,response)://functionisexposedinsidethepropertycallbackfunction.response.tracker=Truetry:response.tracker=TrueuName={"uname":"Linux analysis 2.6.32-696.30.1.el6.x86_64 #1 SMP Tue May 22 03:28:18 UTC 2018 x86_64 x86_64 x86_64 GNU/Linux"};response.next('retrieving uName')response.end(json.dumps(uName))response.exception('INVALID_PARAM','Wrong parameter')exceptdBErrorase:print(e.code,e.source,e.message)try:dbridge.cf.regfn("uName",cfFunInside)dbridge.cf.regfn("sysUpTime",cfFunOutside)exceptdBErrorase:print(e.code,e.source,e.message)dbridge.cf..functions=cfFunctionBinder# unbinding of function exposed by rpc functionsdbridge.cf..unregfn("sysUpTime",cfFunOutside)Below areparametersof the callback function which is exposed toclientfunctions.ParameterDescriptionpayload(string)The inParameter for the clientFunction.response(object)The library creates a response object unique for each client function call. The Response object haspropertiesandfunctionto return execution results of the function back to caller.response:(object)Properties/FunctionDescriptiontracker(boolean)This will enable  response tracker, and eventcf.response.trackerwill be fired if any issue happens in sending back response to caller. Enable this property if your function needs a confirmation of reponse delivered to the caller.id(string)(readonly)Each client function execution is assigned a unique ID by the library.  when the response tracker is enabled, the application can bind to an eventcf.response.trackerto get the delivery notification. The event will indicate the delivery notification linked to this ID. Application will need to maintain this ID to track the delivery notification.next(function)dataBridges CF (Special case RPC |request-response) supports mult-part response. Application can useresponse.nextto send multi-part response to the caller.end(function)response.endis to send the final response to the caller. Onceendis called, the object isclosedand no more response can be sent.exception(function)Two parameter, returnerrorCode(string),errorMessage(string)is sent to caller. This will raise an exception at the caller library.Exceptions:Below exceptions are raised in thecf.regfn.SourceCodeDescriptionDBLIB_CF_REGFNINVALID_FUNCTION_NAMEInvalid Function name.DBLIB_CF_REGFNINVALID_CALLBACKCallback is not a function or is not defined.Below exceptions are raised onresponseobject inside the registered function.SourceCodeDescriptionDBLIB_CF_CALLNETWORK_DISCONNECTEDConnection to dataBridges network is not active.DBLIB_CF_CALLRESPONSE_OBJECT_CLOSEDReturn response object is closed. Thus the function is unable to respond back to the call.resetqueue()dbridgeObjectresetqueue() . The dataBridges network maintains in-process CF function execution status. resetqueue() informs the dataBridges network that all in-process CF function execution will be dropped by the application and response to be invalidated. Resetqueue() use case is intended to be used by application in its self health status management. Sometime due to the application process flow, the application can identify situation where it would like to ease its load by resettiing the CF function execution queue by sending resetqueue() message to dataBridges network and than closing all in-process CF function execution.try:awaitdbridge.cf.resetqueue();exceptdBErrorase:print(e.code,e.source,e.message)Exceptions:SourceCodeDescriptionDBLIB_CF_CALLNETWORK_DISCONNECTEDConnection to dataBridges network is not active.System events for cf objectThere are a number of events which are triggered internally by the library, but can also be of use elsewhere. Below are the list of all events triggered by the library.Below syntax is same for all system events.# Binding to systemevent on dbridgeObjectdefvoidmy_cf_function(payload,metadata):print(payload)try:dbridge.cf.bind('eventName',my_cf_function)exceptdBErrorase:print(e.code,e.source,e.message)cf.response.trackerCallback parametersReturn ValuesDescriptionpayload(string)Tracker identifier. which is same asresponse.idmetadata(string)Refer below table.Error IdentifierDescriptionRE_12616cf caller is disconnected from dataBridges network and hence cannot process response tracking.RE_13151cf caller is disconnected from dataBridges network and hence cannot process response tracking.RE_30030The cf callee is disconnected from dataBridges networkRE_33635The cf callee is disconnected from dataBridges networkcf.callee.queue.exceededpayload:(dberror object){"source":"DBNET_CF_CALL",//(string)Errorsource"code":"ERR_CALLEE_QUEUE_EXCEEDED",//(string)Errorcode"message":""//(string)Errormessageifapplicable.}metadata:nulldberror:SourceCodeDescriptionDBNET_CF_CALLERR_CALLEE_QUEUE_EXCEEDEDNo new cf calls are being routed by the dataBridges network to the application because the application's current cf processing queue has already exceeded.Each application connection cannot exceed cf.queue.maximum. Refer to management console documentation for cf.queue.maximum details.Change LogChange log: Changes in the recent versionsLicenseDataBridges Library is released under theApache 2.0 license.Copyright 2022 Optomate Technologies Private Limited.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.