{"_id":"543d1fa83a300f20000d3206","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"},"user":"543b93f865bf840e00b473b2","__v":13,"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"},"project":"543b943865bf840e00b473b3","is_link":false,"updates":[],"next":{"pages":[],"description":""},"createdAt":"2014-10-14T13:05:44.945Z","link_external":false,"link_url":"","githubsync":"","sync_unique":"","hidden":false,"api":{"results":{"codes":[]},"try":true,"basic_auth":false,"auth":"never","params":[],"url":""},"isReference":false,"order":4,"body":"[block:api-header]\n{\n  \"type\": \"basic\",\n  \"title\": \"A few things about bridge-apps\"\n}\n[/block]\nBefore looking at some code, it's worth knowing a few things about the way bridge-apps work in general. As discussed in the Overview, each app is connected to the bridge manager, the concentrator and a number of device adaptors. The bridge manager takes configuration that is derived from which devices a user has connected to an app and connects the corresponding adaptors. \n\nBridge-apps (and indeed everything running on a bridge) use an event-driven programming paradigm. Anyone who has done web or graphics programming should be familiar with this, but in the context of a bridge-app, it means that every time a message arrives from anything that is connected to the app, a method will be called. The method can do any processing that is necessary as a result of the message. Bridge-app methods can send messages to anything connected to the bridge-app at any point. Most bridge-apps will do relatively little processing, so there is unlikely to be any issue with not being able to process incoming messages fast enough and running out of time. For apps that do a lot of processing there are ways around this that are not covered in this introduction. The thing to note is that you should write a bride-app in such a way that methods respond to an input, do their processing, send off any resulting messages and then return. In particular, do not be tempted to insert artificial delays, for example using Python's time.sleep(). \n\nSome apps will need to do things like schedule tasks to be run at some point in the future. This can be achieved by directly using the communications framework of the bridge-app, Twisted (https://twistedmatrix.com/). Twisted is an event-driven network programming framework. This is not exposed directly to bridge-app developers, but is available for more advanced apps. To see how it's used in the app superclass, look in /opt/cbridge/bridge/lib/cbcommslib.py.\n[block:api-header]\n{\n  \"type\": \"basic\",\n  \"title\": \"Example walk-through\"\n}\n[/block]\nWe will choose a very simple example to start with. A number of sensors and a switch will be connected to the app. The sensors can be any devices that gives an off/on binary output, for example a PIR detector or a button. We will give the complete code for the app and then look at it step by step. This code is copied directly from here:\n\n    https://github.com/ContinuumBridge/demo_switch_app\n[block:code]\n{\n  \"codes\": [\n    {\n      \"code\": \"#!/usr/bin/env python\\n# demo_switch_app_a.py\\n\\\"\\\"\\\"\\nCopyright (c) 2014 ContinuumBridge Limited\\n\\\"\\\"\\\"\\n\\nimport sys\\nimport json\\nfrom cbcommslib import CbApp\\nfrom cbconfig import *\\n\\nclass App(CbApp):\\n    def __init__(self, argv):\\n        self.state = \\\"stopped\\\"\\n        self.switchState = \\\"off\\\"\\n        self.gotSwitch = False\\n        self.sensorsID = [] \\n        self.switchID = \\\"\\\"\\n        # Super-class init must be called\\n        CbApp.__init__(self, argv)\\n\\n    def setState(self, action):\\n        self.state = action\\n        msg = {\\\"id\\\": self.id,\\n               \\\"status\\\": \\\"state\\\",\\n               \\\"state\\\": self.state}\\n        self.sendManagerMessage(msg)\\n\\n    def sendServiceResponse(self, characteristic, device):\\n        r = {\\\"id\\\": self.id,\\n             \\\"request\\\": \\\"service\\\",\\n             \\\"service\\\": [\\n                          {\\\"characteristic\\\": characteristic,\\n                           \\\"interval\\\": 0\\n                          }\\n                        ]\\n            }\\n        self.sendMessage(r, device)\\n\\n    def sendCommand(self, state):\\n        r = {\\\"id\\\": self.id,\\n             \\\"request\\\": \\\"command\\\",\\n             \\\"data\\\": state\\n            }\\n        self.sendMessage(r, self.switchID)\\n\\n    def onAdaptorService(self, message):\\n        self.cbLog(\\\"debug\\\", \\\"onAdaptorService, message: \\\" + str(json.dumps(message, indent=4)))\\n        controller = None\\n        switch = False\\n        for s in message[\\\"service\\\"]:\\n            if s[\\\"characteristic\\\"] == \\\"buttons\\\" \\\\\\n                or s[\\\"characteristic\\\"] == \\\"number_buttons\\\" \\\\\\n                or s[\\\"characteristic\\\"] == \\\"binary_sensor\\\":\\n                controller = s[\\\"characteristic\\\"]\\n            elif s[\\\"characteristic\\\"] == \\\"switch\\\":\\n                self.switchID = message[\\\"id\\\"]\\n                switch = True\\n                self.gotSwitch = True\\n        if controller and not switch:\\n            self.sensorsID.append(message[\\\"id\\\"])\\n            self.sendServiceResponse(controller, message[\\\"id\\\"])\\n        self.setState(\\\"running\\\")\\n\\n    def onAdaptorData(self, message):\\n        self.cbLog(\\\"debug\\\", \\\"onAdaptorData, message: \\\" + str(json.dumps(message, indent=4)))\\n        if message[\\\"id\\\"] in self.sensorsID:\\n            if self.gotSwitch:\\n                if message[\\\"characteristic\\\"] == \\\"binary_sensor\\\":\\n                    self.switchState = message[\\\"data\\\"]\\n                else:\\n                    if self.switchState == \\\"off\\\":\\n                        self.switchState = \\\"on\\\"\\n                    else:\\n                        self.switchState = \\\"off\\\"\\n                self.sendCommand(self.switchState)\\n            else:\\n                self.cbLog(\\\"debug\\\", \\\"Trying to turn on/off before switch connected\\\")\\n\\n    def onConfigureMessage(self, config):\\n        self.setState(\\\"starting\\\")\\n\\nif __name__ == '__main__':\\n    App(sys.argv)\",\n      \"language\": \"python\"\n    }\n  ]\n}\n[/block]\nLooking at this step by step, firstly, the headers:\n[block:code]\n{\n  \"codes\": [\n    {\n      \"code\": \"#!/usr/bin/env python\\n# demo_switch_app.py\\n\\\"\\\"\\\"\\nCopyright (c) 2014 ContinuumBridge Limited\\n\\\"\\\"\\\"\\n\\nimport sys\\nimport json\\nfrom cbcommslib import CbApp\\nfrom cbconfig import *\",\n      \"language\": \"python\"\n    }\n  ]\n}\n[/block]\nThe main thing to note about the imports are that CbApp must be imported from the cbcommslib module and everything must be imported from cbconfig. Details of these are described later in this document, but it's not necessary to know this for this example.\n\nNow, looking at the class declaration and __init__ method for the app:\n[block:code]\n{\n  \"codes\": [\n    {\n      \"code\": \"class App(CbApp):\\n    def __init__(self, argv):\\n        self.state = \\\"stopped\\\"\\n        self.switchState = \\\"off\\\"\\n        self.gotSwitch = False\\n        self.sensorsID = [] \\n        self.switchID = \\\"\\\"\\n        # Super-class init must be called\\n        CbApp.__init__(self, argv)\",\n      \"language\": \"python\"\n    }\n  ]\n}\n[/block]\nFirstly, note that all apps must subclass CbApp. The CbApp super-class takes care of all communication with the bridge manager, adaptors and concentrator. Messages between these entities actually takes place by passing JSON over sockets, but by the time the messages arrive at the user's app they are provided as Python dictionaries. Similarly, messages are sent by passing Python dictionaries to the appropriate CbApp methods. A few variables that will be used later in the app are declared before calling the __init__ method of the CbApp superclass. \n\nWhen messages arrive from the bridge manager, the concentrator or from adaptors, the CbApp superclass calls various method.  These are:\n[block:parameters]\n{\n  \"data\": {\n    \"0-0\": \"onAdaptorServices\",\n    \"0-1\": \"This is called when “service” messages (see below) arrive from adaptors.\",\n    \"1-0\": \"onAdaptorData\",\n    \"1-1\": \"This is called when “data” messages arrive from adaptors.\",\n    \"2-0\": \"onConfigureMessage\",\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]\nThis simple app does not have any concentrator messages and there is not really any configuration to do, but a  method is provided that is called when a configuration message arrives:\n[block:code]\n{\n  \"codes\": [\n    {\n      \"code\": \"    def onConfigureMessage(self, config):\\n        self.setState(\\\"starting\\\")\",\n      \"language\": \"python\"\n    }\n  ]\n}\n[/block]\nThis just calls the setState method which sets the app state to “starting” and sends a message to the bridge manager informing it of the change of state.\n\nAn adaptor advertises the service that it  performs to apps. When the associated message arrives from an adaptor, the onAdaptorService method is called with the message. Here is an example of a message that would arrive from an adaptor that connects to a device that provides temperature, relative humidity and luminance measurements and is also a binary sensor:\n[block:code]\n{\n  \"codes\": [\n    {\n      \"code\": \"{\\n    \\\"name\\\": “Multi-sensor”,\\n    \\\"id\\\": “DID117”,\\n    \\\"content\\\": \\\"service\\\",\\n    \\\"status\\\": \\\"ok\\\",\\n    \\\"service\\\": [{\\\"characteristic\\\": \\\"binary_sensor\\\", \\\"interval\\\": 0},\\n                {\\\"characteristic\\\": \\\"temperature\\\", \\\"interval\\\": 300},\\n                {\\\"characteristic\\\": \\\"luminance\\\", \\\"interval\\\": 300},\\n                {\\\"characteristic\\\": \\\"humidity\\\", \\\"interval\\\": 300}],\\n}\",\n      \"language\": \"json\"\n    }\n  ]\n}\n[/block]\nThe adaptor name is the description provided by the writer of the adaptor. This should not be used in any app logic as the temperature may be provided by any temperature sensor that has been connected to the app. The device ID is important, as this will be used to send messages back to the adaptor. In this example, the adaptor can provide  temperature, humidity and luminance measurements at a minimum interval of 300 seconds. The  code for the onAdaptorService method, below, shows how the app parses this message, finds the binary_sensor parameter and then sends a message back to the adaptor requesting that the binary_sensor information be sent. The interval is specified as 0 because a message is sent every time the sensor changes state rather than at a particular interval. The reason the onAdaptorService code is structured in this precise way is because some switches also have a binary_sensor characteristic, which can be used to determine the state the switch is in. We don't want to use this as an input or we could have a feedback loop with the switch turning itself on and off all the time!\n[block:code]\n{\n  \"codes\": [\n    {\n      \"code\": \"       def sendServiceResponse(self, characteristic, device):\\n        r = {\\\"id\\\": self.id,\\n             \\\"request\\\": \\\"service\\\",\\n             \\\"service\\\": [\\n                          {\\\"characteristic\\\": characteristic,\\n                           \\\"interval\\\": 0\\n                          }\\n                        ]\\n            }\\n        self.sendMessage(r, device\\n\\n    def onAdaptorService(self, message):\\n        self.cbLog(\\\"debug\\\", \\\"onAdaptorService, message: \\\" + str(json.dumps(message, indent=4)))\\n        controller = None\\n        switch = False\\n        for s in message[\\\"service\\\"]:\\n            if s[\\\"characteristic\\\"] == \\\"buttons\\\" \\\\\\n                or s[\\\"characteristic\\\"] == \\\"number_buttons\\\" \\\\\\n                or s[\\\"characteristic\\\"] == \\\"binary_sensor\\\":\\n                controller = s[\\\"characteristic\\\"]\\n            elif s[\\\"characteristic\\\"] == \\\"switch\\\":\\n                self.switchID = message[\\\"id\\\"]\\n                switch = True\\n                self.gotSwitch = True\\n        if controller and not switch:\\n            self.sensorsID.append(message[\\\"id\\\"])\\n            self.sendServiceResponse(controller, message[\\\"id\\\"])\\n        self.setState(\\\"running\\\")\",\n      \"language\": \"python\"\n    }\n  ]\n}\n[/block]\n\n[block:callout]\n{\n  \"type\": \"info\",\n  \"title\": \"What's does the self.cbLog statement do?\",\n  \"body\": \"It sends a message to the bridge manager that causes a message to be written to the log file. There's more about this later on in this example.\"\n}\n[/block]\nThe message sent back to the adaptor, corresponding to the message received above, will therefore be:\n[block:code]\n{\n  \"codes\": [\n    {\n      \"code\": \"{\\n    \\\"id\\\": \\\"AID10\\\",\\n    \\\"request\\\": \\\"service\\\",\\n    \\\"service\\\": [\\n        {\\\"characteristic\\\": \\\"binary_sensor\\\",\\n         \\\"interval\\\": 0\\n        }\\n    ]\\n}\",\n      \"language\": \"json\"\n    }\n  ]\n}\n[/block]\nThe app ID is provided via the CbApp super-class. It is unique to this instance of this app and is included in all messages sent by the app.\n\nThis app can actually be connected to any number of binary sensor sources, the identities of which are stored in the  self.sensorsID list, but only one switch.\n\nThe final thing to note about the onAdaptorService method is that the ID of the switch was stored in the self.switchID variable, so that the app knows where to send messages to turn the switch off and on.\n\nHaving said what it wants from the sensor adaptor, the app just sits back and waits for data to arrive. When it arrives, the onAdaptorData method is called:\n[block:code]\n{\n  \"codes\": [\n    {\n      \"code\": \"    def onAdaptorData(self, message):\\n        self.cbLog(\\\"debug\\\", \\\"onAdaptorData, message: \\\" + str(json.dumps(message, indent=4)))\\n        if message[\\\"id\\\"] in self.sensorsID:\\n            if self.gotSwitch:\\n                if message[\\\"characteristic\\\"] == \\\"binary_sensor\\\":\\n                    self.switchState = message[\\\"data\\\"]\\n                else:\\n                    if self.switchState == \\\"off\\\":\\n                        self.switchState = \\\"on\\\"\\n                    else:\\n                        self.switchState = \\\"off\\\"\\n                self.sendCommand(self.switchState)\\n            else:\\n                self.cbLog(\\\"debug\\\", \\\"Trying to turn on/off before switch connected\\\")\\n\\n    def onConfigureMessage(self, config):\\n        self.setState(\\\"starting\\\")\",\n      \"language\": \"python\"\n    }\n  ]\n}\n[/block]\nIt can be seen that the app looks at the source of the message. If it's from a sensor in the self.sensorsID list either sets the switch state to be the same as the input (in the case of a binary sensor) or toggles the switch state. The “if self.gotSwitch” and setting of self.gotSwitch allows for the fact that data from an an adaptor could arrive before the switch has been initialised (something that was found in debugging this example). There is more about the use of logging later in this document. For completeness, here is an example of a message that may have been received from the adaptor:\n[block:code]\n{\n  \"codes\": [\n    {\n      \"code\": \"{\\n    \\\"name\\\": \\\"Multi-sensor\\\",\\n    \\\"id\\\": \\\"DID117\\\",\\n    \\\"content\\\": \\\"characteristic\\\",\\n    \\\"characteristic\\\": \\\"biinary_sensor\\\",\\n    \\\"data\\\": \\\"on\\\"\\n}\",\n      \"language\": \"json\"\n    }\n  ]\n}\n[/block]\nAnd here is the corresponding message that would be sent to the switch:\n[block:code]\n{\n  \"codes\": [\n    {\n      \"code\": \"{\\n    \\\"id\\\": \\\"AID10\\\",\\n    \\\"request\\\": \\\"command\\\",\\n    \\\"data\\\": \\\"on\\\"\\n}\",\n      \"language\": \"json\"\n    }\n  ]\n}\n[/block]\n\n[block:api-header]\n{\n  \"type\": \"basic\",\n  \"title\": \"Running the example\"\n}\n[/block]\nOverview\n------------\nThis section explains how to run the app in development mode. Once the app is deployed the process is completely automatic.\n\nTo run the example in the real world you will need a binary sensor and a switch that have ContinuumBridge adaptors. To run the example you will need a device that outputs buttons, number_buttons or binary_sensor characteristics ([see the list of devices](Devices)), in addition to a supported switch. We used a Z-wave mains switch. \n\nAccessing the source code\n------------------------------------\nThe source code to the Demo Switch App example and many other apps is on Github (https://github.com/ContinuumBridge/demo_switch_app). To access it, create a directory in the bridge home directory of your Raspberry Pi called apps_dev and clone the code, as follows:\n[block:code]\n{\n  \"codes\": [\n    {\n      \"code\": \"cd ~\\nmkdir apps_dev\\ncd apps_dev\\ngit clone https://github.com/ContinuumBridge/demo_switch_app.git\",\n      \"language\": \"shell\"\n    }\n  ]\n}\n[/block]\nThe source code for the app will now be in the directory ~/apps_dev/demo_switch_app, in the file demo_switch_app_a.py. (There is also a file called demo_switch_app.py. This is to force Python to create a .pyc file after the app has been run for the first time, which makes subsequent start-up of the app slightly more efficient).\n\nFor cbridge to use code in the apps_dev directory in preference to production code that it may have downloaded, you need to add the following line to /opt/cbridge/thisbridge/thisbridge.sh:\n[block:code]\n{\n  \"codes\": [\n    {\n      \"code\": \"export CB_DEV_BRIDGE='True'\\nexport CB_DEV_APPS=\\\"Demo Switch App\\\"\\nexport CB_USERNAME='bridge'\",\n      \"language\": \"shell\"\n    }\n  ]\n}\n[/block]\nThe first line tells cbridge that this Raspberry Pi is being used as a development bridge, and the second tells it to use the local code and not download code. The third line tell cbridge your user name. In this case this is \"bridge\". If you are using the default Raspberry Pi user, CB_USERNAME will be \"pi\".\n\nAlso for development, it is useful to put the following line in /opt/cbridge/thisbridge/thisbridge.sh:\n[block:code]\n{\n  \"codes\": [\n    {\n      \"code\": \"export CB_LOG_ENVIRONMENT='DEBUG'\",\n      \"language\": \"shell\"\n    }\n  ]\n}\n[/block]\nValid values for the log options, apart from “debug”, are “info”, “warning” and “error”. These switch on various levels of logging, some of which can be seen in the Demo Switch App example.\n\nYou are now ready to connect the app to some devices, which is described in the ContinuumBridge Portal section.\n[block:api-header]\n{\n  \"type\": \"basic\",\n  \"title\": \"Other examples\"\n}\n[/block]\nOther example apps can be found by browsing https://github.com/ContinuumBridge. Generally, repositories that contain apps are identified by the word “app” in their name.\n\nNow that you've seen this example, you can:\n\n* [Learn more about writing bridge-apps](doc:developing-bridge-apps-1) \n* [Read some advice about developing and debugging bridge-apps](doc:developing-bridge-apps) \n* [Find out how to deploy bridge-apps so that anyone can use them](doc:deploying-bridge-apps)","excerpt":"","slug":"writing-an-app-on-the-raspberry-pi","type":"basic","title":"A Raspberry Pi App Example"}

