12 marzo 2016

Read magnetic card with raspberry and save to Google spreadsheet



Python code with some comments and link:

#!/usr/bin/python

import sys
import usb.core
import usb.util

import json
import gspread
from oauth2client.client import SignedJwtAssertionCredentials

#It’ necessary discover what are VENDOR_ID and PRODUCT_ID of your card reader device with the command lsusb.
#Device are mainly identified using a pair of hexadecimal numbers, like 0acd:0520 .

VENDOR_ID=0x0acd
PRODUCT_ID=0x0520
DATA_SIZE=337

# keycode mapping
key_pages = [
'', '', '', '',
'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm',
'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z',
'1', '2', '3', '4', '5', '6', '7', '8', '9', '0', '\n', '^]', '^H',
'^I', ' ', '-', '=', '[', ']', '\\', '>', ';', "'", '`', ',', '.',
'/', 'CapsLock', 'F1', 'F2', 'F3', 'F4', 'F5', 'F6', 'F7', 'F8', 'F9', 'F10', 'F11', 'F12',
'PS', 'SL', 'Pause', 'Ins', 'Home', 'PU', '^D', 'End', 'PD', '->', '<-', '-v', '-^', 'NL',
'KP/', 'KP*', 'KP-', 'KP+', 'KPE', 'KP1', 'KP2', 'KP3', 'KP4', 'KP5', 'KP6', 'KP7', 'KP8',
'KP9', 'KP0', '\\', 'App', 'Pow', 'KP=', 'F13', 'F14' ]

key_pages_shift = [
'', '', '', '',
'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M',
'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z',
'!', '@', '#', '$', '%', '^', '&', '*', '(', ')', '\n', '^]', '^H',
'^I', ' ', '_', '+', '{', '}', '|', '<', ':', '"', '~', '<', '>',
'?', 'CapsLock', 'F1', 'F2', 'F3', 'F4', 'F5', 'F6', 'F7', 'F8', 'F9', 'F10', 'F11', 'F12',
'PS', 'SL', 'Pause', 'Ins', 'Home', 'PU', '^D', 'End', 'PD', '->', '<-', '-v', '-^', 'NL',
'KP/', 'KP*', 'KP-', 'KP+', 'KPE', 'KP1', 'KP2', 'KP3', 'KP4', 'KP5', 'KP6', 'KP7', 'KP8',
'KP9', 'KP0', '|', 'App', 'Pow', 'KP=', 'F13', 'F14' ]

def map_character(c):
    return key_pages[c]

