Linux KVM – Error: ioctl(KVM_CREATE_VM) failed: 16 Device or resource busy

flattr this!

When you try to install virtual machine with virt-install or the Virtual Machine Manager you get the following Error:

 

root@syss:~# 
virt-install --connect qemu:///system\
--name syss-test\
--ram 1024\
--disk syss-test.img,size=8\
--network=network:default\
--vnc\
--noautoconsole\
--os-type linux\
--accelerate\
--cdrom /home/syss/Downloads/debian-7.6.0-amd64-netinst.iso
Starting install...
ERROR internal error: Process exited while reading console log output: char device redirected to /dev/pts/45 (label charserial0)
ioctl(KVM_CREATE_VM) failed: 16 Device or resource busy
failed to initialize KVM: Device or resource busy

This is mostly because you have either VirtualBox or VMware running on the same machine. The reason (at least that’s what I think) is that the kernel module of VirtualBox or VMware and KVM can’t take Advantage of Intel VT-x or AMD-V at the same time.

So if you want to run both at the same time you have to deactivate the virtualisation in one of them.

This is a way where you can at least have the machines emulated with QEMU

root@syss:~# 
virt-install --connect qemu:///system\
--name syss-test\
--ram 1024\
--disk syss-test.img,size=8\
--network=network:default\
--vnc\
--noautoconsole\
--os-type linux\
--accelerate\
--cdrom /home/syss/Downloads/debian-7.6.0-amd64-netinst.iso\
--virt-type=qemu

Just add –virt-type=qemu at the end. This is not as fast as Intel VT-x or AMD-V but it works in parallell.

Puppet Agent (client) copy-paste script for Debian and Ubuntu

flattr this!

This is a simple script you can copy and paste to your console to install puppet on a new host. You just need to edit the first two lines with the server information and then sign the requested certificate on the puppet master.

# Stefan Süss
# www.sysstem.at
 
#you only need to edit these 2 lines
SERVER_IP=10.0.0.100
SERVER_DNS=puppet.sysstem.at
 
DEBIAN_RLS=$(cat /etc/os-release | grep VERSION= | awk -F '('  '{print $2}' | awk -F ')' '{print $1}')
PUPPET_DEB=puppetlabs-release-$DEBIAN_RLS.deb
PUPPET_CONF=/etc/puppet/puppet.conf
 
#add server IP to hosts
echo "$SERVER_IP  $SERVER_DNS" >> /etc/hosts
#download the right release of puppet
wget https://apt.puppetlabs.com/$PUPPET_DEB
#install the package
dpkg -i $PUPPET_DEB
#update sources
apt-get update
#install puppet. Needs /dev/null . otherwise it would catch the pasted input
apt-get -y install puppet < "/dev/null"
#remove templatedir
sed -i 's/templatedir/#templatedir/g' $PUPPET_CONF
#insert server
#http://www.theunixschool.com/2012/06/insert-line-before-or-after-pattern.html
sed -i "s/.*#templatedir.*/&\nserver=${SERVER_DNS}/" $PUPPET_CONF
#start puppet agent for the first time (generates the certificate)
puppet agent --onetime --verbose --no-daemonize --waitforcert 1
 
#newline

You can also find the script here: Github

Raspberry Pi library for sensors DHT11, BMP085, DS18B20, WireGate DR9490R and more!

flattr this!

Working with sensors on the Raspberry Pi is real fun. You can try out stuff, expand the Internet of things, make automations and so on.

The problem for me was that there were so many different scripts out there with different functionalities and outputs. I wanted to make on package with unified in and output and there it is. It would have never been possible with the excellent work of Adafruit Industries (DHT, DS18B20 and BMP085 driver) and of course Matt Hawkins from www.raspberrypi-spy.co.uk (Ultrasonic and PIR driver)

Currently supported sensors: DHT11, DHT22, AM2302 (temperature and humidity), DS18B20 (temperature, with kernel driver or Wiregate), HC-SR04 (Ultrasonic distance sensor), BMP085 (Temperature, pressure, altitude), PIR (Motion detection)

DHT11, DHT22, AM2302, DS18B20, WireGate DR9490R, HC-SR04 (Ultrasonic Sensor),  BMP085 (Temperate, Pressure, Altitude), PIR

 

You can get the whole package from here: rpi_sensors

Or get it via Github (make sure to put all into one directory)

git clone https://github.com/syss/rpi_sensors
git clone https://github.com/adafruit/Adafruit-Raspberry-Pi-Python-Code/tree/master/Adafruit_BMP085

When you want to use this library you need to install the following packages: python-dev python-smbus owfs-fuse

This can be done by the following command

#update lists and upgrade software first
sudo apt-get update && sudo apt-get upgrade
sudo apt-get install -y python-dev python-smbus owfs-fuse

It is very convenient to load all needed modules on startup. You need to disable the blacklisted modules (default on raspbian image) here:

/etc/modprobe.d/raspi-blacklist.conf

just comment out the blacklist lines with a sharp (#)

# blacklist spi and i2c by default (many users don't need them)

#blacklist spi-bcm2708
#blacklist i2c-bcm2708

then you need to set the modules which should be loaded on startup. You will find them here:

/etc/modules

edit it so it looks like this.

# /etc/modules: kernel modules to load at boot time.
#
# This file contains the names of kernel modules that should be loaded
# at boot time, one per line. Lines beginning with "#" are ignored.
# Parameters can be specified after the module name.

snd-bcm2835
#Used for BMP085
i2c-dev
i2c-bcm2708
spi_bcm2708
#Used for 1-Wire DS18B20
w1-gpio
w1-therm

If you use the Dallas Wiregate (DR9490R) you can do these easy steps to make it work with this python library. (make sure you have installed the package owfs-fuse). I found the commands from this site

sudo mkdir /media/1-wire
sudo owfs --allow_other -u /media/1-wire

Now you are done and can use the Python library for your projects.

Some examples will follow in the next days.

 

 

 

Raspberry Pi VNC Mirror – simplified

flattr this!

This post describes to setup a VNC Mirror on your Raspberry Pi. You can see any desktop of any machine running VNC on your Raspberry Pi’s connected screen. You may come from these posts: Hardening the Raspberry Pi VNC Mirror and Raspberry Pi – VNC Mirror (Repeater) – Make any computer public anywhere which can be a little bit confusing especially when trying to get both into one project. Here in a few easy and understandable steps

Preparation

Download the latest Raspbian Image from the Raspberry Pi site. Unpack it and write the IMG file with Win32DiskImager (on Windows) or dd (on Linux or MAC) on your SD Card (make sure you have at least 4GB).

First Start

When you first start your Raspberry Pi with a monitor it runs raspi-config. If it doesn’t you can rerun it with

sudo raspi-config

In this menu select

Enable Boot to Desktop/Scratch

then

Desktop Log in as user 'pi'...

but say No to reboot, because we want to know the IP address of the raspberry and work via SSH later on. Type

ifconfig

to get your IP address. You may remember it or write it down. Now you can type

reboot

to restart the Raspberry Pi. (Please do not unplug the Raspberry Pi instead of rebooting because your filesystem may get corrupted)

Installing and configuring

On next start login to SSH via PuTTY (or similair SSH client) and standard credentials (pi/raspberry) Start a root console with

sudo bash

Company / Proxy settings

If you are in a company or using proxies you need to set them for updates and upgrades of packages (you don’t need this in most home environments)

nano /etc/apt/apt.conf

and enter your proxy:

    Acquire::http::Proxy "http://user:password@proxy1.sysstem.at:8080";

Update, Upgrade and Install packages

After the proxy settings are done start the update of the package information and the upgrade your packages

apt-get update && apt-get upgrade -y

Install packages needed for maintaining and for the VNC mirror itself

apt-get install -y x11vnc vim ssvnc unp htop

Store VNC Passwords

Generate a hidden directory for the VNC password file

mkdir /home/pi/.vnc

Generate a VNC password for X11VNC

x11vnc -storepasswd /home/pi/.vnc/x11vncpasswd

Store the VNC password of the remotemachine (the password you have defined on the remote machine)

x11vnc -storepasswd /home/pi/.vnc/remotevncpasswd

set read permission for the password files

chmod +r /home/pi/.vnc/*

Scripts

VNCViewer

open the following file

vim /home/pi/vncviewer

and copy the following content (more about it’s content you can find here)

# Process check script: The script simply checks if a process is running and if it is not found to be running it will execute it.
# The script loops in preset intervals, hence it is possible to monitor a process continuously.

# Variables
Running=1
SleepInterval=10
ProcessInstances=`sudo ps aux | grep [s]svncviewer | wc -l`

#VNC Variables
vnc=ssvncviewer
host=WSWDL02:1
display=0
resolution=1920x1080
passfile=/home/pi/.vnc/remotevncpasswd
para="-display :$display -viewonly -fullscreen -shared -passwd $passfile -scale $resolution -encoding zrle"

function checkstatus() {
        vncpid=$(pidof ssvncviewer)
        sigign=$(sudo cat /proc/${vncpid}/status | grep SigIgn | awk '{print $2}')
}

# Logic
while [ $Running -gt 0 ]
do

        if [ `sudo ps aux | grep [s]svncviewer | wc -l` -gt 0 ]; then
                echo Process already running! Checking the Status.
                checkstatus
                if [ $sigign !=  "0000000000000004" ]; then
                        echo SSVNCViewer has not status 4
                        echo Killing SSVNCViewer
                        kill ${vncpid}
                else
                        echo SSVNCViewer status seems to be ok
                fi
        else
                echo Process not running! Starting process
                # This is the command that should start the process in question
                $vnc $host $para &
        fi

        # How often shall we repeat the check?
        echo Sleeping for $SleepInterval seconds
        sleep $SleepInterval

done

exit 0

Change the permission for this script to execute

chmod +x /home/pi/vncviewer

VNCViewer Daemon

Make a little Daemon for the vncviewer to start and stop it.

vim /etc/init.d/vncviewerd

enter the following

### BEGIN INIT INFO

# Provides: vncviewerd
# Required-Start: $remote_fs $syslog
# Required-Stop: $remote_fs $syslog
# Default-Start: 2 3 4 5
# Default-Stop: 0 1 6
# Short-Description: Start or stop Custom VNC Viewer
# Description: Start or stop Custom VNC Viewer
### END INIT INFO
#! /bin/sh
# /etc/init.d/monitor
# Carry out specific functions when asked to by the system

#Start vncviewer
start() {
    echo Starting VNC Viewer
    su pi /home/pi/vncviewer &
}
#Stop vncviewer
stop() {
    echo Stopping VNC Viewer
    pkill -f vncviewer
}

### main logic ###
case "$1" in
    start)
        start
        ;;
    stop)
        stop
        ;;
    restart|reload)
        stop
        start
        ;;

    *)
        echo "Usage: $0 {start|stop|restart|reload}"
        exit 1
esac
exit 0

Make the script executable

chmod +x /etc/init.d/vncviewerd

and register it for autostart

update-rc.d vncviewerd defaults

Monitor

Create a script for turning on and off your monitor

vim /etc/init.d/monitor

enter the following

### BEGIN INIT INFO

# Provides: monitor
# Required-Start: $remote_fs $syslog
# Required-Stop: $remote_fs $syslog
# Default-Start: 2 3 4 5
# Default-Stop: 0 1 6
# Short-Description: Start or stop Monitor
# Description: Start or stop Monitor
### END INIT INFO
#! /bin/sh
# /etc/init.d/monitor
# Carry out specific functions when asked to by the system

#Start Monitor
start() {
    echo Starting Monitor
    # Enable HDMI with preferred mode
    /opt/vc/bin/tvservice -p
    # Change console to enable monitor output
    # not very nice but ok
    sudo chvt 6
    sudo chvt 7
}
#Stop Monitor
stop() {
    echo Stopping Monitor
    /opt/vc/bin/tvservice -o
}

### main logic ###
case "$1" in
    start)
        start
        ;;
    stop)
        stop
        ;;
    restart|reload)
        stop
        start
        ;;

    *)
        echo "Usage: $0 {start|stop|restart|reload}"
        exit 1
esac
exit 0

Make it executable (but do not add it to autostart!)

chmod +x /etc/init.d/monitor

Miscellaneous Monitor settings

Disable monitor standby

vim /etc/kbd/config

search for POWERDOWN_TIME=30 and set it to 0

POWERDOWN_TIME=0

Restart KBD to activate new settings

sudo /etc/init.d/kbd restart

Disable overscan (it tries shrink the picture a little to fit on older monitors and TVs)

vim /boot/config.txt

remove the sharp (#) from #disable_overscan=1 it should now look like this

disable_overscan=1

Now it’s time to reboot your Raspberry VNC Mirror.

reboot

If you have questions or problems left leave them in the comments!

Get model number and more details of your Raspberry Pi

flattr this!

For better programming with GPIO on the Raspberry Pi it is required to know on which board revision the program is running on.

The following programcode is best used to determine which GPIO ports are available for interacting.

#!/usr/bin/python
# -*- coding: utf-8 -*- 
################################################
# Stefan Süss - www.sysstem.at
################################################

# Listmodel from http://elinux.org/RPi_HardwareHistory
class BoardRevision(object):
        def __init__(self,revision,releasedate,model,pcbrevision,memory,notes):
            self.revision=revision
            self.releasedate=releasedate
            self.model=model
            self.pcbrevision=pcbrevision
            self.memory=memory
            self.notes=notes

#http://elinux.org/RPi_Low-level_peripherals#GPIO_hardware_hacking
pcb_r1_gpio_ports= (0,1,4,7,8,9,10,11,14,15,17,18,21,22,23,24,25)
pcb_r2_gpio_ports= (2,3,4,7,8,9,10,11,14,15,17,18,22,23,24,25,27,28,29,30,31)            

# Listcontent from http://elinux.org/RPi_HardwareHistory
boardrevisionlist=[]
boardrevisionlist.append(BoardRevision("Beta","Q1 2012","B (Beta)","unknown",256000000,"Beta Board"))
boardrevisionlist.append(BoardRevision(0x0002,"Q1 2012","B",1.0,256000000,""))
boardrevisionlist.append(BoardRevision(0x0003,"Q3 2012","B (ECN0001)",1.0,256000000,"Fuses mod and D14 removed"))
boardrevisionlist.append(BoardRevision(0x0004,"Q3 2012","B",2.0,256000000,"(Mfg by Sony)"))
boardrevisionlist.append(BoardRevision(0x0005,"Q4 2012","B",2.0,256000000,"(Mfg by Qisda)"))
boardrevisionlist.append(BoardRevision(0x0006,"Q4 2012","B",2.0,256000000,"(Mfg by Egoman)"))
boardrevisionlist.append(BoardRevision(0x0007,"Q1 2013","A",2.0,256000000,"(Mfg by Egoman)"))
boardrevisionlist.append(BoardRevision(0x0008,"Q1 2013","A",2.0,256000000,"(Mfg by Sony)"))
boardrevisionlist.append(BoardRevision(0x0009,"Q1 2013","A",2.0,256000000,"(Mfg by Qisda)"))
boardrevisionlist.append(BoardRevision(0x000d,"Q4 2012","B",2.0,512000000,"(Mfg by Egoman)"))
boardrevisionlist.append(BoardRevision(0x000e,"Q4 2012","B",2.0,512000000,"(Mfg by Sony)"))
boardrevisionlist.append(BoardRevision(0x000f,"Q4 2012","B",2.0,512000000,"(Mfg by Qisda)"))

def getRevision():
    revisionstring="Revision"
    revision="unknown BoardRevision"
    with open("/proc/cpuinfo","r") as file:
        for line in file.readlines():
            if line.find(revisionstring)!=-1:
                revision="0x"+line.split(":")[1][1:-1]           
    return revision

def getBoardRevision(revision=getRevision()):
    try:
        #only check the last 2 Bytes for revision (ingore overvoltage indicator)
        #http://elinux.org/RPi_HardwareHistory
        revision=int(revision,16)&0xFFFF
    except ValueError:
        revision=revision
    for boardrevision in boardrevisionlist:
        if revision == boardrevision.revision:
            return boardrevision
    return "unknown BoardRevision"

def getGPIOPorts():
    rpi=getBoardRevision()
    try:
        if rpi.pcbrevision == 1.0:
            return pcb_r1_gpio_ports
        if rpi.pcbrevision == 2.0:
            return pcb_r2_gpio_ports
        else:
            return ()
    except AttributeError:
        return ()

def hasBeenOverVolted():
    ovvalue=0x1000000
    try:
        ov=int(getRevision(),16)&ovvalue
        if ov==ovvalue:
            return 1
        else:
            return 0
    #could not determine due to error in reading Revision
    except ValueError:
        return -1

An example of how you can use the code:

#!/usr/bin/python
import rpi_version

print "GPIO Ports: ", rpi_version.getGPIOPorts()
print "Has been overvolted: ",rpi_version.hasBeenOverVolted()
rpi=rpi_version.getBoardRevision()
try:
    print       "Revision: ",hex(rpi.revision)
    print       "Releasedate: ",rpi.releasedate
    print       "Model: ",rpi.model
    print       "PCB Revision: ",rpi.pcbrevision
    print       "Memory: ",rpi.memory*10**-6,"MB"
    print       "Notes: ",rpi.notes
except ValueError:
    print "Could not detect model"

Output:

GPIO Ports:  (2, 3, 4, 7, 8, 9, 10, 11, 14, 15, 17, 18, 22, 23, 24, 25, 27, 28, 29, 30, 31)
Has been overvolted:  0
Revision:  0xd
Releasedate:  Q4 2012
Model:  B
PCB Revision:  2.0
Memory:  512.0 MB
Notes:  (Mfg by Egoman)

I hope that you save some time by using my python code!

 

 

Raspberry Pi – Only Red (Power) LED is on – Raspberry Pi does not boot

flattr this!

Have you had this problem? You bought a new Raspberry Pi, flashed a new Image from http://www.raspberrypi.org/downloads (2013-09-25-wheezy-raspbian.zip) and powered in on. What I see is that it does not work. The red power LED is on only and very low light from the ACT LED which does not do anything.
Luckily I had lots of different RPis and SD cards available to dertermine the fault.I tried all combinations with these µ/SD cards and adapters. Here the results:

  • San Disk SD card works on RPi China + RPi UK
  • The Samsung and the SanDisk µSD cards with the San Disk adapter works with both the Raspberry Pis
  • The Samsung and the SanDisk µSD cards with the Samsung adapter works with the Raspberry Pi made in China but it does NOT work with the Raspberry made in UK.

Raspberry Pis with SD+µSD Cards+Adapter

This is a very interesting thing I have not experienced before. I thought all adapters were the same and there could not be any differnce, but there is.

So before declaring your fresh and new Raspberry Pi as faulty check it with another SD card and try to avoid adapters for testing purposes.

7 Segment Display with 74HC595 Shift Register and Raspberry Pi

flattr this!

This project shows how to use the Raspberry Pi to drive a 7 Segment Display with the help of a 74HC595 chip.

Parts used in this project:

  • Breadboard
  • Wiring cables (Male-Male, Female-Male)
  • 7 Segement display (it actually has 8 segments because of the dot)
  • 74HC595 Chip
  • Raspberry Pi Revision 2
  • some Python code

Here is a schematic made with fritzing of the project when it is ready. Here a link to download the 7-segment-display with 74HC595 and Raspberry Pi fritzing project.

7-Segment-Display_Steckplatine

the interresting thing here is the 74HC595 Chip. It takes some time to understand what it does. I think that the video from Kevin Darrah describes it fast and easy.

Here is the Python code: rpi_7_segment_74hc595

#!/usr/bin/python

import RPi.GPIO as GPIO
import time

#Data Pins needed on the RPi
DATAIN=17 #DS
LATCH=27  #STCP
CLOCK=22  #SHCP
CLEAR=25  #MR Low
OE=11     #Output Enable Low

#inter character sleep
icsleep=0.06 

#defining all the single LEDs
led1=0x80 #10000000
led2=0x40 #01000000
led3=0x20 #00100000
led4=0x10 #00010000
led5=0x08 #00001000
led6=0x04 #00000100
led7=0x02 #00000010
led8=0x01 #00000001

#definition of all writeable letters and numbers
letter={"0":0xFC,
        "1":0x30,
        "2":0xDA,
        "3":0x7A,
        "4":0x36,
        "5":0x6E,
        "6":0xEE,
        "7":0x38,
        "8":0xFE,
        "9":0x3E,
        "a":0xBE,
        "b":0xE6,
        "c":0xCC,
        "d":0xF2,
        "e":0xCE,
        "f":0x8E,
        "g":0x7E,
        "h":0xB6,
        "i":0x30,
        "j":0xF0,
        "l":0xC4,
        "n":0xBC,
        "o":0xFC,
        "p":0x9E,
        "s":0x6E,
        "t":0x38,
        "u":0xF4,
        "x":0xB4,
        "y":0x76,
        "z":0xDE
}

#loading function sequence
load1=0x06 #00000110
load2=0x22 #00100010
load3=0x60 #01100000
load4=0xC0 #11000000
load5=0x82 #10000010
load6=0x12 #00010010
load7=0x18 #00011000
load8=0x0C #00001100

#up-down loading function sequence
ud1=led8
ud2=led2
ud3=led1+led3
ud4=led7
ud5=led6+led4
ud6=led5

#left-right loading function sequence
lr1=led1+led6
lr2=led2+led5+led7
lr3=led3+led4
lr4=led8

#rotational loading function sequence
rot1=led2+led5
rot2=led1+led6+led3+led4+led7

#putting all segments of the sequences in a list
letterrange=[]
hexrange=[]
for value in letter.values():
    letterrange.append(value)
for value in letter.values():
    if value != "g":
        hexrange.append(value)
loadrange=[load1,load2,load3,load4,load5,load6,load7,load8]
udrange=[ud1,ud2,ud3,ud4,ud5,ud6]
ledrange=[led1,led2,led3,led4,led5,led6,led7,led8]
lrrange=[lr1,lr2,lr3,lr4]
rotrange=[rot1,rot2]
spinrange=[led1,led2,led3,led4,led5,led6]

#GPIO definition
def setup():
    GPIO.setmode(GPIO.BCM)
    GPIO.cleanup()
    GPIO.setup(DATAIN,GPIO.OUT)
    GPIO.setup(CLOCK,GPIO.OUT)
    GPIO.setup(LATCH,GPIO.OUT)
    GPIO.setup(CLEAR,GPIO.OUT)
    GPIO.setup(OE,GPIO.OUT)

    GPIO.output(LATCH,False) #Latch is used to output the saved data
    GPIO.output(CLEAR,True)  #Clear must always be true. False clears registers
    GPIO.output(OE,False)    #Output Enable speaks for itself. Must be False to display
    GPIO.output(CLOCK,False) #Used to shift the value of DATAIN to the register
    GPIO.output(DATAIN,False)#Databit to be shifted into the register 

    #Clean up GPIO, set display to no character
def cleanup():
    #Set all leds to off
    writenumber(0)
    #writeout stored in character
    writeout()
    #writeout "nothing"
    writeout()
    time.sleep(0.7)
    GPIO.cleanup()

#shifts in a bit (but does not write it yet)
def shift(input):
   if input == 1:
       input=True
   else:
       input=False

   GPIO.output(DATAIN,input)
   GPIO.output(CLOCK,GPIO.HIGH)
   GPIO.output(CLOCK,GPIO.LOW)
   GPIO.output(DATAIN,GPIO.LOW)

#writes the stored data from register out to pins
def writeout():
   #Display LEDs
   GPIO.output(LATCH,GPIO.HIGH)
   #needed to read characters. otherwise the characters would be display to fast after each other
   time.sleep(icsleep)
   GPIO.output(LATCH,GPIO.LOW)

#writes a character to the register
def writenumber(number):
    for x in range(0,8):
        shift((number>>x)%2)

#writes a range of character to the display        
def writerange(range):
    for x in range:
        writenumber(x)
        writeout()

#additive and following substractive writeout of a range of characters
def writeaddrange(range):
    character=0
    for x in range:
        character+=x
        writenumber(character)
        writeout()
    for x in range:
        character-=x
        writenumber(character)
        writeout()

#additive and following substractive writeout with reversed call of a range of characters
def writeaddremrange(range):
    character=0
    for x in range:
        character+=x
        writenumber(character)
        writeout()
    for x in range:
        character-=x
        writenumber(character)
        writeout()
    for x in reversed(range):
        character+=x
        writenumber(character)
        writeout()
    for x in reversed(range):
        character-=x
        writenumber(character)
        writeout()

#additive and following reversed substractive writeout of characters        
def writeaddbackrange(range):
    character=0
    for x in range:
        character+=x
        writenumber(character)
        writeout()
    for x in reversed(range):
        character-=x
        writenumber(character)
        writeout()

#chained XORed and reversed XORed writeout of characters
def writexorrange(range):
    #close the chain to have no interrupts while displaying
    character=range[0]&range[-1]
    for x in range:
        character^=x
        writenumber(character)
        writeout()
    for x in range:
        character^=x
        writenumber(character)
        writeout()
    for x in reversed(range):
        character^=x
        writenumber(character)
        writeout()
    for x in reversed(range):
        character^=x
        writenumber(character)
        writeout()

print("####Setup####")
setup()

#Tryout of most ranges and displayfunctions
try:
    print("####Write Stuff####")
    while True:
        writerange(letterrange)
        writerange(hexrange)
        writerange(loadrange)
        writeaddremrange(udrange)
        writexorrange(loadrange)
        writexorrange(udrange)
        writexorrange(ledrange)
        writexorrange(lrrange)
        writexorrange(rotrange)
        writexorrange(spinrange)
        writeaddrange(ledrange) 
        writeaddbackrange(ledrange)
#Wait for KeyboardInterrupt or SystemExit (called by kill or others)
except (KeyboardInterrupt, SystemExit):
    print("Exit...")

finally:
    cleanup()

Raspberry Pi drives a 7 Segment Display with the help of a 74HC595.

Have fun driving your 7 Segment display with the Raspberry Pi.

ZXX Font & OCR – some thoughts

flattr this!

It is in all media that Edward Snowden has revealed the surveillance activities of the NSA. This act of spionage can be criticised as an break-in into the privacy of every person’s life.

Therefore Sang Mun has released a Font called ZXX which makes it more difficult for automated optical character recognition (OCR) programs to detect letters. Here a german article from the austrian online newspaper derstandard.at

I have looked on this font with great interrest and think that this could be a great way to avoid automated spionage from others.

When you watch the ZXX Type Secimen Video you will be surprised by how easy you can confuse OCR programs. The most interessting thing for me were the XED and the noise font. It just adds either a thin cross (X) or optimised “random” pixels to the letters where humans are still able to read the text pretty fast. This is not the case for the Camo Font. More to that later.

So thinking of this, why is a human being able to read the Xed and noised text, while computers can’t? The answer was simple for me. (this might not be scientifically proven). The human eye takes a look at a picture and tries to recognise something. If not it focuses or “zooms in and out” to remember the patterns we have all learned in early school years. Moreover we do not only have one point of view, we have two of them. There are two eyes with maybe two different focuspoints which makes us able to see letters behind all that camouflaging stuff. A very easy trick to solve CAPTCHAs and to read the ZXX font is to unfocus the stuff you want to read. It looks blurry. There was a program which I had in mind which can do this for me.

Simple as that I tried it – with success. Have a look at your own.

I took a sample picture from ZXX and cut off the stuff on the side (for better reading)

ZXX sample

 I uploaded this onlineocr.net

This is the result:

ABCDEFGHIJKLMNOPUPST
UVWXYZabcdefghijklmn
opqrstuvwxyz00123450
789%\!?@#/&*().,:$£
+x÷±-=-_"°154afyX%%[]
ABCDEFGHIJKLMNOPUPST
UVWXYZabcdefghijklmn
opqrstuvwxyz00123450
789%\!?@#/&*().,:$
+x÷±-=-_"1@4afyflfl?[]
IMBODffiGliffiktMNOPRPSt
UVWOWEabedgeflijklms
owettAvw*gzelS/2@xtga
U;flZYXWVUTSPUPONML
KJIHGEEDCBAzyxwvutsr
ciponmIkjihgfedcbagg8
765432101 ?ABCDEFGHI3,
KEMNOPR•STUVWXYZabcd
afghilkImnopqrstwvwx
wii01.2345878gRIA22DE 
NW N■v1.• • • 
• • wawl0K461ISdielP•E*
4.*AP101010104.: 
twintootra21224Rea,a

As you can see only some of the characters are found be the program.

If I blur the image all the confusing stuff (for the OCR Software) is removed or partly removed, so that the matches are higher than before. See for yourself.

Blurred image:

zxx-blurred

 

and this is the result.

ABCDEFGHIJKLIANOPOPST
UVWXYZabcdefqhijklmn
opqrstuvwxyz00123450
789%\!?@0/&*(),,:WO
+x+t-m-_".0:42fOgq]
ABCDEFGHIJKLMNOPOPST
UVWXYZabcdefqh1jklmn
opqrstuvwxyz00123450
789%"?"/"().,:$EV
+x-ft-m-_".11:saiyfint[]
IMOCIVIIIJK5M4GPOOSI
UVIORYilabcdsfeit311Imm
opqrstswesszt62234Vd
Re914ZYKWVUTSPOPONML
KJIHGFEDCBAzyxwvutsr
qponmlkjihgfedcba998
70543210!?ABCDEFGHIJ
KLMNOPOPSTUVWXYZebcd
•ighijklionopqrstuvws
yz00123450789? IABCDE
FGHIJKLMNOPOPSTUVWXY
Zabcdefighijklmnopqrs
tuvwxyz0012345078931

I think this is a remarkable difference to the original image.

I also have some words to the two other fonts.

The False font can be easily trained as I have been trained by the video. One needs to search for a big letter, but does not take its information. Instead you search for another letter within the smallest rectangle you can fit around the big letter you just found. (to explain it technically ;-) )

The Camo font is a real hard one. If you simply read the Camo alphabet it is easy to see the letters, because you expect the very next letter. And with this image in mind you procet the vectors over the image you see where it is easy to recognise. Some sort of this is also used in examples of optical illusion. What I have in mind is the Kanizsa triangle.

Kanizsa_triangle.svg

Image from the Wikimedia Commons

You as human see a white triangle where really is none. You just have some points or “suggestions” of vectors and your brain finishes them to form this triangle.

 

Windows Command Line – Password function

flattr this!

Here is a little password function if you need it. Be aware that it is very slow, don’t type too fast. ;) It’s more a concept than a tool you can work with.

Just Enter your password and hit ALT+222 (on your numblock) to terminate.

@echo off
setLocal EnableDelayedExpansion

set allchar=Þ1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ
set pw=

echo Please enter password SLOWLY and terminate with ALT+222
:pwloop
choice /C %allchar% /CS >nul
set cint=%errorlevel%
set /a cint-=1
set pw=%pw%!allchar:~%cint%,1!
if %cint% neq 0 goto pwloop

set pw=%pw:~0,-1%
echo %pw%
set pw=
pause>nul

Here a picture for proof of concept

Commandline-password

Windows Command Line – Service Menu

flattr this!

If you have a collection of CMD Tools you fast loose the overview of what you have. For this I have developed a little menu where you can choose from your programs by name.

Here is the Main Menu

menu-and-logo-ready-to-use

 

You can create your own logo with the following steps.

copy-ascii-logo

 

  • Search and replace all occurences of | with ^| (Mostly found with CTRL+H)

replace-special-characters

 

  • Add echos and some extras

main-menu-with-extras

  •  Copy it into your menu

The good thing about this menu is, that you don’t have to search in a big script for stuff. You just alter this file here

rem Variables
@echo off

call :Var "%source%\Add printer.vbs"				"Add a Printer"
call :Var "%source%\all-printers-settings.cmd"	"Apply BW Print to all Printers"
call :Var "%source%\printercolor.cmd"	"Apply Color Print to one Printer"
call :Var "%source%\AddWSUSURLs.cmd"				"Add WSUS to Registry"
call :Var "%source%\Softphone.cmd"				"Set Softphone DW"
call :Var "%source%\userinfo.cmd"				"User Information + Services"
call :Var "%source%\connectionstab.cmd"			"IE Connections Tab - Internet Explorer Verbindungen Reiter"
call :Var "%source%\dfue.cmd"						"Create DFUE"
call :Var "%source%\austria.hol"					"Outlook Holidays 2013-2015"
call :Var "%source%\office-languagepacks.cmd"		"Office Language Packs"
call :var "%source%\Abfragegenerator2007.cmd"			"Query Builder - Abfragegenerator Office 2007"
call :var "%source%\Terminal-Autologin.cmd"			"Terminal Autologin"
call :Var "%source%\VM2-ODBC.cmd"			"Versandmodule 2 - ODBC Settings"
call :var "%source%\Lawi-setup.cmd"			"Lawi Setup"
call :Var "%source%\lawi-etikett.cmd"			"Lawi Etikett"
call :var "%source%\emppack.cmd"			"Install Empirum Package"
call :var "%source%\EmpirumAgent.cmd"			"Install Empirum Agent"

goto :end

rem Variables
:Var
set /a id+=1
set /a nextpage=%id%%9
if [%nextpage%] EQU [0] set /a menumaxsiteindex+=1
rem set %id%.name=%1&& shift
set %id%.path=%1&& shift
set %id%.description=%1
goto:EOF

:end

And here is the menu where you put your logo

@echo off
cls
setLocal EnableDelayedExpansion

set version=0.6
set menusiteindex=0
set menumaxsiteindex=0
set id=0
set uid=0

rem Choose Source
call :ChooseSource
rem User Variables
if exist "%source%\uservar.cmd" (call "%source%\uservar.cmd") else (call "%source%\..\uservar.cmd")
rem Program Variables
if exist "%source%\progvar.cmd" (call "%source%\progvar.cmd") else (call "%source%\..\progvar.cmd")

set /a menumaxsiteindex=%id%/9+1
rem Variables

:ServiceLoop
call :MenuMapping
call :WriteScreen !%menu_1%.description! !%menu_2%.description! !%menu_3%.description! !%menu_4%.description! !%menu_5%.description! !%menu_6%.description! !%menu_7%.description! !%menu_8%.description! !%menu_9%.description!
goto:ServiceLoop

rem ***************************************************************************
rem * Functions
rem ***************************************************************************

:WriteScreen
cls
call :Logo
call :Menu %*
call :MenuChoice
goto:EOF

:MenuMapping
set prefix=%1
for /L %%a in (1,1,9) do (
	set menuindex=%%a
	set /a menu_%prefix%!menuindex!=!menuindex!+!menusiteindex!*9"
)
goto:EOF

:Logo
rem http://patorjk.com/software/taag/#p=display&f=Doom&t=www.sysstem.at
echo *******************************************************************************
echo *******************************************************************************
echo                                                 _                        _   
echo                                                ^| ^|                      ^| ^|  
echo __      ____      ____      _____ _   _ ___ ___^| ^|_ ___ _ __ ___    __ _^| ^|_ 
echo \ \ /\ / /\ \ /\ / /\ \ /\ / / __^| ^| ^| / __/ __^| __/ _ \ '_ ` _ \  / _` ^| __^|
echo  \ V  V /  \ V  V /  \ V  V /\__ \ ^|_^| \__ \__ \ ^|^|  __/ ^| ^| ^| ^| ^|^| (_^| ^| ^|_ 
echo   \_/\_/    \_/\_/    \_/\_(_)___/\__, ^|___/___/\__\___^|_^| ^|_^| ^|_(_)__,_^|\__^|
echo                                    __/ ^|                                     
echo                                  ^|___/                                    
echo ***************************************************Phone: 0043123456       ****
echo ***************************************************Email: admin@sysstem.at ****
echo.
goto:EOF

:Menu
set menucount=0
set choicestr=

rem http://www.robvanderwoude.com/parameters.php
:Loop
if [%1]==[] GOTO MenuFooter
	rem counter
	set /a menucount+=1
	rem save parameters in variables
	set _%menucount%=%1
	rem dequote variables
	call :DeQuote _%menucount%
	rem [Number] variable value
	echo [%menucount%] !_%menucount%!
	rem add Menunumber to string
	set choicestr=%choicestr%%menucount%
	rem get next parameter
	shift
goto Loop
:MenuFooter
echo.
echo [N]ext [P]revious [F]irst [L]ast [G]oto Page [A]dmin [E]xit
set choicestr=%choicestr%NPFLGAE
goto:EOF

:MenuChoice

choice /c %choicestr%
set /a menuchoice=%errorlevel%
set /a length=%menuchoice%-1
set programid=!menu_%menuchoice%!

if !menuchoice! LEQ !menucount! (
	start !%programid%.description! !%programid%.path!
) else (
	call :MenuSelection !choicestr:~%length%,1!
)
goto:EOF

:MenuSelection
set selection=%1
if /I [%selection%] equ [N] call :NextPage
if /I [%selection%] equ [P] call :PreviousPage
if /I [%selection%] equ [F] call :FirstPage
if /I [%selection%] equ [L] call :LastPage
if /I [%selection%] equ [G] call :GotoPage
if /I [%selection%] equ [A] call :Admin
if /I [%selection%] equ [E] call :Exit
goto:EOF

:NextPage
set /a maxpage=%menumaxsiteindex%-1
if [%menusiteindex%] LSS [%maxpage%] (
	set /a menusiteindex+=1
) else echo This is already the last page &pause>nul
goto:EOF

:PreviousPage
if [%menusiteindex%] GTR [0] (
	set /a menusiteindex-=1
) else echo This is already the first page &pause>nul
goto:EOF

:FirstPage
set /a menusiteindex=0
goto:EOF

:LastPage
set /a menusiteindex=%menumaxsiteindex%-1
goto:EOF

:GotoPage
set /p gotopage="Please enter pagenumber: "
set /a gotopage-=1
if %gotopage% GEQ 0 (
	if %gotopage% LSS %menumaxsiteindex% (
		set /a menusiteindex=%gotopage%
	) else echo No valid page number&pause>nul
) else echo No valid page number&pause>nul
goto:EOF

:Admin
2>nul 1>nul start "%source%\runasadmin.exe" "%~dpf0"&&exit||(echo.&echo Could not get Admin rights.&pause>nul)
goto:EOF

:Exit
exit
goto:EOF

rem ******************************************
rem * Removes Quotes
rem * http://ss64.com/nt/syntax-dequote.html
rem ******************************************

:DeQuote
SET _DeQuoteVar=%1
CALL SET _DeQuoteString=%%!_DeQuoteVar!%%
IF [!_DeQuoteString:~0^,1!]==[^"] (
IF [!_DeQuoteString:~-1!]==[^"] (SET _DeQuoteString=!_DeQuoteString:~1,-1!
) ELSE (GOTO :EOF)
) ELSE (GOTO :EOF)
SET !_DeQuoteVar!=!_DeQuoteString!
SET _DeQuoteVar=
SET _DeQuoteString=
GOTO :EOF

:ChooseSource
set workingdir=%~dp0
set workingdir=%workingdir:~0,-1%
if exist "%workingdir%\CMDTools" (set source=%workingdir%\CMDTools
) else (
	set source=\\backupserver\CMDTools
)
GOTO:EOF

 

This currently only runs on Windows 7 (have not tested Windows 8, but should work too) because Windows XP does not bring choice.exe

And before I forget: you have to provide all the tools for yourselfs. But let me know if you are interessted in one of these mentioned here.

Technical information, scripts, codes and more

%d Bloggern gefällt das: