Created
May 16, 2020 07:47
-
-
Save gandy92/1f9df107b049e12173657e28e20dc56e to your computer and use it in GitHub Desktop.
Python 3 script to demonstrate writing custom data to Ultimaker filament NFC tag
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# -*- coding: utf-8 -*- | |
# https://github.com/BrianHVB/intro-to-smartcard-development#heading--python-example-1 | |
# | |
# required packages: pyscard | |
# | |
from smartcard.Exceptions import NoCardException | |
from smartcard.System import * | |
from smartcard import util | |
from ums5 import MyFilamentSpool, decode | |
import uuid | |
from binascii import hexlify | |
class MustBeEvenException(Exception): | |
pass | |
def cmd_read_page(start, count=4): | |
return [0xff, 0xb0, (start >> 8) & 0xff, start & 0xff, count & 0xff] | |
def cmd_write_page(start, data): | |
if isinstance(data, bytes): | |
data = list(data) | |
count = len(data) | |
return [0xff, 0xd6, (start >> 8) & 0xff, start & 0xff, count & 0xff] + data | |
def main(): | |
# get and print a list of readers attached to the system | |
sc_readers = readers() | |
print(sc_readers) | |
# create a connection to the first reader | |
first_reader = sc_readers[0] | |
connection = first_reader.createConnection() | |
# get ready for a command | |
get_uid = util.toBytes("FF CA 00 00 00") | |
try: | |
# send the command and capture the response data and status | |
connection.connect() | |
uid_data, sw1, sw2 = connection.transmit(get_uid) | |
# print the response | |
uid = util.toHexString(uid_data) | |
status = util.toHexString([sw1, sw2]) | |
serial = hexlify(bytes(uid_data)).decode('latin').upper() | |
print("UID = {}\tstatus = {}\tdata={}".format(uid, status, uid_data)) | |
carbon = MyFilamentSpool(uuid.UUID("4debf055-6eed-4795-b4c4-4643fba8ea53"), 800000, serial) | |
decode(carbon.data()) | |
tag_data = carbon.data() | |
for i in range(0, len(tag_data), 4): | |
page = i//4 + 4 | |
data = list(tag_data[i:i+4]) # no padding required, length of encoded data is already a multiple of 4 | |
print("[{:02x}] = {}".format(page, util.toHexString(data))) | |
# print("[{:02x}] = {}\tstatus = {}".format(page, util.toHexString(data), util.toHexString([sw1, sw2]))) | |
recv, sw1, sw2 = connection.transmit(cmd_write_page(page, data)) | |
print("[{:02x}] = {}\trecv = {}\tstatus = {}".format(page, util.toHexString(data), | |
util.toHexString(recv), | |
util.toHexString([sw1, sw2]))) | |
decode(bytes(tag_data)) | |
except NoCardException: | |
print("ERROR: Card not present") | |
if __name__ == '__main__': | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment