ISP Watcher

 Linux, Python, Raspberry Pi  Comments Off on ISP Watcher
Dec 062015
 

After waiting for several years, we finally got fiber internet connection two months ago.
Sadly in these two months we have had three occasions when we had no connection to internet at all.
Last time, a couple of days ago, it was out for more than 24 hours!
This is way worse than I expected, and much worse than the old ADSL connection we had before.
On the good side is, that when we actually have connection, it works really good.

But to have better statistics on the connection reliability I made a small python program.

#!/usr/bin/python2 -tt
# Joakim Wesslen

'''
Check internet connection and log result to file
'''

"""
The MIT License (MIT)

Copyright (c) 2015 Joakim Wesslen

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

"""

import sys
import time
import urllib2
import socket


logfile = "ispwatcher.txt"
loop_delay_minutes = 30
seconds_per_minute = 60

urls = [
'www.dn.se',
'www.sds.se',
'www.svd.se',
'www.cnn.com',
'www.bbc.co.uk',
'www.dmi.dk',
'www.nrk.no'
]


def getdatetime():
	'''Get date time string'''
	return time.strftime("%Y-%m-%d_%H:%M:%S")


def check_url(url):
	'''check url connection'''
	try:
		response=urllib2.urlopen('http://' + url, timeout=10)
		return True
	except urllib2.URLError as err: 
		pass

	dt = getdatetime()
	s = "Error: {}: {}".format(dt, url)
	print s
	write_result(dt, s)
	return False


def check_urls(urls):
	'''check list of urls'''
	results = []
	for url in urls:
		res = check_url(url)
		results.append(res)
	return results


def calc_result(results):
	'''
	calculate the result of check_urls.
	if one url is accessible, we are connected.
	'''
	if True	in results:
		result = "connected"
	else:
		result = "disconnected"
	return result		


def write_result(dt, result):
	'''write result string to file with datetime'''
	s = "{}: {}".format(dt, result)
	print s
	with open(logfile, "a") as txt_file:
		txt_file.write(s + "\n")


def wait_minutes(minutes):
	'''wait some minutes'''
	time.sleep(minutes * seconds_per_minute)


def get_lock(process_name):
	'''make sure only one instance exists'''
	global lock_socket
	lock_socket = socket.socket(socket.AF_UNIX, socket.SOCK_DGRAM)
	try:
		lock_socket.bind('\0' + process_name)
	except socket.error:
		print "Already running"
		sys.exit()


def close_lock():
	'''release the lock'''
	global lock_socket
	try:
		lock_socket.close()
	except socket.error:
		print "close_lock exception!"


def main(args):
	try:
		while True:
			dt = getdatetime()
			results = check_urls(urls)
			result = calc_result(results)
			write_result(dt, result)
			wait_minutes(loop_delay_minutes)
	except KeyboardInterrupt:
		print 'Stopped by user'
		close_lock()
		sys.exit(0)


if __name__ == '__main__':
	get_lock('ispwatcher')
	sys.exit(main(sys.argv[1:]))

The program checks internet connection two times per hour, and writes the result to a file.
I put it on a Raspberry Pi, connected directly to the router, and also set up a cron job to make sure it runs.
The cron job starts the script every half-hour, and is done as:

00 * * * * /home/pi/ispwatcher.sh
30 * * * * /home/pi/ispwatcher.sh

The shell script is simply starting the python program.

As you can see the python program makes sure only one instance is running, so this setup should be okay I hope.
Let's see what the result will show.

Micro Python

 DIY, Electronics, Python  Comments Off on Micro Python
May 182014
 

Received my Micro Python board on the 12th of May which is a Kickstarter project I supported back in November last year, https://www.kickstarter.com/projects/214379695/micro-python-python-for-microcontrollers.

I just backed the project as I thought it was an interesting idea to use python in an embedded product.
So far I haven't had time to play around with it much, but I am really looking forward to it.

Here is the official web site for the project, http://micropython.org/.

board and box

One thing I noticed though upon starting the device up is that, at least on my Ubuntu machine, I did not get the pop-up window of the pyboard drive as described in the tutorial, if I have the SD-card inserted. If the SD-card is inserted, the only thing I get is the USB drive of that card. Without the SD-card inserted, I get the pyboard drive with the files mentioned. So I will go on without the card for now.

The tutorial, http://micropython.org/doc/tut-contents, is really nice and easy to follow.

To get a micro python prompt to write instructions directly to the board do,

screen /dev/ttyACM0

This is what you get from the help() function on micro python interpreter.

>>> help()         
Welcome to Micro Python!

For online help please visit http://micropython.org/help/.

Quick overview of commands for the board:
  pyb.info()    -- print some general information
  pyb.gc()      -- run the garbage collector
  pyb.delay(n)  -- wait for n milliseconds
  pyb.Switch()  -- create a switch object
                   Switch methods: (), callback(f)
  pyb.LED(n)    -- create an LED object for LED n (n=1,2,3,4)
                   LED methods: on(), off(), toggle(), intensity()
  pyb.Pin(pin)  -- get a pin, eg pyb.Pin('X1')
  pyb.Pin(pin, m, [p]) -- get a pin and configure it for IO mode m, pull mode p
                   Pin methods: init(..), value([v]), high(), low()
  pyb.ExtInt(pin, m, p, callback) -- create an external interrupt object
  pyb.ADC(pin)  -- make an analog object from a pin
                   ADC methods: read(), read_timed(buf, freq)
  pyb.DAC(port) -- make a DAC object
                   DAC methods: triangle(freq), write(n), write_timed(buf, freq)
  pyb.RTC()     -- make an RTC object; methods: datetime([val])
  pyb.rng()     -- get a 30-bit hardware random number
  pyb.Servo(n)  -- create Servo object for servo n (n=1,2,3,4)
                   Servo methods: calibration(..), angle([x, [t]]), speed([x, [t]])
  pyb.Accel()   -- create an Accelerometer object
                   Accelerometer methods: x(), y(), z(), tilt(), filtered_xyz()

Pins are numbered X1-X12, X17-X22, Y1-Y12, or by their MCU name
Pin IO modes are: pyb.Pin.IN, pyb.Pin.OUT_PP, pyb.Pin.OUT_OD
Pin pull modes are: pyb.Pin.PULL_NONE, pyb.Pin.PULL_UP, pyb.Pin.PULL_DOWN
Additional serial bus objects: pyb.I2C(n), pyb.SPI(n), pyb.UART(n)

Control commands:
  CTRL-A        -- on a blank line, enter raw REPL mode
  CTRL-B        -- on a blank line, enter normal REPL mode
  CTRL-C        -- interrupt a running program
  CTRL-D        -- on a blank line, do a soft reset of the board

For further help on a specific object, type help(obj)

To close the screen session do 'Ctrl + a' and 'Ctrl + d' in sequence.

As I said before, really looking forward to digging deeper into what I can do with this board.

Android touch events script

 Android, Python  Comments Off on Android touch events script
Apr 242012
 

When I have been working with touch drivers on Android devices, I usually end up using the getevent tool in adb.
But the output takes some time to understand. In order to make it easier for me and my colleagues, I made a small python script called touchevents.py.
It is a brute force implementation, but it gets the job done. I uploaded it to github here.

This is how it is used.

adb shell getevent | python touchevents.py event9
adb shell getevent -t | python touchevents.py event9