Lots of various updates for Open Sauce

This commit is contained in:
James Hoffman 2024-06-19 22:32:41 -06:00
commit 56a8c92d53
74 changed files with 38056 additions and 0 deletions

176
.gitignore vendored Normal file
View File

@ -0,0 +1,176 @@
# Generated by code
logs/
backup/
__pycache__/
.idea/
build/
data
collar_data
headsetData
mark
data-fake
threshold
options
# ---> Python
# Byte-compiled / optimized / DLL files
__pycache__/
*.py[cod]
*$py.class
# C extensions
*.so
# Distribution / packaging
.Python
build/
develop-eggs/
dist/
downloads/
eggs/
.eggs/
lib/
lib64/
parts/
sdist/
var/
wheels/
share/python-wheels/
*.egg-info/
.installed.cfg
*.egg
MANIFEST
# PyInstaller
# Usually these files are written by a python script from a template
# before PyInstaller builds the exe, so as to inject date/other infos into it.
*.manifest
*.spec
# Installer logs
pip-log.txt
pip-delete-this-directory.txt
# Unit test / coverage reports
htmlcov/
.tox/
.nox/
.coverage
.coverage.*
.cache
nosetests.xml
coverage.xml
*.cover
*.py,cover
.hypothesis/
.pytest_cache/
cover/
# Translations
*.mo
*.pot
# Django stuff:
*.log
local_settings.py
db.sqlite3
db.sqlite3-journal
# Flask stuff:
instance/
.webassets-cache
# Scrapy stuff:
.scrapy
# Sphinx documentation
docs/_build/
# PyBuilder
.pybuilder/
target/
# Jupyter Notebook
.ipynb_checkpoints
# IPython
profile_default/
ipython_config.py
# pyenv
# For a library or package, you might want to ignore these files since the code is
# intended to run in multiple environments; otherwise, check them in:
# .python-version
# pipenv
# According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.
# However, in case of collaboration, if having platform-specific dependencies or dependencies
# having no cross-platform support, pipenv may install dependencies that don't work, or not
# install all needed dependencies.
#Pipfile.lock
# poetry
# Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control.
# This is especially recommended for binary packages to ensure reproducibility, and is more
# commonly ignored for libraries.
# https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control
#poetry.lock
# pdm
# Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control.
#pdm.lock
# pdm stores project-wide configurations in .pdm.toml, but it is recommended to not include it
# in version control.
# https://pdm.fming.dev/#use-with-ide
.pdm.toml
# PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm
__pypackages__/
# Celery stuff
celerybeat-schedule
celerybeat.pid
# SageMath parsed files
*.sage.py
# Environments
.env
.venv
env/
venv/
ENV/
env.bak/
venv.bak/
# Spyder project settings
.spyderproject
.spyproject
# Rope project settings
.ropeproject
# mkdocs documentation
/site
# mypy
.mypy_cache/
.dmypy.json
dmypy.json
# Pyre type checker
.pyre/
# pytype static type analyzer
.pytype/
# Cython debug symbols
cython_debug/
# PyCharm
# JetBrains specific template is maintained in a separate JetBrains.gitignore that can
# be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore
# and can be added to the global gitignore or merged into this file. For a more nuclear
# option (not recommended) you can uncomment the following to ignore the entire idea folder.
#.idea/

3
.gitmodules vendored Normal file
View File

@ -0,0 +1,3 @@
[submodule "Simple-Logger"]
path = Simple-Logger
url = git.timothyhay.org/public/Simple-Logger.git

10
.vscode/Brain.code-workspace vendored Normal file
View File

@ -0,0 +1,10 @@
{
"folders": [
{
"path": ".."
}
],
"settings": {
"C_Cpp.intelliSenseEngine": "default"
}
}

8
.vscode/arduino.json vendored Normal file
View File

@ -0,0 +1,8 @@
{
"configuration": "xtal=80,vt=flash,exception=disabled,stacksmash=disabled,ssl=all,mmu=3232,non32xfer=fast,FlashMode=dout,FlashFreq=40,eesz=4M2M,ip=lm2f,dbg=Disabled,lvl=None____,wipe=none,baud=921600",
"board": "esp8266:esp8266:d1_mini_clone",
"sketch": "other/arduinoTest/arduinoTest.ino",
"port": "/dev/ttyUSB0",
"output": "build",
"programmer": "esptool"
}

379
.vscode/c_cpp_properties.json vendored Normal file
View File

@ -0,0 +1,379 @@
{
"version": 4,
"configurations": [
{
"name": "Linux",
"compilerPath": "/usr/bin/clang",
"compilerArgs": [],
"intelliSenseMode": "linux-clang-x64",
"includePath": [
"${workspaceFolder}/**"
],
"forcedInclude": [],
"cStandard": "c17",
"cppStandard": "c++17",
"defines": [
"USBCON"
]
},
{
"name": "Arduino",
"compilerPath": "/home/jamesh/.arduino15/packages/esp8266/tools/xtensa-lx106-elf-gcc/3.1.0-gcc10.3-e5f9fec/bin/xtensa-lx106-elf-g++",
"compilerArgs": [
"-U__STRICT_ANSI__",
"-free",
"-fipa-pta",
"-Werror=return-type",
"-mlongcalls",
"-mtext-section-literals",
"-fno-rtti",
"-falign-functions=4",
"-std=gnu++17"
],
"intelliSenseMode": "gcc-x64",
"includePath": [
"/home/jamesh/.arduino15/packages/esp8266/hardware/esp8266/3.1.2/tools/sdk/include",
"/home/jamesh/.arduino15/packages/esp8266/hardware/esp8266/3.1.2/tools/sdk/lwip2/include",
"/home/jamesh/Brain/build/core",
"/home/jamesh/.arduino15/packages/esp8266/hardware/esp8266/3.1.2/cores/esp8266",
"/home/jamesh/.arduino15/packages/esp8266/hardware/esp8266/3.1.2/variants/d1_mini",
"/home/jamesh/.arduino15/packages/esp8266/hardware/esp8266/3.1.2/libraries/ESP8266WiFi/src",
"/home/jamesh/.arduino15/packages/esp8266/tools/xtensa-lx106-elf-gcc/3.1.0-gcc10.3-e5f9fec/xtensa-lx106-elf/include/c++/10.3.0",
"/home/jamesh/.arduino15/packages/esp8266/tools/xtensa-lx106-elf-gcc/3.1.0-gcc10.3-e5f9fec/xtensa-lx106-elf/include/c++/10.3.0/xtensa-lx106-elf",
"/home/jamesh/.arduino15/packages/esp8266/tools/xtensa-lx106-elf-gcc/3.1.0-gcc10.3-e5f9fec/xtensa-lx106-elf/include/c++/10.3.0/backward",
"/home/jamesh/.arduino15/packages/esp8266/tools/xtensa-lx106-elf-gcc/3.1.0-gcc10.3-e5f9fec/lib/gcc/xtensa-lx106-elf/10.3.0/include",
"/home/jamesh/.arduino15/packages/esp8266/tools/xtensa-lx106-elf-gcc/3.1.0-gcc10.3-e5f9fec/lib/gcc/xtensa-lx106-elf/10.3.0/include-fixed",
"/home/jamesh/.arduino15/packages/esp8266/tools/xtensa-lx106-elf-gcc/3.1.0-gcc10.3-e5f9fec/xtensa-lx106-elf/include"
],
"forcedInclude": [
"/home/jamesh/.arduino15/packages/esp8266/hardware/esp8266/3.1.2/cores/esp8266/Arduino.h"
],
"cStandard": "c11",
"cppStandard": "c++17",
"defines": [
"__ets__",
"ICACHE_FLASH",
"_GNU_SOURCE",
"ESP8266",
"MMU_IRAM_SIZE=0x8000",
"MMU_ICACHE_SIZE=0x8000",
"NONOSDK22x_190703=1",
"F_CPU=80000000L",
"LWIP_OPEN_SRC",
"TCP_MSS=536",
"LWIP_FEATURES=1",
"LWIP_IPV6=0",
"ARDUINO=10607",
"ARDUINO_ESP8266_WEMOS_D1MINI",
"ARDUINO_ARCH_ESP8266",
"ARDUINO_BOARD=\"ESP8266_WEMOS_D1MINI\"",
"ARDUINO_BOARD_ID=\"d1_mini_clone\"",
"FLASHMODE_DOUT",
"__DBL_MIN_EXP__=(-1021)",
"__cpp_attributes=200809L",
"__UINT_LEAST16_MAX__=0xffff",
"__ATOMIC_ACQUIRE=2",
"__FLT_MIN__=1.1754943508222875e-38F",
"__GCC_IEC_559_COMPLEX=0",
"__cpp_aggregate_nsdmi=201304L",
"__UINT_LEAST8_TYPE__=unsigned char",
"__INTMAX_C(c)=c ## LL",
"__CHAR_BIT__=8",
"__UINT8_MAX__=0xff",
"__WINT_MAX__=0xffffffffU",
"__FLT32_MIN_EXP__=(-125)",
"__cpp_static_assert=200410L",
"__ORDER_LITTLE_ENDIAN__=1234",
"__SIZE_MAX__=0xffffffffU",
"__WCHAR_MAX__=0xffff",
"__DBL_DENORM_MIN__=double(4.9406564584124654e-324L)",
"__GCC_ATOMIC_CHAR_LOCK_FREE=1",
"__GCC_IEC_559=0",
"__FLT32X_DECIMAL_DIG__=17",
"__FLT_EVAL_METHOD__=0",
"__cpp_binary_literals=201304L",
"__FLT64_DECIMAL_DIG__=17",
"__GCC_ATOMIC_CHAR32_T_LOCK_FREE=1",
"__cpp_variadic_templates=200704L",
"__UINT_FAST64_MAX__=0xffffffffffffffffULL",
"__SIG_ATOMIC_TYPE__=int",
"__DBL_MIN_10_EXP__=(-307)",
"__FINITE_MATH_ONLY__=0",
"__cpp_variable_templates=201304L",
"__FLT32X_MAX_EXP__=1024",
"__GNUC_PATCHLEVEL__=0",
"__FLT32_HAS_DENORM__=1",
"__UINT_FAST8_MAX__=0xffffffffU",
"__cpp_rvalue_reference=200610L",
"__FLT32_MAX_10_EXP__=38",
"__INT8_C(c)=c",
"__INT_LEAST8_WIDTH__=8",
"__UINT_LEAST64_MAX__=0xffffffffffffffffULL",
"__SHRT_MAX__=0x7fff",
"__LDBL_MAX__=1.7976931348623157e+308L",
"__UINT_LEAST8_MAX__=0xff",
"__GCC_ATOMIC_BOOL_LOCK_FREE=1",
"__UINTMAX_TYPE__=long long unsigned int",
"__FLT_EVAL_METHOD_TS_18661_3__=0",
"__CHAR_UNSIGNED__=1",
"__UINT32_MAX__=0xffffffffU",
"__GXX_EXPERIMENTAL_CXX0X__=1",
"__LDBL_MAX_EXP__=1024",
"__WINT_MIN__=0U",
"__INT_LEAST16_WIDTH__=16",
"__SCHAR_MAX__=0x7f",
"__WCHAR_MIN__=0",
"__INT64_C(c)=c ## LL",
"__GCC_ATOMIC_POINTER_LOCK_FREE=1",
"__XTENSA_CALL0_ABI__=1",
"__SIZEOF_INT__=4",
"__FLT32X_MANT_DIG__=53",
"__GCC_ATOMIC_CHAR16_T_LOCK_FREE=1",
"__USER_LABEL_PREFIX__",
"__STDC_HOSTED__=1",
"__XTENSA_EL__=1",
"__cpp_decltype_auto=201304L",
"__DBL_DIG__=15",
"__FLT32_DIG__=6",
"__FLT_EPSILON__=1.1920928955078125e-7F",
"__GXX_WEAK__=1",
"__SHRT_WIDTH__=16",
"__LDBL_MIN__=2.2250738585072014e-308L",
"__cpp_threadsafe_static_init=200806L",
"__FLT32X_HAS_INFINITY__=1",
"__INT32_MAX__=0x7fffffff",
"__INT_WIDTH__=32",
"__SIZEOF_LONG__=4",
"__UINT16_C(c)=c",
"__DECIMAL_DIG__=17",
"__FLT64_EPSILON__=2.2204460492503131e-16F64",
"__INT16_MAX__=0x7fff",
"__FLT64_MIN_EXP__=(-1021)",
"__LDBL_HAS_QUIET_NAN__=1",
"__FLT64_MANT_DIG__=53",
"__GNUC__=10",
"__GXX_RTTI=1",
"__FLT_HAS_DENORM__=1",
"__SIZEOF_LONG_DOUBLE__=8",
"__BIGGEST_ALIGNMENT__=16",
"__STDC_UTF_16__=1",
"__FLT64_MAX_10_EXP__=308",
"__cpp_delegating_constructors=200604L",
"__FLT32_HAS_INFINITY__=1",
"__DBL_MAX__=double(1.7976931348623157e+308L)",
"__cpp_raw_strings=200710L",
"__INT_FAST32_MAX__=0x7fffffff",
"__DBL_HAS_INFINITY__=1",
"__HAVE_SPECULATION_SAFE_VALUE=1",
"__INTPTR_WIDTH__=32",
"__UINT_LEAST32_MAX__=0xffffffffU",
"__FLT32X_HAS_DENORM__=1",
"__INT_FAST16_TYPE__=int",
"__LDBL_HAS_DENORM__=1",
"__cplusplus=201402L",
"__cpp_ref_qualifiers=200710L",
"__INT_LEAST32_MAX__=0x7fffffff",
"__DEPRECATED=1",
"__cpp_rvalue_references=200610L",
"__DBL_MAX_EXP__=1024",
"__WCHAR_WIDTH__=16",
"__FLT32_MAX__=3.4028234663852886e+38F32",
"__GCC_ATOMIC_LONG_LOCK_FREE=1",
"__PTRDIFF_MAX__=0x7fffffff",
"__FLT32_HAS_QUIET_NAN__=1",
"__GNUG__=10",
"__LONG_LONG_MAX__=0x7fffffffffffffffLL",
"__SIZEOF_SIZE_T__=4",
"__cpp_nsdmi=200809L",
"__SIZEOF_WINT_T__=4",
"__LONG_LONG_WIDTH__=64",
"__cpp_initializer_lists=200806L",
"__FLT32_MAX_EXP__=128",
"__cpp_hex_float=201603L",
"__GXX_ABI_VERSION=1014",
"__FLT_MIN_EXP__=(-125)",
"__cpp_lambdas=200907L",
"__INT_FAST64_TYPE__=long long int",
"__FLT64_DENORM_MIN__=4.9406564584124654e-324F64",
"__DBL_MIN__=double(2.2250738585072014e-308L)",
"__SIZEOF_POINTER__=4",
"__SIZE_TYPE__=unsigned int",
"__DBL_HAS_QUIET_NAN__=1",
"__FLT32X_EPSILON__=2.2204460492503131e-16F32x",
"__FLT64_MIN_10_EXP__=(-307)",
"__REGISTER_PREFIX__",
"__UINT16_MAX__=0xffff",
"__FLT32_MIN__=1.1754943508222875e-38F32",
"__UINT8_TYPE__=unsigned char",
"__FLT_DIG__=6",
"__NO_INLINE__=1",
"__DEC_EVAL_METHOD__=2",
"__FLT_MANT_DIG__=24",
"__LDBL_DECIMAL_DIG__=17",
"__VERSION__=\"10.3.0\"",
"__UINT64_C(c)=c ## ULL",
"__cpp_unicode_characters=200704L",
"__XTENSA_SOFT_FLOAT__=1",
"__GCC_ATOMIC_INT_LOCK_FREE=1",
"__FLT32_MANT_DIG__=24",
"__FLOAT_WORD_ORDER__=__ORDER_LITTLE_ENDIAN__",
"__SCHAR_WIDTH__=8",
"__INT32_C(c)=c",
"__ORDER_PDP_ENDIAN__=3412",
"__INT_FAST32_TYPE__=int",
"__UINT_LEAST16_TYPE__=short unsigned int",
"__DBL_HAS_DENORM__=1",
"__cpp_rtti=199711L",
"__UINT64_MAX__=0xffffffffffffffffULL",
"__INT8_TYPE__=signed char",
"__cpp_digit_separators=201309L",
"__ELF__=1",
"__xtensa__=1",
"__FLT_RADIX__=2",
"__INT_LEAST16_TYPE__=short int",
"__LDBL_EPSILON__=2.2204460492503131e-16L",
"__UINTMAX_C(c)=c ## ULL",
"__FLT32X_MIN__=2.2250738585072014e-308F32x",
"__SIG_ATOMIC_MAX__=0x7fffffff",
"__GCC_ATOMIC_WCHAR_T_LOCK_FREE=1",
"__SIZEOF_PTRDIFF_T__=4",
"__LDBL_DIG__=15",
"__FLT32X_MIN_EXP__=(-1021)",
"__INT_FAST16_MAX__=0x7fffffff",
"__FLT64_DIG__=15",
"__UINT_FAST32_MAX__=0xffffffffU",
"__UINT_LEAST64_TYPE__=long long unsigned int",
"__FLT_HAS_QUIET_NAN__=1",
"__FLT_MAX_10_EXP__=38",
"__LONG_MAX__=0x7fffffffL",
"__FLT_HAS_INFINITY__=1",
"__cpp_unicode_literals=200710L",
"__UINT_FAST16_TYPE__=unsigned int",
"__INT_FAST32_WIDTH__=32",
"__CHAR16_TYPE__=short unsigned int",
"__PRAGMA_REDEFINE_EXTNAME=1",
"__SIZE_WIDTH__=32",
"__INT_LEAST16_MAX__=0x7fff",
"__INT64_MAX__=0x7fffffffffffffffLL",
"__FLT32_DENORM_MIN__=1.4012984643248171e-45F32",
"__SIG_ATOMIC_WIDTH__=32",
"__INT_LEAST64_TYPE__=long long int",
"__INT16_TYPE__=short int",
"__INT_LEAST8_TYPE__=signed char",
"__INT_FAST8_MAX__=0x7fffffff",
"__INTPTR_MAX__=0x7fffffff",
"__cpp_sized_deallocation=201309L",
"__FLT64_HAS_QUIET_NAN__=1",
"__FLT32_MIN_10_EXP__=(-37)",
"__EXCEPTIONS=1",
"__PTRDIFF_WIDTH__=32",
"__LDBL_MANT_DIG__=53",
"__cpp_range_based_for=200907L",
"__FLT64_HAS_INFINITY__=1",
"__SIG_ATOMIC_MIN__=(-__SIG_ATOMIC_MAX__ - 1)",
"__cpp_return_type_deduction=201304L",
"__INTPTR_TYPE__=int",
"__UINT16_TYPE__=short unsigned int",
"__WCHAR_TYPE__=short unsigned int",
"__SIZEOF_FLOAT__=4",
"__UINTPTR_MAX__=0xffffffffU",
"__INT_FAST64_WIDTH__=64",
"__cpp_decltype=200707L",
"__FLT32_DECIMAL_DIG__=9",
"__INT_FAST64_MAX__=0x7fffffffffffffffLL",
"__GCC_ATOMIC_TEST_AND_SET_TRUEVAL=1",
"__FLT_NORM_MAX__=3.4028234663852886e+38F",
"__UINT_FAST64_TYPE__=long long unsigned int",
"__INT_MAX__=0x7fffffff",
"__INT64_TYPE__=long long int",
"__FLT_MAX_EXP__=128",
"__DBL_MANT_DIG__=53",
"__cpp_inheriting_constructors=201511L",
"__INT_LEAST64_MAX__=0x7fffffffffffffffLL",
"__WINT_TYPE__=unsigned int",
"__UINT_LEAST32_TYPE__=unsigned int",
"__SIZEOF_SHORT__=2",
"__FLT32_NORM_MAX__=3.4028234663852886e+38F32",
"__LDBL_MIN_EXP__=(-1021)",
"__FLT64_MAX__=1.7976931348623157e+308F64",
"__WINT_WIDTH__=32",
"__INT_LEAST8_MAX__=0x7f",
"__INT_LEAST64_WIDTH__=64",
"__FLT32X_MAX_10_EXP__=308",
"__WCHAR_UNSIGNED__=1",
"__LDBL_MAX_10_EXP__=308",
"__ATOMIC_RELAXED=0",
"__DBL_EPSILON__=double(2.2204460492503131e-16L)",
"__UINT8_C(c)=c",
"__FLT64_MAX_EXP__=1024",
"__INT_LEAST32_TYPE__=int",
"__SIZEOF_WCHAR_T__=2",
"__FLT64_NORM_MAX__=1.7976931348623157e+308F64",
"__INTMAX_MAX__=0x7fffffffffffffffLL",
"__INT_FAST8_TYPE__=int",
"__LDBL_HAS_INFINITY__=1",
"__GNUC_STDC_INLINE__=1",
"__FLT64_HAS_DENORM__=1",
"__FLT32_EPSILON__=1.1920928955078125e-7F32",
"__DBL_DECIMAL_DIG__=17",
"__STDC_UTF_32__=1",
"__INT_FAST8_WIDTH__=32",
"__FLT32X_MAX__=1.7976931348623157e+308F32x",
"__DBL_NORM_MAX__=double(1.7976931348623157e+308L)",
"__BYTE_ORDER__=__ORDER_LITTLE_ENDIAN__",
"__XTENSA__=1",
"__INTMAX_WIDTH__=64",
"__ORDER_BIG_ENDIAN__=4321",
"__cpp_runtime_arrays=198712L",
"__UINT64_TYPE__=long long unsigned int",
"__UINT32_C(c)=c ## U",
"__cpp_alias_templates=200704L",
"__FLT_DENORM_MIN__=1.4012984643248171e-45F",
"__INT8_MAX__=0x7f",
"__LONG_WIDTH__=32",
"__UINT_FAST32_TYPE__=unsigned int",
"__FLT32X_NORM_MAX__=1.7976931348623157e+308F32x",
"__CHAR32_TYPE__=unsigned int",
"__FLT_MAX__=3.4028234663852886e+38F",
"__cpp_constexpr=201304L",
"__INT32_TYPE__=int",
"__SIZEOF_DOUBLE__=8",
"__cpp_exceptions=199711L",
"__FLT_MIN_10_EXP__=(-37)",
"__FLT64_MIN__=2.2250738585072014e-308F64",
"__INT_LEAST32_WIDTH__=32",
"__INTMAX_TYPE__=long long int",
"__FLT32X_HAS_QUIET_NAN__=1",
"__ATOMIC_CONSUME=1",
"__GNUC_MINOR__=3",
"__INT_FAST16_WIDTH__=32",
"__UINTMAX_MAX__=0xffffffffffffffffULL",
"__FLT32X_DENORM_MIN__=4.9406564584124654e-324F32x",
"__DBL_MAX_10_EXP__=308",
"__LDBL_DENORM_MIN__=4.9406564584124654e-324L",
"__INT16_C(c)=c",
"__STDC__=1",
"__FLT32X_DIG__=15",
"__PTRDIFF_TYPE__=int",
"__ATOMIC_SEQ_CST=5",
"__UINT32_TYPE__=unsigned int",
"__FLT32X_MIN_10_EXP__=(-307)",
"__UINTPTR_TYPE__=unsigned int",
"__LDBL_MIN_10_EXP__=(-307)",
"__cpp_generic_lambdas=201304L",
"__SIZEOF_LONG_LONG__=8",
"__cpp_user_defined_literals=200809L",
"__GCC_ATOMIC_LLONG_LOCK_FREE=1",
"__FLT_DECIMAL_DIG__=9",
"__UINT_FAST16_MAX__=0xffffffffU",
"__LDBL_NORM_MAX__=1.7976931348623157e+308L",
"__GCC_ATOMIC_SHORT_LOCK_FREE=1",
"__UINT_FAST8_TYPE__=unsigned int",
"__cpp_init_captures=201304L",
"__ATOMIC_ACQ_REL=4",
"__ATOMIC_RELEASE=3",
"USBCON"
]
}
]
}

