Showing posts with label Python. Show all posts
Showing posts with label Python. Show all posts

Saturday, 9 July 2022

CircuitPython and MicroPython - – start file differences

CircuitPython and MicroPython have many similarities, but there are some major differences.

One of the most fundamental are the names of the files executed when the board is powered up.

Start up sequence

MIcroPython 

MIcroPython looks for two files in a set order in the root of its filesystem.

  • boot.py – this file is run when power is first applied to the board or when the board is reset. Probably not of interest in general unless you are modifying MicroPython.
  • main.py – this is the file that is either your program or starts your program. If it is present, it is run after the code in the boot.py file.

CircuitPython

CircuitPython looks for the following files in this order:

  • •code.txt
  • •code.py
  • •main.txt
  • •main.py.

References

https://learn.adafruit.com/getting-started-with-raspberry-pi-pico-circuitpython/micropython-or-circuitpython

https://github.com/adafruit/circuitpython#differences-from-micropython

https://docs.circuitpython.org/en/latest/README.html#differences-from-micropython


Sunday, 20 February 2022

PICO Breakout Garden Base

The Pimoroni PICO Breakout Garden Base has a socket for a Raspberry Pi PICO (available from Pimoroni with headers pre-soldered) plus four I2C sockets and two SPI sockets compatible with the Pimoroni breakout garden breakouts. Pimoroni also do a Breakout Garden to QT/QWIIC adapter.



This allows soldering free development (assuming you buy the PICO with headers attached) and reuse of the various breakouts (with other PICOs including the Explorer Base or Raspberry Pis).

There are libraries for C++, MicroPython and Circuit Python.

Installation

Hardware

Breakout Garden Base, self adhesive feet and a Raspberry Pi PICO.
The printed paws on the underside show where the self adhesive feet go.