def chunks(l, n):
    """ Yield successive n-sized chunks from l.
    for i in xrange(0, len(l), n):
        yield l[i:i+n]

#below the class to write the spreadsheet
def addrow(info):
     json_key = json.load(open('filedownloadedingoogle.json')) # http://gspread.readthedocs.org/en/latest/oauth2.html
     scope = ['https://spreadsheets.google.com/feeds']
     credentials = SignedJwtAssertionCredentials(json_key['client_email'], json_key['private_key'].encode(), scope)
     gc = gspread.authorize(credentials)
     # Open a worksheet from spreadsheet with one shot
     wks = gc.open("worksheetname").sheet1
     #wks.update_acell('B2', "it's down there somewhere, let me take another look.")
     # Fetch cells in the column 1
     values_list = wks.col_values(1)
     count = 0
     flag = 1
     while flag == 1 :  # This constructs an infinite loop
        if (values_list[count]=='') : # loop on cell list until find out empty one
                flag = 0
        count = count + 1
     wks.update_cell(count, 1, count) # in the line count and column 1 I put the index
     wks.update_cell(count, 2, info)  # in the line count and column 2 I put the info
          
class MagSwipe:
    def __init__(self):
        # find the MagSwipe reader
        device = usb.core.find(idVendor=VENDOR_ID, idProduct=PRODUCT_ID)

        if device is None:
            sys.exit("Could not find MagTek USB HID Swipe Reader.")

        # make sure the hiddev kernel driver is not active
        if device.is_kernel_driver_active(0):
            try:
                device.detach_kernel_driver(0)
            except usb.core.USBError as e:
                sys.exit("Could not detatch kernel driver: %s" % str(e))

        # set configuration
        try:
            device.set_configuration()
            device.reset()
        except usb.core.USBError as e:
            sys.exit("Could not set configuration: %s" % str(e))

        self._endpoint = device[0][(0,0)][0]

    def wait_for_swipe(self):
        # wait for swipe
        data = []
        swiped = False
        print "Please swipe your card..."

        while 1:
            try:
                data += self._endpoint.read(self._endpoint.wMaxPacketSize)
                if not swiped:
                    print "Reading..."
                swiped = True

            except usb.core.USBError as e:
                if e.args[0] == 110 and swiped:
                    if len(data) < DATA_SIZE:
                        print "Bad swipe, try again. (%d bytes)" % len(data)
                        print "Data: %s" % ''.join(map(chr, data))
                        data = []
                        swiped = False
                        continue
                    else:
                        break   # we got it!

        # convert text
        map_keys = lambda c: key_pages_shift[c[1]] if c[0] is 2 else key_pages[c[1]]
        data = "".join(map(map_keys, [(d[0], d[2]) for d in chunks(data, 8)]))
          
     return data
          
if __name__ == "__main__":
    info = MagSwipe().wait_for_swipe()
    addrow(info)



30 maggio 2015

aurora: ERROR: Received bad return code (-1 0)

Hi,
I will explain my experience.
This morning my raspberry, where I installed 123Solar, it didn't communicate with my Power One inverter .
So I tried with putty to run the command:
aurora -a 2 -c -T -Y4 -d0 -e /dev/ttyUSB0
and I have received the error:
aurora: ERROR: Received bad return code (-1 0) 

After that I tested the communication with the command:
 aurora -a 2 -b -e /dev/ttyUSB0
and it returned:
aurora -a 2 -b -e /dev/ttyUSB0

szttyDevice: /dev/ttyUSB0
yDelay:     1
yTimeout    0 mS
yMaxRunTime ~
devLCKfile:
devLCKfileNew:
Got Params

RunTime     20150530-10:50:52 v1.8.8
Endian    : Little
tm_gmtoff : no
PID       : 23089

Attempting to get lock on Serial Port /dev/ttyUSB0...
Checking for lock

Checking process 23089 for lock
rPID: 23089 SubStrPos: aurora command: aurora = me
Appears we got the lock.

Opening Serial Port /dev/ttyUSB0...  Serial Port /dev/ttyUSB0 successfully opene                                                                                        d.
Configuring serial device... Flushing unread data first...  Success!
Flushing serial device buffer... Success!

Comm Check: Let's see if the Aurora is listening...
Elapsed time since last comm 0 us
Attempt 1
Clearing read buffer Success!
szSerBufferSave OK! 02 3a 00 00 00 00 00 00 00 00
command: 02 3a 00 00 00 00 00 00 01 b7
Flushing serial device buffer... Success!
Sending command... sent 10 characters
Draining serial device buffer... Success!
Cleared data buffer: 00 00 00 00 00 00 00 00 00 00
Read char #1 RC=0 (00) waited/max    99272/1000000  uS
answer:  Got -1 characters
Comm Check: Failure, aborting...

Restoring Serial Port settings /dev/ttyUSB0... Success!
Flushing serial device buffer... Success!
Closing Serial Port /dev/ttyUSB0... Success!

devLCKfile:
devLCKfileNew:
Clearing Serial Port Lock (23089)... done.

20150530-10:50:53: aurora: ERROR: Received bad return code (-1 0)

Complete 20150530-10:50:53

So I googled to looking for someone met the same error and I find out a post in a forum where someone have suggested to change the parameter Y from -Y4 to -Y10. 

The parameter Y means:
-Y , --retries=      Retry failed communications with inverter up to   times (1-100)

After the changing it looked works but after a while it stopped.

At the end I discovered that a wire was disconnected in the converter RS-485 to USB! I fixed it and now it works!

Bye
Francesco





18 aprile 2015

How to find out php.ini path?

You can create a simple file info.php where you put:



Then, if you open that file with a browser you can see the path:

 


Otherwise, you can get a full phpinfo() using the command:
php -i

And, in there, there is the php.ini file used:

$ php -i | grep 'Configuration File'

Below the screenshot:


NOTE: As you can see the paths are diffent because it's dipend on the context.

Bye
Francesco