3
.vscode/settings.json vendored Normal file
View File

@ -0,0 +1,3 @@
{
"C_Cpp.errorSquiggles": "enabled"
}

674
LICENSE Normal file
View File

@ -0,0 +1,674 @@
GNU GENERAL PUBLIC LICENSE
Version 3, 29 June 2007
Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Preamble
The GNU General Public License is a free, copyleft license for
software and other kinds of works.
The licenses for most software and other practical works are designed
to take away your freedom to share and change the works. By contrast,
the GNU General Public License is intended to guarantee your freedom to
share and change all versions of a program--to make sure it remains free
software for all its users. We, the Free Software Foundation, use the
GNU General Public License for most of our software; it applies also to
any other work released this way by its authors. You can apply it to
your programs, too.
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
them if you wish), that you receive source code or can get it if you
want it, that you can change the software or use pieces of it in new
free programs, and that you know you can do these things.
To protect your rights, we need to prevent others from denying you
these rights or asking you to surrender the rights. Therefore, you have
certain responsibilities if you distribute copies of the software, or if
you modify it: responsibilities to respect the freedom of others.
For example, if you distribute copies of such a program, whether
gratis or for a fee, you must pass on to the recipients the same
freedoms that you received. You must make sure that they, too, receive
or can get the source code. And you must show them these terms so they
know their rights.
Developers that use the GNU GPL protect your rights with two steps:
(1) assert copyright on the software, and (2) offer you this License
giving you legal permission to copy, distribute and/or modify it.
For the developers' and authors' protection, the GPL clearly explains
that there is no warranty for this free software. For both users' and
authors' sake, the GPL requires that modified versions be marked as
changed, so that their problems will not be attributed erroneously to
authors of previous versions.
Some devices are designed to deny users access to install or run
modified versions of the software inside them, although the manufacturer
can do so. This is fundamentally incompatible with the aim of
protecting users' freedom to change the software. The systematic
pattern of such abuse occurs in the area of products for individuals to
use, which is precisely where it is most unacceptable. Therefore, we
have designed this version of the GPL to prohibit the practice for those
products. If such problems arise substantially in other domains, we
stand ready to extend this provision to those domains in future versions
of the GPL, as needed to protect the freedom of users.
Finally, every program is threatened constantly by software patents.
States should not allow patents to restrict development and use of
software on general-purpose computers, but in those that do, we wish to
avoid the special danger that patents applied to a free program could
make it effectively proprietary. To prevent this, the GPL assures that
patents cannot be used to render the program non-free.
The precise terms and conditions for copying, distribution and
modification follow.
TERMS AND CONDITIONS
0. Definitions.
"This License" refers to version 3 of the GNU General Public License.
"Copyright" also means copyright-like laws that apply to other kinds of
works, such as semiconductor masks.
"The Program" refers to any copyrightable work licensed under this
License. Each licensee is addressed as "you". "Licensees" and
"recipients" may be individuals or organizations.
To "modify" a work means to copy from or adapt all or part of the work
in a fashion requiring copyright permission, other than the making of an
exact copy. The resulting work is called a "modified version" of the
earlier work or a work "based on" the earlier work.
A "covered work" means either the unmodified Program or a work based
on the Program.
To "propagate" a work means to do anything with it that, without
permission, would make you directly or secondarily liable for
infringement under applicable copyright law, except executing it on a
computer or modifying a private copy. Propagation includes copying,
distribution (with or without modification), making available to the
public, and in some countries other activities as well.
To "convey" a work means any kind of propagation that enables other
parties to make or receive copies. Mere interaction with a user through
a computer network, with no transfer of a copy, is not conveying.
An interactive user interface displays "Appropriate Legal Notices"
to the extent that it includes a convenient and prominently visible
feature that (1) displays an appropriate copyright notice, and (2)
tells the user that there is no warranty for the work (except to the
extent that warranties are provided), that licensees may convey the
work under this License, and how to view a copy of this License. If
the interface presents a list of user commands or options, such as a
menu, a prominent item in the list meets this criterion.
1. Source Code.
The "source code" for a work means the preferred form of the work
for making modifications to it. "Object code" means any non-source
form of a work.
A "Standard Interface" means an interface that either is an official
standard defined by a recognized standards body, or, in the case of
interfaces specified for a particular programming language, one that
is widely used among developers working in that language.
The "System Libraries" of an executable work include anything, other
than the work as a whole, that (a) is included in the normal form of
packaging a Major Component, but which is not part of that Major
Component, and (b) serves only to enable use of the work with that
Major Component, or to implement a Standard Interface for which an
implementation is available to the public in source code form. A
"Major Component", in this context, means a major essential component
(kernel, window system, and so on) of the specific operating system
(if any) on which the executable work runs, or a compiler used to
produce the work, or an object code interpreter used to run it.
The "Corresponding Source" for a work in object code form means all
the source code needed to generate, install, and (for an executable
work) run the object code and to modify the work, including scripts to
control those activities. However, it does not include the work's
System Libraries, or general-purpose tools or generally available free
programs which are used unmodified in performing those activities but
which are not part of the work. For example, Corresponding Source
includes interface definition files associated with source files for
the work, and the source code for shared libraries and dynamically
linked subprograms that the work is specifically designed to require,
such as by intimate data communication or control flow between those
subprograms and other parts of the work.
The Corresponding Source need not include anything that users
can regenerate automatically from other parts of the Corresponding
Source.
The Corresponding Source for a work in source code form is that
same work.
2. Basic Permissions.
All rights granted under this License are granted for the term of
copyright on the Program, and are irrevocable provided the stated
conditions are met. This License explicitly affirms your unlimited
permission to run the unmodified Program. The output from running a
covered work is covered by this License only if the output, given its
content, constitutes a covered work. This License acknowledges your
rights of fair use or other equivalent, as provided by copyright law.
You may make, run and propagate covered works that you do not
convey, without conditions so long as your license otherwise remains
in force. You may convey covered works to others for the sole purpose
of having them make modifications exclusively for you, or provide you
with facilities for running those works, provided that you comply with
the terms of this License in conveying all material for which you do
not control copyright. Those thus making or running the covered works
for you must do so exclusively on your behalf, under your direction
and control, on terms that prohibit them from making any copies of
your copyrighted material outside their relationship with you.
Conveying under any other circumstances is permitted solely under
the conditions stated below. Sublicensing is not allowed; section 10
makes it unnecessary.
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
No covered work shall be deemed part of an effective technological
measure under any applicable law fulfilling obligations under article
11 of the WIPO copyright treaty adopted on 20 December 1996, or
similar laws prohibiting or restricting circumvention of such
measures.
When you convey a covered work, you waive any legal power to forbid
circumvention of technological measures to the extent such circumvention
is effected by exercising rights under this License with respect to
the covered work, and you disclaim any intention to limit operation or
modification of the work as a means of enforcing, against the work's
users, your or third parties' legal rights to forbid circumvention of
technological measures.
4. Conveying Verbatim Copies.
You may convey verbatim copies of the Program's source code as you
receive it, in any medium, provided that you conspicuously and
appropriately publish on each copy an appropriate copyright notice;
keep intact all notices stating that this License and any
non-permissive terms added in accord with section 7 apply to the code;
keep intact all notices of the absence of any warranty; and give all
recipients a copy of this License along with the Program.
You may charge any price or no price for each copy that you convey,
and you may offer support or warranty protection for a fee.
5. Conveying Modified Source Versions.
You may convey a work based on the Program, or the modifications to
produce it from the Program, in the form of source code under the
terms of section 4, provided that you also meet all of these conditions:
a) The work must carry prominent notices stating that you modified
it, and giving a relevant date.
b) The work must carry prominent notices stating that it is
released under this License and any conditions added under section
7. This requirement modifies the requirement in section 4 to
"keep intact all notices".
c) You must license the entire work, as a whole, under this
License to anyone who comes into possession of a copy. This
License will therefore apply, along with any applicable section 7
additional terms, to the whole of the work, and all its parts,
regardless of how they are packaged. This License gives no
permission to license the work in any other way, but it does not
invalidate such permission if you have separately received it.
d) If the work has interactive user interfaces, each must display
Appropriate Legal Notices; however, if the Program has interactive
interfaces that do not display Appropriate Legal Notices, your
work need not make them do so.
A compilation of a covered work with other separate and independent
works, which are not by their nature extensions of the covered work,
and which are not combined with it such as to form a larger program,
in or on a volume of a storage or distribution medium, is called an
"aggregate" if the compilation and its resulting copyright are not
used to limit the access or legal rights of the compilation's users
beyond what the individual works permit. Inclusion of a covered work
in an aggregate does not cause this License to apply to the other
parts of the aggregate.
6. Conveying Non-Source Forms.
You may convey a covered work in object code form under the terms
of sections 4 and 5, provided that you also convey the
machine-readable Corresponding Source under the terms of this License,
in one of these ways:
a) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by the
Corresponding Source fixed on a durable physical medium
customarily used for software interchange.
b) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by a
written offer, valid for at least three years and valid for as
long as you offer spare parts or customer support for that product
model, to give anyone who possesses the object code either (1) a
copy of the Corresponding Source for all the software in the
product that is covered by this License, on a durable physical
medium customarily used for software interchange, for a price no
more than your reasonable cost of physically performing this
conveying of source, or (2) access to copy the
Corresponding Source from a network server at no charge.
c) Convey individual copies of the object code with a copy of the
written offer to provide the Corresponding Source. This
alternative is allowed only occasionally and noncommercially, and
only if you received the object code with such an offer, in accord
with subsection 6b.
d) Convey the object code by offering access from a designated
place (gratis or for a charge), and offer equivalent access to the
Corresponding Source in the same way through the same place at no
further charge. You need not require recipients to copy the
Corresponding Source along with the object code. If the place to
copy the object code is a network server, the Corresponding Source
may be on a different server (operated by you or a third party)
that supports equivalent copying facilities, provided you maintain
clear directions next to the object code saying where to find the
Corresponding Source. Regardless of what server hosts the
Corresponding Source, you remain obligated to ensure that it is
available for as long as needed to satisfy these requirements.
e) Convey the object code using peer-to-peer transmission, provided
you inform other peers where the object code and Corresponding
Source of the work are being offered to the general public at no
charge under subsection 6d.
A separable portion of the object code, whose source code is excluded
from the Corresponding Source as a System Library, need not be
included in conveying the object code work.
A "User Product" is either (1) a "consumer product", which means any
tangible personal property which is normally used for personal, family,
or household purposes, or (2) anything designed or sold for incorporation
into a dwelling. In determining whether a product is a consumer product,
doubtful cases shall be resolved in favor of coverage. For a particular
product received by a particular user, "normally used" refers to a
typical or common use of that class of product, regardless of the status
of the particular user or of the way in which the particular user
actually uses, or expects or is expected to use, the product. A product
is a consumer product regardless of whether the product has substantial
commercial, industrial or non-consumer uses, unless such uses represent
the only significant mode of use of the product.
"Installation Information" for a User Product means any methods,
procedures, authorization keys, or other information required to install
and execute modified versions of a covered work in that User Product from
a modified version of its Corresponding Source. The information must
suffice to ensure that the continued functioning of the modified object
code is in no case prevented or interfered with solely because
modification has been made.
If you convey an object code work under this section in, or with, or
specifically for use in, a User Product, and the conveying occurs as
part of a transaction in which the right of possession and use of the
User Product is transferred to the recipient in perpetuity or for a
fixed term (regardless of how the transaction is characterized), the
Corresponding Source conveyed under this section must be accompanied
by the Installation Information. But this requirement does not apply
if neither you nor any third party retains the ability to install
modified object code on the User Product (for example, the work has
been installed in ROM).
The requirement to provide Installation Information does not include a
requirement to continue to provide support service, warranty, or updates
for a work that has been modified or installed by the recipient, or for
the User Product in which it has been modified or installed. Access to a
network may be denied when the modification itself materially and
adversely affects the operation of the network or violates the rules and
protocols for communication across the network.
Corresponding Source conveyed, and Installation Information provided,
in accord with this section must be in a format that is publicly
documented (and with an implementation available to the public in
source code form), and must require no special password or key for
unpacking, reading or copying.
7. Additional Terms.
"Additional permissions" are terms that supplement the terms of this
License by making exceptions from one or more of its conditions.
Additional permissions that are applicable to the entire Program shall
be treated as though they were included in this License, to the extent
that they are valid under applicable law. If additional permissions
apply only to part of the Program, that part may be used separately
under those permissions, but the entire Program remains governed by
this License without regard to the additional permissions.
When you convey a copy of a covered work, you may at your option
remove any additional permissions from that copy, or from any part of
it. (Additional permissions may be written to require their own
removal in certain cases when you modify the work.) You may place
additional permissions on material, added by you to a covered work,
for which you have or can give appropriate copyright permission.
Notwithstanding any other provision of this License, for material you
add to a covered work, you may (if authorized by the copyright holders of
that material) supplement the terms of this License with terms:
a) Disclaiming warranty or limiting liability differently from the
terms of sections 15 and 16 of this License; or
b) Requiring preservation of specified reasonable legal notices or
author attributions in that material or in the Appropriate Legal
Notices displayed by works containing it; or
c) Prohibiting misrepresentation of the origin of that material, or
requiring that modified versions of such material be marked in
reasonable ways as different from the original version; or
d) Limiting the use for publicity purposes of names of licensors or
authors of the material; or
e) Declining to grant rights under trademark law for use of some
trade names, trademarks, or service marks; or
f) Requiring indemnification of licensors and authors of that
material by anyone who conveys the material (or modified versions of
it) with contractual assumptions of liability to the recipient, for
any liability that these contractual assumptions directly impose on
those licensors and authors.
All other non-permissive additional terms are considered "further
restrictions" within the meaning of section 10. If the Program as you
received it, or any part of it, contains a notice stating that it is
governed by this License along with a term that is a further
restriction, you may remove that term. If a license document contains
a further restriction but permits relicensing or conveying under this
License, you may add to a covered work material governed by the terms
of that license document, provided that the further restriction does
not survive such relicensing or conveying.
If you add terms to a covered work in accord with this section, you
must place, in the relevant source files, a statement of the
additional terms that apply to those files, or a notice indicating
where to find the applicable terms.
Additional terms, permissive or non-permissive, may be stated in the
form of a separately written license, or stated as exceptions;
the above requirements apply either way.
8. Termination.
You may not propagate or modify a covered work except as expressly
provided under this License. Any attempt otherwise to propagate or
modify it is void, and will automatically terminate your rights under
this License (including any patent licenses granted under the third
paragraph of section 11).
However, if you cease all violation of this License, then your
license from a particular copyright holder is reinstated (a)
provisionally, unless and until the copyright holder explicitly and
finally terminates your license, and (b) permanently, if the copyright
holder fails to notify you of the violation by some reasonable means
prior to 60 days after the cessation.
Moreover, your license from a particular copyright holder is
reinstated permanently if the copyright holder notifies you of the
violation by some reasonable means, this is the first time you have
received notice of violation of this License (for any work) from that
copyright holder, and you cure the violation prior to 30 days after
your receipt of the notice.
Termination of your rights under this section does not terminate the
licenses of parties who have received copies or rights from you under
this License. If your rights have been terminated and not permanently
reinstated, you do not qualify to receive new licenses for the same
material under section 10.
9. Acceptance Not Required for Having Copies.
You are not required to accept this License in order to receive or
run a copy of the Program. Ancillary propagation of a covered work
occurring solely as a consequence of using peer-to-peer transmission
to receive a copy likewise does not require acceptance. However,
nothing other than this License grants you permission to propagate or
modify any covered work. These actions infringe copyright if you do
not accept this License. Therefore, by modifying or propagating a
covered work, you indicate your acceptance of this License to do so.
10. Automatic Licensing of Downstream Recipients.
Each time you convey a covered work, the recipient automatically
receives a license from the original licensors, to run, modify and
propagate that work, subject to this License. You are not responsible
for enforcing compliance by third parties with this License.
An "entity transaction" is a transaction transferring control of an
organization, or substantially all assets of one, or subdividing an
organization, or merging organizations. If propagation of a covered
work results from an entity transaction, each party to that
transaction who receives a copy of the work also receives whatever
licenses to the work the party's predecessor in interest had or could
give under the previous paragraph, plus a right to possession of the
Corresponding Source of the work from the predecessor in interest, if
the predecessor has it or can get it with reasonable efforts.
You may not impose any further restrictions on the exercise of the
rights granted or affirmed under this License. For example, you may
not impose a license fee, royalty, or other charge for exercise of
rights granted under this License, and you may not initiate litigation
(including a cross-claim or counterclaim in a lawsuit) alleging that
any patent claim is infringed by making, using, selling, offering for
sale, or importing the Program or any portion of it.
11. Patents.
A "contributor" is a copyright holder who authorizes use under this
License of the Program or a work on which the Program is based. The
work thus licensed is called the contributor's "contributor version".
A contributor's "essential patent claims" are all patent claims
owned or controlled by the contributor, whether already acquired or
hereafter acquired, that would be infringed by some manner, permitted
by this License, of making, using, or selling its contributor version,
but do not include claims that would be infringed only as a
consequence of further modification of the contributor version. For
purposes of this definition, "control" includes the right to grant
patent sublicenses in a manner consistent with the requirements of
this License.
Each contributor grants you a non-exclusive, worldwide, royalty-free
patent license under the contributor's essential patent claims, to
make, use, sell, offer for sale, import and otherwise run, modify and
propagate the contents of its contributor version.
In the following three paragraphs, a "patent license" is any express
agreement or commitment, however denominated, not to enforce a patent
(such as an express permission to practice a patent or covenant not to
sue for patent infringement). To "grant" such a patent license to a
party means to make such an agreement or commitment not to enforce a
patent against the party.
If you convey a covered work, knowingly relying on a patent license,
and the Corresponding Source of the work is not available for anyone
to copy, free of charge and under the terms of this License, through a
publicly available network server or other readily accessible means,
then you must either (1) cause the Corresponding Source to be so
available, or (2) arrange to deprive yourself of the benefit of the
patent license for this particular work, or (3) arrange, in a manner
consistent with the requirements of this License, to extend the patent
license to downstream recipients. "Knowingly relying" means you have
actual knowledge that, but for the patent license, your conveying the
covered work in a country, or your recipient's use of the covered work
in a country, would infringe one or more identifiable patents in that
country that you have reason to believe are valid.
If, pursuant to or in connection with a single transaction or
arrangement, you convey, or propagate by procuring conveyance of, a
covered work, and grant a patent license to some of the parties
receiving the covered work authorizing them to use, propagate, modify
or convey a specific copy of the covered work, then the patent license
you grant is automatically extended to all recipients of the covered
work and works based on it.
A patent license is "discriminatory" if it does not include within
the scope of its coverage, prohibits the exercise of, or is
conditioned on the non-exercise of one or more of the rights that are
specifically granted under this License. You may not convey a covered
work if you are a party to an arrangement with a third party that is
in the business of distributing software, under which you make payment
to the third party based on the extent of your activity of conveying
the work, and under which the third party grants, to any of the
parties who would receive the covered work from you, a discriminatory
patent license (a) in connection with copies of the covered work
conveyed by you (or copies made from those copies), or (b) primarily
for and in connection with specific products or compilations that
contain the covered work, unless you entered into that arrangement,
or that patent license was granted, prior to 28 March 2007.
Nothing in this License shall be construed as excluding or limiting
any implied license or other defenses to infringement that may
otherwise be available to you under applicable patent law.
12. No Surrender of Others' Freedom.
If conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot convey a
covered work so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you may
not convey it at all. For example, if you agree to terms that obligate you
to collect a royalty for further conveying from those to whom you convey
the Program, the only way you could satisfy both those terms and this
License would be to refrain entirely from conveying the Program.
13. Use with the GNU Affero General Public License.
Notwithstanding any other provision of this License, you have
permission to link or combine any covered work with a work licensed
under version 3 of the GNU Affero General Public License into a single
combined work, and to convey the resulting work. The terms of this
License will continue to apply to the part which is the covered work,
but the special requirements of the GNU Affero General Public License,
section 13, concerning interaction through a network will apply to the
combination as such.
14. Revised Versions of this License.
The Free Software Foundation may publish revised and/or new versions of
the GNU General Public License from time to time. Such new versions will
be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.
Each version is given a distinguishing version number. If the
Program specifies that a certain numbered version of the GNU General
Public License "or any later version" applies to it, you have the
option of following the terms and conditions either of that numbered
version or of any later version published by the Free Software
Foundation. If the Program does not specify a version number of the
GNU General Public License, you may choose any version ever published
by the Free Software Foundation.
If the Program specifies that a proxy can decide which future
versions of the GNU General Public License can be used, that proxy's
public statement of acceptance of a version permanently authorizes you
to choose that version for the Program.
Later license versions may give you additional or different
permissions. However, no additional obligations are imposed on any
author or copyright holder as a result of your choosing to follow a
later version.
15. Disclaimer of Warranty.
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
16. Limitation of Liability.
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
SUCH DAMAGES.
17. Interpretation of Sections 15 and 16.
If the disclaimer of warranty and limitation of liability provided
above cannot be given local legal effect according to their terms,
reviewing courts shall apply local law that most closely approximates
an absolute waiver of all civil liability in connection with the
Program, unless a warranty or assumption of liability accompanies a
copy of the Program in return for a fee.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest
to attach them to the start of each source file to most effectively
state the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.
<one line to give the program's name and a brief idea of what it does.>
Copyright (C) <year> <name of author>
This program 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.
This program 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 this program. If not, see <https://www.gnu.org/licenses/>.
Also add information on how to contact you by electronic and paper mail.
If the program does terminal interaction, make it output a short
notice like this when it starts in an interactive mode:
<program> Copyright (C) <year> <name of author>
This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
This is free software, and you are welcome to redistribute it
under certain conditions; type `show c' for details.
The hypothetical commands `show w' and `show c' should show the appropriate
parts of the General Public License. Of course, your program's commands
might be different; for a GUI interface, you would use an "about box".
You should also get your employer (if you work as a programmer) or school,
if any, to sign a "copyright disclaimer" for the program, if necessary.
For more information on this, and how to apply and follow the GNU GPL, see
<https://www.gnu.org/licenses/>.
The GNU General Public License does not permit incorporating your program
into proprietary programs. If your program is a subroutine library, you
may consider it more useful to permit linking proprietary applications with
the library. If this is what you want to do, use the GNU Lesser General
Public License instead of this License. But first, please read
<https://www.gnu.org/licenses/why-not-lgpl.html>.

