Compare commits

20 Commits

Author SHA1 Message Date
Martin Quarda
80653dfe11 misplaced start and finish 2025-04-16 15:17:58 +02:00
Martin Quarda
b737934f05 clear usb from applications 2025-04-16 13:09:32 +02:00
Martin Quarda
9227a8bfdb fix 2025-04-09 09:09:28 +02:00
Martin Quarda
5a34e9e4e5 more on_success handlers 2025-04-06 09:20:52 +02:00
Martin Quarda
ef915110a7 registrace.py: update racer only on success 2025-04-06 09:14:13 +02:00
Martin Quarda
19ead426fb reoder to make it works 2025-04-04 18:15:13 +02:00
Martin Quarda
2c9ea8e379 reload_racers button 2025-04-04 11:31:07 +02:00
Martin Quarda
8104096c0b remove /api/station/register at unregister, now server handles it 2025-04-04 10:18:13 +02:00
Martin Quarda
c4d7df8b5d testing dialog 2025-04-04 09:35:03 +02:00
Martin Quarda
03d8045990 small fixes 2025-04-01 20:14:05 +02:00
Martin Quarda
c59b24a561 logs 2025-04-01 11:51:17 +02:00
Martin Quarda
586bd3dc84 unify register and main py worker 2025-04-01 09:35:20 +02:00
Martin Quarda
2e9c11d73b refactor usbcardreader into own file 2025-04-01 09:07:51 +02:00
Martin Quarda
ca8d008e77 first working version 2025-04-01 10:47:02 +02:00
Martin Quarda
bc61d8a0bd small fix 2025-03-28 10:42:29 +01:00
Martin Quarda
2221f5b39d more autonomous 2025-03-28 10:41:17 +01:00
Martin Quarda
9deda461ee added error handling in registrace.py 2025-03-27 17:56:04 +01:00
Martin Quarda
52d81c127d finish up unregister and one variable for host in config 2025-03-27 14:57:32 +01:00
Martin Quarda
5653972b8d creation of registrace.py application, upload time to website in StopWatch 2025-03-27 14:37:40 +01:00
Martin Quarda
c441dc7a32 fix spaces 2025-03-25 08:11:28 +01:00
14 changed files with 505 additions and 202 deletions

View File

@@ -16,7 +16,7 @@ results = {}
with open(FILE,'r') as f: with open(FILE,'r') as f:
file_content = f.read() file_content = f.read()
data_dict = json.loads(file_content) data_dict = json.loads(file_content)
for id in data_dict: for id in data_dict:
laps = int(data_dict[id]['laps']) laps = int(data_dict[id]['laps'])
time = 0 time = 0
@@ -26,12 +26,7 @@ for id in data_dict:
print(data_dict[id]['name'],time) print(data_dict[id]['name'],time)
data_dict[id]['total_time'] = time data_dict[id]['total_time'] = time
results[data_dict[id]['name']] = time results[data_dict[id]['name']] = time
print(results) print(results)
dict(sorted(results.items(), key=lambda item: item[0])) dict(sorted(results.items(), key=lambda item: item[0]))
print(results) print(results)

View File

@@ -0,0 +1,7 @@
{
"station_id": 2,
"host": "https://beta.alkator.cz",
"login": "station_register@alkator.cz",
"password": "password_heslo",
"countdown_seconds": 60
}

1
SW/PC/Stopwatch/log.json Normal file
View File

@@ -0,0 +1 @@
[]

View File

