Ethereum Auth – Express + React

I’ve always been fascinated by Ethereum and what it can bring to the table. This article discusses how we can use MetaMask for user registration or sign-in on web portals.

One of the current problems with online systems is that users have to register on almost every website they use. This means that the user has to generate a new password for every registration. Usually, users keep the same password for every website they register with. This is a very dangerous strategy because the same password can be leaked or hacked, especially if the system they’re registering on is not secure. Example: passwords stored as plain text in the database.

Nowadays, web browsers like Google Chrome are generating secure passwords for you, and these passwords are saved on Google’s Cloud. In my opinion, this is more secure than the previously mentioned strategy, but still, one is saving passwords on a third party. Why should we trust Google with our passwords?

Another popular trend is the ‘Login with Google/Facebook/Outlook/Twitter etc.’ This is also a valid approach and again it is safer than using weak passwords but still one is depending on third parties. If for example, Facebook is down, then the users can’t use your system.

With Web3, we have the possibility for the user to sign up/login using a non-custodial wallet. For example, MetaMask. This means that the user/server does not have to connect to a third party to authenticate a particular user. Everything can be done in ‘offline’ mode. This is possible with the use of private keys.

Let’s explain the Sign Up/Login process in these simple steps:

  1. The User must have a wallet. In our example, MetaMask.
  2. The User now has access to his Public and Private Keys
  3. The User sends a message (containing his public key) to the server (backend) that s/he wants to Sign Up/Login
  4. Backend checks whether the public key exists in the database. Basically, whether the user exists or not
  5. Backend generates a unique random code for this user and sets a five-minute timer
  6. Backend notifies the user to ‘sign’ the generated random code in the next five minutes
  7. The User (using his private key) signs the random code and sends the signature to the backend server
  8. Backend checks whether the signature was truly signed by the user (Public Key is generated from the signature)
  9. If the signature is valid, a JWT is generated and sent to the user. This token will be used for future requests by the user to have access to restricted end points.

This is a video demonstrating the mentioned process:

As one can see, we did not make use of third parties. This means that web3 projects don’t have to rely on third parties like Auth0. Also, the user does not have to generate a password for every website. He can use the same wallet to access multiple portals.

So are there any disadvantages? Yes obviously there are:

  • More difficult for the user to understand how to sign up/log in
  • Third parties like Auth0 is will make your life easier (as a developer)
  • The user must have a wallet installed
  • The user has to trust the message he is going to sign. If the signature is leaked, it can be used for malicious behaviour.

If you want to check the implementation you can visit the link below:

Github Link:


Decentralised Games

There’s been a lot of hype around NFTs and Web3. Today, I’ll discuss the issues and myths surrounding NFTs in games, as well as how to create a truly decentralised game.

Let’s get started.

In 2007, a friend of mine used SA-MP to create a mod for GTA San Andreas. He designed an online RPG in which you must work to own property, guns, or cars. You might apply for various jobs, including taxi driver, rubbish collector, policeman, vehicle dealer, and driving instructor. The fact that it was geared in a multiplayer context was particularly appealing. This game had approximately ten active gamers, and we used to spend a lot of time playing this mod. Another nice feature was that purchased assets were saved on the server and password-protected for future use. Virtual money was obviously involved, which was also stored per account. Unfortunately, when the server stopped working, all of these assets were lost. All this hard work was lost.

One can argue that this can solved by using smart contracts on public blockchains. Example storing persistent data on Ethereum/Polygon. But could it really be solved that easilly?

Ok. Let’s imagine some cool scenarios. In the future Rockstar implements NFTs for GTA online and the majority of the stuff is saved on the blockchain. Example: Ownership of Cars/Planes/Helicopters etc. Or Activision creates NFTs for Call of Duty online. Example: Weapon skins, Trophies etc.. Or EA Sports will turn all the football players into NFTs. With these scenarios, there will be an opportunity for open trade between all these virtual assets. People can buy directly from each other, swap with other tokens, convert NFTs to Bitcoin and then to Euros, etc. Well, this sounds all exciting but what happens when the online servers shut down? All these NFTs are rendered useless. All that hard work is lost. The only advantage during this process was that people could trade freely on the blockchain, and one could monitor the number of NTFs in circulation. But is this really decentralised?

It is possible to argue that this problem can be remedied by making the code open-source and allowing others to host their own servers. Now I have serious doubts about this. Do you think Rockstar/Activision/EA Sports will open-source their code? Most likely not. Even if they do, hosting such games will require a lot of resources, and there’s a good chance they’ll rely on third-party services, such as Oracles. Another issue with open-source code is that it is not always free to use, even if it is publicly available. For example, the game Sunflower-land (which runs on Polygon) contains open-source code, but it is clearly noted on GitHub that the assets/code cannot be reused. Is this really a decentralised system?

Now there is another problem with NFTs. Wait what? Another problem? Sadly Yes.

Due to storage constraints, 2D sprites and 3D assets cannot be stored on the blockchain. You can save the hash of these assets instead. So, the main question is: where will these assets be kept? One argument is that they can be stored on centralised infrastructures, such as Google Cloud Storage. But shouldn’t our game be decentralised? One could argue that these assets should be backed up using IPFS or FileCoin, which unfortunately would further complicate the process. Also, IPFS does not guarantee that the file stored is indefinite. Is this truly a decentralised system?

Ok, that’s enough problems for now. But…….. I have to mention another problem. Some smart contracts are NOT self-governed. This means that some actions have to be processed by the contract’s creator. So basically, the contract has an owner (admin) that controls stuff. This is usually done to control or safeguard some processes. But again. Is this really decentralised?

So, as you can see, I’ve been asking the same question repeatedly. “IS THIS REALLY DECENTRALISED?”. I believe in understanding and solving the mentioned problems; we have to analyse what Satoshi did with Bitcoin. So, for sure Bitcoin is decentralised. No one can argue against this. Code is open source with an MIT license; people can freely host their own nodes, create wallets; mine, trade, etc. All of this stuff does not require third-party servers and is not governed by anyone. So, this means that decentralised games have to follow these principles outlined by Satoshi. Now I must admit that with games it’s a bit more complex.

Here are some guidelines that a decentralised game must follow:

  1. Game must be open source with an MIT License
  2. Game must be allowed to be played by different gameplay rules
  3. Hard work should not be lost
  4. Core infrastructure should not be dependent on third-party services

Game must be open source with an MIT License

This means that the game’s infrastructure and assets should be open source, with permissions for Commercial Use, Modification, Distribution, and Private Use. Anti-botting and other backend services should also be open to the public. This implies that if the original company stops supporting the game, developers can easily host or change it in the future. Any 2D/3D assets representing NFTs can be recovered.

Game must be allowed to be played by different gameplay rules

Back in the day, people used to collect Pokémon cards. Every Pokémon had its own ability. People were allowed to create their own rules to play with these cards. Obviously, there were the official guidelines, but they were not forced on the players. Same thing with Monopoly. You purchase the game with all the assets, but you can setup and play by your own rules.

In decentralised games, people should be allowed to either play by the official regulations or else create their own rules. In case the server running the official regulations gets shut down, people can still play the game freely. Also, people should be allowed to add on mods and connect with their preferred servers.

Hard work should not be lost

In case a server is down, players can easily shift to another server without losing data. For example, the Electrum Bitcoin wallet connects to a random node on startup. These nodes are hosted by different people and are not controlled by the same organisation. So, the code should be designed in a way to allow players to connect with different hosted infrastructures.

Core infrastructure should not be dependent on third-party services

Multiplayer games are a big headache. Running a multiplayer game on third-party servers like Firebase, Steam API, PhotonCloud will increase the chance of having the game shut down in the future. Ideally, the multiplayer infrastructure should be developed using open-source libraries such as Mirror Networking for Unity. Developers can freely host the code on servers without relying on mentioned parties.


As one can see, truly decentralised games are very hard to design & develop. I might have missed something in the above guidelines, but they have to be designed and developed as Satoshi once envisioned Bitcoin.

Watch the screen of all students in one webpage during online class

So, the problem is that during live online lessons, some students are not paying attention and probably they are doing something else on their PC. I am currently using MS Teams to deliver lectures and sometimes I ask students to share their screen with me during the session so that I can monitor what they are doing. The problem occurs when you have many students in one session. Asking every student one by one to share his/her screen is going to take some time and you are not constantly monitoring their work. So, we need to come with a better plan.

The idea is that every student must stream his/her screen to YouTube Live as unlisted (for privacy issues) and share the link with the teacher. Then, the teacher during the lesson can easily monitor the students’ screens in one webpage. We are going to build a web app using Google Forms for this.

Note: It is suggested that the students stream to YouTube as unlisted. This means that the YouTube link is changed for every session (privacy issues). Therefore, the student must share the updated link with the teacher before every session. Once again, we are going to mitigate this problem using Google Forms.

Tutorial for Students

Step 1: Install OBS:

Step 2: Set Sources to Display Capture. This should capture your screen without audio

Step 3: Go to

Step 4:  Press the Go Live button. For first time – It takes 24 hours to activate your account for live streaming. Once activated, you can go live instantly.

Step 5: Press the Edit button

Step 6: Change Visibility to Unlisted and press Save.

Step 7: Change Stream latency to ultra low-latency.

Step 8:  Copy the Stream Key

Step 9:  Go back to OBS and select Settings from the File menu

Step 10: Go in the Stream section, choose YouTube as service and paste the Stream Key (the code you copied from YouTube)

Step 11: Hit the Start Streaming button

Step 12: Go back to YouTube and copy the embed code by pressing the right click button on the live thumbnail

Step 13: Fill Up form shared by your teacher and paste the Embed Code.

Step 14:

Note 1: For the next lesson all you need to do is just open YouTube and OBS and press the Start Streaming button. Both applications should remember your settings. When you start streaming, copy again the embed code and update the same google sheets form provided by your teacher.

Note 2: When the live session ends, it is automatically stored in your YouTube account (as unlisted). You can delete live sessions from your account.

Tutorial for Teachers

Step 1: Create a Google Form as shown in video (webapp code is provided down below). Eventually you can duplicate forms for every class and code is automatically copied.

Step 2: Share Google Form with Students

Step 3: Load web app with embedded videos (provided by students)

Step 4: Before your next lecture, remind students to update embed code in previously shared form

Download Code:

Turn On/Off Lights Based On PC Power State

I bought the Philips Hue Bridge with Light Bars to make a cool lighting effect behind my PC monitors. You could easily control them via the Android App, and they look really cool.

The problem is that when I am on my PC, I must manually turn them on/off via the App. I wanted an automated system that handles these requests automatically. This means that whenever I turn on/wake my PC, they light up automatically. And, whenever I put my computer to sleep/shutdown, they turn off automatically.

Yes, I am a bit lazy….

Fortunately, the Hue system comes with an API which can be controlled easily through web requests. Tutorial can be found here:

With this API you can easily turn on/off the lights using code. So first, I created 2 PowerShell scripts (TurnOn/TurnOff). One script was responsible to turn on the lights and the other one to turn off the lights.

Using the Windows Task Scheduler, you can easily call these scripts automatically in various events like startup, user login, system locked, and system unlocked.

Windows Task Scheduler

The problem is that the shutdown event does not exist in the Task Scheduler, but one could call the TurnOff script from the Local Group Policy Editor.

Group Policy

Unfortunately, when I tried this technique, it failed to work for most of my tests. I even configured the group policy to run PowerShell scripts first at user Shutdown but all in vain.

Therefore, I had to come with a better technique.

Fortunately, using the API one could easily create schedules. This means that the Hue Bridge can run automatically commands at a specified time. These schedules can be even deleted which makes it perfect for us. Why? Here is my logic:

  1. On Windows Login turn on the lights
  2. Create an infinite loop:
    1. Create a schedule to turn off the lights automatically in the next 10 seconds
    2. Wait for 5 seconds. If the script is still running, delete the just created schedule and repeat from step a.
    3. If the script is not running (PC is turned off) – the schedule is not cancelled and therefore the schedule turns off both lights.

It works perfectly.

PC Waking Up - Lights Turning On Automatically
PC Turning Off - Lights Turning off Automatically

Here is the script to make this work. This script must be called using the Windows Task Scheduler. I used the below settings:

# Hue Bridge
$hueBridge = ""

# Username
$username = ''

function Switch-Lights($TurnOn){
  if($TurnOn -eq 0){
    #Command to Turn Off
    $apicontent= '{"on" : false}'
  else {
    $apicontent= '{"on" : true}'

  #Invoke commands
  Invoke-WebRequest -Method put -Uri "$($hueBridge)/$($username)/groups/1/action" -Body $apicontent
function Add-FutureEvent {
  #calculate future localtime
  $future_date = (Get-Date).AddSeconds(10)
  $date_format = $future_date.ToString("yyyy/MM/dd")
  $time_format =  $future_date.ToString("HH:mm:ss")
  $future_localtime = "$($date_format)T$($time_format)"

  #Command to Turn off
  '{  "name": "PC Auto Manager",
      "command": {
          "address": "/api/'+$username+'/groups/1/action",
          "method": "PUT",
          "body": {
              "on": false
      "localtime": "'+$future_localtime+'"                      

  #Invoke commands
  $response  = Invoke-RestMethod -Method post -Uri "$($hueBridge)/$($username)/schedules" -Body $apicontent
  #get id from json response 
  return  $

function Remove-Event($event_id){
  #Invoke commands
  Invoke-WebRequest -Method delete -Uri "$($hueBridge)/$($username)/schedules/$($event_id)" 

  Switch-Lights -TurnOn 1
  $event_id = Add-FutureEvent
  Start-Sleep -s 5 #in seconds
  Remove-Event -event_id $event_id

Happy Coding 🙂

Lightning Snacks

A Vending Machine using the Bitcoin Lightning Network on a Full Node Raspberry Pi

Problem Definition

Most vending snack machines are coin-operated. This leads to many drawbacks such as incorrect/no change, some coins are not recognized, management of coins by owner and no coins in your wallet.

Sometimes my colleagues ask me for some coins, and in return they give banknotes or pay me via Revolut. Why should we all go through this hassle if when can do online transactions? We can use Visa/Mastercard scanners attached with vending machines and people can buy snacks easily. Well, the problem is that for every authorized transaction, the bank takes a commission. Is it worth for the merchant to pay a commission for a cheap snack item? I don’t think so. Apart from that, this technique is not recommended because there might be hackers that can attach card sniffers to the vending machine intending to hijack your card. So, what’s the solution?

The Solution

Nowadays everyone owns a smartphone. With Bitcoin, you can have your own non-custodial wallet on your phone. You can do global transactions on decentralized platforms without making use of third-party APIs (banks) to verify transactions. Can we apply this technology to our vending machine? We can but it won’t be ideal. The problem lies in the transaction confirmation time and the transaction fees.

One confirmation (1 block) takes about 10 minutes and we usually assume that a transaction is fully confirmed when it is 6 blocks deep. This means that a full confirmation takes about 1 hour (10 minutes * 6 blocks). This is very fast when compared to traditional systems, but it won’t be ideal for our vending machine system. Imagine our client waiting 1 hour to buy some candy. Since snacks are not expensive, we can assume that one confirmation (1 block deep) is enough, but our client must still wait 10 minutes for the transaction to be processed.

The other problem relies in the transaction fees. Transaction fees are included with every Bitcoin transaction in order to have transactions processed by a miner and confirmed by the Bitcoin network. The space available for transactions in a block is currently limited to 1 MB. This means that to get your transaction processed quickly you must outbid other users. Therefore, it can get expensive to buy some snacks.

Bitcoin Cash (another cryptocurrency – fork of Bitcoin) simply solves these problems by increasing the block size and disabling the ‘replace by higher fee’ feature. Therefore, a transaction can be created with a lower transaction fee and once created, we can safely assume that the transaction is going to be placed in the next block. This might lead to other problems, but I don’t want to debate Bitcoin Cash vs Bitcoin in this article.

The Bitcoin Lightning Network (Layer 2 Protocol on Bitcoin) is the ideal solution for our vending snack machine. It is a decentralized network powered by smart contracts that enables instant payments with very low-cost transaction fees across participants. Lightning enables one to send very small funds in Bitcoin without custodial risk. Everyone can be part of the network by hosting and opening a channel with a node. When opening a channel, participants must commit an amount which is stored on the blockchain. Transactions then can be passed through multiple channels in a mesh network of payment channels. These transactions are not stored on the public blockchain and therefore the base layer fees are avoided. I must admit that it is a bit complicated to work with but once you understand what is happening, you will appreciate the principles behind this system.


Building the Prototype

For this project one used the Raspberry Pi 3 B+ with an external hard disk storing the entire Bitcoin testnet blockchain. The Bitcoin Lightning Network was installed using the Raspibolt tutorial and Python was used to develop the whole system. That is creating the GUI using a game engine called PyGame, interfacing with the LND network, connecting with the Coinbase API for price conversion, making invoices into QRCodes, recursively checking for payments and eventually turning the motors using GPIO commands for successful payments. The Eclair Mobile Testnet app was installed on my phone to test for the client perspective.


Description Link
3D printed some of the objects found in this project.


Official Raspberry Pi 7″ Touchscreen Display
Bitcoin Lighting Network on Raspberry Pi (RaspiBolt)
Python gRPC client for the Lightning Network Daemon
LND gRPC API Reference
Conversion from  Euro to Bitcoin
Python Game Engine for User Interface – PyGame
Raspberry pi motor library
NEMA 17 Motor
Shaft Holder Extension Rod
QR Code Generator
Android Eclair Mobile Testnet



This prototype clearly demonstrates that the Lightning Network is a potential solution for the problems mentioned before. One managed to buy snacks instantly with very low transaction fees. On average, every transaction fee was about 4 satoshis which is equivalent to 0.0002557 EUR (at the time of writing 1 BTC is equivalent to 6385 Euros). One problem that I constantly encountered was the inbound capacity limit which is described clearly here: Developers are working on this using a solution called Lightning Loops: In the future I want to test this prototype on the Bitcoin Mainnet using a 4GB Raspberry Pi 4 and experiment with the looping solution.

Thanks for reading 🙂

Photo booth – Raspberry Pi

Photo Booth using the Raspberry Pi and Pi Camera. Designed for 7″ touch screen. Just run  python code in Raspbian.

from __future__ import print_function
import pygame
import time
from picamera import PiCamera
import sys
from PIL import Image

import os


win = pygame.display.set_mode((0,0),pygame.FULLSCREEN)
camera = PiCamera()
camera.resolution = (800,800)
#camera.color_effects = (128,128) #turn camera to black and white

class button():
    def __init__(self, color, x,y,width,height, text=''):
        self.color = color
        self.x = x
        self.y = y
        self.width = width
        self.height = height
        self.text = text

    def draw(self,win,outline=None):
        #Call this method to draw the button on the screen
        if outline:
            pygame.draw.rect(win, outline,(self.x-2,self.y-2,self.width+4,self.height+4),0)

        pygame.draw.rect(win, self.color,(self.x,self.y,self.width,self.height),0)

        if self.text != '':
            font = pygame.font.SysFont('comicsans', 60)
            text = font.render(self.text, 1, (0,0,0))
            win.blit(text, (self.x + (self.width/2 - text.get_width()/2), self.y + (self.height/2 - text.get_height()/2)))

    def isOver(self, pos):
        #Pos is the mouse position or a tuple of (x,y) coordinates
        if pos[0] > self.x and pos[0]  self.y and pos[1] < self.y + self.height:
                return True

        return False

def redrawWindow():

def counterWindow():
        counterLabel.text = str(counter)
        counterLabel.text = "Smile"

def loadimage():
    global imagename
    img = pygame.image.load(imagename)
    img = pygame.transform.scale(img,(480,480))

def takePhoto():
    global showImage
    global counterActive
    global counter
    global imagename
    print("Take Photo")
    for x in range(4):

    files = [

    result ="RGB", (800, 800))

    for index, file in enumerate(files):
      path = os.path.expanduser(file)
      img =
      img.thumbnail((400, 400), Image.ANTIALIAS)
      x = index // 2 * 400
      y = index % 2 * 400
      w, h = img.size
      print('pos {0},{1} size {2},{3}'.format(x, y, w, h))
      result.paste(img, (x, y, x + w, y + h))

    imagename = str(round(time.time() * 1000)) +'.jpg'
    showImage = True
    counterActive = False
    counter = 6

def resetStatus():
    global counter
    global startProcess
    global counterActive
    global imageCounter

    counter = 6
    startProcess = True
    counterActive = False
    imageCounter = 0

run = True
counter = 6
startProcess = True
counterActive = False
showImage = False
greenButton = button((0,255,0),280,200,250,100,'Take Photos')
counterLabel = button((100,255,255),300,200,250,100,'0')
imageCounter = 0
imagename =""

while run:
    if(startProcess == True):
    elif(counterActive == True):
        counter = counter-1
    elif(showImage == True):
        imageCounter = imageCounter +1
        if(imageCounter == 15):


    if(counterActive == False):
        for event in pygame.event.get():
            pos = pygame.mouse.get_pos()

            if event.type == pygame.QUIT:
                run = False

            if event.type == pygame.MOUSEBUTTONDOWN:
                if greenButton.isOver(pos):
                    print("Clicked the button")
                    counterActive = True
                    startProcess = False

            if event.type == pygame.KEYDOWN:
                if event.key == pygame.K_ESCAPE:
                    run = False

    if(counter == 0):

Flask Server with GPIOs

Let’s say that you have a running Flask server and you want your user to control the state (on/off) of an LED via the GPIO. The following technique shows how to connect Flask server with a separate GPIO script using PID.

Download the whole project

Run the following two scripts at the same time using the terminal:

from flask import *
import os
import signal

app = Flask(__name__)

#create a route path for index page
def index():
    return render_template("index.html")

#create a route path for about page
def about():

    if 'name' in session: #if session 'name' exists
        print(session['name']) #print what's inside session[name]

        session.pop('name',None) #after printing, delete session name

    return render_template("aboutus.html") #render the html template aboutus

#/students accepts a get and post requests
def student():
    if(request.method == 'POST'): #if user fills a form
        studentName = request.form['studentname']
        if(studentName == "jimmy"):
            session["name"] = studentName #create session, name it 'name' and fill with studentName
            return redirect(url_for("about")) #redirect to about page
            return render_template("student.html") #render student template

        return render_template("student.html")#render student template

#routes with paramaters
def led(param=None):
    if(param == "on"): #if paramater is /led/on
        #read process id from text file generated by
        processId = int( #load the process id

        fh.write("1") #save 1 in text file. 1 means LED ON. 0 means LED Off

        #send signal to process id
        os.kill(processId, signal.SIGUSR1)
        return "LED ON"
    elif(param =="off"): # if paramater is /led/off
        #read process id from text file
        processId = int(


        #send signal to process id (ledscript)
        os.kill(processId, signal.SIGUSR1)
        return "LED OFF"
        return "LED MAIN PAGE"

if __name__ == "__main__":
    app.secret_key = 'asdfd!45sdf' #create secret key to secure sessions, host = "")

import RPi.GPIO as GPIO
import time
import traceback
import os
import signal

def Main():
        #when scripts runs create processid.txt
        fh.write(str(os.getpid())) #get current process id and store in file



        GPIO.setup(4, GPIO.OUT, initial = GPIO.LOW) #setup GPIO4 to low

        def handUSR1(signum,frame): #this function is automatically triggered from flask
            led = int(

            if(led == 0): #if 0 is found in text file
                print("LED OFF") #turn off led
                print("LED ON") #if not 0 (1) is found in text file
                GPIO.output(4,GPIO.HIGH) #turn on led

        signal.signal(signal.SIGUSR1,handUSR1) #callback function for SIGUSR1 signal (from flask when kill command is given)


    except Exception as ex:
        GPIO.cleanup() #this ensures a clean exit


Control a separate running script from a Web Server (python)- RPi

Let’s say that you have a running Flask server and you want your user to control the state (on/off) of a motion sensor via the GPIO. The most complex way is to create a multi-threading script which handles the server and GPIO code.

Another approach is to separate the server script from the GPIO script. Thus having two layers of scripts. This has the advantage to debug in isolation. For this technique one has to use Unix Signals which can be used to send signals from one process to another.

When you execute a script on your UNIX system, the system creates a process id (pid) which is different every time. A signal is a software interrupt which notifies a process with a significant event or request.

The following table gives a list of the most common signals:

SIGHUP 1 Linux sends a process this signal when it becomes disconnected from a terminal.
SIGINT 2 Linux sends a process this signal when the user tries to end it by

pressing CTRL+C.

SIGILL 4 Linux sends a process this signal when it attempts to execute an illegal instruction.
SIGABRT 6 Linux sends a process this signal to the process when the process calls the ‘abort ()’ function
SIGFPE 8 Linux sends a process this signal when it has executed an invalid floating-point math instruction
SIGKILL 9 Linux sends a process this signal to end it immediately
SIGUSR1 10 User programs can send this signal to other process
SIGUSR2 12 User programs can send this signal to other process
SIGSEGV 11 Linux sends a process this signal when the program has attempted an invalid memory access
SIGPIPE 13 Linux sends a process this signal when the program has attempted to access a broken data stream, such as a socket connection that has been already closed
SIGALRM 14 A process can receive this signal from the Linux using the function alarm (), after a time period mentioned in its argument.
SIGTERM 15 Linux sends a process this signal requesting it to terminate
SIGCHLD 17 Linux sends a process this signal when a child process exits
SIGXCPU 24 Linux sends a process this signal when it exceeds the limit of

CPU time that it can consume.

SIGVTALRM 26 A process can receive this signal from the Linux using the function setitimer (), after a time period mentioned in its argument.

We are interested in SIGUSR1 and SIGUSR2 which can be used to send user signals.

Step 1:

First create the server layer ( Documentation about Flask server can be found here.

from flask import *
import os
import signal

app = Flask(__name__)

def index():
    return render_template('index.html')

def process1():
    #read process id from text file
    processId = int(

    #send signal to process id
    os.kill(processId, signal.SIGUSR1)

    return render_template('trigger1.html')

def process2():
    #read process id from text file
    processId = int(

    #send signal to process id
    os.kill(processId, signal.SIGUSR2)

    return render_template('trigger2.html')

if __name__ == '__main__':,host='')

Step 2:

Create the script (you can modify this to control the GPIOs)

import os
import signal
import time

fh.write(str(os.getpid())) #get current process id and store in file

def handUSR1(signum,frame):

def handUSR2(signum,frame):

signal.signal(signal.SIGUSR1,handUSR1) #callback function for SIGUSR1 signal
signal.signal(signal.SIGUSR2,handUSR2) #callback function for SIGUSR2 signal

    print("Waiting for signal")

Step 3: Run Server


Step 4: Run


Step 5: 

In the browser, click Trigger 1 and Trigger 2 hyperlink buttons. Notice that outputs ‘triggered 10′ and ‘triggered 12′. This means that both signals were sent and received correctly.


Link to project:

PIXEL(Raspbian)-Virtual Box-Persistence Drive

Please note that this is not officially approved by the PI team but the MagPi magazine offers a similar tutorial using a pendrive.

Step 1

Download the Pixel (Jessie Raspbian) image file:

Step 2:

Open Virtual Box, press new and create the following settings:


Press Create and enter the following settings


Press Start



Step 3:

Browse to the downloaded ISO file and press Start


Pixel is loaded


Step 4:

To test persistence, create a new folder on your desktop and restart your OS.



Once your OS is restarted, you will notice that the folder you created is lost. This is because there is no persistence drive present.


Step 5 (to create persistence drive):

Open terminal window and enter sudo apt install gparted


When installation is finished, enter sudo gparted


Click on Device > Create Partition Table and press Apply


Right Click on the unallocated partition and press New


Enter label name persistence with the following default settings and press Add


Press the green very good sign and press Apply to any warning messages


Press Close and close everything


Now we are going to copy  the whole operating system from the virtual optical drive to
the hard drive.

Open the terminal window and enter sudo dd if=/dev/sr0 of=/dev/sda bs=1M


Close the virtual machine (shutdown the OS)

Step 6:

Create a new Virtual Machine with the following settings. It is very important that you use your previously created virtual hard disk file. Do no create a new virtual hard disk.


Step 7:

Start your new machine and create a new python script to test persistence. I saved my file in the desktop. Restart your OS.


Step 8:

Test file is still there. Persistence worked 🙂