Mastodon

Tuesday, 1 August 2023

Raspberry Pi Access Point

 So you go on holiday and you take your tablets, laptop, phones and other stuff that connects to wifi. You then have to go and enter the new network details into each device to the new network and you put the details away and then find there's something else you haven't connected.

Wouldn't it be nice to take your own wifi connection with you.

So, I had a spare Raspberry Pi zero W version 2, broken camera port, a nice little case, a micro USB to large USB adaptor and some hot glue. All I needed was a second wifi adaptor.

I got this one from our friends at Amazon.

You don't have to get this one, I bought it and it works but feel free to try out any other ones.

First thing of course is to install Raspbian onto the Pi. I've gone for the lite 32 bit version. No desktop but it really isn't a problem. I'm not going through the setup process as if you can't do that you shouldn't do this. And all the config is done through ssh to the onboard wifi. Anything below that's in bold and italics is ok to copy and paste. 

Once you have finished setting it up, plug the adaptor in and you'll find like I did that although it's detected it doesn't work, yet.

The documentation with the adaptor gives you a link to the manufacturers website.

On the webpage it tells you to run the following.

 sh -c 'wget linux.brostrend.com/install -O /tmp/install && sh /tmp/install'

It takes a while and then it just works, you'll have the onboard adaptor of wlan0 and this one wlan2. 

Now we start doing other things and getting some software installed.

sudo apt install hostapd dnsmasq mc

I like mc, it's like Xtree Gold from the old dos days and is a great way to navigate the file system.

Now we run this.

sudo DEBIAN_FRONTEND=noninteractive apt install -y netfilter-persistent iptables-persistent

After that reboot with sudo reboot.

Once it's restarted more configuring files to get it all working.

sudo nano /etc/dhcpcd.conf

Paste all this in at the end.

interface wlan1

    static ip_address=192.168.4.1/24
    nohook wpa_supplicant

Save the files each time you finish, then onto.

sudo nano /etc/sysctl.d/routed-ap.conf

Paste this in and then save.

# Enable IPv4 routing
net.ipv4.ip_forward=1


Add a firewall rule with 
sudo iptables -t nat -A POSTROUTING -o wlan0 -j MASQUERADE

Save the firewall rules with:

sudo netfilter-persistent save

And now setup DHCP and DNS stuff

sudo mv /etc/dnsmasq.conf /etc/dnsmasq.conf.orig
sudo nano /etc/dnsmasq.conf

Add the following to the file and save it.

interface=wlan1
dhcp-range=192.168.4.2,192.168.4.20,255.255.255.0,24h
domain=wlan
address=/gw.wlan/192.168.4.1


Now we setup the access point software.

sudo nano /etc/hostapd/hostapd.conf

Paste this in, changing the country code to where you live, the ssid to the same as your home one if you want and the passphrase needs to be changed too.

country_code=UK

interface=wlan1

ssid=SSID

hw_mode=g

channel=7

macaddr_acl=0

auth_algs=1

ignore_broadcast_ssid=0

wpa=2

wpa_passphrase=PWD

wpa_key_mgmt=WPA-PSK

wpa_pairwise=TKIP

rsn_pairwise=CCMP

Now we run this to get it starting up when the pi boots.


sudo systemctl unmask hostapd

sudo systemctl enable hostapd

sudo systemctl start hostapd


Then give it one final reboot and you should see a new wifi connection pop up.

That's about it really.

Thanks to hackster.io for the initial guidance and Github for a little help in making it work.

You can use just about any Pi for this, seems to work quite well and I may even add  a connection to my vpn from it.

If you want to connect the Pi to a different wifi connection when you're away and travelling, boot it up, ssh into it and run 

sudo raspi-config



Select option 1

Then select S1 and enter the wifi connection details there. There may be a more elegant way like setting up a graphical desktop but this is nice and minimal and it works.

Here's some pictures of the complete thing with a few magnets attached to the back to make it easy to stick to things. And yes, I went overboard with the hot glue gun as I was going to make something that was waterproof first.

Hope this all makes sense to you and have fun.












Thursday, 12 January 2023

PIxelfed



The easiest way to describe Pixelfed is to say it's a federated version of Instagram. There's no big bad company behind it, your data is on your server and you can easily run your own at home if you want too. This can connect to any other Pixelfed instance in the Fediverse as it's called.







The image-sharing platform defines itself as “A free and ethical photo-sharing platform” with no ads, third-party analytics, or tracking.

You can find more on pixelfed.org

What Pixelfed does need is more servers to spread the load, I've put this guide together based on some notes from the Pixelfed website itself and another website that I can't for the life of me find to give credit to.

You will need an install of Ubuntu Server 22.04 to run this using these instructions.

Let us begin

Change to root user

sudo -i

Install latest updates

apt update

apt upgrade -y

reboot now

Then install the required software

apt -y install redis-server mariadb-server ffmpeg jpegoptim optipng pngquant gifsicle unzip zip php-fpm php-cli php-bcmath php-curl php-gd php-intl php-mbstring php-redis php-xml php-zip php-mysql nginx certbot python3-certbot-nginx mc php-json php-tokenizer php-imagick

Make some changes to the php config files

nano /etc/php/8.1/fpm/php.ini

Edit these lines, I've set the max size and max filesize to 100M , max file uploads is 50

post_max_size (default 8M, set this around or slightly greater than your desired post size limit)

file_uploads (default On, which it needs to be)

upload_max_filesize (default 2M, set this <= post_max_size)

max_file_uploads (default 20, but make sure it is >= your desired attachment limit)

max_execution_time (default 30, consider raising this to 600 or more so that longer tasks arent interrupted)


And change the line that says

;date.timezone =

to

date.timezone = Europe/London

or wherever your timezone is.

Enable some of the services

systemctl enable redis-server

systemctl enable mariadb


Setup the database

mysql_secure_installation

mysql -u root -p

create database pixelfed;

grant all privileges on pixelfed.* to 'pixelfed'@'localhost' identified by 'yourpassword';

flush privileges;

exit;



Install Composer

curl -sS <https://getcomposer.org/installer -o /tmp/composer-setup.php>

php /tmp/composer-setup.php --install-dir=/usr/local/bin --filename=composer



Get the software downloaded

cd /var/www

git clone -b dev https://github.com/pixelfed/pixelfed.git pixelfed

cd pixelfed

composer install --no-ansi --no-interaction --optimize-autoloader

cp .env.example .env

nano .env



Edit these lines to your requirements

# Instance Configuration

OPEN_REGISTRATION="true"

ENFORCE_EMAIL_VERIFICATION="false"

PF_MAX_USERS="1000"

OAUTH_ENABLED="true"



# Instance URL Configuration

APP_URL="https://pixelfed.yourdomain"

APP_DOMAIN="pixelfed.yourdomain"

ADMIN_DOMAIN="pixelfed.yourdomain"

SESSION_DOMAIN="pixelfed.yourdomain"

TRUST_PROXIES="*"



# Database Configuration

DB_CONNECTION="mysql"

DB_HOST="127.0.0.1"

DB_PORT="3306"

DB_DATABASE="pixelfed"

DB_USERNAME="pixelfed"

DB_PASSWORD="yourpassword"



# ActivityPub Configuration

ACTIVITY_PUB="true"

AP_REMOTE_FOLLOW="true"

AP_INBOX="true"

AP_OUTBOX="true"

AP_SHAREDINBOX="true"


Setup the permissions

sudo chown -R www-data:www-data /var/www/pixelfed

sudo find . -type d -exec chmod 755 {} \; # set all directories to rwx by user/group

sudo find . -type f -exec chmod 644 {} \; # set all files to rw by user/group


Generate the secret APP_KEY:

php artisan key:generate

Storage/ directory must be linked to the application:

php artisan storage:link

Database migrations must be run:

php artisan migrate --force

If you want to enable support for location data:

php artisan import:cities

If you enabled ActivityPub federation:

php artisan instance:actor

If you enabled OAuth:

php artisan passport:keys

Routes should be cached whenever the source code changes or whenever you change routes:

php artisan route:cache

php artisan view:cache


Every time you edit your .env file, you must run this command to have the changes take effect:

php artisan config:cache

Setup Laravel Horizon - Job queueing

php artisan horizon:install

php artisan horizon:publish


Let's make a startup service for Pixelfed with

nano /etc/systemd/system/pixelfed.service

Paste this in

[Unit]

Description=Pixelfed task queueing via Laravel Horizon

After=network.target

Requires=mariadb

Requires=php8.1-fpm

Requires=redis

Requires=nginx



[Service]

Type=simple

ExecStart=/usr/bin/php artisan horizon --environment=production

ExecStop=/usr/bin/php artisan horizon:terminate --wait

User=www-data

WorkingDirectory=/var/www/pixelfed/

Restart=on-failure



KillSignal=SIGCONT

TimeoutStopSec=3600



[Install]

WantedBy=multi-user.target


Save and exit then run the following to get the services activated

systemctl daemon-reload

systemctl enable pixelfed

systemctl status pixelfed


Create a cron task to do some tidying up

crontab -e

Paste this in

* * * * * /usr/bin/php /var/www/pixelfed/artisan schedule:run >> /dev/null 2>&1


Enable nginx

systemctl enable nginx

Disable the default site

unlink /etc/nginx/sites-enabled/default

Create the pixelfed website

cp /var/www/pixelfed/contrib/nginx.conf /etc/nginx/sites-available/pixelfed.conf

ln -s /etc/nginx/sites-available/pixelfed.conf /etc/nginx/sites-enabled/

nano /etc/nginx/sites-available/pixelfed.conf


Change the server name and the path to your chosen ones and amend the line that says

fastcgi_pass unix:/run/php-fpm/php-fpm.sock; # make sure this is correct

to

fastcgi_pass unix:/run/php/php-fpm.sock; # make sure this is correct

Setup an initial ssl connection, it doesn't need to be done but it's easier.

sudo mkdir /etc/nginx/ssl

sudo openssl req -x509 -nodes -days 365 -newkey rsa:2048 -keyout /etc/nginx/ssl/server.key -out /etc/nginx/ssl/server.crt

systemctl reload nginx

service php8.1-fpm restart

service nginx restart

service pixelfed restart

Install proper ssl certificates

certbot

Create the first user and make admin,

php artisan user:create

And that is it so far, you can now go to https://pixelfed.yourdomain and have some fun.


Once that's all done, I have added a few extra lines to the bottom of the .env file

ENABLE_CONFIG_CACHE=true

MAX_BIO_LENGTH=500

IMPORT_INSTAGRAM=true

MAX_PHOTO_SIZE=100000

IMAGE_DRIVER=imagick

LIMIT_ACCOUNT_SIZE=false

Make sure you run the following to activate the changes.


php artisan config:cache


You really should also setup a firewall to allow only the required connections, you can do this with.


sudo ufw allow http
sudo ufw allow https


You should also setup a port for connection by ssh, the default port is 22 so you would run
sudo ufw allow 22


It would be a good idea to change the port from the default.


Run sudo ufw enable
To enable the firewall, that's it people.


Feel free to look me up on pixelfed @paulholt@pixelfed.travelsoftux.co.uk and look up the man behind it all, @dansup@pixelfed.social.


Sunday, 2 January 2022

Raspberry Pi as a Remote SDR reciever

Having recently renewed my amateur radio licence, I decided it was time to see what I could do with a Raspberry Pi. You can now get software defined radios for incredibly low prices as use these for all sorts of things, one of these is for use as a receiver. You can simply buy one, plug it into a USB socket on your desktop, download sdrsharp and away you go, you do then need to connect the antenna to the USB device and this could result in a long run of cable.

Alternatively, you can connect the USB device to a Raspberry Pi, install some software, put the Pi outside in a waterproof box and connect via ethernet or wirelessly. I've gone for this option and used a wireless connection.

I've gone for the setup shown below, picked up from Amazon.



I'm also using a Raspberry Pi model 3 as it has built in wifi, you can use a 2 with a USB dongle or a 4 if you want.

Once all the stuff is together, it's time to get started. Connect to your Pi via ssh and run the following.

sudo apt update 

sudo apt upgrade -y 

sudo shutdown -r now

sudo apt-get install -y  git cmake  libusb-1.0-0-dev mc

git clone git://git.osmocom.org/rtl-sdr.git

Now we build the RTL SDR package.

cd rtl-sdr

mkdir build

cd build

cmake ../ -DINSTALL_UDEV_RULES=ON

make

sudo make install

sudo cp ../rtl-sdr.rules /etc/udev/rules.d/

sudo ldconfig

sudo nano /etc/udev/rules.d/rtl-sdr.rules

At the top of the file you will see this, change the 0660 to 0666 in both cases.

# original RTL2832U vid/pid (hama nano, for example)

SUBSYSTEMS=="usb", ATTRS{idVendor}=="0bda", ATTRS{idProduct}=="2832", ENV{ID_SOFTWARE_RADIO}="1", MODE="0660", GROUP="plugdev"


# RTL2832U OEM vid/pid, e.g. ezcap EzTV668 (E4000), Newsky TV28T (E4000/R820T) etc.

SUBSYSTEMS=="usb", ATTRS{idVendor}=="0bda", ATTRS{idProduct}=="2838", ENV{ID_SOFTWARE_RADIO}="1", MODE="0660", GROUP="plugdev"


It should now look like this.

# original RTL2832U vid/pid (hama nano, for example)

SUBSYSTEMS=="usb", ATTRS{idVendor}=="0bda", ATTRS{idProduct}=="2832", ENV{ID_SOFTWARE_RADIO}="1", MODE="0666", GROUP="plugdev"


# RTL2832U OEM vid/pid, e.g. ezcap EzTV668 (E4000), Newsky TV28T (E4000/R820T) etc.

SUBSYSTEMS=="usb", ATTRS{idVendor}=="0bda", ATTRS{idProduct}=="2838", ENV{ID_SOFTWARE_RADIO}="1", MODE="0666", GROUP="plugdev"


sudo nano /etc/modprobe.d/blacklist-rtl.conf

Paste this and and save and exit


blacklist dvb_usb_rtl28xxu

blacklist rtl2832

blacklist rtl2830



Now run the following

sudo apt-get install libvolk2-bin -y

volk_profile

This will take some time

Last thing to do is get the software to run at start up, I'm going to create a service to get this started on boot, we also need to provide the IP address that the pi is running at to the command line to get it running.

Let's create a file with sudo nano /bin/sdrstart

Paste this into the file.

#!/bin/bash

# Sets the variable $_IP as the ip address

_IP=$(hostname -I)

# Runs the rtl_tcp app and provides the output to it's own ip.

rtl_tcp -a $_IP

Make the file executable with sudo chmod +x /bin/sdrstart

Now we create a file for the service with sudo nano /etc/systemd/system/rtl.service

Paste this into the file.

[Unit]

Description SDR Start

After=network-online.target


[Service]

[Unit]

Description SDR Start

Wants=network-online.target

After=network-online.target


[Service]

Type=simple

ExecStart=/bin/bash /bin/sdrstart

PermissionStartOnly=true

StandardOutput=null

User=root

[Install]

WantedBy=multi-user.target


Save it and then run

sudo systemctl daemon-reload

sudo systemctl enable rtl.service

sudo service rtl restart

If you then run sudo service rtl status, you should see your Pi reporting that it's all up and running.


Give it a restart and you should be able to connect sdrsharp to the Pi using the RTL_SDR TCP option.



Thanks to Mike Richards G4WNC for the initial article and a lot of searching to fix a few little issues.

Saturday, 1 January 2022

Raspberry Pi Music Streaming

I want to be able to play music from my PC, phone tablet to my hifi system which is on the other side of the room. Bluetooth seems to drop out and I mostly use Spotify or Itunes as a music player. 

I thought I'd have a look at what could be done with a Raspberry Pi and an external sound card to improve the standard sound quality. In the end I tested this out with a Raspberry Pi zero W which worked quite well and ended up running it on a Raspberry Pi Zero 2.

For Spotify to work you do need Spotify premium but iTunes will work quite happily with local files.

I'm not going through with how to install Raspbian onto an SD card and configure the wifi settings here.

Here's the sound card I got hold of from Amazon. £6.99 and it seems to work quite well. You'll also need an adaptor to connect this to the micro USB socket if you're using a Pi Zero.

Once that's all connected it together and you have Raspbian Lite installed on an SD card it's time to get it up and running


As always let's update the os first.

sudo apt-get update 

sudo apt-get upgrade

Then we use the following line to install raspotify

curl -sL https://dtcooper.github.io/raspotify/install.sh | sh

Once it's completed we can edit some settings with:

sudo nano /etc/raspotify/conf

Look for the following line.

# Device name.

# Raspotify defaults to "raspotify (*hostname)".

# Librespot defaults to "Librespot".

# LIBRESPOT_NAME="Music1"

Uncomment the last line and change the Music1 to whatever you want to call it.

Now we activate the USB sound card

sudo nano /usr/share/alsa/alsa.conf

defaults.ctl.card 0

defaults.pcm.card 0

Change the above to the settings shown below

defaults.ctl.card 1

defaults.pcm.card 1

Save the file and then run sudo alsamixer

This should show the display below, just turn the sound all the way up.


If you now run sudo service raspotify restart you should see the device name showing up in your Spotify client, if you connect the audio output to your hifi you can play music from your devices to it.

Now we're going to add Airplay support for Itunes.

sudo apt-get install autoconf automake avahi-daemon build-essential git libasound2-dev libavahi-client-dev libconfig-dev libdaemon-dev libpopt-dev libssl-dev libtool xmltoman

git clone https://github.com/mikebrady/shairport-sync.git

cd shairport-sync

autoreconf -i -f

./configure --with-alsa --with-avahi --with-ssl=openssl --with-systemd --with-metadata

make

sudo make install

This may take some time.

Once it's completed we just need to make sure the service runs on restart.

sudo systemctl enable shairport-sync

Give it a reboot and it should all be running nice and happy.

You should be able to see the device in Spotify and Itunes as shown below.



Thanks to the Raspotify people and Jeff Thompson for my inspiration



Your Own Cloud Server

 So many different cloud storage solutions out there such as Dropbox, Google Drive, One Drive and so on. But what if you want to manage all your data yourself, in the comfort of your own home, NextCloud could be just what you're looking for.



In this article,  I'm going to go through how to setup your own cloud server at home, you need an install of Linux, I've used Ubuntu Mini for this, you need to setup a static IP for the computer that is going to be the cloud server and you also need to forward ports 80 and 443 to that IP address. If you can't install Linux and don't know how to forward the ports then this isn't for you.

The only thing you really need to do during the installation is enable the ssh server so you can do the rest remotely.

The computer I'm using is a small form factor machine with a 250GB SSD and an external RAID enclosure with 2 x 4TB drives connected by USB

Plug the RAID device and the run dmesg shows the RAID device on my machine at /dev/sda

As it's a big drive we need to partition using 

sudo parted /dev/sda

mklabel gpt

mkpart ext4 0% 100%

quit

Now time to format it with 

sudo mkfs.ext4 /dev/sda

This will give you an output similar to this:

Found a gpt partition table in /dev/sda

Proceed anyway? (y/N) y

Creating filesystem with 976740352 4k blocks and 244187136 inodes

Filesystem UUID: 8da4f15d-2def-4cb9-ab7f-c972479529bd

Superblock backups stored on blocks:

        32768, 98304, 163840, 229376, 294912, 819200, 884736, 1605632, 2654208,

        4096000, 7962624, 11239424, 20480000, 23887872, 71663616, 78675968,

        102400000, 214990848, 512000000, 550731776, 644972544

Allocating group tables: done

Writing inode tables: done

Creating journal (262144 blocks): done

Writing superblocks and filesystem accounting information: done


Copy that UUID number, it will be different for you, we will now be modifying the fstab file with 


sudo nano /etc/fstab

Add a line like this to the end, using your UUID.


UUID=8da4f15d-2def-4cb9-ab7f-c972479529bd    /mnt/Data    ext4    defaults,noatime  0       1

Then CTRL X then Y and enter to save.


Make the mount point with;

sudo mkdir /mnt/Data

Then run sudo mount -a to mount the drive.

If you run df -h you should see something like this which shows the RAID drive up and running.


Filesystem      Size  Used Avail Use% Mounted on

udev            3.9G     0  3.9G   0% /dev

tmpfs           786M  820K  785M   1% /run

/dev/sdb5       228G  3.9G  213G   2% /

tmpfs           3.9G     0  3.9G   0% /dev/shm

tmpfs           5.0M     0  5.0M   0% /run/lock

tmpfs           3.9G     0  3.9G   0% /sys/fs/cgroup

/dev/sdb1       511M  4.0K  511M   1% /boot/efi

tmpfs           786M     0  786M   0% /run/user/1000

/dev/sda        3.6T   89M  3.4T   1% /mnt/Data




We're now going to create two directories, one for the Apache web server and one for the NextCloud data.

sudo mkdir /mnt/Data/www

sudo mkdir /mnt/Data/NextCloud


Now we create a symbolic link in the /var directory which points to the www directory we just created.

ln -s /mnt/Data/www/ /var/www

For now we are just going to set the permissions to 0777 with:

chmod 0750 -R /mnt/Data

Now it's time to start installing the required software to get our cloud server running.

sudo -s

apt update && apt upgrade

apt install ssh screen apache2 php mariadb-server php-fpm php-pear php-gd php-mysql php-redis php-curl php-json php-mbstring unrar lame mediainfo subversion ffmpeg redis software-properties-common mc net-tools unzip ufw curl  mc  php-zip -y


Time to secure the database with:

mysql_secure_installation

You should then see the following


NOTE: RUNNING ALL PARTS OF THIS SCRIPT IS RECOMMENDED FOR ALL MariaDB

      SERVERS IN PRODUCTION USE!  PLEASE READ EACH STEP CAREFULLY!

In order to log into MariaDB to secure it, we'll need the current

password for the root user.  If you've just installed MariaDB, and

you haven't set the root password yet, the password will be blank,

so you should just press enter here.


Enter current password for root (enter for none): 

OK, successfully used password, moving on...


Setting the root password ensures that nobody can log into the MariaDB

root user without the proper authorisation.


You already have a root password set, so you can safely answer 'n'.

Change the root password? [Y/n] n

 ... skipping.

By default, a MariaDB installation has an anonymous user, allowing anyone

to log into MariaDB without having to have a user account created for

them.  This is intended only for testing, and to make the installation

go a bit smoother.  You should remove them before moving into a

production environment.


Remove anonymous users? [Y/n] y

 ... Success!

Normally, root should only be allowed to connect from 'localhost'.  This

ensures that someone cannot guess at the root password from the network.

Disallow root login remotely? [Y/n] y

 ... Success!

By default, MariaDB comes with a database named 'test' that anyone can

access.  This is also intended only for testing, and should be removed

before moving into a production environment.

Remove test database and access to it? [Y/n] y

 - Dropping test database...

 ... Success!

 - Removing privileges on test database...

 ... Success!

Reloading the privilege tables will ensure that all changes made so far

will take effect immediately.

Reload privilege tables now? [Y/n] y

 ... Success!

Cleaning up...

All done!  If you've completed all of the above steps, your MariaDB

installation should now be secure.



Thanks for using MariaDB!



Now we create the database for the cloud server with the following, replace password with a good strong password of your own.


mysql -u root -p

<enter password>

CREATE USER 'nextcloud'@'localhost' IDENTIFIED BY 'password';

GRANT ALL PRIVILEGES ON nextcloud.* TO 'nextcloud'@'localhost' WITH GRANT OPTION;

exit

Little bit of file editing now with the following :

nano  /etc/mysql/conf.d/mysql.cnf

Add this to the bottom of the file and then save it:

[mysqld]

group_concat_max_len=8192

innodb_flush_log_at_trx_commit = 2


nano /etc/php/7.4/apache2/php.ini

Change the following lines to match shown below, the time zone one should be changed for your part of the world.

max_execution_time = 120

memory_limit = -1

date.timezone = Europe/London


nano /etc/php/7.4/cli/php.ini

Change the following lines to match shown below, the time zone one should be changed for your part of the world.

max_execution_time = 120

date.timezone = Europe/London

Time now to make the config file for the apache web server:

nano /etc/apache2/sites-available/nextcloud.conf

Add this in changing the ServerName and ServerAlias to your server name, you can use a dynamic host such as no-ip or duckdns to get an domain name, I use my NAS drive to provide one.


<VirtualHost *:80>

ServerName your_domain

