Posts mit dem Label Raspberry Pi werden angezeigt. Alle Posts anzeigen
Posts mit dem Label Raspberry Pi werden angezeigt. Alle Posts anzeigen

Freitag, 24. November 2023

Web-Apps auf RaspberryMatic?

Web-Apps sind Programme, die im Webbrowser des Betrachters laufen. Aber warum sollte man so etwas mit RaspberryMatic einsetzen? Das hat doch schon eine GUI?

Jeder, der bereits ein RaspberryMatic-System aufgesetzt hat, kennt die RaspberryMatic-Weboberfläche. Mit ihr kann man alles einrichten, einstellen und programmieren, was bei einem Homematic-System notwendig ist.

Eines ist sie jedoch nicht: übersichtlich. Jemand, der das System nur oberflächlich kennt, findet sich darin kaum zurecht.

Es liegt also nahe, für solche Benutzer eine angepasste Oberfläche zu programmieren. Diese auf dem Raspberry selbst zu implementieren ist recht schwierig. Bei einer Webanwendung hingegen läuft die Weboberfläche auf dem Rechner des Betrachters, der wahrscheinlich um ein Vielfaches leistungsstärker ist, als ein Raspberry.

Und RaspberryMatic bringt im Prinzip auch alles mit, was man dazu braucht:

  • einen Webserver, über den die App ausgeliefert werden kann
  • mehrere APIs, mit denen Sensoren ausgelesen und Aktoren gesteuert werden können.

Allerdings, im Auslieferungszustand funktioniert diese Idee nicht – und RaspberryMatic trifft dabei nur eine geringe Schuld.

Grund ist ein in allen gängigen Webbrowsern eingebauter Schutzmechanismus: „Same Origin“. Dieser besagt, dass Sachen nur dann ungefragt von einem Webserver nachgeladen werden dürfen, wenn die aufrufende Seite (in diesem Fall die Web-App) auch von dort stammt.

„Same Origin“ bezieht sich hierbei leider nicht nur auf die gleiche Maschine, sondern auch auf den gleichen Port – und der Port, über den die APIs angesprochen werden, ist ein anderer als der HTTP(S)-Port, von dem die Web-App geladen wird.

Wenn die Web-App nun versucht, den API-Port anzusprechen, generiert der Webbrowser, in dem die App läuft, eine Nachfrage auf dem entsprechenden Port, ob der Zugriff gestattet ist: die sog. CORS-Anfrage. Diese versteht RaspberryMatic jedoch nicht und antwortet mit einem Fehler, der vom Webbrowser als ein „Nein“ interpretiert wird. Die Webbrowser blockiert dann die eigentliche API-Kommunikation.

Es gibt mehrere Möglichkeiten, dies zu beheben. Dieser Post beschreibt, wie man diesen Zustand „minimal-invasiv“ ändern kann.

Die hier beschriebene Lösung ermöglicht die API-Abfrage über den normalen HTTPS-Port und besteht aus einigen wenigen zusätzlichen Zeilen in einer Konfigurationsdatei. Damit wird die API-Abfrage wirklich „Same Origin“, die CORS-Anfrage entfällt und RaspberryMatic kann über eine Web-App gesteuert werden.

Hinweis: Die APIs sind eigentlich für „normale“ Programme (Skripts oder ausführbare Anwendungen) auf anderen Rechnern gedacht. Diese kennen den „Same Origin“-Schutz nicht und machen deshalb auch keine CORS-Anfrage.

Auswahl der API

RaspberryMatic kennt zwei APIs: die XML-API und die Homematic-Script-API.

Die XML-API verwendet zur Abfrage von Sensoren und Steuern von Aktoren – wie der Name schon vermuten lässt – XML-Snippets. Der Grund weshalb ich sie in diesem Beispiel nicht verwende ist, dass die XML-API keinen Zugriff auf die bei der Homematic-Programmierung häufig verwendeten Systemvariablen bietet.

Die Homematic-Script-API hingegen erlaubt das Ausführen beliebiger kleiner Homematic-Scripts. Diese Skripts können dann Sensoren abfragen, Aktoren steuern aber eben auch Systemvariablen lesen und schreiben.

Der Zugriff auf die Homematic-Script-API muss in der RaspberryMatic-Firewall freigegeben werden (Einstellungen > Systemsteuerung > Firewall konfigurieren) - siehe nebenstehendes Bild.

Firmware ändern

Um die Firmware eines RaspberryMatic zu ändern, muss man sie zunächst entsperren, d.h. editierbar machen. Hierzu muss der SSH-Zugang im RaspberryMatic freigegeben sein (Einstellungen > Systemsteuerung > Sicherheit > SSH).

Dann kann man sich per SSH als Anwender eingeloggen und hat Root-Rechte. Das Entsperren der Firmware erfolgt dann mit dem Befehl:

mount -o rw,remount /

Nach dem Entsperren kann die Konfigurationsdatei lighttpd.conf des Web-Servers mit dem auf dem System installierten Editor vi editieren werden:

vi /etc/lighttpd/lighttpd.conf

Hängen Sie unten den folgenden Text am Ende der Datei an (Hinweis: Aufrufen des Einfügemodus bei vi erfolgt mit der Taste „i“):

$HTTP["url"] == "/regex.exe" {
  $HTTP["request-method"] == "POST" {
        url.access-allow = ("")
        proxy.server = (
            "" => (
                "localhost" => (
                    "host" => "127.0.0.1",
                    "port" => 8183,
                ),
            ),
        )
   }
}


Speichern Sie die Änderungen… (vi verwendet hierzu ESC : w q)

„Sperren“ Sie die Firmware wieder gegen Änderungen:

mount -o ro,remount /

Stoppen und starten Sie den Webserver

/etc/init.d/S50lighttpd stop
/etc/init.d/S50lighttpd start


oder starten Sie im Zweifelsfall das System über die normale WebUI neu (Einstellungen > Systemsteuerung > Zentralenwartung > RaspberryMatic-Neustart).

Der Zugriff auf die Script-API ist nun auch über den normalen Webport mit einem POST-Befehl an die URL

/regex.exe


möglich.

Beschreibung der Änderung

Bei der Untersuchung des Problems hat sich herausgestellt, dass der RaspberryMatic-Webserver lighttpd auch für die Kommunikation der API-Ports zuständig ist und diese Befehle einfach an einen weiteren internen Port (in diesem Fall 8183) weiterleitet. Und genau das ermöglicht diese Änderung auch für den Zugriff über den normalen Webport.

Persistenz

Diese Änderung übersteht einen Neustart des Systems.

Hingegen überschreibt eine Neuinstallation der Firmware oder das gelegentliche RaspberryMatic Firmware-Update auch Konfigurationsdateien und damit diese Änderung. Nach einem solchen recht seltenen Ereignis muss die Änderung in der Konfigurationsdatei, wie oben beschrieben, erneut vorgenommen werden.

Sicherheitsaspekte

Beim Satz „erlaubt die Ausführung beliebiger Scripts“ sollten eigentlich die Alarmglocken klingeln. Um das Risiko zu minimieren, sollte der Zugriff auf die Homematic-Script-API nur verschlüsselt (HTTPS) und nur passwortgeschützt erfolgen.
Benutzer mit einem gültigen Passwort können jedoch beliebige Scripts auch über die normale RaspberryMatic-Weboberfläche ausführen, d.h. das Risiko ändert sich durch die Web-App also nicht.

Über „Systemsteuerung > Einstellungen > Firewall konfigurieren“ kann man, wie oben gezeigt, den Zugriff auf das lokale Netzwerk (192.168.0.*) einschränken.

Wenn solche Systeme hinter einem Internetrouter laufen und nur aus dem lokalen Netzwerk von einem autorisierten Benutzer angesprochen werden können, ist das Risiko also überschaubar.

Diese Konfigurationsänderung wurde mit den folgenden RaspberryMatic-Firmwareversionen getestet: 3.65.11.20221005 und 3.71.12.20230826.

Weitere Links zum Thema





Mittwoch, 15. Februar 2017

Playing HLS streams with mpd

If you're playing with the idea to turn your Raspberry Pi into an internet radio you will sooner or later come across the MusicPlayerDaemon (mpd).  It's a server daemon without an user interface with the sole objective to play music and manage playlists.  It exposes however a control port over which command line utilities, apps on mobile phones, or even desktop applications can talk to it using a common “command language”.  This way they can make mpd create playlists which can be stored on the server, play songs from a playlist, stop the playback, skip titles etc.