@@ -1,115 +1,136 @@
import gi import gi
import threading import threading
import time import time
import usb.core import datetime
import usb.util
import requests import requests
import json import json
gi.require_version('Gtk', '4.0') gi.require_version('Gtk', '4.0')
from queue import Queue
from gi.repository import Gtk, Gio, Gdk from gi.repository import Gtk, Gio, Gdk
from requests.adapters import HTTPAdapter, Retry
from usbcardreader import UsbCardReader
DEBUG = False
if DEBUG == True: with open('config.json', 'r') as f:
index = 2 config = json.load(f)
else:
index = 1
activeCards = []
TIME = 600
USB_IF = 0 # Interface activeCards = []
USB_TIMEOUT = 5 # Timeout in ms
USB_VENDOR = 0xffff # Vendor-ID:
USB_PRODUCT = 0x0035 # Product-ID
with open('people.json', 'r') as f: TIME = config['countdown_seconds']
db = json.load(f)
db = {}
queue_to_send = []
session = requests.Session()
retries = Retry(total=10,
backoff_factor=1,
status_forcelist=[ 500, 502, 503, 504 ])
session.mount('https://', HTTPAdapter(max_retries=retries))
session.post(config['host'] + '/api/login', {'email':config['login'], 'password': config['password']})
def refreshDb():
global db
resp = session.get(config['host'] + '/api/racers')
if resp.status_code == 200:
json = resp.json()
db = {}
for racer in json:
if racer["card_id"]:
db[racer["card_id"]] = racer
def refreshDbEvery3mins():
while True:
refreshDb()
time.sleep(3 * 60)
threading.Thread(target=refreshDbEvery3mins).start()
log = []
with open('log.json', 'r') as f:
log = json.loads(f.read())
queue = Queue()
def worker():
while True:
item = queue.get()
log.append(item)
with open('log.json', 'w') as f:
f.write(json.dumps(log))
response = session.post(item['url'], json=item['json'])
print(item, response)
threading.Thread(target=worker).start()
def callbackOnCard(card_id):
global win, activeCards, db
if card_id not in db:
refreshDb()
if card_id in db:
if card_id not in activeCards:
activeCards.append(card_id)
win.arb(db[card_id])
print('Card is active now')
else:
print('Card is already active')
else:
print(f'Card {card_id} not found in db')
class UsbCardReader():
def __init__(self, **kargs):
# Find the HID device by vendor/product ID
self.dev = usb.core.find(idVendor=USB_VENDOR, idProduct=USB_PRODUCT)
# Get and store the endpoint
self.endpoint = self.dev[0][(0,0)][0]
if self.dev.is_kernel_driver_active(USB_IF) is True:
self.dev.detach_kernel_driver(USB_IF)
# Claim the device
usb.util.claim_interface(self.dev, USB_IF)
self.receivedNumber = 0
cardread=threading.Thread(target=self.read)
cardread.start()
def read(self):
global win, activeCards, db
print("Waiting for card")
receivedNumber = 0
while True:
control = None
try:
control = self.dev.read(self.endpoint.bEndpointAddress, self.endpoint.wMaxPacketSize, USB_TIMEOUT)
if (control[2] != 40) & (control[2] != 0):
receivedDigit = control[2] - 29
if receivedDigit == 10:
receivedDigit = 0
receivedNumber = 10 * receivedNumber + receivedDigit
if (( control[0] == 0 )) & (( control[2] == 40 )) & (( not receivedNumber == 0 )):
try:
with open('people.json', 'r') as f:
db = json.load(f)
for i in db:
if db[i] == receivedNumber:
if i not in activeCards:
activeCards.append(i)
win.arb(i)
else:
print("Card is active now")
except Exception as e: print(e)
receivedNumber = 0
except KeyboardInterrupt:
exit()
except:
pass
time.sleep(0.001)
class GridRow(): class GridRow():
def __init__(self, parent, runner, index): def __init__(self, parent, racer, index):
self.id = runner global queue_to_send
self.index = index self.id = racer['starting_number']
self.parent = parent self.parent = parent
self.grid = Gtk.Grid() self.grid = Gtk.Grid()
if index % 2 == 0: if index % 2 == 0:
self.grid.set_name("lightgrid") self.grid.set_name("lightgrid")
else: else:
self.grid.set_name("darkgrid") self.grid.set_name("darkgrid")
self.runid = Gtk.Label(label=str(runner), name="gridlabel") self.runid = Gtk.Label(label=str(racer["starting_number"]), name="gridlabel")
self.runid.set_justify(2) self.runid.set_justify(2)
self.runid.set_width_chars(10) self.runid.set_width_chars(10)
self.runb = Gtk.Label(label='00:00', name="gridlabel") self.runb = Gtk.Label(label='00:00', name="gridlabel")
self.runb.set_hexpand(1) self.runb.set_hexpand(1)
self.grid.attach(self.runid, 0, 0, 1, 1) self.grid.attach(self.runid, 0, 0, 1, 1)
self.grid.attach(self.runb, 1, 0, 1, 1) self.grid.attach(self.runb, 1, 0, 1, 1)
parent.grid.attach(self.grid, 0, index, 2, 1) parent.grid.attach(self.grid, 0, index, 2, 1)
countdown=threading.Thread(target=self.updateTime) countdown=threading.Thread(target=self.updateTime)
countdown.start() countdown.start()
queue.put({'url': config['host'] + '/api/station/register', 'json': {
'card_id': racer['card_id'],
'station_id': config['station_id'],
'time': datetime.datetime.now().strftime('%d.%m.%Y %H:%M:%S.%f')
}})
def printIndex(self, button): def printIndex(self, button):
print(self.index) print(self.index)
def updateTime(self): def updateTime(self):
t = TIME t = TIME
while t >= -10: while t >= -10:
@@ -120,70 +141,54 @@ class GridRow():
mins, secs = divmod(t, 60) mins, secs = divmod(t, 60)
timer = '{:02d}:{:02d}'.format(mins, secs) timer = '{:02d}:{:02d}'.format(mins, secs)
self.runb.set_label(timer) self.runb.set_label(timer)
time.sleep(1) time.sleep(1)
t -= 1 t -= 1
if t == 10: if t == 10:
if self.grid.get_name() == "lightgrid": if self.grid.get_name() == "lightgrid":
self.grid.set_name("lredgrid") self.grid.set_name("lredgrid")
else: else:
self.grid.set_name("dredgrid") self.grid.set_name("dredgrid")
GridWindow.remRow(self.parent) GridWindow.remRow(self.parent)
class GridWindow(Gtk.ApplicationWindow): class GridWindow(Gtk.ApplicationWindow):
def __init__(self, **kargs): def __init__(self, **kargs):
super().__init__(**kargs, title='Alkator Clock') super().__init__(**kargs, title='Alkator Clock')
css_provider = Gtk.CssProvider() css_provider = Gtk.CssProvider()
css_provider.load_from_file(Gio.File.new_for_path("style.css")) css_provider.load_from_file(Gio.File.new_for_path("style.css"))
Gtk.StyleContext.add_provider_for_display(Gdk.Display.get_default(), css_provider, Gtk.STYLE_PROVIDER_PRIORITY_APPLICATION) Gtk.StyleContext.add_provider_for_display(Gdk.Display.get_default(), css_provider, Gtk.STYLE_PROVIDER_PRIORITY_APPLICATION)
button1 = Gtk.Button(label='addrow')
button2 = Gtk.Button(label='rmrow')
button1.connect("clicked", self.arb)
button2.connect("clicked", self.rrb)
runlabel = Gtk.Label(label="ID", name="gridlabel") runlabel = Gtk.Label(label="ID", name="gridlabel")
runlabel.set_justify(2) runlabel.set_justify(2)
cntlabel = Gtk.Label(label="Countdown", name="gridlabel") cntlabel = Gtk.Label(label="Countdown", name="gridlabel")
cntlabel.set_justify(2) cntlabel.set_justify(2)
self.runners = [] self.runners = []
self.grid = Gtk.Grid() self.grid = Gtk.Grid()
if DEBUG == True: self.grid.attach(runlabel, 0, 0, 1, 1)
self.grid.attach(button1, 0, 0, 1, 1) self.grid.attach(cntlabel, 1, 0, 2, 1)
self.grid.attach(button2, 1, 0, 2, 1)
self.grid.attach(runlabel, 0, 1, 1, 1)
self.grid.attach(cntlabel, 1, 1, 2, 1)
else:
self.grid.attach(runlabel, 0, 0, 1, 1)
self.grid.attach(cntlabel, 1, 0, 2, 1)
self.set_child(self.grid) self.set_child(self.grid)
def arb(self, personId): def arb(self, racer):
global index self.runners.append(GridRow(self, racer, len(activeCards)))
self.runners.append(GridRow(self, personId, index))
index += 1
def rrb(self, button): def rrb(self, button):
global index
self.remRow() self.remRow()
def addRow(self, runner, index): def addRow(self, runner, index):
runid = Gtk.Label(label=str(runner)) runid = Gtk.Label(label=str(runner))
runb = Gtk.Button(label='time_placeholder') runb = Gtk.Button(label='time_placeholder')
self.grid.attach(runid, 0, index, 1, 1) self.grid.attach(runid, 0, index, 1, 1)
self.grid.attach(runb, 1, index, 1, 1) self.grid.attach(runb, 1, index, 1, 1)
def remRow(self): def remRow(self):
global index, activeCards global activeCards
if index > 1: if len(activeCards) > 0:
self.grid.remove_row(1) self.grid.remove_row(1)
index -= 1
del activeCards[0] del activeCards[0]
@@ -193,7 +198,7 @@ def on_activate(app):
win = GridWindow(application=app) win = GridWindow(application=app)
win.present() win.present()
UsbCardReader() UsbCardReader(callbackOnCard)
app = Gtk.Application(application_id='com.example.App') app = Gtk.Application(application_id='com.example.App')
app.connect('activate', on_activate) app.connect('activate', on_activate)

View File

@@ -0,0 +1,184 @@
import sys
import datetime
import requests
import threading
import json
from PyQt6 import QtWidgets, uic, QtGui, QtCore
from PyQt6.QtCore import pyqtSignal as Signal, pyqtSlot as Slot
from queue import Queue
from requests.adapters import HTTPAdapter, Retry
from usbcardreader import UsbCardReader
app = QtWidgets.QApplication(sys.argv)
with open('config.json', 'r') as f:
config = json.load(f)
session = requests.Session()
session.post(config['host'] + '/api/login', {'email':config['login'], 'password': config['password']})
retries = Retry(total=10,
backoff_factor=1,
status_forcelist=[ 500, 502, 503, 504 ],)
session.mount('https://', HTTPAdapter(max_retries=retries))
last_card = 0
last_time = datetime.datetime.now()
racers = []
log = []
with open('log.json', 'r') as f:
log = json.loads(f.read())
queue = Queue()
class Worker(QtCore.QThread):
returned_state = Signal(str)
def __init__(self):
super().__init__()
self.returned_state.connect(self.handle_returned_state)
self.worker_thread = threading.Thread(target=self.worker)
self.worker_thread.start()
def worker(self):
while True:
item = queue.get()
log.append({
'url': item['url'],
'json': item['json'],
})
with open('log.json', 'w') as f:
f.write(json.dumps(log))
response = session.post(item['url'], json=item['json'])
if response.status_code == 200:
if item.get('on_success'):
item['on_success']()
if item.get('message'):
self.returned_state.emit(f'{item['message']}')
else:
if item.get('failed'):
self.returned_state.emit(f'{item['failed']}')
print(item, response)
def handle_returned_state(self, state):
mb = QtWidgets.QMessageBox(text=f"{state}")
mb.exec()
worker = Worker()
def register_racer():
card_id = last_card
index = window.racers.currentIndex()
if not index.data():
mb = QtWidgets.QMessageBox(text='Prosím vyberte závodníka!')
mb.exec()
return
racer_id = int(index.data().split(' ')[-1])
try:
starting_number = max(filter(lambda r: r['starting_number'], racers), key=lambda racer: racer['starting_number'])['starting_number'] + 1
except ValueError:
starting_number = 1
racer = list(filter(lambda x: x['racer_id'] == racer_id, racers))[0]
def register_update_racer():
racer['card_id'] = card_id
racer['starting_number'] = starting_number
racer['started'] = False
updateRacers()
queue.put({
'url': config['host'] + '/api/card/register',
'json': {'racer_id': racer_id, 'starting_number': starting_number, 'card_id': card_id, 'time': datetime.datetime.now().strftime('%d.%m.%Y %H:%M:%S.%f')},
'message': f"Úspěšné zaregistrování závodníka {racer['first_name']} {racer['last_name']} se startovním číslem {starting_number}!",
'failed': f"Neúspěšná registrace závodníka {racer['first_name']} {racer['last_name']}",
'on_success': register_update_racer,
})
model = QtGui.QStandardItemModel()
def updateRacers():
model.clear()
for racer in racers:
if racer['starting_number'] or racer['card_id']:
continue
item = QtGui.QStandardItem(f"{racer['last_name']} {racer['first_name']} {racer['date_of_birth']} {racer['racer_id']}")
model.appendRow(item)
updateRacers()
def reload_racers():
global racers
response = session.get(config['host'] + '/api/racers')
racers = response.json()
updateRacers()
reload_racers()
def findByCard(card_id):
for racer in racers:
if racer['card_id'] == card_id:
return racer
def updateLastCard(card_id):
global last_card, last_time
if card_id == last_card and datetime.datetime.now() - last_time < datetime.timedelta(seconds=15):
return
time = last_time = datetime.datetime.now()
last_card = card_id
window.lastCard.setText(str(card_id))
racer = findByCard(card_id)
if racer:
if racer['started']:
def finish_update_racer():
racer['card_id'] = None
queue.put({
'url': config['host'] + '/api/card/unregister',
'json': {'racer_id': racer['racer_id'], 'starting_number': racer['starting_number'], 'card_id': card_id, 'time': time.strftime('%d.%m.%Y %H:%M:%S.%f')},
'message': f"Úspěšné odhlášení závodníka {racer['starting_number']}!",
'failed': f"Neúspěšné odhlášení karty závodníka {racer['starting_number']}",
'on_success': finish_update_racer,
})
else:
def start_update_racer():
racer['started'] = True
queue.put({
'url': config['host'] + '/api/station/register',
'json': {'card_id': card_id, 'time': time.strftime('%d.%m.%Y %H:%M:%S.%f'), 'station_id': 1},
'message': f"Úspěšné odstartování závodníka {racer['starting_number']}!",
'failed': f"Núspěšné odstartování závodníka {racer['starting_number']}, prosím registraci opakujte!",
'on_success': start_update_racer,
})
UsbCardReader(updateLastCard)
window = uic.loadUi("registrace.ui")
window.racers.setModel(model)
window.register_racer.clicked.connect(register_racer)
window.reload_racers.clicked.connect(reload_racers)
window.show()
app.exec()