35
README.md Normal file
View File

@ -0,0 +1,35 @@
# A mind controlled shock collar (for humans)
## Overview
<p align="center">
<img width="300px" src="static/images/slime.png" />
<br>Slimecicle getting shocked by my invention
</p>
This is the repo with all the code I used to make a mind controlled shock collar that got me accepted to exhibit at [Open Sauce!](https://opensauce.com)
It also includes all the EEG data I collected while exhibiting at Open Sauce, atleast for day 1. You can find it all in `data.final.day.one`.
*Please note that this is the code in its spaghetti, unclean, rapidly-finished-hours-before-I-left-for-Open-Sauce, glorious mess. So don't expect too much.*
It uses the [Mindflex](https://en.wikipedia.org/wiki/Mindflex) toy and the [Brain](https://github.com/kitschpatrol/Brain) Arduino library to get the EEG values. It then sends them to the server.
The Mindflex and collar both use a ESP8266 in order to communicate data back to the server over UDP. This means that the entire setup is wireless.
You can then use it from a web interface that uses Flask and [Chart.js](https://www.chartjs.org/)
You can use this web interface to play the "game"
For a more detailed overview on how this all works, you can see my blog post here. (Not finished writing)
## The "Game"
<p align="center">
<img width="700px" src="static/images/play-page.png" />
</p>
To play the game itself, you put on both the collar and Mindflex, and you set a threshold (red line) for either meditation or attention. If you pass this threshold, you will be shocked with a varying power level depending on how far you got from the threshold.
For example, if you set the meditation threshold to something like 80, and the condition to be going above, you would get shocked the second that you start to relax.
<p align="center">
<img width="600px" src="static/images/open-sauce-exhibit.png" />
<br>My booth at Open Sauce
</p>

2
Simple-Logger/README.md Normal file
View File

@ -0,0 +1,2 @@
## A super simple logger function
Only here so I can clone it for simple logging.

10
Simple-Logger/__init__.py Normal file
View File

@ -0,0 +1,10 @@
import os, datetime
if os.path.isfile("logs/main.log"):
if os.path.getsize("logs/main.log") >= 128000:
ct = datetime.datetime.now()
os.rename("logs/main.log", "logs/"+str(ct).replace(" ", "-")+".log")
else:
if not os.path.exists("logs"):
os.makedirs("logs")
f = open("logs/main.log", "w").close()

View File

@ -0,0 +1,44 @@
import datetime, os
from inspect import getframeinfo, stack
i="" #Stop ide complaining
class bcolors:
HEADER = '\033[95m'
OKBLUE = '\033[94m'
OKCYAN = '\033[96m'
OKGREEN = '\033[92m'
WARNING = '\033[93m'
FAIL = '\033[91m'
ENDC = '\033[0m'
BOLD = '\033[1m'
UNDERLINE = '\033[4m'
def log(message, level="i", thread="", detail=True, write=True):
global i
message = f"{bcolors.OKCYAN}{message}{bcolors.ENDC}"
if thread != "":
thread = f"{bcolors.OKGREEN}{thread}{bcolors.ENDC}"+":"
if level.lower() == "i":
i = f"{bcolors.HEADER}INFO:{bcolors.ENDC}"
level = "INFO:"
if level.lower() == "w":
message = f"{bcolors.WARNING}{message.strip(bcolors.OKCYAN).strip(bcolors.ENDC)}{bcolors.ENDC}"
i = f"{bcolors.WARNING}WARNING:{bcolors.ENDC}"
level = "WARNING:"
if level.lower() == "e":
message = f"{bcolors.FAIL}{bcolors.BOLD}{message.strip(bcolors.OKCYAN).strip(bcolors.ENDC)}{bcolors.ENDC}"
i = f"{bcolors.FAIL}{bcolors.BOLD}ERROR:{bcolors.ENDC}"
level = "ERROR:"
if detail:
caller = getframeinfo(stack()[1][0])
name = caller.filename.replace(os.getcwd()+"/", "")
e = i + name +":"+f"{bcolors.OKGREEN}{str(caller.lineno)}{bcolors.ENDC}"+":"+thread+" "+message
f = level+name+" "+str(caller.lineno)+":"+thread.strip(bcolors.OKGREEN).strip(bcolors.ENDC).strip(bcolors.WARNING).strip(bcolors.FAIL)+" "+message.strip(bcolors.OKCYAN).strip(bcolors.ENDC).strip(bcolors.WARNING).strip(bcolors.FAIL)
else:
e = i+thread+" "+message
f = level+thread.strip(bcolors.OKGREEN).strip(bcolors.ENDC).strip(bcolors.WARNING).strip(bcolors.FAIL)+" "+message.strip(bcolors.OKCYAN).strip(bcolors.OKGREEN).strip(bcolors.ENDC).strip(bcolors.WARNING).strip(bcolors.FAIL)
print(e)
if write:
logF = open("logs/main.log", "a")
logF.write(str(datetime.datetime.now())+":"+f.replace(bcolors.ENDC, "")+"\n")
logF.close()

25
Simple-Logger/test.py Normal file
View File

@ -0,0 +1,25 @@
from simpleLog import log
import os
os.remove("logs/main.log")
#Test 1
print("Everything should look like how you want it to.\n")
log("Testing...", "i")
log("I should have a thread listed.", "i", "otherThread")
log("Warning...", "w")
log("I should have a thread listed.", "w", "otherThread")
log("Error!", "e")
log("I should have a thread listed.", "e", "otherThread")
print("\nYou should stop seeing any details!\n")
log("Testing...", "i", "", False)
log("I should have a thread listed.", "i", "otherThread",False)
log("Warning...", "w", "", False)
log("I should have a thread listed.", "w", "otherThread", False)
log("Error!", "e", "", False)
log("I should have a thread listed.", "e", "otherThread", False)
print("\nYou should not see the following in the log file!\n")
log("I should not appear in the log file!", "i", "", False, False)
log("I should not appear in the log file!", "i", "", True, False)
print("\nMake sure the log file doesn't have the above or any color codes!")

0
__init__.py Normal file
View File

99
animate_bar.py Normal file
View File

@ -0,0 +1,99 @@
import matplotlib.pyplot as plt #Alot dirtier than animate_graph
import matplotlib.animation as animation
from matplotlib import style
delta_lim = 3500000
theta_lim = 1320000
low_alpha_lim = 600700
high_alpha_lim = 200000
low_beta_lim = 200000
high_beta_lim = 152500
low_gamma_lim = 163000
high_gamma_lim = 125000
def bar(file, event):
event.wait()
style.use('seaborn-v0_8')
fig = plt.figure(figsize=(19, 11))
for i in range(1, 12):
exec("ax"+str(i)+" = fig.add_subplot(3,4,"+str(i)+")")
figManager = plt.get_current_fig_manager()
figManager.window.showMaximized()
plt.tight_layout()
def animate(i):
global delta_lim, theta_lim, low_alpha_lim, high_alpha_lim, low_beta_lim, high_beta_lim, low_gamma_lim, high_gamma_lim, ax1, ax2, ax3, ax4, ax5, ax6, ax7, ax8, ax9, ax10, ax11
graph_data = open(file,'r').read()
lines = graph_data.split('\n')
xs = []
y_strength = []
y_attention = []
y_meditation = []
y_delta = []
y_theta = []
y_low_alpha = []
y_high_alpha = []
y_low_beta = []
y_high_beta = []
y_low_gamma = []
y_high_gamma = []
for line in lines:
if len(line) > 1:
index, strength, attention, meditation, delta, theta, low_alpha, high_alpha, low_beta, high_beta, low_gamma, high_gamma = line.split(",")
y_strength=(float(strength))
y_attention=(float(attention))
y_meditation=(float(meditation))
y_delta=(float(delta))
y_theta=(float(theta))
y_low_alpha=(float(low_alpha))
y_high_alpha=(float(high_alpha))
y_low_beta=(float(low_beta))
y_high_beta=(float(high_beta))
y_low_gamma=(float(low_gamma))
y_high_gamma=(float(high_gamma))
xs=(float(index))
for i in range(1,12):
eval("ax"+str(i)+".clear()")
ax1.set_ylim(0, 200)
ax2.set_ylim(0, 100)
ax3.set_ylim(0, 100)
if y_delta > delta_lim:
delta_lim = y_delta
if y_theta > theta_lim:
theta_lim = y_theta
if y_low_alpha > low_alpha_lim:
low_alpha_lim = y_low_alpha
if y_high_alpha > high_alpha_lim:
high_alpha_lim = y_high_alpha
if y_low_beta > low_beta_lim:
low_beta_lim = y_low_beta
if y_high_beta > low_beta_lim:
low_beta_lim = y_high_beta
if y_low_gamma > low_gamma_lim:
low_gamma_lim = y_low_gamma
if y_high_gamma > high_gamma_lim:
high_gamma_lim = y_high_gamma
ax4.set_ylim(0, delta_lim)
ax5.set_ylim(0, theta_lim)
ax6.set_ylim(0, low_alpha_lim)
ax7.set_ylim(0, high_alpha_lim)
ax8.set_ylim(0, low_beta_lim)
ax9.set_ylim(0, high_beta_lim)
ax10.set_ylim(0, high_gamma_lim)
ax11.set_ylim(0, low_gamma_lim)
ax1.bar(1, y_strength, label="strength", color="b")
ax2.bar(1, y_attention, label="attention", color="g")
ax3.bar(1, y_meditation, label="meditation", color="r")
ax4.bar(1, y_delta, label="delta", color="c")
ax5.bar(1, y_theta, label="theta", color="m")
ax6.bar(1, y_low_alpha, label="low_alpha", color="y")
ax7.bar(1, y_high_alpha, label="high_alpha", color="k")
ax8.bar(1, y_low_beta, label="low_beta", color="b")
ax9.bar(1, y_high_beta, label="high_beta", color="g")
ax10.bar(1, y_low_gamma, label="low_gamma", color="r")
ax11.bar(1, y_high_gamma, label="high_gamma", color="c")
for i in range(1, 12):
eval("ax" + str(i) + ".legend()")
print("animate_bar: Starting animation")
ani = animation.FuncAnimation(fig, animate, interval=800)
plt.show()

123
animate_graph.py Normal file
View File

@ -0,0 +1,123 @@
import matplotlib.pyplot as plt
import matplotlib.animation as animation
from matplotlib import style
from os.path import exists
import os
import time
limit_points = 0 # TODO: Fix markers not following when points are limited.
pop = 0
marked = []
index = 0
def graph(file, event):
event.wait()
style.use('seaborn-v0_8')
fig, ax = plt.subplots(3, 4, figsize=(19, 11))
ax = ax.flatten()
figManager = plt.get_current_fig_manager()
figManager.window.showMaximized()
plt.tight_layout()
def animate(i):
global limit_points, pop, marked, index
graph_data = open(file,'r').read()
lines = graph_data.split('\n')
xs = []
y_strength = []
y_attention = []
y_meditation = []
y_delta = []
y_theta = []
y_low_alpha = []
y_high_alpha = []
y_low_beta = []
y_high_beta = []
y_low_gamma = []
y_high_gamma = []
for line in lines:
if len(line) > 1:
index, strength, attention, meditation, delta, theta, low_alpha, high_alpha, low_beta, high_beta, low_gamma, high_gamma = line.split(",")
y_strength.append(float(strength))
y_attention.append(float(attention))
y_meditation.append(float(meditation))
y_delta.append(float(delta))
y_theta.append(float(theta))
y_low_alpha.append(float(low_alpha))
y_high_alpha.append(float(high_alpha))
y_low_beta.append(float(low_beta))
y_high_beta.append(float(high_beta))
y_low_gamma.append(float(low_gamma))
y_high_gamma.append(float(high_gamma))
xs.append(float(index))
#for i in range(1,12):
#eval("ax"+str(i)+".clear()")
#ax.clear()
if limit_points > 0:
if int(index) > limit_points:
pop = 0
for i in range(int(index)-limit_points):
if len(xs) != 0:
xs.pop(0)
y_strength.pop(0)
y_attention.pop(0)
y_meditation.pop(0)
y_delta.pop(0)
y_theta.pop(0)
y_low_alpha.pop(0)
y_high_alpha.pop(0)
y_low_beta.pop(0)
y_high_beta.pop(0)
y_low_gamma.pop(0)
y_high_gamma.pop(0)
pop += 1
if len(marked) != 0:
for i in range(len(marked)):
marked[i] = marked[i] - 1
if marked[0] == 0:
marked.pop(0)
file_exists = exists("./mark")
if file_exists:
print("Marking " + str(xs[len(xs) - 1])) #Mark in CSV file?
marked.append(int(xs[len(xs) - 1]-pop))
print("Marked: " + str(marked) + " Pop: " + str(pop))
pop = 0
os.remove("./mark")
for i in range(12):
ax[i].clear()
if len(y_strength) == 0: #If the CSV restarts
print("Clearing marked")
marked = []
ax[0].plot(xs, y_strength, color="b", markevery=marked, marker="D", markerfacecolor="black")
ax[0].plot(xs, y_attention, color="g", markevery=marked, marker="D", markerfacecolor="black")
ax[0].plot(xs, y_meditation, color="r", markevery=marked, marker="D", markerfacecolor="black")
ax[0].plot(xs, y_delta, color="c", markevery=marked, marker="D", markerfacecolor="black")
ax[0].plot(xs, y_theta, color="m", markevery=marked, marker="D", markerfacecolor="black")
ax[0].plot(xs, y_low_alpha, color="y", markevery=marked, marker="D", markerfacecolor="black")
ax[0].plot(xs, y_high_alpha, color="k", markevery=marked, marker="D", markerfacecolor="white")
ax[0].plot(xs, y_low_beta, color="b", markevery=marked, marker="D", markerfacecolor="black")
ax[0].plot(xs, y_high_beta, color="g", markevery=marked, marker="D", markerfacecolor="black")
ax[0].plot(xs, y_low_gamma, color="r", markevery=marked, marker="D", markerfacecolor="black")
ax[0].plot(xs, y_high_gamma, color="c", markevery=marked, marker="D", markerfacecolor="black")
if len(y_strength) > 0:
if int(y_strength[len(y_strength)-1]) != 0:
ax[1].plot(xs, y_strength, label="strength", color="r", markevery=marked, marker="D", markerfacecolor="black")
else:
ax[1].plot(xs, y_strength, label="strength", color="b", markevery=marked, marker="D", markerfacecolor="black")
ax[2].plot(xs, y_attention, label="attention", color="g", markevery=marked, marker="D", markerfacecolor="black")
ax[3].plot(xs, y_meditation, label="meditation", color="r", markevery=marked, marker="D", markerfacecolor="black")
ax[4].plot(xs, y_delta, label="delta", color="c", markevery=marked, marker="D", markerfacecolor="black")
ax[5].plot(xs, y_theta, label="theta", color="m", markevery=marked, marker="D", markerfacecolor="black")
ax[6].plot(xs, y_low_alpha, label="low_alpha", color="y", markevery=marked, marker="D", markerfacecolor="black")
ax[7].plot(xs, y_high_alpha, label="high_alpha", color="k", markevery=marked, marker="D", markerfacecolor="white")
ax[8].plot(xs, y_low_beta, label="low_beta", color="b", markevery=marked, marker="D", markerfacecolor="black")
ax[9].plot(xs, y_high_beta, label="high_beta", color="g", markevery=marked, marker="D", markerfacecolor="black")
ax[10].plot(xs, y_low_gamma, label="low_gamma", color="r", markevery=marked, marker="D", markerfacecolor="black")
ax[11].plot(xs, y_high_gamma, label="high_gamma", color="c", markevery=marked, marker="D", markerfacecolor="black")
for i in range(12):
ax[i].legend()
print("animate_graph: Starting animation")
ani = animation.FuncAnimation(fig, animate, interval=500)
plt.show()

View File

@ -0,0 +1,82 @@
// Get brain data over UDP
#include <Brain.h>
#include <ESP8266WiFi.h>
#include <WiFiUdp.h>
const char* SSID = "SSID";
const char* pass = "PASS";
bool transmit;
unsigned int port = 4120;
char incomingPacket[255]; //Packet buffer
WiFiUDP Udp;
Brain brain(Serial);
void setup() {
Serial.begin(9600);
Serial.println();
pinMode(LED_BUILTIN, OUTPUT); //digitalWrite(LED_BUILTIN, HIGH);
digitalWrite(LED_BUILTIN, LOW);
Serial.printf("Connecting to %s", SSID);
WiFi.begin(SSID, pass);
while (WiFi.status() != WL_CONNECTED)
{
delay(500);
Serial.print(".");
}
Serial.println("connected.");
for (int i = 0; i <= 8; i++) {
digitalWrite(LED_BUILTIN, HIGH);
delay(35);
digitalWrite(LED_BUILTIN, LOW);
delay(35);
}
Udp.begin(port);
Serial.printf("Running at IP %s, UDP port %d - ready to transmit.\n", WiFi.localIP().toString().c_str(), port);
}
void loop() {
if (transmit) {
if (brain.update()) {
digitalWrite(LED_BUILTIN, LOW);
Udp.beginPacket(Udp.remoteIP(), Udp.remotePort());
Udp.write(brain.readCSV());
Serial.print("Attempting to transmit: ");
Serial.println(brain.readCSV());
Udp.endPacket();
delay(300);
int packetSize = Udp.parsePacket();
if (!packetSize)
{
Serial.println("Didn't get response! Stopping transmission.");
transmit = false;
for (int i = 0; i <= 5; i++) {
digitalWrite(LED_BUILTIN, HIGH);
delay(50);
digitalWrite(LED_BUILTIN, LOW);
delay(50);
}
}
digitalWrite(LED_BUILTIN, HIGH);
}
}
else {
int packetSize = Udp.parsePacket();
if (packetSize) {
Serial.println("Got packet. Starting to transmit.");
transmit = true;
for (int i = 0; i <= 2; i++) {
digitalWrite(LED_BUILTIN, HIGH);
delay(100);
digitalWrite(LED_BUILTIN, LOW);
delay(100);
}
}
}
//if (brain.update()) {
// Serial.println(brain.readErrors());
// Serial.println(brain.readCSV());
//}
}

1
arduino/arduino.ino Normal file
View File

@ -0,0 +1 @@
// I only exist to prevent Vscodium from complaining

View File

@ -0,0 +1,231 @@
/*
Originally developed by Smouldery and Mikey who very kindly allowed us the use of their code.
Link to Smoulderys original code: https://github.com/smouldery/shock-collar-control/blob/master/Arduino%20Modules/transmitter_vars.ino
adapted by Deviant Designs
Link to Deviant Design work: http://deviant-designs.co.uk/2019/03/29/arduino-controlled-shock-collar/
some timing changes to match the new RF protocol by DpMartee
Adapted to accept commands over UDP by timothyhay
Packet buffer accepts commands in the following format:
0 0 000
| | |
| | collar_power
| |
| mode
|
channel
*/
#include <ESP8266WiFi.h>
#include <WiFiUdp.h>
const char* SSID = "STN";
const char* pass = "88bb6b7054";
unsigned int port = 4120;
char incomingPacket[5]; // Packet buffer.
// The following have a increased length to allow for adding an null terminator to the end.
char activePower[4]; // Power level buffer
char activeChannel[2]; // Channel buffer
char activeMode[2]; // Mode buffer
WiFiUDP Udp;
//=================================================== START OF COLLAR SETUP CODE ======================================================================
//const int shock_min = 0; // Minimum of power a command will be executed at
const int shock_delay = 10; // Maximum rate at which the shock function can be used at
//const int cmd_max = 1000; // Maximum of milliseconds which a command can be executed at
// Constant variables
const int pin_led = LED_BUILTIN; // Pin for indication LED
const int pin_rtx = D2; // Pin to transmit over
const String key = "00101100101001010"; // Key of the transmitter, dont touch if you dont know how it works
// Variables which do change
int collar_chan = 0; // Can be channel 0 or 1. Can be set over UDP.
int collar_duration = 500; // Duration of the command in milliseconds. Seems to be useless.
int collar_power = 10; // Strength of the command, can be 0-100, but will be limited by shock_min and shock_max. Can be set over UDP
int collar_mode = 3; // See below
// Define values for easier recognition
#define COLLAR_LED 1
#define COLLAR_BEEP 2
#define COLLAR_VIB 3
#define COLLAR_ZAP 4
// Strings used for building up the command sequence
String sequence, power, channelnorm, channelinv, modenorm, modeinv;
// Store the last time anything was transmitted to the collar
unsigned long transmit_last = 0;
unsigned long shock_last = 0;
void transmit_command(int c, int m, int p = 0)
{
transmit_last = millis();
switch (c) // Check the channel
{
case 1: // Channel 1
channelnorm = "111";
channelinv = "000";
break;
default: // Channel 0
channelnorm = "000";
channelinv = "111";
break;
}
switch (m) // Check the mode
{
case 1: // Light
modenorm = "1000";
modeinv = "1110";
break;
case 2: // Beep
modenorm = "0100";
modeinv = "1101";
break;
case 4: // Shock
modenorm = "0001";
modeinv = "0111";
shock_last = millis();
break;
default: // Vibrate
modenorm = "0010";
modeinv = "1011";
// p = 10; // Set strengh to 10 for the command to be executed properly
break;
}
// Convert power to binary
int zeros = String(p, BIN).length();
String power;
for (int i = 0; i < 7 - zeros; i++)
{
power = power + "0";
}
power = power + String(p, BIN);
String sequence = "1" + channelnorm + modenorm + key + power + modeinv + channelinv + "00";
digitalWrite(pin_led, LOW);
// d = constrain(d, 50, cmd_max); // Clamp duration of the command
unsigned long cmd_start = millis();
// while (millis() - cmd_start < d)
// {
// start bit
digitalWrite(pin_rtx, HIGH);
delayMicroseconds(400); // chnged to new protocol
digitalWrite(pin_rtx, LOW);
delayMicroseconds(750);// wait 750 uS
for (int n = 0; n < 41 ; n++)
{
if (sequence.charAt(n) == '1') // Transmit a one
{
digitalWrite(pin_rtx, HIGH);
delayMicroseconds(200); // chnged to new protocol
digitalWrite(pin_rtx, LOW);
delayMicroseconds(1500); // chnged to new protocol
}
else // Transmit a zero
{
digitalWrite(pin_rtx, HIGH);
delayMicroseconds(200); // chnged to new protocol
digitalWrite(pin_rtx, LOW);
delayMicroseconds(750); // chnged to new protocol
}
}
delayMicroseconds(9000); // chnged to new protocol
// }
digitalWrite(pin_led, HIGH);
}
void collar_keepalive()
{
if (millis() - transmit_last >= 120000) // Send command to the collar at least every 2 minutes to make it stay on
{
Serial.println("Keep-alive:\tCollar");
transmit_command(collar_chan, COLLAR_LED, 50);
}
}
//=================================================== END OF COLLAR SETUP CODE ======================================================================
void setup()
{
//=================================================== START OF COLLAR SETUP CODE ======================================================================
pinMode(pin_rtx, OUTPUT); // Set transmitter pin as output
pinMode(pin_led, OUTPUT); // Set LED pin as output
Serial.begin(115200);
//=================================================== END OF COLLAR SETUP CODE ======================================================================
Serial.printf("Connecting to %s", SSID);
digitalWrite(LED_BUILTIN, LOW);
WiFi.begin(SSID, pass);
while (WiFi.status() != WL_CONNECTED)
{
delay(500);
Serial.print(".");
}
Serial.println("connected.");
for (int i = 0; i <= 8; i++) {
digitalWrite(LED_BUILTIN, HIGH);
delay(35);
digitalWrite(LED_BUILTIN, LOW);
delay(35);
}
Udp.begin(port);
Serial.printf("Running at IP %s, UDP port %d - listening.\n", WiFi.localIP().toString().c_str(), port);
digitalWrite(LED_BUILTIN, HIGH);
}
void loop()
{
collar_keepalive();
int packetSize = Udp.parsePacket();
if (packetSize) {
int len = Udp.read(incomingPacket, 9);
if (len > 0) {
incomingPacket[len] = '\0';
}
Serial.println("Got packet. Packet received:");
Serial.println(incomingPacket);
for (int i = 0; i <= 3; i++) { // Visually indicate received packet
digitalWrite(LED_BUILTIN, HIGH);
delay(20);
digitalWrite(LED_BUILTIN, LOW);
delay(20);
}
activeChannel[0] = incomingPacket[0];
activeChannel[1] = '\0';
activeMode[0] = incomingPacket[1];
activeMode[1] = '\0';
activePower[0] = incomingPacket[2];
activePower[1] = incomingPacket[3];
activePower[2] = incomingPacket[4];
activePower[3] = '\0';
Serial.print("collar_chan: ");
Serial.println(atoi(activeChannel));
Serial.print("collar_mode: ");
Serial.println(atoi(activeMode));
Serial.print("activePower: ");
Serial.println(atoi(activePower));
transmit_command(atoi(activeChannel), atoi(activeMode), atoi(activePower));
transmit_command(atoi(activeChannel), atoi(activeMode), atoi(activePower));
// if (digitalRead(buttonPin) == LOW) {
// transmit_command(collar_chan, COLLAR_VIB, 100);
// }
}
}

View File

@ -0,0 +1,241 @@
/*
This file is depreceated in favor of collar_rf
I wish I didn't spend so much time trying to reverse engineer the collar I had on hand lol
*/
#include <ESP8266WiFi.h> // This really needs cleaning
#include <WiFiUdp.h>
const char* SSID = "SSID";
const char* pass = "PASS";
unsigned int port = 4120;
char incomingPacket[4]; //Packet buffer size.
WiFiUDP Udp;
// DEBUGGING PURPOSES
int beepDat[] = {1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 1, 1, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 1, 0, 1, 0, 0, 1, 0, 0, 0, 1, 1, 0, 0, 0, 1, 0, 0, 1, 0, 1, 1, 0, 1, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 1, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0}; //Temporary! Ideally, these can be gen on the fly.
int sizeBeepDat = sizeof(beepDat) / sizeof(beepDat[0]);
int shockLvl4[] = { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 1, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 1, 0, 0, 1, 1, 0, 1, 1, 0, 1, 1, 0, 1, 0, 0, 0, 1, 1, 0, 1, 0, 0, 1, 0, 0, 0, 1, 1, 0, 0, 1, 1, 0, 1, 1, 0, 0, 1, 1, 0, 1, 1, 0, 1, 1, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 1, 0, 1, 0, 0, 1, 0, 0, 0, 1, 1, 0, 1, 0, 0, 0, 1, 1, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0 };
int sizeShockLvl4 = sizeof(shockLvl4) / sizeof(shockLvl4[0]);
// 6 TIER
int shock[] = { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 0, 1, 0, 1, 1, 0, 1, 1, 0, 1, 1, 0, 0, 1, 1, 0, 1, 1, 0, 1, 1, 0, 0, 1, 1, 0, 0, 0, 1, 0, 1, 1, 0, 0, 0, 1, 0, 0, 1, 0, 1, 1, 0, 1, 1, 0, 1, 1, 0, 1, 0, 0, 1, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 1, 1, 0, 1, 0, 0, 0, 1, 1, 0, 1, 0, 0, 0, 1, 0, 1, 0, 1, 0, 1, 0 };
int sizeShock = sizeof(shock) / sizeof(shock[0]);
int kiloShock[] = { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 0, 1, 0, 1, 1, 0, 1, 1, 0, 1, 1, 0, 0, 1, 1, 0, 1, 1, 0, 1, 1, 0, 0, 1, 1, 0, 0, 0, 1, 0, 1, 1, 0, 0, 0, 1, 0, 0, 1, 0, 1, 1, 0, 1, 1, 0, 1, 1, 0, 1, 0, 0, 1, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 1, 1, 0, 1, 0, 0, 0, 1, 1, 0, 1, 0, 0, 1, 0, 0, 0, 1, 0, 0, 1, 0, 1, 0 };
int sizeKiloShock = sizeof(kiloShock) / sizeof(kiloShock[0]);
int megaShock[] = { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 0, 1, 0, 1, 1, 0, 1, 1, 0, 1, 1, 0, 0, 1, 1, 0, 1, 1, 0, 1, 1, 0, 0, 1, 1, 0, 0, 0, 1, 0, 1, 1, 0, 0, 0, 1, 0, 0, 1, 0, 1, 1, 0, 1, 1, 0, 1, 1, 0, 1, 0, 0, 1, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 1, 1, 0, 1, 0, 0, 0, 1, 1, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 1, 0, 1, 0 };
int sizeMegaShock = sizeof(megaShock) / sizeof(megaShock[0]);
int gigaShock[] = { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 0, 1, 0, 1, 1, 0, 1, 1, 0, 1, 1, 0, 0, 1, 1, 0, 1, 1, 0, 1, 1, 0, 0, 1, 1, 0, 0, 0, 1, 0, 1, 1, 0, 0, 0, 1, 0, 0, 1, 0, 1, 1, 0, 1, 1, 0, 1, 1, 0, 1, 0, 0, 1, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 1, 1, 0, 1, 0, 0, 0, 1, 0, 1, 0, 1, 0, 0, 1, 0, 0, 0, 1, 0, 0, 1, 0, 1, 0 };
int sizeGigaShock = sizeof(gigaShock) / sizeof(gigaShock[0]);
int teraShock[] = { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 0, 1, 0, 1, 1, 0, 1, 1, 0, 1, 1, 0, 0, 1, 1, 0, 1, 1, 0, 1, 1, 0, 0, 1, 1, 0, 0, 0, 1, 0, 1, 1, 0, 0, 0, 1, 0, 0, 1, 0, 1, 1, 0, 1, 1, 0, 1, 1, 0, 1, 0, 0, 1, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 1, 0, 1, 0, 1, 0, 0, 1, 0, 0, 0, 1, 0, 0, 1, 0, 1, 0 };
int sizeTeraShock = sizeof(teraShock) / sizeof(teraShock[0]);
int petaShock[] = { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 0, 1, 0, 1, 1, 0, 1, 1, 0, 1, 1, 0, 0, 1, 1, 0, 1, 1, 0, 1, 1, 0, 0, 1, 1, 0, 0, 0, 1, 0, 1, 1, 0, 0, 0, 1, 0, 0, 1, 0, 1, 1, 0, 1, 1, 0, 1, 1, 0, 1, 0, 0, 1, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 1, 1, 0, 1, 0, 0, 0, 1, 1, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 1, 0, };
int sizePetaShock = sizeof(petaShock) / sizeof(petaShock[0]);
int incomingByte = 0;
#define COLLAR_IN_PIN D2
// #define LED_BUILTIN 2 // ESP32
void triggerOn(int* dat, int size, int wait = 270) {
// digitalWrite(LED_BUILTIN, HIGH);
// int32_t btime, etime;
// btime = asm_ccount();
for (int i = 0; i < 500; i++) {
digitalWrite(COLLAR_IN_PIN, random(2)); // Generate either 0 or 1
delayMicroseconds(270);
}
for (int i = 0; i < size; i++) {
//Serial.print(dat[i]);
digitalWrite(COLLAR_IN_PIN, dat[i]);
// if (dat[i] == 1) {
// GPOS = (1 << COLLAR_IN_PIN);
// } else {
// GPOC = (1 << COLLAR_IN_PIN);
// }
// delayMicroseconds(wait-((uint32_t)(etime - btime)/80000));
delayMicroseconds(wait);
}
// etime = asm_ccount();
// Serial.println((uint32_t)(etime - btime));
digitalWrite(COLLAR_IN_PIN, 0); // Set data pin to low after sequence, collar expects this.
// digitalWrite(LED_BUILTIN, LOW);
for (int i = 0; i < 500; i++) {
digitalWrite(COLLAR_IN_PIN, random(2)); // Generate either 0 or 1
delayMicroseconds(270);
}
}
static inline int32_t asm_ccount(void) {
int32_t r;
asm volatile ("rsr %0, ccount" : "=r"(r));
return r;
}
static uint32_t
__measure(void (*callback)()) {
int32_t btime, etime;
btime = asm_ccount();
callback();
etime = asm_ccount();
return ((uint32_t)(etime - btime));
}
void setup() {
Serial.begin(115200);
pinMode(COLLAR_IN_PIN, OUTPUT);
pinMode(LED_BUILTIN, OUTPUT);
digitalWrite(LED_BUILTIN, HIGH);
// // wakey wakey, here's some garbage data!
// Serial.println("Feeding garbage to awake device");
// for (int i = 0; i < 8000; i++) {
// digitalWrite(COLLAR_IN_PIN, random(2)); // Generate either 0 or 1
// delayMicroseconds(270);
// }
// Serial.println("Finished feeding garbage, ready for input.");
Serial.printf("Connecting to %s", SSID);
digitalWrite(LED_BUILTIN, LOW);
WiFi.begin(SSID, pass);
while (WiFi.status() != WL_CONNECTED)
{
delay(500);
Serial.print(".");
}
Serial.println("connected.");
for (int i = 0; i <= 8; i++) {
digitalWrite(LED_BUILTIN, HIGH);
delay(35);
digitalWrite(LED_BUILTIN, LOW);
delay(35);
}
Udp.begin(port);
Serial.printf("Running at IP %s, UDP port %d - listening.\n", WiFi.localIP().toString().c_str(), port);
digitalWrite(LED_BUILTIN, HIGH);
}
void loop() {
int packetSize = Udp.parsePacket();
if (Serial.available() > 0) { // Used for debugging.
Serial.println("Got serial input.");
// for (int i = 0; i <= 3; i++) { // Visually indicate received packet
// digitalWrite(LED_BUILTIN, HIGH);
// delay(20);
// digitalWrite(LED_BUILTIN, LOW);
// delay(20);
// }
incomingByte = Serial.read() - '0';
digitalWrite(COLLAR_IN_PIN, incomingByte);
if (incomingByte == 1) {
digitalWrite(COLLAR_IN_PIN, HIGH);
}
if (incomingByte == 0) {
digitalWrite(COLLAR_IN_PIN, LOW);
}
if (incomingByte == 2 ) {
Serial.println("Running triggerOn");
triggerOn(shockLvl4, sizeShockLvl4);
}
if (incomingByte == 3) {
Serial.println("Feeding 5 kbits of garbage");
for (int i = 0; i < 5000; i++) {
digitalWrite(COLLAR_IN_PIN, random(2)); // Generate either 0 or 1
delayMicroseconds(270);
}
Serial.println("Finished feeding garbage");
}
if (incomingByte == 4) {
triggerOn(shock, sizeShock);
}
if (incomingByte == 5) {
triggerOn(kiloShock, sizeKiloShock);
}
if (incomingByte == 6) {
triggerOn(megaShock, sizeMegaShock);
}
if (incomingByte == 7) {
triggerOn(gigaShock, sizeGigaShock);
}
if (incomingByte == 8) {
triggerOn(teraShock, sizeTeraShock);
}
if (incomingByte == 9) {
triggerOn(petaShock, sizePetaShock);
}
delayMicroseconds(270);
} else if (packetSize) {
int len = Udp.read(incomingPacket, 4);
if (len > 0)
{
incomingPacket[len] = '\0';
}
// Serial.println("Got packet. Packet received:");
Serial.println(incomingPacket);
for (int i = 0; i <= 3; i++) { // Visually indicate received packet
digitalWrite(LED_BUILTIN, HIGH);
delay(20);
digitalWrite(LED_BUILTIN, LOW);
delay(20);
}
if (incomingPacket[0] == '1') {
Serial.println("Beep received. Injecting beep...");
triggerOn(beepDat, sizeBeepDat);
} else if (incomingPacket[0] == '0') {
Serial.println("Shock received, injecting shock at specified power...");
if (incomingPacket[1] == '1') {
// Serial.println("Injecting shock at power 1!");
// Serial.println(__measure(triggerOn(shock, sizeShock));
// __measure(triggerOn(shock, sizeShock);
// int32_t btime, etime;
// btime = asm_ccount();
triggerOn(shock, sizeShock);
triggerOn(shock, sizeShock);
triggerOn(shock, sizeShock);
// for (int i = 0; i < 500; i++) {
// digitalWrite(COLLAR_IN_PIN, random(2)); // Generate either 0 or 1
// delayMicroseconds(270);
// }
// triggerOn(shock, sizeShock);
// etime = asm_ccount();
// Serial.println((uint32_t)(etime - btime));
} else if (incomingPacket[1] == '2') {
Serial.println("Injecting shock at power 2!");
triggerOn(kiloShock, sizeKiloShock);
triggerOn(kiloShock, sizeKiloShock);
triggerOn(kiloShock, sizeKiloShock);
} else if (incomingPacket[1] == '3') {
Serial.println("Injecting shock at power 3!");
triggerOn(megaShock, sizeMegaShock);
triggerOn(megaShock, sizeMegaShock);
triggerOn(megaShock, sizeMegaShock);
} else if (incomingPacket[1] == '4') {
Serial.println("Injecting shock at power 4!");
triggerOn(gigaShock, sizeGigaShock);
triggerOn(gigaShock, sizeGigaShock);
triggerOn(gigaShock, sizeGigaShock);
} else if (incomingPacket[1] == '5') {
Serial.println("Injecting shock at power 5!");
triggerOn(teraShock, sizeTeraShock);
triggerOn(teraShock, sizeTeraShock);
triggerOn(teraShock, sizeTeraShock);
} else if (incomingPacket[1] == '6') {
Serial.println("Injecting shock at power 6!");
triggerOn(petaShock, sizePetaShock);
triggerOn(petaShock, sizePetaShock);
triggerOn(petaShock, sizePetaShock);
}
}
} else {
delayMicroseconds(270);
digitalWrite(COLLAR_IN_PIN, random(2)); // Feed garbage when not receiving input
}
}

150
arduino/main/main.ino Normal file
View File

@ -0,0 +1,150 @@
#include <WiFi.h>
#include <WiFiUdp.h>
const char* SSID = "SSID";
const char* pass = "PASS";
unsigned int port = 4120;
char incomingPacket[4]; //Packet buffer size.
WiFiUDP Udp;
int beepDat[] = {1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 1, 1, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 1, 0, 1, 0, 0, 1, 0, 0, 0, 1, 1, 0, 0, 0, 1, 0, 0, 1, 0, 1, 1, 0, 1, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 1, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0}; //Temporary! Ideally, these can be gen on the fly.
int sizeBeepDat = sizeof(beepDat) / sizeof(beepDat[0]);
// 6 TIER
int shock[] = { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 0, 1, 0, 1, 1, 0, 1, 1, 0, 1, 1, 0, 0, 1, 1, 0, 1, 1, 0, 1, 1, 0, 0, 1, 1, 0, 0, 0, 1, 0, 1, 1, 0, 0, 0, 1, 0, 0, 1, 0, 1, 1, 0, 1, 1, 0, 1, 1, 0, 1, 0, 0, 1, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 1, 1, 0, 1, 0, 0, 0, 1, 1, 0, 1, 0, 0, 0, 1, 0, 1, 0, 1, 0, 1, 0 };
int sizeShock = sizeof(shock) / sizeof(shock[0]);
int kiloShock[] = { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 0, 1, 0, 1, 1, 0, 1, 1, 0, 1, 1, 0, 0, 1, 1, 0, 1, 1, 0, 1, 1, 0, 0, 1, 1, 0, 0, 0, 1, 0, 1, 1, 0, 0, 0, 1, 0, 0, 1, 0, 1, 1, 0, 1, 1, 0, 1, 1, 0, 1, 0, 0, 1, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 1, 1, 0, 1, 0, 0, 0, 1, 1, 0, 1, 0, 0, 1, 0, 0, 0, 1, 0, 0, 1, 0, 1, 0 };
int sizeKiloShock = sizeof(kiloShock) / sizeof(kiloShock[0]);
int megaShock[] = { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 0, 1, 0, 1, 1, 0, 1, 1, 0, 1, 1, 0, 0, 1, 1, 0, 1, 1, 0, 1, 1, 0, 0, 1, 1, 0, 0, 0, 1, 0, 1, 1, 0, 0, 0, 1, 0, 0, 1, 0, 1, 1, 0, 1, 1, 0, 1, 1, 0, 1, 0, 0, 1, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 1, 1, 0, 1, 0, 0, 0, 1, 1, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 1, 0, 1, 0 };
int sizeMegaShock = sizeof(megaShock) / sizeof(megaShock[0]);
int gigaShock[] = { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 0, 1, 0, 1, 1, 0, 1, 1, 0, 1, 1, 0, 0, 1, 1, 0, 1, 1, 0, 1, 1, 0, 0, 1, 1, 0, 0, 0, 1, 0, 1, 1, 0, 0, 0, 1, 0, 0, 1, 0, 1, 1, 0, 1, 1, 0, 1, 1, 0, 1, 0, 0, 1, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 1, 1, 0, 1, 0, 0, 0, 1, 0, 1, 0, 1, 0, 0, 1, 0, 0, 0, 1, 0, 0, 1, 0, 1, 0 };
int sizeGigaShock = sizeof(gigaShock) / sizeof(gigaShock[0]);
int teraShock[] = { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 0, 1, 0, 1, 1, 0, 1, 1, 0, 1, 1, 0, 0, 1, 1, 0, 1, 1, 0, 1, 1, 0, 0, 1, 1, 0, 0, 0, 1, 0, 1, 1, 0, 0, 0, 1, 0, 0, 1, 0, 1, 1, 0, 1, 1, 0, 1, 1, 0, 1, 0, 0, 1, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 1, 0, 1, 0, 1, 0, 0, 1, 0, 0, 0, 1, 0, 0, 1, 0, 1, 0 };
int sizeTeraShock = sizeof(teraShock) / sizeof(teraShock[0]);
int petaShock[] = { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 0, 1, 0, 1, 1, 0, 1, 1, 0, 1, 1, 0, 0, 1, 1, 0, 1, 1, 0, 1, 1, 0, 0, 1, 1, 0, 0, 0, 1, 0, 1, 1, 0, 0, 0, 1, 0, 0, 1, 0, 1, 1, 0, 1, 1, 0, 1, 1, 0, 1, 0, 0, 1, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 1, 1, 0, 1, 0, 0, 0, 1, 1, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 1, 0, };
int sizePetaShock = sizeof(petaShock) / sizeof(petaShock[0]);
#define COLLAR_IN_PIN 23
#define LED_BUILTIN 2
void setup() {
Serial.begin(9600);
pinMode(COLLAR_IN_PIN, OUTPUT);
pinMode(LED_BUILTIN, OUTPUT);
digitalWrite(LED_BUILTIN, HIGH);
Serial.printf("Connecting to %s", SSID);
WiFi.begin(SSID, pass);
while (WiFi.status() != WL_CONNECTED)
{
delay(500);
Serial.print(".");
}
Serial.println("connected.");
for (int i = 0; i <= 8; i++) {
digitalWrite(LED_BUILTIN, HIGH);
delay(35);
digitalWrite(LED_BUILTIN, LOW);
delay(35);
}
Udp.begin(port);
Serial.printf("Running at IP %s, UDP port %d - listening.\n", WiFi.localIP().toString().c_str(), port);
}
void triggerOn(int* dat, int size, int wait = 270) {
Serial.println("Injecting data!");
// int32_t btime, etime;
for (int i = 0; i < size; i++) {
//Serial.print(dat[i]);
// btime = asm_ccount();
digitalWrite(COLLAR_IN_PIN, dat[i]);
// if (dat[i] == 1) {
// GPOS = (1 << COLLAR_IN_PIN);
// } else {
// GPOC = (1 << COLLAR_IN_PIN);
// }
// etime = asm_ccount();
// Serial.println((uint32_t)(etime - btime));
// delayMicroseconds(wait-((uint32_t)(etime - btime)/80000));
delayMicroseconds(wait);
}
digitalWrite(COLLAR_IN_PIN, 0); // Set data pin to low after sequence, collar expects this.
}
static inline int32_t asm_ccount(void) {
int32_t r;
asm volatile ("rsr %0, ccount" : "=r"(r));
return r;
}
static uint32_t
__measure(void (*callback)()) {
int32_t btime, etime;
btime = asm_ccount();
callback();
etime = asm_ccount();
return ((uint32_t)(etime - btime));
}
void loop() {
int packetSize = Udp.parsePacket();
if (packetSize) {
int len = Udp.read(incomingPacket, 4);
if (len > 0)
{
incomingPacket[len] = '\0';
}
Serial.println("Got packet. Packet received:");
Serial.println(incomingPacket);
for (int i = 0; i <= 3; i++) {
digitalWrite(LED_BUILTIN, HIGH);
delay(20);
digitalWrite(LED_BUILTIN, LOW);
delay(20);
}
if (incomingPacket[0] == '1') {
Serial.println("Beep received. Injecting beep...");
triggerOn(beepDat, sizeBeepDat);
} else if (incomingPacket[0] == '0') {
// Serial.println("Shock received, injecting shock at specified power...");
if (incomingPacket[1] == '1') {
Serial.println("Injecting shock at power 1!");
// Serial.println(__measure(triggerOn(shock, sizeShock));
// __measure(triggerOn(shock, sizeShock);
// int32_t btime, etime;
// btime = asm_ccount();
triggerOn(shock, sizeShock);
// etime = asm_ccount();
// Serial.println((uint32_t)(etime - btime));
} else if (incomingPacket[1] == '2') {
Serial.println("Injecting shock at power 2!");
triggerOn(kiloShock, sizeKiloShock);
} else if (incomingPacket[1] == '3') {
Serial.println("Injecting shock at power 3!");
triggerOn(megaShock, sizeMegaShock);
} else if (incomingPacket[1] == '4') {
Serial.println("Injecting shock at power 4!");
triggerOn(gigaShock, sizeGigaShock);
} else if (incomingPacket[1] == '5') {
Serial.println("Injecting shock at power 5!");
triggerOn(teraShock, sizeTeraShock);
} else if (incomingPacket[1] == '6') {
Serial.println("Injecting shock at power 6!");
triggerOn(petaShock, sizePetaShock);
}
}
} else {
delayMicroseconds(270);
digitalWrite(COLLAR_IN_PIN, random(2)); // Feed collar garbage while not sending command
}
}

View File

@ -0,0 +1,6 @@
bitstream = input("Enter your bitstream")
bitstream = [*bitstream]
#print(bitstream)
for i in range(len(bitstream)):
print(bitstream[i]+", ", end="")
print(len(bitstream))

View File

@ -0,0 +1,8 @@
bitstream = "1111111111111111000000000000000100100011000100100010010010010001000110100100011000100101101100010001001001001001011000100010010010010010010010"
bitstream = [*bitstream]
#print(bitstream)
for i in range(len(bitstream)):
if bitstream[i] == "0":
print("digitalWrite(COLLAR_IN_PIN, 0);\ndelayMicroseconds(270);")
elif bitstream[i] == "1":
print("digitalWrite(COLLAR_IN_PIN, 1);\ndelayMicroseconds(270);")

32700
data.final.day.one Normal file

File diff suppressed because it is too large Load Diff

73
headset.py Normal file
View File

@ -0,0 +1,73 @@
import socket
import select
from simpleLog import log
def main(host, port, outFile, event, exitAll):
log("Headset: Going to talk to "+str(host)+":"+str(port))
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
sock.setblocking(False)
sock.sendto("START".encode(), (host, port))
f = open(outFile, "w")
f.close()
f = open(outFile, "a")
i = 0
while True:
if exitAll.is_set():
log("headset exiting prematurely.")
exit(0)
break
ready = select.select([sock], [], [], 3)
if (ready[0]):
# log("Data is ready!")
i += 1
data, addr = sock.recvfrom(512)
data = data.decode("utf-8")
sock.sendto("ACK".encode(), (host, port))
if i == 1:
log("Headset: Writing header and 0's to set baseline")
f.write("index,strength,attention,meditation,delta,theta,low_alpha,high_alpha,low_beta,high_beta,low_gamma,high_gamma\n")
f.write("0,0,0,0,0,0,0,0,0,0,0,0\n")
f.write(str(i)+","+data+"\n")
f.flush()
log("Headset: Writing packet and unblocking threads")
event.set() # Unblocks all other threads
elif i != 0:
if exitAll.is_set():
log("headset exiting prematurely.")
exit(0)
break
log("Waiting for data timed out! Re-sending START packet.")
sock.sendto("START".encode(), (host, port))
# strength, attention, meditation, delta, theta, low_alpha, high_alpha, low_beta, high_beta, low_gamma, high_gamma = data.split(",") #signal strength, attention, meditation, delta, theta, low alpha, high alpha, low beta, high beta, low gamma, high gamma
'''
strength = brain[0] # 0 good 200 bad
attention = brain[1] # proprietary "attention"
meditation = brain[2] # proprietary "meditation"
delta = brain[3] # sleep
theta = brain[4] # relaxed, meditative
low_alpha = brain[5] # eyes closed, relaxed
high_alpha = brain[6] # "wakeful relaxation, less depression and anxiety"
low_beta = brain[7] # alert, focused
high_beta = brain[8] # "significant stress, anxiety, paranoia"
low_gamma = brain[9] # multi-sensory processing
high_gamma = brain[10] # "happier, more receptive"
'''
'''
log("\n"*50)
if int(strength) != 0:
log("Signal strength is not ideal; "+strength)
log("Strength: "+strength)
log("Attention: " + attention)
log("Meditation: " + meditation)
log("Delta: " + delta)
log("Theta: " + theta)
log("Low Alpha: " + low_alpha)
log("High Alpha: " + high_alpha)
log("Low Beta: " + low_beta)
log("High Beta: " + high_beta)
log("Low Gamma: " + low_gamma)
log("High Gamma: " + high_gamma)
'''

262
main.py Normal file
View File

@ -0,0 +1,262 @@
headsetHost = "192.168.86.77"
headsetPort = 4120
collarHost = "192.168.12.150" # Note that headset packets require a response from server, but collar packets are just sent out
# RPI is 192.168.12.230
collarPort = 4120
outFile = "data"
optionFile = "options" # All variables between flask and main must be done via files. Also allows Unity to get data and options.
from headset import main as headsetLoop
from animate_graph import graph
from animate_bar import bar
from simpleLog import log
from utils.gen_data import genData
import socket
import threading
import time
import subprocess
from multiprocessing import Process
import multiprocessing
from flask import Flask, render_template, jsonify, request, redirect
import csv
punishAttention = 1 # Punish attention if 0: Don't punish, 1: If it goes above the threshold, 2: If it goes below the threshold
punishMeditation = 0
threshold = 210 # By default set to an impossible value so nobody gets hurt during setup
channel = "1" # Collar channel
mode = "4" # 1: LED, 2: BEEP, 3: VIBRATE, 4: ZAP
timeout = 5 # Punishment timeout in seconds
severityDivider = 2 # Divide amount away from threshold by this value
animWith = 2 # 0: graph, 1: bar, 2: web (also enables controls)
eStop = False # When set to true, no outbound packets are sent
fakeData = False # If I should generate fake data. Used for debugging.
debug = True # Log bugLog?
written = threading.Event() # Allows blocking until new data is written
exitAll = threading.Event() # Exit.
initialWritten = multiprocessing.Event()
log("WARNING: SHOCK IS CURRENTLY OVERRIDED AT LEVEL 100!!!", "e") # remove later
def sendCollar(host, port, command):
global eStop
if eStop:
log("EStop is enabled! I cannot send packets until you restart the program", "e")
else:
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
sock.sendto(command.encode(), (host, port))
def read_csv(filename):
data = []
with open(filename, 'r') as file:
csv_reader = csv.DictReader(file)
for row in csv_reader:
data.append(row)
return data
def rwOptions(write=False, threshold=0, punishAttention=0, punishMeditation=0, punishWith=3, wantOption=0): # Option 0 is threshold, 1 is punishAttention, 2 is punishMeditation, 3 is punishWith
if write == False:
# bugLog("Options are being read from!")
options = open(optionFile, 'r')
if wantOption == 0:
return(options.read().split(",")[0])
elif wantOption == 1:
return(options.read().split(",")[1])
elif wantOption == 2:
return(options.read().split(",")[2])
elif wantOption == 3:
return(options.read().split(",")[3])
elif write:
bugLog("Options are being written to!")
options = open(optionFile, 'w')
options.write(str(threshold)+","+str(punishAttention)+","+str(punishMeditation)+","+str(punishWith))
options.flush()
options.close()
def bugLog(message, level="i"):
global debug
if debug:
log(message, level, "DEBUG")
headsetThread = threading.Thread(target=headsetLoop, args=(headsetHost, headsetPort, outFile, written, exitAll), daemon=True)
headsetThread.start()
rwOptions(True, threshold, punishAttention, punishMeditation, mode)
log("\n\nHello Open Sauce!!! Begin!\n\n")
if fakeData:
log("Starting thread to genearate fake data!", "w")
threading.Thread(target=genData, args=(outFile,), daemon=True).start()
if animWith == 0:
#graphThread = threading.Thread(target=graph, args=(outFile, written, exitAll), daemon=True).start()
graphProc = Process(target=graph, args=(outFile, initialWritten))
graphProc.start()
elif animWith == 1:
graphProc = Process(target=bar, args=(outFile, initialWritten))
graphProc.start()
elif animWith == 2:
log("Starting web interface")
app = Flask(__name__)
@app.route('/')
def index():
return render_template('index.html')
@app.route('/graph')
def graph():
return render_template('graph.html')
@app.route('/play')
def play():
threshold = rwOptions(wantOption=0)
if punishMeditation != 0:
# log("Setting meditation threshold to "+str(threshold))
data = {'threshold': threshold}
elif punishAttention != 0:
# log("Setting meditation threshold to "+str(threshold))
data = {'threshold': threshold}
print(data)
return render_template('play.html', data=data)
@app.route('/open-sussy') # Seperate route because I plan to add more mode specific stuff later (LED stuff)
def open_sussy():
threshold = rwOptions(wantOption=0)
if punishMeditation != 0:
# log("Setting meditation threshold to "+str(threshold))
data = {'threshold': threshold}
elif punishAttention != 0:
# log("Setting meditation threshold to "+str(threshold))
data = {'threshold': threshold}
print(data)
return render_template('openSauce.html', data=data)
@app.route('/shock')
def shock():
level = request.args.get('power')
log("Got request to send a shock of power level " + level + "!")
sendCollar(collarHost, collarPort, channel+mode+"100")
# return 'Successfully sent shock of power level '+str(level)
return redirect('/play')
# @app.route('/restart-headset')
# def restart():
# log("Got request to restart headset unishWith
# pass
# threading.Thread(target=headsetLoop, args=(headsetHost, headsetPort, outFile, written, exitAll),
# daemon=True).start()
# exitAll.clear()
# return 'Successfully killed old headset thread and started new one'
# Route to fetch data from CSV file
@app.route('/headset-data')
def get_data():
return jsonify(read_csv(outFile))
@app.route('/stop')
def stop():
log("E-Stop hit, halting all outbound packets!", "e")
eStop = True
rwOptions(True, 500, 0, 0, 3) # Sets threshold to unreachable value, and sets activation mode to buzz
return render_template('stop.html')
@app.route("/options" , methods=['GET', 'POST'])
def options():
typePunish = request.args.get('type')
condition = request.args.get('condition')
threshold = request.args.get('threshold')
mode = request.args.get('punishment')
if typePunish == "meditation":
if condition == "above":
punishMeditation = 1
elif condition == "below":
punishMeditation = 2
punishAttention = 0
rwOptions(True, threshold, punishAttention, punishMeditation, mode)
bugLog("Setting meditation threshold to "+threshold)
elif typePunish == "attention":
if condition == "above":
punishAttention = 1
elif condition == "below":
punishAttention = 2
punishMeditation = 0
rwOptions(True, threshold, punishAttention, punishMeditation, mode)
bugLog("Setting attention threshold to "+threshold)
else:
log("Invalid data was submitted to the form!", "e")
bugLog("New options were set. punishMeditation: "+str(punishMeditation)+" punishAttention:"+str(punishAttention)+" threshold:"+str(threshold)+" mode:"+str(mode))
# return redirect('/play')
return redirect('open-sussy') # Temp for Open Sauce
webThread = threading.Thread(target=lambda: app.run(debug=True,use_reloader=False), daemon=True).start()
else:
log("No visualization method has been selected!", "w")
def main():
global written
severity = 0
written.wait() # Wait for new data
initialWritten.set() # Unblock animator
written.clear()
line = str(subprocess.check_output(['tail', '-1', '/home/jamesh/Brain/'+outFile]).decode('utf-8')).strip("\n").split(",") # TODO: Make this not stupid
threshold = int(rwOptions(wantOption=0)) # TODO: Make this not stupid and garbage
punishAttention = int(rwOptions(wantOption=1))
punishMeditation = int(rwOptions(wantOption=2))
mode = int(rwOptions(wantOption=3))
bugLog("Current settings are punishMeditation: "+str(punishMeditation)+" punishAttention:"+str(punishAttention)+" threshold:"+str(threshold)+" mode:"+str(mode))
bugLog("Got threshold - currently set to "+str(threshold))
if int(line[1]) == 0:
if punishAttention == 1 and int(line[2]) > threshold or punishAttention == 2 and int(line[2]) < threshold:
if punishAttention == 1:
log("Attention "+line[2]+" is above threshold "+str(threshold)+"!")
severity = int(line[2]) - threshold
if punishAttention == 2:
log("Attention "+line[2]+" is below threshold "+str(threshold)+"!")
severity = threshold - int(line[2])
log("Punishing attention with severity of "+str(severity)+"! Timing out for "+str(timeout)+" seconds.")
if animWith == 1 or 2:
subprocess.run(["touch", "mark"]) # Mark spot where threshold was hit. animate_graph will remove the file.
level = str(int(round((severity / severityDivider), 0)))
if int(level) == 0:
log("Severity results in level " + str(1) + " shock.")
level = "1"
else:
log("Severity results in level " + level + " shock.", "e")
sendCollar(collarHost, collarPort, str(channel) + str(mode) + "100") # 6 tier
# print(channel+mode+level)
time.sleep(timeout)
elif punishMeditation == 1 and int(line[3]) > threshold or punishMeditation == 2 and int(line[3]) < threshold:
if punishMeditation == 1:
log("Meditation "+line[3]+" is above threshold "+str(threshold)+"!")
severity = int(line[3]) - threshold
if punishMeditation == 2:
log("Meditation "+line[3]+" is below threshold "+str(threshold)+"!")
severity = threshold - int(line[3])
log("Punishing meditation with severity of "+str(severity)+"! Timing out for "+str(timeout)+" seconds.")
if animWith == 1 or 2:
subprocess.run(["touch", "mark"]) # Mark spot where threshold was hit. animate_graph will remove the file.
level = str(int(round((severity / severityDivider), 0))) # str(int(round((severity / (maxLevelOffset/6)), 0)))
if int(level) == 0:
log("Severity results in level " + str(1) + " shock.")
level = "1"
else:
log("Severity results in level " + level + " shock.", "e")
# print(channel+mode+level)
sendCollar(collarHost, collarPort, str(channel) + str(mode) + "100") # 6 tier
time.sleep(timeout)
else:
log("You are within your safe limits.")
else:
log("Strength is not ideal. I will not shock until strength reaches 0!", "w")
log("The program will wait for contact with the headset.")
try:
while True:
main()
except (KeyboardInterrupt, SystemExit):
log("Received keyboard interrupt, exiting all threads.", "e")
exitAll.set()
exit(0)

130
minecraft.py Normal file
View File

@ -0,0 +1,130 @@
collarHost = "192.168.1.47" # Note that headset packets require a response from server, but collar packets are just sent out
collarPort = 4120
from time import sleep
import socket
from simpleLog import log
import subprocess
# logPath = '/home/jamesh/.local/share/PolyMC/instances/Other 1.20.4/.minecraft/logs/latest.log'
logPath = '/home/jamesh/.local/share/PolyMC/instances/1.20.4/.minecraft/logs/latest.log'
lastLine = ""
currentHealthP1 = 0 # TODO: A better solution than this
previousHealthP1 = 20 # Assume full health on load
currentHealthP2 = 0
previousHealthP2 = 20
lowHealth = False # Custom rules for maps that change the health the player has. Detects when the health goes from 20 to another arbitrary value.
lowHealthLevel = "20" # Level of punishment delivered when player death is detected in lowHealth mode
lowHealthTrigger = 14 # Triggers punishment when this much damage is taken, so if set to 14, 20 to 6 will trigger.
p1 = "timothyhay"
p2 = "snoopyhoff"
players = 2 # How many players to use. p1 uses channel 1 by default.
channel = "1"
mode = "4" # 1: LED, 2: BEEP, 3: VIBRATE, 4: ZAP
shockMultiplier = 5
block = False # If set to true, no commands will be sent. Used for lowHealth
if mode == "4":
log("WARNING -- You are running with shocks ENABLED! -- WARNING", "w")
log("WARNING -- With a multiplier of "+str(shockMultiplier)+", the max shock level is "+str(shockMultiplier*20)+"! -- WARNING", "w")
def getLastLine(filePath):
with open(filePath, 'r') as file:
lines = file.readlines()
lastLine = lines[-1].strip() # remove newline character
return lastLine
def sendCollar(host, port, command):
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
sock.sendto(command.encode(), (host, port))
def pairCollar(): # Call me before the loop to pair collars
while True:
chan = input("CHANNEL (q to quit): ")
if chan == "q":
exit()
elif chan == "1":
log("Sending channel 1")
sendCollar(collarHost, collarPort, "1350")
elif chan == "2":
log("Sending channel 2")
sendCollar(collarHost, collarPort, "2350")
else:
log("Sending input as raw!")
sendCollar(collarHost, collarPort, str(chan))
# pairCollar()
log("I will monitor the Minecraft logfile located at "+logPath+" and fire packets at "+collarHost+":"+str(collarPort))
while True:
# sleep(.1)
# currentLine = getLastLine(logPath)
currentLine = str((subprocess.check_output(['tail', '-1', logPath])).decode('utf-8')[0:-1])
# if lastLine != currentLine:
if "~" in currentLine:
line = currentLine.split("~")
# log(line[1]) # Player name
# log(line[3]) # Player health
if line[1] == p1:
# log("fsd")
# log(currentHealthP1)
# log(previousHealthP1)
currentHealthP1 = line[3]
if currentHealthP1 != previousHealthP1:
damage = (int(currentHealthP1) - int(previousHealthP1))*-1
log(line[1]+" health: "+currentHealthP1)
if damage > 0:
log(line[1]+" damage: "+str(damage))
level = str(int(damage*shockMultiplier))
if 0 < int(level) <= 100:
if damage == lowHealthTrigger and lowHealth:
log(line[1]+" gets a level "+lowHealthLevel+" shock on channel 1.", "w")
sendCollar(collarHost, collarPort, "1"+mode+lowHealthLevel)
block = True
else:
block = False
if not block and not lowHealth:
log(line[1]+" gets a level "+level+" shock on channel 1.", "w")
sendCollar(collarHost, collarPort, "1"+mode+level)
elif line[1] == p2:
currentHealthP2 = line[3]
if currentHealthP2 != previousHealthP2:
damage = (int(currentHealthP2) - int(previousHealthP2))*-1
log(line[1]+" health: "+currentHealthP2)
if damage > 0:
log(line[1]+" damage: "+str(damage))
level = str(int(damage*shockMultiplier))
if 0 < int(level) <= 100:
if damage == lowHealthTrigger and lowHealth:
print("fds")
log(line[1]+" gets a level "+lowHealthLevel+" shock on channel 2.", "w")
sendCollar(collarHost, collarPort, "2"+mode+lowHealthLevel)
block = True
else:
block = False
if not block and not lowHealth:
print("asfed")
log(line[1]+" gets a level "+level+" shock on channel 2.", "w")
sendCollar(collarHost, collarPort, "2"+mode+level)
# currentHealth = int(currentLine.split("~")[1])
# damage = (currentHealth - previousHealth)*-1 # Get actual damage
# if currentHealth != previousHealth:
# log("Health: "+str(currentHealth))
# if damage > 0:
# log("Damage: "+str(damage)+" damage.")
# level = str(int(damage*shockMultiplier))
# if 0 < int(level) <= 100:
# log("Player gets a level "+level+" shock.")
# sendCollar(collarHost, collarPort, channel+mode+level)
else:
# log(currentLine)
pass
lastLine = currentLine
previousHealthP1 = currentHealthP1
previousHealthP2 = currentHealthP2

BIN
openSauceDisplay.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 251 KiB

0
other/__init__.py Normal file
View File

View File

@ -0,0 +1,155 @@
/*
Originally developed by Smouldery and Mikey who very kindly allowed us the use of their code.
Link to Smoulderys original code: https://github.com/smouldery/shock-collar-control/blob/master/Arduino%20Modules/transmitter_vars.ino
adapted by Deviant Designs
Link to Deviant Design work: http://deviant-designs.co.uk/2019/03/29/arduino-controlled-shock-collar/
some timing changes to match the new RF protocol by DpMartee
*/
byte buttonPin = D1;
//=================================================== START OF COLLAR SETUP CODE ======================================================================
//const int shock_min = 0; // Minimum of power a command will be executed at
const int shock_delay = 10; // Maximum rate at which the shock function can be used at
//const int cmd_max = 1000; // Maximum of milliseconds which a command can be executed at
// Constant variables
const int pin_led = LED_BUILTIN; // Pin for indication LED
const int pin_rtx = D2; // Pin to transmit over
const String key = "00101100101001010"; // Key of the transmitter, dont touch if you dont know how it works
// Variables which do change
int collar_chan = 0; // Can be channel 0 or 1
int collar_duration = 500; // Duration of the command in milliseconds
int collar_power = 10; // Strength of the command, can be 0-100, but will be limited by shock_min and shock_max
// Define values for easier recognition
#define COLLAR_LED 1
#define COLLAR_BEEP 2
#define COLLAR_VIB 3
#define COLLAR_ZAP 4
// Strings used for building up the command sequence
String sequence, power, channelnorm, channelinv, modenorm, modeinv;
// Store the last time anything was transmitted to the collar
unsigned long transmit_last = 0;
unsigned long shock_last = 0;
void transmit_command(int c, int m, int p = 0)
{
transmit_last = millis();
switch (c) // Check the channel
{
case 1: // Channel 1
channelnorm = "111";
channelinv = "000";
break;
default: // Channel 0
channelnorm = "000";
channelinv = "111";
break;
}
switch (m) // Check the mode
{
case 1: // Light
modenorm = "1000";
modeinv = "1110";
break;
case 2: // Beep
modenorm = "0100";
modeinv = "1101";
break;
case 4: // Shock
modenorm = "0001";
modeinv = "0111";
shock_last = millis();
break;
default: // Vibrate
modenorm = "0010";
modeinv = "1011";
// p = 10; // Set strengh to 10 for the command to be executed properly
break;
}
// Convert power to binary
int zeros = String(p, BIN).length();
String power;
for (int i = 0; i < 7 - zeros; i++)
{
power = power + "0";
}
power = power + String(p, BIN);
String sequence = "1" + channelnorm + modenorm + key + power + modeinv + channelinv + "00";
digitalWrite(pin_led, LOW);
// d = constrain(d, 50, cmd_max); // Clamp duration of the command
unsigned long cmd_start = millis();
// while (millis() - cmd_start < d)
// {
// start bit
digitalWrite(pin_rtx, HIGH);
delayMicroseconds(400); // chnged to new protocol
digitalWrite(pin_rtx, LOW);
delayMicroseconds(750);// wait 750 uS
for (int n = 0; n < 41 ; n++)
{
if (sequence.charAt(n) == '1') // Transmit a one
{
digitalWrite(pin_rtx, HIGH);
delayMicroseconds(200); // chnged to new protocol
digitalWrite(pin_rtx, LOW);
delayMicroseconds(1500); // chnged to new protocol
}
else // Transmit a zero
{
digitalWrite(pin_rtx, HIGH);
delayMicroseconds(200); // chnged to new protocol
digitalWrite(pin_rtx, LOW);
delayMicroseconds(750); // chnged to new protocol
}
}
delayMicroseconds(9000); // chnged to new protocol
// }
digitalWrite(pin_led, HIGH);
}
void collar_keepalive()
{
if (millis() - transmit_last >= 120000) // Send command to the collar at least every 2 minutes to make it stay on
{
Serial.println("Keep-alive:\tCollar");
transmit_command(collar_chan, COLLAR_LED, 50);
}
}
//=================================================== END OF COLLAR SETUP CODE ======================================================================
void setup()
{
//=================================================== START OF COLLAR SETUP CODE ======================================================================
pinMode(pin_rtx, OUTPUT); // Set transmitter pin as output
pinMode(pin_led, OUTPUT); // Set LED pin as output
Serial.begin(115200);
//=================================================== END OF COLLAR SETUP CODE ======================================================================
pinMode(buttonPin, INPUT_PULLUP);
}
void loop()
{
collar_keepalive();
if (digitalRead(buttonPin) == LOW) {
Serial.println("Sending command");
transmit_command(collar_chan, COLLAR_VIB, 100);
}
}

1
requirements.txt Normal file
View File

@ -0,0 +1 @@
flask

1
simpleLog.py Symbolic link
View File

@ -0,0 +1 @@
Simple-Logger/simpleLog.py

BIN
static/24.webp Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 21 KiB

BIN
static/CE3E3V2_brain.3mf Normal file

Binary file not shown.

Binary file not shown.

After

Width:  |  Height:  |  Size: 250 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.7 MiB

View File

@ -0,0 +1,212 @@
h1 {
text-align:center;
font-family: "Poppins", Sans-serif;
color: #f8f8f2
}
.box1 {
background-color: #000;
color: #fff;
opacity: .5;
}
/* html {
background-color: #282a36
} */
#main-text {
color: #f8f8f2;
width: 95%;
text-align: center;
margin-left: auto;
margin-right: auto;
margin-top: auto;
height: 88vh;
font-family: "Poppins", Sans-serif;
background-color: #44475a;
min-height:100%;
background:linear-gradient(0deg, rgb(94, 77, 47), rgba(0, 0, 0, 0.2)), url(../images/open-sussy.jpg);
border: 5px solid rgba(245, 245, 255, .5);
background-size: cover;
border-radius: 12px;
color: #f8f8f2;
box-shadow: 10px 5px 5px rgba(0, 0, 0, .3);
}
#row-0 {
display: flex;
justify-content: space-evenly;
z-index: 1;
}
#row-1 {
display: flex;
justify-content: space-evenly;
z-index: 1;
}
#controls {
display: flex;
justify-content: center;
}
ul.c-ul {
display: inline-block;
text-align: left;
}
a {
color: #ff79c6;
}
#glass {
background: rgba( 255, 255, 255, 0.25 );
box-shadow: 0 8px 32px 0 rgba( 31, 38, 135, 0.37 );
backdrop-filter: blur( 4px );
-webkit-backdrop-filter: blur( 4px );
border-radius: 10px;
border: 1px solid rgba( 255, 255, 255, 0.18 );
}
.dropbtn {
background-color: #000;
color: white;
padding: 16px;
font-size: 16px;
border: none;
}
.dropdown {
position: relative;
display: inline-block;
margin-left: 3%;
}
.dropdown-content {
display: none;
position: absolute;
background-color: #000;
min-width: 160px;
box-shadow: 0px 8px 16px 0px rgba(0,0,0,0.2);
z-index: 1;
font-family: "Poppins", Sans-serif;
border-radius: 8px;
-webkit-transition: all 0.3s ease;
-moz-transition: all 0.3s ease;
-ms-transition: all 0.3s ease;
-o-transition: all 0.3s ease;
transition: all 0.3s ease;
}
.dropdown-content a {
color: white;
padding: 12px 16px;
text-decoration: none;
display: block;
}
.dropdown-content a:hover {
background-color: #EB9822;
border-radius: 8px;
}
.dropdown:hover .dropdown-content {
display: block;
opacity: 1;
pointer-events: all;
}
.dropdown:hover .dropbtn {background-color: #EB9822;}
button {
font-family: "Poppins", Sans-serif;
background-color: #000;
border: none;
color: white;
padding: 15px 32px;
text-align: center;
text-decoration: none;
display: inline-block;
font-size: 16px;
margin: 4px 2px;
cursor: pointer;
-webkit-transition-duration: 0.4s; /* Safari */
transition-duration: 0.4s;
border-radius: 8px;
}
button:hover {
background-color: #EB9822;
color: white;
box-shadow: 0 12px 16px 0 rgba(0,0,0,0.24), 0 17px 50px 0 rgba(0,0,0,0.19);
}
input, select {
/* width: 100%; */
font-family: "Poppins", Sans-serif;
padding: 12px 20px;
height: 15%;
margin: 8px 0;
display: inline-block;
border: 0px solid #232634;
border-radius: 8px;
box-sizing: border-box;
background-color: #000;
border: none;
color: white;
padding: 15px 32px;
text-align: center;
text-decoration: none;
display: inline-block;
font-size: 17px;
margin: 4px 2px;
cursor: pointer;
box-shadow: 0;
transition: box-shadow 1s;
border-radius: 8px;
}
select option[value="attention"] {
background: #000;
border-radius: 8px;
}
select option[value="meditation"] {
background: #000;
border-radius: 8px;
}
input[type=submit] {
/* width: 100%; */
font-family: "Poppins", Sans-serif;
height: 15%;
background-color: #000;
color: white;
padding: 14px 20px;
margin: 8px 0;
border: none;
border-radius: 4px;
cursor: pointer;
}
input[type=submit]:hover {
background-color: #EB9822;
}
#control-text {
margin: 9px 0px;
font-family: "Poppins", Sans-serif;
color: #f8f8f2;
font-size: 36px;
}
#notice-text {
margin: 9px 0px;
font-family: "Poppins", Sans-serif;
color: #f8f8f2;
font-size: 20px;
}

