{"_id":"543f8f8a051bdc0e00dfbf02","version":{"_id":"543b943865bf840e00b473b6","__v":5,"project":"543b943865bf840e00b473b3","createdAt":"2014-10-13T08:58:32.703Z","releaseDate":"2014-10-13T08:58:32.703Z","categories":["543b943865bf840e00b473b7","543b96e1b1479b1400c42f3d","543d1cdc3a300f20000d31ee","553e061924ec240d00b1f897","553e06431a946a0d00ad6f78"],"is_deprecated":false,"is_hidden":false,"is_beta":true,"is_stable":true,"codename":"","version_clean":"1.0.0","version":"1.0"},"__v":14,"category":{"_id":"543b943865bf840e00b473b7","version":"543b943865bf840e00b473b6","project":"543b943865bf840e00b473b3","__v":15,"pages":["543ffb2c22a3b30e001bdc37","543b965fb1479b1400c42f3a","543d1cbb5276641a00a593c3","543d3ff2a10ab32000b3aa9e","543d1fa83a300f20000d3206","543f8f8a051bdc0e00dfbf02","543d4a17a10ab32000b3aace","543ea21f3f50eb1a00ed2050","543ea6ac3f50eb1a00ed205e","543ebaedcc182e08005d0cc4","543f8cb422a3b30e001bdb48","543f838422a3b30e001bdb36","544184629c7623200053c8e7","5541356a69a03a2d00ce0b3b"],"sync":{"url":"","isSync":false},"reference":false,"createdAt":"2014-10-13T08:58:32.718Z","from_sync":false,"order":9999,"slug":"documentation","title":"Documentation"},"project":"543b943865bf840e00b473b3","user":"543b93f865bf840e00b473b2","is_link":false,"updates":[],"next":{"pages":[],"description":""},"createdAt":"2014-10-16T09:27:38.963Z","link_external":false,"link_url":"","githubsync":"","sync_unique":"","hidden":false,"api":{"basic_auth":false,"results":{"codes":[]},"try":true,"auth":"never","params":[],"url":""},"isReference":false,"order":5,"body":"Before reading this section, we suggest you have a look at the [A Raspberry Pi App Example](doc:writing-an-app-on-the-raspberry-pi) section. This section contains more details of how bridge-apps work and advice for writing more advanced apps. When you come to write an app yourself, it's usually a good idea to copy an existing app and modify it. See [How to Write Bridge-Apps](doc:developing-bridge-apps-1) for advice on a good way of doing about this to make you app easily deployable.\n[block:api-header]\n{\n  \"type\": \"basic\",\n  \"title\": \"Event-driven programming\"\n}\n[/block]\nEvent-driven programming will not be familiar to some people. When we first lean programming, we generally write programs that start, do a job and then stop. Bridge-apps start when the bridge is first turned on and then effectively run forever, but they are only active when there is something to do. This should be borne in mind when reading the following paragraphs.\n[block:api-header]\n{\n  \"type\": \"basic\",\n  \"title\": \"Overview\"\n}\n[/block]\nTo create a bridge-app, start by sub-classing the CbApp class, the definition of which can be found in cbcommslib, as follows:\n[block:code]\n{\n  \"codes\": [\n    {\n      \"code\": \"from cbcommslib import CbApp\\nfrom cbconfig import *\\n\\nclass App(CbApp):\\n    def __init__(self, argv):\\n        # Super-class init must be called\\n        CbApp.__init__(self, argv)\\n        \\nif __name__ == '__main__':\\n    App(sys.argv)\",\n      \"language\": \"python\"\n    }\n  ]\n}\n[/block]\nWithin class App, you must provide the following three methods, which are each called when messages arrive:\n[block:parameters]\n{\n  \"data\": {\n    \"0-0\": \"onAdaptorServices\",\n    \"1-0\": \"onAdaptorData\",\n    \"2-0\": \"onConfigureMessage\",\n    \"0-1\": \"This is called when “service” messages (see below) arrive from adaptors.\",\n    \"1-1\": \"This is called when “data” messages arrive from adaptors.\",\n    \"2-1\": \"This is called when configuration messages arrive from the bridge manager.\\nonConcMessage. This is called when messages arrive from the concentrator.\"\n  },\n  \"cols\": 2,\n  \"rows\": 3\n}\n[/block]\nThe definition of the messages can be found in [The Bridge-App API](doc:the-bridge-app-api).\n[block:api-header]\n{\n  \"type\": \"basic\",\n  \"title\": \"The configuration message\"\n}\n[/block]\nIn many cases, your app will not need to do anything with the configuration message. The main thing that the app gets from this message is a list of the names of the adaptors it is connected to , together with their \"friendly names\" (the names that they were given when the devices were installed), and the superclass already creates a dictionary with these in it, called self.friendlyLookup, which has the following format (with one entry for each connected adaptor):\n[block:code]\n{\n  \"codes\": [\n    {\n      \"code\": \"{\\\"id\\\": \\\"friendly_name\\\"}\",\n      \"language\": \"python\"\n    }\n  ]\n}\n[/block]\nBy convention, you should set the state of your app to \"starting\" on receiving this message, as shown in [A Raspberry Pi App Example](doc:writing-an-app-on-the-raspberry-pi).\n[block:api-header]\n{\n  \"type\": \"basic\",\n  \"title\": \"The adaptor service message\"\n}\n[/block]\nSome time after being receiving a configuration message, an app will receive a service message from each adaptor that it is connected to, with onAdaptorServices being called once for each configuration message. A service message from an adaptor contains the id of the adaptor. It's important to store this as that's how your app will know what data messages to expect from the adaptor and what to do with them.  The service message contains details of the service that an adaptor provides, with the service being composed of a number of characteristics, as detailed in [The Bridge-App API](doc:the-bridge-app-api). Details of the characteristics that are supported can be found in [Characteristics](doc:characteristics). \n\nAn app should respond to the service message by sending a service request message back to the adaptor. This is again detailed in [The Bridge-App API](doc:the-bridge-app-api). A device, and hence it adaptor, often supplies several characteristics as part of its service and an app should select which ones it is interested in. For example, PIR sensors quite often supply characteristics such as temperature and luminance as well. A security app is likely to be only interested in the PIR (a binary_sensor) and will respond requesting this, but not temperature and luminance. An energy management system may use all three of these and respond requesting them all.\n\nTo send a message to an adaptor, an app uses the sendMessage method:\n[block:code]\n{\n  \"codes\": [\n    {\n      \"code\": \"self.sendMessage(messsage, id)\",\n      \"language\": \"python\"\n    }\n  ]\n}\n[/block]\nwhere: message is the message to be send and id is the id of the adaptor to send it to. Here's a trivial example of an onAdaptorServices method that does this:\n[block:code]\n{\n  \"codes\": [\n    {\n      \"code\": \"def onAdaptorService(self, message):\\n    for p in message[\\\"service\\\"]:\\n        if p[\\\"characteristic\\\"] == \\\"temperature\\\":\\n            self.temperatures.append(message[\\\"id\\\"]\\n            request = {\\\"id\\\": self.id,\\n                       \\\"request\\\": \\\"service\\\",\\n                       \\\"service\\\": [\\n                                    {\\\"characteristic\\\": \\\"temperature\\\",\\n                                     \\\"interval\\\": 600\\n                                    }\\n                                  ]\\n                       }\\n            self.sendMessage(req, message[\\\"id\\\"])\",\n      \"language\": \"python\"\n    }\n  ]\n}\n[/block]\nHere, self.temperatures is a list of the ids of adaptors that the app will receive temperature from. The app replied to any adaptor that can provide temperature by saying that it wants to receive it every 10 minutes (600 seconds). The message from the adaptor also has an \"interval\" key, which says the minimum interval at which the adaptor can provide the characteristic. As a lot of devices are battery-powered, you are strongly advised to use the maximum interval that is possible for your application, in order to save energy. \n[block:callout]\n{\n  \"type\": \"info\",\n  \"title\": \"How do I know where the characteristic has come from?\",\n  \"body\": \"The astute reader will have noticed that we have not provided any way for the app to know where a characteristic has come from. Is the temperature from the kitchen, from outside or a thermometer inside the dog? The next major upgrade of the ContinuumBridge platform will provide a way for apps to say what they want. When a user connects a device on the portal, there will be an input say, for example \\\"Temperature inside dog\\\", so that they know that's what they need to connect to it. In the meantime, you can use a combination of the \\\"type\\\" of the service, which goes with each characteristic and friendly names (so the user will need to use the words \\\"inside dog\\\", for example, when they install the device).\"\n}\n[/block]\n\n[block:api-header]\n{\n  \"type\": \"basic\",\n  \"title\": \"The adaptor data message\"\n}\n[/block]\nOnce you have subscribed to characteristics from an adaptor, as described above, you app will receive adaptor data messages with the characteristics you have requested. This is best shown in a simple example:\n[block:code]\n{\n  \"codes\": [\n    {\n      \"code\": \"def onAdaptorData(self, message):\\n    if message[\\\"characteristic\\\"] == \\\"temperature\\\":\\n        sample = {message[\\\"timestamp\\\"]: message[\\\"data\\\"])\\n        self.temperatures[message[\\\"id\\\"].append(sample)\",\n      \"language\": \"python\"\n    }\n  ]\n}\n[/block]\nHere, self.temperatures is an list of dictionaries or the form {timestamp: temperature}. All the method does is to append each new sample to this list.\n\nQuite often, you may want a call of onAdaptorData to do other things as well. For example, you could compare the temperature to a desired temperature and send an on/off message to a heating controller (using the self.sendMessage method) or call a method that sends data to a cloud platform. Example apps that do these and more can be found in the [ContinuumBridge GitHub area](https://github.com/ContinuumBridge).\n[block:api-header]\n{\n  \"type\": \"basic\",\n  \"title\": \"Twisted time\"\n}\n[/block]\nIn cbridge, apps and adaptors (and everything else) communicate over sockets. ContinuumBridge makes use of an event-driven networking engine called [Twisted](https://twistedmatrix.com/trac/) to call methods in apps when data arrives, and you can also use Twisted to control when things happen in your app. \n[block:callout]\n{\n  \"type\": \"warning\",\n  \"title\": \"Twisted\",\n  \"body\": \"Although we've given a link to the Twisted Matix website, above, we don't actually recommend that you read it unless you're really keen. Twisted is a very powerful engine and some parts of it can be quite difficult to understand. We don't actually use that much of it in cbridge, and this documentation contains enough information to write comprehensive apps.\"\n}\n[/block]\nThe core of Twisted is the reactor. As the name implies, the reactor reacts to things, such as data arriving at a port. When data arrives from an adaptor, for example, Twisted converts it into a Python dictionary and calls either onAdaptorService or onAdaptorData, whichever is appropriate. A call to self.sendMessage causes the message to be sent via the appropriate socket. \n\nThere are two main circumstances where you will need to call Twisted methods directly yourself:\n\nScheduling something to happen at some time in the future\n-----------------------------------------------------------------------------\nYou may want to do some processing every minute, for example, based on samples that have arrived from devices and some other information. The first thing you need in your code is:\n[block:code]\n{\n  \"codes\": [\n    {\n      \"code\": \"from twisted.internet import reactor\",\n      \"language\": \"python\"\n    }\n  ]\n}\n[/block]\nThen you can write things like:\n[block:code]\n{\n  \"codes\": [\n    {\n      \"code\": \"reactor.callLater(60, self.checkSensors)\",\n      \"language\": \"text\"\n    }\n  ]\n}\n[/block]\nThis will cause the method checkSensors to be called in 60 seconds time. You could, for example include this in onConfigureMessage and then again at the end of the checkSensors method. \n\nThreading\n-------------\nOne thing to remember about writing apps is that, generally, if your code is waiting for something to happen, then no other methods can run. You may, for example, want to send some information to a cloud platform using an http POST. If the platform you are posting to is slow to respond, data from adaptors won't be processed until the POST has completed. This might be a problem, for example, if someone has pressed a button to turn on a light and nothing happens for three seconds. It's good programming practice to put all such tasks in threads, which can run \"at the same time\" as other things (or at least appear to - in reality the operating system is time-slicing between them). Twisted threads are essentially the same as standard Python threads, but we strongly recommend you use them in apps because Twisted understands them. To use them you need to:\n[block:code]\n{\n  \"codes\": [\n    {\n      \"code\": \"from twisted.internet import threads\",\n      \"language\": \"python\"\n    }\n  ]\n}\n[/block]\nand then you can do things like:\n[block:code]\n{\n  \"codes\": [\n    {\n      \"code\": \"reactor.callInThread(self.postValues)\",\n      \"language\": \"python\"\n    }\n  ]\n}\n[/block]\n\n[block:callout]\n{\n  \"type\": \"info\",\n  \"title\": \"Thread-safe?\",\n  \"body\": \"All the usual rules about using threads and ensuring your program is thread-safe apply. Just remember that all threads in your program have access to exactly the same data structures, so if you add data that's arrived from an adaptor to a list at the same time as your are sending that list from a thread the results are likely to be indeterminate. You could get around this by calling the thread with the number of samples to send. eg: reactor.callInThread(self.postValues, 5).\"\n}\n[/block]\nAny method that you call from a thread will be part of the thread. Sending of messages, using self.sendMessage, if something that Twisted's reactor must handle, and that is not running in your thread, so you must use this construct:\n[block:code]\n{\n  \"codes\": [\n    {\n      \"code\": \"reactor.callFromThread(self.sendMessage, msg, a).\",\n      \"language\": \"python\"\n    }\n  ]\n}\n[/block]\n\n[block:callout]\n{\n  \"type\": \"danger\",\n  \"title\": \"Calling Twisted methods from threads\",\n  \"body\": \"If you don't use reactor.callFromThread, as described above, your program can do very strange things, like appear to work a lot of the time and occasionally go wrong. This is difficult to debug!\"\n}\n[/block]\n[Next ...](doc:developing-bridge-apps)","excerpt":"","slug":"developing-bridge-apps-1","type":"basic","title":"How to Write Bridge-Apps"}

