Wednesday, 15 November 2017

Slack command line stream

I thought a Slack console might be useful, a very simple client I could display on an always on screen, so I did some experimenting with the Slack Developer Kit for Python and made a super simple command line program which streams messages.

It is most definitely a starting point rather than a finished solution, but someone might find it useful.


Setup (assuming you are using a Raspberry Pi / Linux computer, although it will work on Windows as well).

1. Generate a security token for the slack group you want to stream.

2. Create an environment variable SLACK_API_TOKEN and put your security token in it.

Edit /etc/profile adding the export to the bottom:
sudo nano /etc/profile
export SLACK_API_TOKEN=[my super long token]
3. Install slackclient and colorama using pip:
sudo pip3 install colorama
sudo pip3 install slackclient
4. Download the slack_stream.py from gist:
wget https://gist.githubusercontent.com/martinohanlon/477b6ea4c3bdc679ddff92dfc3bff4a7/raw/8ec39d08a9501b25d381ac3b008e9cf7be92377a/slack_streamer.py
5. Run it:
python3 slack_streamer.py

Friday, 7 July 2017

Python Bluetooth RFCOMM Client Server

As part of the Blue Dot project I needed to create a simple Bluetooth client / server library so that the communication could be managed. This library, btcomm, is part of bluedot but its not exclusive and can be used for Bluetooth communication in Python.

It uses a 2 way RFCOMM communication - you can send messages to and from 2 devices, 1 being the server which waits for connections, 1 being the client which makes a connection.

Install the library
sudo apt-get install python3-dbus
sudo pip3 install bluedot

Pairing

The 2 devices you which want to communicate between will need to be paired, the Blue Dot documentation describes how to pair 2 raspberry pi's which might be useful.

Simple Client / Server Example
Lets create a simple example, a server which waits for connections and when it receives data it echo's it back to the client.

Create a new Python program and save it as btserver.py:

from bluedot.btcomm import BluetoothServer
from signal import pause

def data_received(data):
    print(data)
    s.send(data)

s = BluetoothServer(data_received)
pause()

Create a 2nd program and save it as btclient.py:
from bluedot.btcomm import BluetoothClient
from signal import pause

def data_received(data):
    print(data)

c = BluetoothClient("nameofyourserver", data_received)
c.send("helloworld")

pause()

Run the server and then run the client, the client should connect and "Hello World" will be sent to the server and displayed on the screen, the server will then send the same "Hello World" message back to the client, which will print it to the screen.

Adapter

There is also a useful API for accessing the Bluetooth adapter allowing you to get its current status, power it on/off, make it discoverable or find the devices its paired with.
from bluedot.btcomm import BluetoothAdapter

a = BluetoothAdapter()

print("Powered = {}".format(a.powered))
print(a.paired_devices)
a.allow_pairing()

Documentation

There is comprehensive documentation for the btcomm library, which describes the API and how to use it.


Tuesday, 4 July 2017

Mac OS - Check Java version before running script

I needed to check what version of Java was installed on a Mac before running my program, so with the help of stackoverflow and a few other resources I pulled together the following bash script which checks to see if the version of Java is greater than 1.8 before continuing.
# Work out the JAVA version we are working with:
JAVA_VER_MAJOR=""
JAVA_VER_MINOR=""
JAVA_VER_BUILD=""

