Package: platypush
PlatypushUseful linksIntroductionWhat it can doInstallationSystem installationInstall throughpipInstall through a system package managerInstall from sourcesInstalling the dependencies for your extensionsInstall viaextrasnameInstall viamanifest.yamlCheck the instructions reported in the documentationVirtual environment installationDocker installationArchitecturePluginsActionsBackendsEventsHooksMore complex filtersProceduresCronjobsEntitiesThe web interfaceThe main web panelThe execution panelOther web panelsDashboardsRunning in production modePWA supportMobile appTestsFundingUseful linksRecommended read:Getting started with Platypush.Theblogis a good place to get more insights
and inspiration on what you can build.Thewikialso
contains many resources on getting started.Extensive documentation for all the available integrations and messagesis
available.If you have issues/feature requests/enhancements pleasecreate an
issue.AMatrix instanceis
available if you are looking for interactive support.AReddit channelis available for
general questions.IntroductionPlatypush is a general-purpose extensible platform for automation across
multiple services and devices.It enables users to create their own self-hosted pieces of automation based on
events (if this happens then do that)
and it provides a comprehensive and customizable user interface that collects
everything you need to visualize and control under one roof.It takes some concepts fromIFTTT,Tasker,Microsoft
FlowandHome
Assistantto provide an environment where the
user can easily connect things together.It's built with compatibility and flexibility in mind, and it can easily run on
any device that can run a Python interpreter - from a Raspberry Pi zero, to an
old smartphone, to a beefy server.What it can doYou can use Platypush to do things like:Control your smart home lightsControl your music and synchronize it to multiple devicesCreate custom and privacy-secure voice assistants that run custom hooks on your phrasesBuild integrations betweensensors,cameras,microphonesandmachine learning
modelsto create smart
pieces of automation for e.g.people detectionorsound detectionGet events from your Google or Facebook calendarsRead data from your sensors and trigger custom events whenever they go above or below some custom thresholdsControl and automate a self-built robotDeliver automated newsletters from custom RSS digestsSynchronize the clipboards on your devicesControl your smart switchesImplement automated custom text-to-speech routinesBuild any kind of interactions and automation routines with your Android device using TaskerPlaylocal
videos,
YouTube videos and torrent media from any device and service, to any deviceGet weather forecast events for your location and build automation routines on themCreate a custom single hub for Zigbee and Z-Wave smart devicesBuild your own web dashboard with calendar, weather, news and music controls
(basically, anything that has a Platypush web widget)...and much more (basically, anything that comes with aPlatypush plugin)InstallationSystem installationPlatypush uses Redis to deliver and store requests and temporary messages:# Example for Debian-based distributions[sudo]apt-get install redis-server# Enable and start the service[sudo] systemctl enable redis[sudo] systemctl start redisInstall throughpip[sudo]pip3installplatypushInstall through a system package managerNote: currently only Arch Linux and derived distributions are supported.You can either install theplatypushpackage (for the
latest stable version) or theplatypush-gitpackage
(for the latest git version) through your favourite AUR package manager. For
example, usingyay:yayplatypush# Oryayplatypush-gitThe Arch Linux packages on AUR are automatically updated upon new git commits
or tags.Install from sourcesgitclonehttps://git.platypush.tech/platypush/platypush.gitcdplatypush[sudo]pipinstall.# Or[sudo]python3setup.pyinstallInstalling the dependencies for your extensionsAfter installing the base platform, you may want to check the dependencies and
configuration required by the extensions that you wish to use. There are a few
ways to check the dependencies required by an extension:Install viaextrasnameAll the extensions that require extra dependencies are listed in theextras_requiresection undersetup.py.Install viamanifest.yamlAll the plugins and backends have amanifest.yamlfile in their source folder.
Any extra dependencies are listed thereIf you followed theextrasormanifest.yamlway to discover the
dependencies, then you can install them in two ways:pipinstallation:[sudo]pip3install'platypush[extra1,extra2,extra3]'Sources installation:cd$DIR_TO_PLATYPUSH[sudo]pip3install'.[extra1,extra2,extra3]'Check the instructions reported in the documentationIf you follow this route then simply run the commands listed in theplugin/backend documentationto get the
dependencies installed.After installing the dependencies, create a configuration file under~/.config/platypush/config.yaml(the application can load the configuration
from another location through the-coption) containing the configuration of
the backend and plugins that you want to use, and add any hooks and procedures
for your use case.You can then start the service by simply running:platypushIt's advised to run it as a systemd service though - simply copy the provided.servicefileto~/.config/systemd/user, check if the path ofplatypushmatches the path
where it's installed on your system, and start the service viasystemctl:systemctl--userstartplatypushVirtual environment installationPlatypush provides a script namedplatyvenvthat can parse aconfig.yamland automatically create a virtual environment (under~/.local/share/platypush/venv/<device_id>) with all the dependencies required
by the configured integrations.Create the environment from a configuration file:platyvenvbuild-c/path/to/config.yamlStart the service from the virtual environment:# device_id matches either the hostname or the device_id in config.yamlplatyvenvstartdevice_idStop the instance:platyvenvstopdevice_idRemove the instance:platyvenvrmdevice_idWiki instructionsDocker installationYou can also install Platypush in a container - the application provides a
script namedplatydockthat automatically creates a container instance from aconfig.yaml:Create the container from a configuration file:platydockbuild-c/path/to/config.yamlStart the container:# device_id matches either the hostname or the device_id in config.yamlplatydockstartdevice_idStop the instance:platydockstopdevice_idRemove the instance:platydockrmdevice_idNote that both the virtual environment and Docker container option offer the
possibility to include extra YAML configuration files in the mainconfig.yamlthrough theincludedirective (as long as they are in the same folder as the
mainconfig.yaml), as well as external Python scripts in ascriptsdirectory in the same folder as theconfig.yaml.Wiki instructionsArchitectureThe architecture of Platypush consists of a few simple pieces, orchestrated by
a configuration file stored by default under~/.config/platypush/config.yaml:PluginsFull listPlugins are integrations that do things - likemodify
files,train and evaluate machine learning
models,control
cameras,read
sensors,parse a web
page,control
lights,send
emails,control
Chromecasts,run voice
queries,handle torrent
transfersor controlZigbeeorZ-Wavedevices.The configuration of a plugin matches one-on-one that of its documented class
constructor, so it's very straightforward to write a configuration for a plugin
by reading its documentation:light.hue:# Groups that will be controlled by defaultgroups:-Living Room-HallActionsPlugins exposeactions, that match one-on-one the plugin class methods
denoted by@action, so it's very straightforward to invoke plugin actions by
just reading the plugin documentation. They can be invoked directly from your
own scripts or they can be sent to the platform through any supported channel
as simple JSON messages:{"type":"request","action":"light.hue.on","args":{"lights":["Entrance Bulb"]}}BackendsFull listThey are background services that listen for messages on channels (like
anHTTP
backend, anMQTT
instance, aKafka
instance,Pushbulletetc.).If a backend supports the execution of requests (e.g. HTTP, MQTT, Kafka,
Websocket and TCP) then you can send requests to these services in JSON format.
For example, in the case of the HTTP backend:# Get a tokencurl-XPOST-H'Content-Type: application/json'-d'{"username": "$YOUR_USER","password": "$YOUR_PASSWORD"}'http://host:8008/auth# Execute a requestcurl-XPOST-H'Content-Type: application/json'\-H"Authorization: Bearer$YOUR_TOKEN"-d'{"type": "request","action": "tts.say","args": {"text": "This is a test"}}'http://host:8008/executeEventsFull listWhen a certain event occurs (e.g. a JSON request is received, or aBluetooth
device is
connected,
or aFlic button is
pressed,
or somespeech is detected on the voice assistant
service,
or anRSS feed has new
items,
or anew email is
received,
or anew track is
played,
or anNFC tag is
detected,
ornew sensor data is
available,
ora value of a Zigbee device
changes,
etc.), the associated backend will trigger anevent.HooksEvent hooks are custom pieces of logic that will be run when a certain event is
triggered. Hooks are the glue that connects events to actions, exposing a
paradigm similar to IFTTT (if a certain event happens then run these
actions). They can declared as:Sections of theconfig.yaml.
Example:event.hook.SearchSongVoiceCommand:if:type:platypush.message.event.assistant.SpeechRecognizedEventphrase:"play${title}by${artist}"then:-action:music.mpd.clear-action:music.mpd.searchargs:filter:artist:${artist}title:${title}-if ${len(output)}:-action:music.mpd.playargs:resource:${output[0]['file']}Stand-alone Python scripts stored under~/.config/platypush/scriptsand
will be dynamically imported at start time.Example:fromplatypush.event.hookimporthookfromplatypush.utilsimportrunfromplatypush.message.event.assistantimportSpeechRecognizedEvent@hook(SpeechRecognizedEvent,phrase='play ${title}by ${artist}')defon_music_play_command(event,title=None,artist=None,**context):results=run('music.mpd.search',filter={'artist':artist,'title':title,})ifresults:run('music.mpd.play',results[0]['file'])More complex filtersYour event hooks can include more complex filters too. Structured filters
against partial event arguments are also possible, and relational operators are
supported as well. For example:fromplatypush.event.hookimporthookfromplatypush.message.event.sensorimportSensorDataChangeEvent@hook(SensorDataChangeEvent,data=1):defhook_1(event):"""Triggered when event.data == 1"""@hook(SensorDataChangeEvent,data={'state':1}):defhook_2(event):"""Triggered when event.data['state'] == 1"""@hook(SensorDataChangeEvent,data={'temperature':{'$gt':25},'humidity':{'$le':15}}):defhook_3(event):"""Triggered when event.data['temperature'] > 25 andevent.data['humidity'] <= 15."""The supported relational fields are the same supported by ElasticSearch -$gtfor greater than,$ltfor lesser than,$gefor greater or equal,$nefor
not equal, etc.ProceduresProcedures are pieces of custom logic that can be executed as atomic actions
usingprocedure.<name>as an action name.They can be defined either in theconfig.yamlor as Python scripts stored
under~/.config/platypush/scripts- provided that the procedure is also
imported in~/.config/platypush/scripts/__init__.pyso it can be discovered
by the service.YAML example for a procedure that can be executed when we arrive home and turns
on the lights if the luminosity is lower that a certain thresholds, says a
welcome home message using the TTS engine and starts playing the music:procedure.at_home:# Get luminosity data from a sensor - e.g. LTR559-action:gpio.sensor.ltr559.get_data# If it's lower than a certain threshold, turn on the lights-if ${int(light or 0) < 110}:-action:light.hue.on# Say a welcome home message-action:tts.google.sayargs:text:Welcome home# Play the music-action:music.mpd.playPython example:# Content of ~/.config/platypush/scripts/home.pyfromplatypush.procedureimportprocedurefromplatypush.utilsimportrun@proceduredefat_home(**context):sensor_data=run('gpio.sensor.ltr559.get_data')ifsensor_data['light']<110:run('light.hue.on')run('tts.google.say',text='Welcome home')run('music.mpd.play')In either case, you can easily trigger the at-home procedure by sending an
action request message to a backend - for example, over the HTTP backend:curl-XPOST-H'Content-Type: application/json'\-H"Authorization: Bearer$YOUR_TOKEN"-d'{"type": "request","action": "procedure.at_home"}'http://host:8008/executeCronjobsCronjobs are pieces of logic that will be run at regular intervals, expressed
in crontab-compatible syntax. They can be defined either in theconfig.yamlor as Python scripts stored under~/.config/platypush/scriptsas functions
labelled by the@crondecorator.Note that seconds are also supported (unlike the standard crontab definition),
but, for back-compatibility with the standard crontab format, they are at the
end of the cron expression, so the expression is actually in the format<minute> <hour> <day_of_month> <month> <day_of_week> <second>.YAML example for a cronjob that is executed every 30 seconds and checks if a
Bluetooth device is nearby:cron.check_bt_device:cron_expression:'******/30'actions:-action:bluetooth.lookup_nameargs:addr:XX:XX:XX:XX:XX:XX-if ${name}:-action:procedure.on_device_on-else:-action:procedure.on_device_offPython example:# Content of ~/.config/platypush/scripts/bt_cron.pyfromplatypush.cronimportcronfromplatypush.utilsimportrun@cron('* * * * * */30')defcheck_bt_device(**context):name=run('bluetooth.lookup_name').get('name')ifname:# on_device_on logic hereelse:# on_device_off logic hereEntitiesEntities are a fundamental building block of Platypush. Most of the
integrations will store their state or connected devices in the form of
entities - e.g. the sensors detected by the Z-Wave/Zigbee/Bluetooth
integration, or the lights connected to a Hue bridge, or your cloud nodes, or
your custom Arduino/ESP machinery, and so on.Entities provide a consistent interface to interact with your integrations
regardless of their type and the plugin that handles them. For instance, all
temperature sensors will expose the same interface, regardless if they are
Bluetooth or Zigbee sensors, and all the media plugins will expose the same
interface, regardless if they manage Chromecasts, Kodi, Plex, Jellyfin or a
local VLC player.Once you enable the HTTP backend and a few integrations that export entities
and register a user, you can query the detected entities via:curl-XPOST-H'Content-Type: application/json'\-H"Authorization: Bearer$YOUR_TOKEN"\-d'{"type":"request", "action":"entities.get"}'\http://localhost:8008/executeAll the entities expose the same interface and can be manipulated through the
same API. Also, when an entity is updated it always emits anEntityUpdateEvent,
so you can easily create hooks that react to these events and act on multiple
types of entities.The web interfaceIfbackend.httpis enabled then a web interface will be provided by default onhttp://host:8008/. Besides using the/executeendpoint for running
requests, the built-in web server also provides a full-featured interface that
groups together the controls for most of the plugins - e.g. sensors, switches,
music controls and search, media library and torrent management, lights,
Zigbee/Z-Wave devices and so on. The UI is responsive and mobile-friendly.Some screenshots:The main web panelThis is the default panel available athttp://<host>:<port>after
registration/login. It provides all the entities published by the integrations
under one view, with custom grouping and filtering options.The execution panelThe web interface provides anexecutepanel as well. You can use this panel to
interactively inspect the available integrations and their actions, together
with their documentation and parameters, run requests directly from the web
interface, and inspect the JSON responses.Other web panelsSeveral integrations add their own feature-rich panels to the web view, turning
Platypush into a gateway to all of your services - from Zigbee sensors, to media
players and services, to your music cloud, and more.DashboardsThe web service also provides means for the user to createcustom
dashboardsthat can be used to show information from multiple sources on a large screen.Running in production modeIf you want to access your Platypush web panel outside your home network, it may
be a good idea to use an nginx/Apache reverse proxy with a valid SSL certificate
(e.g. managed by certbot). Asample an nginx
configurationis provided in the repository.PWA supportNote that having the web application served over SSL is a requirement for the
PWA (progressive web app) to work. The Platypush PWA allows you to install a
Platypush native-like client on your mobile devices if you don't want to use the
full Android app.Mobile appAnofficial Android
appis provided on
the F-Droid store. It allows to easily discover and manage multiple Platypush
services on a network through the web interface, and it easily brings the power
of Platypush to your fingertips.TestsTo run the tests simply runpytesteither from the project root folder or thetests/folder.FundingIf you use and love Platypush, please considerbuying me a coffee/beer.I've been working on Platypush all by myself in my spare time for the past few
years, and I've made sure that it remains open and free.If you like this product, please consider supporting - I'm definitely not
planning to get rich with this project, but I'd love to have at least the costs
for the server covered by users.Issues and requests opened by donors will also be given priority over others.