View File

@@ -0,0 +1,61 @@
<?xml version="1.0" encoding="UTF-8"?>
<ui version="4.0">
<class>Frame</class>
<widget class="QFrame" name="Frame">
<property name="geometry">
<rect>
<x>0</x>
<y>0</y>
<width>315</width>
<height>289</height>
</rect>
</property>
<property name="windowTitle">
<string>Registrace závodníků</string>
</property>
<layout class="QGridLayout" name="gridLayout">
<item row="4" column="0">
<spacer name="verticalSpacer">
<property name="orientation">
<enum>Qt::Orientation::Vertical</enum>
</property>
<property name="sizeHint" stdset="0">
<size>
<width>20</width>
<height>40</height>
</size>
</property>
</spacer>
</item>
<item row="0" column="0">
<widget class="QPushButton" name="register_racer">
<property name="text">
<string>Registrovat</string>
</property>
</widget>
</item>
<item row="2" column="0">
<widget class="QLineEdit" name="lastCard"/>
</item>
<item row="1" column="0">
<widget class="QLabel" name="label_2">
<property name="text">
<string>číslo karty</string>
</property>
</widget>
</item>
<item row="0" column="1" rowspan="5">
<widget class="QListView" name="racers"/>
</item>
<item row="3" column="0">
<widget class="QPushButton" name="reload_racers">
<property name="text">
<string>Obnovit Závodníky</string>
</property>
</widget>
</item>
</layout>
</widget>
<resources/>
<connections/>
</ui>