# Based on: http://stackoverflow.com/a/32026447
for token in $(java -version 2>&1 | grep -i version)
do
    if [[ $token =~ \"([[:digit:]])\.([[:digit:]])\.(.*)\" ]]
    then
        JAVA_VER_MAJOR=${BASH_REMATCH[1]}
        JAVA_VER_MINOR=${BASH_REMATCH[2]}
        JAVA_VER_BUILD=${BASH_REMATCH[3]}
        break
    fi
done

#check version is greater than 1.7 (i.e. at least 1.8)
if [ "$JAVA_VER_MAJOR" -gt "1" ]; then
    echo start your program
elif [ "$JAVA_VER_MINOR" -gt "7" ]; then
    echo start your program
else
    echo ERROR - Java needs to be updated.
    echo Currently installed version is $JAVA_VER_MAJOR.$JAVA_VER_MINOR - 1.8 is required
fi

Friday, 5 May 2017

Raspberry Pi Touchscreen Portrait

I recently wanted to turn my Raspberry Pi Official Touchscreen portrait (i.e. sideways!), which turns out is a bit of pain.

Turning the display is relatively easy but making the touch work is more difficult - there was a set of instructions on the Raspberry Pi forum, but a recent update to Jessie meant they no longer worked, so I pulled this set of instructions together:

Install xinput:
sudo apt-get install xinput
Rotate the display by editing config.txt:
sudo nano /boot/config.txt
 .. add this to the buttom of the file:
display_rotate=1
Use Ctrl X, Yes to Save
Create a script to rotate the touchscreen:
nano /home/pi/touch_rotate.sh
 .. add the following command
xinput --set-prop 'FT5406 memory based driver' 'Coordinate Transformation Matrix'  0 1 0 -1 0 1 0 0 1
Make the script executable:
chmod +x touch_rotate.sh
Make the script run when the GUI starts by editing autostart:
sudo nano ~/.config/lxsession/LXDE-pi/autostart
 .. add this to the bottom to run your script
@/home/pi/touch_rotate.sh
Reboot:
sudo reboot

Monday, 24 April 2017

Blue Dot - a bluetooth remote for Raspberry Pi

Blue Dot is a really simple way to add Bluetooth remote control to your Raspberry Pi projects.


I created Blue Dot after being asked many times at Picademy “how can I get rid of all these wires?”. 

Blue dot is an android app (client) and really easy to use Python library which allows you to wirelessly control your Python projects, whether that is a light switch, remote camera, robot or anything else you can think of!


See the getting started guide for more info on 'getting started', or follow the tutorial below.

Installation & Use
These instructions assume your Raspberry Pi is running the latest version of Raspbian with Pixel.

You will need a Raspberry Pi with built-in Bluetooth (such as the Pi 3 or Pi Zero W) or a Raspberry Pi and a USB Bluetooth dongle.

Get the app
Download and install the Blue Dot app from the google play store.


If you are wondering why there is no iOS app? Its because iOS doesn't support Bluetooth serial comms; you can only really talk to 'standard devices' (cars, speakers, fitness trackers, etc).

Python library
Open a terminal (Menu > Accessories > Terminal) and type:
sudo apt-get install python3-dbus
sudo pip3 install bluedot
Or if you need to use Python 2 (please dont tho!):
sudo apt-get install python-dbus
sudo pip install bluedot

Pairing
In order to communicate over Bluetooth securely you need to pair your phone to your Raspberry Pi.

On your Android phone:
  1. Open Settings
  2. Select Bluetooth
  3. This will make your phone Discoverable
Using your Raspberry Pi
  1. Click the bluetooth icon on the taskbar
  2. Turn on Bluetooth (if its off)
  3. Click Make Discoverable
  4. Click Add Device
  5. Your phone will appear in the list, select it and click Pair
  6. Enter a PIN code
On your Android phone
  1. Enter the same PIN code when prompted
  2. Click Ok
Code
The simplest way to use the Blue Dot is as a button:
  1. Open Python 3 (Menu > Programming > Python 3)
  2. Create a new file (File > New File)
  3. The following code, will start up the Blue Dot, and wait for it to be pressed:
  4. from bluedot import BlueDot
    bd = BlueDot()
    bd.wait_for_press()
    print("You pressed the blue dot!")
  5. Save your program (File > Save) as mydot.py
  6. Run your program (Run > Run Module)
  7. Open the Blue Dot app
  8. Connect to your Raspberry Pi
  9. Press the Blue Dot
As well as waiting for something to happen you can also call functions when the button is pressed, released or the position its pressed moves.
from bluedot import BlueDot
from signal import pause

def say_hello():
    print("Hello World")

def say_goodbye():
    print("goodbye")

bd = BlueDot()
bd.when_pressed = say_hello
bd.when_released = say_goodbye

pause()
By using the position of where the button is pressed you can use the Blue Dot like a joystick:
from bluedot import BlueDot
from signal import pause

def dpad(pos):
    if pos.top:
        print("up")
    elif pos.bottom:
        print("down")
    elif pos.left:
        print("left")
    elif pos.right:
        print("right")
    elif pos.middle:
        print("fire")

bd = BlueDot()
bd.when_pressed = dpad

pause()
Add to this gpiozero's Robot functions, you can create a Bluetooth controlled robot with very little code.
from bluedot import BlueDot
from gpiozero import Robot
from signal import pause

bd = BlueDot()
robot = Robot(left=(lfpin, lbpin), right=(rfpin, rbpin))

def move(pos):
    if pos.top:
        robot.forward()
    elif pos.bottom:
        robot.backward()
    elif pos.left:
        robot.left()
    elif pos.right:
        robot.right()

def stop():
    robot.stop()

bd.when_pressed = move
bd.when_moved = move
bd.when_released = stop

pause()
Check out the Blue Dot documentation for more information and ideas - you really can do a lot with a simple circle :)

Thursday, 5 January 2017

Raspberry Pi - 4 digit 7 Segment display, gpiozero

I recently picked up some 'retro 4 digit LED displays' from pimoroni, noticing there was no support in gpiozero for 7 segment displays (either single or multi digit) I decided to add them and create a pull request.

This builds on the code I created for driving single 7 segment displays.


Hopefully the PR will get added into a gpiozero release soon, but until then add this code to your project and use the following to drive your display.
#setup the pins

#these are the pins the LED are connected too
# (in the order A, B, C, D, E, F, G, decimal point)
LED_PINS = (7, 22, 25, 17, 8, 27, 4, 24)
#these are the pins the digits are connected too
DIGIT_PINS = (23, 18, 15, 14)

#create the multi seven segment display
# use active_high=True when digit pins are cathode (ground)
multi_sev = MultiSevenSegmentDisplay(LED_PINS, DIGIT_PINS,
                                     active_high=True)

#display your message
multi_sev.display("LEDS")

#turn off the display using
multi_sev.off()
The display function works by plexing the display, turning the LEDs on one at a time, so quickly it tricks the eye into thinking the display is showing 1 message.



Thursday, 8 December 2016

Raspberry Pi - bash memory split check

I needed a bash script which would only launch a program on a Raspberry Pi if there was enough memory dedicated to the GPU.

I pulled this script together which checks to see if there is at least 128 MB dedicated to the GPU before starting the program.

#!/bin/bash

#check there is enough gpu memory to start
#get the gpu memory and output to a file called gpu_mem
vcgencmd get_mem gpu > gpu_mem
source gpu_mem
#strip last char from the output (i.e. 64M)
gpu=${gpu%?}
if (( $gpu >= 128 )); then
    ./launch_program
else
    echo "The program needs at least 128MB of memory allocated to the GPU"
    echo "Use sudo raspi-config (Advanced Options > Memory Split) to change"
fi
#remove the gpu_mem file
rm gpu_mem