ServerAlias www.your_domain

    <Directory /var/www/nextcloud/>

        Options FollowSymLinks

        AllowOverride All

        Order allow,deny

        allow from all

    </Directory>

    DocumentRoot /var/www/nextcloud

</VirtualHost>



Let's get the Nextcloud software installed:

cd /var/www

wget https://download.nextcloud.com/server/releases/nextcloud-23.0.0.zip

unzip nextcloud-23.0.0.zip

rm nextcloud-23.0.0.zip

Set up permissions

chmod 0750 -R /var/www/

chmod 0750 -R /mnt/Data/NextCloud/

chown -R www-data:www-data /mnt/Data/NextCloud/

chown -R www-data:www-data /var/www/


Setup the firewall rules now with:

ufw default deny incoming

ufw default allow outgoing

ufw allow ssh

ufw allow 80

ufw allow 443

ufw enable



Time now to activate the server config

a2dissite 000-default.conf

a2ensite nextcloud.conf

a2enmod proxy_fcgi setenvif

a2enconf php7.4-fpm

a2enmod rewrite

systemctl restart php7.4-fpm

systemctl restart apache2

systemctl restart mysql


Now to setup some ssl security

apt install certbot python3-certbot-apache


Then just type certbot followed by enter.

And answer the questions.

On the screen that says "Which names would you like to activate HTTPS for" you should see  the names of the ones you entered in the Apache config file earlier. Just press enter here.

And then select 2 to create a redirect.

That so far is all the installation done, now it's time to open up a web browser and point it to the domain you created for the cloud server, this is the dynamic dns one.


http://servername:

Fill in all the details requested and make sure you change the data path to 

/mnt/Data/NextCloud or whatever you have set yours to.

Once that's all done you can install the desktop client and the mobile client and have a play around. That's all your data under your control.





Saturday, 17 April 2021

PiCorder (The Next Generation)

The original PiCorder worked, took ages to start recording and I couldn't hear what I was recording as it was being recorded, it was time for a rethink. 

I decided to throw away the original idea and add a small USB sound card, this is what I got in all for it, apart from the Raspberry Pi Zero W of course.

These are fantastic, reversible USB micro leads, not USB C, USB micro, they can go in either way around. 

I got them from Amazon, £7.99 for 2, there are probably other places so please shop around/
This is the mic I got, again from Amazon, £7.59, you can probably use any mic with a 3.5mm jack, I didn't have one so this did the job.
Nice little case for it all to go in, as it's transparent you can use the onboard LED as a sort of status thingy, Amazon again and £8.99


Then there's the sound card, there's quite a few of these about, I got two and they seem to work quite well to be fair. Again from Amazon at a cost of £7.59.


You don't have to get one of these but in my mind it makes the sound card fit better with the case. Cost for the two is £5.10 from Amazon.









Power was the next thing on my shopping list, I got one of these, mainly because I liked the look of it and if you press the test button on it then it turns the power back on, more on that later. I managed to get one from Morrisons at £9.99.













And last but not least apart from the Raspberry Pi itself was something to give me a bit of directionality without being too big and intrusive and was light. I looked at bullet mics and parabolic dishes and although the dish itself probably gives the best results I fell back on the idea of the really old hearing aids, basically a funnel. I found these in Poundland and managed to get some grey ones.

You need a micro SD card too of course, I got a 32GB one, I would suggest getting a decent make, I got some cheap ones and they gave up after about a week.




Put together will all the magic stuff from a glue gun and the old favourite Blu Tack and it looks like this, the special effect guys from Blakes 7 couldn't have done better. You have a headphone socket so that you can hear what you're recording and you can collapse the funnel back to make it less obtrusive. It's not brilliant but it works, the funnel does get rid of some outside noise and I'll include some sound samples later on.

I also added some small push buttons, top one is connected to GPIO 3 and ground, the bottom to GPIO 13 and ground. I soldered these directly to the board but you can break it and the warranty is void of course.







Time to put it all together now, I'm not going through how to install the OS onto the SD card, I used Raspbian Lite for it, don't really need a desktop environment and it's all set up by SSH so make sure that's enabled. 

We're going to have to get the sound card working first and change the playback and sound levels, run the following:

sudo nano /usr/share/alsa/alsa.conf

defaults.ctl.card 0

defaults.pcm.card 0

Change these to a 1 as shown below.

defaults.ctl.card 1

defaults.pcm.card 1



Run sudo alsamixer and you should see this, select the Speaker and Mic and up the levels and we are now ready to get on with the rest.






We're going to turn off bluetooth as this seemed to be the cause of some electrical noise.

Open up the /boot/config.txt file with:

sudo nano /boot/config.txt

Add the following to the bottom of the file

# Disable bluetooth
dtoverlay=disable-bt

# Allows power off and on
dtoverlay=gpio-shutdown

Now we remove the bluetooth software

sudo systemctl disable hciuart.service

sudo systemctl disable bluealsa.service

sudo systemctl disable bluetooth.service

 sudo apt-get purge bluez -y

sudo apt-get autoremove -y



