{"id":13499810,"url":"https://github.com/WebThingsIO/webthing-python","last_synced_at":"2025-03-29T05:32:28.063Z","repository":{"id":45636527,"uuid":"124557300","full_name":"WebThingsIO/webthing-python","owner":"WebThingsIO","description":"Python implementation of a Web Thing server","archived":false,"fork":false,"pushed_at":"2023-04-14T09:28:02.000Z","size":178,"stargazers_count":177,"open_issues_count":3,"forks_count":38,"subscribers_count":21,"default_branch":"master","last_synced_at":"2024-09-29T09:24:50.749Z","etag":null,"topics":[],"latest_commit_sha":null,"homepage":"","language":"Python","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mpl-2.0","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/WebThingsIO.png","metadata":{"files":{"readme":"README.rst","changelog":"CHANGELOG.md","contributing":null,"funding":null,"license":"LICENSE.txt","code_of_conduct":"CODE_OF_CONDUCT.md","threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null}},"created_at":"2018-03-09T15:22:43.000Z","updated_at":"2024-08-12T19:36:48.000Z","dependencies_parsed_at":"2024-04-15T06:30:18.193Z","dependency_job_id":"79d601aa-71c1-4aa1-a705-12324d3355a6","html_url":"https://github.com/WebThingsIO/webthing-python","commit_stats":null,"previous_names":[],"tags_count":27,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/WebThingsIO%2Fwebthing-python","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/WebThingsIO%2Fwebthing-python/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/WebThingsIO%2Fwebthing-python/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/WebThingsIO%2Fwebthing-python/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/WebThingsIO","download_url":"https://codeload.github.com/WebThingsIO/webthing-python/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":222465667,"owners_count":16989057,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":[],"created_at":"2024-07-31T22:00:43.236Z","updated_at":"2024-10-31T18:31:14.454Z","avatar_url":"https://github.com/WebThingsIO.png","language":"Python","funding_links":[],"categories":["Section"],"sub_categories":["Libraries"],"readme":"webthing\n========\n\n.. image:: https://github.com/WebThingsIO/webthing-python/workflows/Python%20package/badge.svg\n    :target: https://github.com/WebThingsIO/webthing-python/workflows/Python%20package\n.. image:: https://img.shields.io/pypi/v/webthing.svg\n    :target: https://pypi.org/project/webthing/\n.. image:: https://img.shields.io/badge/license-MPL--2.0-blue.svg\n    :target: https://github.com/WebThingsIO/webthing-python/blob/master/LICENSE.txt\n\nImplementation of an HTTP `Web Thing \u003chttps://iot.mozilla.org/wot/\u003e`_. This library is compatible with Python 2.7 and 3.5+.\n\nInstallation\n============\n\n``webthing`` can be installed via ``pip``, as such:\n\n.. code:: shell\n\n  $ pip install webthing\n\nRunning the Sample\n==================\n\n.. code:: shell\n\n  $ wget https://raw.githubusercontent.com/WebThingsIO/webthing-python/master/example/single-thing.py\n  $ python3 single-thing.py\n\nThis starts a server and lets you search for it from your gateway through mDNS. To add it to your gateway, navigate to the Things page in the gateway's UI and click the + icon at the bottom right. If both are on the same network, the example thing will automatically appear.\n\nExample Implementation\n======================\n\nIn this code-walkthrough we will set up a dimmable light and a humidity sensor (both using fake data, of course). Both working examples can be found in the `examples directory \u003chttps://github.com/WebThingsIO/webthing-python/tree/master/example\u003e`_.\n\nDimmable Light\n--------------\n\nImagine you have a dimmable light that you want to expose via the web of things API. The light can be turned on/off and the brightness can be set from 0% to 100%. Besides the name, description, and type, a |Light|_ is required to expose two properties:\n\n.. |Light| replace:: ``Light``\n.. _Light: https://webthings.io/schemas/#Light\n\n* ``on``: the state of the light, whether it is turned on or off\n\n  - Setting this property via a ``PUT {\"on\": true/false}`` call to the REST API toggles the light.\n\n* ``brightness``: the brightness level of the light from 0-100%\n\n  - Setting this property via a PUT call to the REST API sets the brightness level of this light.\n\nFirst we create a new Thing:\n\n.. code:: python\n\n    light = Thing(\n        'urn:dev:ops:my-lamp-1234',\n        'My Lamp',\n        ['OnOffSwitch', 'Light'],\n        'A web connected lamp'\n    )\n\nNow we can add the required properties.\n\nThe ``on`` property reports and sets the on/off state of the light. For this, we need to have a ``Value`` object which holds the actual state and also a method to turn the light on/off. For our purposes, we just want to log the new state if the light is switched on/off.\n\n.. code:: python\n\n  light.add_property(\n      Property(\n          light,\n          'on',\n          Value(True, lambda v: print('On-State is now', v)),\n          metadata={\n              '@type': 'OnOffProperty',\n              'title': 'On/Off',\n              'type': 'boolean',\n              'description': 'Whether the lamp is turned on',\n          }))\n\nThe ``brightness`` property reports the brightness level of the light and sets the level. Like before, instead of actually setting the level of a light, we just log the level.\n\n.. code:: python\n\n  light.add_property(\n      Property(\n          light,\n          'brightness',\n          Value(50, lambda v: print('Brightness is now', v)),\n          metadata={\n              '@type': 'BrightnessProperty',\n              'title': 'Brightness',\n              'type': 'number',\n              'description': 'The level of light from 0-100',\n              'minimum': 0,\n              'maximum': 100,\n              'unit': 'percent',\n          }))\n\nNow we can add our newly created thing to the server and start it:\n\n.. code:: python\n\n  # If adding more than one thing, use MultipleThings() with a name.\n  # In the single thing case, the thing's name will be broadcast.\n  server = WebThingServer(SingleThing(light), port=8888)\n\n  try:\n      server.start()\n  except KeyboardInterrupt:\n      server.stop()\n\nThis will start the server, making the light available via the WoT REST API and announcing it as a discoverable resource on your local network via mDNS.\n\nSensor\n------\n\nLet's now also connect a humidity sensor to the server we set up for our light.\n\nA |MultiLevelSensor|_ (a sensor that returns a level instead of just on/off) has one required property (besides the name, type, and optional description): ``level``. We want to monitor this property and get notified if the value changes.\n\n.. |MultiLevelSensor| replace:: ``MultiLevelSensor``\n.. _MultiLevelSensor: https://webthings.io/schemas/#MultiLevelSensor\n\nFirst we create a new Thing:\n\n.. code:: python\n\n  sensor = Thing(\n      'urn:dev:ops:my-humidity-sensor-1234',\n      'My Humidity Sensor',\n       ['MultiLevelSensor'],\n       'A web connected humidity sensor'\n  )\n\nThen we create and add the appropriate property:\n\n* ``level``: tells us what the sensor is actually reading\n\n  - Contrary to the light, the value cannot be set via an API call, as it wouldn't make much sense, to SET what a sensor is reading. Therefore, we are creating a **readOnly** property.\n\n    .. code:: python\n\n      level = Value(0.0);\n\n      sensor.add_property(\n          Property(\n              sensor,\n              'level',\n              level,\n              metadata={\n                  '@type': 'LevelProperty',\n                  'title': 'Humidity',\n                  'type': 'number',\n                  'description': 'The current humidity in %',\n                  'minimum': 0,\n                  'maximum': 100,\n                  'unit': 'percent',\n                  'readOnly': True,\n              }))\n\nNow we have a sensor that constantly reports 0%. To make it usable, we need a thread or some kind of input when the sensor has a new reading available. For this purpose we start a thread that queries the physical sensor every few seconds. For our purposes, it just calls a fake method.\n\n.. code:: python\n\n  self.sensor_update_task = \\\n      get_event_loop().create_task(self.update_level())\n\n  async def update_level(self):\n      try:\n          while True:\n              await sleep(3)\n              new_level = self.read_from_gpio()\n              logging.debug('setting new humidity level: %s', new_level)\n              self.level.notify_of_external_update(new_level)\n      except CancelledError:\n          pass\n\nThis will update our ``Value`` object with the sensor readings via the ``self.level.notify_of_external_update(read_from_gpio())`` call. The ``Value`` object now notifies the property and the thing that the value has changed, which in turn notifies all websocket listeners.\n\nAdding to Gateway\n=================\n\nTo add your web thing to the WebThings Gateway, install the \"Web Thing\" add-on and follow the instructions `here \u003chttps://github.com/WebThingsIO/thing-url-adapter#readme\u003e`_.\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2FWebThingsIO%2Fwebthing-python","html_url":"https://awesome.ecosyste.ms/projects/github.com%2FWebThingsIO%2Fwebthing-python","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2FWebThingsIO%2Fwebthing-python/lists"}