202
static/css/style.css Normal file
View File

@ -0,0 +1,202 @@
h1 {
text-align:center;
font-family: Arial, Helvetica, sans-serif;
color: #f8f8f2
}
.box1 {
background-color: #000;
color: #fff;
opacity: .5;
}
/* html {
background-color: #282a36
} */
#main-text {
color: #f8f8f2;
width: 95%;
text-align: center;
margin-left: auto;
margin-right: auto;
margin-top: auto;
height: 88vh;
font-family: Arial, Helvetica, sans-serif;
background-color: #44475a;
min-height:100%;
background:linear-gradient(0deg, rgb(94, 77, 47), rgba(0, 0, 0, 0.2)), url(../images/open-sussy.jpg);
border: 5px solid rgba(245, 245, 255, .5);
background-size: cover;
border-radius: 12px;
color: #f8f8f2;
box-shadow: 10px 5px 5px rgba(0, 0, 0, .3);
}
#row-0 {
display: flex;
justify-content: space-evenly;
z-index: 1;
}
#row-1 {
display: flex;
justify-content: space-evenly;
z-index: 1;
}
#controls {
display: flex;
justify-content: center;
}
ul.c-ul {
display: inline-block;
text-align: left;
}
a {
color: #ff79c6;
}
#glass {
background: rgba( 255, 255, 255, 0.25 );
box-shadow: 0 8px 32px 0 rgba( 31, 38, 135, 0.37 );
backdrop-filter: blur( 4px );
-webkit-backdrop-filter: blur( 4px );
border-radius: 10px;
border: 1px solid rgba( 255, 255, 255, 0.18 );
}
.dropbtn {
background-color: #e594a4;
color: white;
padding: 16px;
font-size: 16px;
border: none;
}
.dropdown {
position: relative;
display: inline-block;
margin-left: 3%;
}
.dropdown-content {
display: none;
position: absolute;
background-color: #e594a4;
min-width: 160px;
box-shadow: 0px 8px 16px 0px rgba(0,0,0,0.2);
z-index: 1;
font-family: Arial, Helvetica, sans-serif;
border-radius: 8px;
-webkit-transition: all 0.3s ease;
-moz-transition: all 0.3s ease;
-ms-transition: all 0.3s ease;
-o-transition: all 0.3s ease;
transition: all 0.3s ease;
}
.dropdown-content a {
color: white;
padding: 12px 16px;
text-decoration: none;
display: block;
}
.dropdown-content a:hover {
background-color: #b3727f;
border-radius: 8px;
}
.dropdown:hover .dropdown-content {
display: block;
opacity: 1;
pointer-events: all;
}
.dropdown:hover .dropbtn {background-color: #b3727f;}
button {
background-color: #e594a4;
border: none;
color: white;
padding: 15px 32px;
text-align: center;
text-decoration: none;
display: inline-block;
font-size: 16px;
margin: 4px 2px;
cursor: pointer;
-webkit-transition-duration: 0.4s; /* Safari */
transition-duration: 0.4s;
border-radius: 8px;
}
button:hover {
background-color: #b3727f;
color: white;
box-shadow: 0 12px 16px 0 rgba(0,0,0,0.24), 0 17px 50px 0 rgba(0,0,0,0.19);
}
input, select {
/* width: 100%; */
padding: 12px 20px;
height: 15%;
margin: 8px 0;
display: inline-block;
border: 0px solid #232634;
border-radius: 8px;
box-sizing: border-box;
background-color: #e594a4;
border: none;
color: white;
padding: 15px 32px;
text-align: center;
text-decoration: none;
display: inline-block;
font-size: 17px;
margin: 4px 2px;
cursor: pointer;
box-shadow: 0;
transition: box-shadow 1s;
border-radius: 8px;
}
select option[value="attention"] {
background: #e594a4;
border-radius: 8px;
}
select option[value="meditation"] {
background: #e594a4;
border-radius: 8px;
}
input[type=submit] {
/* width: 100%; */
height: 15%;
background-color: #e594a4;
color: white;
padding: 14px 20px;
margin: 8px 0;
border: none;
border-radius: 4px;
cursor: pointer;
}
input[type=submit]:hover {
background-color: #b3727f;
}
#control-text {
margin: 9px 0px;
font-family: Arial, Helvetica, sans-serif;
color: #f8f8f2;
font-size: 36px;
}

Binary file not shown.

After

Width:  |  Height:  |  Size: 30 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 199 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 628 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 217 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 442 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 523 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 379 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 615 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 607 KiB

BIN
static/images/bigger.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 845 KiB

BIN
static/images/brain.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 153 KiB

BIN
static/images/fat.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.4 MiB

BIN
static/images/graph.jpg Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 247 KiB

1000
static/images/inky Normal file

File diff suppressed because it is too large Load Diff

BIN
static/images/long.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 723 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.1 MiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 444 KiB

BIN
static/images/play-page.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 144 KiB

BIN
static/images/play.jpeg Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.0 MiB

BIN
static/images/shock.jpg Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 110 KiB

BIN
static/images/slime.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 821 KiB

BIN
static/images/stop.jpg Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 250 KiB

BIN
static/images/stop.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 25 KiB

170
static/js/graph.js Normal file
View File

@ -0,0 +1,170 @@
let myChart; // Make chart global
let maxValues = 50;
const canvas = document.querySelector("canvas"); // Set correct canvas size
canvas.width = window.innerWidth
canvas.height = window.innerHeight - 50
window.addEventListener('resize', function(event) { // TODO: Fix
console.log("Resize event!");
canvas.width = window.innerWidth
canvas.height = window.innerHeight
// initialRender();
}, true);
async function fetchData() {
const response = await fetch('/headset-data');
const data = await response.json();
return data;
}
async function updateChart() {
const data = await fetchData();
const latestData = data.slice(-maxValues);
// const labels = latestData.map(item => item.index);
// const strength = latestData.map(item => item.strength);
// const attention = latestData.map(item => item.attention);
// const meditation = latestData.map(item => item.meditation);
// const delta = latestData.map(item => item.delta);
// const theta = latestData.map(item => item.theta);
// const low_alpha = latestData.map(item => item.low_alpha);
// const high_alpha = latestData.map(item => item.high_alpha);
// const low_beta = latestData.map(item => item.low_beta);
// const high_beta = latestData.map(item => item.high_beta);
// const low_gamma = latestData.map(item => item.low_gamma);
// const high_gamma = latestData.map(item => item.high_gamma);
myChart.data.labels = latestData.map(item => item.index);
myChart.data.datasets[0].data = latestData.map(item => item.strength);
myChart.data.datasets[1].data = latestData.map(item => item.attention);
myChart.data.datasets[2].data = latestData.map(item => item.meditation);
myChart.data.datasets[3].data = latestData.map(item => item.delta);
myChart.data.datasets[4].data = latestData.map(item => item.theta);
myChart.data.datasets[5].data = latestData.map(item => item.low_alpha);
myChart.data.datasets[6].data = latestData.map(item => item.high_alpha);
myChart.data.datasets[7].data = latestData.map(item => item.low_beta);
myChart.data.datasets[8].data = latestData.map(item => item.high_beta);
myChart.data.datasets[9].data = latestData.map(item => item.low_gamma);
myChart.data.datasets[10].data = latestData.map(item => item.high_gamma);
if (latestData.length >= maxValues) {
myChart.update('none'); // Prevent animations when shifting the whole chart.
} else {
myChart.update();
}
}
async function initialRender() {
const data = await fetchData();
const latestData = data.slice(-maxValues);
const labels = latestData.map(item => item.index);
const strength = latestData.map(item => item.strength);
const attention = latestData.map(item => item.attention);
const meditation = latestData.map(item => item.meditation);
const delta = latestData.map(item => item.delta);
const theta = latestData.map(item => item.theta);
const low_alpha = latestData.map(item => item.low_alpha);
const high_alpha = latestData.map(item => item.high_alpha);
const low_beta = latestData.map(item => item.low_beta);
const high_beta = latestData.map(item => item.high_beta);
const low_gamma = latestData.map(item => item.low_gamma);
const high_gamma = latestData.map(item => item.high_gamma);
const ctx = document.getElementById('myChart').getContext('2d');
myChart = new Chart(ctx, {
type: 'line',
data: {
labels: labels,
datasets: [{
label: 'Signal Strength',
data: strength,
borderWidth: 1,
borderColor: 'red',
fill: false
},{
label: 'Attention',
data: attention,
borderWidth: 1,
borderColor: 'green',
fill: false
},{
label: 'Meditation',
data: meditation,
borderWidth: 1,
borderColor: 'blue',
fill: false
},{
label: 'Delta',
data: delta,
borderWidth: 1,
borderColor: 'orange',
fill: false
},{
label: 'Theta',
data: theta,
borderWidth: 1,
borderColor: 'purple',
fill: false
},{
label: 'Low Alpha',
data: low_alpha,
borderWidth: 1,
borderColor: 'cyan',
fill: false
},{
label: 'High Alpha',
data: high_alpha,
borderWidth: 1,
borderColor: 'magenta',
fill: false
},{
label: 'Low Beta',
data: low_beta,
borderWidth: 1,
borderColor: 'yellow',
fill: false
},{
label: 'High Beta',
data: high_beta,
borderWidth: 1,
borderColor: 'black',
fill: false
},{
label: 'Low Gamma',
data: low_gamma,
borderWidth: 1,
borderColor: 'gray',
fill: false
},{
label: 'High Gamma',
data: high_gamma,
borderWidth: 1,
borderColor: 'brown',
fill: false
}]
},
options: {
scales: {
y: {
beginAtZero: true
}
}
}
});
}
function settingsPrompt() {
maxValues = prompt("How many samples should be shown at once?", "50");
if (maxValues == null || maxValues == "") {
text = "User cancelled the prompt.";
}
}
function home() {
window.location.href = "/";
}
initialRender();
setInterval(updateChart, 800);

160
static/js/open-sussy.js Normal file
View File

@ -0,0 +1,160 @@
let myChart; // Make chart global
let maxValues = 50;
const canvas = document.querySelector("canvas"); // Set correct canvas size
canvas.width = window.innerWidth - (window.innerWidth * .4)
canvas.height = window.innerHeight - (window.innerHeight * .6)
Chart.defaults.color = '#232634';
window.onresize = function(){ location.reload(); }
console.log("Current threshold is: "+threshold);
window.addEventListener('resize', function(event) { // TODO: Fix
console.log("Resize event!");
canvas.width = window.innerWidth
canvas.height = window.innerHeight
// initialRender();
}, true);
async function fetchData() {
const response = await fetch('/headset-data');
const data = await response.json();
return data;
}
async function updateChart() {
const data = await fetchData();
const latestData = data.slice(-maxValues);
// const labels = latestData.map(item => item.index);
// const strength = latestData.map(item => item.strength);
// const attention = latestData.map(item => item.attention);
const meditation = latestData.map(item => item.meditation);
// const delta = latestData.map(item => item.delta);
// const theta = latestData.map(item => item.theta);
// const low_alpha = latestData.map(item => item.low_alpha);
// const high_alpha = latestData.map(item => item.high_alpha);
// const low_beta = latestData.map(item => item.low_beta);
// const high_beta = latestData.map(item => item.high_beta);
// const low_gamma = latestData.map(item => item.low_gamma);
// const high_gamma = latestData.map(item => item.high_gamma);
myChart.data.labels = latestData.map(item => item.index);
myChart.data.datasets[0].data = latestData.map(item => item.strength);
myChart.data.datasets[1].data = latestData.map(item => item.attention);
myChart.data.datasets[2].data = latestData.map(item => item.meditation);
myChart.data.datasets[3].data = Array.from({ length: meditation.length }, () => threshold);
// myChart.data.datasets[3].data = latestData.map(item => item.delta);
// myChart.data.datasets[4].data = latestData.map(item => item.theta);
// myChart.data.datasets[5].data = latestData.map(item => item.low_alpha);
// myChart.data.datasets[6].data = latestData.map(item => item.high_alpha);
// myChart.data.datasets[7].data = latestData.map(item => item.low_beta);
// myChart.data.datasets[8].data = latestData.map(item => item.high_beta);
// myChart.data.datasets[9].data = latestData.map(item => item.low_gamma);
// myChart.data.datasets[10].data = latestData.map(item => item.high_gamma);
if (latestData.length >= maxValues) {
myChart.update('none'); // Prevent animations when shifting the whole chart.
} else {
myChart.update();
}
}
async function initialRender() {
const data = await fetchData();
const latestData = data.slice(-maxValues);
const labels = latestData.map(item => item.index);
const strength = latestData.map(item => item.strength);
const attention = latestData.map(item => item.attention);
const meditation = latestData.map(item => item.meditation);
const thresholdArr = Array.from({ length: meditation.length }, () => threshold);
// const delta = latestData.map(item => item.delta);
// const theta = latestData.map(item => item.theta);
// const low_alpha = latestData.map(item => item.low_alpha);
// const high_alpha = latestData.map(item => item.high_alpha);
// const low_beta = latestData.map(item => item.low_beta);
// const high_beta = latestData.map(item => item.high_beta);
// const low_gamma = latestData.map(item => item.low_gamma);
// const high_gamma = latestData.map(item => item.high_gamma);
const ctx = document.getElementById('myChart').getContext('2d');
myChart = new Chart(ctx, {
type: 'line',
data: {
labels: labels,
datasets: [{
label: 'Signal Strength',
data: strength,
borderWidth: 1,
borderColor: 'black',
fill: false
},{
label: 'Attention',
data: attention,
borderWidth: 1,
borderColor: 'white',
borderWidth: 5,
fill: false
},{
label: 'Meditation',
data: meditation,
borderWidth: 1,
borderColor: 'black',
borderWidth: 5,
fill: false
},{
label: 'Threshold',
data: thresholdArr,
borderWidth: 1,
borderColor: 'red',
borderWidth: 5,
fill: false
}]
},
options: {
scales: {
y: {
beginAtZero: true
}
}
}
});
}
function settingsPrompt() {
maxValues = prompt("How many samples should be shown at once?", "50");
if (maxValues == null || maxValues == "") {
text = "User cancelled the prompt.";
}
}
function home() {
window.location.href = "/";
}
function sendShock(shockLvl) {
fetch("/shock?power="+shockLvl)
.then((response) => response.json())
.then((json) => console.log(json));
}
// document.getElementById("sendShock").onsubmit = function() {
// fetch("/shock?power="+document.getElementById("shockLevel").value)
// .then((response) => response.json())
// .then((json) => console.log(json));
// }
function restartHeadset() {
fetch("/restart-headset")
.then((response) => response.json())
.then((json) => console.log(json));
}
function eStop() {
fetch("/stop")
.then((response) => response.json())
.then((json) => console.log(json));
}
initialRender();
setInterval(updateChart, 800);

157
static/js/play.js Normal file
View File

@ -0,0 +1,157 @@
let myChart; // Make chart global
let maxValues = 50;
const canvas = document.querySelector("canvas"); // Set correct canvas size
canvas.width = window.innerWidth - (window.innerWidth * .4)
canvas.height = window.innerHeight - (window.innerHeight * .6)
Chart.defaults.color = '#232634';
window.onresize = function(){ location.reload(); }
console.log("Current threshold is: "+threshold);
window.addEventListener('resize', function(event) { // TODO: Fix
console.log("Resize event!");
canvas.width = window.innerWidth
canvas.height = window.innerHeight
// initialRender();
}, true);
async function fetchData() {
const response = await fetch('/headset-data');
const data = await response.json();
return data;
}
async function updateChart() {
const data = await fetchData();
const latestData = data.slice(-maxValues);
// const labels = latestData.map(item => item.index);
// const strength = latestData.map(item => item.strength);
// const attention = latestData.map(item => item.attention);
const meditation = latestData.map(item => item.meditation);
// const delta = latestData.map(item => item.delta);
// const theta = latestData.map(item => item.theta);
// const low_alpha = latestData.map(item => item.low_alpha);
// const high_alpha = latestData.map(item => item.high_alpha);
// const low_beta = latestData.map(item => item.low_beta);
// const high_beta = latestData.map(item => item.high_beta);
// const low_gamma = latestData.map(item => item.low_gamma);
// const high_gamma = latestData.map(item => item.high_gamma);
myChart.data.labels = latestData.map(item => item.index);
myChart.data.datasets[0].data = latestData.map(item => item.strength);
myChart.data.datasets[1].data = latestData.map(item => item.attention);
myChart.data.datasets[2].data = latestData.map(item => item.meditation);
myChart.data.datasets[3].data = Array.from({ length: meditation.length }, () => threshold);
// myChart.data.datasets[3].data = latestData.map(item => item.delta);
// myChart.data.datasets[4].data = latestData.map(item => item.theta);
// myChart.data.datasets[5].data = latestData.map(item => item.low_alpha);
// myChart.data.datasets[6].data = latestData.map(item => item.high_alpha);
// myChart.data.datasets[7].data = latestData.map(item => item.low_beta);
// myChart.data.datasets[8].data = latestData.map(item => item.high_beta);
// myChart.data.datasets[9].data = latestData.map(item => item.low_gamma);
// myChart.data.datasets[10].data = latestData.map(item => item.high_gamma);
if (latestData.length >= maxValues) {
myChart.update('none'); // Prevent animations when shifting the whole chart.
} else {
myChart.update();
}
}
async function initialRender() {
const data = await fetchData();
const latestData = data.slice(-maxValues);
const labels = latestData.map(item => item.index);
const strength = latestData.map(item => item.strength);
const attention = latestData.map(item => item.attention);
const meditation = latestData.map(item => item.meditation);
const thresholdArr = Array.from({ length: meditation.length }, () => threshold);
// const delta = latestData.map(item => item.delta);
// const theta = latestData.map(item => item.theta);
// const low_alpha = latestData.map(item => item.low_alpha);
// const high_alpha = latestData.map(item => item.high_alpha);
// const low_beta = latestData.map(item => item.low_beta);
// const high_beta = latestData.map(item => item.high_beta);
// const low_gamma = latestData.map(item => item.low_gamma);
// const high_gamma = latestData.map(item => item.high_gamma);
const ctx = document.getElementById('myChart').getContext('2d');
myChart = new Chart(ctx, {
type: 'line',
data: {
labels: labels,
datasets: [{
label: 'Signal Strength',
data: strength,
borderWidth: 1,
borderColor: 'orange',
fill: false
},{
label: 'Attention',
data: attention,
borderWidth: 1,
borderColor: 'green',
fill: false
},{
label: 'Meditation',
data: meditation,
borderWidth: 1,
borderColor: 'blue',
fill: false
},{
label: 'Threshold',
data: thresholdArr,
borderWidth: 1,
borderColor: 'red',
fill: false
}]
},
options: {
scales: {
y: {
beginAtZero: true
}
}
}
});
}
function settingsPrompt() {
maxValues = prompt("How many samples should be shown at once?", "50");
if (maxValues == null || maxValues == "") {
text = "User cancelled the prompt.";
}
}
function home() {
window.location.href = "/";
}
function sendShock(shockLvl) {
fetch("/shock?power="+shockLvl)
.then((response) => response.json())
.then((json) => console.log(json));
}
// document.getElementById("sendShock").onsubmit = function() {
// fetch("/shock?power="+document.getElementById("shockLevel").value)
// .then((response) => response.json())
// .then((json) => console.log(json));
// }
function restartHeadset() {
fetch("/restart-headset")
.then((response) => response.json())
.then((json) => console.log(json));
}
function eStop() {
fetch("/stop")
.then((response) => response.json())
.then((json) => console.log(json));
}
initialRender();
setInterval(updateChart, 800);

151
static/js/playMinecraft.js Normal file
View File

@ -0,0 +1,151 @@
let myChart; // Make chart global
let maxValues = 50;
const canvas = document.querySelector("canvas"); // Set correct canvas size
canvas.width = window.innerWidth - (window.innerWidth * .4)
canvas.height = window.innerHeight - (window.innerHeight * .6)
Chart.defaults.color = '#232634';
window.onresize = function(){ location.reload(); }
console.log("Current threshold is: "+threshold);
window.addEventListener('resize', function(event) { // TODO: Fix
console.log("Resize event!");
canvas.width = window.innerWidth
canvas.height = window.innerHeight
// initialRender();
}, true);
async function fetchData() {
const response = await fetch('/headset-data');
const data = await response.json();
return data;
}
async function updateChart() {
const data = await fetchData();
const latestData = data.slice(-maxValues);
// const labels = latestData.map(item => item.index);
// const strength = latestData.map(item => item.strength);
// const attention = latestData.map(item => item.attention);
const meditation = latestData.map(item => item.meditation);
// const delta = latestData.map(item => item.delta);
// const theta = latestData.map(item => item.theta);
// const low_alpha = latestData.map(item => item.low_alpha);
// const high_alpha = latestData.map(item => item.high_alpha);
// const low_beta = latestData.map(item => item.low_beta);
// const high_beta = latestData.map(item => item.high_beta);
// const low_gamma = latestData.map(item => item.low_gamma);
// const high_gamma = latestData.map(item => item.high_gamma);
myChart.data.labels = latestData.map(item => item.index);
myChart.data.datasets[0].data = latestData.map(item => item.strength);
myChart.data.datasets[1].data = latestData.map(item => item.attention);
myChart.data.datasets[2].data = latestData.map(item => item.meditation);
myChart.data.datasets[3].data = Array.from({ length: meditation.length }, () => threshold);
// myChart.data.datasets[3].data = latestData.map(item => item.delta);
// myChart.data.datasets[4].data = latestData.map(item => item.theta);
// myChart.data.datasets[5].data = latestData.map(item => item.low_alpha);
// myChart.data.datasets[6].data = latestData.map(item => item.high_alpha);
// myChart.data.datasets[7].data = latestData.map(item => item.low_beta);
// myChart.data.datasets[8].data = latestData.map(item => item.high_beta);
// myChart.data.datasets[9].data = latestData.map(item => item.low_gamma);
// myChart.data.datasets[10].data = latestData.map(item => item.high_gamma);
if (latestData.length >= maxValues) {
myChart.update('none'); // Prevent animations when shifting the whole chart.
} else {
myChart.update();
}
}
async function initialRender() {
const data = await fetchData();
const latestData = data.slice(-maxValues);
const labels = latestData.map(item => item.index);
const strength = latestData.map(item => item.strength);
const attention = latestData.map(item => item.attention);
const meditation = latestData.map(item => item.meditation);
const thresholdArr = Array.from({ length: meditation.length }, () => threshold);
// const delta = latestData.map(item => item.delta);
// const theta = latestData.map(item => item.theta);
// const low_alpha = latestData.map(item => item.low_alpha);
// const high_alpha = latestData.map(item => item.high_alpha);
// const low_beta = latestData.map(item => item.low_beta);
// const high_beta = latestData.map(item => item.high_beta);
// const low_gamma = latestData.map(item => item.low_gamma);
// const high_gamma = latestData.map(item => item.high_gamma);
const ctx = document.getElementById('myChart').getContext('2d');
myChart = new Chart(ctx, {
type: 'line',
data: {
labels: labels,
datasets: [{
label: 'Signal Strength',
data: strength,
borderWidth: 1,
borderColor: 'orange',
fill: false
},{
label: 'Attention',
data: attention,
borderWidth: 1,
borderColor: 'green',
fill: false
},{
label: 'Meditation',
data: meditation,
borderWidth: 1,
borderColor: 'blue',
fill: false
},{
label: 'Threshold',
data: thresholdArr,
borderWidth: 1,
borderColor: 'red',
fill: false
}]
},
options: {
scales: {
y: {
beginAtZero: true
}
}
}
});
}
function settingsPrompt() {
maxValues = prompt("How many samples should be shown at once?", "50");
if (maxValues == null || maxValues == "") {
text = "User cancelled the prompt.";
}
}
function home() {
window.location.href = "/";
}
function sendShock(shockLvl) {
fetch("/shock?power="+shockLvl)
.then((response) => response.json())
.then((json) => console.log(json));
}
function restartHeadset() {
fetch("/restart-headset")
.then((response) => response.json())
.then((json) => console.log(json));
}
function eStop() {
fetch("/stop")
.then((response) => response.json())
.then((json) => console.log(json));
}
initialRender();
setInterval(updateChart, 800);

BIN
static/openSauceDisplay.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 248 KiB

13
static/scripts/chart.min.js vendored Normal file

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

20
templates/graph.html Normal file
View File

@ -0,0 +1,20 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Data Graph</title>
<script src="{{url_for('static', filename='scripts/chart.min.js')}}"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
</head>
<body>
<canvas id="myChart" width="400" height="150"></canvas>
<!-- Note that the above canvas will reisze itself to fill screen, but leave some space below. -->
<div style="text-align:center; margin-top: 15">
<button style="font-size: 18px;", onclick="settingsPrompt()">
<i class="fa fa-solid fa-sliders"></i> Max samples to display</button>
<button style="font-size: 18px;", onclick="home()">
<i class="fa fa-solid fa-home"></i> Home</button>
</div>
<script src="{{url_for('static', filename='js/graph.js')}}"></script>
</body>
</html>

43
templates/index.html Normal file
View File

@ -0,0 +1,43 @@
<!DOCTYPE html>
<html>
<head>
<h1 style="color: #f1fa8c;">Dashboard</h1>
<title>Home Page</title>
<link rel="stylesheet" href="{{url_for('static', filename='css/style.css')}}">
</head>
<body style="background-color: #282a36">
<div id="main-text">
<h3 style="text-align: center"><br>&nbsp;&nbsp;Select an option.</h3>
<p style="text-align: center; margin-left: auto; margin-right: auto; width: 85%; font-size: 21px;">Select "Graph the data" if you want to see a live graph of the data coming from the headset, or select "Play" to play the "game".</p>
<div id="row-0">
<figure>
<a href="play"><img style="border: 7px solid rgba(235, 235, 255, .3); border-radius: 12px; box-shadow: 10px 5px 5px rgba(0, 0, 0, .3);" height=230px; src="{{url_for('static', filename='images/play.jpeg')}}"/></a>
<figcaption style="font-size: 19px; font-weight: bold;">Play</figcaption>
</figure>
<figure>
<a href="graph"><img style="border: 7px solid rgba(235, 235, 255, .3); border-radius: 12px; box-shadow: 10px 5px 5px rgba(0, 0, 0, .3);" height=230px; src="{{url_for('static', filename='images/graph.jpg')}}"/></a>
<figcaption style="font-size: 19px; font-weight: bold;">Graph the data</figcaption>
</figure>
</div>
<div id="row-1">
<figure>
<a href="open-sussy"><img style="border: 7px solid rgba(235, 235, 255, .3); border-radius: 12px; box-shadow: 10px 5px 5px rgba(0, 0, 0, .3);" height=230px; src="{{url_for('static', filename='images/OS-LOGO-W-Header.png')}}"/></a>
<figcaption style="font-size: 19px; font-weight: bold;">Open Sauce Mode</figcaption>
</figure>
<!-- <figure style="margin-top: 14px;">
<p style="position: relative; top: 50%; left: 50%; font-size: 21px; font-weight: bold; color: #f1fa8c; transform: translate(-50%, -50%); z-index: 1; background-color:rgba(68, 71, 90, 0.7);">Not finished yet!</p>
<img style="opacity: 0.7; filter: alpha(opacity=70); border: 7px solid rgba(235, 235, 255, .3); border-radius: 12px; box-shadow: 10px 5px 5px rgba(0, 0, 0, .3);" height=230px; src="images/research.jpg"/>
<figcaption style="opacity: 0.7; filter: alpha(opacity=70); font-size: 18px; font-weight: bold;">Research</figcaption>
</figure>
<figure>
<p style="position: relative; top: 50%; left: 50%; font-size: 21px; font-weight: bold; color: #f1fa8c; transform: translate(-50%, -50%); z-index: 1; background-color:rgba(68, 71, 90, 0.7);">Not finished yet!</p>
<img style="opacity: 0.7; filter: alpha(opacity=70); border: 7px solid rgba(235, 235, 255, .3); border-radius: 12px; box-shadow: 10px 5px 5px rgba(0, 0, 0, .3);" height=230px; src="images/nuclear-symbol.jpg"/>
<figcaption style="opacity: 0.7; filter: alpha(opacity=70); font-size: 19px; font-weight: bold;">Public Perception/Debate</figcaption>
</figure>
</div> -->
</div>
<footer>
<p style="font-family: Arial, Helvetica, sans-serif; color: #f1fa8c; bottom: 0;">Made by James Hoffman</p>
</footer>
</body>

