PDF-Schnittmuster zusammenfügen

vintage sewing patterns

Manchmal is es nötig aus vielen einzelnen PDF-Seiten eine große ganze zusammenzufügen. Das ist z.B. nötig wenn man ein Schnittmuser auf vielen Seiten verteilt ist, aber man den ganzen Plan ausdrucken will.

Dafür gibt es einige Methoden z.B. ein shell script mit Hilfe von [pdftk CLI] und [imagemagick], jedoch nur unter Linux / OSX. Beide Programme gäbe es auch als Windows Versionen jedoch mit GUI und daher eine anstrengende „Klickerei“ auf Dauer, also alles andere als einfach und deshalb hier eine einfachere Methode um PDFs zusammenzufügen.

LaTeX Variante

Für diese Methode benötigt man das Ausgangs-PDF (mit den einzelnen Schnittmuster-Seiten) und Zugang zu LaTeX. Dafür benötigt man jedoch keine Installation man kann dies online sehr einfach machen.

Weiterlesen

Advertisements

Raspberry Pi + TI Sensortag + Plotly

In the last post (Raspberry Pi 2 TI Sensortag) I recapped the possibility to use Raspberry Pi to connect with BLE to a TI Sensortag using the bluepy-library.

A logical next step is to push the data to the „cloud“.

First register under https://plot.ly/ go to settings and note your API Key and your tokens (create two).

To use it with the Raspberry Pi ssh into it (or use a terminal) and install the prerequistes:
sudo apt-get install python-dev
sudo apt-get install python-pip
sudo pip install rpi.gpio
sudo pip install plotly

The next step is to create a script which uploads the streaming data plot.ly, it is heaviliy based on this intructable from plotlygraphs:

import plotly.plotly as py
from plotly.graph_objs import Scatter, Layout, Figure, Data
import time
import datetime
import sensortag

username = 'your_username'
api_key = 'your_api_key'
stream_token1 = 'one_unique_token'
stream_token2 = 'another_unique_token'

py.sign_in(username, api_key)

trace1 = Scatter(
    x=[],
    y=[],
    name='Ambient Temp.',
    stream=dict(
        token=stream_token1,
        maxpoints=5000
    )
)
trace2 = Scatter(
    x=[],
    y=[],
    name='IR Temp.',
    stream=dict(
        token=stream_token2,
        maxpoints=5000
    )
)

layout = Layout(
    title='Raspberry Pi Streaming Sensor Data',
    showlegend=True,
    autosize=True
)

data = Data([trace1,trace2])
fig = Figure(data=data, layout=layout)

print(py.plot(fig, filename='Raspberry Pi Streaming Example Values'))

# activate sensortag
intervall = 20 # seconds
print "Push button on sensortag"
time.sleep(2.0)
tag = sensortag.SensorTag('BC:6A:29:AC:53:D1')

time.sleep(1.0)
tag.IRtemperature.enable()
print("Connected")

i = 0
stream1 = py.Stream(stream_token1)
stream1.open()

stream2 = py.Stream(stream_token2)
stream2.open()


#the main sensor reading loop
while True:
    sensor_data = tag.IRtemperature.read()
    now = datetime.datetime.now()
    stream1.write({'x': now, 'y': sensor_data[0]})
    stream2.write({'x': now, 'y': sensor_data[1]})
    i += 1
        # wait for new measurement
    tag.waitForNotifications(intervall)
    if i > 100:
        break

stream1.close()
stream2.close()
tag.disconnect()
print("Finished!")

The result looks somthing like this.

Raspberry Pi 2 BLE TI Sensor Tag

Install necessary packages:
sudo apt-get install bluez-utils libopenobex1 build-essential libglib2.0-dev libdbus-1-dev

Restart the bluetooth service
sudo service bluetooth restart

Scan for BLE enabled devices connected to the Raspberry Pi:
hciconfig --all

hci0: Type: BR/EDR Bus: USB
BD Address: 00:1A:7D:DA:71:0C ACL MTU: 310:10 SCO MTU: 64:8
UP RUNNING PSCAN
...

Scan for BLE devices:
sudo hcitool lescan

BC:6A:29:AC:53:D1 SensorTag
F4:F9:51:C7:4C:23 (unknown)
BC:6A:29:AC:53:D1 (unknown)
BC:6A:29:AC:53:D1 SensorTag
BC:6A:29:AC:53:D1 (unknown)
...

It shows two devices, but we are only interrested in the Sensor Tag. The adress is BC:6A:29:AC:53:D1 (this address may be different with each device).
So we know bluetooth is working and the mac address of the sensor tag.

Next step is to download/install the great bluepy library from Ian Harvey:
git clone https://github.com/IanHarvey/bluepy.git
cd bluepy/bluepy
make

To read now sensor data from the sensortag, use the example script sensortag.py:
usage: sensortag.py [-h] [-n COUNT] [-t T] [-T] [-A] [-H] [-M] [-B] [-G] [-K]
[--all]
host

positional arguments:
host MAC of BT device

optional arguments:
-h, --help show this help message and exit
-n COUNT Number of times to loop data
-t T time between polling
-T, --temperature
-A, --accelerometer
-H, --humidity
-M, --magnetometer
-B, --barometer
-G, --gyroscope
-K, --keypress
--all

I.e. to read the temperature five times in an interval of 0.5 seconds we use:
python sensortag.py BC:6A:29:AC:53:D1 -n 5 -t 0.5 -T
then press the button on the side of the sensortag
Connecting to BC:6A:29:AC:53:D1
('Temp: ', (31.71875, 30.4396374686782))
('Temp: ', (31.75, 28.29441505369789))
('Temp: ', (31.71875, 27.21886394070981))
('Temp: ', (31.71875, 27.21886394070981))
('Temp: ', (31.71875, 28.54570004702458))

It is also possible (without any changes to the sensortag.py-script) to use it as a python script:
import time
import sensortag

tag = sensortag.SensorTag('BC:6A:29:AC:53:D1')

time.sleep(1.0)
tag.IRtemperature.enable()
for i in range(5):
tag.waitForNotifications(1.0)
print tag.IRtemperature.read()
tag.disconnect()
del tag

One remark if you want to import the module from another folder I recommend adding to the __init__.py file the line:
from . import *
Than it is possible to import the package with realtive importing like:
from bluepy.bluepy import sensortag

Reading Analog Light Sensor Values via WIFI

Recently I got a Texas Instruments MSP430F5229 Launchpad and seached for an easy way to try it with my CC3000 Boosterpack. One of the first ideas was a wireless sensor node with a simple web server providing data for late analysis.

First the controller reads an analog value from an light sensitive resistor and than it provides a JSON file for download (especially for its flexibility to add or change values / parameters) which is polled. This analyisis and safe-step was done via requests and pickle python librarys.

So first to the code providing the JSON file on the web server running within the MSP430 launchpad. I programmed it for quick development in Energia and started with the example program for Simple Web Server created by Robert Wessels (who derived it from Hans Scharler).

First step is to chang the SSID and passwort to allow the connection.

#define WLAN_SSID       "myssid"
#define WLAN_PASS       "mypassword"

Then add the definition for the analog pins

int analogPin = A0;     // analog pin
int val = 0;           // variable to store the value read

The client gets the right file when browsed to xxx.xxx.xxx.xxx/data.json (check the IP adress) with

        if (currentLine.endsWith("GET /data.json ")) {
          statusConfig = 0;
          printData();
        }

within the void loop subprogram. This calls printData();.

void printData() {
  //Serial.println("Print Data");

  client.println("HTTP/1.1 200 OK");
  client.println("Content-type:application/json; charset=utf-8");
  client.println();
  val = analogRead(analogPin);    // read the input pin
  //Serial.println(val);             // debug value

  client.println("[");
  client.println("{");
  client.println("\"light_sensor\": {");
  client.print("\"value\": ");
  client.print(val);
  client.println("}");
  client.println("}");
  client.println("]");

  client.println();
}

which reads the analog sensor and provides the JSON-file to the client:

[
    {
        "light_sensor": {
            "value": 773}
    }
]

The hardware setup itself is more or less simple a 1K R is connected between ground and pin A0 and the photoresistor is connected between +5 V and A0. Than program the launchpad and supporut it with power (with attached booster pack).

Now to the server side. A simple python script polls the data using requests and exception handling i.e. timeouts (necessary because the server is not a google server…) (function read_json_data):

from __future__ import division, print_function
import requests, json
import time
import datetime
import numpy as np
import pickle
import socket

## Read Light Measurement Data from IP via JSON-File
# Michael Russwurm 2014
# under GNU GENERAL PUBLIC LICENSE Version 3, 29 June 2007

print("# Gathering Light Sensor Measurements #")
print("Started at ", datetime.datetime.now())

def read_json_data(url_string, time_out):
    """Reads Data from url string in JSON format.\n
    Returns False if not working properly or JSON object without errors.
    time_out in seconds defines request duration.
    Imports needed: json, requests and socket.
    """
    exception = False
    try:
        req = requests.get(url_string, timeout=time_out)
        # print( r.json()
        #print(r.encoding)
        #print(r.text)
    except requests.exceptions.RequestException as requests_error:
        print ("Error: ", requests_error)
        exception = True
    except socket.error as socket_error:
        print("Error: ", socket_error)
        exception = True
    if exception is False:
        data = json.loads(req.content)
        data = data[0] # data[0][...][...] not necessary anymore
    else:
        data = False
    return(data)

COUNT = 100 # x100
for j in range(COUNT):
    data_array = []
    for i in range(100):
        # change IP adress HERE, 30 s timeout
        data_point = read_json_data('http://xxx.xxx.xxx.xxx/data.json', 30) 
        time.sleep(5)
        if data_point is not False:
            data_array.append([datetime.datetime.now(),
                               data_point["light_sensor"]["value"]])
            #print("Light Sensor: ",data_point["light_sensor"]["value"],
                               #" No. ",(i+1))
        else:
            #print("Light Sensor: ERROR "," No. ",(i+1))
            time.sleep(30)
    print("Try to append to existing file")
    try:
        data_array = np.append(pickle.load(open("light_sensor_data.p", "rb")),
                         np.array(data_array), axis=0)
        print("Existing file found - append to existing file")
    except IOError:
        data_array = np.array(data_array)
        print("No existing file found - creating new one")
    pickle.dump(data_array, open("light_sensor_data.p", "wb"))
    print("Saved at ", datetime.datetime.now())
print("Finished")

A for loop polls the site every 5 seconds and converts integer number and appends it together with an timestep (datetime.datetime.now()) to a list ( data_array ). After 100 values the whole array is safed in a new file using pickle to safe file size. A if/else condition checks if there is already a file and would append it. Another advantage of this approach is that it is possible to restart the programm with a max. loss of 100 measurement points.

Last but not least another script reads the data and plot it:

from __future__ import print_function, division
import pickle
import matplotlib.pyplot as plt
from matplotlib import dates

## Print Light Sensor Data
# Michael Russwurm 2014
# under GNU GENERAL PUBLIC LICENSE Version 3, 29 June 2007

data_array = pickle.load(open("light_sensor_data.p", "rb"))
print("# Plot Light Sensor Data #")
#print(data)

# matplotlib date format object
hfmt = dates.DateFormatter('%d.%m.%y %H:%M')
fig, ax = plt.subplots(1, 1)
# 12 bit = 4095, 3.3 V
ax.plot(data_array[:, 0], data_array[:, 1]/4095*3.3, "--o", label="Brightness")
ax.grid()
ax.legend(loc="lower right")
ax.set_ylabel("Brightness Sensor Output [V]")
ax.set_xlabel("Time")
ax.set_title("Light Sensor Data")
ax.xaxis.set_major_locator(dates.AutoDateLocator())
ax.xaxis.set_major_formatter(hfmt)
plt.gcf().autofmt_xdate()
plt.show()