A Raspberry Pi App Example


[block:api-header] { "type": "basic", "title": "A few things about bridge-apps" } [/block] Before looking at some code, it's worth knowing a few things about the way bridge-apps work in general. As discussed in the Overview, each app is connected to the bridge manager, the concentrator and a number of device adaptors. The bridge manager takes configuration that is derived from which devices a user has connected to an app and connects the corresponding adaptors. Bridge-apps (and indeed everything running on a bridge) use an event-driven programming paradigm. Anyone who has done web or graphics programming should be familiar with this, but in the context of a bridge-app, it means that every time a message arrives from anything that is connected to the app, a method will be called. The method can do any processing that is necessary as a result of the message. Bridge-app methods can send messages to anything connected to the bridge-app at any point. Most bridge-apps will do relatively little processing, so there is unlikely to be any issue with not being able to process incoming messages fast enough and running out of time. For apps that do a lot of processing there are ways around this that are not covered in this introduction. The thing to note is that you should write a bride-app in such a way that methods respond to an input, do their processing, send off any resulting messages and then return. In particular, do not be tempted to insert artificial delays, for example using Python's time.sleep(). Some apps will need to do things like schedule tasks to be run at some point in the future. This can be achieved by directly using the communications framework of the bridge-app, Twisted (https://twistedmatrix.com/). Twisted is an event-driven network programming framework. This is not exposed directly to bridge-app developers, but is available for more advanced apps. To see how it's used in the app superclass, look in /opt/cbridge/bridge/lib/cbcommslib.py. [block:api-header] { "type": "basic", "title": "Example walk-through" } [/block] We will choose a very simple example to start with. A number of sensors and a switch will be connected to the app. The sensors can be any devices that gives an off/on binary output, for example a PIR detector or a button. We will give the complete code for the app and then look at it step by step. This code is copied directly from here: https://github.com/ContinuumBridge/demo_switch_app [block:code] { "codes": [ { "code": "#!/usr/bin/env python\n# demo_switch_app_a.py\n\"\"\"\nCopyright (c) 2014 ContinuumBridge Limited\n\"\"\"\n\nimport sys\nimport json\nfrom cbcommslib import CbApp\nfrom cbconfig import *\n\nclass App(CbApp):\n def __init__(self, argv):\n self.state = \"stopped\"\n self.switchState = \"off\"\n self.gotSwitch = False\n self.sensorsID = [] \n self.switchID = \"\"\n # Super-class init must be called\n CbApp.__init__(self, argv)\n\n def setState(self, action):\n self.state = action\n msg = {\"id\": self.id,\n \"status\": \"state\",\n \"state\": self.state}\n self.sendManagerMessage(msg)\n\n def sendServiceResponse(self, characteristic, device):\n r = {\"id\": self.id,\n \"request\": \"service\",\n \"service\": [\n {\"characteristic\": characteristic,\n \"interval\": 0\n }\n ]\n }\n self.sendMessage(r, device)\n\n def sendCommand(self, state):\n r = {\"id\": self.id,\n \"request\": \"command\",\n \"data\": state\n }\n self.sendMessage(r, self.switchID)\n\n def onAdaptorService(self, message):\n self.cbLog(\"debug\", \"onAdaptorService, message: \" + str(json.dumps(message, indent=4)))\n controller = None\n switch = False\n for s in message[\"service\"]:\n if s[\"characteristic\"] == \"buttons\" \\\n or s[\"characteristic\"] == \"number_buttons\" \\\n or s[\"characteristic\"] == \"binary_sensor\":\n controller = s[\"characteristic\"]\n elif s[\"characteristic\"] == \"switch\":\n self.switchID = message[\"id\"]\n switch = True\n self.gotSwitch = True\n if controller and not switch:\n self.sensorsID.append(message[\"id\"])\n self.sendServiceResponse(controller, message[\"id\"])\n self.setState(\"running\")\n\n def onAdaptorData(self, message):\n self.cbLog(\"debug\", \"onAdaptorData, message: \" + str(json.dumps(message, indent=4)))\n if message[\"id\"] in self.sensorsID:\n if self.gotSwitch:\n if message[\"characteristic\"] == \"binary_sensor\":\n self.switchState = message[\"data\"]\n else:\n if self.switchState == \"off\":\n self.switchState = \"on\"\n else:\n self.switchState = \"off\"\n self.sendCommand(self.switchState)\n else:\n self.cbLog(\"debug\", \"Trying to turn on/off before switch connected\")\n\n def onConfigureMessage(self, config):\n self.setState(\"starting\")\n\nif __name__ == '__main__':\n App(sys.argv)", "language": "python" } ] } [/block] Looking at this step by step, firstly, the headers: [block:code] { "codes": [ { "code": "#!/usr/bin/env python\n# demo_switch_app.py\n\"\"\"\nCopyright (c) 2014 ContinuumBridge Limited\n\"\"\"\n\nimport sys\nimport json\nfrom cbcommslib import CbApp\nfrom cbconfig import *", "language": "python" } ] } [/block] The main thing to note about the imports are that CbApp must be imported from the cbcommslib module and everything must be imported from cbconfig. Details of these are described later in this document, but it's not necessary to know this for this example. Now, looking at the class declaration and __init__ method for the app: [block:code] { "codes": [ { "code": "class App(CbApp):\n def __init__(self, argv):\n self.state = \"stopped\"\n self.switchState = \"off\"\n self.gotSwitch = False\n self.sensorsID = [] \n self.switchID = \"\"\n # Super-class init must be called\n CbApp.__init__(self, argv)", "language": "python" } ] } [/block] Firstly, note that all apps must subclass CbApp. The CbApp super-class takes care of all communication with the bridge manager, adaptors and concentrator. Messages between these entities actually takes place by passing JSON over sockets, but by the time the messages arrive at the user's app they are provided as Python dictionaries. Similarly, messages are sent by passing Python dictionaries to the appropriate CbApp methods. A few variables that will be used later in the app are declared before calling the __init__ method of the CbApp superclass. When messages arrive from the bridge manager, the concentrator or from adaptors, the CbApp superclass calls various method. These are: [block:parameters] { "data": { "0-0": "onAdaptorServices", "0-1": "This is called when “service” messages (see below) arrive from adaptors.", "1-0": "onAdaptorData", "1-1": "This is called when “data” messages arrive from adaptors.", "2-0": "onConfigureMessage", "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] This simple app does not have any concentrator messages and there is not really any configuration to do, but a method is provided that is called when a configuration message arrives: [block:code] { "codes": [ { "code": " def onConfigureMessage(self, config):\n self.setState(\"starting\")", "language": "python" } ] } [/block] This just calls the setState method which sets the app state to “starting” and sends a message to the bridge manager informing it of the change of state. An adaptor advertises the service that it performs to apps. When the associated message arrives from an adaptor, the onAdaptorService method is called with the message. Here is an example of a message that would arrive from an adaptor that connects to a device that provides temperature, relative humidity and luminance measurements and is also a binary sensor: [block:code] { "codes": [ { "code": "{\n \"name\": “Multi-sensor”,\n \"id\": “DID117”,\n \"content\": \"service\",\n \"status\": \"ok\",\n \"service\": [{\"characteristic\": \"binary_sensor\", \"interval\": 0},\n {\"characteristic\": \"temperature\", \"interval\": 300},\n {\"characteristic\": \"luminance\", \"interval\": 300},\n {\"characteristic\": \"humidity\", \"interval\": 300}],\n}", "language": "json" } ] } [/block] The adaptor name is the description provided by the writer of the adaptor. This should not be used in any app logic as the temperature may be provided by any temperature sensor that has been connected to the app. The device ID is important, as this will be used to send messages back to the adaptor. In this example, the adaptor can provide temperature, humidity and luminance measurements at a minimum interval of 300 seconds. The code for the onAdaptorService method, below, shows how the app parses this message, finds the binary_sensor parameter and then sends a message back to the adaptor requesting that the binary_sensor information be sent. The interval is specified as 0 because a message is sent every time the sensor changes state rather than at a particular interval. The reason the onAdaptorService code is structured in this precise way is because some switches also have a binary_sensor characteristic, which can be used to determine the state the switch is in. We don't want to use this as an input or we could have a feedback loop with the switch turning itself on and off all the time! [block:code] { "codes": [ { "code": " def sendServiceResponse(self, characteristic, device):\n r = {\"id\": self.id,\n \"request\": \"service\",\n \"service\": [\n {\"characteristic\": characteristic,\n \"interval\": 0\n }\n ]\n }\n self.sendMessage(r, device\n\n def onAdaptorService(self, message):\n self.cbLog(\"debug\", \"onAdaptorService, message: \" + str(json.dumps(message, indent=4)))\n controller = None\n switch = False\n for s in message[\"service\"]:\n if s[\"characteristic\"] == \"buttons\" \\\n or s[\"characteristic\"] == \"number_buttons\" \\\n or s[\"characteristic\"] == \"binary_sensor\":\n controller = s[\"characteristic\"]\n elif s[\"characteristic\"] == \"switch\":\n self.switchID = message[\"id\"]\n switch = True\n self.gotSwitch = True\n if controller and not switch:\n self.sensorsID.append(message[\"id\"])\n self.sendServiceResponse(controller, message[\"id\"])\n self.setState(\"running\")", "language": "python" } ] } [/block] [block:callout] { "type": "info", "title": "What's does the self.cbLog statement do?", "body": "It sends a message to the bridge manager that causes a message to be written to the log file. There's more about this later on in this example." } [/block] The message sent back to the adaptor, corresponding to the message received above, will therefore be: [block:code] { "codes": [ { "code": "{\n \"id\": \"AID10\",\n \"request\": \"service\",\n \"service\": [\n {\"characteristic\": \"binary_sensor\",\n \"interval\": 0\n }\n ]\n}", "language": "json" } ] } [/block] The app ID is provided via the CbApp super-class. It is unique to this instance of this app and is included in all messages sent by the app. This app can actually be connected to any number of binary sensor sources, the identities of which are stored in the self.sensorsID list, but only one switch. The final thing to note about the onAdaptorService method is that the ID of the switch was stored in the self.switchID variable, so that the app knows where to send messages to turn the switch off and on. Having said what it wants from the sensor adaptor, the app just sits back and waits for data to arrive. When it arrives, the onAdaptorData method is called: [block:code] { "codes": [ { "code": " def onAdaptorData(self, message):\n self.cbLog(\"debug\", \"onAdaptorData, message: \" + str(json.dumps(message, indent=4)))\n if message[\"id\"] in self.sensorsID:\n if self.gotSwitch:\n if message[\"characteristic\"] == \"binary_sensor\":\n self.switchState = message[\"data\"]\n else:\n if self.switchState == \"off\":\n self.switchState = \"on\"\n else:\n self.switchState = \"off\"\n self.sendCommand(self.switchState)\n else:\n self.cbLog(\"debug\", \"Trying to turn on/off before switch connected\")\n\n def onConfigureMessage(self, config):\n self.setState(\"starting\")", "language": "python" } ] } [/block] It can be seen that the app looks at the source of the message. If it's from a sensor in the self.sensorsID list either sets the switch state to be the same as the input (in the case of a binary sensor) or toggles the switch state. The “if self.gotSwitch” and setting of self.gotSwitch allows for the fact that data from an an adaptor could arrive before the switch has been initialised (something that was found in debugging this example). There is more about the use of logging later in this document. For completeness, here is an example of a message that may have been received from the adaptor: [block:code] { "codes": [ { "code": "{\n \"name\": \"Multi-sensor\",\n \"id\": \"DID117\",\n \"content\": \"characteristic\",\n \"characteristic\": \"biinary_sensor\",\n \"data\": \"on\"\n}", "language": "json" } ] } [/block] And here is the corresponding message that would be sent to the switch: [block:code] { "codes": [ { "code": "{\n \"id\": \"AID10\",\n \"request\": \"command\",\n \"data\": \"on\"\n}", "language": "json" } ] } [/block] [block:api-header] { "type": "basic", "title": "Running the example" } [/block] Overview ------------ This section explains how to run the app in development mode. Once the app is deployed the process is completely automatic. To run the example in the real world you will need a binary sensor and a switch that have ContinuumBridge adaptors. To run the example you will need a device that outputs buttons, number_buttons or binary_sensor characteristics ([see the list of devices](Devices)), in addition to a supported switch. We used a Z-wave mains switch. Accessing the source code ------------------------------------ The source code to the Demo Switch App example and many other apps is on Github (https://github.com/ContinuumBridge/demo_switch_app). To access it, create a directory in the bridge home directory of your Raspberry Pi called apps_dev and clone the code, as follows: [block:code] { "codes": [ { "code": "cd ~\nmkdir apps_dev\ncd apps_dev\ngit clone https://github.com/ContinuumBridge/demo_switch_app.git", "language": "shell" } ] } [/block] The source code for the app will now be in the directory ~/apps_dev/demo_switch_app, in the file demo_switch_app_a.py. (There is also a file called demo_switch_app.py. This is to force Python to create a .pyc file after the app has been run for the first time, which makes subsequent start-up of the app slightly more efficient). For cbridge to use code in the apps_dev directory in preference to production code that it may have downloaded, you need to add the following line to /opt/cbridge/thisbridge/thisbridge.sh: [block:code] { "codes": [ { "code": "export CB_DEV_BRIDGE='True'\nexport CB_DEV_APPS=\"Demo Switch App\"\nexport CB_USERNAME='bridge'", "language": "shell" } ] } [/block] The first line tells cbridge that this Raspberry Pi is being used as a development bridge, and the second tells it to use the local code and not download code. The third line tell cbridge your user name. In this case this is "bridge". If you are using the default Raspberry Pi user, CB_USERNAME will be "pi". Also for development, it is useful to put the following line in /opt/cbridge/thisbridge/thisbridge.sh: [block:code] { "codes": [ { "code": "export CB_LOG_ENVIRONMENT='DEBUG'", "language": "shell" } ] } [/block] Valid values for the log options, apart from “debug”, are “info”, “warning” and “error”. These switch on various levels of logging, some of which can be seen in the Demo Switch App example. You are now ready to connect the app to some devices, which is described in the ContinuumBridge Portal section. [block:api-header] { "type": "basic", "title": "Other examples" } [/block] Other example apps can be found by browsing https://github.com/ContinuumBridge. Generally, repositories that contain apps are identified by the word “app” in their name. Now that you've seen this example, you can: * [Learn more about writing bridge-apps](doc:developing-bridge-apps-1) * [Read some advice about developing and debugging bridge-apps](doc:developing-bridge-apps) * [Find out how to deploy bridge-apps so that anyone can use them](doc:deploying-bridge-apps)