84
templates/openSauce.html Normal file
View File

@ -0,0 +1,84 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Data Graph</title>
<script src="{{url_for('static', filename='scripts/chart.min.js')}}"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
<link rel="stylesheet" href="{{url_for('static', filename='css/style-opensauce.css')}}">
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link href="https://fonts.googleapis.com/css2?family=Poppins:ital,wght@0,400;0,600;0,700;0,800;0,900;1,400;1,600;1,700;1,800;1,900&display=swap" rel="stylesheet">
</head>
<body style="background-color: #EB9822; font-family: Poppins, Sans-serif; font-weight: 700;">
<canvas id="myChart" width="400" height="150"></canvas>
<!-- Note that the above canvas will reisze itself to fill screen, but leave some space below. -->
<div style="text-align:center; margin-top: 15">
<button style="font-size: 18px;", onclick="settingsPrompt()">
<i class="fa fa-solid fa-sliders"></i> Max samples to display</button>
<button style="font-size: 18px;", onclick="home()">
<i class="fa fa-solid fa-home"></i> Home</button>
<br><svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 448 512" style="width: 50px; margin-top: 30px;">!Font Awesome Free 6.5.2 by @fontawesome - https://fontawesome.com License - https://fontawesome.com/license/free Copyright 2024 Fonticons, Inc.<path d="M243.6 91.6L323.7 138.4C326.6 140 326.7 144.6 323.7 146.2L228.5 201.9C225.6 203.6 222.2 203.4 219.5 201.9L124.4 146.2C121.4 144.6 121.4 140 124.4 138.4L204.4 91.6V0L0 119.4V358.3L78.4 312.5V218.9C78.3 215.6 82.2 213.2 85.1 215L180.3 270.6C183.2 272.3 184.8 275.3 184.8 278.5V389.7C184.8 393 181 395.4 178.1 393.6L98 346.8L19.6 392.6L224 512L428.4 392.6L350 346.8L269.9 393.6C267.1 395.3 263.1 393.1 263.2 389.7V278.5C263.2 275.1 265.1 272.2 267.7 270.6L362.9 215C365.7 213.2 369.7 215.5 369.6 218.9V312.5L448 358.3V119.4L243.6 0V91.6z"/></svg><p id="control-text"> UNITY CONNECTED</p>
<!-- <button style="font-size: 18px;", onclick="restartHeadset()">-->
<!-- <i class="fa fa-solid fa-rotate-right"></i> Restart headset thread</button>-->
<!-- <button style="font-size: 18px;", onclick="sendShock(10)">
<i class="fa fa-solid fa-bolt"></i> Level 10 shock</button>
<button style="font-size: 18px;", onclick="sendShock(20)">
<i class="fa fa-solid fa-bolt"></i><i class="fa fa-solid fa-bolt"></i> Level 20 shock</button>
<button style="font-size: 18px;", onclick="sendShock(30)">
<i class="fa fa-solid fa-bolt"></i><i class="fa fa-solid fa-bolt"></i><i class="fa fa-solid fa-bolt"></i> Level 30 shock</button>
<button style="font-size: 18px;", onclick="sendShock(40)">
<i class="fa fa-solid fa-bolt"></i><i class="fa fa-solid fa-bolt"></i><i class="fa fa-solid fa-bolt"></i> Level 40 shock <i class="fa fa-solid fa-bolt"></i></button>
<button style="font-size: 18px;", onclick="sendShock(50)">
<i class="fa fa-solid fa-bolt"></i><i class="fa fa-solid fa-bolt"></i><i class="fa fa-solid fa-bolt"></i> Level 50 shock <i class="fa fa-solid fa-bolt"></i><i class="fa fa-solid fa-bolt"></i></button>
<button style="font-size: 18px;", onclick="sendShock(60)">
<i class="fa fa-solid fa-bolt"></i><i class="fa fa-solid fa-bolt"></i><i class="fa fa-solid fa-bolt"></i> Level 60 shock <i class="fa fa-solid fa-bolt"></i><i class="fa fa-solid fa-bolt"></i><i class="fa fa-solid fa-bolt"></i></button> -->
<!-- <form name="sendShock" id="sendShock" style="display: inline" action="{{ url_for ('shock') }}">
<input type="text" id="power" name="power" placeholder="Level" style="width: 10%">
<input type="submit" value="Send test shock" style="margin:4px 2px; border-radius: 8px; height: 15%">
</form> -->
<!-- <br><br> -->
<!-- <div class="dropdown">
<button class="dropbtn">Element to monitor</button> -->
<!-- TODO: Make this select -->
<!-- <div class="dropdown-content">
<a href="#">Meditation</a>
<a href="#">Attention</a>
</div> -->
<!-- </div> -->
<!-- <iframe name="dummyframe" id="dummyframe" style="display: none;"></iframe> -->
<form action="{{ url_for('options')}}">
<!-- <form method="POST" action="{{ url_for('options')}}"> -->
<div id="controls">
&nbsp;&nbsp;&nbsp;<p id="control-text">IF </p>&nbsp;
<select name="type" class="select">
<option value="meditation">meditation</option>
<option value="attention">attention</option>
</select>
<select name="condition" class="select">
<option value="above">goes above</option>
<option value="below">goes below</option>
</select>
<input type="text" id="fname" name="threshold" placeholder="Threshold" style="width: 10%">
&nbsp;&nbsp;<p id="control-text"> "PUNISH" PLAYER WITH A </p>&nbsp;
<select name="punishment" class="select">
<option value="2">beep!</option>
<option value="3">buzz!</option>
<option value="4">zap!</option>
</select>
<input type="submit" value="Submit" style="margin:4px 2px; border-radius: 8px; height: 15%">
</div>
</form>
<!-- <label for="fname">Threshold</label> -->
<!-- <div id="controls"><a href="stop"><img style="box-shadow: 10px 5px 5px rgba(0, 0, 0, .3); border-radius: 12px;" height=148px; src="{{url_for('static', filename='images/stop.png')}}"/></a> -->
<!-- <figcaption style="font-size: 19px; font-weight: bold;"></figcaption></div> -->
<!-- <br><div id="notice-text">NOTE: Shock is disabled in Open Sauce mode (because they won't let me shock <br>you guys, something about insurance and liability...) so enjoy the lights instead!</div> -->
<p style="font-family: Poppins, Helvetica, sans-serif; color: #f1fa8c; bottom: 0;">Made by James Hoffman</p>
</div>
<script type="text/javascript">
var threshold = {{ data.threshold }}
</script>
<script src="{{url_for('static', filename='js/open-sussy.js')}}"></script>
</body>
</html>

79
templates/play.html Normal file
View File

@ -0,0 +1,79 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Data Graph</title>
<script src="{{url_for('static', filename='scripts/chart.min.js')}}"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
<link rel="stylesheet" href="{{url_for('static', filename='css/style.css')}}">
</head>
<body style="background-color: #babbf1;">
<canvas id="myChart" width="400" height="150"></canvas>
<!-- Note that the above canvas will reisze itself to fill screen, but leave some space below. -->
<div style="text-align:center; margin-top: 15">
<button style="font-size: 18px;", onclick="settingsPrompt()">
<i class="fa fa-solid fa-sliders"></i> Max samples to display</button>
<button style="font-size: 18px;", onclick="home()">
<i class="fa fa-solid fa-home"></i> Home</button>
<!-- <button style="font-size: 18px;", onclick="restartHeadset()">-->
<!-- <i class="fa fa-solid fa-rotate-right"></i> Restart headset thread</button>-->
<!-- <button style="font-size: 18px;", onclick="sendShock(10)">
<i class="fa fa-solid fa-bolt"></i> Level 10 shock</button>
<button style="font-size: 18px;", onclick="sendShock(20)">
<i class="fa fa-solid fa-bolt"></i><i class="fa fa-solid fa-bolt"></i> Level 20 shock</button>
<button style="font-size: 18px;", onclick="sendShock(30)">
<i class="fa fa-solid fa-bolt"></i><i class="fa fa-solid fa-bolt"></i><i class="fa fa-solid fa-bolt"></i> Level 30 shock</button>
<button style="font-size: 18px;", onclick="sendShock(40)">
<i class="fa fa-solid fa-bolt"></i><i class="fa fa-solid fa-bolt"></i><i class="fa fa-solid fa-bolt"></i> Level 40 shock <i class="fa fa-solid fa-bolt"></i></button>
<button style="font-size: 18px;", onclick="sendShock(50)">
<i class="fa fa-solid fa-bolt"></i><i class="fa fa-solid fa-bolt"></i><i class="fa fa-solid fa-bolt"></i> Level 50 shock <i class="fa fa-solid fa-bolt"></i><i class="fa fa-solid fa-bolt"></i></button>
<button style="font-size: 18px;", onclick="sendShock(60)">
<i class="fa fa-solid fa-bolt"></i><i class="fa fa-solid fa-bolt"></i><i class="fa fa-solid fa-bolt"></i> Level 60 shock <i class="fa fa-solid fa-bolt"></i><i class="fa fa-solid fa-bolt"></i><i class="fa fa-solid fa-bolt"></i></button> -->
<form name="sendShock" id="sendShock" style="display: inline" action="{{ url_for ('shock') }}">
<input type="text" id="power" name="power" placeholder="Level" style="width: 10%">
<input type="submit" value="Send test shock" style="margin:4px 2px; border-radius: 8px; height: 15%">
</form>
<br><br>
<!-- <div class="dropdown">
<button class="dropbtn">Element to monitor</button> -->
<!-- TODO: Make this select -->
<!-- <div class="dropdown-content">
<a href="#">Meditation</a>
<a href="#">Attention</a>
</div> -->
<!-- </div> -->
<!-- <iframe name="dummyframe" id="dummyframe" style="display: none;"></iframe> -->
<form action="{{ url_for('options')}}">
<!-- <form method="POST" action="{{ url_for('options')}}"> -->
<div id="controls">
&nbsp;&nbsp;&nbsp;<p id="control-text">If</p>&nbsp;
<select name="type" class="select">
<option value="meditation">meditation</option>
<option value="attention">attention</option>
</select>
<select name="condition" class="select">
<option value="above">goes above</option>
<option value="below">goes below</option>
</select>
<input type="text" id="fname" name="threshold" placeholder="Threshold" style="width: 10%">
&nbsp;&nbsp;<p id="control-text"> punish player with a </p>&nbsp;
<select name="punishment" class="select">
<option value="2">beep!</option>
<option value="3">buzz!</option>
<option value="4">zap!</option>
</select>
<input type="submit" value="Submit" style="margin:4px 2px; border-radius: 8px; height: 15%">
</div>
</form>
<!-- <label for="fname">Threshold</label> -->
<div id="controls"><a href="stop"><img style="box-shadow: 10px 5px 5px rgba(0, 0, 0, .3); border-radius: 12px;" height=148px; src="{{url_for('static', filename='images/stop.png')}}"/></a>
<figcaption style="font-size: 19px; font-weight: bold;"></figcaption></div>
</div>
<script type="text/javascript">
var threshold = {{ data.threshold }}
</script>
<script src="{{url_for('static', filename='js/play.js')}}"></script>
</body>
</html>

View File

@ -0,0 +1,70 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Data Graph</title>
<script src="{{url_for('static', filename='scripts/chart.min.js')}}"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
<link rel="stylesheet" href="{{url_for('static', filename='css/style.css')}}">
</head>
<body style="background-color: #babbf1;">
<canvas id="myChart" width="400" height="150"></canvas>
<!-- Note that the above canvas will reisze itself to fill screen, but leave some space below. -->
<div style="text-align:center; margin-top: 15">
<button style="font-size: 18px;", onclick="settingsPrompt()">
<i class="fa fa-solid fa-sliders"></i> Max samples to display</button>
<button style="font-size: 18px;", onclick="home()">
<i class="fa fa-solid fa-home"></i> Home</button>
<!-- <button style="font-size: 18px;", onclick="restartHeadset()">-->
<!-- <i class="fa fa-solid fa-rotate-right"></i> Restart headset thread</button>-->
<button style="font-size: 18px;", onclick="sendShock(1)">
<i class="fa fa-solid fa-bolt"></i> Send shock</button>
<button style="font-size: 18px;", onclick="sendShock(2)">
<i class="fa fa-solid fa-bolt"></i><i class="fa fa-solid fa-bolt"></i> Send kiloshock</button>
<button style="font-size: 18px;", onclick="sendShock(3)">
<i class="fa fa-solid fa-bolt"></i><i class="fa fa-solid fa-bolt"></i><i class="fa fa-solid fa-bolt"></i> Send megashock</button>
<button style="font-size: 18px;", onclick="sendShock(4)">
<i class="fa fa-solid fa-bolt"></i><i class="fa fa-solid fa-bolt"></i><i class="fa fa-solid fa-bolt"></i> Send gigashock <i class="fa fa-solid fa-bolt"></i></button>
<button style="font-size: 18px;", onclick="sendShock(5)">
<i class="fa fa-solid fa-bolt"></i><i class="fa fa-solid fa-bolt"></i><i class="fa fa-solid fa-bolt"></i> Send terashock <i class="fa fa-solid fa-bolt"></i><i class="fa fa-solid fa-bolt"></i></button>
<button style="font-size: 18px;", onclick="sendShock(6)">
<i class="fa fa-solid fa-bolt"></i><i class="fa fa-solid fa-bolt"></i><i class="fa fa-solid fa-bolt"></i> Send petashock <i class="fa fa-solid fa-bolt"></i><i class="fa fa-solid fa-bolt"></i><i class="fa fa-solid fa-bolt"></i></button>
<br><br>
<!-- <div class="dropdown">
<button class="dropbtn">Element to monitor</button> -->
<!-- TODO: Make this select -->
<!-- <div class="dropdown-content">
<a href="#">Meditation</a>
<a href="#">Attention</a>
</div> -->
<!-- </div> -->
<!-- <iframe name="dummyframe" id="dummyframe" style="display: none;"></iframe> -->
<form action="{{ url_for('options')}}">
<!-- <form method="POST" action="{{ url_for('options')}}"> -->
<div id="controls">
&nbsp;&nbsp;&nbsp;<p id="control-text">If</p>&nbsp;
<select name="type" class="select">
<option value="meditation">meditation</option>
<option value="attention">attention</option>
</select>
<select name="condition" class="select">
<option value="above">goes above</option>
<option value="below">goes below</option>
</select>
<input type="text" id="fname" name="threshold" placeholder="Threshold" style="width: 10%">
&nbsp;&nbsp;<p id="control-text"> punish player.</p>&nbsp;
<input type="submit" value="Submit" style="margin:4px 2px; border-radius: 8px; height: 15%">
</div>
</form>
<!-- <label for="fname">Threshold</label> -->
<div id="controls"><a href="stop"><img style="box-shadow: 10px 5px 5px rgba(0, 0, 0, .3); border-radius: 12px;" height=148px; src="{{url_for('static', filename='images/stop.png')}}"/></a>
<figcaption style="font-size: 19px; font-weight: bold;"></figcaption></div>
</div>
<script type="text/javascript">
var threshold = {{ data.threshold }}
</script>
<script src="{{url_for('static', filename='js/play.js')}}"></script>
</body>
</html>

38
templates/stop.html Normal file
View File

@ -0,0 +1,38 @@
<!DOCTYPE html>
<html>
<head>
<h1 style="color: #f1fa8c;">Program has stopped</h1>
<title>Stopped program</title>
<link rel="stylesheet" href="{{url_for('static', filename='css/style.css')}}">
</head>
<body style="background-color: #282a36">
<div id="main-text" style="background:linear-gradient(0deg, rgb(90, 68, 68), rgba(0, 0, 0, 0.2)), url(../static/images/shock.jpg);">
<h3 style="text-align: center; color:#e78284; font-size: 30px;"><br>&nbsp;&nbsp;Set threshold to 500 and {punishAttention, punishMeditation} to 0. To continue operation, go <a href="/">home.</a></h3>
<p style="text-align: center; margin-left: auto; margin-right: auto; width: 85%; font-size: 21px;"></p>
<!-- <div id="row-0">
<figure>
<a href="play"><img style="border: 7px solid rgba(235, 235, 255, .3); border-radius: 12px; box-shadow: 10px 5px 5px rgba(0, 0, 0, .3);" height=230px; src="{{url_for('static', filename='images/play.jpeg')}}"/></a>
<figcaption style="font-size: 19px; font-weight: bold;">Play</figcaption>
</figure>
<figure>
<a href="graph"><img style="border: 7px solid rgba(235, 235, 255, .3); border-radius: 12px; box-shadow: 10px 5px 5px rgba(0, 0, 0, .3);" height=230px; src="{{url_for('static', filename='images/graph.jpg')}}"/></a>
<figcaption style="font-size: 19px; font-weight: bold;">Graph the data</figcaption>
<!-- </div>
<div id="row-1">
<figure style="margin-top: 14px;">
<p style="position: relative; top: 50%; left: 50%; font-size: 21px; font-weight: bold; color: #f1fa8c; transform: translate(-50%, -50%); z-index: 1; background-color:rgba(68, 71, 90, 0.7);">Not finished yet!</p>
<img style="opacity: 0.7; filter: alpha(opacity=70); border: 7px solid rgba(235, 235, 255, .3); border-radius: 12px; box-shadow: 10px 5px 5px rgba(0, 0, 0, .3);" height=230px; src="images/research.jpg"/>
<figcaption style="opacity: 0.7; filter: alpha(opacity=70); font-size: 18px; font-weight: bold;">Research</figcaption>
</figure>
<figure>
<p style="position: relative; top: 50%; left: 50%; font-size: 21px; font-weight: bold; color: #f1fa8c; transform: translate(-50%, -50%); z-index: 1; background-color:rgba(68, 71, 90, 0.7);">Not finished yet!</p>
<img style="opacity: 0.7; filter: alpha(opacity=70); border: 7px solid rgba(235, 235, 255, .3); border-radius: 12px; box-shadow: 10px 5px 5px rgba(0, 0, 0, .3);" height=230px; src="images/nuclear-symbol.jpg"/>
<figcaption style="opacity: 0.7; filter: alpha(opacity=70); font-size: 19px; font-weight: bold;">Public Perception/Debate</figcaption>
</figure>
</div> -->
<!-- </div> -->
<footer>
<p style="font-family: Arial, Helvetica, sans-serif; color: #f1fa8c; bottom: 0;">Sowwy i shocked u :(</p>
</footer>
</body>

18
utils/gen_data.py Normal file
View File

@ -0,0 +1,18 @@
from time import sleep
import random
import os
def genData(filename):
os.system('rm '+filename)
i = 0
file = open(filename, "w")
file.write("index,strength,attention,meditation,delta,theta,low_alpha,high_alpha,low_beta,high_beta,low_gamma,high_gamma")
file.write("\n"+str(i)+","+str(random.randint(0, 200))+","+str(random.randint(0, 200))+","+str(random.randint(0, 200))+","+str(random.randint(0, 100000))+","+str(random.randint(0, 100000))+","+str(random.randint(0, 100000))+","+str(random.randint(0, 100000))+","+str(random.randint(0, 100000))+","+str(random.randint(0, 100000))+","+str(random.randint(0, 100000))+","+str(random.randint(0, 100000)))
file.flush()
while True:
sleep(.5)
file.write("\n"+str(i)+","+str(random.randint(0, 100))+","+str(random.randint(0, 100))+","+str(random.randint(0, 100))+","+str(random.randint(0, 100000))+","+str(random.randint(0, 100000))+","+str(random.randint(0, 100000))+","+str(random.randint(0, 100000))+","+str(random.randint(0, 100000))+","+str(random.randint(0, 100000))+","+str(random.randint(0, 100000))+","+str(random.randint(0, 100000)))
i += 1
file.flush()