View File

@@ -1,51 +1,51 @@
import usb.core import usb.core
import usb.util import usb.util
import time import time
import requests import requests
import json import json
USB_IF = 0 # Interface USB_IF = 0 # Interface
USB_TIMEOUT = 5 # Timeout in MS USB_TIMEOUT = 5 # Timeout in MS
USB_VENDOR = 0xffff # Vendor-ID: USB_VENDOR = 0xffff # Vendor-ID:
USB_PRODUCT = 0x0035 # Product-ID USB_PRODUCT = 0x0035 # Product-ID
# Find the HID device by vender/product ID # Find the HID device by vender/product ID
dev = usb.core.find(idVendor=USB_VENDOR, idProduct=USB_PRODUCT) dev = usb.core.find(idVendor=USB_VENDOR, idProduct=USB_PRODUCT)
# Get and store the endpoint # Get and store the endpoint
endpoint = dev[0][(0,0)][0] endpoint = dev[0][(0,0)][0]
if dev.is_kernel_driver_active(USB_IF) is True: if dev.is_kernel_driver_active(USB_IF) is True:
dev.detach_kernel_driver(USB_IF) dev.detach_kernel_driver(USB_IF)
# Claim the device # Claim the device
usb.util.claim_interface(dev, USB_IF) usb.util.claim_interface(dev, USB_IF)
receivedNumber = 0 receivedNumber = 0
while True: while True:
control = None control = None
try: try:
# Read a character from the device # Read a character from the device
control = dev.read(endpoint.bEndpointAddress, endpoint.wMaxPacketSize, USB_TIMEOUT) control = dev.read(endpoint.bEndpointAddress, endpoint.wMaxPacketSize, USB_TIMEOUT)
# Here you have to analyze what's coming in. # Here you have to analyze what's coming in.
# In my case you had to check the first byte (command) # In my case you had to check the first byte (command)
if (control[2] != 40) & (control[2] != 0): if (control[2] != 40) & (control[2] != 0):
# Convert ascii to a number, there's probably better ways to do so. # Convert ascii to a number, there's probably better ways to do so.
receivedDigit = control[2] - 29 receivedDigit = control[2] - 29
if receivedDigit == 10: if receivedDigit == 10:
receivedDigit = 0 receivedDigit = 0
# Append the digit to the number # Append the digit to the number
receivedNumber = 10 * receivedNumber + receivedDigit receivedNumber = 10 * receivedNumber + receivedDigit
# Check if the received character is CRLF # Check if the received character is CRLF
if (( control[0] == 0 )) & (( control[2] == 40 )) & (( not receivedNumber == 0 )): if (( control[0] == 0 )) & (( control[2] == 40 )) & (( not receivedNumber == 0 )):
print('cardNumber:', receivedNumber) print('cardNumber:', receivedNumber)
except KeyboardInterrupt: except KeyboardInterrupt:
exit() exit()
except: except:
pass pass
time.sleep(0.001) # Let CTRL+C actually exit time.sleep(0.001) # Let CTRL+C actually exit

View File

@@ -12,7 +12,7 @@ if DEBUG == True:
index = 2 index = 2
else: else:
index = 1 index = 1
activeCards = [] activeCards = []
TIME = 600 TIME = 600
@@ -53,16 +53,16 @@ class UsbCardReader():
# Claim the device # Claim the device
usb.util.claim_interface(self.dev, USB_IF) usb.util.claim_interface(self.dev, USB_IF)
self.receivedNumber = 0 self.receivedNumber = 0
cardread=threading.Thread(target=self.read) cardread=threading.Thread(target=self.read)
cardread.start() cardread.start()
def read(self): def read(self):
global activeCards, db, times, times_json global activeCards, db, times, times_json
print("Waiting for card") print("Waiting for card")
receivedNumber = 0 receivedNumber = 0
while True: while True:
control = None control = None
try: try:
@@ -72,7 +72,7 @@ class UsbCardReader():
if receivedDigit == 10: if receivedDigit == 10:
receivedDigit = 0 receivedDigit = 0
receivedNumber = 10 * receivedNumber + receivedDigit receivedNumber = 10 * receivedNumber + receivedDigit
if (( control[0] == 0 )) & (( control[2] == 40 )) & (( not receivedNumber == 0 )): if (( control[0] == 0 )) & (( control[2] == 40 )) & (( not receivedNumber == 0 )):
try: try:
with open('people.json', 'r') as f: with open('people.json', 'r') as f:
@@ -99,12 +99,12 @@ class UsbCardReader():
print(times) print(times)
except Exception as e: print(e) except Exception as e: print(e)
receivedNumber = 0 receivedNumber = 0
except KeyboardInterrupt: except KeyboardInterrupt:
exit() exit()
except: except:
pass pass
time.sleep(0.001) time.sleep(0.001)
UsbCardReader() UsbCardReader()

View File

@@ -0,0 +1,52 @@
import usb.core
import usb.util
import threading
import time
USB_IF = 0 # Interface
USB_TIMEOUT = 5 # Timeout in ms
USB_VENDOR = 0xffff # Vendor-ID:
USB_PRODUCT = 0x0035 # Product-ID
class UsbCardReader:
def __init__(self, callback):
#fn called on found card
self.callback = callback
# Find the HID device by vendor/product ID
self.dev = usb.core.find(idVendor=USB_VENDOR, idProduct=USB_PRODUCT)
# Get and store the endpoint
self.endpoint = self.dev[0][(0,0)][0]
if self.dev.is_kernel_driver_active(USB_IF) is True:
self.dev.detach_kernel_driver(USB_IF)
# Claim the device
usb.util.claim_interface(self.dev, USB_IF)
self.receivedNumber = 0
cardread=threading.Thread(target=self.read)
cardread.start()
def read(self):
receivedNumber = 0
while True:
control = None
try:
control = self.dev.read(self.endpoint.bEndpointAddress, self.endpoint.wMaxPacketSize, USB_TIMEOUT)
if (control[2] != 40) and (control[2] != 0):
receivedDigit = control[2] - 29
if receivedDigit == 10:
receivedDigit = 0
receivedNumber = 10 * receivedNumber + receivedDigit
if ( control[0] == 0 ) and ( control[2] == 40 ) and ( not receivedNumber == 0 ):
self.callback(receivedNumber)
receivedNumber = 0
except KeyboardInterrupt:
exit()
except:
receivedNumber = 0
pass
time.sleep(0.001)

View File

@@ -29,12 +29,12 @@ class UsbCardReader():
# Claim the device # Claim the device
usb.util.claim_interface(self.dev, USB_IF) usb.util.claim_interface(self.dev, USB_IF)
self.receivedNumber = 0 self.receivedNumber = 0
def read(self): def read(self):
global activeCards global activeCards
print("Priloz kartu") print("Priloz kartu")
while True: while True:
control = None control = None
try: try:
@@ -44,7 +44,7 @@ class UsbCardReader():
if receivedDigit == 10: if receivedDigit == 10:
receivedDigit = 0 receivedDigit = 0
self.receivedNumber = 10 * self.receivedNumber + receivedDigit self.receivedNumber = 10 * self.receivedNumber + receivedDigit
if (( control[0] == 0 )) & (( control[2] == 40 )) & (( not self.receivedNumber == 0 )): if (( control[0] == 0 )) & (( control[2] == 40 )) & (( not self.receivedNumber == 0 )):
try: try:
cardPresent = False cardPresent = False
@@ -60,24 +60,24 @@ class UsbCardReader():
self.receivedNumber = 0 self.receivedNumber = 0
print("Priloz kartu") print("Priloz kartu")
except Exception as e: print(e) except Exception as e: print(e)
except KeyboardInterrupt: except KeyboardInterrupt:
exit() exit()
except: except:
pass pass
time.sleep(0.001) time.sleep(0.001)
def assign(self): def assign(self):
global activeCards global activeCards
n = input("Cislo zavodnika: ") n = input("Cislo zavodnika: ")
activeCards[str(n)] = self.receivedNumber activeCards[str(n)] = self.receivedNumber
with open('people.json', 'w') as f: with open('people.json', 'w') as f:
f.write(json.dumps(activeCards, indent = 4)) f.write(json.dumps(activeCards, indent = 4))
self.receivedNumber = 0 self.receivedNumber = 0
print("Ulozeno, priloz kartu") print("Ulozeno, priloz kartu")
if __name__ == "__main__": if __name__ == "__main__":
reader = UsbCardReader() reader = UsbCardReader()
print("Zapis zavodniku ready") print("Zapis zavodniku ready")

View File

@@ -46,17 +46,17 @@ def read(ser):
lap += 1 lap += 1
data_dict[data[0]]['laps'] = lap data_dict[data[0]]['laps'] = lap
data_dict[data[0]]['time'] = get_seconds() data_dict[data[0]]['time'] = get_seconds()
except: except:
data_dict[data[0]] = {'name': data[1]} data_dict[data[0]] = {'name': data[1]}
data_dict[data[0]]['time'] = get_seconds() data_dict[data[0]]['time'] = get_seconds()
data_dict[data[0]]['laps'] = 0 data_dict[data[0]]['laps'] = 0
data_json = json.dumps(data_dict, indent=4) data_json = json.dumps(data_dict, indent=4)
print(data_json) print(data_json)
with open(JSON_PATH, 'w') as file: with open(JSON_PATH, 'w') as file:
file.write(data_json) file.write(data_json)
def write(ser): def write(ser):
while True: while True:
data = input('ID:') data = input('ID:')
@@ -77,10 +77,10 @@ def write(ser):
def main(): def main():
s = serial.Serial(port="/dev/ttyACM3", parity=serial.PARITY_EVEN, stopbits=serial.STOPBITS_ONE, timeout=1) s = serial.Serial(port="/dev/ttyACM3", parity=serial.PARITY_EVEN, stopbits=serial.STOPBITS_ONE, timeout=1)
s.flush() s.flush()
rw = input('Read or Write tags? [R/w]') rw = input('Read or Write tags? [R/w]')
rw = rw.lower() rw = rw.lower()
if rw == 'w': if rw == 'w':
s.write('w\r'.encode()) s.write('w\r'.encode())
write(s) write(s)
@@ -90,12 +90,11 @@ def main():
elif rw == '': elif rw == '':
s.write('r\r'.encode()) s.write('r\r'.encode())
read(s) read(s)
else: else:
print('Invalid option') print('Invalid option')
if __name__ == "__main__":
if __name__ == "__main__":
main() main()

View File

