DIY Raspberry Pi based Media Box

This was posted on 2023-07-08


This project is focused on building a system for my Raspberry Pi so that it can do the following things.

Setting up the Raspberry Pi

I initially got started with a new Raspbian lite OS and connect through SSH

sudo apt-get update
sudo apt-get upgrade

Mounting USB Drives

Check the drives currently mounted

sudo cat /proc/mounts

  or

sudo fdisk -l

and look for the partition starting with /dev/ that has the expected file size, e.g. /dev/sda/.

sudo mkdir /mnt/MediaBox
sudo mount /dev/sda1 /mnt/MediaBox

Gety UUID to Set up Automatic Mounting

sudo blkid
sudo nano /etc/fstab

Add following line with UUID, mount location and file system type 

UUID=27705CE4072C15B2 /mnt/MediaBox ntfs defaults,auto,users,rw,nofail 0 0

Setting up a location to maintain server files

mkdir server
cd server

mkdir static
mkdir templates

Setting static IP

hostname -I
ip r
grep 'namesever' /etc/resolv.conf

nano /etc/dhcpcd.conf

Then appended the following lines to the end of the file

interface wlan0
static ip_address=192.168.1.30/24
static routers=192.168.1.1
static domain_name_servers=1.1.1.1

interface eth0
static ip_address=192.168.1.32/24
static routers=192.168.1.1
static domain_name_servers=1.1.1.1
sudo reboot

Setting up NAS (Samba server)

sudo apt-get install samba samba-common-bin
sudo nano /etc/samba/smb.conf
[Media]
path = /mnt/MediaBox
writeable=Yes
create mask=0777
directory mask=0777
public=no

[Pi]
path = /home/pi
writeable=Yes
create mask=0777
directory mask=0777
public=no

Creating user account with username 'pi' and password 'raspberry'

sudo smbpasswd -a pi
sudo systemctl restart smbd

Setting up Transmission

sudo apt-get install transmission-daemon

Setting up transmission

sudo systemctl stop transmission-daemon
sudo nano /etc/transmission-daemon/settings.json

How to Setup Transmission on the Raspberry Pi - Pi My Life Up

Install PyEnv

sudo apt install git
curl https://pyenv.run | bash
sudo apt-get install --yes libssl-dev zlib1g-dev libbz2-dev libreadline-dev libsqlite3-dev llvm libncurses5-dev libncursesw5-dev xz-utils tk-dev libgdbm-dev lzma lzma-dev tcl-dev libxml2-dev libxmlsec1-dev libffi-dev liblzma-dev wget curl make build-essential openssl

pyenv install 3.7.12
cd /mnt/MediaBox/MediaBox
pyenv local 3.7.12

Setting up Flask Server

sudo apt-get install python3-flask

pip install schedule -y
pip install logger -y
pip install Flask -y
pip install telepot -y
pip install Pillow -y
pip install feedparser -y
pip install numpy -y
pip install opencv-python -y
pip install urllib3 -y
pip install imaplib2 -y
pip install transmission-rpc -y
pip install openai -y
pip install MySQL-python -y
pip install dirsync -y

Setting up TensorFlow Lite (May not be needed)

sudo apt update
sudo apt upgrade -y

curl https://packages.cloud.google.com/apt/doc/apt-key.gpg | sudo apt-key add -
echo 'deb https://packages.cloud.google.com/apt coral-edgetpu-stable main' | sudo tee /etc/apt/sources.list.d/coral-edgetpu.list
sudo apt-get update

sudo apt install python3-tflite-runtime libatlas-base-dev

Setting up TensorFlow 2

Guide: Sam Westby

sudo apt-get install -y libhdf5-dev libc-ares-dev libeigen3-dev gcc gfortran libgfortran5 libatlas3-base libatlas-base-dev libopenblas-dev libopenblas-base libblas-dev liblapack-dev cython3 libatlas-base-dev openmpi-bin libopenmpi-dev python3-dev

#bookworm
sudo apt-get install -y libhdf5-dev libc-ares-dev libeigen3-dev gcc gfortran libgfortran5 libatlas3-base libatlas-base-dev libopenblas-dev libblas-dev liblapack-dev cython3 libatlas-base-dev openmpi-bin libopenmpi-dev python3-dev

pip install -U wheel mock six
uname -m
cat /etc/os-release
python -V

Output:

armv7l
PRETTY_NAME='Raspbian GNU/Linux 11 (bullseye)'
NAME='Raspbian GNU/Linux'
VERSION_ID='11'
VERSION='11 (bullseye)'
VERSION_CODENAME=bullseye
ID=raspbian
ID_LIKE=debian
HOME_URL='http://www.raspbian.org/'
SUPPORT_URL='http://www.raspbian.org/RaspbianForums'
BUG_REPORT_URL='http://www.raspbian.org/RaspbianBugs'
Python 3.9.2

Wheels: Tensorflow-bin/previous_versions at main · PINTO0309/Tensorflow-bin · GitHub

