Skip to content

Instantly share code, notes, and snippets.

@jmpinit
Created December 31, 2013 00:46
Show Gist options
  • Save jmpinit/8190649 to your computer and use it in GitHub Desktop.
Save jmpinit/8190649 to your computer and use it in GitHub Desktop.
MSR900 MagStripe reader/writer.
import sys, serial
from operator import eq
ser = serial.Serial('/dev/ttyUSB0', 9600)
init = [0x61, 0x65, 0x61]
delimiter = [0x3F, 0x1C, 0x1B]
ok = [0x30]
errors = [0x31, 0x32, 0x34, 0x39]
def send(data):
ser.write(chr(0x1B))
if type(data) is int:
ser.write(chr(data))
elif type(data) is str:
ser.write(data)
elif type(data) is list:
for c in data:
send(c)
def erase(tracks):
tracks &= 0x3
send('c')
send(tracks)
return ser.read(2)[1]
def cardwrite(tracks):
t1, t2, t3 = tracks
card_data = [0x1B, 0x01] + t1 + [0x1B, 0x02] + t2 + [0x1B, 0x03] + t3
data_block = [0x1B, 0x73] + card_data + [0x3F, 0x1C]
cmd = [0x1B, 0x77] + data_block
send(cmd)
print cmd
return ser.read(2)[1]
def cardread():
send('r')
msg = []
while True:
next = ord(ser.read(1))
msg += [next]
if len(msg) >= 4:
a, b, c = msg[-4:-1]
if a == delimiter[0] and b == delimiter[1] and c == delimiter[2]:
break
return msg
def get_tracks(data):
buf = []
track1 = []
track2 = []
track3 = []
for a, b in zip(data, data[1:]):
buf += [a]
if a == 0x1B:
if b == 1:
buf = []
if b == 2:
track1 = buf[1:]
buf = []
if b == 3:
track2 = buf[1:]
buf = []
track3 = buf[1:]
return (track1, track2, track3)
#send(init)
data = cardread()
t1, t2, t3 = get_tracks(data)
print "track 1"
print "".join([chr(c) for c in t1])
print "track 2"
print "".join([chr(c) for c in t2])
print "track 3"
print "".join([chr(c) for c in t3])
#print erase(0x3)
#print cardwrite((list("hello"), list("world"), [1, 2, 3]))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment