mardi 22 septembre 2020

 MPD et les streams Radio France

J'utilise MPD sur un raspberry conjointement avec l'interface web mympd.
J'écoute principalement des streams de Radio France en haute qualité (AAC 192 kbs) et depuis quelques semaines et le matin seulement je constate des coupures du son voir l'abandon par MPD du stream qui passe au suivant de la playlist.

J'ai corrigé ce problème en remplacent le plugin d'entrée curl par ffmpeg
J'ai modifier le plugin d'entrée:
input {
        plugin "ffmpeg"
}
 
#input {
#        plugin "curl"
#}
... et ça ne résou rien :(
 
J'ai regardé les paquets TCP échangés. 
J'ai remarqué que le dns renvoyé plusieurs adresses IP pour le serveur radiofrance:
Première essai de connexion: 
Domain Name System (response)
Transaction ID: 0xbeed
Flags: 0x8180 Standard query response, No error
Questions: 1
Answer RRs: 7
Authority RRs: 0
Additional RRs: 0
Queries
Answers
icecast.radiofrance.fr: type CNAME, class IN, cname icecasta.prods1public.radiofrance.fr
icecasta.prods1public.radiofrance.fr: type A, class IN, addr 163.172.182.190
icecasta.prods1public.radiofrance.fr: type A, class IN, addr 51.158.65.164
icecasta.prods1public.radiofrance.fr: type A, class IN, addr 212.47.251.152
icecasta.prods1public.radiofrance.fr: type A, class IN, addr 51.158.117.244
icecasta.prods1public.radiofrance.fr: type A, class IN, addr 51.158.104.58
icecasta.prods1public.radiofrance.fr: type A, class IN, addr 163.172.145.72
[Request In: 1]
[Time: 0.027922000 seconds]

le player utilise la dernière proposée:
-> icecasta.prods1public.radiofrance.fr: type A, class IN, addr 163.172.145.72

Deuxième essai de connexion:
Domain Name System (response)
Transaction ID: 0x101d
Flags: 0x8180 Standard query response, No error
Questions: 1
Answer RRs: 7
Authority RRs: 0
Additional RRs: 0
Queries
Answers
icecast.radiofrance.fr: type CNAME, class IN, cname icecasta.prods1public.radiofrance.fr
icecasta.prods1public.radiofrance.fr: type A, class IN, addr 163.172.182.190
icecasta.prods1public.radiofrance.fr: type A, class IN, addr 51.158.117.244
icecasta.prods1public.radiofrance.fr: type A, class IN, addr 51.158.104.58
icecasta.prods1public.radiofrance.fr: type A, class IN, addr 163.172.145.72
icecasta.prods1public.radiofrance.fr: type A, class IN, addr 51.158.65.164
icecasta.prods1public.radiofrance.fr: type A, class IN, addr 212.47.251.152
[Request In: 1]
[Time: 0.026924000 seconds]


le player utilise la dernière proposée:
 -> icecasta.prods1public.radiofrance.fr: type A, class IN, addr 212.47.251.152 
 
Je pense que le player web du site radiofrance "jongle" avec ces adresses pour utiliser le serveur le plus disponible au lieu de prendre le dernier..
Un coup d'oeil sur les paquets échangés lors de l'utilisation du player web, montre des échanges bien plus complexes.
Le player fini par utiliser 2.21.132.169 comme serveur de stream, soit : a2-21-132-169.deploy.static.akamaitechnologies.com  ...
 

 


 

jeudi 10 septembre 2020

Music Player Daemon build on Raspberry Pi

Build MPD from sources on Raspberry Pi 

Original post here:

Get the sources:

git clone https://github.com/MusicPlayerDaemon/MPD.git 
cd MPD 

Get all necessary dependencies

sudo apt-get install g++ \
  libpcre3-dev \
  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 libtwolame-dev libshine-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 libshout3-dev \
  libsndio-dev \
  libmpdclient-dev \
  libnfs-dev libsmbclient-dev \
  libupnp-dev \
  libavahi-client-dev \
  libsqlite3-dev \
  libsystemd-dev libwrap0-dev \
  libgtest-dev \
  libboost-dev \
  libicu-dev \
  libgcrypt-dev \
  libsidplayfp-dev

Install messon and ninja tools:

sudo apt-get install python3 python3-pip ninja-build
sudo pip3 install meson 

Stop mpd service:

sudo service mpd stop 

Compile mpd:

meson . output/release --buildtype=debugoptimized -Db_ndebug=true
meson configure output/release
ninja -C output/release
sudo ninja -C output/release install  
  • mpd is in ./output/release
  • service files are ./output/release/systemd
  • use the mpdconf.example in ./doc for configuration

Workarrounds and errors:

mpd binary is located in /usr/local/bin and this mpd binary try to open mpd.conf located in /usr/local/etc NOT in usual folder /etc

So, you have to link these file and folder:

sudo mv /usr/bin/mpd /usr/bin/mpd_old
sudo ln -s /usr/local/bin/mpd /usr/bin/mpd

Check if folder /usr/local/etc already exists:

ls /usr/local

If an etc folder exists, rename it to etc_bak

sudo mv /usr/local/etc /usr/local/etc_old

Link etc folder:

sudo ln -s /etc /usr/local

move old etc files to linked folder:

sudo mv /usr/local/etc_old/* /usr/local/etc

dimanche 12 janvier 2020

Repairing Domoticz database...

Some error appearing in domoticz log concerning VACUUM:

2020-01-12 15:00:01.363 Error: SQL Query("VACUUM") : database disk image is malformed

First, stop domoticz:

$ sudo service domoticz.sh stop

Backup the database:

$ cp ./domoticz/domoticz.db ./domoticz/domoticz.db.bak

Method 1

$ sqlite3 ./domoticz/domoticz.db
sqlite> .output domo.sql 
sqlite> .dump
sqlite> .quit

Download domo.sql to your Windows PC,

Try to import domo.sql in Sqlite Browser ( https://sqlitebrowser.org/ ) ,
Note error messages if exists and cleanup manualy ( notepad++ ) domo.sql (duplicate inserts, etc...) until importation success.

When sql is successfully imported, save to "domoticz.db"
Upload to domoticz machine, 

$ rm ./domoticz/domoticz.db
$ cp ./domoticz.db ./domoticz/domoticz.db
$ sudo service domoticz.sh start

If no success then :
$ rm ./domoticz/domoticz.db
$ cp ./domoticz/domoticz.db.bak ./domoticz/domoticz.db

Method 2 (not worked for me)

Open database with sqlite3:

$ sqlite3 ./domoticz/domoticz.db

Check integrity:

sqlite> PRAGMA integrity_check;
*** in database main ***
On tree page 138 cell 50: Rowid 2287 out of order
row 252 missing from index ds_hduts_idx
wrong # of entries in index ds_hduts_idx
...

First reindex DeviceStatus:

sqlite> reindex ds_hduts_idx;

Check integrity again:

sqlite> PRAGMA integrity_check;
*** in database main ***
On tree page 138 cell 50: Rowid 2287 out of order

... Error: database disk image is malformed

Build a clean copy of database:

sqlite> .clone domoticz-clone.sqlite

DeviceStatus... done
LightingLog... done
SceneLog... done
Preferences... done
Rain... done
Rain_Calendar... done
Temperature... done
Temperature_Calendar... done
Timers... done
SetpointTimers... done
UV... done
UV_Calendar... done
Wind... done
Wind_Calendar... done
Meter... done
Meter_Calendar... done
MultiMeter... done
MultiMeter_Calendar... done
Notifications... done
Hardware... done
Users... done
LightSubDevices... done
Cameras... done
CamerasActiveDevices... done
DeviceToPlansMap... done
Plans... done
Scenes... done
SceneDevices... done
TimerPlans... done
SceneTimers... done
SharedDevices... done
EventMaster... done
EventRules... done
ZWaveNodes... done
WOLNodes... done
Percentage... done
Percentage_Calendar... done
Fan... done
Fan_Calendar... done
BackupLog... done
EnoceanSensors... done
FibaroLink... done
HttpLink... done
PushLink... done
GooglePubSubLink... done
UserVariables... done
Floorplans... done
CustomImages... done
MySensors... done
MySensorsVars... done
MySensorsChilds... done
ToonDevices... done
UserSessions... done
MobileDevices... done
sqlite_stat1... Error: object name reserved for internal use: sqlite_stat1
SQL: [CREATE TABLE sqlite_stat1(tbl,idx,stat)]
Error 1: no such table: sqlite_stat1 on [SELECT * FROM "sqlite_stat1"]
done
sqlite_autoindex_UserSessions_1... done
sqlite_autoindex_UserSessions_2... done
ds_hduts_idx... done
f_id_idx... done
f_id_date_idx... done
fc_id_idx... done
fc_id_date_idx... done
ll_id_idx... done
ll_id_date_idx... done
sl_id_idx... done
sl_id_date_idx... done
m_id_idx... done
m_id_date_idx... done
mc_id_idx... done
mc_id_date_idx... done
mm_id_idx... done
mm_id_date_idx... done
mmc_id_idx... done
mmc_id_date_idx... done
p_id_idx... done
p_id_date_idx... done
pc_id_idx... done
pc_id_date_idx... done
r_id_idx... done
r_id_date_idx... done
rc_id_idx... done
rc_id_date_idx... done
t_id_idx... done
t_id_date_idx... done
tc_id_idx... done
tc_id_date_idx... done
u_id_idx... done
u_id_date_idx... done
uv_id_idx... done
uv_id_date_idx... done
w_id_idx... done
w_id_date_idx... done
wc_id_idx... done
wc_id_date_idx... done
devicestatusupdate... done
deviceplantatusupdate... done
planordertrigger... done
scenesupdate... done
scenedevicesupdate... done
floorplanordertrigger... done
...
sqlite> PRAGMA user_version;
0  <----- TAKE NOTE OF THIS VALUE it may be different for you
sqlite> .exit

Open the database copy and correct:

$ sqlite3 domoticz-clone.sqlite
sqlite> PRAGMA integrity_check;
ok
sqlite> PRAGMA user_version = 0;  -- use the number you got from PRAGMA user_version; above
sqlite> PRAGMA journal_mode = truncate;
truncate
sqlite> PRAGMA page_size = 32768;
sqlite> VACUUM;
sqlite> PRAGMA journal_mode = wal;
wal
sqlite> .exit

Copy new cleaned database on domoticz database:

$ mv domoticz-clone.sqlite ./domoticz/domoticz.db

Finally start domoticz service:

$ sudo service domoticz.sh start

You can now check domoticz log with web ui...

dimanche 22 décembre 2019

cron.minutely, cron.daily, etc...

L'utilisation de cron.daily ou autre pour programmer des tâches à exécuter n'est pas trivial:

Il faut placer le scripte SANS EXTENSION dans le dossier concerné et son nom ne doit comporter que des lettres, chiffres, signe - ou _

Genre : "monScript"

Il faut lui donner le droit d'exécution : sudo chmod +x monScript

Pour savoir si le scripte sera prit en compte on exécute la commande :

sudo run-parts --test /etc/cron.daily/

Le scripte doit apparaitre dans la liste : 

/etc/cron.daily/apt-compat
/etc/cron.daily/apt-show-versions
/etc/cron.daily/dietpi
/etc/cron.daily/dpkg
/etc/cron.daily/lighttpd

/etc/cron.daily/monScript
/etc/cron.daily/passwd

Avec Dietpi, un utilitaire permet de définir précisément quand la tâche sera lancée, par exemple à la troisième seconde de chaque minute pour minutely, ou à 1h23 pour daily



vendredi 20 décembre 2019

domoticz letsencrypt certbot auto renew

Install certificat :

cd ~
mkdir certbot
cd certbot/
wget https://dl.eff.org/certbot-auto
sudo chown root ./certbot-auto
sudo chmod 0755 ./certbot-auto
sudo ./certbot-auto certonly --standalone -d w4v3.com
lsa ~/domoticz/
sudo rm ~/domoticz/server_cert.pem
sudo cat /etc/letsencrypt/live/YOURDOMAIN.COM/privkey.pem >> ~/domoticz/server_cert.pem
sudo cat /etc/letsencrypt/live/YOURDOMAIN.COM/fullchain.pem >> ~/domoticz/server_cert.pem
sudo cp ~/domoticz/server_cert.pem ~/domoticz/domo_server_cert.pem
cd ..
cd domoticz/
sudo /etc/init.d/domoticz.sh restart


Wait 20s then check your server status using a browser : https://www.digicert.com/help/

Auto renew now :

cd ..
cd certbot/
nano cert-domoticz-update.sh

#!/bin/bash
/home/pi/certbot/certbot-auto renew
rm /home/pi/domoticz/server_cert.pem
rm /home/pi/domoticz/domo_server_cert.pem
cat /etc/letsencrypt/live/YOURDOMAIN.COM/privkey.pem >> /home/pi/domoticz/domo_server_cert.pem
cat /etc/letsencrypt/live/YOURDOMAIN.COM/fullchain.pem >> /home/pi/domoticz/domo_server_cert.pem
cp /home/pi/domoticz/domo_server_cert.pem /home/pi/domoticz/server_cert.pem
/etc/init.d/domoticz.sh restart


I use dietpi so home is /home/dietpi instead of /home/pi

Use Cron to renew certificat every day :

sudo chown root certDomoticzUpdate.sh
sudo chmod 0755 certDomoticzUpdate.sh


Place the script without extension in /etc/cron.daily

sudo cp /home/pi/certDomoticzUpdate.sh /etc/cron.daily/certDomoticzUpdate

Then verify cron status:

sudo run-parts --test /etc/cron.daily/


Scripte must appears in list


/etc/cron.daily/apt-compat
/etc/cron.daily/apt-show-versions
/etc/cron.daily/dietpi
/etc/cron.daily/dpkg
/etc/cron.daily/lighttpd
/etc/cron.daily/certDomoticzUpdate
/etc/cron.daily/passwd

mardi 3 décembre 2019

myMPD une branche de ympd le client web léger pour music player deamon

myMPD : https://github.com/jcorporation/myMPD

Pré-requis:

sudo apt update
sudo apt upgrade
sudo apt install mediainfo
sudo apt install libmpdclient-dev

Téléchragement des sources:

git clone https://github.com/jcorporation/myMPD.git

Construction du binaire:

cd myMPD/
sudo ./build.sh releaseinstall

Edition du fichier de configuration:

sudo nano /etc/mympd.conf

Essais:

sudo service mympd start
sudo service mympd stop

Ajustement du fichier de configuration:

sudo nano /etc/mympd.conf

Installation du service au démarrage:

sudo systemctl enable mympd

Démarrage manuel:

sudo service mympd start

samedi 12 octobre 2019

Un serveur de marée (?)

Un ingénieux développeur ( https://github.com/joelkoz ) a mis en ligne le code d'un serveur web de données json et graphique de marées basé sur le célèbre xtide, fameux et historique logiciel de calcul des marées : https://github.com/joelkoz/xtwsd

Ce serveur web renvoi des horaires de marée, des graphes et autres coefficients harmoniques

Ma seule contribution est cette méthode de mise en œuvre ainsi que l'ajout des coefficients harmoniques pour Arcachon, mais attention les résultats pour ce port sont expérimentaux et d'ailleurs incorrect, à peaufiner donc.

Si vous disposez de meilleurs coefficients harmoniques pour Arcachon et autres, je suis preneur !

Installation : 

La quincaillerie:
pi@dietpi:~/wtide$ sudo apt install git cmake gcc g++ bzip2 ragel libpng-dev libssl-dev
..
..
..

La librairie boost:
pi@dietpi:~/wtide$ wget https://dl.bintray.com/boostorg/release/1.71.0/source/boost_1_71_0.tar.bz2
pi@dietpi:~/wtide$ tar --bzip2 -xf boost_1_71_0.tar.bz2
pi@dietpi:~/wtide$ cd boost_1_71_0
pi@dietpi:~/wtide/boost_1_71_0$ ./bootstrap.sh -with-libraries=system
pi@dietpi:~/wtide/boost_1_71_0$ sudo ./b2 install
..
..
...updated 15188 targets...


La librairie TCD:
pi@dietpi:~/wtide/boost_1_71_0$ cd ..
pi@dietpi:~/wtide$ wget https://flaterco.com/files/xtide/libtcd-2.2.7-r2.tar.bz2
pi@dietpi:~/wtide$ tar --bzip2 -xf libtcd-2.2.7-r2.tar.bz2
pi@dietpi:~/wtide$ cd libtcd-2.2.7
pi@dietpi:~/wtide/libtcd-2.2.7$ ./configure
pi@dietpi:~/wtide/libtcd-2.2.7$ make
pi@dietpi:~/wtide/libtcd-2.2.7$ sudo make install
pi@dietpi:~/wtide/libtcd-2.2.7$ cd ..

Le serveur:
pi@dietpi:~/wtide$ git clone --recursive https://github.com/joelkoz/xtwsd.git
pi@dietpi:~/wtide$ mkdir xtwsd/build
pi@dietpi:~/wtide$ cd xtwsd/build
pi@dietpi:~/wtide/xtwsd/build$ cmake -Wno-dev ..
pi@dietpi:~/wtide$ cd xtwsd/
pi@dietpi:~/wtide/xtwsd$ ls
pi@dietpi:~/wtide/xtwsd$ cd build
pi@dietpi:~/wtide/xtwsd/build$ make
..
..
..
zzzzzz..rrr
..
pi@dietpi:~/wtide/xtwsd/build$ sudo make install

Le fichier d'harmoniques:
pi@dietpi:~/wtide/xtwsd/build$ cd /usr/local/share/
pi@dietpi:/usr/local/share$ sudo mkdir xtide
pi@dietpi:/usr/local/share$ cd xtide
pi@dietpi:/usr/local/share/xtide$ sudo wget https://flaterco.com/files/xtide/harmonics-dwf-20190620-free.tar.bz2
pi@dietpi:/usr/local/share/xtide$ sudo tar --bzip2 -xf harmonics-dwf-20190620-free.tar.bz2
pi@dietpi:/usr/local/share/xtide$ sudo rm harmonics-dwf-20190620-free.tar.bz2
pi@dietpi:/usr/local/share/xtide$ sudo cp harmonics-dwf-20190620/harmonics-dwf-20190620-free.tcd harmonics.tcd
pi@dietpi:/usr/local/share/xtide$ sudo rm -R harmonics-dwf-20190620/
pi@dietpi:/usr/local/share/xtide$ export HFILE_PATH=/usr/local/share/xtide/harmonics.tcd
pi@dietpi:~/wtide/xtwsd/build$ sudo nano /etc/xtide.conf

    /usr/local/share/xtide/harmonics.tcd
   

Test #1:
pi@dietpi:/usr/local/share/xtide$ cd /home/pi/xtwsd/build
pi@dietpi:~/wtide/xtwsd/build$ sudo ./xtwsd 800
xtwsd v0.2
Starting web service on port 800
^C

Test #2 dans un screen:
pi@dietpi:~/wtide/xtwsd/build$ screen -S server
pi@dietpi:~/wtide/xtwsd/build$ sudo ./xtwsd 800

^a d


Ajoutons les ports des Caraïbes:

pi@dietpi:~/wtide/xtwsd/build$ ./nos2xt -f ../src/util/caribbean.txt -p 800

Building context map...Indexing /usr/local/share/xtide/harmonics.tcd...
Done.
Building context map...Done.
..
..
..
Building context map...Done.

Ajoutons Arcachon Eyrac (au hazard)
pi@dietpi:~/wtide/xtwsd/build$ nano eyrac-full.json


{
"comments": "",
"country": "France",
"harmonics": {
"confidence": 10,
"constituents": [
{
"name": "M2",
"amp": 1.339,
"epoch": 147.0
},
{
"name": "S2",
"amp": 0.443,
"epoch": 188.0
},
{
"name": "N2",
"amp": 0.261,
"epoch": 130.0
},
{
"name": "K1",
"amp": 0.045,
"epoch": 100.0
},
{
"name": "O1",
"amp": 0.069,
"epoch": 350.0
},
{
"name": "NU2",
"amp": 0.0492,
"epoch": 130.0
},
{
"name": "MU2",
"amp": 0.0414,
"epoch": 130.0
},
{
"name": "2N2",
"amp": 0.0343,
"epoch": 130.0
},
{
"name": "OO1",
"amp": 0.003,
"epoch": 100
},
{
"name": "LAM2",
"amp": 0.0094,
"epoch": 188
},
{
"name": "M1",
"amp": 0.0049,
"epoch": 100.0
},
{
"name": "J1",
"amp": 0.0055,
"epoch": 100.0
},
{
"name": "MM",
"amp": 0.0,
"epoch": 0.0
},
{
"name": "SSA",
"amp": 0.0,
"epoch": 0.0
},
{
"name": "SA",
"amp": 0.011,
"epoch": 182.0
},
{
"name": "MF",
"amp": 0.0,
"epoch": 0.0
},
{
"name": "RHO",
"amp": 0.0026,
"epoch": 100.0
},
{
"name": "Q1",
"amp": 0.0150,
"epoch": 304.0
},
{
"name": "T2",
"amp": 0.0261,
"epoch": 188
},
{
"name": "R2",
"amp": 0.0035,
"epoch": 188.00
},
{
"name": "2Q1",
"amp": 0.0018,
"epoch": 100
},
{
"name": "P1",
"amp": 0.015,
"epoch": 100.0
},
{
"name": "L2",
"amp": 0.0383,
"epoch": 147
},
{
"name": "K2",
"amp": 0.1197,
"epoch": 188
},
{
"name": "M3",
"amp": 0.0,
"epoch": 0
},
{
"name": "M4",
"amp": 0.091,
"epoch": 93
},
{
"name": "M6",
"amp": 0.0,
"epoch": 0
},
{
"name": "M8",
"amp": 0.0,
"epoch": 0
},
{
"name": "S1",
"amp": 0.0,
"epoch": 0
},
{
"name": "S4",
"amp": 0.0,
"epoch": 0
},
{
"name": "S6",
"amp": 0.0,
"epoch": 0
},
{
"name": "MK3",
"amp": 0.0,
"epoch": 0
},
{
"name": "2MK3",
"amp": 0.0,
"epoch": 0
},
{
"name": "MN4",
"amp": 0.028,
"epoch": 72.0
},
{
"name": "2SM2",
"amp": 0.0,
"epoch": 0
},
{
"name": "MSF",
"amp": 0.0,
"epoch": 0
},
{
"name": "MS4",
"amp": 0.0500,
"epoch": 159
}
],
"datum": "Mean Lower Low Water",
"datumOffset": 0,
"zoneOffset": 0
},
"levelUnits": "meters",
"name": "Arcachon Eyrac",
"notes": "",
"position": {
"lat": 44.665076,
"long": -1.163666
},
"referenceStation": true,
"source": {
"context": "SHOM",
"name": "xtwsd",
"stationId": "1"
},
"timezone": ":Europe/Paris",
"type": "tide"
}

pi@dietpi:~/wtide/xtwsd/build$ curl -vX POST http://127.0.0.1:800/harmonics -d @eyrac-full.json --header "Content-Type: application/json"

Test #3:
On récupère la marée(?) pour Arcachon:
Dans un navigateur:
http://192.168.1.3:800/location/SHOM:1?start=2019-10-12%2000:00%20am%20EDT&local=1&detailed=1

ou 192.168.1.3 est l'adresse du Pi.. On obtient quelque chose comme ça:

{"index":214,"id":"SHOM:1","name":"Arcachon Eyrac","position":{"lat":44.665076,"long":-1.163666},"timezone":":Europe/Paris","note":"","type":"tide","levelUnits":"m","events":[{"time":"2019-10-12 12:13 AM CEST","name":"Low Tide","isMaxMin":true,"level":-1.4912528607527973},{"time":"2019-10-12 06:29 AM CEST","name":"High Tide","isMaxMin":true,"level":1.3308788824466118},{"time":"2019-10-12 06:31 AM CEST","name":"Moonset","isMaxMin":false},{"time":"2019-10-12 08:15 AM CEST","name":"Sunrise","isMaxMin":false},{"time":"2019-10-12 12:26 PM CEST","name":"Low Tide","isMaxMin":true,"level":-1.5278729066763577},{"time":"2019-10-12 06:43 PM CEST","name":"High Tide","isMaxMin":true,"level":1.5119263360270265},{"time":"2019-10-12 07:20 PM CEST","name":"Moonrise","isMaxMin":false},{"time":"2019-10-12 07:26 PM CEST","name":"Sunset","isMaxMin":false}]}


Un beau graphe:
http://192.168.1.3:800//graph/SHOM:1?local=1&detailed=1

ohhhh le beau svg (ci-dessous tout moche en png)!


Démarrage automatique?... ok:
pi@dietpi:~ sudo nano /etc/init.d/xtwsdd

#! /bin/sh
### BEGIN INIT INFO
# Provides: xtwsd
# Required-Start: $network $remote_fs $syslog
# Required-Stop: $network $remote_fs $syslog
# Default-Start: 2 3 4 5
# Default-Stop: 0 1 6
# Short-Description: Serveur de marees
# Description: Serveur web json de marée basé sur xtide
### END INIT INFO

# Do NOT "set -e"

PATH=/sbin:/bin:/usr/sbin:/usr/bin:/usr/local/bin
DESC="Serveur de marees"
NAME=xtwsd
USERNAME=root
PIDFILE=/var/run/$NAME.pid
SCRIPTNAME=/etc/init.d/$NAME

DAEMON=/usr/local/bin/$NAME
DAEMON_ARGS="$DAEMON_ARGS 800"

# Exit if the package is not installed
[ -x "$DAEMON" ] || exit 0

# Load the VERBOSE setting and other rcS variables
. /lib/init/vars.sh

# Define LSB log_* functions.
# Depend on lsb-base (>= 3.2-14) to ensure that this file is present
# and status_of_proc is working.
. /lib/lsb/init-functions

pidof_xtwsd() {
# if there is actually a xtwsd process whose pid is in PIDFILE,
# print it and return 0.
if [ -e "$PIDFILE" ]; then
if pidof $NAME | tr ' ' '\n' | grep -w $(cat $PIDFILE); then
return 0
fi
fi
return 1
}

#
# Function that starts the daemon/service
#
do_start()
{
# Return
# 0 if daemon has been started
# 1 if daemon was already running
# 2 if daemon could not be started
start-stop-daemon --chuid $USERNAME --start --quiet --pidfile $PIDFILE --exec $DAEMON --test > /dev/null \
|| return 1
start-stop-daemon --start --quiet --pidfile $PIDFILE --exec $DAEMON -- \
$DAEMON_ARGS \
|| return 2
}

#
# Function that stops the daemon/service
#
do_stop()
{
# Return
# 0 if daemon has been stopped
# 1 if daemon was already stopped
# 2 if daemon could not be stopped
# other if a failure occurred
start-stop-daemon --stop --quiet --retry=TERM/30/KILL/5 --pidfile $PIDFILE --name $NAME
RETVAL="$?"
[ "$RETVAL" = 2 ] && return 2
# Wait for children to finish too if this is a daemon that forks
# and if the daemon is only ever run from this initscript.
# If the above conditions are not satisfied then add some other code
# that waits for the process to drop all resources that could be
# needed by services started subsequently. A last resort is to
# sleep for some time.
start-stop-daemon --stop --quiet --oknodo --retry=0/30/KILL/5 --exec $DAEMON
[ "$?" = 2 ] && return 2
# Many daemons don't delete their pidfiles when they exit.
rm -f $PIDFILE
return "$RETVAL"
}

case "$1" in
start)
[ "$VERBOSE" != no ] && log_daemon_msg "Starting $DESC" "$NAME"
do_start
case "$?" in
0|1) [ "$VERBOSE" != no ] && log_end_msg 0 ;;
2) [ "$VERBOSE" != no ] && log_end_msg 1 ;;
esac
;;
stop)
[ "$VERBOSE" != no ] && log_daemon_msg "Stopping $DESC" "$NAME"
do_stop
case "$?" in
0|1) [ "$VERBOSE" != no ] && log_end_msg 0 ;;
2) [ "$VERBOSE" != no ] && log_end_msg 1 ;;
esac
;;
status)
status_of_proc "$DAEMON" "$NAME" && exit 0 || exit $?
;;
reload)
log_daemon_msg "Reloading $DESC" "$NAME"
PID=$(pidof_xtwsd) || true
if [ "${PID}" ]; then
kill -HUP $PID
log_end_msg 0
else
log_end_msg 1
fi
;;
restart)
log_daemon_msg "Restarting $DESC" "$NAME"
do_stop
case "$?" in
0|1)
do_start
case "$?" in
0) log_end_msg 0 ;;
1) log_end_msg 1 ;; # Old process is still running
*) log_end_msg 1 ;; # Failed to start
esac
;;
*)
# Failed to stop
log_end_msg 1
;;
esac
;;
*)
echo "Usage: $SCRIPTNAME {start|stop|status|restart|reload}" >&2
exit 3
;;
esac

:

 ^o ^x


pi@dietpi:~ sudo chmod 755 /etc/init.d/xtwsdd
pi@dietpi:~ sudo update-rc.d xtwsdd defaults
pi@dietpi:~ sudo systemctl daemon-reload

Test #4
pi@dietpi:~ sudo /etc/init.d/xtwsdd start

Navigateur : http://192.168.1.3:800//graph/SHOM:1?local=1&detailed=1
On doit obtenir un graphe

 pi@dietpi:~ sudo reboot
..
..
Navigateur : http://192.168.1.3:800//graph/SHOM:1?local=1&detailed=1
Idem

Voilà !

vendredi 20 septembre 2019

Régulation de chauffage et même plus...

Après avoir envisagé la réalisation de A à Z d'un système de régulation de chauffage électrique à base de Raspberry et d'une interface fil pilote, je me suis finalement et heureusement orienté vers une solution existante (pourquoi réinventer l'eau chaude?) ou presque.
Le labo(rdel) :

Le matériel:

Le cœur : Raspberry Pi 3 B+ (quad cores) +  dietpi + pihole (pour d'autres raisons)

Module radio 433 MHz RFlink (Arduino 2560 mega + récepteur et émetteur 433 MHz) c'est pas cher, c'est très facile à mettre en œuvre, ça marche.
Sondes de température oregon et autre (Auriol, sans marque, RFLink est compatible avec beaucoup de module)
Prises secteur commandées en 433 MHz

Le logiciel:

DietPi (raspbian est aussi bien)
Domoticz.... pourquoi ? ben tout à fonctionné du premier coup, c'est un projet pérenne

C'est parti!

Installer depuis l'utilisateur pi ou dietpi par sudo (pas en root)

🚩Si jamais domoticz plante au redémarrage ou de temps en temps c'est justement peut-être un problème d'accès aux fichiers ou aux dossiers, donc faire :
cd domoticz
sudo service domoticz stop
sudo chown -R pi.pi *
 
ou bien : sudo chown -R dietpi.dietpi * suivant l'utilisateur qui a installer domoticz

🚩Pensez à sauvegarder la configuration de domoticz, c'est un vrai plaisir de la restaurer !
 
🚩Vous pouvez aussi sanvegarder la config de pi-hole... mais je ne suis jamais arrivé à la restaurer 😕
 

Fabrication du module "fil pilote"

L'interface montée:
Le parti pris:
La commande sera partielle: seules les commandes "Hors gel" et "Confort" seront disponibles, les raisons sont : Simplicité du montage et des commandes. Il faudra donc régler les radiateurs à un valeur de consigne légèrement supérieure à celle utilisée "normalement"
Ce qui en cas de panne du système ne pourra avoir comme conséquences que soit une température légèrement supérieure à la normale, soit une coupure de chauffage avec une protection "Hors gel" malgrés tout.
Le schéma, simple donc:
https://drive.google.com/open?id=1ZxQ2F3j3TgUWipmgAYc8Ib9v33t9pW4x

Les PCB ont été réalisés en Chine, 5 pièces pour moins de 10€ port compris (imbattable)
Schéma et tracés au format Kicad sont disponibles ici :
https://drive.google.com/file/d/1GpU_VEaQiBhTw2qPmWH0dix0gT8Tgb6J/view?usp=sharing

Il faudra après connecter l'interface au RFLink à l'aide d'un HE10 et cable en nappe puis bornier ou autres sur le RFLink. Utiliser une carte d'extension est une bonne idée:

Test du hardware:

Connecter le RFLink au PC, ouvrir un terminal sur le port série (57600 baud N 8 1) puis envoyer après boot les commandes suivantes:

mettre tout à OFF : 
10;GPIOset;30;0;OFF;
10;GPIOset;31;0;OFF;
10;GPIOset;32;0;OFF;
10;GPIOset;33;0;OFF;
10;GPIOset;34;0;OFF;
10;GPIOset;35;0;OFF;

mettre gpio ON: 
10;SETGPIO=ON;

Vérifier l'état des sorties:
10;GPIOset;30;0;ON;
10;GPIOset;30;0;OFF;

10;GPIOset;31;0;ON;
10;GPIOset;31;0;OFF;

10;GPIOset;32;0;ON;
10;GPIOset;32;0;OFF;

etc..

Création dans domoticz des dispositifs miniGPIO du RFLink :

(Configuration) > (Matériel) Dans la ligne RFLink > (Create RFLink Devices)
Saisir "10;setgpio=on" > (Ok)
(Configuration) > (Paramètres) > Paragraphe "Matériel/dispositifs:" > (Autoriser pendant 5 minutes)
Faites alors changer l'état des entrées logiques 26 27 28 et 29, les dispositifs seront créés automatiquement (attention: les autres aussi! faire le ménage après dans les dispositifs)

Ajouter les sorties numériques: (Configuration) > (Matériel) Dans la ligne RFLink > (Create RFLink Devices)
Saisir "20;01;GPIOset;ID=30;SWITCH=0;CMD=ON;" > (Ok)

(Create RFLink Devices)
Saisir "20;01;GPIOset;ID=31;SWITCH=0;CMD=ON;" > (Ok)
(Create RFLink Devices)
Saisir "20;01;GPIOset;ID=32;SWITCH=0;CMD=ON;" > (Ok)
(Create RFLink Devices)
Saisir "20;01;GPIOset;ID=33;SWITCH=0;CMD=ON;" > (Ok)
(Create RFLink Devices)
Saisir "20;01;GPIOset;ID=34;SWITCH=0;CMD=ON;" > (Ok)
(Create RFLink Devices)
Saisir "20;01;GPIOset;ID=35;SWITCH=0;CMD=ON;" > (Ok)

TeleInfo ERDF

Le port serie GPIO est utilisé dans ce cas.
....

Préparation du raspberry (V3 mini):

Dans le fichier /boot/cmdline.txt :
supprimer : console=serial0,115200
ajouter : enable_uart=1

Inutile de modifier le fichier /etc/inittab.

Dans mon cas (RPI 3 + DietPi) le port se nomme : /dev/ttyAMA0 c'est ce port que je choisi dans Domoticz

Domoticz

Ajouter le matériel "Teleinfo EDF"
et selectionner le port série





Régulation de chauffage avec un orange pi

Régulation de chauffage avec un orange pi

Projet abandonné pour Domoticz + RFLink + ...

Objectif

Gestion améliorée du chauffage électrique de ma maison en utilisant un raspberry (orangepi en fait), des capteurs de température sans fil de la marque Oregon scientific et Auriol, et les fils pilote des radiateurs grâce à une interface à définir...

L'ordinateur

Un orange Pi one, parce qu’il est pas cher (:-))

Les sondes 

Une sonde de température Auriol et deux sondes Oregon scientific donnant température et taux d'humidité.

Les radiateurs

Des radiateurs basic de marque atlantic avec fil pilote.

Réception 433 MHz

J'utilise un module de réception (environ 8€) connecté à mon raspberry

Essai de réception de la température et taux d'humidité avec la sonde Oregon Scientific THGR 122 NX (environ 20 €)


git clone -b master https://github.com/1000io/OregonPi.git

cd OregonPi
nano test.cpp

changer la ligne
    int RXPIN = 1;
par
    int RXPIN = 16;
   

make

./test

Après quelques secondes vous allez recevoir quelque chose comme :

OSV2 1A2D40FD901870054EF1
Temp : 18.900000
Humidity : 57.000000
Channel : 3

------------------------------

 pilight

"pilight is a free, open source, full fledged domotica solution that runs on a Raspberry Pi, Hummingboard, and BananaPi"

git clone https://github.com/wo-rasp/pilight.git
git clone --depth 5 -b development https://github.com/wo-rasp/pilight.git
cd pilight

nano CMakeLists.txt

Modifier la ligne 40 (?) comme suit :
-set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -Wall")
+set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -Wall -fomit-frame-pointer")

chmod +x setup.sh
sudo ./setup.sh

Sélectionner le protocole Oregon entre autres

Editer le fichier de config :

sudo nano /etc/pilight/config.json

{
    "devices": {
        "TempSensTHGR122N": {
            "protocol": [ "oregon_21" ],
            "id": [{
                "device_id": 7456,
                "id": 3,
                "unit": 155
            }],
            "battery": 0,
            "humidity": 10.00,
            "temperature": 10.00
        }
    },
    "rules": { },
    "gui": {
        "TempSensTHGR122N": {
            "name": "Living_Room",
            "group": [ "Weather" ],
            "media": [ "all" ],
            "temperature-decimals": 2,
            "humidity-decimals": 1,
            "show-battery": 1,
            "show-temperature": 1,
            "show-humidity": 1
        }
    },
    "settings": {
        "log-level": 6,
        "pid-file": "/var/run/pilight.pid",
        "log-file": "/var/log/pilight.log",
        "webserver-enable": 1,
        "webserver-root": "/usr/local/share/pilight/webgui",
        "webserver-http-port": 80,
        "webserver-https-port": 443,
        "webserver-cache": 1,
        "whitelist": "",
        "gpio-platform": "none"
    },
    "hardware": {
        "433gpio": {
            "sender": 0,
            "receiver": 16
        }
    },
    "registry": { }
}


Backup disks on samba server with fsarchiver

fsarchiver : http://www.fsarchiver.org/

Install samba client
sorry, use google...

Mount samba folder

sudo mkdir /media/nas
nano ~/.smbcredentials

Add this: 
user=nasuser
password=naspass
 

Save and:   
chmod 0600 ~/.smbcredentials
 

sudo nano /etc/fstab


Add this:
//192.168.1.230/commun  /media/nas cifs  credentials=/home/pi/.smbcredentials,x-systemd.automount,defaults 0 0

Save and:

Install fsarchiver

sudo apt install fsarchiver

Backup your disks

Display your disks:

sudo fdisk -l
.
.
.

Device         Boot Start     End Sectors  Size Id Type
/dev/mmcblk0p1       8192   93813   85622 41,8M  c W95 FAT32 (LBA)
/dev/mmcblk0p2      94208 5678280 5584073  2,7G 83 Linux



Before backup, a good idea is to use SCREEN:

Install screen
sudo apt install screen 

Create a vitual screen:

sudo screen -S backup 

Archive the boot particion:
sudo fsarchiver -A savefs /media/nas/boot_`date +%y-%m-%d`.fsa /dev/mmcblk0p1

    Statistics for filesystem 0
    * files successfully processed:....regfiles=216, directories=3, symlinks=0, hardlinks=0, specials=0
    * files with errors:...............regfiles=0, directories=0, symlinks=0, hardlinks=0, specials=0


Archive the system partition:
sudo fsarchiver -A savefs /media/nas/root_`date +%y-%m-%d`.fsa /dev/mmcblk0p2

... take long time ZZZ zzzz ...

Ctrl a + d to quit the virtual screen

To check backup progress, enter in screen :

sudo screen -x backup
Ctrl a + d


Etc... (You can close ssh session, and re enter in screen)

And a very long time after:

15193+1 enregistrements lus
15193+1 enregistrements écrits
15931539456 bytes (16 GB, 15 GiB) copied, 3750,82 s, 4,2 MB/s
root@cabass:/home/pi# sudo fsarchiver -A savefs /media/nas/cabass-system.fsa /dev/mmcblk0p2
Statistics for filesystem 0
* files successfully processed:....regfiles=66035, directories=7967, symlinks=13449, hardlinks=209, specials=222
* files with errors:...............regfiles=0, directories=0, symlinks=0, hardlinks=0, specials=0


On destination samba server you have two new files:
ie.:
boot_19-09-29.fsa
root_19-09-29.fsa


Restoring:

fsarchiver restfs /media/nas/cabass-boot.fsa id=0,dest=/dev/mmcblk0p1

and:


fsarchiver restfs /media/nas/cabass-system.fsa id=0,dest=/dev/mmcblk0p2