How to Write Bridge-Apps


Before reading this section, we suggest you have a look at the [A Raspberry Pi App Example](doc:writing-an-app-on-the-raspberry-pi) section. This section contains more details of how bridge-apps work and advice for writing more advanced apps. When you come to write an app yourself, it's usually a good idea to copy an existing app and modify it. See [How to Write Bridge-Apps](doc:developing-bridge-apps-1) for advice on a good way of doing about this to make you app easily deployable. [block:api-header] { "type": "basic", "title": "Event-driven programming" } [/block] Event-driven programming will not be familiar to some people. When we first lean programming, we generally write programs that start, do a job and then stop. Bridge-apps start when the bridge is first turned on and then effectively run forever, but they are only active when there is something to do. This should be borne in mind when reading the following paragraphs. [block:api-header] { "type": "basic", "title": "Overview" } [/block] To create a bridge-app, start by sub-classing the CbApp class, the definition of which can be found in cbcommslib, as follows: [block:code] { "codes": [ { "code": "from cbcommslib import CbApp\nfrom cbconfig import *\n\nclass App(CbApp):\n def __init__(self, argv):\n # Super-class init must be called\n CbApp.__init__(self, argv)\n \nif __name__ == '__main__':\n App(sys.argv)", "language": "python" } ] } [/block] Within class App, you must provide the following three methods, which are each called when messages arrive: [block:parameters] { "data": { "0-0": "onAdaptorServices", "1-0": "onAdaptorData", "2-0": "onConfigureMessage", "0-1": "This is called when “service” messages (see below) arrive from adaptors.", "1-1": "This is called when “data” messages arrive from adaptors.", "2-1": "This is called when configuration messages arrive from the bridge manager.\nonConcMessage. This is called when messages arrive from the concentrator." }, "cols": 2, "rows": 3 } [/block] The definition of the messages can be found in [The Bridge-App API](doc:the-bridge-app-api). [block:api-header] { "type": "basic", "title": "The configuration message" } [/block] In many cases, your app will not need to do anything with the configuration message. The main thing that the app gets from this message is a list of the names of the adaptors it is connected to , together with their "friendly names" (the names that they were given when the devices were installed), and the superclass already creates a dictionary with these in it, called self.friendlyLookup, which has the following format (with one entry for each connected adaptor): [block:code] { "codes": [ { "code": "{\"id\": \"friendly_name\"}", "language": "python" } ] } [/block] By convention, you should set the state of your app to "starting" on receiving this message, as shown in [A Raspberry Pi App Example](doc:writing-an-app-on-the-raspberry-pi). [block:api-header] { "type": "basic", "title": "The adaptor service message" } [/block] Some time after being receiving a configuration message, an app will receive a service message from each adaptor that it is connected to, with onAdaptorServices being called once for each configuration message. A service message from an adaptor contains the id of the adaptor. It's important to store this as that's how your app will know what data messages to expect from the adaptor and what to do with them. The service message contains details of the service that an adaptor provides, with the service being composed of a number of characteristics, as detailed in [The Bridge-App API](doc:the-bridge-app-api). Details of the characteristics that are supported can be found in [Characteristics](doc:characteristics). An app should respond to the service message by sending a service request message back to the adaptor. This is again detailed in [The Bridge-App API](doc:the-bridge-app-api). A device, and hence it adaptor, often supplies several characteristics as part of its service and an app should select which ones it is interested in. For example, PIR sensors quite often supply characteristics such as temperature and luminance as well. A security app is likely to be only interested in the PIR (a binary_sensor) and will respond requesting this, but not temperature and luminance. An energy management system may use all three of these and respond requesting them all. To send a message to an adaptor, an app uses the sendMessage method: [block:code] { "codes": [ { "code": "self.sendMessage(messsage, id)", "language": "python" } ] } [/block] where: message is the message to be send and id is the id of the adaptor to send it to. Here's a trivial example of an onAdaptorServices method that does this: [block:code] { "codes": [ { "code": "def onAdaptorService(self, message):\n for p in message[\"service\"]:\n if p[\"characteristic\"] == \"temperature\":\n self.temperatures.append(message[\"id\"]\n request = {\"id\": self.id,\n \"request\": \"service\",\n \"service\": [\n {\"characteristic\": \"temperature\",\n \"interval\": 600\n }\n ]\n }\n self.sendMessage(req, message[\"id\"])", "language": "python" } ] } [/block] Here, self.temperatures is a list of the ids of adaptors that the app will receive temperature from. The app replied to any adaptor that can provide temperature by saying that it wants to receive it every 10 minutes (600 seconds). The message from the adaptor also has an "interval" key, which says the minimum interval at which the adaptor can provide the characteristic. As a lot of devices are battery-powered, you are strongly advised to use the maximum interval that is possible for your application, in order to save energy. [block:callout] { "type": "info", "title": "How do I know where the characteristic has come from?", "body": "The astute reader will have noticed that we have not provided any way for the app to know where a characteristic has come from. Is the temperature from the kitchen, from outside or a thermometer inside the dog? The next major upgrade of the ContinuumBridge platform will provide a way for apps to say what they want. When a user connects a device on the portal, there will be an input say, for example \"Temperature inside dog\", so that they know that's what they need to connect to it. In the meantime, you can use a combination of the \"type\" of the service, which goes with each characteristic and friendly names (so the user will need to use the words \"inside dog\", for example, when they install the device)." } [/block] [block:api-header] { "type": "basic", "title": "The adaptor data message" } [/block] Once you have subscribed to characteristics from an adaptor, as described above, you app will receive adaptor data messages with the characteristics you have requested. This is best shown in a simple example: [block:code] { "codes": [ { "code": "def onAdaptorData(self, message):\n if message[\"characteristic\"] == \"temperature\":\n sample = {message[\"timestamp\"]: message[\"data\"])\n self.temperatures[message[\"id\"].append(sample)", "language": "python" } ] } [/block] Here, self.temperatures is an list of dictionaries or the form {timestamp: temperature}. All the method does is to append each new sample to this list. Quite often, you may want a call of onAdaptorData to do other things as well. For example, you could compare the temperature to a desired temperature and send an on/off message to a heating controller (using the self.sendMessage method) or call a method that sends data to a cloud platform. Example apps that do these and more can be found in the [ContinuumBridge GitHub area](https://github.com/ContinuumBridge). [block:api-header] { "type": "basic", "title": "Twisted time" } [/block] In cbridge, apps and adaptors (and everything else) communicate over sockets. ContinuumBridge makes use of an event-driven networking engine called [Twisted](https://twistedmatrix.com/trac/) to call methods in apps when data arrives, and you can also use Twisted to control when things happen in your app. [block:callout] { "type": "warning", "title": "Twisted", "body": "Although we've given a link to the Twisted Matix website, above, we don't actually recommend that you read it unless you're really keen. Twisted is a very powerful engine and some parts of it can be quite difficult to understand. We don't actually use that much of it in cbridge, and this documentation contains enough information to write comprehensive apps." } [/block] The core of Twisted is the reactor. As the name implies, the reactor reacts to things, such as data arriving at a port. When data arrives from an adaptor, for example, Twisted converts it into a Python dictionary and calls either onAdaptorService or onAdaptorData, whichever is appropriate. A call to self.sendMessage causes the message to be sent via the appropriate socket. There are two main circumstances where you will need to call Twisted methods directly yourself: Scheduling something to happen at some time in the future ----------------------------------------------------------------------------- You may want to do some processing every minute, for example, based on samples that have arrived from devices and some other information. The first thing you need in your code is: [block:code] { "codes": [ { "code": "from twisted.internet import reactor", "language": "python" } ] } [/block] Then you can write things like: [block:code] { "codes": [ { "code": "reactor.callLater(60, self.checkSensors)", "language": "text" } ] } [/block] This will cause the method checkSensors to be called in 60 seconds time. You could, for example include this in onConfigureMessage and then again at the end of the checkSensors method. Threading ------------- One thing to remember about writing apps is that, generally, if your code is waiting for something to happen, then no other methods can run. You may, for example, want to send some information to a cloud platform using an http POST. If the platform you are posting to is slow to respond, data from adaptors won't be processed until the POST has completed. This might be a problem, for example, if someone has pressed a button to turn on a light and nothing happens for three seconds. It's good programming practice to put all such tasks in threads, which can run "at the same time" as other things (or at least appear to - in reality the operating system is time-slicing between them). Twisted threads are essentially the same as standard Python threads, but we strongly recommend you use them in apps because Twisted understands them. To use them you need to: [block:code] { "codes": [ { "code": "from twisted.internet import threads", "language": "python" } ] } [/block] and then you can do things like: [block:code] { "codes": [ { "code": "reactor.callInThread(self.postValues)", "language": "python" } ] } [/block] [block:callout] { "type": "info", "title": "Thread-safe?", "body": "All the usual rules about using threads and ensuring your program is thread-safe apply. Just remember that all threads in your program have access to exactly the same data structures, so if you add data that's arrived from an adaptor to a list at the same time as your are sending that list from a thread the results are likely to be indeterminate. You could get around this by calling the thread with the number of samples to send. eg: reactor.callInThread(self.postValues, 5)." } [/block] Any method that you call from a thread will be part of the thread. Sending of messages, using self.sendMessage, if something that Twisted's reactor must handle, and that is not running in your thread, so you must use this construct: [block:code] { "codes": [ { "code": "reactor.callFromThread(self.sendMessage, msg, a).", "language": "python" } ] } [/block] [block:callout] { "type": "danger", "title": "Calling Twisted methods from threads", "body": "If you don't use reactor.callFromThread, as described above, your program can do very strange things, like appear to work a lot of the time and occasionally go wrong. This is difficult to debug!" } [/block] [Next ...](doc:developing-bridge-apps)