Setup a Raspberry Pi TOR proxy

This is not a real HOW TO, it’s a two-step guide for setting up a Raspberry PI (with a wifi usb adapter) in order to create an easy-to-use TOR proxy on a WiFi Access Point.
Two simple steps:

  1. Create a Wifi Access Point on your Raspberry following this guide: https://learn.adafruit.com/setting-up-a-raspberry-pi-as-a-wifi-access-point/install-software https://www.raspberrypi.org/documentation/configuration/wireless/access-point.md
  2. Install and configure TOR using this git repo: https://github.com/sarbyn/tor_box/blob/master/README.md

So simple!

Install KODI on raspiNAS

My raspiNAS is based on a raspberry pi 2, with 1GB of ram and a 4core ARM processor, a more powerful board able to run a NAS and also a full HD media center. So in order to simplify my home setup and remove a raspberry I’ve decided to merge the KODI mediacenter (based on OSMC) into the raspiNAS board.

We have to create the group “input” if it doesn’t exist.

sudo addgroup --system input

Edit the file

sudo nano /etc/udev/rules.d/99-input.rules

enter the following text and save it:

SUBSYSTEM==input, GROUP=input, MODE=0660
KERNEL==tty[0-9]*, GROUP=tty, MODE=0660

Create & edit the following file:

sudo nano /etc/udev/rules.d/10-permissions.rules

enter this text and save it:

# input
KERNEL=="mouse*|mice|event*",   MODE="0660", GROUP="input"
KERNEL=="ts[0-9]*|uinput",     MODE="0660", GROUP="input"
KERNEL==js[0-9]*,             MODE=0660, GROUP=input
# tty
KERNEL==tty[0-9]*,            MODE=0666
# vchiq
SUBSYSTEM==vchiq,  GROUP=video, MODE=0660

Run the following commands for user pi (if you haven’t changed your user name):

sudo usermod -a -G audio pi
sudo usermod -a -G video pi
sudo usermod -a -G input pi
sudo usermod -a -G dialout pi
sudo usermod -a -G plugdev pi
sudo usermod -a -G tty pi

To play full HD video in Kodi, you have to set

gpu_mem=160

in /boot/config.txt (or higher) and reboot the board.

Now install kodi with:

sudo apt-get install kodi

Edit /etc/default/kodi in order to start kodi at boot:

# Set this to 1 to enable startup
ENABLED=1

# The user to run Kodi as
USER=pi

# Adjust niceness of Kodi (decrease for higher priority)
NICE=-5

Source: https://www.raspberrypi.org/forums/viewtopic.php?t=99866

RaspiNAS – DIY nas with a Raspberry

After more than one year with my NAS build over an ALIX, I bought a Raspberry pi 2 and I want to check if the “USB POWER BUG” is resolved now.

I don’t need an high speed NAS so the speed issue with the shared PCI link between USB hub and network adapter is not so important.

Advantages of a Raspberry pi 2 setup are:

  • Less power consumption: raspberry drain half the power of an Alix card
  • Flexibility: 4 USB ports instead of 2
  • Smaller: Raspberry Pi 2 is smaller than Alix board

So this is a copy&paste from my previous post, adapted for the new environment

Install Raspbian lite

Go to Raspbian download page and download the lite version

Install VIM
# apt-get install vim
Add new user
# useradd -m -s /bin/bash sarbyn
# passwd sarbyn
Add user to sudo
# visudo --- add user
Install NTFS-3G
# apt-get install ntfs-3g
Fstab and volumes
# mkdir /mnt/TimeMachine
# mkdir /mnt/MUSIC
# chown sarbyn:sarbyn /mnt/MUSIC
# chown sarbyn:sarbyn /mnt/TimeMachine

UUID=206606FF6606D606 /mnt/MUSIC ntfs-3g   rw,defaults     0       0
UUID=03c90579-88f0-4478-ae8d-adc64972a07d /mnt/TimeMachine ext4 defaults 0 0
Samba
# apt-get install samba samba-common-bin
# service samba stop
# mv /var/lib/samba /var/tmp/samba
# ln -s /var/tmp/samba /var/lib/samba
# smbpasswd -a sarbyn
[mnt]
path = /mnt
read only = Yes
guest only = Yes
guest ok = Yes

[mnt_RW]
path = /mnt
read only = No
valid user = sarbyn
browseable = yes
writable = yes
SSH
$ mkdir .ssh
$ chmod 0700 .ssh/
$ cd .ssh
$ ls
$ vim authorized_keys
$ chmod 600 authorized_keys

Disable root login and plaintext login in /etc/ssh/sshd_config file

Transmission
# apt-get install transmission-daemon
# service transmission-daemon start
FIX cracklib config

I don’t know if it is required with new Jessie debian version…but I’ve repeated it

# apt-get install cracklib-runtime
# create-cracklib-dict /usr/share/dict/*

Before
root@voyage:/var/cache/cracklib# ls -la
-rw-r--r-- 1 root root 1024 Oct 4 13:28 cracklib_dict.hwm
-rw-r--r-- 1 root root 16 Oct 4 13:28 cracklib_dict.pwd
-rw-r--r-- 1 root root 16 Oct 4 13:28 cracklib_dict.pwi
-rw-r--r-- 1 root root 65 Oct 4 13:17 src-dicts

AFTER
root@voyage:/var/cache/cracklib# ls -la
-rw-r--r-- 1 root root 1024 Oct 7 22:46 cracklib_dict.hwm
-rw-r--r-- 1 root root 412696 Oct 7 22:46 cracklib_dict.pwd
-rw-r--r-- 1 root root 22968 Oct 7 22:46 cracklib_dict.pwi
-rw-r--r-- 1 root root 65 Oct 4 13:17 src-dicts
# cd /usr/lib/
# root@voyage:/usr/lib# ln -s  /var/cache/cracklib/cracklib_dict.hwm
# root@voyage:/usr/lib# ln -s  /var/cache/cracklib/cracklib_dict.pwd
# root@voyage:/usr/lib# ln -s  /var/cache/cracklib/cracklib_dict.pwi
Netatalk

*DON’T USE NETATALK FROM DEBIAN REPOS*
The older version of netatalk are VERY…VERY unstable. Download the sources from Netatalk site and follow —> this tutorial <—

# apt-get install build-essential libevent-dev libssl-dev libgcrypt11-dev libkrb5-dev libpam0g-dev libwrap0-dev libdb-dev libtdb-dev libmysqlclient-dev avahi-daemon libavahi-client-dev libacl1-dev libldap2-dev libcrack2-dev systemtap-sdt-dev libdbus-1-dev libdbus-glib-1-dev libglib2.0-dev tracker libtracker-sparql-1.0-dev libtracker-miner-1.0-dev 
# apt-get install avahi-daemon

# insserv avahi-daemon
# insserv netatalk
# /etc/init.d/avahi-daemon start
# /etc/init.d/netatalk start

Edit “/usr/local/etc/afp.conf”.

[Global]
; Global server settings
uam list = uams_dhx.so,uams_dhx2.so
set password = yes

[MusicAFP]
    path = /mnt/MUSIC

[TimeMachineAFP]
    path = /mnt/TimeMachine
    time machine = yes

Add user to Netatalk (using the SHORT password)

# afppasswd -an sarbyn
FIX BOOT

The NTFS volume does not mount at boot, so add some lines on /etc/rc.local

# vim /etc/rc.local

service transmission-daemon stop
mount -a
swapon /mnt/MUSIC/swapfile
service transmission-daemon start

# chmod +x /etc/rc.local
NOIP client
# wget http://www.no-ip.com/client/linux/noip-duc-linux.tar.gz
# tar xzf noip-duc-linux.tar.gz
# cd no-ip-2.1.9
# make
# make install
# sudo noip2 -U 60
Install RPI monitor

Rpi monitor is a small web application that shows usage statistics of a raspberry pi board. Install rpi monitor following this link
Configure /etc/rpimonitor/storage.conf in order to setup storage monitoring and edit the /etc/rpimonitor/data.conf in order to include the storage.conf entry.

Optional – MiniDLNA support

If you need miniDLNA support follow this link

Final step – do a MicroSD backup

Now is all setted up but it’s better to do a MicroSD backup using dd

# dd if=DISK of=raspinas-backup.img bs=1m

Send email when webcam detects movement

In my previous post I’ve explained how to configure a DIY IP camera using motion.

Now let configure an email alert system that send email upon motion detection and the video recorded. It’s very simple.

First of all, install some software:

sudo apt-get update
sudo apt-get install sendemail libio-socket-ssl-perl libnet-ssleay-perl

If you want to use GMAIL as smtp you need to fix SSL config. Open /usr/share/perl5/IO/Socket/SSL.pm and then change

m{^(!?)(?:(SSL(?:v2|v3|v23|v2/3))|(TLSv1[12]?))$}i

to:

m{^(!?)(?:(SSL(?:v2|v3|v23|v2/3))|(TLSv1[12]?))}i

Now change motion.conf file.

# email sent when an event starts
on_event_start sendEmail -f YOURFROMEMAIL@gmail.com -t YOURTOEMAIL@gmail.com -u "[Motion] Event detected" -m "Movement has been detected on: %d %m %Y. The time of the movement was: %H:%M (Hour:Minute). Video will follow" -s smtp.gmail.com -xu YOURGMAIL@gmail.com -xp YOURGMAILPASSWORD -o tls=yes

# send video as attachment
on_movie_end sendEmail -f YOURFROMEMAIL@gmail.com -t YOURTOEMAIL@gmail.com -u "[Motion] video" -m "Video" -s smtp.gmail.com -xu YOURGMAIL@gmail.com -xp YOURGMAILPASSWORD -o tls=yes -a %f

DIY IP camera with Raspberry Pi

I found an old webcam somewhere in a drawer and I decided to plug the webcam to my Raspberry IP in order to build a video-surveillance system with auto motion detection.

The Hardware is simple:

  • Raspberry PI (with sdcard and power supply)
  • Microsoft LifeCam VX-500
Install motion

Motion is an open source software that can collect images and video from a webcam when a movement is detected. It has also an embedded web server that can share the livestream.

sudo apt-get update
sudo apt-get install motion
Setup motion

You also need to enable the motion daemon so that motion will always run:

sudo nano /etc/default/motion

and change the line to:

start_motion_daemon=yes

Set also the right image resolution (in my example, 640×480) and if you want change also these settings:

pre_capture 2
post_capture 2
ffmpeg_video_codec mpeg4
  • pre_capture: how many frames record before the movement
  • post_capture: how many frames record after movement stops
  • ffmpeg_video_codec: video codec (default flv)
Web server (optional)

If you want to share your image over the web you can also change the config for “Live Webcam Server” and “HTTP Based Control”. The live stream page is not protected by username-password, so BE CAREFUL!!!
Another thing: the live stream page does not work on Chrome. In order to see the stream you have to embed the “http://host:port/” address in an HTML page (using IMG tag)

Set target dir

Raspberry PI has a very small storage on SD card. It’s better to use a network folder as destination for images and video. Configure the mount point in /etc/fstab

//YOURSERVERNAME/YOURSHAREDFOLDERNAME /media/camshare cifs username=YOURSHAREDFOLDERUSERNAME,password=YOURSHAREDFOLDERPASSWORD,iocharset=utf8,file_mode=0777,dir_mode=0777 0 0

and change motion config file in order to use the new mounted network folder

target_dir /media/camshare
Schedule Webcam capture time

If you want to schedule motion start and stop, you can do it easily with crontab (as root)

crontab –e

For example, if you want to start motion at 11AM (from monday to friday) until 5PM:

00 11 * * 1-5 /usr/bin/motion
00 17 * * 1-5 killall motion

Don’t use “service motion start|stop” or “/etc/init.d/motion start|stop” as cron command because….doesn’t work. I don’t know why, maybe some weird environment variables configuration

Thermistor sample code for Arduino – Raspberry

This is a C++ class for a simple NTC thermistor. I used the thermistor included in the cooking-hacks.com starter kit (datasheet) and the cooking-hacks.com Raspebby to Arduino shield, but this sample is easily adaptable for any NTC thermistor or also for Arduino platform. It can be used with another NTC thermistor: simply change the BasicThermistor.h values:

  • BETA (o B-Value) : the beta value of thermistor
  • THERMISTOR: zero power resistance at 25° C
BasicThermistor schema
BasicThermistor schema

Some notes:

  • This class is designed for a read every 10 seconds.
  • Check the real value of 10k resistance with a multimeter! The 10% tollerance changes the value of about ± 1° C!. In my example I use 9840 Ω instead of 10000 Ω
  • I use a arithmetic mean over 12 readings (2 minutes) in order to normalize the temperature value and discard read errors
  • I use a simple “is_valid_value” function that discard a macroscopic read error. A “digital” read error of ± 20 is converted to an error of ± 14° C ! So if the previous valueis too big or too small, discard the current value