Now reboot to continue, once it's back up you should find a press of the top button will shut the Pi down and once it's closed down completely the status lights on the charger will go off. Press the test button on the charger and the Pi will come back on.

I've made a small script called mtbootme which is in the bin folder, makes it easier to add things when it boots up, just run sudo nano /bin/mtbootme and add the following lines



# Turns the light off

echo 0 >/sys/class/leds/led0/brightness

# Makes the light flash

echo heartbeat >/sys/class/leds/led0/trigger

Save it and make it executable with sudo chmod +x /bin/mtbootme

Now we need a way of recording the sound and also of being able to monitor it while it's recording. There's probably a better way of doing it but I came up with this, there's about a second delay.



The bit of shell script I use checks for a file number, if it's not there it starts at 1, if it is there it adds a 1 to it. 

sudo nano /bin/mtcapture

Paste this lot in

#!/bin/bash

# shuts down the wifi

ifconfig wlan0 down

# Turns the LED on fully

echo 0 >/sys/class/leds/led0/brightness

echo 1 >/sys/class/leds/led0/brightness

# sorts the file number

FILE=/share/filenum

if [ -f "$FILE" ]; then

    echo "$FILE exists."

else

    echo "$FILE does not exist."

echo "0"> /share/filenum

fi

read newfile < /share/filenum

echo $newfile

newfile=$((newfile+1))

echo $newfile > /share/filenum

# Records the noises

arecord -f cd - | tee /share/AudioTux1-$newfile.wav | aplay -  &

echo $newfile

# updates the file number

echo $newfile > /share/filenum



Make it executable with sudo chmod +x /bin/mtcapture

That's how we start it recording, don't run this just yet as it will turn the wifi off and you'll lose your connection or rem out the wifi line while testing.



Now we do the stop recording file

sudo nano /bin/mtstop

#!/bin/bash

# Kill all recording services

pkill mtcapture

pkill mtcapture

pkill arecord

pkill aplay

# Starts up the wifi

ifconfig wlan0 up

# Flashes the green light so we know recording has stopped

echo 0 >/sys/class/leds/led0/brightness

echo heartbeat >/sys/class/leds/led0/trigger



Save it and make it executable again with sudo chmod +x /bin/mtstop



A bit of python now to monitor the stop start button.

sudo nano record.py

This lot goes in here.

# !/bin/python

import RPi.GPIO as GPIO

import time

from subprocess import call

import os

GPIO.setmode(GPIO.BCM)

GPIO.setup(13,GPIO.IN,pull_up_down=GPIO.PUD_UP)

flag = False

while True:

                input = GPIO.input(13)

                if(input == False):

                        if(flag == False):

                                os.system("/bin/mtcapture")

                                flag = True

                                time.sleep(0.4)

                        else:

                                os.system("/bin/mtstop")

                                flag = False



We don't need to make this executable to run it.

Finally we edit the rc.local file to get things working on startup


sudo nano /etc/rc.local


Add these two lines just before the exit 0 at the bottom

python2 /root/record.py &

/bin/mtbootme &


Save it and reboot and you're ready to go, one last thing I've done is to install samba so I can pull the files off it. All the recordings are saved in the directory /share.

Install Samba and MC, it's one of the first things I install as it makes navigating the structure and editing really easy.

sudo apt install samba mc

Once done edit the samba config file


sudo nano /etc/samba/smb.conf


Add this to the bottom[Shares]

path = /share

public = yes

browseable = yes

writeable = yes

delete readonly = yes

force create mode = 777

force directory mode = 777

writeable = yes

directory mode = 777

create mode = 777


Save it and restart samba with sudo service smbd restart


And you are now ready to go, once you've powered it up the green status LED should be flashing, plus some headphones into the socket and press the lower button and it should start recording, you'll hear a delayed sound in the headphones, press it again and it will stop.

It's not supposed to be a professional bit of equipment, it's small, it's light and it sort of works and more than anything it's a bit of fun and it will get you more involved with nature.

Advantages of the funnel at the end are that it's completely collapsible, you can put it in a pocket and fold it over as shown below and it still works. Disadvantages are that you look like a mad professor when you're out and about with it.


And finally some sample sounds, there's a bit of noise in the background which is from a nearby industrial unit,



Sunday, 28 March 2021

PiCorder

I enjoy getting out and about when I can, nature reserves are a great place to go and I've thought a while about recording birdsong and other noises such as rivers and so on. I could use a phone but where's the fun in that and then once you get the phone out there's the distractions of social media. It's nice to leave those things behind.

I decided to knock up a sound recorder using a Raspberry Pi Zero W, it's never going to be brilliant, there's no display or controls on it so the sound is a fixed level but it had to be tried.



I got hold of one of these from Amazon, no drivers needed, just plug it in and it will work is what was said everywhere. Not quite really but in the end it wasn't too hard to get sorted.

I followed all the initial instructions and nothing happened, just an error so more searching on the Google thing found me this.


sudo nano /usr/share/alsa/alsa.conf

defaults.ctl.card 0

defaults.pcm.card 0

Change these to a 1 as shown below.