Before fitting the Raspberry Pi PICO to the Breakout Garden Base, I would recommend testing the PICO. The Blink program (that flashes the PICO's built in LED) is a good test.

The Breakout Garden Base has two rows of sockets to take the pins soldered to the Raspberry Pi PICO microcontroller. Match the orientation of the Pico with the drawing between the sockets and align the pins on the Raspberry Pi PICO with the holes in the sockets and gently and evenly apply pressure until the PICO is in place.

Software

To use the I2C and SPI sockets on the base, Pimoroni have created a custom UF2 file including the required drivers. Follow the instructions here: https://learn.pimoroni.com/tutorial/hel/getting-started-with-pico

If you find the latest Pimoroni UF2 version does not work as expected, use the Update Firmware option on Thonny to return to a vanilla flavour UF2 and reload the Blink example.

It might be that the latest version has introduced a bug in the Breakout Garden handling. Download and install an earlier version of the Pimoroni UF2.

It is very useful to add parts of the Blink example to your code when testing to show that the code is working.

There are examples for a number of the breakouts available.

A 1.3" SPI Colour Round LCD example in operation.

References

https://shop.pimoroni.com/products/pico-breakout-garden-base

https://shop.pimoroni.com/products/raspberry-pi-pico?variant=32402092326995

https://shop.pimoroni.com/collections/breakout-garden

https://shop.pimoroni.com/products/breakout-garden-to-qwiic-adaptor

https://en.wikipedia.org/wiki/I%C2%B2C

https://en.wikipedia.org/wiki/Serial_Peripheral_Interface

https://learn.pimoroni.com/tutorial/hel/getting-started-with-pico

https://github.com/pimoroni/pimoroni-pico/releases

https://github.com/pimoroni/pimoroni-pico/tree/main/micropython/examples




Monday, 17 January 2022

Raspberry Pi Pico Explorer

The Raspberry Pi Pico Explorer is a plug-in board that provides a number of built-in devices including a 240x240 colour display, four buttons, a piezo buzzer, two I2S Breakout Garden sockets and sockets connected to the Pico's pins plus a small solderless breadboard.

A Raspberry Pi Pico with pre-soldered headers makes development easy without needing to solder delicate electronics.


Assembly was easy, care being taken to make sure all the pins aligned with the corresponding holes in the socket on the board.

Updating the Firmware

To use the components on the Explorer board, Pimoroni has created a custom UF2 file, including the required drivers. As of 03/01/2022 the latest version of the Pimoroni firmware (0.3.2) does not work, use version 0.3.1. This might not be the case for other boards.

Use the Update Firmware option on Thonny to return to a vanilla flavour and the Blink example if the current Pimoroni version does not work as expected. Select an earlier version of the UF2 and try again.

There is an example that measures the cpu temperature which is then displayed as text and a bar graph.
The next stage was to make use of the Breakout Garden sockets and add some breakout units. 
To provide some measurements, a BME680 environmental sensor was added to the right hand socket. In the left hand socket is a rotary encoder with a built in RGB LED.
The two sockets allow the addition of two breakouts. PIMORONI have a range of breakouts, including additional convertors that allow connection to STEMMA or Qwiic devices.

The BME680 breakout is an older model, the current version includes a built in STEMMA or Qwiic connector.
The example program was modified to get the temperature, pressure and humidity from the BME680 sensor plus the cpi temperature.

The code to set the encoder's RGB LED colour was also added.
The graph code was designed to display both the cpu temperature and the sensor temperature.

Finally a maximum and minimum sensor temperature was added to the display.

Code

Do check the indenting as Python uses the indenting to define the structure of the program.

import machine
import utime

from breakout_bme68x import BreakoutBME68X
from pimoroni_i2c import PimoroniI2C

PINS_BREAKOUT_GARDEN = {"sda": 4, "scl": 5}
PINS_PICO_EXPLORER = {"sda": 20, "scl": 21}

i2c = PimoroniI2C(**PINS_PICO_EXPLORER)

# Pico Explorer boilerplate
import picoexplorer as display
width = display.get_width()
height = display.get_height()
display_buffer = bytearray(width * height * 2)
display.init(display_buffer)

# BME68x configuration
bme = BreakoutBME68X(i2c)
#bme.configure(FILTER_COEFF_3, STANDBY_TIME_1000_MS, OVERSAMPLING_16X, OVERSAMPLING_2X, OVERSAMPLING_1X)

# reads from Pico's temp sensor and converts it into a more manageable number
sensor_temp = machine.ADC(4)
conversion_factor = 3.3 / (65535)

# Set up text areas
blockHeight = 33
textBlocks = 8
textArea=list()
for x in range(textBlocks):
    if(textBlocks>4):
        if(x<4):
            textArea.append([10,(blockHeight*x)+1,120,blockHeight])        
        else:
            textArea.append([120,(blockHeight*(x-4))+1,120,blockHeight])
    else:
        textArea.append([120,(blockHeight*x)+1,120,blockHeight])

# Set up background and text pens
background_pen = display.create_pen(0,0,0)
cpu_temp_pen = display.create_pen(255, 64, 64)
bme_temp_pen = display.create_pen(64, 255, 64)
pressure_pen = display.create_pen(64, 64, 255)
humidity_pen = display.create_pen(0, 255, 255)

# Define number of pixels for the graph points
graph_element_size = 1
graph_y_scale = 4

def drawTemp(i,cpu_temp,sensor_temp):
    diff = abs((cpu_temp*graph_element_size)-(sensor_temp*graph_element_size))
    if(diff<graph_element_size):
        display.set_pen(255,255,0)
        display.rectangle(i, height - (cpu_temp * graph_y_scale), graph_element_size,graph_element_size)
    else:
        display.set_pen(cpu_temp_pen)
        display.rectangle(i, height - (cpu_temp * graph_y_scale), graph_element_size,graph_element_size)
        display.set_pen(bme_temp_pen)
        display.rectangle(i, height - (int(sensor_temp) * graph_y_scale), graph_element_size,graph_element_size)
    
def writeInBlock(text, location, pen, paper, size):
    # Draw background to clear display area
    display.set_pen(paper)
    display.rectangle(location[0],location[1],location[2],location[3])
    # Write text in location one pixel left and down
    display.set_pen(pen)
    display.text(text, location[0]+1,location[1]+1,100,size)
    
# Initialise run variables
i = 0
count = 0
max_temp = 0
min_temp = 100

while True:
    # the following two lines do some maths to convert the number from the temp sensor into celsius
    reading = sensor_temp.read_u16() * conversion_factor
    temperature = round(27 - (reading - 0.706) / 0.001721)
    bmetemp, pressure, humidity, gas_resistance, status, gas_index, meas_index = bme.read()
    max_temp=max(max_temp,bmetemp)
    min_temp=min(min_temp,bmetemp)
    
    # Clear the display and reset counter if the graph reaches the right hand side
    if i >= (width + 1):
        i = 0
        display.set_pen(0, 0, 0)
        display.clear()

    # Draw graph element
    drawTemp(i,temperature,bmetemp)

    writeInBlock("{:.0f}".format(temperature) + "c", textArea[0],cpu_temp_pen,background_pen,4)
    writeInBlock("{:.0f}".format(bmetemp) + "c", textArea[1],bme_temp_pen,background_pen,4)
    writeInBlock("{:.0f}".format(pressure/1000) + "kPa", textArea[2],pressure_pen,background_pen,3)
    writeInBlock("{:.0f}".format(humidity)+"%", textArea[3],humidity_pen,background_pen,4)
    writeInBlock("Mx {:.0f}".format(max_temp) + "c", textArea[4],bme_temp_pen,background_pen,3)
    writeInBlock("Mn {:.0f}".format(min_temp) + "c", textArea[5],bme_temp_pen,background_pen,3)
    # time to update the display
    display.update()

    # waits for 5 seconds
    utime.sleep(1)

    # Set next graph element location
    i+=graph_element_size



Saturday, 26 June 2021

Temperature measuring Web Server

So, having had the Pimoroni Breakout Garden for a while and having used it as a temperature measurement device with a BME680 and display, I needed to measure the temperature and compare it with the temperature measured  by the analogue sensor of an Adafruit PyPortal and the CPU temperature.

The BME680 results are affected by the heat generated by the CPU, and a correction formula based on the CPU temperature was used to compensate for the CPU temperature.

An alternative is to separate the temperature sensor from the CPU.

This was achieved using a Breakout Garden to Stemma QT/QWIIC adapter and STEMMA QT / Qwiic to Breakout Garden Adapter  joined by a JST to JST cable. A BMP280 breakout was plugged in at one end, and the other plugged into the Breakout Garden. This should provide sufficient thermal isolation from the hot CPU.


Software installation

The Python library for the BMP280 temperature, pressure and altitude sensor is available via PIP. As with all installations, check if pip is for the now obsolete Python 2.x or Python 3.x. If the former, then use pip3 (that is the case on my Raspberry Pi Zero development systerm).

sudo pip3 install bmp280

The easiest way to make the data available to an Internet connectable device is by making the temperature measuring Raspberry Pi a web server.

The Flask library is similarly installed with pip. Note Flask starts with a capital letter
sudo pip3 install -U Flask

Web Server

This is a very simple web server, it has two  pages - /temperature and /json.

from flask import Flask, render_template
import time
import datetime
import json
from bmp280 import BMP280

try:
    from smbus2 import SMBus
except ImportError:
    from smbus import SMBus
app = Flask(__name__)

@app.route('/temperature')
def temperature():
    now = datetime.datetime.now()
    timeString = now.strftime("%Y-%m-%d %H:%M")
    temperature = bmp280.get_temperature()
    temp = '{:05.2f}*C'.format(temperature)
    templateData = {
      'temperature' : temp,
      'time': timeString
      }
    return render_template('temperature.html', **templateData)

@app.route('/json')
def tempjson():
    now = datetime.datetime.now()
    timeString = now.strftime("%Y-%m-%d %H:%M")
    temperature = bmp280.get_temperature()
    temp = '{:05.2f}'.format(temperature)
    templateData = {
      'temperature' : temp,
      'time': timeString
      }

    return json.dumps(templateData)

if __name__ == '__main__':
    bus = SMBus(1)
    bmp280 = BMP280(i2c_dev=bus)
    app.run(debug=True, host='0.0.0.0')

References


Saturday, 2 January 2021

Reading RSS feeds using Python

RSS Feeds

RSS stands for Really Simple Syndication and is a method of supplying information generally to be read by computers. An RSS feed is a web page and contains a number of entries, each entry commonly containing: title, link, description, publication date, and entry ID.

If you Google reading RSS in Python, you will often be directed to the feedparser library. This handles a lot of the background work involved in using an RSS feed and has a lot of protection against some of the potential pitfalls of reading what is effectively XML from potentially unknown sources. This includes only reading elements from a whitelist of trusted elements.

Unfortunately not all RSS feeds use elements on that whitelist.

One of those is the BBC RSS feeds. This is a problem in that I wanted to download the free BBC podcasts automatically.

So it was back to basics, the Requests library to access the RSS feed and download the files, and the defusedxml library to manipulate the RSS file as XML.

RSS files contain publication dates, so if you record the date of the last file you have downloaded, you can then use that date to only download new files when you retry the feed.

Installation

Remember to check that the version of pip is for Python 3.x (if not then replace pip with pip3)

Requests

pip install requests

Defusedxml

pip install defusedxml

Dateutil

This is required for date reading and comparison
pip install python-dateutil

Design

There are four main elements of the program:
  • Read the RSS file
  • Iterate through the new files
  • Download the podcasts
  • Update the last file date

Code

import defusedxml.ElementTree as ET
from pathlib import Path
import requests
from dateutil.parser import parse
import os

# Save the file refereenced by the URL to the supplied filepath
def saveMP3(url, filepath):
    print(filepath)
    r = requests.get(url)
    with open(filepath, 'wb') as f:
        f.write(r.content)

# Get all the files from the supplied RSS url that are newer than the 
# last file date stored in the matching file
def getFiles(url, target_folder, prefix):
    # Build the Namespace for the XML searching
    ns = {'media': "http://search.yahoo.com/mrss/"}

    # Create target folder if required
    if not Path(target_folder).is_dir():
        os.makedirs(target_folder)

    # Get response from URL
    r = requests.get(rss_url)
    print(r.status_code)

    # Make XML document from response text
    root = ET.fromstring(r.text)

    # Get the channel title
    channel_title = root.find("channel/title").text.replace(": ", "-")

    # Build the filename for the last downloaded file date
    channel_file = channel_title + "_lastdate.txt"
    print(channel_file)
    
    last_file_date = ""
    # Set up a default date if there is no file
    last_date = parse("2000-01-01 00:00:00 +00:00")

    # If there is a file, obtain the date from the file
    if Path(channel_file).is_file():
        f = open(channel_file, "r")
        last_file_date = f.read()
        last_date = parse(last_file_date)
        f.close()
    print(last_date)

    # Find the item elements from the XML
    items = root.findall("channel/item")

    print(channel_title + " files:" + str(len(items)))
    download_count = 0
    first_file_downloaded_date = ""

    # For each item found
    for y in items:
        # Obtain the information required
        title = y.find("title")
        link = y.find("media:content", ns)
        pub_date = y.find("pubDate")
        # Create the published date as datetime
        datetime_object = parse(pub_date.text)
        print(title.text)
        print(datetime_object)
        if last_file_date == "":              # Download if no previous date
            saveMP3(link.attrib['url'], target_folder+prefix+datetime_object.strftime("%Y%m%d%H%M%S") + ".mp3")
            download_count = download_count+1
        elif last_date < datetime_object:     # Download if newer than the last run
            saveMP3(link.attrib['url'], target_folder+prefix+datetime_object.strftime("%Y%m%d%H%M%S") + ".mp3")
            download_count = download_count+1
        else:                               # Otherwise exit loop
            print("Not downloading")
            break
        # Record the filedate of the first (most recent) file
        if first_file_downloaded_date == "":
            first_file_downloaded_date = pub_date.text
    
    # Print how many files and the most recent file date
    print("Downloaded " + str(download_count))
    print(first_file_downloaded_date)
    
    # Write the most recent file date to the file
    if first_file_downloaded_date != "":
        f = open(channel_file, "w")
        f.write(first_file_downloaded_date)
        f.close()

# If this is the main call
if __name__ == "__main__":
    rss_url = 'https://podcasts.files.bbci.co.uk/p02nrss1.rss'
    getFiles(rss_url, "/home/pi/Music/moreorless/","mol")

References


Sunday, 26 April 2020

Pimoroni Pirate Audio MP3 server.

Pimoroni of Sheffield have recently introduced a range of PHAT form boards for the Raspberry Pi family of single board computers. Their Pirate Audio range offer high quality MP3 playback via a variety of outputs together with the a 240 x 240 full colour display..

I decided on the Pirate Audio Headphone Amp.

The Components


The board is supplied in an resealable anti-static bag.

 I was so excited when I received the package from Pimoroni, I opened it before taking the photograph.
The PHAT form boards are smaller than the standard HAT boards, they are designed to stack on top of any 40 pin Raspberry PI, but they are specifically designed to have the same board dimensions as the Raspberry Pi Zero. So with the Pirate Audio board, I also bought a Raspberry Pi Zero W, as soldering is not one of my skills,  Pimoroni offer them with  pre-soldered  headers.

 So this is the board itself. The screen is not cracked, the protective plastic sheet has partially lifted. Eventually I will remove it once I have finished working on it.
There are four buttons around the screen and a headphone jack on the laft side.
 You can see how the PHAT form boards fit directly on top of the Pi Zero board.
The back of the board showing the Hi/Lo Gain amplifier option switch. Though it is inside the board sandwich when assembled, the switch can be operated using a suitably sized rod.

Assembly

I had a 64GB Sandisk SD in stock (I buy them when they are on sale at my local supermarkets), but Linux in general has issues with the default ExFAT format and Raspberry Pis cannot boot from them. However it is easy to reformat them to FAT32. See this post for details.

I used the recently released Raspberry Pi Imager to install the latest version of Raspbian Buster.

The new SD card was inserted into the Pi Zero and it was connected to a keyboard, mouse, monitor and a USB Ethernet connector via a powered hub. The USB Ethernet connector speeds up the updates
Once the initial set up was complete, it was time to assemble the boards.
The two boards were offered up and then gently pushed together.
I also had a couple of stand offs that I used to support the front of the board sandwich.

Software Installation


The installation script has some issues. Over the Christmas 2019 holidays, the core music server underwent a major upgrade. Unfortunately this seriously broke the software used on the board.
You can follow the story here.

The only real issue to currently be aware of is that the Mopidy Local service is not included in the install script. It was included in the base Mopidy repository, but was split off during the upgrade.

It is easy to install:
sudo apt-get install mopidy-local
After that it is all set up.

Loading MP3s.

Of course a music player is not much use without some music to play.

Martin O'Hanlon has a useful post on Stuff About Code on copying CD music to MP3.
The Python code opens the CD drive, you pop a CD in, close it and off it goes. When it has finished, it pops the drive open again. If you put another CD in and close it, it will process it. This continues until you stop feeding it CDs. Ingenious.

I used his code, but did convert it to Python 3.

I have a Samsung external USB DVD drive. Now it is a bit power hungry. I initially used a powered hub to supply power to the Raspberry Pi, the mouse and keyboard, and the DVD player.

When I tried it, it kept throwing errors. I did wonder if the DVD drive was not compatible. So I tried it on my Raspberry Pi 3 and that happily copied and converted a CD.

So I powered the Raspberry Pi with a separate USB supply and used the USB hub to power the DVD drive, and the keyboard and mouse.

It does make a bit of a rat's nest of cables.

Once I had loaded a few CDs (18), it was time to  give it a try.

I plugged in my headphones and pointed the browser of my tablet at the IP and port number displayed on the Pirate Audio screen. Select the album of choice and...
The sound level is a bit high, so I will have a look at that.

Conclusion

With the exception of the installation of the mopidy-local, the installation was easy.
Remember, if you use a CD/DVD player to ensure you have a suitable power supply.

The Raspberry Pi Zero is a lot less computationally powerful than the Pi 3 or 4, so it does take a while to process the CDs, and the user interface is a bit slow when you run it locally. It is fine on the browser of another machine.

Sunday, 5 April 2020

Pimoroni BME680 Environment sensor

So, having a display is all well and good, but now you need something to display.

The Pimoroni BME680 breakout board has a Bosch BME680 temperature, pressure, humidity and air quality sensor.

The following code assumes you have the BME680 and the SH1106 OLED display on the default I2C addresses.

import os
import time
import datetime
import sys

from PIL import Image

from PIL import ImageFont
from PIL import ImageDraw

import bme680

from luma.core.interface.serial import i2c
from luma.oled.device import sh1106
from luma.core.render import canvas

TEMPERATURE_UPDATE_INTERVAL = 0.1  # in seconds


# Temperature offset 

TEMP_OFFSET = 0.0

print("Temperature/pressure monitor - OLED")

print("Initialising")

# Instantiate object for SH1106 OLED display

oled = sh1106(i2c(port=1, address=0x3C), rotate=2, height=128, width=128)

# Instantiate object to read  BME680 sensor

sensor = bme680.BME680()

# Set up the sensors

sensor.set_humidity_oversample(bme680.OS_2X)
sensor.set_pressure_oversample(bme680.OS_4X)
sensor.set_temperature_oversample(bme680.OS_8X)
sensor.set_filter(bme680.FILTER_SIZE_3)
sensor.set_temp_offset(TEMP_OFFSET)

# Build the fonts

rr_path = os.path.abspath(os.path.join(os.path.dirname(__file__), 'fonts',
                                       'Roboto-Regular.ttf'))
rb_path = os.path.abspath(os.path.join(os.path.dirname(__file__), 'fonts',
                                       'Roboto-Black.ttf'))
rr_24 = ImageFont.truetype(rr_path, 24)
rb_20 = ImageFont.truetype(rb_path, 20)
rr_15 = ImageFont.truetype(rr_path, 15)
rr_40 = ImageFont.truetype(rr_path, 40)

# Get sensor data first so that device settings take effect

sensor.get_sensor_data()
# Get the initial date/time and max/min temperature
low_temp = sensor.data.temperature
high_temp = sensor.data.temperature
curr_date = datetime.date.today().day

last_checked = time.time()


# Main loop

while True:
    if sensor.get_sensor_data():
        temp = sensor.data.temperature
        press = sensor.data.pressure
        humidity =sensor.data.humidity
        if datetime.datetime.today().day == curr_date:
            if temp < low_temp:
                low_temp = temp
            elif temp > high_temp:
                high_temp = temp
        else:
            curr_date = datetime.datetime.today().day
            low_temp = temp
            high_temp = temp

        # Write data to canvas

        with canvas(oled) as draw:
            draw.text((65, 55), u"{0:4.0f}".format(press), fill="white", font=rb_20)
            draw.text((1, 55), u"{0:2.1f}%".format(humidity), fill="white", font=rb_20)
            draw.text((1, 1), u"{0:2.0f}°".format(temp), fill="white", font=rr_40)

            draw.text((65, 4), u"max: {0:2.0f}°".format(high_temp), fill="white", font=rr_15)

            draw.text((65, 30), u"min: {0:2.0f}°".format(low_temp), fill="white", font=rr_15)

            if int(time.time()) % 2 == 0:

                draw.text((14, 78), datetime.datetime.now().strftime("%H:%M"),
                          fill="white", font=rr_40)
            else:
                draw.text((14, 78), datetime.datetime.now().strftime("%H %M"),
                          fill="white", font=rr_40)

    time.sleep(TEMPERATURE_UPDATE_INTERVAL)


And this is the result.

There is a potential issue with the temperature. The temperature sensor is directly above the Raspberry Pi Zero, and more importantly close to being above the processor. This does mean that the heat from the processor may well be affecting the temperature being sensed and hence displayed.

Dealing with that is for the next instalment.


Sunday, 29 March 2020

Pimoroni 1.12" OLED breakout

A long time ago I bought a Pimoroni Breakout Garden and a selection of breakouts.

I had intended to write some very simple test code  and put it on the blog, unfortunately I then managed to break the SD card with the code on. Must remember to back up regularly...

The Breakout Garden equipped Pi Zero then languished at the back of the cupboard while other, shinier things caught my attention.

And then I wanted to know what the temperature was. I do have a number of pieces of technology that would do that (Arduino, Micro:Bit, Raspberry Pi), but decided that the Breakout Garden would be a good starting point.

But first I wanted to check out the operation of the OLED display.

1.12" OLED breakout

Pimoroni provide a good set of example code, including a complete weather station, but I wanted to build my own using the supplied modules.

First off a simple piece of Python to display a message on the screen.

# Simple test of a Pimoroni SH1106 Breakout board attached to a Breakout Garden HAT

# Required modules
from luma.core.interface.serial import i2c, spi
from luma.core.render import canvas
from luma.oled.device import ssd1306, ssd1309, ssd1325, ssd1331, sh1106

# Instantiate a luma SH1106 object
oled = sh1106(i2c(port=1, address=0x3C), rotate=2, height=128, width=128)

# Create a suitable canvas to draw on
with canvas(oled) as draw:
    draw.rectangle(oled.bounding_box, outline="white", fill="black")
    draw.text((30, 40), "Hello SH1106!", fill="white")

print("There should be something on the display now")

References



Wednesday, 19 February 2020

Simple Bar Code Reader using a Raspberry Pi

Reading Bar Codes with the Raspberry Pi

Installation 

Install OpenCV
sudo apt get install python-opencv libopencv-dev 
You might find it is already installed.

Install Python bindings 

pip3 install opencv-python 

Install additional libraries 

sudo apt-get install libcblas-dev 
sudo apt-get install libhdf5-dev -y
 && sudo apt-get install libhdf5-serial-dev -y 
 && sudo apt-get install libatlas-base-dev -y
 && sudo apt-get install libjasper-dev -y
 && sudo apt-get install libqtgui4 -y
 && sudo apt-get install libqt4-test -y 

Install ZBAR and PYZBAR 

According to one of the references, zbar does not have a python3 version, however the pyzbar works with Python3.
sudo apt-get install libzbar0 
pip3 install pyzbar 
Remember to use pip3 not pip to install pyzbar for Python3 (your installation may vary - pip defaults to Python2 in most installations).

Test program 

from pyzbar import pyzbar
import cv2

imagefile="/home/pi/Documents/Python/barcodetest.jpg"

print(imagefile)
# load the input image
image = cv2.imread(imagefile)
# find the barcodes in the image and decode each of the barcodes
barcodes = pyzbar.decode(image)

# loop over the detected barcodes
for barcode in barcodes:
    # extract the bounding box location of the barcode and draw the
    # bounding box surrounding the barcode on the image
    (x, y, w, h) = barcode.rect
    cv2.rectangle(image, (x, y), (x + w, y + h), (0, 0, 255), 2)
    # the barcode data is a bytes object so if we want to draw it on
    # our output image we need to convert it to a string first
    barcodeData = barcode.data.decode("utf-8")
    barcodeType = barcode.type
    # draw the barcode data and barcode type on the image
    text = "{} ({})".format(barcodeData, barcodeType)
    cv2.putText(image, text, (x, y - 10), cv2.FONT_HERSHEY_SIMPLEX,
        0.5, (0, 0, 255), 2)
    # print the barcode type and data to the terminal
    print("[INFO] Found {} barcode: {}".format(barcodeType, barcodeData))

# show the output image
cv2.imshow("Image", image)
cv2.waitKey(0)

Troubleshooting

There may be issues with the version of numpy installed by the above.
If you getr an import error, remove the installed version of numpy and replace it with one from the Raspbian repository.

pip3 uninstall numpy  # remove previously installed version
apt install python3-numpy
https://numpy.org/devdocs/user/troubleshooting-importerror.html

References 

https://www.pyimagesearch.com/2018/05/21/an-opencv-barcode-and-qr-code-scanner-with-zbar/
https://www.learnopencv.com/barcode-and-qr-code-scanner-using-zbar-and-opencv/
https://www.raspberrypi.org/forums/viewtopic.php?p=848265 
https://stackoverflow.com/questions/19876079/cannot-find-module-cv2-when-using-opencv

Friday, 27 December 2019

Drinking from the Flask part 3

A Brief Interlude

So far the source has been Python and the recipient has been .Net.

Python has a number of modules to handle HTTP requests, and one of the simplest to use is the Requests module.

import requests
req = requests.get('https://<your-user-name>.pythonanywhere.com/subscribers')
print(req.text)

This will return the same data as the browser example earlier:

>>> %Run firstrequest.py
{"Subscribers":[{"subscriber": {"emailaddress": "email_0@tec.com", "subscriptionid": 0}}, {"subscriber": {"emailaddress": "email_1@tec.com", "subscriptionid": 1}}, {"subscriber": {"emailaddress": "email_2@tec.com", "subscriptionid": 2}}, {"subscriber": {"emailaddress": "email_3@tec.com", "subscriptionid": 3}}, {"subscriber": {"emailaddress": "email_4@tec.com", "subscriptionid": 4}}]}
>>>
Now once you have the data, it needs to be converted into something usable.

JSON is based on the structure of Javascript, but the Python Dictionary is easily convertible to and from JSON.

The data has a dictionary (Subscribers), within which is a list. Each item (subscriber) in the list has two name-value pairs (subscriptionid and emailaddress).

import json
import requests

req = requests.get('https://<your-user-name>.pythonanywhere.com/subscribers'

aDictionary = json.loads(req.text)
#print(y['Subscribers'])

for x in aDictionary['Subscribers']:
    print(x['subscriber']['subscriptionid'],x['subscriber']['emailaddress'])

The output:

0 email_0@tec.com
1 email_1@tec.com
2 email_2@tec.com
3 email_3@tec.com
4 email_4@tec.com

References



Saturday, 21 December 2019

Drinking from the Flask part 2

Drinking from the Flask with .Net

Background

This small project will integrate Python, Flask, JSON and .Net.

Task 1: Set up a JSON end point using Python and Flask
Task 2:  .Net application to read data from the end point
Task 3: Expand end points on the Python server for details
Task 4: Select and search for details via JSON calls.

A first sip from the Flask

This assumes you have a suitable version of Visual Studio installed, and an internet connection (plus you have a working JSON source from the previous post).

Ordering the drink

For simplicity we shall start with a Console application.

Create a new .Net Framework Console application (is it me or does Microsoft continue to add steps that add no value to their dialogues?). I called mine JSONTestProgram.

Leaving the Console program until later, I then created another project (a .Net Framework Class) in the solution called JSONClient. I renamed the class to JSONGetData. I then added an additional class file to the project called JSONSubscribers.cs.

The JSONGetData.cs file contains the following code (remember to use the URL of your Flask project).

using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using System.Net.Http;
//using System

namespace JSONClient
{
    /// <summary>
    /// This class is used to get JSON data from an endpoint
    /// </summary>
    public class JSONGetData
    {
        /// <summary>
        /// URL for getting the sunscribers information from the JSON source
        /// </summary>
        public static readonly string URLGetSubscribers = "https:// <yourusername>.pythonanywhere.com/subscribers";
        
        static HttpClient client = new HttpClient();
        /// <summary>
        /// Asynchronous function that obtains data from the URLSubscribers endpoint 
        /// and returns a dictionary of email addresses and subscription ids
        /// </summary>
        /// <returns>A dictionary with key and value of type string</returns>
        public static async Task<Dictionary<string,string>> GetSubscribers()
        {
            string content;
            Dictionary<string, string> dictSubscribers=null;
            using (HttpResponseMessage response = await client.GetAsync(URLGetSubscribers, HttpCompletionOption.ResponseHeadersRead).ConfigureAwait(false))
            {
                if (response.IsSuccessStatusCode)
                {
                    dictSubscribers = new Dictionary<string, string>();
                    content = await response.Content.ReadAsStringAsync();
                    Rootobject x = Newtonsoft.Json.JsonConvert.DeserializeObject<Rootobject>(content);
                    foreach (JSONClient.Subscriber subscriber in x.Subscribers)
                    {
                        dictSubscribers.Add(subscriber.subscriber.emailaddress, subscriber.subscriber.subscriptionid.ToString());
                    }
                }
            }  
            return dictSubscribers;
        }
    }
}
You need to add a reference to the Newtonsoft.Json package via Edit/Manage NuGet Packages.

A static instance of the HTTPClient is used in this case for simplicity (only one URL is in use).

The asynchronous task GetSubscribers will return a Dictionary of email and subscriber ids.
The GetSubscribers code first creates the dictionary to be returned.
An HTTPResponseMessage is created and initialised by an asynchronous call to the URLGetSubscribers URL.
If the response contains a status success code, the dictionary to be returned is initialised.
The content of the response is read into a string and then deserialized using the NewtonSoft component and a target class (more of which anon).
For each subscriber in the object, the email address and subscription ID is extracted and added to the dictionary.
If the response does not contain a status success code, the dictionary is returned uninitialized.

JSON data cannot be read in the same way as XML data (there is no Document Object Model equivalent), so you generally need to know the format or schema of the JSON.

This is where the JSONSubscribers.cs file comes in.
Visual Studio has added a feature which allows you to use an Edit/Paste Special command to paste text as either XML or JSON, converting the text being pasted into the required classes. When you do this, it is generally a good idea to paste it into a dedicated file - then when (if) you change the JSON file, you can just scrub and re-paste it.
This is the result in the current JSONSubscribers.cs file.

namespace JSONClient
{

    public class Rootobject
    {
        public Subscriber[] Subscribers { get; set; }
    }

    public class Subscriber
    {
        public Subscriber1 subscriber { get; set; }
    }

    public class Subscriber1
    {
        public string emailaddress { get; set; }
        public int subscriptionid { get; set; }
    }

}

The root object is used as the overall class for the conversion. The element names within the classes may not match up with the recommended naming scheme in C#, it is possible to tell it to use one name in the source and generate another in the object but that is beyond this simple example.
So, how do we call this code?

The Console program

The most complicated part of the Main method is the RunAsync().GetAwaiter().GetResult() call.
It is a lazy (and liable to deadlocks) way of calling an asynchronous call synchronously. Not really for production code.
You will need to add references to the Newtonsoft.Json package via Manage NuGet packages menu item. You also need to reference the JSONClient project.

class Program
    {
        static void Main(string[] args)
        {
            RunAsync().GetAwaiter().GetResult();
            Console.WriteLine("Press any key");
            Console.ReadKey();
        }
        static async Task RunAsync()
        {
            Dictionary<string, string> subscribers = new Dictionary<string, string>();
            subscribers = await JSONClient.JSONGetData.GetSubscribers();
            foreach (string key in subscribers.Keys)
            {
                Console.WriteLine($"{key}: {subscribers[key]}");
            }

        }
    }

The RunAysnc task calls the GetSubscribers code to obtain the Dictionary and then writes the email address and subscriber id (key - value) to the Console.
When the Console program runs, the result is as follows:
email_0@tec.com: 0
email_1@tec.com: 1
email_2@tec.com: 2
email_3@tec.com: 3
email_4@tec.com: 4
Press any key

Building a Windows Form program

This is slightly more complicated, as there are a lot of threads that can get tangled (for more details see the references).
Add a new Windows Forms project to your solution - in my case I called it JSONTestProgram.

Construct your form similar to this one (it has a label, a text box and a second button used ina later example).


The form comprises a status bar at the bottom and a tool bar at the top. There is a Docked panel in the middle with a Docked SplitContainer inside.
One of the split panels has a ListBox called lbSubscribers (which again is Docked).
The Toolbar has a number of buttons, but only the one marked Load is currently active.
The project needs to have references to the project  JSONClient and a NuGet reference to NewtonSoft.JSON.

Code wise, click on the Load Subscribers button and note the control's name.
Add:

static Dictionary<string, string> subscribers =new Dictionary<string, string>();
inside the Program class (we will be using it later).
You also need to replace the existing method generated when you clicked on the button with:

        private async void toolStripButton2_Click(object sender, EventArgs e)
        {
            subscribers = await JSONClient.JSONGetData.GetSubscribers();
            foreach (string key in subscribers.Keys)
            {
                lbSubscribers.Items.Add(key);
            }
        }

Change the tool strip button name to match the button on your form. Visual Studio will grumble about the method name, which is annoying as it created it.

That is the first part completed. Now change this to be the Start Up project for the solution and run it.
Click on the Load Subscribers button and the list of subscribers generated by your Flask project will be displayed.




References