Categories
Python

Raspberry Pi – Access to WordPress with Python wordpress-api

Would not it be nice if the Raspberry Pi could create articles on my website, modify them and become an editor?
If you use WordPress on your website, it’s relatively easy, since WordPress from version 4.8 includes the REST interface as standard and there is a corresponding plugin for older versions.

Whether the interface is available, can be easily detected by attaching ‘wp-json’ to the URL for each WordPress web page. For example, http://www.henrykoch.de/wp-json should display a Json string in the browser:

"name":"www.HenryKoch.de","description":"","url":"http:\/\/www.henrykoch.de","home":"http:\/\/www.henrykoch.de\/de","gmt_offset":2,"timezone_string":"Europe\/Berlin"

Installation python wordpress-api

For the installation of the WordPress Api for python, I am followed this guide https://pypi.python.org/pypi/wordpress-api/1.2.2, which did not work immediately.
To get the API running, additional packages had to be installed.

So I came to the result (On the Raspberry Pi)

sudo apt-get update
sudo apt-get install libxml2-dev
sudo apt-get build-dep python3-lxml
pip install wordpress-api

Libxml and lxml were missing from me.

Authentication

I spent a lot of time here.
I really wanted an OAuth authentication and I failed with the described REST oauth1 plugin.
After a long back and forth I installed this plugin: WP OAuth Server

As seen on the pictures, there is an OAuth server entry after installation on the dashboard on the left side. There I created a user. If this is done, the user is listed and a client ID is specified. Consumer_key in the phthon script
In addition, the Secret Key can now be displayed -> consumer_secret in the python script.

first test script

#!/usr/bin/python
# -*- coding: utf-8 -*-
from wordpress import api as wpapi
from wordpress import API
 
wpapi = API(
    url="http://ai.henrykoch.de/", #your URL
    consumer_key="xxxxxxxxxxxxx", #your key
    consumer_secret="xxxxxxxxxxxxx", #your secret key
    api="wp-json",
    version="wp/v2",
    wp_user="xxx",    #your wp User
    wp_pass="xxx"     #wp users password
)
r = wpapi.get("posts")
print r.status_code
print r.headers['content-type']
print r.encoding
print r.text
print r.json()

The result

pi@raspberrypi:~/python/Wordpress $ python myscript.py
200
application/json; charset=UTF-8
UTF-8
[{"id":1,"date":"2017-08-08T15:25:58","date_gmt":"2017-08-08T13:25:58","guid":{"rendered":"http:\/\/ai.henrykoch.de\/?p=1"},"modified":"2017-08-08T15:38:46","modified_gmt":"2017-08-08T13:38:46","slug":
...
Categories
Raspberry Pi

USB over IP, extend the network, Wifi – to use Arduino over Raspberry Pi as gateway

USB over IP – First contact point:

Actions on the server side – Raspberry Pi

USB over IP is to be available on the Raspberry Pi from kernel Linux 3.17 without further installation.

Check what kernel I have:

17:45:46|pi@raspberrypi:~|$ uname -r
4.1.13+

Kernel version is higher :-)
Test:

17:49:05|pi@raspberrypi:~|$ usbip
-bash: usbip: Command not found.

That’s not much good. :-(

Continue with the tips from the forum: https://www.raspberrypi.org/forums/viewtopic.php?p=121691

install usbip

17:49:25|pi@raspberrypi:~|$ sudo apt-get install usbip

loading the Kernel module

17:54:16|pi@raspberrypi:~|$ sudo modprobe usbip-host

Starting the usbip daemon

08:52:50|pi@raspberrypi:~|$ sudo usbipd -D

listing USB devices (without Arduino)

18:01:48|pi@raspberrypi:~|$ lsusb
Bus 001 Device 002: ID 0424:9512 Standard Microsystems Corp. 
Bus 001 Device 001: ID 1d6b:0002 Linux Foundation 2.0 root hub
Bus 001 Device 003: ID 0424:ec00 Standard Microsystems Corp.

and listing USB devices (with Arduino plugged in)

18:02:30|pi@raspberrypi:~|$ lsusb
Bus 001 Device 002: ID 0424:9512 Standard Microsystems Corp. 
Bus 001 Device 001: ID 1d6b:0002 Linux Foundation 2.0 root hub
Bus 001 Device 003: ID 0424:ec00 Standard Microsystems Corp. 
Bus 001 Device 005: ID 1a86:7523 QinHeng Electronics HL-340 USB-Serial adapter

In my case is the ID of the USB device: 1a86:7523
The same again with the program usbip

18:05:21|pi@raspberrypi:~|$ sudo usbip list -l
Local USB devices
=================
 - busid 1-1 (0424:9512)
         1-1:1.0 -> hub
 
 - busid 1-1.1 (0424:ec00)
         1-1.1:1.0 -> smsc95xx
 
 - busid 1-1.2 (1a86:7523)
         1-1.2:1.0 -> ch341

Binding of the USB device

09:22:48|pi@raspberrypi:~/deb_pakete|$ sudo usbip bind -b 1-1.2
bind device on busid 1-1.2: complete

Actions on the client side – in my case a laptop with Ubuntu

download and install of the matching usbip version

10:04:25|henry@t410:~/deb_pakete|$ wget http://ftp.de.debian.org/debian/pool/main/l/linux-tools/usbip_1.1.1+3.2.17-1_amd64.deb
--2016-02-13 10:05:51--  http://ftp.de.debian.org/debian/pool/main/l/linux-tools/usbip_1.1.1+3.2.17-1_amd64.deb
Auflösen des Hostnamen »ftp.de.debian.org (ftp.de.debian.org)«... 141.76.2.4
Verbindungsaufbau zu ftp.de.debian.org (ftp.de.debian.org)|141.76.2.4|:80... verbunden.
HTTP-Anforderung gesendet, warte auf Antwort... 200 OK
Länge: 52602 (51K) [application/x-debian-package]
In »»usbip_1.1.1+3.2.17-1_amd64.deb«« speichern.
 
100%[=====================================>] 52.602      --.-K/s   in 0,08s   
 
2016-02-13 10:05:51 (628 KB/s) - »»usbip_1.1.1+3.2.17-1_amd64.deb«« gespeichert [52602/52602]
 
10:05:51|henry@t410:~/deb_pakete|$ sudo dpkg -i usbip_1.1.1+3.2.17-1_amd64.deb Vormals nicht ausgewähltes Paket usbip wird gewählt.
(Lese Datenbank ... 588070 Dateien und Verzeichnisse sind derzeit installiert.)
Vorbereitung zum Entpacken von usbip_1.1.1+3.2.17-1_amd64.deb ...
Entpacken von usbip (1.1.1+3.2.17-1) ...
usbip (1.1.1+3.2.17-1) wird eingerichtet ...
Trigger für man-db (2.6.7.1-1ubuntu1) werden verarbeitet ...

loading Kernel module

10:06:22|henry@t410:~/deb_pakete|$ sudo modprobe vhci-hcd
10:08:30|henry@t410:~/deb_pakete|$ lsmod | grep vhci
vhci_hcd               33435  0 
usbip_core             27617  1 vhci_hcd

Listing the USB devices that are provided on the PI

10:11:10|henry@t410:~/deb_pakete|$ sudo usbip list -r 192.xxx.xxx.xxx
Exportable USB devices
======================
 - 192.xxx.xxx.xxx
      1-1.2: QinHeng Electronics : HL-340 USB-Serial adapter (1a86:7523)
           : /sys/devices/platform/bcm2708_usb/usb1/1-1/1-1.2
           : Vendor Specific Class / unknown subclass / unknown protocol (ff/00/00)
           :  0 - Vendor Specific Class / unknown subclass / unknown protocol (ff/01/02)

adding the USB Device

10:24:20|henry@t410:~/deb_pakete|$ sudo usbip attach -h 192.xxx.xxx.xxx -b 1-1.2
10:24:45|henry@t410:~/deb_pakete|$ lsusb
Bus 003 Device 002: ID 1a86:7523 QinHeng Electronics HL-340 USB-Serial adapter

Check with the Arduino IDE

USB over IP Arduiono Remote programmiert über IP

Actions on the server side – Raspberry Pi

After using on the server side – releasing the USB device

09:22:54|pi@raspberrypi:~/deb_pakete|$ sudo usbip unbind -b 1-1.2
unbind device on busid 1-1.2: complete

Papst ebm G1G133-DE19-15* fan speed measuring / controlling with Arduino and Raspberry Pi

On ebay are offered used fan with DC motors from 13 euro, which with up to air flow: 225 m³ per hour with a maximum of 45 watts have very good performance values.
For me it was important that it is possible to regulate the speed of the fan, because I don’t always need full power.

In the reviews of the product below in the auction, it was announced that the speed of the motor can be controlled by PWM.
This data sheet of an almost identical fan shows on page 4 that it is possible to control the speed via a PWM signal. With my fan this doesn’t work.

After many attempts to create a PWM signal and to pick up a speed pulse, I decided to take the fan apart.

Inside it is not a normal DC motor, that is more a microcontroller-controlled high-tech product. I am sure that the circuitry would allow speed control even if for that the internal fan microcontroller’s code would have to be adapted.

continuing on the following pages:

(Deutsch) Dashboard – IOT – Sensordaten – von meiner Raspberry Pi

Dashboard IOT Realtime sensor data, sent by Raspberry Pi’s

The last update took place: loading …

Categories
Python

Raspberry Pi – Python – SQLite database – a simple frugal way to manage data professionally

The following post provides code examples in Python inclusive the complete sources for download

  1. Create a new SQLite database
  2. Create a new table
  3. Display of all tables in a database
  4. Insert values into a table
  5. View table contents
  6. Code to download

0 Preliminary two links to SQLite descriptions / tutorials

1 Create a new SQLite database

To create a database it’s enough to make a connect to a non-existing database and the database file will be created automatically.

#!/usr/bin/python
# -*- coding: utf-8 -*-
 
import sqlite3 as lite
import sys
 
def create_new_database(PfadzurDatenbank):
    try:
        con = lite.connect(PfadzurDatenbank) 
        con.commit()
 
    except lite.Error, e:
        if con:
            con.rollback()
            print "Error %s:" % e.args[0]
            sys.exit(1)
 
    finally:
        if con:
            con.close() 
 
create_new_database("/home/pi/sqlite3/BeispielDatenbank.db")
pi@raspberrypi ~/sqlite3 $ ls -al
insgesamt 580
drwxr-xr-x  2 pi pi   4096 Okt 21 10:02 .
drwxr-xr-x 12 pi pi   4096 Sep 27 20:26 ..
-rw-r--r--  1 pi pi      0 Okt 21 10:02 BeispielDatenbank.db

2 Create a new table

In the following code example, a table will be created, which will be used to store the measured values of a temperature sensor DS18820.
The table consists of three columns

  • time stamp
  • minimum temperature
  • maximum temperature

The goal for this table is to insert timestamps and temperature values. Each
row stands for a timeframe of one hour. The temperatures which are measured within the hour, will be compared to the maximum and minimum values that already stored in the table.
Bildschirmfoto vom 2015-10-21 11:14:11

If the new value is greater than the maximum value at the table, it will be replaced. If the new value is less than minimum value in the table, the minimum value will be replaced.
So regardless of the number of measurements (greater than 1) remain three values per hour (timestamp, MinTemp, MaxTemp), which is perfectly adequate for a normal measurement of space or outdoor temperatures.

#!/usr/bin/python
# -*- coding: utf-8 -*-
 
import sqlite3 as lite
import sys
 
def create_new_temperature_sensor_table(PathToDatabase, TableName):
    try:
        con = lite.connect(PathToDatabase)
        cur = con.cursor()  
        cur.executescript("""
            CREATE TABLE %s(    Timestamp INT PRIMARY KEY, 
                                Temp_MIN REAL, 
                                Temp_MAX REAL); 
            """ % TableName) 
        con.commit()
 
    except lite.Error, e:
 
        if con:
            con.rollback()
 
            print "Error %s:" % e.args[0]
            sys.exit(1)
 
    finally:
 
        if con:
            con.close() 
create_new_temperature_sensor_table("/home/pi/sqlite3/BeispielDatenbank.db", "Fuehler1")

3 Display of all tables in a database

Currently, only one table (Fuehler1) in the database was created, which can be displayed by using the following script.

#!/usr/bin/python
# -*- coding: utf-8 -*-
 
import sqlite3 as lite
import sys
def list_all_tables_in_DB(PathToDatabase):
    try:
        con = lite.connect(PathToDatabase)
 
        with con:
 
            cur = con.cursor()    
            cur.execute("SELECT name FROM sqlite_master WHERE type='table'")
 
            rows = cur.fetchall()
 
            for row in rows:
                print row[0]
 
    except lite.Error, e:
 
        if con:
            con.rollback()
 
            print "Error %s:" % e.args[0]
            sys.exit(1)
 
    finally:
 
        if con:
            con.close() 
 
list_all_tables_in_DB("/home/pi/sqlite3/BeispielDatenbank.db")
pi@raspberrypi ~/python_scripts $ python DB_Funktionen.py 
Fuehler1

4 Insert values into a table

The following is to be inserted into the table Fuehler1:

  • Timestamp: 1445432400
  • Temp_MIN: 15.0
  • Temp_MAX: 17.22
#!/usr/bin/python
# -*- coding: utf-8 -*-
 
import sqlite3 as lite
import sys
 
def insert_new_line_in_temperature_sensor_table(PathToDatabase, TableName, 
                                                Timestamp, Temp_MIN, Temp_MAX):
 
    try:
        con = lite.connect(PathToDatabase)
        cur = con.cursor()  
        cur.execute("""
            INSERT INTO %s 
            VALUES( %i , %.3f, %.3f)
            """ % (TableName, Timestamp, Temp_MIN, Temp_MAX))
        con.commit()
 
    except lite.Error, e:
 
        if con:
            con.rollback()
 
            print "Error %s:" % e.args[0]
            sys.exit(1)
 
    finally:
 
        if con:
            con.close() 
 
insert_new_line_in_temperature_sensor_table("/home/pi/sqlite3/BeispielDatenbank.db", 
                                            "Fuehler1", 1445432400, 15.0, 17.22)

5 View table contents

#!/usr/bin/python
# -*- coding: utf-8 -*-
 
import sqlite3 as lite
import sys
 
def show_all_table_entries(PathToDatabase, TableName):
    try:
        con = lite.connect(PathToDatabase)
        cur = con.cursor()  
        cur.execute("SELECT * FROM %s" % TableName)
        lines = cur.fetchall()
        for line in lines:
            print line
        con.commit()
 
    except lite.Error, e:
        if con:
            con.rollback()
            print "Error %s:" % e.args[0]
            sys.exit(1)
 
    finally:
        if con:
            con.close()
show_all_table_entries("/home/pi/sqlite3/BeispielDatenbank.db", "Fuehler1")
pi@raspberrypi ~/python_scripts $ python DB_Funktionen.py 
(1445432400, 15.0, 17.22)

6 Code to download

download: DB_Funktionen.py

Categories
Raspberry Pi

Raspberry Pi – configure automatically daily restart / reboot with cron

A nice thing is the ability to perform actions automatically to defined times with the cron daemon.

A helpful introduction about cron can be found here: https://www.raspberrypi.org/documentation/linux/usage/cron.md
Those like me who has difficulty to use with vi, can be pleased, because the necessary command to configure sudo crontab -e opens the nano editor.

Should, for example, the Raspberry Pi do every day at 14:44 clock a healthy reboot, you have to add following to the crontab of the root user (with sudo).

17:10:33|pi@raspberrypi:~|$ sudo crontab -e
# For more information see the manual pages of crontab(5) and cron(8)
#
# m h  dom mon dow   command
44 14 * * * /sbin/shutdown -r now

Now, the system should make every day at 14:44 o clock a reboot.

Categories
Python

(Deutsch) Raspberry Pi – Python – (HC-SR04) Ultraschall Abstandsmessung – fehlerhafte Ergebnisse durch Statistik in den Griff bekommen – Teil1

Sorry, this entry is only available in German.

Categories
Raspberry Pi

Read temperature of Raspberry on the command line

As the owner of one or more Raspberry Pis arises certainly sometime interest in monitoring the CPU temperature.
In particular, when the CPU (maybe even outside the “permitted” area) is overclocked (read more)

Categories
Python

Python – remove oldest files in a directory, only a defined count of them remains

By experimenting with the Pi camera and PIR at may Raspberry Pi were quickly many images written to the SD card.

In order to get some control, the following Python Script is a good basis.
There is the possibility to specify a directory and the maximum number of files stored in it.

Exceeds the number of files the defined value, older files are deleted.

In my case, I always keep a maximum of 1000 images in the folder.

Sample code:

#!/usr/bin/python
 
import os
 
path = "/home/pi/pictures/"
max_Files = 1000
 
def sorted_ls(path):
    mtime = lambda f: os.stat(os.path.join(path, f)).st_mtime
    return list(sorted(os.listdir(path), key=mtime))
 
del_list = sorted_ls(path)[0:(len(sorted_ls(path))-max_Files)]
 
for dfile in del_list:
    os.remove(path + dfile)
Categories
Raspberry Pi

Raspberry Pi – setting up WIFI via the command line

Link to a official instruction manual, how you can setup access to your home wifi, in few and well understandable steps.
http://www.raspberrypi.org/documentation/configuration/wireless/wireless-cli.md

The WIFI stick was detected from my linux automatically without problems.

Maybe a little bit better is the following explanation:
http://weworkweplay.com/play/automatically-connect-a-raspberry-pi-to-a-wifi-network/