Saturday, August 18, 2018

Recent python door cam code - ugly, but works.

Updated version of the code...
It deals with the occasional hangs in the camera capture process by
rebooting when they happen. A line in /etc/rc.local runs the program again.

# Program for PiDoorCam

# Detects motion, and when it spots some, takes a high resolution
# picture, and sends the picture to PiScreen

import io
import os
import picamera
import ftplib
import time
from datetime import datetime
from PIL import Image
import requests

camera = picamera.PiCamera()
picamera.PiCamera.CAPTURE_TIMEOUT = 30

# If we detect 100 pixels that changed by 30, we have seen movement.
#difference = 30
#pixels = 100
# Desensitise!
#difference = 30
difference = 50
pixels = 150

# May as well use the maximum resolution of the camera.
# This is for V1. V2 is 3280 x 2464.
width = 2592
height = 1944

# I copied this voodoo motion detection from somewhere. Changed the timeout
#  setting above to prevent the occasional failures to complete captures.
def compare():
   camera.resolution = (100, 75)
   stream = io.BytesIO()
   format = 'bmp'
   # Handle occasional 'Timed out waiting for capture to end'
   try:
      camera.capture(stream, format)
   except:
      print ("Camera timed out, reboot needed!")
      os.system("sudo reboot now")
       
   stream.seek(0)
   im = Image.open(stream)
   buffer = im.load()
   stream.close()
   return im, buffer

# Function to take a new high resolution picture, send it to PiScreen
# send it to my phone, and then delete it.
def newimage(width, height):
    when = datetime.now()
    filename = "door-%04d%02d%02d-%02d%02d%02d.jpg" % (when.year, when.month, when.day, when.hour, when.minute, when.second)
    camera.resolution = (width, height)
    camera.capture(filename)

    connected = True
    ftp = ftplib.FTP()
    ftp.connect("PiScreen")
   
    try:
        ftp.login("pi","******************")
    except ftplib.all_errors:
        connected = False
        print ("Failed to connect to server %s" % e)   
       
    if connected:
        ftp.storbinary('STOR '+filename, open(filename, "rb"))
        print ("Sent ", filename)

    ftp.quit()

# Code to send the Pushover message. Make picture smaller first.
    im = Image.open(filename)
    im.resize((324,243),Image.ANTIALIAS)
    im.save(filename)
   
    r = requests.post("https://api.pushover.net/1/messages.json", data = {
        "token": "***********************************",
        "user": "*************************************",
        "device": "***********",
        "sound": "intermission",
        "message": filename
    },
    files = {
        "attachment": (filename, open(filename, "rb"), "image/jpeg")
    })
# Check r for problems - maybe put a delay here?
    if r.status_code != 200:
        print("Pushover message failed.")
    else:
        print("Pushover accepted the message.")
       
# Now delete the file.
    os.remove(filename)
    # Delay to avoid being nasty to Pushover server.
    time.sleep(5)

# Main program.

camera.rotation = 180
print("Running door.py")
image1, buffer1 = compare()

newimage(width, height)

while (True):

   image2, buffer2 = compare()

   changedpixels = 0
   for x in range(0, 100):
      for y in range(0, 75):
         pixdiff = abs(buffer1[x,y][1] - buffer2[x,y][1])
         if pixdiff > difference:
            changedpixels += 1

   if changedpixels > pixels:
      newimage(width, height)

   image1 = image2
   buffer1 = buffer2



Code below is an older version, the "error handling" doesn't actually work.

# Program for PiDoorCam

# Detects motion, and when it spots some, takes a high resolution
# picture, and sends the picture to PiScreen

import io
import os
import picamera
import ftplib
import time
from datetime import datetime
from PIL import Image
import requests

camera = picamera.PiCamera()
picamera.PiCamera.CAPTURE_TIMEOUT = 30

# If we detect 100 pixels that changed by 30, we have seen movement.
#difference = 30
#pixels = 100
# Desensitise!
difference = 30
pixels = 150

# May as well use the maximum resolution of the camera.
# This is for V1. V2 is 3280 x 2464.
width = 2592
height = 1944

# I copied this voodoo motion detection from somewhere. Changed the timeout
#  setting above to prevent the occasional failures to complete captures.
def compare():
   camera.resolution = (100, 75)
   stream = io.BytesIO()
   format = 'bmp'
   # Handle occasional 'Timed out waiting for capture to end'
   try:
      camera.capture(stream, format)
   except:
      print ("Retrying camera.capture()")
      camera.capture(stream, format)
 
   stream.seek(0)
   im = Image.open(stream)
   buffer = im.load()
   stream.close()
   return im, buffer

# Function to take a new high resolution picture, send it to PiScreen
# send it to my phone, and then delete it.
def newimage(width, height):
    when = datetime.now()
    filename = "door-%04d%02d%02d-%02d%02d%02d.jpg" % (when.year, when.month, when.day, when.hour, when.minute, when.second)
    camera.resolution = (width, height)
    camera.capture(filename)

    connected = True
    ftp = ftplib.FTP()
    ftp.connect("PiScreen")
 
    try:
        ftp.login("pi","**********************************")
    except ftplib.all_errors:
        connected = False
        print ("Failed to connect to server %s" % e) 
     
    if connected:
        ftp.storbinary('STOR '+filename, open(filename, "rb"))
        print ("Sent ", filename)

    ftp.quit()

# Code to send the Pushover message. Make picture smaller first.
    im = Image.open(filename)
#    im.resize((648,486),Image.ANTIALIAS)
    im.resize((324,243),Image.ANTIALIAS)
    im.save(filename)
 
    r = requests.post("https://api.pushover.net/1/messages.json", data = {
        "token": "**********************************",
        "user": "********************************",
        "device": "************",
        "sound": "intermission",
        "message": filename
    },
    files = {
#        "attachment": ("image.jpg", open(filename, "rb"), "image/jpeg")
        "attachment": (filename, open(filename, "rb"), "image/jpeg")
    })
# Check r for problems - maybe put a delay here?
    if r.status_code != 200:
        print("Pushover message failed.")
    else:
        print("Pushover accepted the message.")
       
# Now delete the file.
    os.remove(filename)
    # Delay to avoid being nasty to Pushover server.
    time.sleep(5)

# Main program.

camera.rotation = 180
print("Running door.py")
image1, buffer1 = compare()

newimage(width, height)

while (True):

   image2, buffer2 = compare()

   changedpixels = 0
   for x in range(0, 100):
      for y in range(0, 75):
         pixdiff = abs(buffer1[x,y][1] - buffer2[x,y][1])
         if pixdiff > difference:
            changedpixels += 1

   if changedpixels > pixels:
      newimage(width, height)

   image1 = image2
   buffer1 = buffer2

Friday, June 22, 2018

The Wisdom of the Ancients - Part 94

I tried to find this one one Google, but there was no sign of it!

mpirun mca_oob_tcp_recv_handler  invalid message type: 43

Basically, it means you have not noticed you are trying to control a cluster of Raspberry Pi 3 B+ computers that are running Raspbian Stretch with a Raspberry Pi that has somehow still got Raspbian Jessie on it.

You're welcome!

Oyster, before I got all the bricks.


Monday, January 15, 2018

Marmalade


Marmalade.
I was never all that happy with the previous batch of marmalade I made in 2014. I thought it had been boiled too much, as it was quite a dark colour, and recently, I noticed that what I thought was the last jar was getting quite low.* There are only a couple of weeks of the year when the right oranges for marmalade making are in the shops, and last week I found some in Tesco. I grabbed the last Kilo.





In case you don't know, proper marmalade is made with Seville oranges, named after the part of Spain where they are grown. These oranges are a bitter variety, full of pips. You wouldn't want to eat them, or drink the juice. If you use ordinary oranges, you will end up with some sort of orange jam, that may well be very pleasant, but it won't be marmalade.





If you are not near enough to Spain to have them in the shops, and want to make marmalade, look for something too bitter to enjoy, with unbelievable numbers of pips. The pips are more important than you might think, as they are full of the pectin that makes the marmalade set. 

As well as a Kilo of oranges, you will need two Kilos of granulated sugar, and two lemons. I don't know why Tesco is only stocking foreign sugar, but local shops like Spar and the Co-op do have British sugar, made from beet. [It may have something to do with a certain government minister who used to be high up in that foreign sugar company.]


Ingredients.
1 Kg Seville oranges
2 lemons
2 Kg granulated sugar
500 ml water

These are Seville oranges; look at those pips!















The method. You will need a pressure cooker for this recipe. There are other recipes involving boiling things for hours, and I'm sure they work pretty much as well as this one does, but we have a pressure cooker, and it saves quite a lot of time. Cut the oranges in half, squeeze them with one of those glass juice squeezing things, which I completely forgot to take a picture of. Put the juice, and the peels in the pressure cooker. Add the juice of two lemons, but not their peels. The lemon pips can go in with the orange pips.


I used a plastic strainer to stop the pips going in. There tend to be pips still hiding in the peels, but that can be sorted out at a later stage. The pips get wrapped in a nice open weave cloth, such as cheese-cloth, muslin, or whatever you have handy that seems reasonable to use in cooking. Now add 500 ml of water. The picture on the left is the contents of the pressure cooker before boiling.





And here's a picture of the contents of the pressure cooker after ten minutes of boiling at full pressure, followed by allowing them to cool naturally to room temperature. Notice that the pith of the oranges is cooked, and very much softer than before.



Transfer the juices to your preserving pan. It's nice if you have a big copper plated pan for this, but we use a big old Teflon saucepan. Hooked onto the side, is our old sugar thermometer.



Now you need to squeeze the pips into the pan, until they... no, just squeeze them until you don't think you will get any more out of them. Squeezing pips until they squeak turns out to be really difficult. Only politicians can do it. 

Throw the bag of pips away once you have got as much as you can from it. The pips supply pectin, which is what makes the marmalade set nicely.
Now, chop up the peels to your preferred size chunks. Some people like very fine pieces of peel, while I quite like big chunks. I've cut these ones to a medium size, as my wife prefers them small. Notice that this is when you remove the pips that have been cunningly hiding in the peels. 
Put the chopped up peels in the pan with the juice, and bring them to the boil.
Tip in the two Kilograms of sugar, and stir until it is properly dissolved. Keep heating, and keep stirring. You need to raise the temperature to 105°C.

Warning! Hot, concentrated sugar solution holds much more heat than mere boiling water, and if you splash this on yourself it will burn you badly.

That old sugar thermometer is no longer doing its job properly! It was showing something a bit below 105°C, but I thought the marmalade was looking ready, so I checked it with a cheap electronic thermometer, and as you can see, the marmalade was done! If I had heated it until the old thermometer said it was done, I would have had another batch of over-boiled marmalade.

There are all sorts of ways to test whether your marmalade is going to set, including cold saucers in the fridge, with a splash of marmalade on, but I don't think this recipe can avoid setting, if you follow it properly, and make sure you get it to the magic 105°C.

All that remains to do is put it in clean jars. Dishwashers are the best way to clean jam jars. If you don't have one, you'll have to boil them up in some suitable manner. Below, you see my results. It's very much better looking, and tasting, than the previous batch.


* I found another jar of the old, dark stuff. I threw the contents away.

Saturday, June 03, 2017

Cretan Loukanika - Part 1

We went on holiday for a fortnight in Crete, this year. As ever, I loved the food, and brought back a recipe book. It's not without its problems. I keep meaning to finish a scathing article on the many things recipe books get wrong, but don't hold your breath for me to get that done!

Loukanika are also called village sausages, and the authentic ones in tavernas vary a lot from place to place. I tried to make some before, using a recipe that involved lots of orange zest and paprika, but wasn't really convinced they were anything like the Greek ones we had eaten.




Here's a good example of a problematic recipe! For a start, there's no clue as to how much pepper, cumin, and salt to use. And the method completely forgets to put the pork in... But we can cope with minor problems like that!

I had 1400g of pork shoulder, and ran it through the mincer. They may have meant the sort of malt vinegar that gets put on chips, for all I know, but I made a mixture of red wine vinegar, sherry vinegar, and a splash of balsamic. I used 700g of it, and I can tell you now, that turns out to be about twice as much as is actually necessary. As the vinegar seemed to be intended to cure the meat, I only used 30g of salt. Using the cooking skill known as guesswork, I ground up 20g of black pepper corns, and added 50g of dried cumin. It smelled about right, I felt.
Into the fridge it went, for six days, during which I obtained about forty yards of pig casings, from a UK company called Breck Casings. If you are not in the UK, you should be able to find a supplier easily enough with Google.

When it came to time to stuff the casings, it was obvious the mixture was far too wet, and I used a sieve to attempt to dry it out a bit. Even then, it was a struggle, with vinegar dripping from various parts of the mincer as I worked.

Still, the resulting fourteen sausages looked reasonable. They are tied with butchers' string like that so that they would hang easily over the wire at the top of my large smoking dustbin. You might not be able to see it, but most of the sausages are linked together by unfilled bits of casing. 
We had no cedar wood sawdust, and there was no obvious online source that wasn't asking for absurd amounts of money, so I used oak. You can see I added some herbs, as the recipe suggests, thyme, sage and some very nice Lesbian oregano. The smoker, in case you are wondering, is called a Pro-Q, and it does a very good job.
Here are the sausages, hung up in the smoker (galvanised dustbin) yesterday evening, with the smoke just starting. A few hours later, vinegar dripped on the sawdust and put it out.

I've reloaded the Pro-Q and lit it up again, with the bin tilted so that any further drips miss the sawdust. Once they are smoked, I will be able to report on whether they are more authentic than the previous batch.

Friday, March 10, 2017

Fish, two ways...


This is fish the first way, a salmon fillet with no bones in it, served with some new potatoes, cauliflower, home grown broccoli, and parsley sauce from a packet. It was very pleasant with a white wine to help it on its way. My wife liked it, and there were no bones in the fish to annoy her.

However...


These little beauties are sprats, and they are so cheap that I allow myself a big handful as a treat, when my wife is away. Treat? These cost less than a pound. 

I was asked to make these postings more instructional. So, off with their heads, use the pointy end of the knife to gut them, and shake them in a bowl with a little seasoned flour, until they are covered thinly with it. Heat a pan with some olive oil in it, and put the fish in. The lass in the shop, that sold them to me said she had stirred hers, and they broke up. No surprise, poor little things. After a couple of minutes, turn them over and give the other side a couple of minutes.

This is the result. I got a bit excited, and ate one before I took this picture. The flesh comes off the bones very easily, but it's a good idea to have bread and butter handy, to eat with any bones you might happen to put in your mouth. They won't last five minutes in stomach acid, so it doesn't matter if you eat some.
Then again, if you don't, you will have something like this left. Obviously, they go in your compost bin, and will make things grow well in your garden....

Bon appetite, as we say here in Wales!