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

30 marzo 2015

How to setup Wi-Fi dongle on Raspberry Pi

Hi,
in order to enable the wi-fi dongle it’s necessary follow these steps:

  1. Edit the file “interfaces”:

    sudo nano /etc/network/interfaces

    add the follow strings

    allow-hotplug wlan0
    iface wlan0 inet dhcpwpa-conf /etc/wpa_supplicant/wpa_supplicant.confiface default inet dhcp
    below the screeshot:

  2. Edit the file “wpa_supplicant.conf” with the command:

    sudo nano /etc/wpa_supplicant/wpa_supplicant.conf
    Add the follow strings

    network={
    ssid="YOURSSID"

    psk="YOURPASSWORD"

    # Protocol type can be: RSN (for WP2) and WPA (for WPA1)

    proto=WPA

    # Key management type can be: WPA-PSK or WPA-EAP (Pre-Shared or Enterprise)

    key_mgmt=WPA-PSK

    # Pairwise can be CCMP or TKIP (for WPA2 or WPA1)

    pairwise=TKIP

    #Authorization option should be OPEN for both WPA1/WPA2 (in less commonly used are SHARED and LEAP)

    auth_alg=OPEN

    }

    below the screeshot:
  3. When editing files is done, is the time to run the command: sudo reboot .Immediately after run the command,  unplug the Ethernet cable and plug in the Wi-Fi dongle.

Bye
Francesco

How to: Change root password in raspberry pi (in a general linux)

Hi,
it’s very simple changing the root password in every Linux with the command “passwd root”.
For do this it’s necessary having the rights and be a sudoers member.
In the screenshot below I used the pi user:


Bye
Francesco

7 marzo 2015

How-to: Clone Raspberry Pi SD Card


  1. Open the application Win32DiskImager (probably you have used it during the first installation)

  2. In the "Image File" textbox, enter the path of the image file. For example, I put c:\temp\clone_raspberry_20131115.img
  3. In the "Device" combobox, select the letter of your SD card reader.
  4. Click the "Read" button to create the image file from your card.
Enjoy it!

Who users are connected or login to Oracle applications?

It give the number of session users on the system in the past 1 hour:

select "is".user_id, user_name, description, email_address,  to_char(min(first_connect) ,  'DD-MON-YYYY HH24:MI:SS') min_first_connect, to_char(max(last_connect),'DD-MON-YYYY HH24:MI:SS') max_last_connect,count(*) "# sessions"
from apps.icx_sessions "is"
inner join apps.fnd_user fu on fu.user_id = "is".user_id
where  last_connect > sysdate - 1/24 and "is".user_id != '-1'
group by "is".user_id, user_name, description, email_address;

This return the user login into system with at least a session and a process:

select d.user_id, d.user_name, d.description, d.email_address, a.terminal_id, b.machine, to_char(a.start_time,  'DD-MON-YYYY HH24:MI:SS') start_time
from apps.fnd_logins a,
v$session b, v$process c, apps.fnd_user d
where b.paddr = c.addr
and a.pid=c.pid
and a.spid = b.process
and d.user_id = a.user_id
and (d.user_name = 'USER_NAME' OR 1=1);

Enjoy it!

6 marzo 2015

How to create a tar file encrypted with gpg in linux

First step is to create a script for the compression + encryption. You could to call it for instance: “encrypt”.

#!/bin/bash
  tput sc
  while [ -s $pass ] || [ $pass '!=' $pass2 ]; do
   read -s -p "Enter Passphrase: " pass;
   tput rc;
  read -s -p "Re-Enter Passphrase: " pass2;
   tput el1;
   tput rc;
  done;

  for file in $@; do
   tar -cf - $file | gpg -c --passphrase $pass > $file.gpg;
   srm $file;
  done

Next, if you want decrypt a file will be necessary to run another script defined as:

#!/bin/bash
  tput sc;
  while [ -s $pass ]; do
   read -s -p "Enter Passphrase: " pass;
   tput el1;
   tput rc;
  done;

  for file in $@; do
    tar -xf <(cat $file | gpg -d --passphrase $pass);
    if [ $? -eq 0 ]; then
      srm $file;
    else
      echo Failed to Decrypt;
      echo [password might be wrong];
    fi;
  done;

Finally, after the script definitions, you could run when you wish encrypt or decrypt a file:

encrypt filename
decrypt filename

Enjoy it!