?view=chart&key= Give the data as JSON: ?view=runs&key=... ?view=data&key=...&device=...&run=... Give the CSV export: ?view=csv&key=...&device=...&run=... Keep the events of other kinds (activity, sales, ...) as JSON lines in other/ - for the records use upscale-receiver.php (hash chain, "stored", requests). ---------------------------------------------------------------------------------------- 1st: What you need: ---------------------------------------------------------------------------------------- 1.) A web server with PHP 7.4 or newer (PHP 8.1+ recommended). Mode 3 needs the openssl extension. No database: the runs are plain files, so the example runs on every host. FOR REAL USE, CHANGE THE STORAGE TO A DATABASE (SQLite, MySQL / MariaDB, PostgreSQL, InfluxDB ...): many scales, long runs at short intervals and several people viewing at once are faster and safer in SQL. Only the functions run_meta(), run_save(), run_add_points(), run_alarm() and the views "runs" / "data" / "csv" touch the files - replace them, e.g. with PDO and a table points(device, run_id, t, n, gross_g, net_g, PRIMARY KEY(device, run_id, t)): INSERT OR IGNORE then drops the doubled points. 2.) A data folder the web server may write to (see UPSCALE_DATA). This script creates it if it can; if it can not, every request answers 500 with what to do, and ?view=setup&key= (or: php --setup) shows what works: PHP, openssl, the folder, the e-mail settings. Usually it is: mkdir upscale-tracking-data && chown www-data upscale-tracking-data && chmod 770 upscale-tracking-data (www-data = the user of your web server - the setup page shows its name; on shared hosting the folder is often fine as it is, or set its rights to 755 / 775 in the file manager of your host). Never 777 on a shared server. 3.) https for mode 1 and for the app (browsers only post from the app to https). Modes 2 and 3 also work on plain http in your own network. 4.) Your settings below (or as environment variables of the web server): UPSCALE_MODES the modes this receiver takes, e.g. "1,2,3" or "3" UPSCALE_TOKENS mode 1: the token(s), comma separated UPSCALE_SECRET modes 2 + 3: the secret you typed into the webhook card UPSCALE_DATA the folder for the runs: OUTSIDE your web root if you can (else this script puts a "deny all" .htaccess into it) UPSCALE_VIEW_KEY the key of the chart / data / CSV pages (a long random text) UPSCALE_MAIL_TO who gets the alarm e-mails (comma separated; empty: no e-mails) UPSCALE_MAIL_FROM the sender address (on most hosts: an address of your domain) UPSCALE_SMTP_HOST empty: PHP mail(); else your SMTP server - with UPSCALE_SMTP_PORT (587 STARTTLS, 465 TLS), UPSCALE_SMTP_USER, UPSCALE_SMTP_PASS and UPSCALE_SMTP_TLS (starttls | ssl | none - default: ssl on 465, else starttls) UPSCALE_LIMIT_LOW your own limits in g (empty: off): an e-mail when a point is at or UPSCALE_LIMIT_HIGH below LOW (at or above HIGH), again only after it was back inside UPSCALE_SILENCE_MIN with the cron job: an e-mail when a recording run sent no point for this many minutes (0: off) 5.) THE SCALE SENDS ITSELF (WiFi, PRO): in the app LINK -> 🔗 Webhook & JSON API -> 🔗 Webhook export: the address of this file, the security mode + the secret, and tick "📈 Tracking: start, end and every alarm" and "📈 Tracking: every new point". Start a run in the TRACKING MODE - the app can be closed, the scale posts every point by itself. THE APP SENDS (Bluetooth / USB, PRO): Settings -> 🔗 LIMS / ELN FORWARDING: the https address of this file and a token (mode 1), tick the two tracking kinds. The app sends while it is open and connected; the scale keeps recording when it is closed, and the app sends the missing alarms and the newest point when it connects again. 6.) The silence check (optional), a cron job every 5 minutes: 0-59/5 * * * * php /path/to/upscale-tracking-receiver.php --check ---------------------------------------------------------------------------------------- What you get in the data folder: ---------------------------------------------------------------------------------------- runs///points.csv number,epoch_s,time_utc,gross_g,net_g - one line per point (gross: against the zero of the run, net: like the display - the same until a tare) runs///alarms.jsonl every alarm (of the scale and your own limits) runs///run.json name, state, interval, target, last point ... other/-.jsonl the events of other kinds, as they came state/ seen event ids, the last n per scale (mode 3) receiver.log refused requests, e-mail errors The run id is "-" (e.g. "7-1764316800"): the same from the scale and from the app. A gap (the scale restarted) is a line with an empty weight. Apache with PHP-FPM drops the Authorization header? Add to the .htaccess of this folder: CGIPassAuth On (or: RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}]) ---------------------------------------------------------------------------------------- */ // ---------- your settings ---------- $MODES = array_map('intval', explode(',', getenv('UPSCALE_MODES') ?: '1,2,3')); $TOKENS = array_filter(array_map('trim', explode(',', getenv('UPSCALE_TOKENS') ?: 'CHANGE-ME-TOKEN'))); $SECRET = getenv('UPSCALE_SECRET') ?: 'CHANGE-ME-SECRET'; $DATA = rtrim(getenv('UPSCALE_DATA') ?: __DIR__ . '/upscale-tracking-data', '/'); $VIEW_KEY = getenv('UPSCALE_VIEW_KEY') ?: 'CHANGE-ME-VIEW-KEY'; // the app's address (the offline app - the single file - sends the origin "null": add 'null' only if you use it) $ORIGINS = ['https://up-scales.com']; // e-mail $MAIL_TO = getenv('UPSCALE_MAIL_TO') ?: ''; $MAIL_FROM = getenv('UPSCALE_MAIL_FROM') ?: 'scale@' . preg_replace('/[^A-Za-z0-9.-]/', '', (string)($_SERVER['SERVER_NAME'] ?? 'localhost')); $SMTP = ['host' => getenv('UPSCALE_SMTP_HOST') ?: '', 'port' => (int)(getenv('UPSCALE_SMTP_PORT') ?: 587), 'user' => getenv('UPSCALE_SMTP_USER') ?: '', 'pass' => getenv('UPSCALE_SMTP_PASS') ?: '', 'tls' => strtolower(getenv('UPSCALE_SMTP_TLS') ?: '')]; if(!in_array($SMTP['tls'], ['starttls', 'ssl', 'none'], true)) {$SMTP['tls'] = $SMTP['port'] == 465 ? 'ssl' : 'starttls';} // which events send an e-mail: the alarms of the scale, your own limits, the end of a run, a silent scale $MAIL_KINDS = ['target', 'constant', 'jump', 'restart', 'peak', 'above', 'below', 'low', 'high', 'own_low', 'own_high', 'stop', 'silence']; // your own limits (g, '' = off), the weight they look at ('gross' = the real weight of the item, 'net' = like the display), hysteresis (g) $LIMIT_LOW = getenv('UPSCALE_LIMIT_LOW'); $LIMIT_HIGH = getenv('UPSCALE_LIMIT_HIGH'); $LIMIT_WEIGHT = 'gross'; $LIMIT_HYST = 0.0; $SILENCE_MIN = (int)(getenv('UPSCALE_SILENCE_MIN') ?: 0); // the live weight (event "weight") as a run per day - false: dropped $LIVE_RUNS = true; // the secret of a scale (modes 2 + 3). Several scales with their own secrets: // $secrets = ['a1b2c3d4e5f6' => 'secret of scale 1', '0a1b2c3d4e5f' => 'secret of scale 2']; // return $secrets[strtolower($device)] ?? ''; function secret_for($device) { global $SECRET; return $SECRET; } // ---------- helpers ---------- function not_set($s) {return $s === '' || $s === false || strncmp((string)$s, 'CHANGE-ME', 9) == 0;} function log_line($text) { global $DATA; @file_put_contents($DATA . '/receiver.log', gmdate('Y-m-d\TH:i:s\Z') . ' ' . $text . "\n", FILE_APPEND | LOCK_EX); } function json_file($path) { $j = is_file($path) ? json_decode((string)file_get_contents($path), true) : null; return is_array($j) ? $j : []; } function json_save($path, $data) { if(@file_put_contents($path . '.tmp', json_encode($data, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT), LOCK_EX) === false || !@rename($path . '.tmp', $path)) { throw new RuntimeException('can not write ' . $path . ' - see ?view=setup'); } } // the user this PHP runs as (the owner the data folder needs) function php_user() { if(function_exists('posix_geteuid') && function_exists('posix_getpwuid')) {$u = posix_getpwuid(posix_geteuid()); if($u) {return $u['name'];}} return get_current_user() ?: 'the web server user'; } // why the data folder can not be used ('' = it can): created if missing, then a test file written and removed function data_problem() { global $DATA; foreach(['', '/runs', '/other', '/state', '/state/seen'] as $dir) { $path = $DATA . $dir; if(!is_dir($path) && !@mkdir($path, 0770, true) && !is_dir($path)) { $parent = dirname($path); while(!is_dir($parent) && $parent !== dirname($parent)) {$parent = dirname($parent);} return 'can not create the folder ' . $path . ' - the folder ' . $parent . ' is not writable for ' . php_user() . '. Create it yourself and give it to that user: mkdir ' . $path . ' && chown ' . php_user() . ' ' . $path . ' && chmod 770 ' . $path . ' (shared hosting: create it in the file manager, rights 755 or 775), or set UPSCALE_DATA to a folder that is writable.'; } $test = $path . '/.write-test-' . getmypid(); if(@file_put_contents($test, 'x') !== 1) { return 'the folder ' . $path . ' exists but ' . php_user() . ' can not write into it (owner: ' . (function_exists('posix_getpwuid') && ($o = @posix_getpwuid(fileowner($path))) ? $o['name'] : fileowner($path)) . ', rights: ' . substr(sprintf('%o', fileperms($path)), -4) . '). Fix: chown -R ' . php_user() . ' ' . $DATA . ' && chmod -R u+rwX,g+rwX ' . $DATA . ' (shared hosting: rights 755 / 775 in the file manager; never 777 on a shared server).'; } @unlink($test); } return ''; } function data_dirs() { global $DATA; $why = data_problem(); if($why !== '') { log_line('SETUP: ' . $why); error_log('upscale-tracking-receiver: ' . $why); if(PHP_SAPI === 'cli') {fwrite(STDERR, $why . "\n"); exit(1);} // (500: the scale keeps its points and sends them again when the folder works) http_response_code(500); header('Content-Type: application/json'); echo json_encode(['error' => 'receiver not set up: the data folder is not writable - see ?view=setup']); exit; } if(!is_file($DATA . '/.htaccess')) {file_put_contents($DATA . '/.htaccess', "Require all denied\n");} } // what works (?view=setup&key=..., php --setup) function setup_report() { global $DATA, $MODES, $TOKENS, $SECRET, $VIEW_KEY, $MAIL_TO, $SMTP, $SILENCE_MIN; $why = data_problem(); $rows = [ ['PHP ' . PHP_VERSION, version_compare(PHP_VERSION, '7.4', '>=') ? 'ok' : 'too old: PHP 7.4 or newer'], ['runs as', php_user()], ['data folder ' . $DATA, $why === '' ? 'ok (created / writable)' : $why], ['data folder outside the web root', (isset($_SERVER['DOCUMENT_ROOT']) && $_SERVER['DOCUMENT_ROOT'] !== '' && strpos(realpath($DATA) ?: $DATA, realpath($_SERVER['DOCUMENT_ROOT']) ?: '//') === 0) ? 'no - protected by its .htaccess on Apache; on nginx block it yourself (location ~ /upscale-tracking-data { deny all; })' : 'ok'], ['modes', implode(', ', $MODES)], ['mode 1 token', in_array(1, $MODES, true) ? (array_filter($TOKENS, function($t) {return !not_set($t);}) ? 'set' : 'NOT SET (UPSCALE_TOKENS)') : 'mode 1 off'], ['modes 2 / 3 secret', (in_array(2, $MODES, true) || in_array(3, $MODES, true)) ? (not_set($SECRET) ? 'NOT SET (UPSCALE_SECRET)' : 'set') : 'off'], ['openssl (mode 3)', function_exists('openssl_decrypt') ? 'ok' : (in_array(3, $MODES, true) ? 'MISSING - mode 3 will not work' : 'missing (mode 3 off)')], ['view key', not_set($VIEW_KEY) ? 'NOT SET (UPSCALE_VIEW_KEY)' : 'set'], ['e-mail', $MAIL_TO === '' ? 'off (UPSCALE_MAIL_TO empty)' : ($SMTP['host'] !== '' ? 'SMTP ' . $SMTP['host'] . ':' . $SMTP['port'] . ' (' . $SMTP['tls'] . ')' : (function_exists('mail') ? 'PHP mail()' : 'PHP mail() is disabled on this server - use UPSCALE_SMTP_HOST'))], ['silence check', $SILENCE_MIN > 0 ? 'after ' . $SILENCE_MIN . ' min (needs the cron job)' : 'off'], ]; return $rows; } function safe_device($d) {return preg_match('/^[0-9a-fA-F]{12}$/', (string)$d) ? strtolower($d) : (preg_replace('/[^A-Za-z0-9_-]/', '', (string)$d) ?: 'unknown');} function safe_run($r) {return preg_match('/^(\d{1,3}-\d{1,10}|live-\d{4}-\d{2}-\d{2})$/', (string)$r) ? (string)$r : '';} function run_dir($device, $run) { global $DATA; return $DATA . '/runs/' . safe_device($device) . '/' . $run; } function iso($t) {return gmdate('Y-m-d\TH:i:s', (int)floor($t)) . (($t - floor($t)) > 0.0005 ? sprintf('.%03d', round(($t - floor($t)) * 1000)) : '') . 'Z';} function num($v) {return ($v === null || !is_numeric($v)) ? null : (float)$v;} // ---------- e-mail ---------- $MAIL_QUEUE = []; function mail_later($kind, $subject, $text) { global $MAIL_QUEUE, $MAIL_TO, $MAIL_KINDS; if($MAIL_TO === '' || !in_array($kind, $MAIL_KINDS, true)) {return;} $MAIL_QUEUE[] = [$subject, $text]; } function mail_send_all() { global $MAIL_QUEUE, $SMTP; foreach($MAIL_QUEUE as $m) { $ok = $SMTP['host'] !== '' ? smtp_send($m[0], $m[1]) : mail_plain($m[0], $m[1]); if(!$ok) {log_line('e-mail not sent: ' . $m[0]);} } $MAIL_QUEUE = []; } function mail_plain($subject, $text) { global $MAIL_TO, $MAIL_FROM; $headers = 'From: ' . $MAIL_FROM . "\r\nContent-Type: text/plain; charset=UTF-8\r\nContent-Transfer-Encoding: 8bit"; return mail($MAIL_TO, '=?UTF-8?B?' . base64_encode($subject) . '?=', $text, $headers); } // a small SMTP client: STARTTLS (587), TLS (465) or none (UPSCALE_SMTP_TLS), AUTH LOGIN function smtp_send($subject, $text) { global $SMTP, $MAIL_TO, $MAIL_FROM; $host = ($SMTP['tls'] == 'ssl' ? 'ssl://' : '') . $SMTP['host']; $s = @stream_socket_client($host . ':' . $SMTP['port'], $errno, $error, 15); if(!$s) {log_line('SMTP: ' . $error); return false;} stream_set_timeout($s, 15); $read = function() use ($s) {$all = ''; while(($line = fgets($s, 1024)) !== false) {$all .= $line; if(strlen($line) < 4 || $line[3] == ' ') {break;}} return $all;}; $say = function($cmd, $want) use ($s, $read) {if($cmd !== null) {fwrite($s, $cmd . "\r\n");} $r = $read(); if((int)substr($r, 0, 3) != $want) {log_line('SMTP: ' . trim($r)); return false;} return true;}; $me = preg_replace('/[^A-Za-z0-9.-]/', '', (string)($_SERVER['SERVER_NAME'] ?? 'localhost')) ?: 'localhost'; $ok = $say(null, 220) && $say('EHLO ' . $me, 250); if($ok && $SMTP['tls'] == 'starttls') { $ok = $say('STARTTLS', 220) && stream_socket_enable_crypto($s, true, STREAM_CRYPTO_METHOD_TLSv1_2_CLIENT | STREAM_CRYPTO_METHOD_TLSv1_3_CLIENT) && $say('EHLO ' . $me, 250); } if($ok && $SMTP['user'] !== '') { $ok = $say('AUTH LOGIN', 334) && $say(base64_encode($SMTP['user']), 334) && $say(base64_encode($SMTP['pass']), 235); } $ok = $ok && $say('MAIL FROM:<' . $MAIL_FROM . '>', 250); foreach(array_filter(array_map('trim', explode(',', $MAIL_TO))) as $to) {$ok = $ok && $say('RCPT TO:<' . $to . '>', 250);} if($ok && $say('DATA', 354)) { $body = 'From: ' . $MAIL_FROM . "\r\nTo: " . $MAIL_TO . "\r\nSubject: =?UTF-8?B?" . base64_encode($subject) . "?=\r\nDate: " . date('r') . "\r\nMIME-Version: 1.0\r\nContent-Type: text/plain; charset=UTF-8\r\nContent-Transfer-Encoding: 8bit\r\n\r\n" . preg_replace('/^\./m', '..', str_replace("\n", "\r\n", str_replace("\r\n", "\n", $text))); $ok = $say($body . "\r\n.", 250); } else { $ok = false; } fwrite($s, "QUIT\r\n"); fclose($s); return $ok; } function alarm_mail($kind, $meta, $text, $t, $g) { global $VIEW_KEY; $who = trim(($meta['scale'] ?? '') . ' ' . ($meta['name'] !== '' ? '- ' . $meta['name'] : '')); $line = $text . ($g !== null ? ': ' . round($g, 3) . ' g' : '') . ' at ' . iso($t ?: time()) . ' (UTC)'; $link = ''; if(isset($_SERVER['HTTP_HOST'])) { $link = "\n\nLive chart: " . (empty($_SERVER['HTTPS']) || $_SERVER['HTTPS'] === 'off' ? 'http' : 'https') . '://' . $_SERVER['HTTP_HOST'] . strtok((string)($_SERVER['REQUEST_URI'] ?? ''), '?') . '?view=chart&device=' . rawurlencode($meta['device']) . '&run=' . rawurlencode($meta['run_id']); } mail_later($kind, 'UP↑SCALE ' . $who . ': ' . $text, $line . "\n\nScale: " . ($meta['scale'] ?? '') . ' (' . $meta['device'] . ")\nRun: " . $meta['run_id'] . ($meta['name'] !== '' ? ' "' . $meta['name'] . '"' : '') . "\nLast point: " . ($meta['last_g'] !== null ? round($meta['last_g'], 3) . ' g' : '-') . $link . "\n"); } // ---------- the runs ---------- // run.json of a run (new: the defaults) function run_meta($device, $run) { $m = json_file(run_dir($device, $run) . '/run.json'); return array_merge(['device' => safe_device($device), 'run_id' => $run, 'run' => null, 'name' => '', 'scale' => '', 'src' => '', 'state' => '', 'started' => null, 'updated' => null, 'interval_s' => null, 'target_g' => null, 'start_g' => null, 'unit' => 'g', 'points' => 0, 'last_t' => 0, 'last_g' => null, 'last_n' => 0, 'own' => 0, 'silent' => false, 'stopped' => null], $m); } function run_folder($meta) { $dir = run_dir($meta['device'], $meta['run_id']); if(!is_dir($dir) && !@mkdir($dir, 0770, true) && !is_dir($dir)) {throw new RuntimeException('can not create ' . $dir . ' - see ?view=setup');} return $dir; } function run_save($meta) { $dir = run_folder($meta); $meta['updated'] = time(); json_save($dir . '/run.json', $meta); } // the run id of an event: run_id (scale, app) - else the newest run with that number of this scale (app: before it knows the time of the run) function run_of($device, $d, $fallbackTime) { $id = safe_run($d['run_id'] ?? ''); if($id !== '') {return $id;} $no = (int)($d['run'] ?? 0); $best = ''; $bestUpdated = 0; foreach(glob(run_dir($device, $no . '-*'), GLOB_ONLYDIR) ?: [] as $dir) { $m = json_file($dir . '/run.json'); if(($m['updated'] ?? 0) > $bestUpdated && ($m['updated'] ?? 0) > time() - 2 * 86400) {$bestUpdated = $m['updated']; $best = basename($dir);} } return $best !== '' ? $best : $no . '-' . (int)$fallbackTime; } // the fields every tracking event carries function run_take_fields(&$meta, $ev, $d) { if(!empty($ev['scale'])) {$meta['scale'] = (string)$ev['scale'];} if(isset($d['name']) && $d['name'] !== '') {$meta['name'] = (string)$d['name'];} if(isset($d['run'])) {$meta['run'] = (int)$d['run'];} if(isset($d['state']) && $d['state'] !== '') {$meta['state'] = (string)$d['state'];} foreach(['interval_s', 'target_g', 'start_g'] as $k) {if(array_key_exists($k, $d)) {$meta[$k] = num($d[$k]);}} $meta['src'] = (($ev['src'] ?? '') === 'scale') ? 'scale' : 'app'; if($meta['started'] === null && preg_match('/-(\d{9,10})$/', $meta['run_id'], $mm)) {$meta['started'] = (int)$mm[1];} } // new points ([number, epoch s, gross, net]) into points.csv - only newer than the last one (the scale sends a run again after a // restart: those are dropped here); a point without a weight = a gap (empty) function run_add_points(&$meta, $list) { global $LIMIT_LOW, $LIMIT_HIGH, $LIMIT_WEIGHT, $LIMIT_HYST; $lines = ''; foreach($list as $p) { if(!is_array($p) || count($p) < 3) {continue;} $t = num($p[1]); if($t === null || $t <= $meta['last_t']) {continue;} $gross = num($p[2]); $net = num($p[3] ?? $p[2]); $n = (int)$p[0]; $lines .= $n . ',' . rtrim(rtrim(sprintf('%.3f', $t), '0'), '.') . ',' . iso($t) . ',' . ($gross === null ? '' : $gross) . ',' . ($net === null ? '' : $net) . "\n"; $meta['last_t'] = $t; $meta['last_n'] = $n; $meta['points']++; $meta['silent'] = false; if($gross === null) {continue;} $meta['last_g'] = $gross; // your own limits $g = ($LIMIT_WEIGHT === 'net') ? $net : $gross; if(!not_set($LIMIT_LOW) && is_numeric($LIMIT_LOW)) { if(!($meta['own'] & 1) && $g <= (float)$LIMIT_LOW) {$meta['own'] |= 1; run_alarm($meta, 'own_low', 'below your limit of ' . $LIMIT_LOW . ' g', $n, $t, $g, 'receiver');} elseif(($meta['own'] & 1) && $g > (float)$LIMIT_LOW + $LIMIT_HYST) {$meta['own'] &= ~1;} } if(!not_set($LIMIT_HIGH) && is_numeric($LIMIT_HIGH)) { if(!($meta['own'] & 2) && $g >= (float)$LIMIT_HIGH) {$meta['own'] |= 2; run_alarm($meta, 'own_high', 'above your limit of ' . $LIMIT_HIGH . ' g', $n, $t, $g, 'receiver');} elseif(($meta['own'] & 2) && $g < (float)$LIMIT_HIGH - $LIMIT_HYST) {$meta['own'] &= ~2;} } } if($lines === '') {return;} $dir = run_folder($meta); $file = $dir . '/points.csv'; $head = is_file($file) ? '' : "number,epoch_s,time_utc,gross_g,net_g\n"; if(file_put_contents($file, $head . $lines, FILE_APPEND | LOCK_EX) === false) {throw new RuntimeException('could not store the points');} } function run_alarm(&$meta, $kind, $text, $point, $t, $g, $from) { $dir = run_folder($meta); $line = json_encode(['alarm' => $kind, 'text' => $text, 'point' => $point, 't' => $t, 'time_utc' => $t ? iso($t) : null, 'g' => $g, 'from' => $from], JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE); file_put_contents($dir . '/alarms.jsonl', $line . "\n", FILE_APPEND | LOCK_EX); alarm_mail($kind, $meta, $text, $t, $g); } // one event (an array) -> true: stored function take_event($ev) { global $DATA, $LIVE_RUNS; $type = preg_replace('/[^a-z0-9_-]/', '', strtolower((string)($ev['type'] ?? ''))) ?: 'other'; $device = safe_device($ev['device'] ?? ''); $d = is_array($ev['data'] ?? null) ? $ev['data'] : []; if($type == 'points') { $list = $d['list'] ?? null; // (an app without "list": the newest point from the fields) if(!is_array($list)) {$list = [[(int)($d['points'] ?? 0), strtotime((string)($d['time'] ?? '')) ?: time(), $d['last_point_g'] ?? null]];} $first = (is_array($list[0] ?? null) && is_numeric($list[0][1] ?? null)) ? $list[0][1] : time(); $meta = run_meta($device, run_of($device, $d, $first)); run_take_fields($meta, $ev, $d); run_add_points($meta, $list); run_save($meta); return true; } if($type == 'tracking') { $meta = run_meta($device, run_of($device, $d, strtotime((string)($d['time'] ?? '')) ?: time())); $was = $meta['state']; run_take_fields($meta, $ev, $d); $what = (string)($d['event'] ?? ''); if($what == 'stop' && $meta['stopped'] === null) { $meta['stopped'] = time(); $meta['state'] = 'stopped'; alarm_mail('stop', $meta, 'run stopped' . (($d['points'] ?? null) !== null ? ' after ' . (int)$d['points'] . ' points' : ''), time(), num($d['last_point_g'] ?? null)); } elseif($what == 'alarm') { $key = preg_replace('/[^a-z_]/', '', (string)($d['alarm'] ?? 'alarm')); $t = num($d['alarm_time'] ?? null) ?: (strtotime((string)($d['time'] ?? '')) ?: time()); $g = array_key_exists('alarm_g', $d) ? num($d['alarm_g']) : num($d['last_point_g'] ?? null); run_alarm($meta, $key, (string)($d['text'] ?? $key), $d['alarm_point'] ?? ($d['points'] ?? null), $t, $g, $meta['src']); } run_save($meta); return true; } if($type == 'weight') { if(!$LIVE_RUNS) {return true;} $t = strtotime((string)($d['time'] ?? '')) ?: time(); $meta = run_meta($device, 'live-' . gmdate('Y-m-d', (int)$t)); $meta['name'] = 'live weight ' . gmdate('Y-m-d', (int)$t); $meta['state'] = 'live'; $meta['src'] = 'scale'; if(!empty($ev['scale'])) {$meta['scale'] = (string)$ev['scale'];} if($meta['started'] === null) {$meta['started'] = (int)$t;} // (several weights in one second: the time gets the milliseconds of receiving) if($t <= $meta['last_t']) {$t = $meta['last_t'] + 0.001;} run_add_points($meta, [[$meta['last_n'] + 1, $t, $d['grams'] ?? null, $d['grams'] ?? null]]); run_save($meta); return true; } // other kinds: kept as they came $line = json_encode($ev, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE); return file_put_contents($DATA . '/other/' . $type . '-' . gmdate('Y-m-d') . '.jsonl', $line . "\n", FILE_APPEND | LOCK_EX) !== false; } // ---------- the silence check (cron: php upscale-tracking-receiver.php --check) ---------- if(PHP_SAPI === 'cli') { if(in_array('--setup', $argv, true)) { foreach(setup_report() as $row) {echo str_pad($row[0], 36) . ' ' . $row[1] . "\n";} echo "(the command line may run as another user than the web server - the setup page ?view=setup shows the web server's view)\n"; exit(0); } if(!in_array('--check', $argv, true)) {fwrite(STDERR, "usage: php " . basename(__FILE__) . " --check (the silence check, e.g. every 5 minutes by cron)\n php " . basename(__FILE__) . " --setup (what works)\n"); exit(2);} if($SILENCE_MIN <= 0) {echo "UPSCALE_SILENCE_MIN is 0: nothing to check\n"; exit(0);} data_dirs(); $lock = fopen($DATA . '/state/.lock', 'c'); flock($lock, LOCK_EX); foreach(glob($DATA . '/runs/*/*/run.json') ?: [] as $file) { $meta = run_meta(basename(dirname($file, 2)), basename(dirname($file))); if($meta['state'] !== 'recording' || $meta['silent'] || !$meta['last_t']) {continue;} // (a point is due every interval: silent = no point for the minutes you set, and at least 3 intervals) $wait = max($SILENCE_MIN * 60, 3 * (float)($meta['interval_s'] ?: 0)); if(time() - $meta['last_t'] < $wait) {continue;} $meta['silent'] = true; alarm_mail('silence', $meta, 'no point for ' . round((time() - $meta['last_t']) / 60) . ' minutes', time(), $meta['last_g']); run_save($meta); echo 'silent: ' . $meta['device'] . ' ' . $meta['run_id'] . "\n"; } flock($lock, LOCK_UN); mail_send_all(); exit(0); } // ---------- CORS: the app runs in the browser ---------- $origin = (string)($_SERVER['HTTP_ORIGIN'] ?? ''); header('Access-Control-Allow-Origin: ' . (in_array($origin, $ORIGINS, true) ? $origin : $ORIGINS[0])); header('Vary: Origin'); header('Access-Control-Allow-Methods: POST, GET, OPTIONS'); header('Access-Control-Allow-Headers: Content-Type, Authorization'); header('Access-Control-Allow-Private-Network: true'); $method = $_SERVER['REQUEST_METHOD'] ?? 'GET'; if($method == 'OPTIONS') {http_response_code(204); exit;} function finish($code, $text = '') { http_response_code($code); header('Content-Type: application/json'); echo $text === '' ? '' : json_encode(['error' => $text]); exit; } function hdr($name) { $key = 'HTTP_' . strtoupper(str_replace('-', '_', $name)); if(isset($_SERVER[$key])) {return (string)$_SERVER[$key];} if($name == 'Authorization' && isset($_SERVER['REDIRECT_HTTP_AUTHORIZATION'])) {return (string)$_SERVER['REDIRECT_HTTP_AUTHORIZATION'];} return ''; } function refuse($code, $text) { log_line($code . ' ' . $text . ' (' . ($_SERVER['REMOTE_ADDR'] ?? '?') . ')'); finish($code, $text); } // the 12-byte AES-GCM nonce: the 6 bytes of the Device ID (XOR 0xFF for the answer) + n as 6 bytes little-endian function seal_nonce($device, $n, $answer) { $d = hex2bin($device); if($answer) {$d ^= str_repeat("\xFF", 6);} return $d . substr(pack('P', $n), 0, 6); } // ---------- the pages: chart, runs, data, CSV (with the view key) ---------- if($method == 'GET' && isset($_GET['view'])) { $view = (string)$_GET['view']; if(not_set($VIEW_KEY)) {finish(503, 'set UPSCALE_VIEW_KEY');} // (the chart page asks for the key itself and keeps it in this browser: the key is not in the address you share) if($view != 'chart' && !hash_equals($VIEW_KEY, (string)($_GET['key'] ?? hdr('X-View-Key')))) {sleep(1); finish(401, 'wrong or missing key');} if($view == 'chart') { header('Content-Type: text/html; charset=utf-8'); header('Cache-Control: no-store'); header("Content-Security-Policy: default-src 'none'; script-src 'unsafe-inline'; style-src 'unsafe-inline'; connect-src 'self'"); echo chart_page(); exit; } if($view == 'setup') { header('Content-Type: text/plain; charset=utf-8'); header('Cache-Control: no-store'); foreach(setup_report() as $row) {echo str_pad($row[0], 36) . ' ' . $row[1] . "\n";} exit; } if($view == 'runs') { $out = []; foreach(glob($DATA . '/runs/*/*/run.json') ?: [] as $file) {$out[] = run_meta(basename(dirname($file, 2)), basename(dirname($file)));} usort($out, function($a, $b) {return ($b['updated'] ?? 0) <=> ($a['updated'] ?? 0);}); header('Content-Type: application/json'); header('Cache-Control: no-store'); echo json_encode($out, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE); exit; } $device = safe_device($_GET['device'] ?? ''); $run = safe_run($_GET['run'] ?? ''); if($run === '' || !is_dir(run_dir($device, $run))) {finish(404, 'no such run');} $dir = run_dir($device, $run); if($view == 'csv') { header('Content-Type: text/csv; charset=utf-8'); header('Content-Disposition: attachment; filename="upscale-' . $device . '-' . $run . '.csv"'); if(is_file($dir . '/points.csv')) {readfile($dir . '/points.csv');} else {echo "number,epoch_s,time_utc,gross_g,net_g\n";} exit; } if($view == 'data') { // points newer than "since" (epoch s): [[t, gross, net], ...] - the first load: all (at most 20000: then every k-th) $since = (float)($_GET['since'] ?? 0); $points = []; if(is_file($dir . '/points.csv')) { $f = fopen($dir . '/points.csv', 'r'); fgets($f); while(($line = fgets($f)) !== false) { $c = explode(',', trim($line)); if(count($c) < 5 || (float)$c[1] <= $since) {continue;} $points[] = [(float)$c[1], $c[3] === '' ? null : (float)$c[3], $c[4] === '' ? null : (float)$c[4]]; } fclose($f); } if(count($points) > 20000) { $k = (int)ceil(count($points) / 20000); $last = end($points); $points = array_values(array_filter($points, function($p, $i) use ($k) {return $i % $k == 0 || $p[1] === null;}, ARRAY_FILTER_USE_BOTH)); if(end($points) !== $last) {$points[] = $last;} } $alarms = []; if(is_file($dir . '/alarms.jsonl')) { foreach(file($dir . '/alarms.jsonl', FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES) as $line) {$a = json_decode($line, true); if($a) {$alarms[] = $a;}} } header('Content-Type: application/json'); header('Cache-Control: no-store'); echo json_encode(['run' => run_meta($device, $run), 'points' => $points, 'alarms' => $alarms], JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE); exit; } finish(404, 'no such view'); } // ---------- an event of the scale or of the app ---------- if($method != 'POST' && $method != 'GET') {finish(405);} $isPoll = ($method == 'GET'); if($isPoll && ($_GET['poll'] ?? '') !== '1') {finish(405);} $raw = $isPoll ? '' : (string)file_get_contents('php://input'); $body = $isPoll ? null : json_decode($raw); // which mode: the form of the request says it if(hdr('X-Upscale-Signature') !== '') {$mode = 2;} elseif($isPoll ? isset($_GET['n']) : (is_object($body) && ($body->schema ?? '') === 'upscale.sealed/1')) {$mode = 3;} else {$mode = 1;} if(!in_array($mode, $MODES, true)) {finish(401, 'mode ' . $mode . ' not accepted here');} if($mode == 1 && !array_filter($TOKENS, function($t) {return !not_set($t);})) {finish(503, 'set UPSCALE_TOKENS');} $device = $isPoll ? (string)($_GET['device'] ?? '') : (string)(is_object($body) ? ($body->device ?? '') : ''); if($mode != 1 && not_set(secret_for($device))) {finish(503, 'set UPSCALE_SECRET');} data_dirs(); $lock = fopen($DATA . '/state/.lock', 'c'); flock($lock, LOCK_EX); $event = null; $nonce = ''; $n = 0; if($mode == 1) { $auth = hdr('Authorization'); $given = strncmp($auth, 'Bearer ', 7) == 0 ? substr($auth, 7) : (hdr('X-API-Key') !== '' ? hdr('X-API-Key') : (string)($_GET['token'] ?? '')); $ok = false; foreach($TOKENS as $t) {if(!not_set($t) && hash_equals($t, $given)) {$ok = true;}} if(!$ok) {refuse(401, 'mode 1: wrong or missing token');} $event = $raw; } elseif($mode == 2) { $nonce = hdr('X-Upscale-Nonce'); $want = 'sha256=' . hash_hmac('sha256', hdr('X-Upscale-Time') . '.' . $nonce . '.' . $raw, secret_for($device)); if(!hash_equals($want, hdr('X-Upscale-Signature'))) {refuse(401, 'mode 2: signature wrong');} $event = $raw; } else { if(!function_exists('openssl_decrypt')) {refuse(500, 'mode 3 needs the PHP openssl extension');} $n = $isPoll ? (string)($_GET['n'] ?? '') : ($body->n ?? ''); if(!preg_match('/^[0-9a-fA-F]{12}$/', $device) || !preg_match('/^[0-9]{1,15}$/', (string)$n) || (int)$n < 1 || (int)$n > 0xFFFFFFFFFFFF) {refuse(400, 'mode 3: device or n wrong');} $n = (int)$n; $key = hash('sha256', secret_for($device), true); if($isPoll) { $tag = ''; openssl_encrypt('', 'aes-256-gcm', $key, OPENSSL_RAW_DATA, seal_nonce($device, $n, false), $tag, '', 16); if(!hash_equals(bin2hex($tag), strtolower((string)($_GET['t'] ?? '')))) {refuse(401, 'mode 3: poll tag t wrong or missing');} } else { $bin = base64_decode((string)($body->ct ?? ''), true); $plain = ($bin !== false && strlen($bin) > 16) ? openssl_decrypt(substr($bin, 0, -16), 'aes-256-gcm', $key, OPENSSL_RAW_DATA, seal_nonce($device, $n, false), substr($bin, -16)) : false; if($plain === false) {refuse(401, 'mode 3: the envelope does not open');} $event = $plain; } // replay check: n only goes up (per scale) $lastFile = $DATA . '/state/last-n.json'; $last = json_file($lastFile); $dev = strtolower($device); if($n <= ($last[$dev] ?? 0)) {refuse(409, 'mode 3: n ' . $n . ' not higher than ' . ($last[$dev] ?? 0) . ' (replay)');} $last[$dev] = $n; json_save($lastFile, $last); } $answer = []; $status = 200; if(!$isPoll) { $ev = json_decode((string)$event, true); if(!is_array($ev) || empty($ev['id']) || !is_string($ev['id']) || empty($ev['type'])) { log_line('400 not an event (' . ($_SERVER['REMOTE_ADDR'] ?? '?') . ')'); if($mode == 1) {finish(400, 'not an event');} // (modes 2 + 3: the refusal goes signed / sealed like an answer) $status = 400; $answer = ['error' => 'not an event']; } else { // a doubled id (a lost answer, a resend): not taken again - acknowledged again (points: by their time, run_add_points) $hid = hash('sha256', $ev['id']); $marker = $DATA . '/state/seen/' . substr($hid, 0, 2) . '/' . $hid; if(!in_array($ev['type'], ['points', 'weight'], true) && is_file($marker)) { $answer = ['ack' => $ev['id'], 'ref' => trim((string)file_get_contents($marker))]; } else { try { if(!take_event($ev)) {throw new RuntimeException('could not store');} } catch(Throwable $e) { refuse(500, $e->getMessage()); } $ref = gmdate('Ymd') . '-' . substr($hid, 0, 16); if(!in_array($ev['type'], ['points', 'weight'], true)) { if(!is_dir(dirname($marker))) {mkdir(dirname($marker), 0770, true);} file_put_contents($marker, $ref); } $answer = ['ack' => $ev['id'], 'ref' => $ref]; } } } flock($lock, LOCK_UN); // ---------- the answer: signed (mode 2) or sealed (mode 3) ---------- $out = json_encode((object)$answer, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE); http_response_code($status); header('Content-Type: application/json'); if($mode == 2) { $t = (string)time(); header('X-Upscale-Time: ' . $t); header('X-Upscale-Nonce: ' . $nonce); header('X-Upscale-Signature: sha256=' . hash_hmac('sha256', $t . '.' . $nonce . '.' . $out, secret_for($device))); } elseif($mode == 3) { $tag = ''; $ct = openssl_encrypt($out, 'aes-256-gcm', hash('sha256', secret_for($device), true), OPENSSL_RAW_DATA, seal_nonce($device, $n, true), $tag, '', 16); $out = json_encode(['schema' => 'upscale.sealed/1', 'n' => $n, 'ct' => base64_encode($ct . $tag)], JSON_UNESCAPED_SLASHES); // (never \/ in the base64) } header('Content-Length: ' . strlen($out)); echo $out; // the e-mails after the answer: the scale does not wait for your mail server if($MAIL_QUEUE) { if(function_exists('fastcgi_finish_request')) {fastcgi_finish_request();} else {@ob_end_flush(); flush();} ignore_user_abort(true); mail_send_all(); } exit; // ---------- the live chart (plain JavaScript, no library) ---------- function chart_page() { return <<<'HTML' UP↑SCALE tracking - live chart

UP↑SCALE 📈 live chart

now-
change since start-
rate (last hour)-
points-
Alarms
none
HTML; }