commit
5a25d1e47e
113 changed files with 3955 additions and 3933 deletions
@ -1,28 +1,32 @@ |
|||||||
FROM commaai/openpilot-base:latest |
FROM commaai/openpilot-base:latest |
||||||
|
|
||||||
ENV PYTHONUNBUFFERED 1 |
ENV PYTHONUNBUFFERED 1 |
||||||
ENV PYTHONPATH /tmp/openpilot:${PYTHONPATH} |
|
||||||
|
|
||||||
RUN mkdir -p /tmp/openpilot |
ENV OPENPILOT_PATH /home/batman/openpilot/ |
||||||
|
ENV PYTHONPATH ${OPENPILOT_PATH}:${PYTHONPATH} |
||||||
|
|
||||||
COPY SConstruct \ |
RUN mkdir -p ${OPENPILOT_PATH} |
||||||
.pylintrc \ |
WORKDIR ${OPENPILOT_PATH} |
||||||
.pre-commit-config.yaml \ |
|
||||||
/tmp/openpilot/ |
|
||||||
|
|
||||||
COPY ./pyextra /tmp/openpilot/pyextra |
COPY Pipfile Pipfile.lock $OPENPILOT_PATH |
||||||
COPY ./phonelibs /tmp/openpilot/phonelibs |
RUN pip install --no-cache-dir pipenv==2020.8.13 && \ |
||||||
COPY ./site_scons /tmp/openpilot/site_scons |
pipenv install --system --deploy --dev --clear && \ |
||||||
COPY ./laika /tmp/openpilot/laika |
pip uninstall -y pipenv |
||||||
COPY ./laika_repo /tmp/openpilot/laika_repo |
|
||||||
COPY ./rednose /tmp/openpilot/rednose |
COPY SConstruct ${OPENPILOT_PATH} |
||||||
COPY ./tools /tmp/openpilot/tools |
|
||||||
COPY ./release /tmp/openpilot/release |
COPY ./pyextra ${OPENPILOT_PATH}/pyextra |
||||||
COPY ./common /tmp/openpilot/common |
COPY ./phonelibs ${OPENPILOT_PATH}/phonelibs |
||||||
COPY ./opendbc /tmp/openpilot/opendbc |
COPY ./site_scons ${OPENPILOT_PATH}/site_scons |
||||||
COPY ./cereal /tmp/openpilot/cereal |
COPY ./laika ${OPENPILOT_PATH}/laika |
||||||
COPY ./panda /tmp/openpilot/panda |
COPY ./laika_repo ${OPENPILOT_PATH}/laika_repo |
||||||
COPY ./selfdrive /tmp/openpilot/selfdrive |
COPY ./rednose ${OPENPILOT_PATH}/rednose |
||||||
|
COPY ./tools ${OPENPILOT_PATH}/tools |
||||||
|
COPY ./release ${OPENPILOT_PATH}/release |
||||||
|
COPY ./common ${OPENPILOT_PATH}/common |
||||||
|
COPY ./opendbc ${OPENPILOT_PATH}/opendbc |
||||||
|
COPY ./cereal ${OPENPILOT_PATH}/cereal |
||||||
|
COPY ./panda ${OPENPILOT_PATH}/panda |
||||||
|
COPY ./selfdrive ${OPENPILOT_PATH}/selfdrive |
||||||
|
|
||||||
WORKDIR /tmp/openpilot |
|
||||||
RUN scons -j$(nproc) |
RUN scons -j$(nproc) |
||||||
|
@ -1 +1 @@ |
|||||||
Subproject commit 61a3b45ed2597b24be6e9d8920b2cd36609267db |
Subproject commit 610fa77bc41ddf58e57f52ef678222a435cb6748 |
@ -0,0 +1,22 @@ |
|||||||
|
import numpy as np |
||||||
|
|
||||||
|
|
||||||
|
def deep_interp_np(x, xp, fp, axis=None): |
||||||
|
if axis is not None: |
||||||
|
fp = fp.swapaxes(0,axis) |
||||||
|
x = np.atleast_1d(x) |
||||||
|
xp = np.array(xp) |
||||||
|
if len(xp) < 2: |
||||||
|
return np.repeat(fp, len(x), axis=0) |
||||||
|
if min(np.diff(xp)) < 0: |
||||||
|
raise RuntimeError('Bad x array for interpolation') |
||||||
|
j = np.searchsorted(xp, x) - 1 |
||||||
|
j = np.clip(j, 0, len(xp)-2) |
||||||
|
d = np.divide(x - xp[j], xp[j + 1] - xp[j], out=np.ones_like(x, dtype=np.float64), where=xp[j + 1] - xp[j] != 0) |
||||||
|
vals_interp = (fp[j].T*(1 - d)).T + (fp[j + 1].T*d).T |
||||||
|
if axis is not None: |
||||||
|
vals_interp = vals_interp.swapaxes(0,axis) |
||||||
|
if len(vals_interp) == 1: |
||||||
|
return vals_interp[0] |
||||||
|
else: |
||||||
|
return vals_interp |
@ -1 +1 @@ |
|||||||
Subproject commit 4b7947374e31df02587dcdd4c7562a78344e11b3 |
Subproject commit f8f5788df38cb286e1d136e96fb109f197deee37 |
@ -1,83 +0,0 @@ |
|||||||
#!/usr/bin/env python3 |
|
||||||
import os |
|
||||||
import sys |
|
||||||
import time |
|
||||||
import signal |
|
||||||
import traceback |
|
||||||
import usb1 |
|
||||||
from panda import Panda, PandaDFU |
|
||||||
from multiprocessing import Pool |
|
||||||
|
|
||||||
jungle = "JUNGLE" in os.environ |
|
||||||
if jungle: |
|
||||||
from panda_jungle import PandaJungle # pylint: disable=import-error |
|
||||||
|
|
||||||
import cereal.messaging as messaging |
|
||||||
from selfdrive.boardd.boardd import can_capnp_to_can_list |
|
||||||
|
|
||||||
def initializer(): |
|
||||||
"""Ignore CTRL+C in the worker process. |
|
||||||
source: https://stackoverflow.com/a/44869451 """ |
|
||||||
signal.signal(signal.SIGINT, signal.SIG_IGN) |
|
||||||
|
|
||||||
def send_thread(sender_serial): |
|
||||||
global jungle |
|
||||||
while True: |
|
||||||
try: |
|
||||||
if jungle: |
|
||||||
sender = PandaJungle(sender_serial) |
|
||||||
else: |
|
||||||
sender = Panda(sender_serial) |
|
||||||
sender.set_safety_mode(Panda.SAFETY_ALLOUTPUT) |
|
||||||
|
|
||||||
sender.set_can_loopback(False) |
|
||||||
can_sock = messaging.sub_sock('can') |
|
||||||
|
|
||||||
while True: |
|
||||||
tsc = messaging.recv_one(can_sock) |
|
||||||
snd = can_capnp_to_can_list(tsc.can) |
|
||||||
snd = list(filter(lambda x: x[-1] <= 2, snd)) |
|
||||||
|
|
||||||
try: |
|
||||||
sender.can_send_many(snd) |
|
||||||
except usb1.USBErrorTimeout: |
|
||||||
pass |
|
||||||
|
|
||||||
# Drain panda message buffer |
|
||||||
sender.can_recv() |
|
||||||
except Exception: |
|
||||||
traceback.print_exc() |
|
||||||
time.sleep(1) |
|
||||||
|
|
||||||
if __name__ == "__main__": |
|
||||||
if jungle: |
|
||||||
serials = PandaJungle.list() |
|
||||||
else: |
|
||||||
serials = Panda.list() |
|
||||||
num_senders = len(serials) |
|
||||||
|
|
||||||
if num_senders == 0: |
|
||||||
print("No senders found. Exiting") |
|
||||||
sys.exit(1) |
|
||||||
else: |
|
||||||
print("%d senders found. Starting broadcast" % num_senders) |
|
||||||
|
|
||||||
if "FLASH" in os.environ: |
|
||||||
for s in PandaDFU.list(): |
|
||||||
PandaDFU(s).recover() |
|
||||||
|
|
||||||
time.sleep(1) |
|
||||||
for s in serials: |
|
||||||
Panda(s).recover() |
|
||||||
Panda(s).flash() |
|
||||||
|
|
||||||
pool = Pool(num_senders, initializer=initializer) |
|
||||||
pool.map_async(send_thread, serials) |
|
||||||
|
|
||||||
while True: |
|
||||||
try: |
|
||||||
time.sleep(10) |
|
||||||
except KeyboardInterrupt: |
|
||||||
pool.terminate() |
|
||||||
pool.join() |
|
||||||
raise |
|
@ -1,10 +1,18 @@ |
|||||||
#pragma once |
#pragma once |
||||||
|
const int TRAJECTORY_SIZE = 33; |
||||||
|
const float MIN_DRAW_DISTANCE = 10.0; |
||||||
|
const float MAX_DRAW_DISTANCE = 100.0; |
||||||
|
|
||||||
constexpr int MODEL_PATH_DISTANCE = 192; |
const double T_IDXS[TRAJECTORY_SIZE] = {0. , 0.00976562, 0.0390625 , 0.08789062, 0.15625 , |
||||||
constexpr int TRAJECTORY_SIZE = 33; |
0.24414062, 0.3515625 , 0.47851562, 0.625 , 0.79101562, |
||||||
constexpr float MIN_DRAW_DISTANCE = 10.0; |
0.9765625 , 1.18164062, 1.40625 , 1.65039062, 1.9140625 , |
||||||
constexpr float MAX_DRAW_DISTANCE = 100.0; |
2.19726562, 2.5 , 2.82226562, 3.1640625 , 3.52539062, |
||||||
constexpr int POLYFIT_DEGREE = 4; |
3.90625 , 4.30664062, 4.7265625 , 5.16601562, 5.625 , |
||||||
constexpr int SPEED_PERCENTILES = 10; |
6.10351562, 6.6015625 , 7.11914062, 7.65625 , 8.21289062, |
||||||
constexpr int DESIRE_PRED_SIZE = 32; |
8.7890625 , 9.38476562, 10.}; |
||||||
constexpr int OTHER_META_SIZE = 4; |
const double X_IDXS[TRAJECTORY_SIZE] = { 0. , 0.1875, 0.75 , 1.6875, 3. , 4.6875, |
||||||
|
6.75 , 9.1875, 12. , 15.1875, 18.75 , 22.6875, |
||||||
|
27. , 31.6875, 36.75 , 42.1875, 48. , 54.1875, |
||||||
|
60.75 , 67.6875, 75. , 82.6875, 90.75 , 99.1875, |
||||||
|
108. , 117.1875, 126.75 , 136.6875, 147. , 157.6875, |
||||||
|
168.75 , 180.1875, 192.}; |
||||||
|
File diff suppressed because it is too large
Load Diff
@ -0,0 +1,92 @@ |
|||||||
|
#!/usr/bin/env python3 |
||||||
|
import os |
||||||
|
import time |
||||||
|
from multiprocessing import Process |
||||||
|
from tqdm import tqdm |
||||||
|
|
||||||
|
os.environ['TESTING_CLOSET'] = '1' |
||||||
|
os.environ['FILEREADER_CACHE'] = '1' |
||||||
|
|
||||||
|
from common.realtime import config_realtime_process, Ratekeeper |
||||||
|
from selfdrive.boardd.boardd import can_capnp_to_can_list |
||||||
|
from selfdrive.pandad import set_panda_power |
||||||
|
from tools.lib.logreader import LogReader |
||||||
|
|
||||||
|
from panda import Panda |
||||||
|
try: |
||||||
|
from panda_jungle import PandaJungle # pylint: disable=import-error |
||||||
|
except Exception: |
||||||
|
PandaJungle = None # type: ignore |
||||||
|
|
||||||
|
ROUTE = "77611a1fac303767/2020-03-24--09-50-38" |
||||||
|
NUM_SEGS = 2 # route has 82 segments available |
||||||
|
|
||||||
|
print("Loading log...") |
||||||
|
CAN_MSGS = [] |
||||||
|
for i in tqdm(list(range(1, NUM_SEGS+1))): |
||||||
|
log_url = f"https://commadataci.blob.core.windows.net/openpilotci/{ROUTE}/{i}/rlog.bz2" |
||||||
|
lr = LogReader(log_url) |
||||||
|
CAN_MSGS += [can_capnp_to_can_list(m.can) for m in lr if m.which() == 'can'] |
||||||
|
|
||||||
|
def send_thread(sender, core): |
||||||
|
config_realtime_process(core, 55) |
||||||
|
|
||||||
|
if "Jungle" in str(type(sender)): |
||||||
|
for i in [0, 1, 2, 3, 0xFFFF]: |
||||||
|
sender.can_clear(i) |
||||||
|
sender.set_ignition(False) |
||||||
|
time.sleep(5) |
||||||
|
sender.set_ignition(True) |
||||||
|
sender.set_panda_power(True) |
||||||
|
else: |
||||||
|
sender.set_safety_mode(Panda.SAFETY_ALLOUTPUT) |
||||||
|
sender.set_can_loopback(False) |
||||||
|
|
||||||
|
log_idx = 0 |
||||||
|
rk = Ratekeeper(100) |
||||||
|
while True: |
||||||
|
snd = CAN_MSGS[log_idx] |
||||||
|
log_idx = (log_idx + 1) % len(CAN_MSGS) |
||||||
|
snd = list(filter(lambda x: x[-1] <= 2, snd)) |
||||||
|
sender.can_send_many(snd) |
||||||
|
|
||||||
|
# Drain panda message buffer |
||||||
|
sender.can_recv() |
||||||
|
rk.keep_time() |
||||||
|
|
||||||
|
def connect(): |
||||||
|
serials = {} |
||||||
|
while True: |
||||||
|
# look for new devices |
||||||
|
for p in [Panda, PandaJungle]: |
||||||
|
if p is None: |
||||||
|
continue |
||||||
|
|
||||||
|
for s in p.list(): |
||||||
|
if s not in serials: |
||||||
|
print("starting send thread for", s) |
||||||
|
serials[s] = Process(target=send_thread, args=(p(s), 3)) |
||||||
|
serials[s].start() |
||||||
|
|
||||||
|
# try to join all send procs |
||||||
|
cur_serials = serials.copy() |
||||||
|
for s, p in cur_serials.items(): |
||||||
|
p.join(0.01) |
||||||
|
if p.exitcode is not None: |
||||||
|
del serials[s] |
||||||
|
|
||||||
|
time.sleep(1) |
||||||
|
|
||||||
|
if __name__ == "__main__": |
||||||
|
set_panda_power(False) |
||||||
|
time.sleep(1) |
||||||
|
|
||||||
|
if "FLASH" in os.environ and PandaJungle is not None: |
||||||
|
for s in PandaJungle.list(): |
||||||
|
PandaJungle(s).flash() |
||||||
|
|
||||||
|
while True: |
||||||
|
try: |
||||||
|
connect() |
||||||
|
except Exception: |
||||||
|
pass |
@ -0,0 +1 @@ |
|||||||
|
clpeak/ |
@ -0,0 +1,22 @@ |
|||||||
|
#!/usr/bin/bash |
||||||
|
|
||||||
|
DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" >/dev/null 2>&1 && pwd )" |
||||||
|
cd $DIR |
||||||
|
|
||||||
|
if [ ! -d "$DIR/clpeak" ]; then |
||||||
|
git clone https://github.com/krrishnarraj/clpeak.git |
||||||
|
|
||||||
|
cd clpeak |
||||||
|
git fetch |
||||||
|
git checkout ec2d3e70e1abc7738b81f9277c7af79d89b2133b |
||||||
|
git reset --hard origin/master |
||||||
|
git submodule update --init --recursive --remote |
||||||
|
|
||||||
|
git apply ../run_continuously.patch |
||||||
|
fi |
||||||
|
|
||||||
|
cd clpeak |
||||||
|
mkdir build || true |
||||||
|
cd build |
||||||
|
cmake .. |
||||||
|
cmake --build . |
Binary file not shown.
@ -0,0 +1,13 @@ |
|||||||
|
diff --git a/src/clpeak.cpp b/src/clpeak.cpp
|
||||||
|
index 8cb192b..b6fe6f5 100644
|
||||||
|
--- a/src/clpeak.cpp
|
||||||
|
+++ b/src/clpeak.cpp
|
||||||
|
@@ -47,7 +47,7 @@ int clPeak::runAll()
|
||||||
|
|
||||||
|
log->xmlOpenTag("clpeak");
|
||||||
|
log->xmlAppendAttribs("os", OS_NAME);
|
||||||
|
- for (size_t p = 0; p < platforms.size(); p++)
|
||||||
|
+ for (size_t p = 0; p < platforms.size(); (p+1 % platforms.size()))
|
||||||
|
{
|
||||||
|
if (forcePlatform && (p != specifiedPlatform))
|
||||||
|
continue;
|
@ -0,0 +1,37 @@ |
|||||||
|
#include <assert.h> |
||||||
|
#include <string> |
||||||
|
|
||||||
|
#include "common/swaglog.h" |
||||||
|
#include "common/util.h" |
||||||
|
#include "logger.h" |
||||||
|
#include "messaging.hpp" |
||||||
|
|
||||||
|
int main(int argc, char** argv) { |
||||||
|
LoggerState logger; |
||||||
|
logger_init(&logger, "bootlog", false); |
||||||
|
|
||||||
|
char segment_path[4096]; |
||||||
|
int err = logger_next(&logger, LOG_ROOT.c_str(), segment_path, sizeof(segment_path), nullptr); |
||||||
|
assert(err == 0); |
||||||
|
LOGW("bootlog to %s", segment_path); |
||||||
|
|
||||||
|
MessageBuilder msg; |
||||||
|
auto boot = msg.initEvent().initBoot(); |
||||||
|
|
||||||
|
boot.setWallTimeNanos(nanos_since_epoch()); |
||||||
|
|
||||||
|
std::string lastKmsg = util::read_file("/sys/fs/pstore/console-ramoops"); |
||||||
|
boot.setLastKmsg(capnp::Data::Reader((const kj::byte*)lastKmsg.data(), lastKmsg.size())); |
||||||
|
|
||||||
|
std::string lastPmsg = util::read_file("/sys/fs/pstore/pmsg-ramoops-0"); |
||||||
|
boot.setLastPmsg(capnp::Data::Reader((const kj::byte*)lastPmsg.data(), lastPmsg.size())); |
||||||
|
|
||||||
|
std::string launchLog = util::read_file("/tmp/launch_log"); |
||||||
|
boot.setLaunchLog(capnp::Text::Reader(launchLog.data(), launchLog.size())); |
||||||
|
|
||||||
|
auto bytes = msg.toBytes(); |
||||||
|
logger_log(&logger, bytes.begin(), bytes.size(), false); |
||||||
|
|
||||||
|
logger_close(&logger); |
||||||
|
return 0; |
||||||
|
} |
@ -1 +1 @@ |
|||||||
852c79998828975cce184114537b0067b80bc608 |
4d71a89ccbfd351cbe58fcf217ee2eefa48eee2d |
||||||
|
@ -1 +1 @@ |
|||||||
196c58580ec9cfd9691a9c4ebaad2dcd01cc0777 |
9ffa2b9927f188bdc07be62b2cc4ee00e5632522 |
@ -1,108 +0,0 @@ |
|||||||
#!/usr/bin/env python3 |
|
||||||
import os |
|
||||||
import time |
|
||||||
import sys |
|
||||||
import subprocess |
|
||||||
|
|
||||||
import cereal.messaging as messaging |
|
||||||
from common.basedir import BASEDIR |
|
||||||
from selfdrive.test.helpers import set_params_enabled |
|
||||||
|
|
||||||
def cputime_total(ct): |
|
||||||
return ct.cpuUser + ct.cpuSystem + ct.cpuChildrenUser + ct.cpuChildrenSystem |
|
||||||
|
|
||||||
|
|
||||||
def print_cpu_usage(first_proc, last_proc): |
|
||||||
procs = [ |
|
||||||
("selfdrive.controls.controlsd", 47.0), |
|
||||||
("./loggerd", 42.0), |
|
||||||
("selfdrive.locationd.locationd", 35.0), |
|
||||||
("selfdrive.locationd.paramsd", 12.0), |
|
||||||
("selfdrive.controls.plannerd", 10.0), |
|
||||||
("./_modeld", 7.12), |
|
||||||
("./camerad", 7.07), |
|
||||||
("./_sensord", 6.17), |
|
||||||
("./_ui", 5.82), |
|
||||||
("selfdrive.controls.radard", 5.67), |
|
||||||
("./boardd", 3.63), |
|
||||||
("./_dmonitoringmodeld", 2.67), |
|
||||||
("selfdrive.logmessaged", 1.7), |
|
||||||
("selfdrive.thermald.thermald", 2.41), |
|
||||||
("selfdrive.locationd.calibrationd", 2.0), |
|
||||||
("selfdrive.monitoring.dmonitoringd", 1.90), |
|
||||||
("./proclogd", 1.54), |
|
||||||
("./_gpsd", 0.09), |
|
||||||
("./clocksd", 0.02), |
|
||||||
("./ubloxd", 0.02), |
|
||||||
("selfdrive.tombstoned", 0), |
|
||||||
("./logcatd", 0), |
|
||||||
] |
|
||||||
|
|
||||||
r = True |
|
||||||
dt = (last_proc.logMonoTime - first_proc.logMonoTime) / 1e9 |
|
||||||
result = "------------------------------------------------\n" |
|
||||||
for proc_name, normal_cpu_usage in procs: |
|
||||||
try: |
|
||||||
first = [p for p in first_proc.procLog.procs if proc_name in p.cmdline][0] |
|
||||||
last = [p for p in last_proc.procLog.procs if proc_name in p.cmdline][0] |
|
||||||
cpu_time = cputime_total(last) - cputime_total(first) |
|
||||||
cpu_usage = cpu_time / dt * 100. |
|
||||||
if cpu_usage > max(normal_cpu_usage * 1.1, normal_cpu_usage + 5.0): |
|
||||||
result += f"Warning {proc_name} using more CPU than normal\n" |
|
||||||
r = False |
|
||||||
elif cpu_usage < min(normal_cpu_usage * 0.65, max(normal_cpu_usage - 1.0, 0.0)): |
|
||||||
result += f"Warning {proc_name} using less CPU than normal\n" |
|
||||||
r = False |
|
||||||
result += f"{proc_name.ljust(35)} {cpu_usage:.2f}%\n" |
|
||||||
except IndexError: |
|
||||||
result += f"{proc_name.ljust(35)} NO METRICS FOUND\n" |
|
||||||
r = False |
|
||||||
result += "------------------------------------------------\n" |
|
||||||
print(result) |
|
||||||
return r |
|
||||||
|
|
||||||
def test_cpu_usage(): |
|
||||||
cpu_ok = False |
|
||||||
|
|
||||||
# start manager |
|
||||||
os.environ['SKIP_FW_QUERY'] = "1" |
|
||||||
os.environ['FINGERPRINT'] = "TOYOTA COROLLA TSS2 2019" |
|
||||||
manager_path = os.path.join(BASEDIR, "selfdrive/manager.py") |
|
||||||
manager_proc = subprocess.Popen(["python", manager_path]) |
|
||||||
try: |
|
||||||
proc_sock = messaging.sub_sock('procLog', conflate=True, timeout=2000) |
|
||||||
cs_sock = messaging.sub_sock('controlsState') |
|
||||||
|
|
||||||
# wait until everything's started |
|
||||||
msg = None |
|
||||||
start_time = time.monotonic() |
|
||||||
while msg is None and time.monotonic() - start_time < 240: |
|
||||||
msg = messaging.recv_sock(cs_sock) |
|
||||||
|
|
||||||
# take first sample |
|
||||||
time.sleep(15) |
|
||||||
first_proc = messaging.recv_sock(proc_sock, wait=True) |
|
||||||
if first_proc is None: |
|
||||||
raise Exception("\n\nTEST FAILED: progLog recv timed out\n\n") |
|
||||||
|
|
||||||
# run for a minute and get last sample |
|
||||||
time.sleep(60) |
|
||||||
last_proc = messaging.recv_sock(proc_sock, wait=True) |
|
||||||
cpu_ok = print_cpu_usage(first_proc, last_proc) |
|
||||||
finally: |
|
||||||
manager_proc.terminate() |
|
||||||
ret = manager_proc.wait(20) |
|
||||||
if ret is None: |
|
||||||
manager_proc.kill() |
|
||||||
return cpu_ok |
|
||||||
|
|
||||||
if __name__ == "__main__": |
|
||||||
set_params_enabled() |
|
||||||
|
|
||||||
passed = False |
|
||||||
try: |
|
||||||
passed = test_cpu_usage() |
|
||||||
except Exception as e: |
|
||||||
print("\n\n\n", "TEST FAILED:", str(e), "\n\n\n") |
|
||||||
finally: |
|
||||||
sys.exit(int(not passed)) |
|
@ -0,0 +1,112 @@ |
|||||||
|
#!/usr/bin/env python3 |
||||||
|
import os |
||||||
|
import time |
||||||
|
import subprocess |
||||||
|
import unittest |
||||||
|
from pathlib import Path |
||||||
|
|
||||||
|
import cereal.messaging as messaging |
||||||
|
from common.basedir import BASEDIR |
||||||
|
from common.timeout import Timeout |
||||||
|
from selfdrive.loggerd.config import ROOT |
||||||
|
from selfdrive.test.helpers import set_params_enabled |
||||||
|
from tools.lib.logreader import LogReader |
||||||
|
|
||||||
|
PROCS = [ |
||||||
|
("selfdrive.controls.controlsd", 47.0), |
||||||
|
("./loggerd", 45.0), |
||||||
|
("selfdrive.locationd.locationd", 35.0), |
||||||
|
("selfdrive.controls.plannerd", 20.0), |
||||||
|
("selfdrive.locationd.paramsd", 12.0), |
||||||
|
("./_modeld", 7.12), |
||||||
|
("./camerad", 7.07), |
||||||
|
("./_sensord", 6.17), |
||||||
|
("./_ui", 5.82), |
||||||
|
("selfdrive.controls.radard", 5.67), |
||||||
|
("./boardd", 3.63), |
||||||
|
("./_dmonitoringmodeld", 2.67), |
||||||
|
("selfdrive.logmessaged", 1.7), |
||||||
|
("selfdrive.thermald.thermald", 2.41), |
||||||
|
("selfdrive.locationd.calibrationd", 2.0), |
||||||
|
("selfdrive.monitoring.dmonitoringd", 1.90), |
||||||
|
("./proclogd", 1.54), |
||||||
|
("./_gpsd", 0.09), |
||||||
|
("./clocksd", 0.02), |
||||||
|
("./ubloxd", 0.02), |
||||||
|
("selfdrive.tombstoned", 0), |
||||||
|
("./logcatd", 0), |
||||||
|
] |
||||||
|
|
||||||
|
# ***** test helpers ***** |
||||||
|
|
||||||
|
def cputime_total(ct): |
||||||
|
return ct.cpuUser + ct.cpuSystem + ct.cpuChildrenUser + ct.cpuChildrenSystem |
||||||
|
|
||||||
|
def check_cpu_usage(first_proc, last_proc): |
||||||
|
result = "------------------------------------------------\n" |
||||||
|
result += "------------------ CPU Usage -------------------\n" |
||||||
|
result += "------------------------------------------------\n" |
||||||
|
|
||||||
|
r = True |
||||||
|
dt = (last_proc.logMonoTime - first_proc.logMonoTime) / 1e9 |
||||||
|
for proc_name, normal_cpu_usage in PROCS: |
||||||
|
first, last = None, None |
||||||
|
try: |
||||||
|
first = [p for p in first_proc.procLog.procs if proc_name in p.cmdline][0] |
||||||
|
last = [p for p in last_proc.procLog.procs if proc_name in p.cmdline][0] |
||||||
|
cpu_time = cputime_total(last) - cputime_total(first) |
||||||
|
cpu_usage = cpu_time / dt * 100. |
||||||
|
if cpu_usage > max(normal_cpu_usage * 1.1, normal_cpu_usage + 5.0): |
||||||
|
result += f"Warning {proc_name} using more CPU than normal\n" |
||||||
|
r = False |
||||||
|
elif cpu_usage < min(normal_cpu_usage * 0.65, max(normal_cpu_usage - 1.0, 0.0)): |
||||||
|
result += f"Warning {proc_name} using less CPU than normal\n" |
||||||
|
r = False |
||||||
|
result += f"{proc_name.ljust(35)} {cpu_usage:.2f}%\n" |
||||||
|
except IndexError: |
||||||
|
result += f"{proc_name.ljust(35)} NO METRICS FOUND {first=} {last=}\n" |
||||||
|
r = False |
||||||
|
result += "------------------------------------------------\n" |
||||||
|
print(result) |
||||||
|
return r |
||||||
|
|
||||||
|
|
||||||
|
class TestOnroad(unittest.TestCase): |
||||||
|
|
||||||
|
@classmethod |
||||||
|
def setUpClass(cls): |
||||||
|
os.environ['SKIP_FW_QUERY'] = "1" |
||||||
|
os.environ['FINGERPRINT'] = "TOYOTA COROLLA TSS2 2019" |
||||||
|
set_params_enabled() |
||||||
|
|
||||||
|
initial_segments = set(Path(ROOT).iterdir()) |
||||||
|
|
||||||
|
# start manager and run openpilot for a minute |
||||||
|
try: |
||||||
|
manager_path = os.path.join(BASEDIR, "selfdrive/manager.py") |
||||||
|
proc = subprocess.Popen(["python", manager_path]) |
||||||
|
|
||||||
|
sm = messaging.SubMaster(['carState']) |
||||||
|
with Timeout(60, "controls didn't start"): |
||||||
|
while not sm.updated['carState']: |
||||||
|
sm.update(1000) |
||||||
|
|
||||||
|
time.sleep(60) |
||||||
|
finally: |
||||||
|
proc.terminate() |
||||||
|
if proc.wait(20) is None: |
||||||
|
proc.kill() |
||||||
|
|
||||||
|
new_segments = set(Path(ROOT).iterdir()) - initial_segments |
||||||
|
|
||||||
|
segments = [p for p in new_segments if len(list(p.iterdir())) > 1] |
||||||
|
cls.segment = [s for s in segments if str(s).endswith("--0")][0] |
||||||
|
cls.lr = list(LogReader(os.path.join(str(cls.segment), "rlog.bz2"))) |
||||||
|
|
||||||
|
def test_cpu_usage(self): |
||||||
|
proclogs = [m for m in self.lr if m.which() == 'procLog'] |
||||||
|
cpu_ok = check_cpu_usage(proclogs[5], proclogs[-3]) |
||||||
|
self.assertTrue(cpu_ok) |
||||||
|
|
||||||
|
if __name__ == "__main__": |
||||||
|
unittest.main() |
@ -1,86 +0,0 @@ |
|||||||
#!/usr/bin/env python3 |
|
||||||
import errno |
|
||||||
import fcntl |
|
||||||
import os |
|
||||||
import signal |
|
||||||
import subprocess |
|
||||||
import sys |
|
||||||
import time |
|
||||||
|
|
||||||
import requests |
|
||||||
|
|
||||||
from common.params import Params |
|
||||||
from common.timeout import Timeout |
|
||||||
|
|
||||||
HOST = "testing.comma.life" |
|
||||||
|
|
||||||
|
|
||||||
def unblock_stdout(): |
|
||||||
# get a non-blocking stdout |
|
||||||
child_pid, child_pty = os.forkpty() |
|
||||||
if child_pid != 0: # parent |
|
||||||
|
|
||||||
# child is in its own process group, manually pass kill signals |
|
||||||
signal.signal(signal.SIGINT, lambda signum, frame: os.kill(child_pid, signal.SIGINT)) |
|
||||||
signal.signal(signal.SIGTERM, lambda signum, frame: os.kill(child_pid, signal.SIGTERM)) |
|
||||||
|
|
||||||
fcntl.fcntl(sys.stdout, fcntl.F_SETFL, fcntl.fcntl(sys.stdout, fcntl.F_GETFL) | os.O_NONBLOCK) |
|
||||||
|
|
||||||
while True: |
|
||||||
try: |
|
||||||
dat = os.read(child_pty, 4096) |
|
||||||
except OSError as e: |
|
||||||
if e.errno == errno.EIO: |
|
||||||
break |
|
||||||
continue |
|
||||||
|
|
||||||
if not dat: |
|
||||||
break |
|
||||||
|
|
||||||
try: |
|
||||||
sys.stdout.write(dat.decode('utf8')) |
|
||||||
except (OSError, IOError, UnicodeDecodeError): |
|
||||||
pass |
|
||||||
|
|
||||||
# os.wait() returns a tuple with the pid and a 16 bit value |
|
||||||
# whose low byte is the signal number and whose high byte is the exit satus |
|
||||||
exit_status = os.wait()[1] >> 8 |
|
||||||
os._exit(exit_status) |
|
||||||
|
|
||||||
|
|
||||||
def heartbeat(): |
|
||||||
work_dir = '/data/openpilot' |
|
||||||
|
|
||||||
while True: |
|
||||||
try: |
|
||||||
with open(os.path.join(work_dir, "selfdrive", "common", "version.h")) as _versionf: |
|
||||||
version = _versionf.read().split('"')[1] |
|
||||||
|
|
||||||
tmux = "" |
|
||||||
|
|
||||||
# try: |
|
||||||
# tmux = os.popen('tail -n 100 /tmp/tmux_out').read() |
|
||||||
# except Exception: |
|
||||||
# pass |
|
||||||
|
|
||||||
params = Params() |
|
||||||
msg = { |
|
||||||
'version': version, |
|
||||||
'dongle_id': params.get("DongleId").rstrip().decode('utf8'), |
|
||||||
'remote': subprocess.check_output(["git", "config", "--get", "remote.origin.url"], cwd=work_dir).decode('utf8').rstrip(), |
|
||||||
'branch': subprocess.check_output(["git", "rev-parse", "--abbrev-ref", "HEAD"], cwd=work_dir).decode('utf8').rstrip(), |
|
||||||
'revision': subprocess.check_output(["git", "rev-parse", "HEAD"], cwd=work_dir).decode('utf8').rstrip(), |
|
||||||
'serial': subprocess.check_output(["getprop", "ro.boot.serialno"]).decode('utf8').rstrip(), |
|
||||||
'tmux': tmux, |
|
||||||
} |
|
||||||
with Timeout(10): |
|
||||||
requests.post('http://%s/eon/heartbeat/' % HOST, json=msg, timeout=5.0) |
|
||||||
except Exception as e: |
|
||||||
print("Unable to send heartbeat", e) |
|
||||||
|
|
||||||
time.sleep(5) |
|
||||||
|
|
||||||
|
|
||||||
if __name__ == "__main__": |
|
||||||
unblock_stdout() |
|
||||||
heartbeat() |
|
@ -0,0 +1,127 @@ |
|||||||
|
#include <QDateTime> |
||||||
|
#include <QDebug> |
||||||
|
#include <QFile> |
||||||
|
#include <QJsonDocument> |
||||||
|
#include <QJsonObject> |
||||||
|
#include <QNetworkReply> |
||||||
|
#include <QNetworkRequest> |
||||||
|
#include <QString> |
||||||
|
#include <QWidget> |
||||||
|
#include <QTimer> |
||||||
|
#include <QRandomGenerator> |
||||||
|
#include "api.hpp" |
||||||
|
#include "home.hpp" |
||||||
|
#include "common/params.h" |
||||||
|
#include "common/util.h" |
||||||
|
#if defined(QCOM) || defined(QCOM2) |
||||||
|
const std::string private_key_path = "/persist/comma/id_rsa"; |
||||||
|
#else |
||||||
|
const std::string private_key_path = util::getenv_default("HOME", "/.comma/persist/comma/id_rsa", "/persist/comma/id_rsa"); |
||||||
|
#endif |
||||||
|
|
||||||
|
QByteArray CommaApi::rsa_sign(QByteArray data) { |
||||||
|
auto file = QFile(private_key_path.c_str()); |
||||||
|
if (!file.open(QIODevice::ReadOnly)) { |
||||||
|
qDebug() << "No RSA private key found, please run manager.py or registration.py"; |
||||||
|
return QByteArray(); |
||||||
|
} |
||||||
|
auto key = file.readAll(); |
||||||
|
file.close(); |
||||||
|
file.deleteLater(); |
||||||
|
BIO* mem = BIO_new_mem_buf(key.data(), key.size()); |
||||||
|
assert(mem); |
||||||
|
RSA* rsa_private = PEM_read_bio_RSAPrivateKey(mem, NULL, NULL, NULL); |
||||||
|
assert(rsa_private); |
||||||
|
auto sig = QByteArray(); |
||||||
|
sig.resize(RSA_size(rsa_private)); |
||||||
|
unsigned int sig_len; |
||||||
|
int ret = RSA_sign(NID_sha256, (unsigned char*)data.data(), data.size(), (unsigned char*)sig.data(), &sig_len, rsa_private); |
||||||
|
assert(ret == 1); |
||||||
|
assert(sig_len == sig.size()); |
||||||
|
BIO_free(mem); |
||||||
|
RSA_free(rsa_private); |
||||||
|
return sig; |
||||||
|
} |
||||||
|
|
||||||
|
QString CommaApi::create_jwt(QVector<QPair<QString, QJsonValue>> payloads, int expiry) { |
||||||
|
QJsonObject header; |
||||||
|
header.insert("alg", "RS256"); |
||||||
|
QJsonObject payload; |
||||||
|
QString dongle_id = QString::fromStdString(Params().get("DongleId")); |
||||||
|
payload.insert("identity", dongle_id); |
||||||
|
auto t = QDateTime::currentSecsSinceEpoch(); |
||||||
|
payload.insert("nbf", t); |
||||||
|
payload.insert("iat", t); |
||||||
|
payload.insert("exp", t + expiry); |
||||||
|
for (auto load : payloads) { |
||||||
|
payload.insert(load.first, load.second); |
||||||
|
} |
||||||
|
QString jwt = |
||||||
|
QJsonDocument(header).toJson(QJsonDocument::Compact).toBase64(QByteArray::Base64UrlEncoding | QByteArray::OmitTrailingEquals) + |
||||||
|
'.' + |
||||||
|
QJsonDocument(payload).toJson(QJsonDocument::Compact).toBase64(QByteArray::Base64UrlEncoding | QByteArray::OmitTrailingEquals); |
||||||
|
auto hash = QCryptographicHash::hash(jwt.toUtf8(), QCryptographicHash::Sha256); |
||||||
|
auto sig = rsa_sign(hash); |
||||||
|
jwt += '.' + sig.toBase64(QByteArray::Base64UrlEncoding | QByteArray::OmitTrailingEquals); |
||||||
|
return jwt; |
||||||
|
} |
||||||
|
|
||||||
|
QString CommaApi::create_jwt() { |
||||||
|
return create_jwt(*(new QVector<QPair<QString, QJsonValue>>())); |
||||||
|
} |
||||||
|
|
||||||
|
RequestRepeater::RequestRepeater(QWidget* parent, QString requestURL, int period_seconds, QVector<QPair<QString, QJsonValue>> payloads, bool disableWithScreen) |
||||||
|
: disableWithScreen(disableWithScreen) { |
||||||
|
networkAccessManager = new QNetworkAccessManager(parent); |
||||||
|
QTimer* timer = new QTimer(this); |
||||||
|
QObject::connect(timer, &QTimer::timeout, [=](){sendRequest(requestURL, payloads);}); |
||||||
|
timer->start(period_seconds * 1000); |
||||||
|
networkTimer = new QTimer(this); |
||||||
|
networkTimer->setSingleShot(true); |
||||||
|
networkTimer->setInterval(20000); // 20s before aborting
|
||||||
|
connect(networkTimer, SIGNAL(timeout()), this, SLOT(requestTimeout())); |
||||||
|
} |
||||||
|
|
||||||
|
void RequestRepeater::sendRequest(QString requestURL, QVector<QPair<QString, QJsonValue>> payloads){ |
||||||
|
// No network calls onroad
|
||||||
|
if(GLWindow::ui_state.started){ |
||||||
|
return; |
||||||
|
} |
||||||
|
if (!active || (!GLWindow::ui_state.awake && disableWithScreen)) { |
||||||
|
return; |
||||||
|
} |
||||||
|
if(reply != NULL){ |
||||||
|
return; |
||||||
|
} |
||||||
|
aborted = false; |
||||||
|
callId = QRandomGenerator::global()->bounded(1000); |
||||||
|
QString token = CommaApi::create_jwt(payloads); |
||||||
|
QNetworkRequest request; |
||||||
|
request.setUrl(QUrl(requestURL)); |
||||||
|
request.setRawHeader("Authorization", ("JWT " + token).toUtf8()); |
||||||
|
reply = networkAccessManager->get(request); |
||||||
|
networkTimer->start(); |
||||||
|
connect(reply, SIGNAL(finished()), this, SLOT(requestFinished())); |
||||||
|
} |
||||||
|
|
||||||
|
void RequestRepeater::requestTimeout(){ |
||||||
|
aborted = true; |
||||||
|
reply->abort(); |
||||||
|
} |
||||||
|
|
||||||
|
// This function should always emit something
|
||||||
|
void RequestRepeater::requestFinished(){ |
||||||
|
if(!aborted){ |
||||||
|
networkTimer->stop(); |
||||||
|
QString response = reply->readAll(); |
||||||
|
if (reply->error() == QNetworkReply::NoError) { |
||||||
|
emit receivedResponse(response); |
||||||
|
} else { |
||||||
|
emit failedResponse(reply->errorString()); |
||||||
|
} |
||||||
|
}else{ |
||||||
|
emit failedResponse("Custom Openpilot network timeout"); |
||||||
|
} |
||||||
|
reply->deleteLater(); |
||||||
|
reply = NULL; |
||||||
|
} |
@ -0,0 +1,47 @@ |
|||||||
|
#pragma once |
||||||
|
|
||||||
|
#include <QCryptographicHash> |
||||||
|
#include <QJsonValue> |
||||||
|
#include <QNetworkReply> |
||||||
|
#include <QNetworkRequest> |
||||||
|
#include <QPair> |
||||||
|
#include <QString> |
||||||
|
#include <QVector> |
||||||
|
#include <QWidget> |
||||||
|
#include <atomic> |
||||||
|
#include <openssl/bio.h> |
||||||
|
#include <openssl/pem.h> |
||||||
|
#include <openssl/rsa.h> |
||||||
|
class CommaApi : public QObject { |
||||||
|
Q_OBJECT |
||||||
|
public: |
||||||
|
static QByteArray rsa_sign(QByteArray data); |
||||||
|
static QString create_jwt(QVector<QPair<QString, QJsonValue>> payloads, int expiry = 60); |
||||||
|
static QString create_jwt(); |
||||||
|
private: |
||||||
|
QNetworkAccessManager* networkAccessManager; |
||||||
|
}; |
||||||
|
|
||||||
|
/**
|
||||||
|
* Makes repeated requests to the request endpoint. |
||||||
|
*/ |
||||||
|
class RequestRepeater : public QObject { |
||||||
|
Q_OBJECT |
||||||
|
public: |
||||||
|
explicit RequestRepeater(QWidget* parent, QString requestURL, int period = 10, QVector<QPair<QString, QJsonValue>> payloads = *(new QVector<QPair<QString, QJsonValue>>()), bool disableWithScreen = true); |
||||||
|
bool active = true; |
||||||
|
private: |
||||||
|
bool disableWithScreen; |
||||||
|
int callId; |
||||||
|
QNetworkReply* reply; |
||||||
|
QNetworkAccessManager* networkAccessManager; |
||||||
|
QTimer* networkTimer; |
||||||
|
std::atomic<bool> aborted = false; // Not 100% sure we need atomic
|
||||||
|
void sendRequest(QString requestURL, QVector<QPair<QString, QJsonValue>> payloads); |
||||||
|
private slots: |
||||||
|
void requestTimeout(); |
||||||
|
void requestFinished(); |
||||||
|
signals: |
||||||
|
void receivedResponse(QString response); |
||||||
|
void failedResponse(QString errorString); |
||||||
|
}; |
@ -0,0 +1,862 @@ |
|||||||
|
/*
|
||||||
|
* QR Code generator library (C++) |
||||||
|
*
|
||||||
|
* Copyright (c) Project Nayuki. (MIT License) |
||||||
|
* https://www.nayuki.io/page/qr-code-generator-library
|
||||||
|
*
|
||||||
|
* Permission is hereby granted, free of charge, to any person obtaining a copy of |
||||||
|
* this software and associated documentation files (the "Software"), to deal in |
||||||
|
* the Software without restriction, including without limitation the rights to |
||||||
|
* use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of |
||||||
|
* the Software, and to permit persons to whom the Software is furnished to do so, |
||||||
|
* subject to the following conditions: |
||||||
|
* - The above copyright notice and this permission notice shall be included in |
||||||
|
* all copies or substantial portions of the Software. |
||||||
|
* - The Software is provided "as is", without warranty of any kind, express or |
||||||
|
* implied, including but not limited to the warranties of merchantability, |
||||||
|
* fitness for a particular purpose and noninfringement. In no event shall the |
||||||
|
* authors or copyright holders be liable for any claim, damages or other |
||||||
|
* liability, whether in an action of contract, tort or otherwise, arising from, |
||||||
|
* out of or in connection with the Software or the use or other dealings in the |
||||||
|
* Software. |
||||||
|
*/ |
||||||
|
|
||||||
|
#include <algorithm> |
||||||
|
#include <climits> |
||||||
|
#include <cstddef> |
||||||
|
#include <cstdlib> |
||||||
|
#include <cstring> |
||||||
|
#include <sstream> |
||||||
|
#include <stdexcept> |
||||||
|
#include <utility> |
||||||
|
#include "QrCode.hpp" |
||||||
|
|
||||||
|
using std::int8_t; |
||||||
|
using std::uint8_t; |
||||||
|
using std::size_t; |
||||||
|
using std::vector; |
||||||
|
|
||||||
|
|
||||||
|
namespace qrcodegen { |
||||||
|
|
||||||
|
QrSegment::Mode::Mode(int mode, int cc0, int cc1, int cc2) : |
||||||
|
modeBits(mode) { |
||||||
|
numBitsCharCount[0] = cc0; |
||||||
|
numBitsCharCount[1] = cc1; |
||||||
|
numBitsCharCount[2] = cc2; |
||||||
|
} |
||||||
|
|
||||||
|
|
||||||
|
int QrSegment::Mode::getModeBits() const { |
||||||
|
return modeBits; |
||||||
|
} |
||||||
|
|
||||||
|
|
||||||
|
int QrSegment::Mode::numCharCountBits(int ver) const { |
||||||
|
return numBitsCharCount[(ver + 7) / 17]; |
||||||
|
} |
||||||
|
|
||||||
|
|
||||||
|
const QrSegment::Mode QrSegment::Mode::NUMERIC (0x1, 10, 12, 14); |
||||||
|
const QrSegment::Mode QrSegment::Mode::ALPHANUMERIC(0x2, 9, 11, 13); |
||||||
|
const QrSegment::Mode QrSegment::Mode::BYTE (0x4, 8, 16, 16); |
||||||
|
const QrSegment::Mode QrSegment::Mode::KANJI (0x8, 8, 10, 12); |
||||||
|
const QrSegment::Mode QrSegment::Mode::ECI (0x7, 0, 0, 0); |
||||||
|
|
||||||
|
|
||||||
|
QrSegment QrSegment::makeBytes(const vector<uint8_t> &data) { |
||||||
|
if (data.size() > static_cast<unsigned int>(INT_MAX)) |
||||||
|
throw std::length_error("Data too long"); |
||||||
|
BitBuffer bb; |
||||||
|
for (uint8_t b : data) |
||||||
|
bb.appendBits(b, 8); |
||||||
|
return QrSegment(Mode::BYTE, static_cast<int>(data.size()), std::move(bb)); |
||||||
|
} |
||||||
|
|
||||||
|
|
||||||
|
QrSegment QrSegment::makeNumeric(const char *digits) { |
||||||
|
BitBuffer bb; |
||||||
|
int accumData = 0; |
||||||
|
int accumCount = 0; |
||||||
|
int charCount = 0; |
||||||
|
for (; *digits != '\0'; digits++, charCount++) { |
||||||
|
char c = *digits; |
||||||
|
if (c < '0' || c > '9') |
||||||
|
throw std::domain_error("String contains non-numeric characters"); |
||||||
|
accumData = accumData * 10 + (c - '0'); |
||||||
|
accumCount++; |
||||||
|
if (accumCount == 3) { |
||||||
|
bb.appendBits(static_cast<uint32_t>(accumData), 10); |
||||||
|
accumData = 0; |
||||||
|
accumCount = 0; |
||||||
|
} |
||||||
|
} |
||||||
|
if (accumCount > 0) // 1 or 2 digits remaining
|
||||||
|
bb.appendBits(static_cast<uint32_t>(accumData), accumCount * 3 + 1); |
||||||
|
return QrSegment(Mode::NUMERIC, charCount, std::move(bb)); |
||||||
|
} |
||||||
|
|
||||||
|
|
||||||
|
QrSegment QrSegment::makeAlphanumeric(const char *text) { |
||||||
|
BitBuffer bb; |
||||||
|
int accumData = 0; |
||||||
|
int accumCount = 0; |
||||||
|
int charCount = 0; |
||||||
|
for (; *text != '\0'; text++, charCount++) { |
||||||
|
const char *temp = std::strchr(ALPHANUMERIC_CHARSET, *text); |
||||||
|
if (temp == nullptr) |
||||||
|
throw std::domain_error("String contains unencodable characters in alphanumeric mode"); |
||||||
|
accumData = accumData * 45 + static_cast<int>(temp - ALPHANUMERIC_CHARSET); |
||||||
|
accumCount++; |
||||||
|
if (accumCount == 2) { |
||||||
|
bb.appendBits(static_cast<uint32_t>(accumData), 11); |
||||||
|
accumData = 0; |
||||||
|
accumCount = 0; |
||||||
|
} |
||||||
|
} |
||||||
|
if (accumCount > 0) // 1 character remaining
|
||||||
|
bb.appendBits(static_cast<uint32_t>(accumData), 6); |
||||||
|
return QrSegment(Mode::ALPHANUMERIC, charCount, std::move(bb)); |
||||||
|
} |
||||||
|
|
||||||
|
|
||||||
|
vector<QrSegment> QrSegment::makeSegments(const char *text) { |
||||||
|
// Select the most efficient segment encoding automatically
|
||||||
|
vector<QrSegment> result; |
||||||
|
if (*text == '\0'); // Leave result empty
|
||||||
|
else if (isNumeric(text)) |
||||||
|
result.push_back(makeNumeric(text)); |
||||||
|
else if (isAlphanumeric(text)) |
||||||
|
result.push_back(makeAlphanumeric(text)); |
||||||
|
else { |
||||||
|
vector<uint8_t> bytes; |
||||||
|
for (; *text != '\0'; text++) |
||||||
|
bytes.push_back(static_cast<uint8_t>(*text)); |
||||||
|
result.push_back(makeBytes(bytes)); |
||||||
|
} |
||||||
|
return result; |
||||||
|
} |
||||||
|
|
||||||
|
|
||||||
|
QrSegment QrSegment::makeEci(long assignVal) { |
||||||
|
BitBuffer bb; |
||||||
|
if (assignVal < 0) |
||||||
|
throw std::domain_error("ECI assignment value out of range"); |
||||||
|
else if (assignVal < (1 << 7)) |
||||||
|
bb.appendBits(static_cast<uint32_t>(assignVal), 8); |
||||||
|
else if (assignVal < (1 << 14)) { |
||||||
|
bb.appendBits(2, 2); |
||||||
|
bb.appendBits(static_cast<uint32_t>(assignVal), 14); |
||||||
|
} else if (assignVal < 1000000L) { |
||||||
|
bb.appendBits(6, 3); |
||||||
|
bb.appendBits(static_cast<uint32_t>(assignVal), 21); |
||||||
|
} else |
||||||
|
throw std::domain_error("ECI assignment value out of range"); |
||||||
|
return QrSegment(Mode::ECI, 0, std::move(bb)); |
||||||
|
} |
||||||
|
|
||||||
|
|
||||||
|
QrSegment::QrSegment(Mode md, int numCh, const std::vector<bool> &dt) : |
||||||
|
mode(md), |
||||||
|
numChars(numCh), |
||||||
|
data(dt) { |
||||||
|
if (numCh < 0) |
||||||
|
throw std::domain_error("Invalid value"); |
||||||
|
} |
||||||
|
|
||||||
|
|
||||||
|
QrSegment::QrSegment(Mode md, int numCh, std::vector<bool> &&dt) : |
||||||
|
mode(md), |
||||||
|
numChars(numCh), |
||||||
|
data(std::move(dt)) { |
||||||
|
if (numCh < 0) |
||||||
|
throw std::domain_error("Invalid value"); |
||||||
|
} |
||||||
|
|
||||||
|
|
||||||
|
int QrSegment::getTotalBits(const vector<QrSegment> &segs, int version) { |
||||||
|
int result = 0; |
||||||
|
for (const QrSegment &seg : segs) { |
||||||
|
int ccbits = seg.mode.numCharCountBits(version); |
||||||
|
if (seg.numChars >= (1L << ccbits)) |
||||||
|
return -1; // The segment's length doesn't fit the field's bit width
|
||||||
|
if (4 + ccbits > INT_MAX - result) |
||||||
|
return -1; // The sum will overflow an int type
|
||||||
|
result += 4 + ccbits; |
||||||
|
if (seg.data.size() > static_cast<unsigned int>(INT_MAX - result)) |
||||||
|
return -1; // The sum will overflow an int type
|
||||||
|
result += static_cast<int>(seg.data.size()); |
||||||
|
} |
||||||
|
return result; |
||||||
|
} |
||||||
|
|
||||||
|
|
||||||
|
bool QrSegment::isAlphanumeric(const char *text) { |
||||||
|
for (; *text != '\0'; text++) { |
||||||
|
if (std::strchr(ALPHANUMERIC_CHARSET, *text) == nullptr) |
||||||
|
return false; |
||||||
|
} |
||||||
|
return true; |
||||||
|
} |
||||||
|
|
||||||
|
|
||||||
|
bool QrSegment::isNumeric(const char *text) { |
||||||
|
for (; *text != '\0'; text++) { |
||||||
|
char c = *text; |
||||||
|
if (c < '0' || c > '9') |
||||||
|
return false; |
||||||
|
} |
||||||
|
return true; |
||||||
|
} |
||||||
|
|
||||||
|
|
||||||
|
QrSegment::Mode QrSegment::getMode() const { |
||||||
|
return mode; |
||||||
|
} |
||||||
|
|
||||||
|
|
||||||
|
int QrSegment::getNumChars() const { |
||||||
|
return numChars; |
||||||
|
} |
||||||
|
|
||||||
|
|
||||||
|
const std::vector<bool> &QrSegment::getData() const { |
||||||
|
return data; |
||||||
|
} |
||||||
|
|
||||||
|
|
||||||
|
const char *QrSegment::ALPHANUMERIC_CHARSET = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ $%*+-./:"; |
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
int QrCode::getFormatBits(Ecc ecl) { |
||||||
|
switch (ecl) { |
||||||
|
case Ecc::LOW : return 1; |
||||||
|
case Ecc::MEDIUM : return 0; |
||||||
|
case Ecc::QUARTILE: return 3; |
||||||
|
case Ecc::HIGH : return 2; |
||||||
|
default: throw std::logic_error("Assertion error"); |
||||||
|
} |
||||||
|
} |
||||||
|
|
||||||
|
|
||||||
|
QrCode QrCode::encodeText(const char *text, Ecc ecl) { |
||||||
|
vector<QrSegment> segs = QrSegment::makeSegments(text); |
||||||
|
return encodeSegments(segs, ecl); |
||||||
|
} |
||||||
|
|
||||||
|
|
||||||
|
QrCode QrCode::encodeBinary(const vector<uint8_t> &data, Ecc ecl) { |
||||||
|
vector<QrSegment> segs{QrSegment::makeBytes(data)}; |
||||||
|
return encodeSegments(segs, ecl); |
||||||
|
} |
||||||
|
|
||||||
|
|
||||||
|
QrCode QrCode::encodeSegments(const vector<QrSegment> &segs, Ecc ecl, |
||||||
|
int minVersion, int maxVersion, int mask, bool boostEcl) { |
||||||
|
if (!(MIN_VERSION <= minVersion && minVersion <= maxVersion && maxVersion <= MAX_VERSION) || mask < -1 || mask > 7) |
||||||
|
throw std::invalid_argument("Invalid value"); |
||||||
|
|
||||||
|
// Find the minimal version number to use
|
||||||
|
int version, dataUsedBits; |
||||||
|
for (version = minVersion; ; version++) { |
||||||
|
int dataCapacityBits = getNumDataCodewords(version, ecl) * 8; // Number of data bits available
|
||||||
|
dataUsedBits = QrSegment::getTotalBits(segs, version); |
||||||
|
if (dataUsedBits != -1 && dataUsedBits <= dataCapacityBits) |
||||||
|
break; // This version number is found to be suitable
|
||||||
|
if (version >= maxVersion) { // All versions in the range could not fit the given data
|
||||||
|
std::ostringstream sb; |
||||||
|
if (dataUsedBits == -1) |
||||||
|
sb << "Segment too long"; |
||||||
|
else { |
||||||
|
sb << "Data length = " << dataUsedBits << " bits, "; |
||||||
|
sb << "Max capacity = " << dataCapacityBits << " bits"; |
||||||
|
} |
||||||
|
throw data_too_long(sb.str()); |
||||||
|
} |
||||||
|
} |
||||||
|
if (dataUsedBits == -1) |
||||||
|
throw std::logic_error("Assertion error"); |
||||||
|
|
||||||
|
// Increase the error correction level while the data still fits in the current version number
|
||||||
|
for (Ecc newEcl : vector<Ecc>{Ecc::MEDIUM, Ecc::QUARTILE, Ecc::HIGH}) { // From low to high
|
||||||
|
if (boostEcl && dataUsedBits <= getNumDataCodewords(version, newEcl) * 8) |
||||||
|
ecl = newEcl; |
||||||
|
} |
||||||
|
|
||||||
|
// Concatenate all segments to create the data bit string
|
||||||
|
BitBuffer bb; |
||||||
|
for (const QrSegment &seg : segs) { |
||||||
|
bb.appendBits(static_cast<uint32_t>(seg.getMode().getModeBits()), 4); |
||||||
|
bb.appendBits(static_cast<uint32_t>(seg.getNumChars()), seg.getMode().numCharCountBits(version)); |
||||||
|
bb.insert(bb.end(), seg.getData().begin(), seg.getData().end()); |
||||||
|
} |
||||||
|
if (bb.size() != static_cast<unsigned int>(dataUsedBits)) |
||||||
|
throw std::logic_error("Assertion error"); |
||||||
|
|
||||||
|
// Add terminator and pad up to a byte if applicable
|
||||||
|
size_t dataCapacityBits = static_cast<size_t>(getNumDataCodewords(version, ecl)) * 8; |
||||||
|
if (bb.size() > dataCapacityBits) |
||||||
|
throw std::logic_error("Assertion error"); |
||||||
|
bb.appendBits(0, std::min(4, static_cast<int>(dataCapacityBits - bb.size()))); |
||||||
|
bb.appendBits(0, (8 - static_cast<int>(bb.size() % 8)) % 8); |
||||||
|
if (bb.size() % 8 != 0) |
||||||
|
throw std::logic_error("Assertion error"); |
||||||
|
|
||||||
|
// Pad with alternating bytes until data capacity is reached
|
||||||
|
for (uint8_t padByte = 0xEC; bb.size() < dataCapacityBits; padByte ^= 0xEC ^ 0x11) |
||||||
|
bb.appendBits(padByte, 8); |
||||||
|
|
||||||
|
// Pack bits into bytes in big endian
|
||||||
|
vector<uint8_t> dataCodewords(bb.size() / 8); |
||||||
|
for (size_t i = 0; i < bb.size(); i++) |
||||||
|
dataCodewords[i >> 3] |= (bb.at(i) ? 1 : 0) << (7 - (i & 7)); |
||||||
|
|
||||||
|
// Create the QR Code object
|
||||||
|
return QrCode(version, ecl, dataCodewords, mask); |
||||||
|
} |
||||||
|
|
||||||
|
|
||||||
|
QrCode::QrCode(int ver, Ecc ecl, const vector<uint8_t> &dataCodewords, int msk) : |
||||||
|
// Initialize fields and check arguments
|
||||||
|
version(ver), |
||||||
|
errorCorrectionLevel(ecl) { |
||||||
|
if (ver < MIN_VERSION || ver > MAX_VERSION) |
||||||
|
throw std::domain_error("Version value out of range"); |
||||||
|
if (msk < -1 || msk > 7) |
||||||
|
throw std::domain_error("Mask value out of range"); |
||||||
|
size = ver * 4 + 17; |
||||||
|
size_t sz = static_cast<size_t>(size); |
||||||
|
modules = vector<vector<bool> >(sz, vector<bool>(sz)); // Initially all white
|
||||||
|
isFunction = vector<vector<bool> >(sz, vector<bool>(sz)); |
||||||
|
|
||||||
|
// Compute ECC, draw modules
|
||||||
|
drawFunctionPatterns(); |
||||||
|
const vector<uint8_t> allCodewords = addEccAndInterleave(dataCodewords); |
||||||
|
drawCodewords(allCodewords); |
||||||
|
|
||||||
|
// Do masking
|
||||||
|
if (msk == -1) { // Automatically choose best mask
|
||||||
|
long minPenalty = LONG_MAX; |
||||||
|
for (int i = 0; i < 8; i++) { |
||||||
|
applyMask(i); |
||||||
|
drawFormatBits(i); |
||||||
|
long penalty = getPenaltyScore(); |
||||||
|
if (penalty < minPenalty) { |
||||||
|
msk = i; |
||||||
|
minPenalty = penalty; |
||||||
|
} |
||||||
|
applyMask(i); // Undoes the mask due to XOR
|
||||||
|
} |
||||||
|
} |
||||||
|
if (msk < 0 || msk > 7) |
||||||
|
throw std::logic_error("Assertion error"); |
||||||
|
this->mask = msk; |
||||||
|
applyMask(msk); // Apply the final choice of mask
|
||||||
|
drawFormatBits(msk); // Overwrite old format bits
|
||||||
|
|
||||||
|
isFunction.clear(); |
||||||
|
isFunction.shrink_to_fit(); |
||||||
|
} |
||||||
|
|
||||||
|
|
||||||
|
int QrCode::getVersion() const { |
||||||
|
return version; |
||||||
|
} |
||||||
|
|
||||||
|
|
||||||
|
int QrCode::getSize() const { |
||||||
|
return size; |
||||||
|
} |
||||||
|
|
||||||
|
|
||||||
|
QrCode::Ecc QrCode::getErrorCorrectionLevel() const { |
||||||
|
return errorCorrectionLevel; |
||||||
|
} |
||||||
|
|
||||||
|
|
||||||
|
int QrCode::getMask() const { |
||||||
|
return mask; |
||||||
|
} |
||||||
|
|
||||||
|
|
||||||
|
bool QrCode::getModule(int x, int y) const { |
||||||
|
return 0 <= x && x < size && 0 <= y && y < size && module(x, y); |
||||||
|
} |
||||||
|
|
||||||
|
|
||||||
|
std::string QrCode::toSvgString(int border) const { |
||||||
|
if (border < 0) |
||||||
|
throw std::domain_error("Border must be non-negative"); |
||||||
|
if (border > INT_MAX / 2 || border * 2 > INT_MAX - size) |
||||||
|
throw std::overflow_error("Border too large"); |
||||||
|
|
||||||
|
std::ostringstream sb; |
||||||
|
sb << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"; |
||||||
|
sb << "<!DOCTYPE svg PUBLIC \"-//W3C//DTD SVG 1.1//EN\" \"http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd\">\n"; |
||||||
|
sb << "<svg xmlns=\"http://www.w3.org/2000/svg\" version=\"1.1\" viewBox=\"0 0 "; |
||||||
|
sb << (size + border * 2) << " " << (size + border * 2) << "\" stroke=\"none\">\n"; |
||||||
|
sb << "\t<rect width=\"100%\" height=\"100%\" fill=\"#FFFFFF\"/>\n"; |
||||||
|
sb << "\t<path d=\""; |
||||||
|
for (int y = 0; y < size; y++) { |
||||||
|
for (int x = 0; x < size; x++) { |
||||||
|
if (getModule(x, y)) { |
||||||
|
if (x != 0 || y != 0) |
||||||
|
sb << " "; |
||||||
|
sb << "M" << (x + border) << "," << (y + border) << "h1v1h-1z"; |
||||||
|
} |
||||||
|
} |
||||||
|
} |
||||||
|
sb << "\" fill=\"#000000\"/>\n"; |
||||||
|
sb << "</svg>\n"; |
||||||
|
return sb.str(); |
||||||
|
} |
||||||
|
|
||||||
|
|
||||||
|
void QrCode::drawFunctionPatterns() { |
||||||
|
// Draw horizontal and vertical timing patterns
|
||||||
|
for (int i = 0; i < size; i++) { |
||||||
|
setFunctionModule(6, i, i % 2 == 0); |
||||||
|
setFunctionModule(i, 6, i % 2 == 0); |
||||||
|
} |
||||||
|
|
||||||
|
// Draw 3 finder patterns (all corners except bottom right; overwrites some timing modules)
|
||||||
|
drawFinderPattern(3, 3); |
||||||
|
drawFinderPattern(size - 4, 3); |
||||||
|
drawFinderPattern(3, size - 4); |
||||||
|
|
||||||
|
// Draw numerous alignment patterns
|
||||||
|
const vector<int> alignPatPos = getAlignmentPatternPositions(); |
||||||
|
size_t numAlign = alignPatPos.size(); |
||||||
|
for (size_t i = 0; i < numAlign; i++) { |
||||||
|
for (size_t j = 0; j < numAlign; j++) { |
||||||
|
// Don't draw on the three finder corners
|
||||||
|
if (!((i == 0 && j == 0) || (i == 0 && j == numAlign - 1) || (i == numAlign - 1 && j == 0))) |
||||||
|
drawAlignmentPattern(alignPatPos.at(i), alignPatPos.at(j)); |
||||||
|
} |
||||||
|
} |
||||||
|
|
||||||
|
// Draw configuration data
|
||||||
|
drawFormatBits(0); // Dummy mask value; overwritten later in the constructor
|
||||||
|
drawVersion(); |
||||||
|
} |
||||||
|
|
||||||
|
|
||||||
|
void QrCode::drawFormatBits(int msk) { |
||||||
|
// Calculate error correction code and pack bits
|
||||||
|
int data = getFormatBits(errorCorrectionLevel) << 3 | msk; // errCorrLvl is uint2, msk is uint3
|
||||||
|
int rem = data; |
||||||
|
for (int i = 0; i < 10; i++) |
||||||
|
rem = (rem << 1) ^ ((rem >> 9) * 0x537); |
||||||
|
int bits = (data << 10 | rem) ^ 0x5412; // uint15
|
||||||
|
if (bits >> 15 != 0) |
||||||
|
throw std::logic_error("Assertion error"); |
||||||
|
|
||||||
|
// Draw first copy
|
||||||
|
for (int i = 0; i <= 5; i++) |
||||||
|
setFunctionModule(8, i, getBit(bits, i)); |
||||||
|
setFunctionModule(8, 7, getBit(bits, 6)); |
||||||
|
setFunctionModule(8, 8, getBit(bits, 7)); |
||||||
|
setFunctionModule(7, 8, getBit(bits, 8)); |
||||||
|
for (int i = 9; i < 15; i++) |
||||||
|
setFunctionModule(14 - i, 8, getBit(bits, i)); |
||||||
|
|
||||||
|
// Draw second copy
|
||||||
|
for (int i = 0; i < 8; i++) |
||||||
|
setFunctionModule(size - 1 - i, 8, getBit(bits, i)); |
||||||
|
for (int i = 8; i < 15; i++) |
||||||
|
setFunctionModule(8, size - 15 + i, getBit(bits, i)); |
||||||
|
setFunctionModule(8, size - 8, true); // Always black
|
||||||
|
} |
||||||
|
|
||||||
|
|
||||||
|
void QrCode::drawVersion() { |
||||||
|
if (version < 7) |
||||||
|
return; |
||||||
|
|
||||||
|
// Calculate error correction code and pack bits
|
||||||
|
int rem = version; // version is uint6, in the range [7, 40]
|
||||||
|
for (int i = 0; i < 12; i++) |
||||||
|
rem = (rem << 1) ^ ((rem >> 11) * 0x1F25); |
||||||
|
long bits = static_cast<long>(version) << 12 | rem; // uint18
|
||||||
|
if (bits >> 18 != 0) |
||||||
|
throw std::logic_error("Assertion error"); |
||||||
|
|
||||||
|
// Draw two copies
|
||||||
|
for (int i = 0; i < 18; i++) { |
||||||
|
bool bit = getBit(bits, i); |
||||||
|
int a = size - 11 + i % 3; |
||||||
|
int b = i / 3; |
||||||
|
setFunctionModule(a, b, bit); |
||||||
|
setFunctionModule(b, a, bit); |
||||||
|
} |
||||||
|
} |
||||||
|
|
||||||
|
|
||||||
|
void QrCode::drawFinderPattern(int x, int y) { |
||||||
|
for (int dy = -4; dy <= 4; dy++) { |
||||||
|
for (int dx = -4; dx <= 4; dx++) { |
||||||
|
int dist = std::max(std::abs(dx), std::abs(dy)); // Chebyshev/infinity norm
|
||||||
|
int xx = x + dx, yy = y + dy; |
||||||
|
if (0 <= xx && xx < size && 0 <= yy && yy < size) |
||||||
|
setFunctionModule(xx, yy, dist != 2 && dist != 4); |
||||||
|
} |
||||||
|
} |
||||||
|
} |
||||||
|
|
||||||
|
|
||||||
|
void QrCode::drawAlignmentPattern(int x, int y) { |
||||||
|
for (int dy = -2; dy <= 2; dy++) { |
||||||
|
for (int dx = -2; dx <= 2; dx++) |
||||||
|
setFunctionModule(x + dx, y + dy, std::max(std::abs(dx), std::abs(dy)) != 1); |
||||||
|
} |
||||||
|
} |
||||||
|
|
||||||
|
|
||||||
|
void QrCode::setFunctionModule(int x, int y, bool isBlack) { |
||||||
|
size_t ux = static_cast<size_t>(x); |
||||||
|
size_t uy = static_cast<size_t>(y); |
||||||
|
modules .at(uy).at(ux) = isBlack; |
||||||
|
isFunction.at(uy).at(ux) = true; |
||||||
|
} |
||||||
|
|
||||||
|
|
||||||
|
bool QrCode::module(int x, int y) const { |
||||||
|
return modules.at(static_cast<size_t>(y)).at(static_cast<size_t>(x)); |
||||||
|
} |
||||||
|
|
||||||
|
|
||||||
|
vector<uint8_t> QrCode::addEccAndInterleave(const vector<uint8_t> &data) const { |
||||||
|
if (data.size() != static_cast<unsigned int>(getNumDataCodewords(version, errorCorrectionLevel))) |
||||||
|
throw std::invalid_argument("Invalid argument"); |
||||||
|
|
||||||
|
// Calculate parameter numbers
|
||||||
|
int numBlocks = NUM_ERROR_CORRECTION_BLOCKS[static_cast<int>(errorCorrectionLevel)][version]; |
||||||
|
int blockEccLen = ECC_CODEWORDS_PER_BLOCK [static_cast<int>(errorCorrectionLevel)][version]; |
||||||
|
int rawCodewords = getNumRawDataModules(version) / 8; |
||||||
|
int numShortBlocks = numBlocks - rawCodewords % numBlocks; |
||||||
|
int shortBlockLen = rawCodewords / numBlocks; |
||||||
|
|
||||||
|
// Split data into blocks and append ECC to each block
|
||||||
|
vector<vector<uint8_t> > blocks; |
||||||
|
const vector<uint8_t> rsDiv = reedSolomonComputeDivisor(blockEccLen); |
||||||
|
for (int i = 0, k = 0; i < numBlocks; i++) { |
||||||
|
vector<uint8_t> dat(data.cbegin() + k, data.cbegin() + (k + shortBlockLen - blockEccLen + (i < numShortBlocks ? 0 : 1))); |
||||||
|
k += static_cast<int>(dat.size()); |
||||||
|
const vector<uint8_t> ecc = reedSolomonComputeRemainder(dat, rsDiv); |
||||||
|
if (i < numShortBlocks) |
||||||
|
dat.push_back(0); |
||||||
|
dat.insert(dat.end(), ecc.cbegin(), ecc.cend()); |
||||||
|
blocks.push_back(std::move(dat)); |
||||||
|
} |
||||||
|
|
||||||
|
// Interleave (not concatenate) the bytes from every block into a single sequence
|
||||||
|
vector<uint8_t> result; |
||||||
|
for (size_t i = 0; i < blocks.at(0).size(); i++) { |
||||||
|
for (size_t j = 0; j < blocks.size(); j++) { |
||||||
|
// Skip the padding byte in short blocks
|
||||||
|
if (i != static_cast<unsigned int>(shortBlockLen - blockEccLen) || j >= static_cast<unsigned int>(numShortBlocks)) |
||||||
|
result.push_back(blocks.at(j).at(i)); |
||||||
|
} |
||||||
|
} |
||||||
|
if (result.size() != static_cast<unsigned int>(rawCodewords)) |
||||||
|
throw std::logic_error("Assertion error"); |
||||||
|
return result; |
||||||
|
} |
||||||
|
|
||||||
|
|
||||||
|
void QrCode::drawCodewords(const vector<uint8_t> &data) { |
||||||
|
if (data.size() != static_cast<unsigned int>(getNumRawDataModules(version) / 8)) |
||||||
|
throw std::invalid_argument("Invalid argument"); |
||||||
|
|
||||||
|
size_t i = 0; // Bit index into the data
|
||||||
|
// Do the funny zigzag scan
|
||||||
|
for (int right = size - 1; right >= 1; right -= 2) { // Index of right column in each column pair
|
||||||
|
if (right == 6) |
||||||
|
right = 5; |
||||||
|
for (int vert = 0; vert < size; vert++) { // Vertical counter
|
||||||
|
for (int j = 0; j < 2; j++) { |
||||||
|
size_t x = static_cast<size_t>(right - j); // Actual x coordinate
|
||||||
|
bool upward = ((right + 1) & 2) == 0; |
||||||
|
size_t y = static_cast<size_t>(upward ? size - 1 - vert : vert); // Actual y coordinate
|
||||||
|
if (!isFunction.at(y).at(x) && i < data.size() * 8) { |
||||||
|
modules.at(y).at(x) = getBit(data.at(i >> 3), 7 - static_cast<int>(i & 7)); |
||||||
|
i++; |
||||||
|
} |
||||||
|
// If this QR Code has any remainder bits (0 to 7), they were assigned as
|
||||||
|
// 0/false/white by the constructor and are left unchanged by this method
|
||||||
|
} |
||||||
|
} |
||||||
|
} |
||||||
|
if (i != data.size() * 8) |
||||||
|
throw std::logic_error("Assertion error"); |
||||||
|
} |
||||||
|
|
||||||
|
|
||||||
|
void QrCode::applyMask(int msk) { |
||||||
|
if (msk < 0 || msk > 7) |
||||||
|
throw std::domain_error("Mask value out of range"); |
||||||
|
size_t sz = static_cast<size_t>(size); |
||||||
|
for (size_t y = 0; y < sz; y++) { |
||||||
|
for (size_t x = 0; x < sz; x++) { |
||||||
|
bool invert; |
||||||
|
switch (msk) { |
||||||
|
case 0: invert = (x + y) % 2 == 0; break; |
||||||
|
case 1: invert = y % 2 == 0; break; |
||||||
|
case 2: invert = x % 3 == 0; break; |
||||||
|
case 3: invert = (x + y) % 3 == 0; break; |
||||||
|
case 4: invert = (x / 3 + y / 2) % 2 == 0; break; |
||||||
|
case 5: invert = x * y % 2 + x * y % 3 == 0; break; |
||||||
|
case 6: invert = (x * y % 2 + x * y % 3) % 2 == 0; break; |
||||||
|
case 7: invert = ((x + y) % 2 + x * y % 3) % 2 == 0; break; |
||||||
|
default: throw std::logic_error("Assertion error"); |
||||||
|
} |
||||||
|
modules.at(y).at(x) = modules.at(y).at(x) ^ (invert & !isFunction.at(y).at(x)); |
||||||
|
} |
||||||
|
} |
||||||
|
} |
||||||
|
|
||||||
|
|
||||||
|
long QrCode::getPenaltyScore() const { |
||||||
|
long result = 0; |
||||||
|
|
||||||
|
// Adjacent modules in row having same color, and finder-like patterns
|
||||||
|
for (int y = 0; y < size; y++) { |
||||||
|
bool runColor = false; |
||||||
|
int runX = 0; |
||||||
|
std::array<int,7> runHistory = {}; |
||||||
|
for (int x = 0; x < size; x++) { |
||||||
|
if (module(x, y) == runColor) { |
||||||
|
runX++; |
||||||
|
if (runX == 5) |
||||||
|
result += PENALTY_N1; |
||||||
|
else if (runX > 5) |
||||||
|
result++; |
||||||
|
} else { |
||||||
|
finderPenaltyAddHistory(runX, runHistory); |
||||||
|
if (!runColor) |
||||||
|
result += finderPenaltyCountPatterns(runHistory) * PENALTY_N3; |
||||||
|
runColor = module(x, y); |
||||||
|
runX = 1; |
||||||
|
} |
||||||
|
} |
||||||
|
result += finderPenaltyTerminateAndCount(runColor, runX, runHistory) * PENALTY_N3; |
||||||
|
} |
||||||
|
// Adjacent modules in column having same color, and finder-like patterns
|
||||||
|
for (int x = 0; x < size; x++) { |
||||||
|
bool runColor = false; |
||||||
|
int runY = 0; |
||||||
|
std::array<int,7> runHistory = {}; |
||||||
|
for (int y = 0; y < size; y++) { |
||||||
|
if (module(x, y) == runColor) { |
||||||
|
runY++; |
||||||
|
if (runY == 5) |
||||||
|
result += PENALTY_N1; |
||||||
|
else if (runY > 5) |
||||||
|
result++; |
||||||
|
} else { |
||||||
|
finderPenaltyAddHistory(runY, runHistory); |
||||||
|
if (!runColor) |
||||||
|
result += finderPenaltyCountPatterns(runHistory) * PENALTY_N3; |
||||||
|
runColor = module(x, y); |
||||||
|
runY = 1; |
||||||
|
} |
||||||
|
} |
||||||
|
result += finderPenaltyTerminateAndCount(runColor, runY, runHistory) * PENALTY_N3; |
||||||
|
} |
||||||
|
|
||||||
|
// 2*2 blocks of modules having same color
|
||||||
|
for (int y = 0; y < size - 1; y++) { |
||||||
|
for (int x = 0; x < size - 1; x++) { |
||||||
|
bool color = module(x, y); |
||||||
|
if ( color == module(x + 1, y) && |
||||||
|
color == module(x, y + 1) && |
||||||
|
color == module(x + 1, y + 1)) |
||||||
|
result += PENALTY_N2; |
||||||
|
} |
||||||
|
} |
||||||
|
|
||||||
|
// Balance of black and white modules
|
||||||
|
int black = 0; |
||||||
|
for (const vector<bool> &row : modules) { |
||||||
|
for (bool color : row) { |
||||||
|
if (color) |
||||||
|
black++; |
||||||
|
} |
||||||
|
} |
||||||
|
int total = size * size; // Note that size is odd, so black/total != 1/2
|
||||||
|
// Compute the smallest integer k >= 0 such that (45-5k)% <= black/total <= (55+5k)%
|
||||||
|
int k = static_cast<int>((std::abs(black * 20L - total * 10L) + total - 1) / total) - 1; |
||||||
|
result += k * PENALTY_N4; |
||||||
|
return result; |
||||||
|
} |
||||||
|
|
||||||
|
|
||||||
|
vector<int> QrCode::getAlignmentPatternPositions() const { |
||||||
|
if (version == 1) |
||||||
|
return vector<int>(); |
||||||
|
else { |
||||||
|
int numAlign = version / 7 + 2; |
||||||
|
int step = (version == 32) ? 26 : |
||||||
|
(version*4 + numAlign*2 + 1) / (numAlign*2 - 2) * 2; |
||||||
|
vector<int> result; |
||||||
|
for (int i = 0, pos = size - 7; i < numAlign - 1; i++, pos -= step) |
||||||
|
result.insert(result.begin(), pos); |
||||||
|
result.insert(result.begin(), 6); |
||||||
|
return result; |
||||||
|
} |
||||||
|
} |
||||||
|
|
||||||
|
|
||||||
|
int QrCode::getNumRawDataModules(int ver) { |
||||||
|
if (ver < MIN_VERSION || ver > MAX_VERSION) |
||||||
|
throw std::domain_error("Version number out of range"); |
||||||
|
int result = (16 * ver + 128) * ver + 64; |
||||||
|
if (ver >= 2) { |
||||||
|
int numAlign = ver / 7 + 2; |
||||||
|
result -= (25 * numAlign - 10) * numAlign - 55; |
||||||
|
if (ver >= 7) |
||||||
|
result -= 36; |
||||||
|
} |
||||||
|
if (!(208 <= result && result <= 29648)) |
||||||
|
throw std::logic_error("Assertion error"); |
||||||
|
return result; |
||||||
|
} |
||||||
|
|
||||||
|
|
||||||
|
int QrCode::getNumDataCodewords(int ver, Ecc ecl) { |
||||||
|
return getNumRawDataModules(ver) / 8 |
||||||
|
- ECC_CODEWORDS_PER_BLOCK [static_cast<int>(ecl)][ver] |
||||||
|
* NUM_ERROR_CORRECTION_BLOCKS[static_cast<int>(ecl)][ver]; |
||||||
|
} |
||||||
|
|
||||||
|
|
||||||
|
vector<uint8_t> QrCode::reedSolomonComputeDivisor(int degree) { |
||||||
|
if (degree < 1 || degree > 255) |
||||||
|
throw std::domain_error("Degree out of range"); |
||||||
|
// Polynomial coefficients are stored from highest to lowest power, excluding the leading term which is always 1.
|
||||||
|
// For example the polynomial x^3 + 255x^2 + 8x + 93 is stored as the uint8 array {255, 8, 93}.
|
||||||
|
vector<uint8_t> result(static_cast<size_t>(degree)); |
||||||
|
result.at(result.size() - 1) = 1; // Start off with the monomial x^0
|
||||||
|
|
||||||
|
// Compute the product polynomial (x - r^0) * (x - r^1) * (x - r^2) * ... * (x - r^{degree-1}),
|
||||||
|
// and drop the highest monomial term which is always 1x^degree.
|
||||||
|
// Note that r = 0x02, which is a generator element of this field GF(2^8/0x11D).
|
||||||
|
uint8_t root = 1; |
||||||
|
for (int i = 0; i < degree; i++) { |
||||||
|
// Multiply the current product by (x - r^i)
|
||||||
|
for (size_t j = 0; j < result.size(); j++) { |
||||||
|
result.at(j) = reedSolomonMultiply(result.at(j), root); |
||||||
|
if (j + 1 < result.size()) |
||||||
|
result.at(j) ^= result.at(j + 1); |
||||||
|
} |
||||||
|
root = reedSolomonMultiply(root, 0x02); |
||||||
|
} |
||||||
|
return result; |
||||||
|
} |
||||||
|
|
||||||
|
|
||||||
|
vector<uint8_t> QrCode::reedSolomonComputeRemainder(const vector<uint8_t> &data, const vector<uint8_t> &divisor) { |
||||||
|
vector<uint8_t> result(divisor.size()); |
||||||
|
for (uint8_t b : data) { // Polynomial division
|
||||||
|
uint8_t factor = b ^ result.at(0); |
||||||
|
result.erase(result.begin()); |
||||||
|
result.push_back(0); |
||||||
|
for (size_t i = 0; i < result.size(); i++) |
||||||
|
result.at(i) ^= reedSolomonMultiply(divisor.at(i), factor); |
||||||
|
} |
||||||
|
return result; |
||||||
|
} |
||||||
|
|
||||||
|
|
||||||
|
uint8_t QrCode::reedSolomonMultiply(uint8_t x, uint8_t y) { |
||||||
|
// Russian peasant multiplication
|
||||||
|
int z = 0; |
||||||
|
for (int i = 7; i >= 0; i--) { |
||||||
|
z = (z << 1) ^ ((z >> 7) * 0x11D); |
||||||
|
z ^= ((y >> i) & 1) * x; |
||||||
|
} |
||||||
|
if (z >> 8 != 0) |
||||||
|
throw std::logic_error("Assertion error"); |
||||||
|
return static_cast<uint8_t>(z); |
||||||
|
} |
||||||
|
|
||||||
|
|
||||||
|
int QrCode::finderPenaltyCountPatterns(const std::array<int,7> &runHistory) const { |
||||||
|
int n = runHistory.at(1); |
||||||
|
if (n > size * 3) |
||||||
|
throw std::logic_error("Assertion error"); |
||||||
|
bool core = n > 0 && runHistory.at(2) == n && runHistory.at(3) == n * 3 && runHistory.at(4) == n && runHistory.at(5) == n; |
||||||
|
return (core && runHistory.at(0) >= n * 4 && runHistory.at(6) >= n ? 1 : 0) |
||||||
|
+ (core && runHistory.at(6) >= n * 4 && runHistory.at(0) >= n ? 1 : 0); |
||||||
|
} |
||||||
|
|
||||||
|
|
||||||
|
int QrCode::finderPenaltyTerminateAndCount(bool currentRunColor, int currentRunLength, std::array<int,7> &runHistory) const { |
||||||
|
if (currentRunColor) { // Terminate black run
|
||||||
|
finderPenaltyAddHistory(currentRunLength, runHistory); |
||||||
|
currentRunLength = 0; |
||||||
|
} |
||||||
|
currentRunLength += size; // Add white border to final run
|
||||||
|
finderPenaltyAddHistory(currentRunLength, runHistory); |
||||||
|
return finderPenaltyCountPatterns(runHistory); |
||||||
|
} |
||||||
|
|
||||||
|
|
||||||
|
void QrCode::finderPenaltyAddHistory(int currentRunLength, std::array<int,7> &runHistory) const { |
||||||
|
if (runHistory.at(0) == 0) |
||||||
|
currentRunLength += size; // Add white border to initial run
|
||||||
|
std::copy_backward(runHistory.cbegin(), runHistory.cend() - 1, runHistory.end()); |
||||||
|
runHistory.at(0) = currentRunLength; |
||||||
|
} |
||||||
|
|
||||||
|
|
||||||
|
bool QrCode::getBit(long x, int i) { |
||||||
|
return ((x >> i) & 1) != 0; |
||||||
|
} |
||||||
|
|
||||||
|
|
||||||
|
/*---- Tables of constants ----*/ |
||||||
|
|
||||||
|
const int QrCode::PENALTY_N1 = 3; |
||||||
|
const int QrCode::PENALTY_N2 = 3; |
||||||
|
const int QrCode::PENALTY_N3 = 40; |
||||||
|
const int QrCode::PENALTY_N4 = 10; |
||||||
|
|
||||||
|
|
||||||
|
const int8_t QrCode::ECC_CODEWORDS_PER_BLOCK[4][41] = { |
||||||
|
// Version: (note that index 0 is for padding, and is set to an illegal value)
|
||||||
|
//0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40 Error correction level
|
||||||
|
{-1, 7, 10, 15, 20, 26, 18, 20, 24, 30, 18, 20, 24, 26, 30, 22, 24, 28, 30, 28, 28, 28, 28, 30, 30, 26, 28, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30}, // Low
|
||||||
|
{-1, 10, 16, 26, 18, 24, 16, 18, 22, 22, 26, 30, 22, 22, 24, 24, 28, 28, 26, 26, 26, 26, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28}, // Medium
|
||||||
|
{-1, 13, 22, 18, 26, 18, 24, 18, 22, 20, 24, 28, 26, 24, 20, 30, 24, 28, 28, 26, 30, 28, 30, 30, 30, 30, 28, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30}, // Quartile
|
||||||
|
{-1, 17, 28, 22, 16, 22, 28, 26, 26, 24, 28, 24, 28, 22, 24, 24, 30, 28, 28, 26, 28, 30, 24, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30}, // High
|
||||||
|
}; |
||||||
|
|
||||||
|
const int8_t QrCode::NUM_ERROR_CORRECTION_BLOCKS[4][41] = { |
||||||
|
// Version: (note that index 0 is for padding, and is set to an illegal value)
|
||||||
|
//0, 1, 2, 3, 4, 5, 6, 7, 8, 9,10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40 Error correction level
|
||||||
|
{-1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 4, 4, 4, 4, 4, 6, 6, 6, 6, 7, 8, 8, 9, 9, 10, 12, 12, 12, 13, 14, 15, 16, 17, 18, 19, 19, 20, 21, 22, 24, 25}, // Low
|
||||||
|
{-1, 1, 1, 1, 2, 2, 4, 4, 4, 5, 5, 5, 8, 9, 9, 10, 10, 11, 13, 14, 16, 17, 17, 18, 20, 21, 23, 25, 26, 28, 29, 31, 33, 35, 37, 38, 40, 43, 45, 47, 49}, // Medium
|
||||||
|
{-1, 1, 1, 2, 2, 4, 4, 6, 6, 8, 8, 8, 10, 12, 16, 12, 17, 16, 18, 21, 20, 23, 23, 25, 27, 29, 34, 34, 35, 38, 40, 43, 45, 48, 51, 53, 56, 59, 62, 65, 68}, // Quartile
|
||||||
|
{-1, 1, 1, 2, 4, 4, 4, 5, 6, 8, 8, 11, 11, 16, 16, 18, 16, 19, 21, 25, 25, 25, 34, 30, 32, 35, 37, 40, 42, 45, 48, 51, 54, 57, 60, 63, 66, 70, 74, 77, 81}, // High
|
||||||
|
}; |
||||||
|
|
||||||
|
|
||||||
|
data_too_long::data_too_long(const std::string &msg) : |
||||||
|
std::length_error(msg) {} |
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
BitBuffer::BitBuffer() |
||||||
|
: std::vector<bool>() {} |
||||||
|
|
||||||
|
|
||||||
|
void BitBuffer::appendBits(std::uint32_t val, int len) { |
||||||
|
if (len < 0 || len > 31 || val >> len != 0) |
||||||
|
throw std::domain_error("Value out of range"); |
||||||
|
for (int i = len - 1; i >= 0; i--) // Append bit by bit
|
||||||
|
this->push_back(((val >> i) & 1) != 0); |
||||||
|
} |
||||||
|
|
||||||
|
} |
@ -0,0 +1,556 @@ |
|||||||
|
/*
|
||||||
|
* QR Code generator library (C++) |
||||||
|
*
|
||||||
|
* Copyright (c) Project Nayuki. (MIT License) |
||||||
|
* https://www.nayuki.io/page/qr-code-generator-library
|
||||||
|
*
|
||||||
|
* Permission is hereby granted, free of charge, to any person obtaining a copy of |
||||||
|
* this software and associated documentation files (the "Software"), to deal in |
||||||
|
* the Software without restriction, including without limitation the rights to |
||||||
|
* use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of |
||||||
|
* the Software, and to permit persons to whom the Software is furnished to do so, |
||||||
|
* subject to the following conditions: |
||||||
|
* - The above copyright notice and this permission notice shall be included in |
||||||
|
* all copies or substantial portions of the Software. |
||||||
|
* - The Software is provided "as is", without warranty of any kind, express or |
||||||
|
* implied, including but not limited to the warranties of merchantability, |
||||||
|
* fitness for a particular purpose and noninfringement. In no event shall the |
||||||
|
* authors or copyright holders be liable for any claim, damages or other |
||||||
|
* liability, whether in an action of contract, tort or otherwise, arising from, |
||||||
|
* out of or in connection with the Software or the use or other dealings in the |
||||||
|
* Software. |
||||||
|
*/ |
||||||
|
|
||||||
|
#pragma once |
||||||
|
|
||||||
|
#include <array> |
||||||
|
#include <cstdint> |
||||||
|
#include <stdexcept> |
||||||
|
#include <string> |
||||||
|
#include <vector> |
||||||
|
|
||||||
|
|
||||||
|
namespace qrcodegen { |
||||||
|
|
||||||
|
/*
|
||||||
|
* A segment of character/binary/control data in a QR Code symbol. |
||||||
|
* Instances of this class are immutable. |
||||||
|
* The mid-level way to create a segment is to take the payload data |
||||||
|
* and call a static factory function such as QrSegment::makeNumeric(). |
||||||
|
* The low-level way to create a segment is to custom-make the bit buffer |
||||||
|
* and call the QrSegment() constructor with appropriate values. |
||||||
|
* This segment class imposes no length restrictions, but QR Codes have restrictions. |
||||||
|
* Even in the most favorable conditions, a QR Code can only hold 7089 characters of data. |
||||||
|
* Any segment longer than this is meaningless for the purpose of generating QR Codes. |
||||||
|
*/ |
||||||
|
class QrSegment final { |
||||||
|
|
||||||
|
/*---- Public helper enumeration ----*/ |
||||||
|
|
||||||
|
/*
|
||||||
|
* Describes how a segment's data bits are interpreted. Immutable. |
||||||
|
*/ |
||||||
|
public: class Mode final { |
||||||
|
|
||||||
|
/*-- Constants --*/ |
||||||
|
|
||||||
|
public: static const Mode NUMERIC; |
||||||
|
public: static const Mode ALPHANUMERIC; |
||||||
|
public: static const Mode BYTE; |
||||||
|
public: static const Mode KANJI; |
||||||
|
public: static const Mode ECI; |
||||||
|
|
||||||
|
|
||||||
|
/*-- Fields --*/ |
||||||
|
|
||||||
|
// The mode indicator bits, which is a uint4 value (range 0 to 15).
|
||||||
|
private: int modeBits; |
||||||
|
|
||||||
|
// Number of character count bits for three different version ranges.
|
||||||
|
private: int numBitsCharCount[3]; |
||||||
|
|
||||||
|
|
||||||
|
/*-- Constructor --*/ |
||||||
|
|
||||||
|
private: Mode(int mode, int cc0, int cc1, int cc2); |
||||||
|
|
||||||
|
|
||||||
|
/*-- Methods --*/ |
||||||
|
|
||||||
|
/*
|
||||||
|
* (Package-private) Returns the mode indicator bits, which is an unsigned 4-bit value (range 0 to 15). |
||||||
|
*/ |
||||||
|
public: int getModeBits() const; |
||||||
|
|
||||||
|
/*
|
||||||
|
* (Package-private) Returns the bit width of the character count field for a segment in |
||||||
|
* this mode in a QR Code at the given version number. The result is in the range [0, 16]. |
||||||
|
*/ |
||||||
|
public: int numCharCountBits(int ver) const; |
||||||
|
|
||||||
|
}; |
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
/*---- Static factory functions (mid level) ----*/ |
||||||
|
|
||||||
|
/*
|
||||||
|
* Returns a segment representing the given binary data encoded in |
||||||
|
* byte mode. All input byte vectors are acceptable. Any text string |
||||||
|
* can be converted to UTF-8 bytes and encoded as a byte mode segment. |
||||||
|
*/ |
||||||
|
public: static QrSegment makeBytes(const std::vector<std::uint8_t> &data); |
||||||
|
|
||||||
|
|
||||||
|
/*
|
||||||
|
* Returns a segment representing the given string of decimal digits encoded in numeric mode. |
||||||
|
*/ |
||||||
|
public: static QrSegment makeNumeric(const char *digits); |
||||||
|
|
||||||
|
|
||||||
|
/*
|
||||||
|
* Returns a segment representing the given text string encoded in alphanumeric mode. |
||||||
|
* The characters allowed are: 0 to 9, A to Z (uppercase only), space, |
||||||
|
* dollar, percent, asterisk, plus, hyphen, period, slash, colon. |
||||||
|
*/ |
||||||
|
public: static QrSegment makeAlphanumeric(const char *text); |
||||||
|
|
||||||
|
|
||||||
|
/*
|
||||||
|
* Returns a list of zero or more segments to represent the given text string. The result |
||||||
|
* may use various segment modes and switch modes to optimize the length of the bit stream. |
||||||
|
*/ |
||||||
|
public: static std::vector<QrSegment> makeSegments(const char *text); |
||||||
|
|
||||||
|
|
||||||
|
/*
|
||||||
|
* Returns a segment representing an Extended Channel Interpretation |
||||||
|
* (ECI) designator with the given assignment value. |
||||||
|
*/ |
||||||
|
public: static QrSegment makeEci(long assignVal); |
||||||
|
|
||||||
|
|
||||||
|
/*---- Public static helper functions ----*/ |
||||||
|
|
||||||
|
/*
|
||||||
|
* Tests whether the given string can be encoded as a segment in alphanumeric mode. |
||||||
|
* A string is encodable iff each character is in the following set: 0 to 9, A to Z |
||||||
|
* (uppercase only), space, dollar, percent, asterisk, plus, hyphen, period, slash, colon. |
||||||
|
*/ |
||||||
|
public: static bool isAlphanumeric(const char *text); |
||||||
|
|
||||||
|
|
||||||
|
/*
|
||||||
|
* Tests whether the given string can be encoded as a segment in numeric mode. |
||||||
|
* A string is encodable iff each character is in the range 0 to 9. |
||||||
|
*/ |
||||||
|
public: static bool isNumeric(const char *text); |
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
/*---- Instance fields ----*/ |
||||||
|
|
||||||
|
/* The mode indicator of this segment. Accessed through getMode(). */ |
||||||
|
private: Mode mode; |
||||||
|
|
||||||
|
/* The length of this segment's unencoded data. Measured in characters for
|
||||||
|
* numeric/alphanumeric/kanji mode, bytes for byte mode, and 0 for ECI mode. |
||||||
|
* Always zero or positive. Not the same as the data's bit length. |
||||||
|
* Accessed through getNumChars(). */ |
||||||
|
private: int numChars; |
||||||
|
|
||||||
|
/* The data bits of this segment. Accessed through getData(). */ |
||||||
|
private: std::vector<bool> data; |
||||||
|
|
||||||
|
|
||||||
|
/*---- Constructors (low level) ----*/ |
||||||
|
|
||||||
|
/*
|
||||||
|
* Creates a new QR Code segment with the given attributes and data. |
||||||
|
* The character count (numCh) must agree with the mode and the bit buffer length, |
||||||
|
* but the constraint isn't checked. The given bit buffer is copied and stored. |
||||||
|
*/ |
||||||
|
public: QrSegment(Mode md, int numCh, const std::vector<bool> &dt); |
||||||
|
|
||||||
|
|
||||||
|
/*
|
||||||
|
* Creates a new QR Code segment with the given parameters and data. |
||||||
|
* The character count (numCh) must agree with the mode and the bit buffer length, |
||||||
|
* but the constraint isn't checked. The given bit buffer is moved and stored. |
||||||
|
*/ |
||||||
|
public: QrSegment(Mode md, int numCh, std::vector<bool> &&dt); |
||||||
|
|
||||||
|
|
||||||
|
/*---- Methods ----*/ |
||||||
|
|
||||||
|
/*
|
||||||
|
* Returns the mode field of this segment. |
||||||
|
*/ |
||||||
|
public: Mode getMode() const; |
||||||
|
|
||||||
|
|
||||||
|
/*
|
||||||
|
* Returns the character count field of this segment. |
||||||
|
*/ |
||||||
|
public: int getNumChars() const; |
||||||
|
|
||||||
|
|
||||||
|
/*
|
||||||
|
* Returns the data bits of this segment. |
||||||
|
*/ |
||||||
|
public: const std::vector<bool> &getData() const; |
||||||
|
|
||||||
|
|
||||||
|
// (Package-private) Calculates the number of bits needed to encode the given segments at
|
||||||
|
// the given version. Returns a non-negative number if successful. Otherwise returns -1 if a
|
||||||
|
// segment has too many characters to fit its length field, or the total bits exceeds INT_MAX.
|
||||||
|
public: static int getTotalBits(const std::vector<QrSegment> &segs, int version); |
||||||
|
|
||||||
|
|
||||||
|
/*---- Private constant ----*/ |
||||||
|
|
||||||
|
/* The set of all legal characters in alphanumeric mode, where
|
||||||
|
* each character value maps to the index in the string. */ |
||||||
|
private: static const char *ALPHANUMERIC_CHARSET; |
||||||
|
|
||||||
|
}; |
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
/*
|
||||||
|
* A QR Code symbol, which is a type of two-dimension barcode. |
||||||
|
* Invented by Denso Wave and described in the ISO/IEC 18004 standard. |
||||||
|
* Instances of this class represent an immutable square grid of black and white cells. |
||||||
|
* The class provides static factory functions to create a QR Code from text or binary data. |
||||||
|
* The class covers the QR Code Model 2 specification, supporting all versions (sizes) |
||||||
|
* from 1 to 40, all 4 error correction levels, and 4 character encoding modes. |
||||||
|
*
|
||||||
|
* Ways to create a QR Code object: |
||||||
|
* - High level: Take the payload data and call QrCode::encodeText() or QrCode::encodeBinary(). |
||||||
|
* - Mid level: Custom-make the list of segments and call QrCode::encodeSegments(). |
||||||
|
* - Low level: Custom-make the array of data codeword bytes (including |
||||||
|
* segment headers and final padding, excluding error correction codewords), |
||||||
|
* supply the appropriate version number, and call the QrCode() constructor. |
||||||
|
* (Note that all ways require supplying the desired error correction level.) |
||||||
|
*/ |
||||||
|
class QrCode final { |
||||||
|
|
||||||
|
/*---- Public helper enumeration ----*/ |
||||||
|
|
||||||
|
/*
|
||||||
|
* The error correction level in a QR Code symbol. |
||||||
|
*/ |
||||||
|
public: enum class Ecc { |
||||||
|
LOW = 0 , // The QR Code can tolerate about 7% erroneous codewords
|
||||||
|
MEDIUM , // The QR Code can tolerate about 15% erroneous codewords
|
||||||
|
QUARTILE, // The QR Code can tolerate about 25% erroneous codewords
|
||||||
|
HIGH , // The QR Code can tolerate about 30% erroneous codewords
|
||||||
|
}; |
||||||
|
|
||||||
|
|
||||||
|
// Returns a value in the range 0 to 3 (unsigned 2-bit integer).
|
||||||
|
private: static int getFormatBits(Ecc ecl); |
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
/*---- Static factory functions (high level) ----*/ |
||||||
|
|
||||||
|
/*
|
||||||
|
* Returns a QR Code representing the given Unicode text string at the given error correction level. |
||||||
|
* As a conservative upper bound, this function is guaranteed to succeed for strings that have 2953 or fewer |
||||||
|
* UTF-8 code units (not Unicode code points) if the low error correction level is used. The smallest possible |
||||||
|
* QR Code version is automatically chosen for the output. The ECC level of the result may be higher than |
||||||
|
* the ecl argument if it can be done without increasing the version. |
||||||
|
*/ |
||||||
|
public: static QrCode encodeText(const char *text, Ecc ecl); |
||||||
|
|
||||||
|
|
||||||
|
/*
|
||||||
|
* Returns a QR Code representing the given binary data at the given error correction level. |
||||||
|
* This function always encodes using the binary segment mode, not any text mode. The maximum number of |
||||||
|
* bytes allowed is 2953. The smallest possible QR Code version is automatically chosen for the output. |
||||||
|
* The ECC level of the result may be higher than the ecl argument if it can be done without increasing the version. |
||||||
|
*/ |
||||||
|
public: static QrCode encodeBinary(const std::vector<std::uint8_t> &data, Ecc ecl); |
||||||
|
|
||||||
|
|
||||||
|
/*---- Static factory functions (mid level) ----*/ |
||||||
|
|
||||||
|
/*
|
||||||
|
* Returns a QR Code representing the given segments with the given encoding parameters. |
||||||
|
* The smallest possible QR Code version within the given range is automatically |
||||||
|
* chosen for the output. Iff boostEcl is true, then the ECC level of the result |
||||||
|
* may be higher than the ecl argument if it can be done without increasing the |
||||||
|
* version. The mask number is either between 0 to 7 (inclusive) to force that |
||||||
|
* mask, or -1 to automatically choose an appropriate mask (which may be slow). |
||||||
|
* This function allows the user to create a custom sequence of segments that switches |
||||||
|
* between modes (such as alphanumeric and byte) to encode text in less space. |
||||||
|
* This is a mid-level API; the high-level API is encodeText() and encodeBinary(). |
||||||
|
*/ |
||||||
|
public: static QrCode encodeSegments(const std::vector<QrSegment> &segs, Ecc ecl, |
||||||
|
int minVersion=1, int maxVersion=40, int mask=-1, bool boostEcl=true); // All optional parameters
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
/*---- Instance fields ----*/ |
||||||
|
|
||||||
|
// Immutable scalar parameters:
|
||||||
|
|
||||||
|
/* The version number of this QR Code, which is between 1 and 40 (inclusive).
|
||||||
|
* This determines the size of this barcode. */ |
||||||
|
private: int version; |
||||||
|
|
||||||
|
/* The width and height of this QR Code, measured in modules, between
|
||||||
|
* 21 and 177 (inclusive). This is equal to version * 4 + 17. */ |
||||||
|
private: int size; |
||||||
|
|
||||||
|
/* The error correction level used in this QR Code. */ |
||||||
|
private: Ecc errorCorrectionLevel; |
||||||
|
|
||||||
|
/* The index of the mask pattern used in this QR Code, which is between 0 and 7 (inclusive).
|
||||||
|
* Even if a QR Code is created with automatic masking requested (mask = -1), |
||||||
|
* the resulting object still has a mask value between 0 and 7. */ |
||||||
|
private: int mask; |
||||||
|
|
||||||
|
// Private grids of modules/pixels, with dimensions of size*size:
|
||||||
|
|
||||||
|
// The modules of this QR Code (false = white, true = black).
|
||||||
|
// Immutable after constructor finishes. Accessed through getModule().
|
||||||
|
private: std::vector<std::vector<bool> > modules; |
||||||
|
|
||||||
|
// Indicates function modules that are not subjected to masking. Discarded when constructor finishes.
|
||||||
|
private: std::vector<std::vector<bool> > isFunction; |
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
/*---- Constructor (low level) ----*/ |
||||||
|
|
||||||
|
/*
|
||||||
|
* Creates a new QR Code with the given version number, |
||||||
|
* error correction level, data codeword bytes, and mask number. |
||||||
|
* This is a low-level API that most users should not use directly. |
||||||
|
* A mid-level API is the encodeSegments() function. |
||||||
|
*/ |
||||||
|
public: QrCode(int ver, Ecc ecl, const std::vector<std::uint8_t> &dataCodewords, int msk); |
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
/*---- Public instance methods ----*/ |
||||||
|
|
||||||
|
/*
|
||||||
|
* Returns this QR Code's version, in the range [1, 40]. |
||||||
|
*/ |
||||||
|
public: int getVersion() const; |
||||||
|
|
||||||
|
|
||||||
|
/*
|
||||||
|
* Returns this QR Code's size, in the range [21, 177]. |
||||||
|
*/ |
||||||
|
public: int getSize() const; |
||||||
|
|
||||||
|
|
||||||
|
/*
|
||||||
|
* Returns this QR Code's error correction level. |
||||||
|
*/ |
||||||
|
public: Ecc getErrorCorrectionLevel() const; |
||||||
|
|
||||||
|
|
||||||
|
/*
|
||||||
|
* Returns this QR Code's mask, in the range [0, 7]. |
||||||
|
*/ |
||||||
|
public: int getMask() const; |
||||||
|
|
||||||
|
|
||||||
|
/*
|
||||||
|
* Returns the color of the module (pixel) at the given coordinates, which is false |
||||||
|
* for white or true for black. The top left corner has the coordinates (x=0, y=0). |
||||||
|
* If the given coordinates are out of bounds, then false (white) is returned. |
||||||
|
*/ |
||||||
|
public: bool getModule(int x, int y) const; |
||||||
|
|
||||||
|
|
||||||
|
/*
|
||||||
|
* Returns a string of SVG code for an image depicting this QR Code, with the given number |
||||||
|
* of border modules. The string always uses Unix newlines (\n), regardless of the platform. |
||||||
|
*/ |
||||||
|
public: std::string toSvgString(int border) const; |
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
/*---- Private helper methods for constructor: Drawing function modules ----*/ |
||||||
|
|
||||||
|
// Reads this object's version field, and draws and marks all function modules.
|
||||||
|
private: void drawFunctionPatterns(); |
||||||
|
|
||||||
|
|
||||||
|
// Draws two copies of the format bits (with its own error correction code)
|
||||||
|
// based on the given mask and this object's error correction level field.
|
||||||
|
private: void drawFormatBits(int msk); |
||||||
|
|
||||||
|
|
||||||
|
// Draws two copies of the version bits (with its own error correction code),
|
||||||
|
// based on this object's version field, iff 7 <= version <= 40.
|
||||||
|
private: void drawVersion(); |
||||||
|
|
||||||
|
|
||||||
|
// Draws a 9*9 finder pattern including the border separator,
|
||||||
|
// with the center module at (x, y). Modules can be out of bounds.
|
||||||
|
private: void drawFinderPattern(int x, int y); |
||||||
|
|
||||||
|
|
||||||
|
// Draws a 5*5 alignment pattern, with the center module
|
||||||
|
// at (x, y). All modules must be in bounds.
|
||||||
|
private: void drawAlignmentPattern(int x, int y); |
||||||
|
|
||||||
|
|
||||||
|
// Sets the color of a module and marks it as a function module.
|
||||||
|
// Only used by the constructor. Coordinates must be in bounds.
|
||||||
|
private: void setFunctionModule(int x, int y, bool isBlack); |
||||||
|
|
||||||
|
|
||||||
|
// Returns the color of the module at the given coordinates, which must be in range.
|
||||||
|
private: bool module(int x, int y) const; |
||||||
|
|
||||||
|
|
||||||
|
/*---- Private helper methods for constructor: Codewords and masking ----*/ |
||||||
|
|
||||||
|
// Returns a new byte string representing the given data with the appropriate error correction
|
||||||
|
// codewords appended to it, based on this object's version and error correction level.
|
||||||
|
private: std::vector<std::uint8_t> addEccAndInterleave(const std::vector<std::uint8_t> &data) const; |
||||||
|
|
||||||
|
|
||||||
|
// Draws the given sequence of 8-bit codewords (data and error correction) onto the entire
|
||||||
|
// data area of this QR Code. Function modules need to be marked off before this is called.
|
||||||
|
private: void drawCodewords(const std::vector<std::uint8_t> &data); |
||||||
|
|
||||||
|
|
||||||
|
// XORs the codeword modules in this QR Code with the given mask pattern.
|
||||||
|
// The function modules must be marked and the codeword bits must be drawn
|
||||||
|
// before masking. Due to the arithmetic of XOR, calling applyMask() with
|
||||||
|
// the same mask value a second time will undo the mask. A final well-formed
|
||||||
|
// QR Code needs exactly one (not zero, two, etc.) mask applied.
|
||||||
|
private: void applyMask(int msk); |
||||||
|
|
||||||
|
|
||||||
|
// Calculates and returns the penalty score based on state of this QR Code's current modules.
|
||||||
|
// This is used by the automatic mask choice algorithm to find the mask pattern that yields the lowest score.
|
||||||
|
private: long getPenaltyScore() const; |
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
/*---- Private helper functions ----*/ |
||||||
|
|
||||||
|
// Returns an ascending list of positions of alignment patterns for this version number.
|
||||||
|
// Each position is in the range [0,177), and are used on both the x and y axes.
|
||||||
|
// This could be implemented as lookup table of 40 variable-length lists of unsigned bytes.
|
||||||
|
private: std::vector<int> getAlignmentPatternPositions() const; |
||||||
|
|
||||||
|
|
||||||
|
// Returns the number of data bits that can be stored in a QR Code of the given version number, after
|
||||||
|
// all function modules are excluded. This includes remainder bits, so it might not be a multiple of 8.
|
||||||
|
// The result is in the range [208, 29648]. This could be implemented as a 40-entry lookup table.
|
||||||
|
private: static int getNumRawDataModules(int ver); |
||||||
|
|
||||||
|
|
||||||
|
// Returns the number of 8-bit data (i.e. not error correction) codewords contained in any
|
||||||
|
// QR Code of the given version number and error correction level, with remainder bits discarded.
|
||||||
|
// This stateless pure function could be implemented as a (40*4)-cell lookup table.
|
||||||
|
private: static int getNumDataCodewords(int ver, Ecc ecl); |
||||||
|
|
||||||
|
|
||||||
|
// Returns a Reed-Solomon ECC generator polynomial for the given degree. This could be
|
||||||
|
// implemented as a lookup table over all possible parameter values, instead of as an algorithm.
|
||||||
|
private: static std::vector<std::uint8_t> reedSolomonComputeDivisor(int degree); |
||||||
|
|
||||||
|
|
||||||
|
// Returns the Reed-Solomon error correction codeword for the given data and divisor polynomials.
|
||||||
|
private: static std::vector<std::uint8_t> reedSolomonComputeRemainder(const std::vector<std::uint8_t> &data, const std::vector<std::uint8_t> &divisor); |
||||||
|
|
||||||
|
|
||||||
|
// Returns the product of the two given field elements modulo GF(2^8/0x11D).
|
||||||
|
// All inputs are valid. This could be implemented as a 256*256 lookup table.
|
||||||
|
private: static std::uint8_t reedSolomonMultiply(std::uint8_t x, std::uint8_t y); |
||||||
|
|
||||||
|
|
||||||
|
// Can only be called immediately after a white run is added, and
|
||||||
|
// returns either 0, 1, or 2. A helper function for getPenaltyScore().
|
||||||
|
private: int finderPenaltyCountPatterns(const std::array<int,7> &runHistory) const; |
||||||
|
|
||||||
|
|
||||||
|
// Must be called at the end of a line (row or column) of modules. A helper function for getPenaltyScore().
|
||||||
|
private: int finderPenaltyTerminateAndCount(bool currentRunColor, int currentRunLength, std::array<int,7> &runHistory) const; |
||||||
|
|
||||||
|
|
||||||
|
// Pushes the given value to the front and drops the last value. A helper function for getPenaltyScore().
|
||||||
|
private: void finderPenaltyAddHistory(int currentRunLength, std::array<int,7> &runHistory) const; |
||||||
|
|
||||||
|
|
||||||
|
// Returns true iff the i'th bit of x is set to 1.
|
||||||
|
private: static bool getBit(long x, int i); |
||||||
|
|
||||||
|
|
||||||
|
/*---- Constants and tables ----*/ |
||||||
|
|
||||||
|
// The minimum version number supported in the QR Code Model 2 standard.
|
||||||
|
public: static constexpr int MIN_VERSION = 1; |
||||||
|
|
||||||
|
// The maximum version number supported in the QR Code Model 2 standard.
|
||||||
|
public: static constexpr int MAX_VERSION = 40; |
||||||
|
|
||||||
|
|
||||||
|
// For use in getPenaltyScore(), when evaluating which mask is best.
|
||||||
|
private: static const int PENALTY_N1; |
||||||
|
private: static const int PENALTY_N2; |
||||||
|
private: static const int PENALTY_N3; |
||||||
|
private: static const int PENALTY_N4; |
||||||
|
|
||||||
|
|
||||||
|
private: static const std::int8_t ECC_CODEWORDS_PER_BLOCK[4][41]; |
||||||
|
private: static const std::int8_t NUM_ERROR_CORRECTION_BLOCKS[4][41]; |
||||||
|
|
||||||
|
}; |
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
/*---- Public exception class ----*/ |
||||||
|
|
||||||
|
/*
|
||||||
|
* Thrown when the supplied data does not fit any QR Code version. Ways to handle this exception include: |
||||||
|
* - Decrease the error correction level if it was greater than Ecc::LOW. |
||||||
|
* - If the encodeSegments() function was called with a maxVersion argument, then increase |
||||||
|
* it if it was less than QrCode::MAX_VERSION. (This advice does not apply to the other |
||||||
|
* factory functions because they search all versions up to QrCode::MAX_VERSION.) |
||||||
|
* - Split the text data into better or optimal segments in order to reduce the number of bits required. |
||||||
|
* - Change the text or binary data to be shorter. |
||||||
|
* - Change the text to fit the character set of a particular segment mode (e.g. alphanumeric). |
||||||
|
* - Propagate the error upward to the caller/user. |
||||||
|
*/ |
||||||
|
class data_too_long : public std::length_error { |
||||||
|
|
||||||
|
public: explicit data_too_long(const std::string &msg); |
||||||
|
|
||||||
|
}; |
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
/*
|
||||||
|
* An appendable sequence of bits (0s and 1s). Mainly used by QrSegment. |
||||||
|
*/ |
||||||
|
class BitBuffer final : public std::vector<bool> { |
||||||
|
|
||||||
|
/*---- Constructor ----*/ |
||||||
|
|
||||||
|
// Creates an empty bit buffer (length 0).
|
||||||
|
public: BitBuffer(); |
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
/*---- Method ----*/ |
||||||
|
|
||||||
|
// Appends the given number of low-order bits of the given value
|
||||||
|
// to this buffer. Requires 0 <= len <= 31 and val < 2^len.
|
||||||
|
public: void appendBits(std::uint32_t val, int len); |
||||||
|
|
||||||
|
}; |
||||||
|
|
||||||
|
} |
@ -0,0 +1,276 @@ |
|||||||
|
#include <QDebug> |
||||||
|
#include <QJsonDocument> |
||||||
|
#include <QJsonObject> |
||||||
|
#include <QLabel> |
||||||
|
#include <QStackedLayout> |
||||||
|
#include <QTimer> |
||||||
|
#include <QVBoxLayout> |
||||||
|
|
||||||
|
#include "QrCode.hpp" |
||||||
|
#include "api.hpp" |
||||||
|
#include "common/params.h" |
||||||
|
#include "common/util.h" |
||||||
|
#include "home.hpp" |
||||||
|
#include "setup.hpp" |
||||||
|
|
||||||
|
using qrcodegen::QrCode; |
||||||
|
|
||||||
|
#if defined(QCOM) || defined(QCOM2) |
||||||
|
const std::string private_key_path = "/persist/comma/id_rsa"; |
||||||
|
#else |
||||||
|
const std::string private_key_path = util::getenv_default("HOME", "/.comma/persist/comma/id_rsa", "/persist/comma/id_rsa"); |
||||||
|
#endif |
||||||
|
|
||||||
|
PairingQRWidget::PairingQRWidget(QWidget* parent) : QWidget(parent) { |
||||||
|
qrCode = new QLabel; |
||||||
|
qrCode->setScaledContents(true); |
||||||
|
QVBoxLayout* v = new QVBoxLayout; |
||||||
|
v->addWidget(qrCode, 0, Qt::AlignCenter); |
||||||
|
setLayout(v); |
||||||
|
|
||||||
|
QTimer* timer = new QTimer(this); |
||||||
|
timer->start(30 * 1000);// HaLf a minute
|
||||||
|
connect(timer, SIGNAL(timeout()), this, SLOT(refresh())); |
||||||
|
refresh(); // Not waiting for the first refresh
|
||||||
|
} |
||||||
|
|
||||||
|
void PairingQRWidget::refresh(){ |
||||||
|
QString IMEI = QString::fromStdString(Params().get("IMEI")); |
||||||
|
QString serial = QString::fromStdString(Params().get("HardwareSerial")); |
||||||
|
|
||||||
|
if (std::min(IMEI.length(), serial.length()) <= 5) { |
||||||
|
qrCode->setText("Error getting serial: contact support"); |
||||||
|
qrCode->setWordWrap(true); |
||||||
|
qrCode->setStyleSheet(R"( |
||||||
|
font-size: 60px; |
||||||
|
)"); |
||||||
|
return; |
||||||
|
} |
||||||
|
QVector<QPair<QString, QJsonValue>> payloads; |
||||||
|
payloads.push_back(qMakePair(QString("pair"), true)); |
||||||
|
QString pairToken = CommaApi::create_jwt(payloads); |
||||||
|
|
||||||
|
QString qrString = IMEI + "--" + serial + "--" + pairToken; |
||||||
|
this->updateQrCode(qrString); |
||||||
|
} |
||||||
|
|
||||||
|
void PairingQRWidget::updateQrCode(QString text) { |
||||||
|
QrCode qr = QrCode::encodeText(text.toUtf8().data(), QrCode::Ecc::LOW); |
||||||
|
qint32 sz = qr.getSize(); |
||||||
|
// We make the image larger so we can have a white border
|
||||||
|
QImage im(sz + 2, sz + 2, QImage::Format_RGB32); |
||||||
|
QRgb black = qRgb(0, 0, 0); |
||||||
|
QRgb white = qRgb(255, 255, 255); |
||||||
|
|
||||||
|
for (int y = 0; y < sz + 2; y++) { |
||||||
|
for (int x = 0; x < sz + 2; x++) { |
||||||
|
im.setPixel(x, y, white); |
||||||
|
} |
||||||
|
} |
||||||
|
for (int y = 0; y < sz; y++) { |
||||||
|
for (int x = 0; x < sz; x++) { |
||||||
|
im.setPixel(x + 1, y + 1, qr.getModule(x, y) ? black : white); |
||||||
|
} |
||||||
|
} |
||||||
|
// Integer division to prevent anti-aliasing
|
||||||
|
int approx500 = (500 / (sz + 2)) * (sz + 2); |
||||||
|
qrCode->setPixmap(QPixmap::fromImage(im.scaled(approx500, approx500, Qt::KeepAspectRatio, Qt::FastTransformation), Qt::MonoOnly)); |
||||||
|
qrCode->setFixedSize(approx500, approx500); |
||||||
|
} |
||||||
|
|
||||||
|
PrimeUserWidget::PrimeUserWidget(QWidget* parent) : QWidget(parent) { |
||||||
|
mainLayout = new QVBoxLayout(this); |
||||||
|
QLabel* commaPrime = new QLabel("COMMA PRIME", this); |
||||||
|
commaPrime->setStyleSheet(R"( |
||||||
|
font-size: 60px; |
||||||
|
)"); |
||||||
|
mainLayout->addWidget(commaPrime); |
||||||
|
|
||||||
|
username = new QLabel("", this); |
||||||
|
mainLayout->addWidget(username); |
||||||
|
|
||||||
|
mainLayout->addSpacing(200); |
||||||
|
|
||||||
|
QLabel* commaPoints = new QLabel("COMMA POINTS", this); |
||||||
|
commaPoints->setStyleSheet(R"( |
||||||
|
font-size: 60px; |
||||||
|
color: #b8b8b8; |
||||||
|
)"); |
||||||
|
mainLayout->addWidget(commaPoints); |
||||||
|
|
||||||
|
points = new QLabel("", this); |
||||||
|
mainLayout->addWidget(points); |
||||||
|
|
||||||
|
setLayout(mainLayout); |
||||||
|
QString dongleId = QString::fromStdString(Params().get("DongleId")); |
||||||
|
QString url = "https://api.commadotai.com/v1/devices/" + dongleId + "/owner"; |
||||||
|
RequestRepeater* repeater = new RequestRepeater(this, url, 6); |
||||||
|
|
||||||
|
QObject::connect(repeater, SIGNAL(receivedResponse(QString)), this, SLOT(replyFinished(QString))); |
||||||
|
} |
||||||
|
|
||||||
|
void PrimeUserWidget::replyFinished(QString response) { |
||||||
|
QJsonDocument doc = QJsonDocument::fromJson(response.toUtf8()); |
||||||
|
if (doc.isNull()) { |
||||||
|
qDebug() << "JSON Parse failed on getting username and points"; |
||||||
|
return; |
||||||
|
} |
||||||
|
QJsonObject json = doc.object(); |
||||||
|
QString username_str = json["username"].toString(); |
||||||
|
if (username_str.length()) { |
||||||
|
username_str = "@" + username_str; |
||||||
|
} |
||||||
|
QString points_str = QString::number(json["points"].toInt()); |
||||||
|
|
||||||
|
username->setText(username_str); |
||||||
|
points->setText(points_str); |
||||||
|
} |
||||||
|
|
||||||
|
PrimeAdWidget::PrimeAdWidget(QWidget* parent) : QWidget(parent) { |
||||||
|
QVBoxLayout* vlayout = new QVBoxLayout(this); |
||||||
|
|
||||||
|
QLabel* upgradeNow = new QLabel("Upgrade now", this); |
||||||
|
vlayout->addWidget(upgradeNow); |
||||||
|
|
||||||
|
QLabel* description = new QLabel("Become a comma prime member in the comma app and get premium features!", this); |
||||||
|
description->setStyleSheet(R"( |
||||||
|
font-size: 50px; |
||||||
|
color: #b8b8b8; |
||||||
|
)"); |
||||||
|
description->setWordWrap(true); |
||||||
|
vlayout->addWidget(description); |
||||||
|
|
||||||
|
vlayout->addSpacing(50); |
||||||
|
|
||||||
|
QVector<QString> features = {"✓ REMOTE ACCESS", "✓ 14 DAYS OF STORAGE", "✓ DEVELOPER PERKS"}; |
||||||
|
for (auto featureContent : features) { |
||||||
|
QLabel* feature = new QLabel(featureContent, this); |
||||||
|
feature->setStyleSheet(R"( |
||||||
|
font-size: 40px; |
||||||
|
)"); |
||||||
|
|
||||||
|
vlayout->addWidget(feature); |
||||||
|
vlayout->addSpacing(15); |
||||||
|
} |
||||||
|
|
||||||
|
setLayout(vlayout); |
||||||
|
} |
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
SetupWidget::SetupWidget(QWidget* parent) : QWidget(parent) { |
||||||
|
QVBoxLayout* backgroundLayout = new QVBoxLayout(this); |
||||||
|
|
||||||
|
backgroundLayout->addSpacing(100); |
||||||
|
|
||||||
|
QFrame* background = new QFrame(this); |
||||||
|
|
||||||
|
mainLayout = new QStackedLayout(this); |
||||||
|
|
||||||
|
QWidget* blankWidget = new QWidget(this); |
||||||
|
mainLayout->addWidget(blankWidget); |
||||||
|
|
||||||
|
QWidget* finishRegistration = new QWidget(this); |
||||||
|
|
||||||
|
QVBoxLayout* finishRegistationLayout = new QVBoxLayout(this); |
||||||
|
finishRegistationLayout->addSpacing(50); |
||||||
|
QPushButton* finishButton = new QPushButton("Finish registration", this); |
||||||
|
finishButton->setFixedHeight(200); |
||||||
|
finishButton->setStyleSheet(R"( |
||||||
|
border-radius: 30px; |
||||||
|
font-size: 60px; |
||||||
|
font-weight: bold; |
||||||
|
background: #787878; |
||||||
|
)"); |
||||||
|
QObject::connect(finishButton, SIGNAL(released()), this, SLOT(showQrCode())); |
||||||
|
finishRegistationLayout->addWidget(finishButton); |
||||||
|
|
||||||
|
QLabel* registrationDescription = new QLabel("Pair your device with comma connect app", this); |
||||||
|
registrationDescription->setStyleSheet(R"( |
||||||
|
font-size: 50px; |
||||||
|
)"); |
||||||
|
|
||||||
|
registrationDescription->setWordWrap(true); |
||||||
|
finishRegistationLayout->addWidget(registrationDescription); |
||||||
|
|
||||||
|
finishRegistration->setLayout(finishRegistationLayout); |
||||||
|
mainLayout->addWidget(finishRegistration); |
||||||
|
|
||||||
|
QVBoxLayout* qrLayout = new QVBoxLayout(this); |
||||||
|
|
||||||
|
QLabel* qrLabel = new QLabel("Pair with Comma Connect app!", this); |
||||||
|
qrLabel->setStyleSheet(R"( |
||||||
|
font-size: 40px; |
||||||
|
)"); |
||||||
|
qrLayout->addWidget(qrLabel); |
||||||
|
|
||||||
|
qrLayout->addWidget(new PairingQRWidget(this)); |
||||||
|
|
||||||
|
QWidget* q = new QWidget(this); |
||||||
|
q->setLayout(qrLayout); |
||||||
|
mainLayout->addWidget(q); |
||||||
|
|
||||||
|
PrimeAdWidget* primeAd = new PrimeAdWidget(this); |
||||||
|
mainLayout->addWidget(primeAd); |
||||||
|
|
||||||
|
PrimeUserWidget* primeUserWidget = new PrimeUserWidget(this); |
||||||
|
mainLayout->addWidget(primeUserWidget); |
||||||
|
|
||||||
|
background->setLayout(mainLayout); |
||||||
|
background->setStyleSheet(R"( |
||||||
|
.QFrame { |
||||||
|
border-radius: 40px; |
||||||
|
padding: 60px; |
||||||
|
} |
||||||
|
)"); |
||||||
|
backgroundLayout->addWidget(background); |
||||||
|
setLayout(backgroundLayout); |
||||||
|
|
||||||
|
QString dongleId = QString::fromStdString(Params().get("DongleId")); |
||||||
|
QString url = "https://api.commadotai.com/v1.1/devices/" + dongleId + "/"; |
||||||
|
RequestRepeater* repeater = new RequestRepeater(this, url, 5); |
||||||
|
|
||||||
|
QObject::connect(repeater, SIGNAL(receivedResponse(QString)), this, SLOT(replyFinished(QString))); |
||||||
|
QObject::connect(repeater, SIGNAL(failedResponse(QString)), this, SLOT(parseError(QString))); |
||||||
|
|
||||||
|
} |
||||||
|
|
||||||
|
void SetupWidget::parseError(QString response) { |
||||||
|
showQr = false; |
||||||
|
mainLayout->setCurrentIndex(0); |
||||||
|
setStyleSheet(R"( |
||||||
|
font-size: 90px; |
||||||
|
background-color: #000000; |
||||||
|
)"); |
||||||
|
} |
||||||
|
void SetupWidget::showQrCode(){ |
||||||
|
showQr = true; |
||||||
|
mainLayout->setCurrentIndex(2); |
||||||
|
} |
||||||
|
void SetupWidget::replyFinished(QString response) { |
||||||
|
QJsonDocument doc = QJsonDocument::fromJson(response.toUtf8()); |
||||||
|
if (doc.isNull()) { |
||||||
|
qDebug() << "JSON Parse failed on getting pairing and prime status"; |
||||||
|
return; |
||||||
|
} |
||||||
|
if (mainLayout->currentIndex() == 0) { // If we are still on the blank widget
|
||||||
|
setStyleSheet(R"( |
||||||
|
font-size: 90px; |
||||||
|
font-weight: bold; |
||||||
|
background-color: #292929; |
||||||
|
)"); |
||||||
|
} |
||||||
|
QJsonObject json = doc.object(); |
||||||
|
bool is_paired = json["is_paired"].toBool(); |
||||||
|
bool is_prime = json["prime"].toBool(); |
||||||
|
|
||||||
|
if (!is_paired) { |
||||||
|
mainLayout->setCurrentIndex(1 + showQr); |
||||||
|
} else if (is_paired && !is_prime) { |
||||||
|
showQr = false; |
||||||
|
mainLayout->setCurrentIndex(3); |
||||||
|
} else if (is_paired && is_prime) { |
||||||
|
showQr = false; |
||||||
|
mainLayout->setCurrentIndex(4); |
||||||
|
} |
||||||
|
} |
Some files were not shown because too many files have changed in this diff Show More
Loading…
Reference in new issue