defaults.ctl.card 1

defaults.pcm.card 1

Save the file and it, sort of. Loads of noise on the recordings and suggestions of adding capacitors across the USB ports to dampen it down seemed drastic. Not a lot seemed to work, looked like it was going to be a complete failure.

So I had a poo and it came to me, first thing was get the recording level
up, I'm running everything here as root, there's nothing on here that is precious.

Run alsamixer and you should see this:

Press F4 to select the capture device and using the arrow keys increase the gain to the top as shown below.


Press escape to leave it.

As mentioned before, I was getting loads of noise when I tried this earlier, I decided to hard wire power and a record button onto the Pi, this meant soldering the power wires to the board on pins 2 and 6, you can see the complete list of pins here.

And the stop start button soldered to pins 36 and 34 (GPIO 16 and Ground)  Don't blame me if you break your Pi while doing this. 

I got hold of one of these so I could connect the mic into the Pi, no cables needed, again from them Amazon people.

Then I decided that as I wanted to keep power usage down I would disable the bluetooth connection and remove the bluetooth software.



Open the config.txt file with

sudo nano /boot/config.txt and then add this to the bottom of the file:


# Disable Bluetooth

dtoverlay=disable-bt

Save and close it then run the following to remove all the bluetooth stuff.

sudo systemctl disable hciuart.service

sudo systemctl disable bluealsa.service

sudo systemctl disable bluetooth.service

 sudo apt-get purge bluez -y

sudo apt-get autoremove -y

I rebooted and carried out a test recording and there was no electrical noise apart from the odd regular buzz, I disabled the wifi and retested and this time no noise at all.

It was now time to stick it in a box and make it work.

I needed a way of getting the files off afterwards, easiest option was install samba with 

apt install samba

Create a directory with 

mkdir /share

Open the samba config with

nano /etc/samba/smb.conf

Add the following at the bottom

[Sounds]

path = /share

public = yes

writeable = yes

browseable = yes

Restart Samba with service smbd restart


I decided to create a sound recording service with:

nano /etc/systemd/system/soundrec.service


[Unit]

Description=Sound Recording

[Service]

ExecStart=/bin/mtcapture

WorkingDirectory=/share

StandardOutput=inherit

StandardError=inherit

Restart=always

User=root

[Install]

WantedBy=multi-user.target


I'm not enabling the service to auto start

Create some files in the bin folder:

nano /bin/mtstart

#!/bin/bash

# shuts down the wifi

ifconfig wlan0 down

service soundrec start

# sleep 1

echo 0 >/sys/class/leds/led0/brightness

# Makes the green LED flash so we know it's recording

echo heartbeat >/sys/class/leds/led0/trigger


nano /bin/mtstop

#!/bin/bash

service soundrec stop

# Starts up the wifi

ifconfig wlan0 up

# sleep 1

echo 0 >/sys/class/leds/led0/brightness

sleep 3

# Leaves the green LED on so we know it's finished

echo 1 >/sys/class/leds/led0/brightness


nano /bin/mtcapture

#!/bin/bash

for (( ; ; ))

do

FILE=/share/filenum

if [ -f "$FILE" ]; then

    echo "$FILE exists."

else

    echo "$FILE does not exist."

echo "0"> /share/filenum

fi

read newfile < /share/filenum

echo $newfile

newfile=$((newfile+1))

echo $newfile > /share/filenum

arecord -f cd /share/AudioTux1-$newfile.wav

done

This increments the file number each time it's run so we can have as many files as we want until we run out of space.



You need to make all these executable with chmod +x filename


Then a little bit of python to get it working

nano record.py


# !/bin/python

import RPi.GPIO as GPIO

import time

from subprocess import call

import os

GPIO.setmode(GPIO.BCM)

GPIO.setup(16,GPIO.IN,pull_up_down=GPIO.PUD_UP)


flag = False

while True:

                input = GPIO.input(16)

                if(input == False):

                        if(flag == False):

                                print "Start"

                                os.system("/bin/mtstart")

                                flag = True

                                time.sleep(0.4)

                        else:

                                print "Stop"

                                os.system("/bin/mtstop")

                                flag = False

                                time.sleep(0.4)



Open up the rc.local file with

nano /etc/rc.local

And add the following just before the exit 0 at the bottom

python2 /root/record.py &


Then restart it, once it's up and running, pressing the button connected to the GPIO pins should start it recording. A second press will stop if, while it's recording the wifi will be disabled. If you want you can add a second button connected to pins 5 and 6 (GPIO 3 and Ground), add the following to the bottom of the /boot/config.txt file.

dtoverlay=gpio-shutdown

Reboot and on press on the button will shut the pi down, a second press will restart it.


Here's the finished item, it's not overly pretty as I got the wrong case but it works, the USB mic at the top can be unplugged and put on an extension cable and possibly fitted into a parabolic dish, but that's for another time.


It does work, seems to take ages to start recording as the service has to start and once started it then takes ages to stop the service.

It needed a rethink and so was born "PiCorder, the Next Generation"

Instructions are here.