Header file – BasicThermistor.h

/*
 * BasicThermistor.h
 *
 * Created on: 07/ago/2013
 * Author: sarbyn
 * Website: http://www.sarbyn.com
 */
#ifndef BASICTHERMISTOR_H_
#define BASICTHERMISTOR_H_

#include &quot;arduPi.h&quot;
#include

/**
 * Based on cooking-hacks NTC thermistor - datasheet available at
 * http://www.cooking-hacks.com/skin/frontend/default/cooking/pdf/159-282-86001.pdf
 */

// The real 10k resistor value
#define TENKRESISTOR 9840.0f
// Thermistor beta value (from datasheet)
#define BETA 3950.0f
// The thermistor value at room temp (25 C)
// the original value was 2800 ohm
#define THERMISTOR 2700.0f
// The room temperature (25 C) in kelvin
#define ROOMTEMPK 298.15f

// Number of readings over which calculate
// the temperature
#define READINGS 12
// Delay (in ms) between Wire operations
#define DELAY_BETWEEN_OPERATION 20

// The digital value readed from ADC
// must be lower than DIGITAL_TOLLERANCE
// Otherwise it is treaded as a read error
#define DIGITAL_TOLLERANCE 20
// If the digital value readed from ADC is wrong for
// more than DIGITAL_TOLLERANCE_COUNTER, it is a correct value
// and so use it. This is used in case of sudden
// temperature change. If the temperature changes suddenly,
// the value is discarded for DIGITAL_TOLLERANCE_COUNTER reads. After that
// the value is accepted
#define DIGITAL_TOLLERANCE_COUNTER 6

#define ADC_I2C_ADDRESS 8

class BasicThermistor {
public:
   BasicThermistor(byte i2c_address, boolean debug_flag);
   float read_temperature();
private:
   byte address;
   boolean debug;
   int digital_value;
   float read_buffer[READINGS];
   unsigned int cached_digital_value;
   float temperature;
   int invalid_read_counter;
   int buffer_pointer;

   int read_digital_value();
   int is_valid_value(int value);
   float calc_temperature(int value);
};

#endif /* BASICTHERMISTOR_H_ */

Class file – BasicThermistor.cpp

/*
 * BasicThermistor.cpp
 *
 * Created on: 07/ago/2013
 * Author: sarbyn
 * Website: http://www.sarbyn.com
 *
 */

/**
 * Based on cooking-hacks NTC thermistor - datasheet available at
 * http://www.cooking-hacks.com/skin/frontend/default/cooking/pdf/159-282-86001.pdf
 */

#include &quot;BasicThermistor.h&quot;

// Costructor
BasicThermistor::BasicThermistor(byte i2c_address, boolean debug_flag) {
  address = i2c_address;
  debug = debug_flag;
  temperature = 0.0;
  cached_digital_value = 0;
  digital_value = 0;
  invalid_read_counter = 0;
  buffer_pointer = 0;

  for (int i = 0; i &lt; READINGS; i++) {
    read_buffer[i] = -1.0f;
  }
}
// Read the digital value from ADC using Wire class
int BasicThermistor::read_digital_value() {
  unsigned char val_0 = 0;
  unsigned char val_1 = 0;
  unsigned int digital_value;
  Wire.beginTransmission(ADC_I2C_ADDRESS);
  Wire.write(address);
  // sleep in order to reduce read error
  delay(DELAY_BETWEEN_OPERATION);
  Wire.requestFrom(ADC_I2C_ADDRESS, 2);
  // sleep in order to reduce read error
  delay(DELAY_BETWEEN_OPERATION);
  val_0 = Wire.read();
  // sleep in order to reduce read error
  delay(DELAY_BETWEEN_OPERATION);
  val_1 = Wire.read();
  // sleep in order to reduce read error
  delay(DELAY_BETWEEN_OPERATION);
  digital_value = int(val_0)*16 + int(val_1&gt;&gt;4);

  if (debug) {
    printf(&quot;[BT] val [%2x,%2x]\n&quot;, val_0, val_1);
    printf(&quot;[BT] Read digital value %d\n&quot;, digital_value);
  }
  return digital_value;
}

// Check if the readed value is valid
int BasicThermistor::is_valid_value(int value) {
  if (cached_digital_value == 0) {
    cached_digital_value = value;
    return 1;
  }

  // check against DIGITAL_TOLLERANCE
  if (abs(cached_digital_value - value) &lt; DIGITAL_TOLLERANCE) {
    if (debug) printf(&quot;[BT] Valid digital value %d\n&quot;, value);
    cached_digital_value = value;
    invalid_read_counter = 0;
    return 1;
  }
  if (invalid_read_counter &gt; DIGITAL_TOLLERANCE_COUNTER) {
    // too many invalid readings ---&gt; this is a valid read
   if (debug) printf(&quot;[BT] Too many invalid digital value %d..so use it\n&quot;, value);
   cached_digital_value = value;
   invalid_read_counter = 0;
   return 1;
 }

  // throw away invalid reading
  invalid_read_counter++;
  if (debug) printf(&quot;[BT] Invalid digital value %d\n&quot;, value);
  return 0;
}

// Convert the ADC value to Celsius Temperature
float BasicThermistor::calc_temperature(int value) {
  // convert value
  float analog_value = value * 1023.0 / 4095.0;

  analog_value = (1023 / analog_value) - 1;
  analog_value = TENKRESISTOR / analog_value;
  analog_value = analog_value / THERMISTOR;

  if (debug) printf(&quot;[BT] Analog value %f\n&quot;, analog_value);

  float kelvin = log(analog_value);
  kelvin /= BETA;
  kelvin += 1.0 / ROOMTEMPK;
  kelvin = 1.0 / kelvin;

  return kelvin - 273.15;
}

// Main read function: read the current temperature and return it.
// This is designed for a read every 10 seconds: it collects 12 readings
// (READINGS macro value, 2 minutes) and calculate mean over all the values.
// In this way the temperature value does not change suddenly and
// become more stable
float BasicThermistor::read_temperature() {
  digital_value = read_digital_value();
  float single_temperature;
  if (is_valid_value(digital_value)) {
    single_temperature = calc_temperature(digital_value);
    if (debug) printf(&quot;[BT] Single current temperature is %f\n&quot;, single_temperature);
  } else {
    single_temperature = calc_temperature(cached_digital_value);
    if (debug) printf(&quot;[BT] Invalid temp, using cached value %f\n&quot;, single_temperature);
  }

  if (debug)
    printf(&quot;[BT] Storing the temp at pointer %d\n&quot;, buffer_pointer);

  read_buffer[buffer_pointer] = single_temperature;
  buffer_pointer++;

  if (read_buffer[buffer_pointer] == -1.0f) {
    // this is the first reading....init the buffer
    for (int i = buffer_pointer; i &lt; READINGS; i++) {
      read_buffer[i] = single_temperature;
    }
  }

  // reset the pointer
  if (buffer_pointer == READINGS) buffer_pointer = 0;

  temperature = 0;

  if (debug) {
    printf(&quot;[BT] Temp. buffer[&quot;);
    for (int i = 0; i &lt; READINGS; i++) {
      printf(&quot;%0.1f,&quot;, read_buffer[i]);
    }
    printf(&quot;]\n&quot;);
  }

  for (int i = 0; i &lt; READINGS; i++) {
    temperature += read_buffer[i];
  }

  temperature /= READINGS;

  return temperature;
}

LiquidCrystal_i2c for ArduPi

I bought on ebay a simple LCD screen with an i2c controller. My purpose is to add a simple output screen to my project TermoPi (a smart thermostat for my home). I found a ready-to-use CPP library called LiquidCrystal_I2C that helps the developer to connect the LCD screen to an Arduino board. I want to use my raspberry Pi with the coocking-hacks.com “Raspberry to arduino shields” , a connection board that export the arduino input-output pins, using the arduino conventions. A developer can use the Arduino coding style and libraries with his RaspberryPi, using ArduPi CPP library and coocking-hacks shield. But the original LiquidCrystal_I2C library is not compatible with ArduPi compatibility library: this library is similiar to arduino SDK…but it’s not arduino SDK:

  • LiquidCrystal_I2C refers to Arduino “print.cpp” functions, not available on ArduPI
  • ArduPi Wire CPP class implements a different Wire.endTrasmission() function, that close and release the I2C comunication pins (it seems a bug)

After some little changes, LiquidCrystal_I2C is ready to use on RaspberryPi with ArduPI library. You can download the library sources from my Bitbuchet GitHub repository:

https://github.com/sarbyn/liquidcrystal_i2c-for-ardupi