wget https://raw.githubusercontent.com/PINTO0309/Tensorflow-bin/main/previous_versions/download_tensorflow-2.5.0-cp37-none-linux_armv7l.sh
sudo chmod +x download_tensorflow-2.5.0-cp37-none-linux_armv7l.sh
./download_tensorflow-2.5.0-cp37-none-linux_armv7l.sh
pip install tensorflow-2.5.0-cp37-none-linux_armv7l.whl

Depreciation Errors

pip install protobuf==3.20.*

pip uninstall h5py
pip install h5py

sudo apt-get install libopenjp2-7

SQL Database

Guide: Setup a Raspberry Pi MYSQL Database - Pi My Life Up

sudo apt install mariadb-server

Set Authorization

sudo mysql_secure_installation

Program

The program was written in Python. The momst up to date file can be seen on my Github: iamJohnnySam/MediaBox (github.com)

Below are some highlights

Checking Email

class CCTVChecker:
    folderSize = 0
    output = 0.000001
    outlook = imaplib.IMAP4_SSL('outlook.office365.com', 993)

    def __int__(self):
        for f in os.listdir(settings.cctv_download):
            self.folderSize = self.folderSize + os.path.getsize(os.path.join(settings.cctv_download, f))
        print('Current Folder size -', '{:,}'.format(self.folderSize))

    def log_in(self, mb):
        try:
            self.outlook.login(settings.em, settings.pw)
        except:
            pass
        self.outlook.select(mailbox=mb, readonly=False)

    def get_attachment(self, data):
        msg = email.message_from_bytes(data[0][1])
        date = msg['Date']
        date = date.replace(' +0530', '')

        att_path = 'No attachment found.'
        for part in msg.walk():
            if part.get_content_maintype() == 'multipart':
                continue
            if part.get('Content-Disposition') is None:
                continue

            filename = part.get_filename()
            save_as = date + ' ' + filename
            att_path = os.path.join(settings.cctv_download, save_as)

            image = part.get_payload(decode=True)
            fp = open(att_path, 'wb')
            fp.write(image)
            fp.close()

            settings.bot.sendPhoto(settings.telepot_chat, photo=open(att_path, 'rb'))
            settings.bot.sendMessage(settings.telepot_chat, 'Sus lvl ' + str(self.output))

            if sus:
                self.folderSize = self.folderSize + os.path.getsize(att_path)
                print(filename, self.output, '{:,}'.format(self.folderSize))

    def scan_mail(self, scan_type, get_attach, delete):
        (result, messages) = self.outlook.search(None, scan_type)

        if result == 'OK':
            for message in messages[0].split():
                try:
                    ret, data = self.outlook.fetch(message, '(RFC822)')
                except:
                    print('No new emails to read.')
                    self.outlook.connection.close()
                    exit()

                if get_attach:
                    self.get_attachment(data)

                if delete:
                    self.outlook.store(message, '+FLAGS', 'Deleted')
                    self.outlook.expunge()

    def send_email(self, send_to, body):
        msg = MIMEMultipart()
        msg['From'] = settings.em
        msg['To'] = ', '.join(send_to)
        msg['Date'] = formatdate(localtime=True)
        msg['Subject'] = 'Suspicious Activity'

        msg.attach(MIMEText(body, 'html'))

        for f in os.listdir(settings.cctv_download):
            with open(os.path.join(settings.cctv_download, f), 'rb') as fil:
                part = MIMEApplication(fil.read(), Name=basename(f))
            part['Content-Disposition'] = 'attachment; filename='%s'' % basename(f)
            msg.attach(part)

        context = ssl.create_default_context()
        server = smtplib.SMTP('smtp.office365.com', 587)
        server.starttls(context=context)
        server.login(settings.em, settings.pw)
        server.sendmail(settings.em, send_to, msg.as_string())
        server.close()

    def run_code(self):
        self.log_in('Security')
        self.scan_mail('UnSeen', True, True)
        self.outlook.close()

        if self.folderSize > 0:
        send_to = [settings.email1, settings.email2]
        body = '''Hi,

               We detected some activity on the CCTV in the last 24 hours

             
        '''

        self.send_email(send_to, body)

Flask Boilerplate code

from flask import Flask, render_template

app = Flask(__name__)


@app.route('/')
def index():
    return render_template('index.html')


@app.route('/Movies/')
def movies():
    return render_template('movies.html')

ChatGPT for writing starter code: https://chat.openai.com/share/01f6b2bd-0edb-477b-9369-48855efa367b

References

Similar Posts

See other projects and posts in the same category as this post

blog item Creating a Personal Assistant to automate my lifestyle
Designing, Building and Programming a personal assistant to automate my lifestyle.
python, machine learning, programming, smart home 2024-01-13 | Read More....
blog item DIY Raspberry Pi based Media Box
My effort at creating a system to unify the media around my house
raspberry pi, ssh, media 2023-07-08 | Read More....
blog item Home-made Raspberry Pi based Home Security System
A home made security solution that can be customized and expanded as needed
Raspberry Pi, Project, Home Security 2022-02-25 | Read More....
blog item Home-made Raspberry Pi based Media Center
A homemade solution for a networked media storage and madia playback
Raspberry Pi, Kodi, LibreELEC, Samba, Network Storage 2020-10-30 | Read More....
Comment Box is loading comments...