Even though the content usually resides on your hard disc mpd can fetch it from other devices, e.g. a NAS on your LAN, or even from (web radio stations on) the internet.  The list of your favourite stations boils down to a simple playlist containing their urls, switching stations is the same as skipping to the next song in the playlist of your favourite artists.

Most stations use MP3 or AAC streams which are easily handled by the version of mpd available in the repository of your Linux distribution, even though that version might be a little dated.

HLS streams - as deployed by the BBC for example - are a little trickier.  In order to get to the music various playlists have to be downloaded and parsed, and every 10 seconds or so, the next chunk has to be downloaded from another url.  ffmpeg (or its fork avconv) can handle this overhead but even though ffmpeg is compiled into most version of mpd installed from repositories, trying to open an HLS stream will not work.

The current (Feb. 2017) repository version of mpd is 0.19.1.  You can check the decoder plugins:

$ ./mpd --version
Music Player Daemon 0.19.1
...
Decoders plugins:
...
[ffmpeg] 16sv 3g2 3gp 4xm …


The solution to remedy this situation is already in the source code – perhaps a little hidden. You will have to compile mpd as described below.

However, I did install the version from the repository first. It comes with some system integration like start and stop scripts for the boot process, setting up of an mpd user account on the Raspberry, etc. I've modified the scripts in a few places to point them to the freshly compiled mpd version.

As we have to compile it anyway, let's us the newest version from the mpc homepage.

(The following steps have been tested with mpc 0.20.4 on a Raspberry Pi 3.
In the description below change the version number accordingly.)

Start by installing the required libraries:

sudo apt-get install g++ \
  libmad0-dev libmpg123-dev libid3tag0-dev \
  libflac-dev libvorbis-dev libopus-dev \
  libadplug-dev libaudiofile-dev libsndfile1-dev libfaad-dev \
  libfluidsynth-dev libgme-dev libmikmod2-dev libmodplug-dev \
  libmpcdec-dev libwavpack-dev libwildmidi-dev \
  libsidplay2-dev libsidutils-dev libresid-builder-dev \
  libavcodec-dev libavformat-dev \
  libmp3lame-dev \
  libsamplerate0-dev libsoxr-dev \
  libbz2-dev libcdio-paranoia-dev libiso9660-dev libmms-dev \
  libzzip-dev \
  libcurl4-gnutls-dev libyajl-dev libexpat-dev \
  libasound2-dev libao-dev libjack-jackd2-dev libopenal-dev \
  libpulse-dev libroar-dev libshout3-dev \
  libmpdclient-dev \
  libnfs-dev libsmbclient-dev \
  libupnp-dev \
  libavahi-client-dev \
  libsqlite3-dev \
  libsystemd-daemon-dev libwrap0-dev \
  libcppunit-dev xmlto \
  libboost-dev \
  libicu-dev


Download the source code:

wget https://www.musicpd.org/download/mpd/0.20/mpd-0.20.4.tar.xz

You might want to check the GPG signature:

wget https://www.musicpd.org/download/mpd/0.20/mpd-0.20.4.tar.xz.sig
gpg --verify mpd-0.20.4.tar.xz.sig


Unpack the archive:

tar xvfJ mpd-0.20.4.tar.xz
cd mpd-0.20.4
./configure


Now to the special magic. The ./configure utility has scanned the system environment and has written its findings into configure.h. Open that file with an editor. You should be able to find the following line:

#define ENABLE_FFMPEG 1

This means that the ffmpeg libraries have been detected and will be used.
Now add the following line and save the file:

#define HAVE_FFMPEG 1

This line will change the fallback decoder in src/decoder/DecoderThread.cxx from “mad” to “ffmpeg”. ffmpeg can handle m3u8 playlists typically used by HLS while mad can not.

Now start the build process with

make

and if there are no errors install mpd:

sudo make install


On the Raspberry this new version is stored in /usr/local/bin while the original version still remains in /usr/bin.

Confirm the version of the new file:

$ /usr/local/bin/mpd --version
Music Player Daemon 0.20.4


Additional changes

The following changes of the initial mpd install are necessary to get the new version running on the Raspberry Pi.

Raspberry uses systemd.  There is a control file for the mpd service that needs to be changed:

sudo nano /lib/systemd/system/mpd.service

change:
ExecStart=/usr/bin/mpd --no-daemon $MPDCONF
to the new location:
ExecStart=/usr/local/bin/mpd --no-daemon $MPDCONF

Keep in mind that this change might be overwritten if the repository version of mpd is being updated later on... which doesn't happen that often.

Uncomment the following line in /etc/default/mpd. This will define the variable MPDCONF.

MPDCONF=/etc/mpd.conf


Let us change some settings in mpd configuration file /etc/mpd.conf

sudo nano /etc/mpd.conf

In the default configuration mpd and its client must run on the same machine. In order to allow access via the network change:

bind_to_address         "localhost"
to
bind_to_address         "any"

For convenience I've changed my music_directory to a place where I can more easily add music files. Keep in mind that his folder needs to be world readable so that mpd running as user “mpd” can access it.

music_directory         "/home/pi/Music"

Now we have to tell the system to read the new configuration and restart the mpd service.

sudo systemctl daemon-reload
sudo service mpd restart


Check the status of the service:

sudo service mpd status

Unrelated problem

In my first attempts mpd froze after playing the first title.  Someone suggested to remove pulseaudio... and it worked.

sudo apt-get remove pulseaudio
sudo reboot


Links

  • https://www.musicpd.org/doc/user/install_source.html
  • https://www.musicpd.org/download.html
  • https://www.digitalocean.com/community/tutorials/how-to-use-systemctl-to-manage-systemd-services-and-units

Mittwoch, 25. Februar 2015

TP-LINK TL-WN725N v2 working on Raspberry Pi (Raspbian)

A few days back I got my first Raspberry Pi. To make things easier, I bought a starter pack which contained – among others – a small Wifi adapter TL-WM725N from TP-Link.

As it turned out, this USB device does not work out-of-the-box with the current version of Raspbian. According to the sources listed below, the TL-WM725N once did work without problems with the Raspberry Pi until the new and shiny version 2 of the TL-WM725N was released. It seems that this fact slipped by the vendor of this starter pack.

The USB ID of this particular Wifi adapter is: 0bda:8179

The current version (Feb. 2015) of the kernel, as returned by uname -a is:
Linux raspberrypi 3.18.7+ #758 PREEMPT Mon Feb 23 19:27:03 GMT 2015 armv6l GNU/Linux

dmesg showed this message:

[   23.690020] r8188eu 1-1.4:1.0: Direct firmware load for rtlwifi/rtl8188eufw.bin failed with error -2
[   23.690072] r8188eu 1-1.4:1.0: Firmware rtlwifi/rtl8188eufw.bin not available


The most helpful posting on this topic was this one. It contains a link to a ZIP file and instructions to install it.

The ZIP files contains firmware for the Wifi adapter and a kernel module.

Contrary to the claims of the author of the blog post, the firmware was missing in my version of Raspbian. On the other hand the kernel module is not needed. This is a good thing because kernel modules depend on a specific kernel version and the one in the ZIP file is outdated and must not be installed. It would delete the existing module which is complaining about the missing firmware.

Which means, I only had to copy the firmware (rtl8188eufw.bin):

wget https://dl.dropboxusercontent.com/u/80256631/8188eu-20140307.tar.gz
tar -zxvf 8188eu-20140307.tar.gz
sudo cp rtl8188eufw.bin /lib/firmware/rtlwifi
sudo reboot


The dropbox link may vanish any time. A better solution would be appreciated.

As an alternative that should run out of the box, this blog post suggests the EDIMAX EW-7811U.


Links
  • http://laurenthinoul.com/how-to-install-tp-link-tl-wn725n-on-raspberry-pi/
  • http://www.mendrugox.net/2013/08/tp-link-tl-wn725n-v2-working-on-raspberry-raspbian/
  • http://blog.pi3g.com/2013/05/tp-link-150mbps-wireless-n-nano-usb-adapter-tl-wn725n-und-raspberry-pi/ (german)
  • http://www.amazingcode.de/tp-link-tl-wn725n-auf-raspbian/ (german)