@@ -56,13 +56,13 @@ def loop_neopixel():
led_strip.fill(color) led_strip.fill(color)
led_strip.write() led_strip.write()
time.sleep(1) time.sleep(1)
neopix_loop_dot_pos = 0 neopix_loop_dot_pos = 0
def neopixel_loop_dot(): def neopixel_loop_dot():
global neopix_loop_dot_pos global neopix_loop_dot_pos
color = (255, 0, 0) color = (255, 0, 0)
black = (0, 0, 0) black = (0, 0, 0)
color = set_neopixel_brightness(color) color = set_neopixel_brightness(color)
led_strip[neopix_loop_dot_pos] = black led_strip[neopix_loop_dot_pos] = black
neopix_loop_dot_pos += 1 neopix_loop_dot_pos += 1
@@ -71,16 +71,16 @@ def neopixel_loop_dot():
led_strip[neopix_loop_dot_pos] = color led_strip[neopix_loop_dot_pos] = color
led_strip.write() led_strip.write()
time.sleep(0.2) time.sleep(0.2)
def lightup_led(index, color): def lightup_led(index, color):
led_strip[index] = color led_strip[index] = color
led_strip.write() led_strip.write()
def blink_and_beep(times): def blink_and_beep(times):
global pushbutton_pressed, blink_interrupted global pushbutton_pressed, blink_interrupted
blink_delay = 0.2 blink_delay = 0.2
#insert beep #insert beep
buzzer.value(1) buzzer.value(1)
for i in range(0, times): for i in range(0, times):
@@ -97,20 +97,20 @@ def blink_and_beep(times):
buzzer.value(0) buzzer.value(0)
return return
buzzer.value(0) buzzer.value(0)
ten_min_timer = 0 ten_min_timer = 0
ten_min_timer_led_index = 11 ten_min_timer_led_index = 11
def count_10_min(): def count_10_min():
global ten_min_timer, ten_min_timer_led_index, pushbutton_pressed, blink_interrupted global ten_min_timer, ten_min_timer_led_index, pushbutton_pressed, blink_interrupted
red = (255, 0, 0) red = (255, 0, 0)
red = set_neopixel_brightness(red) red = set_neopixel_brightness(red)
green = (0, 255, 0) green = (0, 255, 0)
green = set_neopixel_brightness(green) green = set_neopixel_brightness(green)
if ten_min_timer_led_index == 11: if ten_min_timer_led_index == 11:
return return
if (ten_min_timer % 60) == 0: if (ten_min_timer % 60) == 0:
if ten_min_timer_led_index == 10: if ten_min_timer_led_index == 10:
pushbutton_pressed = 0 pushbutton_pressed = 0
@@ -128,7 +128,7 @@ def count_10_min():
return return
lightup_led(ten_min_timer_led_index, red) lightup_led(ten_min_timer_led_index, red)
ten_min_timer_led_index += 1 ten_min_timer_led_index += 1
ten_min_timer += 1 ten_min_timer += 1
def button_callback(push_button): def button_callback(push_button):

View File

@@ -406,4 +406,3 @@ class PN532:
_COMMAND_INDATAEXCHANGE, params=params, response_length=1 _COMMAND_INDATAEXCHANGE, params=params, response_length=1
) )
return response[0] == 0x00 return response[0] == 0x00

View File

@@ -84,12 +84,12 @@ def read_nfc_loop():
# Try again if no card is available. # Try again if no card is available.
if uid is not None: if uid is not None:
break break
set_neopixel_color(255,255,0) set_neopixel_color(255,255,0)
ntag_string = 'Data: ' ntag_string = 'Data: '
sys.stdout.write('Reading ntag \r') sys.stdout.write('Reading ntag \r')
leds_on = 0 leds_on = 0
for page in range(20,40): for page in range(20,40):
try: try:
@@ -105,7 +105,7 @@ def read_nfc_loop():
if leds_on > 7: if leds_on > 7:
leds_on = 7 leds_on = 7
led_strip.write() led_strip.write()
if ntag2xx_page is not None: if ntag2xx_page is not None:
for char in ntag2xx_page: for char in ntag2xx_page:
ntag_string += chr(char) ntag_string += chr(char)
@@ -115,11 +115,11 @@ def read_nfc_loop():
except: except:
sys.stdout.write('Error reading card\r') sys.stdout.write('Error reading card\r')
return 1 return 1
set_neopixel_color(0,255,0) set_neopixel_color(0,255,0)
sys.stdout.write(ntag_string + '\r') sys.stdout.write(ntag_string + '\r')
time.sleep(3) time.sleep(3)
return 0 return 0
#print('PAGE ',page,': ',[chr(x) for x in ntag2xx_page]) #print('PAGE ',page,': ',[chr(x) for x in ntag2xx_page])
@@ -138,14 +138,14 @@ def write_nfc_loop(data):
# Try again if no card is available. # Try again if no card is available.
if uid is not None: if uid is not None:
break break
set_neopixel_color(255,255,0) set_neopixel_color(255,255,0)
sys.stdout.write('Erasing card\r') sys.stdout.write('Erasing card\r')
for page in range(20,41): for page in range(20,41):
content_erase = b'\x00\x00\x00\x00' content_erase = b'\x00\x00\x00\x00'
pn532.ntag2xx_write_block(page, content_erase) pn532.ntag2xx_write_block(page, content_erase)
sys.stdout.write('Writing card\r') sys.stdout.write('Writing card\r')
for page in range(20,20 + pages): for page in range(20,20 + pages):
content_slice = bytearray(4) content_slice = bytearray(4)
@@ -157,7 +157,7 @@ def write_nfc_loop(data):
#content_slice.append(content[i + 4 * (page - 20)]) #content_slice.append(content[i + 4 * (page - 20)])
print(content_slice) print(content_slice)
pn532.ntag2xx_write_block(page, content_slice) pn532.ntag2xx_write_block(page, content_slice)
sys.stdout.write('Write done\r') sys.stdout.write('Write done\r')
set_neopixel_color(0,255,0) set_neopixel_color(0,255,0)