This piece of code is also responsible of converting the AD-values to voltage values (lux conversion would be possible wiht calibration).

The result looks somthing similar to this:
Light Sensor Data

This system is easy adaptable to more than one sensor or even more than one sensor node (although not very cheap).

pyrocket – Amateur Rocket Simulation Script

A small little python script for simulation of an ameteur rocket.

https://github.com/Lageos/pyrocket

It is a one dimensional simulation (acceleration, velocity and altitude), which considers drag changing temperature and density over altitude, changing mass and thrust.

Example Output of Amateur Rocket
Example Output of Amateur Rocket

It also simulates the optimum spearation time for two stage rockets. This is kind of arbitrary cause it is alway (except the drag difference is really huge) always best to use the inertia of the accelerated mass as long as possible in an unpropelled state to work against the drag.

One additional gimnick is the necessary angle of an autotracking device separated from the launchpad.

Rotary Encoder Disks with Matplotlib

Did you ever needed a quick way to make your own rotary encoder disks?

Here a quick way to make the graphics. Afterwards only a printer and scissors are necessary.

First import the packages numpy and matplotlib

import matplotlib.pylab as plt
import numpy as np

And now define the outer and inner diameter as well as the number of lines:

di = 300.e-3# inner diameter
da = 340.e-3 # outer diameter
lpr = 720. # lines per 360°

And here comes the rest:

fig, ax = plt.subplots(1,1, subplot_kw=dict(polar=True))
theta = np.linspace(0.,2*np.pi,lpr+1)
radii=np.empty(lpr+1); radii.fill((da-di)/2)
dis=np.empty(lpr+1); dis.fill(di/2)
ax.bar(theta, radii, width=np.radians(360/(2*lpr)), bottom=dis,
           color='black', edgecolor = 'none', linewidth  = 0.)
ax.plot(0,0,'.',color='black')
ax.xaxis.set_visible(False)
ax.yaxis.set_visible(False)
fig.patch.set_visible(False)
ax.axis('off')

It is a polar plot with bars, separeted from inner diameter to outer diameter. Important is to suppress any lines which disturb your signals (suppress tick and labels).

And here is an example output:

Rotary Encoder Disk
Rotary Encoder Disk

Only thing what’s left is to print and build.

Install Anaconda and IPython (notebook) in Ubuntu

Sometimes it is either hard to remember or there are many way to fulfill a certain goal. During my (re-)setup of my laptop with Ubuntu 12.04 I had to install IPython with its notebook capabilities.

The first step is to download the recent anaconda package from:
http://continuum.io/downloads
Either the 32 or 64 bit version. Next make it executable either by right click on the downloaded file and choose „Properties“ then the tab „Permissions“ or with an editor

sudo chmod +x Anaconda-1.x.x-Linux-xxx_xx.sh

.

Next start the installation by typing

./Anaconda-1.x.x-Linux-xxx_xx.sh 

. Choose the recommended options. (Be careful not to hit the enter key to often at beginning otherwise it kicks you out.)

This installs the necessary files, but we need to add the directory to the PATH. Therefore we change the the profile configuration by

gedit ~/.profile

and change the line

PATH="$HOME/bin:$PATH"

to

PATH="$HOME/bin:$PATH:~/anaconda/bin"

. Afterwards only safe the file. EDIT: It is also possible to restart or logout / login to update the PATH.

Next -but not strictly necessary- it is always favorable to update the existing files. To do this we can use the anaconda built in conda repository management system.
Type

conda update ipython

Now you’re read to start the IPython notebook everywhere (although it is recommended to start it always from the same directory, otherwise it isn’t possible to open the old files directly with the notebook manager).

 ipython notebook