Initial commit: aplicatie de cantarire si etichetare
Aplicatie Flask + SQLite pentru productie alimentara: cantarirea componentelor unui produs finit si tiparirea etichetei prin QZ Tray. - produse finite (retete) formate din componente cantarite - designer vizual de etichete (mm/px, zona sigura, campuri variabile, cod QR cu continut din mai multe bucati) - legare produs finit -> sablon de eticheta - navigare pe doua taburi: Cantarire / Setari - administrare: componente, produse finite, sabloane, campuri, istoric - backup, resetare baza de date, checklist de pregatire, /healthz - CLI de administrare si serviciu systemd pentru productie - vendor/syncpulse-scale-bridge (GPL-3.0-or-later) pentru citirea cantarului
This commit is contained in:
@@ -0,0 +1,4 @@
|
||||
* text=auto eol=lf
|
||||
*.bat text eol=crlf
|
||||
*.png binary
|
||||
*.ico binary
|
||||
@@ -0,0 +1,53 @@
|
||||
name: CI
|
||||
|
||||
on:
|
||||
push:
|
||||
branches: [main]
|
||||
tags: ["v*"]
|
||||
pull_request:
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
|
||||
jobs:
|
||||
test:
|
||||
strategy:
|
||||
fail-fast: false
|
||||
matrix:
|
||||
os: [windows-latest, ubuntu-latest]
|
||||
python: ["3.9", "3.12"]
|
||||
runs-on: ${{ matrix.os }}
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- uses: actions/setup-python@v5
|
||||
with:
|
||||
python-version: ${{ matrix.python }}
|
||||
- run: python -m pip install -r requirements.txt pytest
|
||||
- run: python -m pytest -q
|
||||
|
||||
windows-exe:
|
||||
needs: test
|
||||
runs-on: windows-latest
|
||||
permissions:
|
||||
contents: write
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- uses: actions/setup-python@v5
|
||||
with:
|
||||
python-version: "3.12"
|
||||
- run: python -m pip install -r requirements-dev.txt
|
||||
- run: python scripts/build.py
|
||||
- uses: actions/upload-artifact@v4
|
||||
with:
|
||||
name: SyncPulseScaleBridge
|
||||
path: |
|
||||
dist/SyncPulseScaleBridge.exe
|
||||
dist/SyncPulseScaleBridge.exe.sha256
|
||||
- name: Attach to the release
|
||||
if: startsWith(github.ref, 'refs/tags/v')
|
||||
shell: bash
|
||||
env:
|
||||
GH_TOKEN: ${{ github.token }}
|
||||
run: |
|
||||
gh release view "$GITHUB_REF_NAME" >/dev/null 2>&1 || gh release create "$GITHUB_REF_NAME" --title "$GITHUB_REF_NAME" --notes-file CHANGELOG.md
|
||||
gh release upload "$GITHUB_REF_NAME" dist/SyncPulseScaleBridge.exe dist/SyncPulseScaleBridge.exe.sha256 --clobber
|
||||
@@ -0,0 +1,22 @@
|
||||
# settings and logs written next to the program (they hold the access key)
|
||||
bridge.json
|
||||
bridge.json.broken
|
||||
bridge.log*
|
||||
|
||||
# build output
|
||||
build/
|
||||
dist/
|
||||
*.spec
|
||||
|
||||
# Python
|
||||
__pycache__/
|
||||
*.py[cod]
|
||||
.venv*/
|
||||
.pytest_cache/
|
||||
*.egg-info/
|
||||
|
||||
# editors / OS
|
||||
.vscode/
|
||||
.idea/
|
||||
Thumbs.db
|
||||
.DS_Store
|
||||
+51
@@ -0,0 +1,51 @@
|
||||
# Changelog
|
||||
|
||||
## 1.1.2 — 2026-10-13
|
||||
|
||||
- Platform-neutral wording: the control page, command line, README and package metadata describe the bridge
|
||||
for any system that needs a weight; the *Connect* tab is now **Network access** and shows the request to send
|
||||
(`GET /weight?profile=…` with `X-Bridge-Token`).
|
||||
|
||||
## 1.1.1 — 2026-10-11
|
||||
|
||||
- Fix: a continuous format whose frames are closed only by the start of the next one (XK3190 / YH-T7E
|
||||
`=081.100=081.100…`) was not read by `/weight` when the indicator pauses between frames, so that every frame
|
||||
arrives on its own — detection found it, the live reading did not. Each chunk is now read together with the
|
||||
end of the previous one.
|
||||
- `xk3190_reversed` field-tested on a Yaohua YH-T7E indicator (9600 8N1, about nine frames a second).
|
||||
|
||||
## 1.1.0 — 2026-10-11
|
||||
|
||||
Scales that send only when their Print key is pressed — typically indicators wired to a label printer.
|
||||
|
||||
- New protocol `label_print`: reads the label an indicator sends to its label printer — TSPL/TSPL2 (TSC and
|
||||
compatibles), EPL2 (Zebra/Eltron, Argox) and ZPL (Zebra). The weight is the number printed with a weight unit;
|
||||
the other values on the label (order number, shift, date, time, thickness …) come along as `fields`.
|
||||
Field-tested on a PTC400 indicator printing to a TSC printer (TSPL, 9600 8N1).
|
||||
- Auto-detection: new *wait for Print* option (`--wait-print SECONDS`) holds the port open until the operator
|
||||
presses Print, steps to the next speed if the data is unreadable, and reads 7E1/7O1 from a single press; new
|
||||
*listen only* option (`--listen-only`) never sends a byte to the device.
|
||||
- The bridge keeps the ports of such scales open all the time and records every printed label: the last 500 in
|
||||
memory (`GET /labels?profile=…&after=SEQ`) and a daily `labels/<profile>-YYYY-MM-DD.jsonl` file.
|
||||
- `/weight` answers include `fields` and `on_print`; a print-only scale answers at once ("waiting for the Print
|
||||
key") instead of holding the caller.
|
||||
- The control page shows the last printed label, its fields and a short label history.
|
||||
|
||||
## 1.0.0 — 2026-10-01
|
||||
|
||||
First public release.
|
||||
|
||||
- Automatic detection of the port, speed, framing (8N1, 7E1, 7O1 …) and protocol, with quick and thorough modes,
|
||||
confidence score, raw samples and a cancel button. Read-only requests only.
|
||||
- Protocol library: Mettler Toledo MT-SICS and Toledo Continuous, A&D, SMA, NCI 3835, Ohaus, Sartorius SBI,
|
||||
CAS (experimental), XK3190 (tF=0 and reversed stream), Mahak MDS (field-tested), generic text, custom binary and
|
||||
custom text formats.
|
||||
- Saved scale profiles and a parsed-weight API: `GET/POST /weight` with value, unit, stability, net/gross,
|
||||
overload, age and checksum result; unit conversion.
|
||||
- Compatible with SyncPulse Serial Bridge 1.x (`/health`, `/ports`, `POST /read`, `bridge.json`).
|
||||
- Bilingual control page (English/Persian): live weights, auto-detection, connection details, access key,
|
||||
allowed clients, raw monitor with protocol guesses, protocol library, about.
|
||||
- One-click Windows Firewall rule and start-with-Windows task (SYSTEM, no 72-hour limit, restart on failure),
|
||||
both with a UAC prompt.
|
||||
- Single-file Windows program with version information; single-instance start that opens the running copy.
|
||||
- Simulated scales for every protocol (`--simulate`) and a test suite that needs no hardware.
|
||||
+32
@@ -0,0 +1,32 @@
|
||||
# Contributing
|
||||
|
||||
Thank you for helping more scales work out of the box.
|
||||
|
||||
## Reporting a scale that is not recognised
|
||||
|
||||
Open an issue with:
|
||||
|
||||
- the brand and model of the indicator, and its serial settings menu if you know it;
|
||||
- what **Manual & monitor** shows (hex and text) at the speed and framing that gives readable data;
|
||||
- what the display showed at that moment (e.g. `0.550 kg`, stable).
|
||||
|
||||
## Adding a protocol
|
||||
|
||||
1. In `scale_bridge/protocols.py`, write a `Protocol` subclass whose `readings(data)` returns `Reading`s from raw
|
||||
bytes — value, unit, and `stable`/`net`/`overload`/`checksum_ok` when the format carries them. Never raise on
|
||||
bad input; skip what does not match.
|
||||
2. Add it to `_catalogue()` with `kind`, the **read-only** `request` (if any), `families`, `reference` and
|
||||
`specificity` (3 = strictly framed or checksummed, 2 = distinctive text, 1 = loose).
|
||||
3. Add its id to `CONTINUOUS_IDS` and/or `POLL_IDS` so detection tries it.
|
||||
4. Teach `scale_bridge/simulator.py` to produce it (`frame_for`, and `REQUESTS` or `CONTINUOUS`).
|
||||
5. Add tests in `tests/test_protocols.py` with sample frames from the manufacturer's document, and a case in
|
||||
`tests/test_detect.py`.
|
||||
6. Run `python -m pytest`.
|
||||
|
||||
Never add a request that changes the scale (zero, tare, reset, print, display off, configuration) to detection.
|
||||
|
||||
## Code
|
||||
|
||||
- Python 3.9+, standard library plus `pyserial` only.
|
||||
- Keep the source headers (SPDX line and copyright) and the author attribution described in [NOTICE.md](NOTICE.md).
|
||||
- Contributions are accepted under the project's licence (GPL-3.0-or-later with the section 7(b) attribution term).
|
||||
+674
@@ -0,0 +1,674 @@
|
||||
GNU GENERAL PUBLIC LICENSE
|
||||
Version 3, 29 June 2007
|
||||
|
||||
Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
|
||||
Everyone is permitted to copy and distribute verbatim copies
|
||||
of this license document, but changing it is not allowed.
|
||||
|
||||
Preamble
|
||||
|
||||
The GNU General Public License is a free, copyleft license for
|
||||
software and other kinds of works.
|
||||
|
||||
The licenses for most software and other practical works are designed
|
||||
to take away your freedom to share and change the works. By contrast,
|
||||
the GNU General Public License is intended to guarantee your freedom to
|
||||
share and change all versions of a program--to make sure it remains free
|
||||
software for all its users. We, the Free Software Foundation, use the
|
||||
GNU General Public License for most of our software; it applies also to
|
||||
any other work released this way by its authors. You can apply it to
|
||||
your programs, too.
|
||||
|
||||
When we speak of free software, we are referring to freedom, not
|
||||
price. Our General Public Licenses are designed to make sure that you
|
||||
have the freedom to distribute copies of free software (and charge for
|
||||
them if you wish), that you receive source code or can get it if you
|
||||
want it, that you can change the software or use pieces of it in new
|
||||
free programs, and that you know you can do these things.
|
||||
|
||||
To protect your rights, we need to prevent others from denying you
|
||||
these rights or asking you to surrender the rights. Therefore, you have
|
||||
certain responsibilities if you distribute copies of the software, or if
|
||||
you modify it: responsibilities to respect the freedom of others.
|
||||
|
||||
For example, if you distribute copies of such a program, whether
|
||||
gratis or for a fee, you must pass on to the recipients the same
|
||||
freedoms that you received. You must make sure that they, too, receive
|
||||
or can get the source code. And you must show them these terms so they
|
||||
know their rights.
|
||||
|
||||
Developers that use the GNU GPL protect your rights with two steps:
|
||||
(1) assert copyright on the software, and (2) offer you this License
|
||||
giving you legal permission to copy, distribute and/or modify it.
|
||||
|
||||
For the developers' and authors' protection, the GPL clearly explains
|
||||
that there is no warranty for this free software. For both users' and
|
||||
authors' sake, the GPL requires that modified versions be marked as
|
||||
changed, so that their problems will not be attributed erroneously to
|
||||
authors of previous versions.
|
||||
|
||||
Some devices are designed to deny users access to install or run
|
||||
modified versions of the software inside them, although the manufacturer
|
||||
can do so. This is fundamentally incompatible with the aim of
|
||||
protecting users' freedom to change the software. The systematic
|
||||
pattern of such abuse occurs in the area of products for individuals to
|
||||
use, which is precisely where it is most unacceptable. Therefore, we
|
||||
have designed this version of the GPL to prohibit the practice for those
|
||||
products. If such problems arise substantially in other domains, we
|
||||
stand ready to extend this provision to those domains in future versions
|
||||
of the GPL, as needed to protect the freedom of users.
|
||||
|
||||
Finally, every program is threatened constantly by software patents.
|
||||
States should not allow patents to restrict development and use of
|
||||
software on general-purpose computers, but in those that do, we wish to
|
||||
avoid the special danger that patents applied to a free program could
|
||||
make it effectively proprietary. To prevent this, the GPL assures that
|
||||
patents cannot be used to render the program non-free.
|
||||
|
||||
The precise terms and conditions for copying, distribution and
|
||||
modification follow.
|
||||
|
||||
TERMS AND CONDITIONS
|
||||
|
||||
0. Definitions.
|
||||
|
||||
"This License" refers to version 3 of the GNU General Public License.
|
||||
|
||||
"Copyright" also means copyright-like laws that apply to other kinds of
|
||||
works, such as semiconductor masks.
|
||||
|
||||
"The Program" refers to any copyrightable work licensed under this
|
||||
License. Each licensee is addressed as "you". "Licensees" and
|
||||
"recipients" may be individuals or organizations.
|
||||
|
||||
To "modify" a work means to copy from or adapt all or part of the work
|
||||
in a fashion requiring copyright permission, other than the making of an
|
||||
exact copy. The resulting work is called a "modified version" of the
|
||||
earlier work or a work "based on" the earlier work.
|
||||
|
||||
A "covered work" means either the unmodified Program or a work based
|
||||
on the Program.
|
||||
|
||||
To "propagate" a work means to do anything with it that, without
|
||||
permission, would make you directly or secondarily liable for
|
||||
infringement under applicable copyright law, except executing it on a
|
||||
computer or modifying a private copy. Propagation includes copying,
|
||||
distribution (with or without modification), making available to the
|
||||
public, and in some countries other activities as well.
|
||||
|
||||
To "convey" a work means any kind of propagation that enables other
|
||||
parties to make or receive copies. Mere interaction with a user through
|
||||
a computer network, with no transfer of a copy, is not conveying.
|
||||
|
||||
An interactive user interface displays "Appropriate Legal Notices"
|
||||
to the extent that it includes a convenient and prominently visible
|
||||
feature that (1) displays an appropriate copyright notice, and (2)
|
||||
tells the user that there is no warranty for the work (except to the
|
||||
extent that warranties are provided), that licensees may convey the
|
||||
work under this License, and how to view a copy of this License. If
|
||||
the interface presents a list of user commands or options, such as a
|
||||
menu, a prominent item in the list meets this criterion.
|
||||
|
||||
1. Source Code.
|
||||
|
||||
The "source code" for a work means the preferred form of the work
|
||||
for making modifications to it. "Object code" means any non-source
|
||||
form of a work.
|
||||
|
||||
A "Standard Interface" means an interface that either is an official
|
||||
standard defined by a recognized standards body, or, in the case of
|
||||
interfaces specified for a particular programming language, one that
|
||||
is widely used among developers working in that language.
|
||||
|
||||
The "System Libraries" of an executable work include anything, other
|
||||
than the work as a whole, that (a) is included in the normal form of
|
||||
packaging a Major Component, but which is not part of that Major
|
||||
Component, and (b) serves only to enable use of the work with that
|
||||
Major Component, or to implement a Standard Interface for which an
|
||||
implementation is available to the public in source code form. A
|
||||
"Major Component", in this context, means a major essential component
|
||||
(kernel, window system, and so on) of the specific operating system
|
||||
(if any) on which the executable work runs, or a compiler used to
|
||||
produce the work, or an object code interpreter used to run it.
|
||||
|
||||
The "Corresponding Source" for a work in object code form means all
|
||||
the source code needed to generate, install, and (for an executable
|
||||
work) run the object code and to modify the work, including scripts to
|
||||
control those activities. However, it does not include the work's
|
||||
System Libraries, or general-purpose tools or generally available free
|
||||
programs which are used unmodified in performing those activities but
|
||||
which are not part of the work. For example, Corresponding Source
|
||||
includes interface definition files associated with source files for
|
||||
the work, and the source code for shared libraries and dynamically
|
||||
linked subprograms that the work is specifically designed to require,
|
||||
such as by intimate data communication or control flow between those
|
||||
subprograms and other parts of the work.
|
||||
|
||||
The Corresponding Source need not include anything that users
|
||||
can regenerate automatically from other parts of the Corresponding
|
||||
Source.
|
||||
|
||||
The Corresponding Source for a work in source code form is that
|
||||
same work.
|
||||
|
||||
2. Basic Permissions.
|
||||
|
||||
All rights granted under this License are granted for the term of
|
||||
copyright on the Program, and are irrevocable provided the stated
|
||||
conditions are met. This License explicitly affirms your unlimited
|
||||
permission to run the unmodified Program. The output from running a
|
||||
covered work is covered by this License only if the output, given its
|
||||
content, constitutes a covered work. This License acknowledges your
|
||||
rights of fair use or other equivalent, as provided by copyright law.
|
||||
|
||||
You may make, run and propagate covered works that you do not
|
||||
convey, without conditions so long as your license otherwise remains
|
||||
in force. You may convey covered works to others for the sole purpose
|
||||
of having them make modifications exclusively for you, or provide you
|
||||
with facilities for running those works, provided that you comply with
|
||||
the terms of this License in conveying all material for which you do
|
||||
not control copyright. Those thus making or running the covered works
|
||||
for you must do so exclusively on your behalf, under your direction
|
||||
and control, on terms that prohibit them from making any copies of
|
||||
your copyrighted material outside their relationship with you.
|
||||
|
||||
Conveying under any other circumstances is permitted solely under
|
||||
the conditions stated below. Sublicensing is not allowed; section 10
|
||||
makes it unnecessary.
|
||||
|
||||
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
|
||||
|
||||
No covered work shall be deemed part of an effective technological
|
||||
measure under any applicable law fulfilling obligations under article
|
||||
11 of the WIPO copyright treaty adopted on 20 December 1996, or
|
||||
similar laws prohibiting or restricting circumvention of such
|
||||
measures.
|
||||
|
||||
When you convey a covered work, you waive any legal power to forbid
|
||||
circumvention of technological measures to the extent such circumvention
|
||||
is effected by exercising rights under this License with respect to
|
||||
the covered work, and you disclaim any intention to limit operation or
|
||||
modification of the work as a means of enforcing, against the work's
|
||||
users, your or third parties' legal rights to forbid circumvention of
|
||||
technological measures.
|
||||
|
||||
4. Conveying Verbatim Copies.
|
||||
|
||||
You may convey verbatim copies of the Program's source code as you
|
||||
receive it, in any medium, provided that you conspicuously and
|
||||
appropriately publish on each copy an appropriate copyright notice;
|
||||
keep intact all notices stating that this License and any
|
||||
non-permissive terms added in accord with section 7 apply to the code;
|
||||
keep intact all notices of the absence of any warranty; and give all
|
||||
recipients a copy of this License along with the Program.
|
||||
|
||||
You may charge any price or no price for each copy that you convey,
|
||||
and you may offer support or warranty protection for a fee.
|
||||
|
||||
5. Conveying Modified Source Versions.
|
||||
|
||||
You may convey a work based on the Program, or the modifications to
|
||||
produce it from the Program, in the form of source code under the
|
||||
terms of section 4, provided that you also meet all of these conditions:
|
||||
|
||||
a) The work must carry prominent notices stating that you modified
|
||||
it, and giving a relevant date.
|
||||
|
||||
b) The work must carry prominent notices stating that it is
|
||||
released under this License and any conditions added under section
|
||||
7. This requirement modifies the requirement in section 4 to
|
||||
"keep intact all notices".
|
||||
|
||||
c) You must license the entire work, as a whole, under this
|
||||
License to anyone who comes into possession of a copy. This
|
||||
License will therefore apply, along with any applicable section 7
|
||||
additional terms, to the whole of the work, and all its parts,
|
||||
regardless of how they are packaged. This License gives no
|
||||
permission to license the work in any other way, but it does not
|
||||
invalidate such permission if you have separately received it.
|
||||
|
||||
d) If the work has interactive user interfaces, each must display
|
||||
Appropriate Legal Notices; however, if the Program has interactive
|
||||
interfaces that do not display Appropriate Legal Notices, your
|
||||
work need not make them do so.
|
||||
|
||||
A compilation of a covered work with other separate and independent
|
||||
works, which are not by their nature extensions of the covered work,
|
||||
and which are not combined with it such as to form a larger program,
|
||||
in or on a volume of a storage or distribution medium, is called an
|
||||
"aggregate" if the compilation and its resulting copyright are not
|
||||
used to limit the access or legal rights of the compilation's users
|
||||
beyond what the individual works permit. Inclusion of a covered work
|
||||
in an aggregate does not cause this License to apply to the other
|
||||
parts of the aggregate.
|
||||
|
||||
6. Conveying Non-Source Forms.
|
||||
|
||||
You may convey a covered work in object code form under the terms
|
||||
of sections 4 and 5, provided that you also convey the
|
||||
machine-readable Corresponding Source under the terms of this License,
|
||||
in one of these ways:
|
||||
|
||||
a) Convey the object code in, or embodied in, a physical product
|
||||
(including a physical distribution medium), accompanied by the
|
||||
Corresponding Source fixed on a durable physical medium
|
||||
customarily used for software interchange.
|
||||
|
||||
b) Convey the object code in, or embodied in, a physical product
|
||||
(including a physical distribution medium), accompanied by a
|
||||
written offer, valid for at least three years and valid for as
|
||||
long as you offer spare parts or customer support for that product
|
||||
model, to give anyone who possesses the object code either (1) a
|
||||
copy of the Corresponding Source for all the software in the
|
||||
product that is covered by this License, on a durable physical
|
||||
medium customarily used for software interchange, for a price no
|
||||
more than your reasonable cost of physically performing this
|
||||
conveying of source, or (2) access to copy the
|
||||
Corresponding Source from a network server at no charge.
|
||||
|
||||
c) Convey individual copies of the object code with a copy of the
|
||||
written offer to provide the Corresponding Source. This
|
||||
alternative is allowed only occasionally and noncommercially, and
|
||||
only if you received the object code with such an offer, in accord
|
||||
with subsection 6b.
|
||||
|
||||
d) Convey the object code by offering access from a designated
|
||||
place (gratis or for a charge), and offer equivalent access to the
|
||||
Corresponding Source in the same way through the same place at no
|
||||
further charge. You need not require recipients to copy the
|
||||
Corresponding Source along with the object code. If the place to
|
||||
copy the object code is a network server, the Corresponding Source
|
||||
may be on a different server (operated by you or a third party)
|
||||
that supports equivalent copying facilities, provided you maintain
|
||||
clear directions next to the object code saying where to find the
|
||||
Corresponding Source. Regardless of what server hosts the
|
||||
Corresponding Source, you remain obligated to ensure that it is
|
||||
available for as long as needed to satisfy these requirements.
|
||||
|
||||
e) Convey the object code using peer-to-peer transmission, provided
|
||||
you inform other peers where the object code and Corresponding
|
||||
Source of the work are being offered to the general public at no
|
||||
charge under subsection 6d.
|
||||
|
||||
A separable portion of the object code, whose source code is excluded
|
||||
from the Corresponding Source as a System Library, need not be
|
||||
included in conveying the object code work.
|
||||
|
||||
A "User Product" is either (1) a "consumer product", which means any
|
||||
tangible personal property which is normally used for personal, family,
|
||||
or household purposes, or (2) anything designed or sold for incorporation
|
||||
into a dwelling. In determining whether a product is a consumer product,
|
||||
doubtful cases shall be resolved in favor of coverage. For a particular
|
||||
product received by a particular user, "normally used" refers to a
|
||||
typical or common use of that class of product, regardless of the status
|
||||
of the particular user or of the way in which the particular user
|
||||
actually uses, or expects or is expected to use, the product. A product
|
||||
is a consumer product regardless of whether the product has substantial
|
||||
commercial, industrial or non-consumer uses, unless such uses represent
|
||||
the only significant mode of use of the product.
|
||||
|
||||
"Installation Information" for a User Product means any methods,
|
||||
procedures, authorization keys, or other information required to install
|
||||
and execute modified versions of a covered work in that User Product from
|
||||
a modified version of its Corresponding Source. The information must
|
||||
suffice to ensure that the continued functioning of the modified object
|
||||
code is in no case prevented or interfered with solely because
|
||||
modification has been made.
|
||||
|
||||
If you convey an object code work under this section in, or with, or
|
||||
specifically for use in, a User Product, and the conveying occurs as
|
||||
part of a transaction in which the right of possession and use of the
|
||||
User Product is transferred to the recipient in perpetuity or for a
|
||||
fixed term (regardless of how the transaction is characterized), the
|
||||
Corresponding Source conveyed under this section must be accompanied
|
||||
by the Installation Information. But this requirement does not apply
|
||||
if neither you nor any third party retains the ability to install
|
||||
modified object code on the User Product (for example, the work has
|
||||
been installed in ROM).
|
||||
|
||||
The requirement to provide Installation Information does not include a
|
||||
requirement to continue to provide support service, warranty, or updates
|
||||
for a work that has been modified or installed by the recipient, or for
|
||||
the User Product in which it has been modified or installed. Access to a
|
||||
network may be denied when the modification itself materially and
|
||||
adversely affects the operation of the network or violates the rules and
|
||||
protocols for communication across the network.
|
||||
|
||||
Corresponding Source conveyed, and Installation Information provided,
|
||||
in accord with this section must be in a format that is publicly
|
||||
documented (and with an implementation available to the public in
|
||||
source code form), and must require no special password or key for
|
||||
unpacking, reading or copying.
|
||||
|
||||
7. Additional Terms.
|
||||
|
||||
"Additional permissions" are terms that supplement the terms of this
|
||||
License by making exceptions from one or more of its conditions.
|
||||
Additional permissions that are applicable to the entire Program shall
|
||||
be treated as though they were included in this License, to the extent
|
||||
that they are valid under applicable law. If additional permissions
|
||||
apply only to part of the Program, that part may be used separately
|
||||
under those permissions, but the entire Program remains governed by
|
||||
this License without regard to the additional permissions.
|
||||
|
||||
When you convey a copy of a covered work, you may at your option
|
||||
remove any additional permissions from that copy, or from any part of
|
||||
it. (Additional permissions may be written to require their own
|
||||
removal in certain cases when you modify the work.) You may place
|
||||
additional permissions on material, added by you to a covered work,
|
||||
for which you have or can give appropriate copyright permission.
|
||||
|
||||
Notwithstanding any other provision of this License, for material you
|
||||
add to a covered work, you may (if authorized by the copyright holders of
|
||||
that material) supplement the terms of this License with terms:
|
||||
|
||||
a) Disclaiming warranty or limiting liability differently from the
|
||||
terms of sections 15 and 16 of this License; or
|
||||
|
||||
b) Requiring preservation of specified reasonable legal notices or
|
||||
author attributions in that material or in the Appropriate Legal
|
||||
Notices displayed by works containing it; or
|
||||
|
||||
c) Prohibiting misrepresentation of the origin of that material, or
|
||||
requiring that modified versions of such material be marked in
|
||||
reasonable ways as different from the original version; or
|
||||
|
||||
d) Limiting the use for publicity purposes of names of licensors or
|
||||
authors of the material; or
|
||||
|
||||
e) Declining to grant rights under trademark law for use of some
|
||||
trade names, trademarks, or service marks; or
|
||||
|
||||
f) Requiring indemnification of licensors and authors of that
|
||||
material by anyone who conveys the material (or modified versions of
|
||||
it) with contractual assumptions of liability to the recipient, for
|
||||
any liability that these contractual assumptions directly impose on
|
||||
those licensors and authors.
|
||||
|
||||
All other non-permissive additional terms are considered "further
|
||||
restrictions" within the meaning of section 10. If the Program as you
|
||||
received it, or any part of it, contains a notice stating that it is
|
||||
governed by this License along with a term that is a further
|
||||
restriction, you may remove that term. If a license document contains
|
||||
a further restriction but permits relicensing or conveying under this
|
||||
License, you may add to a covered work material governed by the terms
|
||||
of that license document, provided that the further restriction does
|
||||
not survive such relicensing or conveying.
|
||||
|
||||
If you add terms to a covered work in accord with this section, you
|
||||
must place, in the relevant source files, a statement of the
|
||||
additional terms that apply to those files, or a notice indicating
|
||||
where to find the applicable terms.
|
||||
|
||||
Additional terms, permissive or non-permissive, may be stated in the
|
||||
form of a separately written license, or stated as exceptions;
|
||||
the above requirements apply either way.
|
||||
|
||||
8. Termination.
|
||||
|
||||
You may not propagate or modify a covered work except as expressly
|
||||
provided under this License. Any attempt otherwise to propagate or
|
||||
modify it is void, and will automatically terminate your rights under
|
||||
this License (including any patent licenses granted under the third
|
||||
paragraph of section 11).
|
||||
|
||||
However, if you cease all violation of this License, then your
|
||||
license from a particular copyright holder is reinstated (a)
|
||||
provisionally, unless and until the copyright holder explicitly and
|
||||
finally terminates your license, and (b) permanently, if the copyright
|
||||
holder fails to notify you of the violation by some reasonable means
|
||||
prior to 60 days after the cessation.
|
||||
|
||||
Moreover, your license from a particular copyright holder is
|
||||
reinstated permanently if the copyright holder notifies you of the
|
||||
violation by some reasonable means, this is the first time you have
|
||||
received notice of violation of this License (for any work) from that
|
||||
copyright holder, and you cure the violation prior to 30 days after
|
||||
your receipt of the notice.
|
||||
|
||||
Termination of your rights under this section does not terminate the
|
||||
licenses of parties who have received copies or rights from you under
|
||||
this License. If your rights have been terminated and not permanently
|
||||
reinstated, you do not qualify to receive new licenses for the same
|
||||
material under section 10.
|
||||
|
||||
9. Acceptance Not Required for Having Copies.
|
||||
|
||||
You are not required to accept this License in order to receive or
|
||||
run a copy of the Program. Ancillary propagation of a covered work
|
||||
occurring solely as a consequence of using peer-to-peer transmission
|
||||
to receive a copy likewise does not require acceptance. However,
|
||||
nothing other than this License grants you permission to propagate or
|
||||
modify any covered work. These actions infringe copyright if you do
|
||||
not accept this License. Therefore, by modifying or propagating a
|
||||
covered work, you indicate your acceptance of this License to do so.
|
||||
|
||||
10. Automatic Licensing of Downstream Recipients.
|
||||
|
||||
Each time you convey a covered work, the recipient automatically
|
||||
receives a license from the original licensors, to run, modify and
|
||||
propagate that work, subject to this License. You are not responsible
|
||||
for enforcing compliance by third parties with this License.
|
||||
|
||||
An "entity transaction" is a transaction transferring control of an
|
||||
organization, or substantially all assets of one, or subdividing an
|
||||
organization, or merging organizations. If propagation of a covered
|
||||
work results from an entity transaction, each party to that
|
||||
transaction who receives a copy of the work also receives whatever
|
||||
licenses to the work the party's predecessor in interest had or could
|
||||
give under the previous paragraph, plus a right to possession of the
|
||||
Corresponding Source of the work from the predecessor in interest, if
|
||||
the predecessor has it or can get it with reasonable efforts.
|
||||
|
||||
You may not impose any further restrictions on the exercise of the
|
||||
rights granted or affirmed under this License. For example, you may
|
||||
not impose a license fee, royalty, or other charge for exercise of
|
||||
rights granted under this License, and you may not initiate litigation
|
||||
(including a cross-claim or counterclaim in a lawsuit) alleging that
|
||||
any patent claim is infringed by making, using, selling, offering for
|
||||
sale, or importing the Program or any portion of it.
|
||||
|
||||
11. Patents.
|
||||
|
||||
A "contributor" is a copyright holder who authorizes use under this
|
||||
License of the Program or a work on which the Program is based. The
|
||||
work thus licensed is called the contributor's "contributor version".
|
||||
|
||||
A contributor's "essential patent claims" are all patent claims
|
||||
owned or controlled by the contributor, whether already acquired or
|
||||
hereafter acquired, that would be infringed by some manner, permitted
|
||||
by this License, of making, using, or selling its contributor version,
|
||||
but do not include claims that would be infringed only as a
|
||||
consequence of further modification of the contributor version. For
|
||||
purposes of this definition, "control" includes the right to grant
|
||||
patent sublicenses in a manner consistent with the requirements of
|
||||
this License.
|
||||
|
||||
Each contributor grants you a non-exclusive, worldwide, royalty-free
|
||||
patent license under the contributor's essential patent claims, to
|
||||
make, use, sell, offer for sale, import and otherwise run, modify and
|
||||
propagate the contents of its contributor version.
|
||||
|
||||
In the following three paragraphs, a "patent license" is any express
|
||||
agreement or commitment, however denominated, not to enforce a patent
|
||||
(such as an express permission to practice a patent or covenant not to
|
||||
sue for patent infringement). To "grant" such a patent license to a
|
||||
party means to make such an agreement or commitment not to enforce a
|
||||
patent against the party.
|
||||
|
||||
If you convey a covered work, knowingly relying on a patent license,
|
||||
and the Corresponding Source of the work is not available for anyone
|
||||
to copy, free of charge and under the terms of this License, through a
|
||||
publicly available network server or other readily accessible means,
|
||||
then you must either (1) cause the Corresponding Source to be so
|
||||
available, or (2) arrange to deprive yourself of the benefit of the
|
||||
patent license for this particular work, or (3) arrange, in a manner
|
||||
consistent with the requirements of this License, to extend the patent
|
||||
license to downstream recipients. "Knowingly relying" means you have
|
||||
actual knowledge that, but for the patent license, your conveying the
|
||||
covered work in a country, or your recipient's use of the covered work
|
||||
in a country, would infringe one or more identifiable patents in that
|
||||
country that you have reason to believe are valid.
|
||||
|
||||
If, pursuant to or in connection with a single transaction or
|
||||
arrangement, you convey, or propagate by procuring conveyance of, a
|
||||
covered work, and grant a patent license to some of the parties
|
||||
receiving the covered work authorizing them to use, propagate, modify
|
||||
or convey a specific copy of the covered work, then the patent license
|
||||
you grant is automatically extended to all recipients of the covered
|
||||
work and works based on it.
|
||||
|
||||
A patent license is "discriminatory" if it does not include within
|
||||
the scope of its coverage, prohibits the exercise of, or is
|
||||
conditioned on the non-exercise of one or more of the rights that are
|
||||
specifically granted under this License. You may not convey a covered
|
||||
work if you are a party to an arrangement with a third party that is
|
||||
in the business of distributing software, under which you make payment
|
||||
to the third party based on the extent of your activity of conveying
|
||||
the work, and under which the third party grants, to any of the
|
||||
parties who would receive the covered work from you, a discriminatory
|
||||
patent license (a) in connection with copies of the covered work
|
||||
conveyed by you (or copies made from those copies), or (b) primarily
|
||||
for and in connection with specific products or compilations that
|
||||
contain the covered work, unless you entered into that arrangement,
|
||||
or that patent license was granted, prior to 28 March 2007.
|
||||
|
||||
Nothing in this License shall be construed as excluding or limiting
|
||||
any implied license or other defenses to infringement that may
|
||||
otherwise be available to you under applicable patent law.
|
||||
|
||||
12. No Surrender of Others' Freedom.
|
||||
|
||||
If conditions are imposed on you (whether by court order, agreement or
|
||||
otherwise) that contradict the conditions of this License, they do not
|
||||
excuse you from the conditions of this License. If you cannot convey a
|
||||
covered work so as to satisfy simultaneously your obligations under this
|
||||
License and any other pertinent obligations, then as a consequence you may
|
||||
not convey it at all. For example, if you agree to terms that obligate you
|
||||
to collect a royalty for further conveying from those to whom you convey
|
||||
the Program, the only way you could satisfy both those terms and this
|
||||
License would be to refrain entirely from conveying the Program.
|
||||
|
||||
13. Use with the GNU Affero General Public License.
|
||||
|
||||
Notwithstanding any other provision of this License, you have
|
||||
permission to link or combine any covered work with a work licensed
|
||||
under version 3 of the GNU Affero General Public License into a single
|
||||
combined work, and to convey the resulting work. The terms of this
|
||||
License will continue to apply to the part which is the covered work,
|
||||
but the special requirements of the GNU Affero General Public License,
|
||||
section 13, concerning interaction through a network will apply to the
|
||||
combination as such.
|
||||
|
||||
14. Revised Versions of this License.
|
||||
|
||||
The Free Software Foundation may publish revised and/or new versions of
|
||||
the GNU General Public License from time to time. Such new versions will
|
||||
be similar in spirit to the present version, but may differ in detail to
|
||||
address new problems or concerns.
|
||||
|
||||
Each version is given a distinguishing version number. If the
|
||||
Program specifies that a certain numbered version of the GNU General
|
||||
Public License "or any later version" applies to it, you have the
|
||||
option of following the terms and conditions either of that numbered
|
||||
version or of any later version published by the Free Software
|
||||
Foundation. If the Program does not specify a version number of the
|
||||
GNU General Public License, you may choose any version ever published
|
||||
by the Free Software Foundation.
|
||||
|
||||
If the Program specifies that a proxy can decide which future
|
||||
versions of the GNU General Public License can be used, that proxy's
|
||||
public statement of acceptance of a version permanently authorizes you
|
||||
to choose that version for the Program.
|
||||
|
||||
Later license versions may give you additional or different
|
||||
permissions. However, no additional obligations are imposed on any
|
||||
author or copyright holder as a result of your choosing to follow a
|
||||
later version.
|
||||
|
||||
15. Disclaimer of Warranty.
|
||||
|
||||
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
|
||||
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
|
||||
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
|
||||
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
|
||||
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
|
||||
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
|
||||
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
|
||||
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
|
||||
|
||||
16. Limitation of Liability.
|
||||
|
||||
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
|
||||
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
|
||||
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
|
||||
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
|
||||
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
|
||||
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
|
||||
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
|
||||
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
|
||||
SUCH DAMAGES.
|
||||
|
||||
17. Interpretation of Sections 15 and 16.
|
||||
|
||||
If the disclaimer of warranty and limitation of liability provided
|
||||
above cannot be given local legal effect according to their terms,
|
||||
reviewing courts shall apply local law that most closely approximates
|
||||
an absolute waiver of all civil liability in connection with the
|
||||
Program, unless a warranty or assumption of liability accompanies a
|
||||
copy of the Program in return for a fee.
|
||||
|
||||
END OF TERMS AND CONDITIONS
|
||||
|
||||
How to Apply These Terms to Your New Programs
|
||||
|
||||
If you develop a new program, and you want it to be of the greatest
|
||||
possible use to the public, the best way to achieve this is to make it
|
||||
free software which everyone can redistribute and change under these terms.
|
||||
|
||||
To do so, attach the following notices to the program. It is safest
|
||||
to attach them to the start of each source file to most effectively
|
||||
state the exclusion of warranty; and each file should have at least
|
||||
the "copyright" line and a pointer to where the full notice is found.
|
||||
|
||||
<one line to give the program's name and a brief idea of what it does.>
|
||||
Copyright (C) <year> <name of author>
|
||||
|
||||
This program is free software: you can redistribute it and/or modify
|
||||
it under the terms of the GNU General Public License as published by
|
||||
the Free Software Foundation, either version 3 of the License, or
|
||||
(at your option) any later version.
|
||||
|
||||
This program is distributed in the hope that it will be useful,
|
||||
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
GNU General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU General Public License
|
||||
along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
|
||||
Also add information on how to contact you by electronic and paper mail.
|
||||
|
||||
If the program does terminal interaction, make it output a short
|
||||
notice like this when it starts in an interactive mode:
|
||||
|
||||
<program> Copyright (C) <year> <name of author>
|
||||
This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
|
||||
This is free software, and you are welcome to redistribute it
|
||||
under certain conditions; type `show c' for details.
|
||||
|
||||
The hypothetical commands `show w' and `show c' should show the appropriate
|
||||
parts of the General Public License. Of course, your program's commands
|
||||
might be different; for a GUI interface, you would use an "about box".
|
||||
|
||||
You should also get your employer (if you work as a programmer) or school,
|
||||
if any, to sign a "copyright disclaimer" for the program, if necessary.
|
||||
For more information on this, and how to apply and follow the GNU GPL, see
|
||||
<https://www.gnu.org/licenses/>.
|
||||
|
||||
The GNU General Public License does not permit incorporating your program
|
||||
into proprietary programs. If your program is a subroutine library, you
|
||||
may consider it more useful to permit linking proprietary applications with
|
||||
the library. If this is what you want to do, use the GNU Lesser General
|
||||
Public License instead of this License. But first, please read
|
||||
<https://www.gnu.org/licenses/why-not-lgpl.html>.
|
||||
+51
@@ -0,0 +1,51 @@
|
||||
# Notice and additional terms
|
||||
|
||||
**SyncPulse Scale Bridge**
|
||||
Copyright (C) 2026 Farshad Zamani — Cloudtart
|
||||
|
||||
- Author: Farshad Zamani
|
||||
- Company: Cloudtart — <https://cloudtart.com>
|
||||
- GitHub: <https://github.com/farshad-zamani>
|
||||
- LinkedIn: <https://www.linkedin.com/in/farshad-zamani92/>
|
||||
- Source: <https://github.com/farshad-zamani/syncpulse-scale-bridge>
|
||||
|
||||
This program is free software: you can redistribute it and/or modify it under
|
||||
the terms of the GNU General Public License as published by the Free Software
|
||||
Foundation, either version 3 of the License, or (at your option) any later
|
||||
version. See [LICENSE](LICENSE) for the full text.
|
||||
|
||||
This program is distributed in the hope that it will be useful, but WITHOUT
|
||||
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
|
||||
FOR A PARTICULAR PURPOSE.
|
||||
|
||||
## Additional term under section 7(b) of the GNU GPL v3
|
||||
|
||||
As permitted by section 7(b) of the GNU General Public License version 3, the
|
||||
following term is added to the License for this program:
|
||||
|
||||
> **Preservation of author attribution.** Every copy of this program, and
|
||||
> every work based on it, in source or object form, must keep the author
|
||||
> attribution in the Appropriate Legal Notices that the program displays —
|
||||
> the author's name **Farshad Zamani**, the company name **Cloudtart**, and
|
||||
> the links to <https://cloudtart.com>, <https://github.com/farshad-zamani>
|
||||
> and <https://www.linkedin.com/in/farshad-zamani92/> — in the footer and the
|
||||
> "About" page of the user interface, in the `about` command and in the
|
||||
> `/health` response. These notices must stay legible and must not be
|
||||
> removed, hidden or replaced. A modified version must be marked as changed
|
||||
> and must not be presented as the original program or as the work of
|
||||
> another author; the names of modifiers may be added next to, but not in
|
||||
> place of, the original attribution.
|
||||
|
||||
This term does not restrict any other freedom the GNU GPL grants. If you
|
||||
received this program with this term removed, you may restore it.
|
||||
|
||||
## Third-party components
|
||||
|
||||
- [pyserial](https://github.com/pyserial/pyserial) — BSD-3-Clause
|
||||
- The single-file Windows program is packaged with
|
||||
[PyInstaller](https://pyinstaller.org) (GPL-2.0 with a bootloader exception)
|
||||
and contains the Python runtime (PSF License).
|
||||
|
||||
Brand and product names of scale manufacturers mentioned in this project are
|
||||
used only to describe data formats and belong to their owners. This project is
|
||||
not affiliated with or endorsed by any of them.
|
||||
+212
@@ -0,0 +1,212 @@
|
||||
<div dir="rtl">
|
||||
|
||||
<p align="center"><img src="assets/icon.png" width="96" alt=""></p>
|
||||
|
||||
<h1 align="center">SyncPulse Scale Bridge</h1>
|
||||
|
||||
<p align="center">
|
||||
باسکول دارای درگاه RS-232 را به هر رایانهی ویندوزی وصل کنید و یک فایل را اجرا کنید؛ درگاه، سرعت و پروتکل را
|
||||
خودش پیدا میکند، وزن زنده را نشان میدهد و آن را بهصورت JSON روی شبکه در اختیار میگذارد.
|
||||
</p>
|
||||
|
||||
<p align="center"><a href="README.md">English</a> · <b>فارسی</b></p>
|
||||
|
||||
---
|
||||
|
||||
ساختهی **[فرشاد زمانی](https://github.com/farshad-zamani)** در **[کلادتارت (Cloudtart)](https://cloudtart.com)**. نرمافزار
|
||||
آزاد است و با رابط سادهی HTTP/JSON با هر سامانهای کار میکند — ERP، MES، فرم وب، ماکروی صفحهگسترده یا اسکریپت خودتان.
|
||||
|
||||
<p align="center">
|
||||
<img src="docs/screenshots/scales-fa.png" width="49%" alt="وزن زنده">
|
||||
<img src="docs/screenshots/connect-fa.png" width="49%" alt="دسترسی از شبکه">
|
||||
</p>
|
||||
|
||||
## چرا
|
||||
|
||||
بیشتر باسکولها و نمایشگرهای توزین صنعتی هنوز با درگاه سریال کار میکنند و هر برند قالب، سرعت و تنظیم خط خودش
|
||||
را دارد. معمولاً برای وصل کردن یک باسکول باید دفترچه را پیدا کرد، 9600 8N1 یا 2400 7E1 را حدس زد، برنامهی
|
||||
خواندن نوشت و آن را کنار باسکول روشن نگه داشت. این برنامه همهی این کارها را انجام میدهد:
|
||||
|
||||
- **باسکول را خودش پیدا میکند** — روی هر درگاه COM با همهی سرعتهای رایج گوش میدهد، قالب ۷ بیتی با پریتی را
|
||||
تشخیص میدهد و سپس با زبان سازندگان اصلی از باسکول وزن میخواهد. فقط درخواستهای خواندنی فرستاده میشود؛ هیچوقت
|
||||
صفر، تار یا چاپ نمیکند.
|
||||
- **قالبهای زیادی را میخواند** — Mettler Toledo (MT-SICS و Toledo Continuous)، A&D، SMA (Rice Lake، Avery
|
||||
Weigh-Tronix، Cardinal، Fairbanks و…)، NCI، Ohaus، Sartorius SBI، CAS، خانوادهی چینی XK3190، محک MDS، هر متن
|
||||
خوانا، و قالبهای دودویی/متنی دلخواه.
|
||||
- **وزن را نشان میدهد و در اختیار میگذارد** — صفحهی دوزبانه (فارسی/انگلیسی) روی همان رایانه، و API از نوع JSON با
|
||||
مقدار، واحد، پایداری، خالص/ناخالص، بیشازظرفیت و بررسی checksum.
|
||||
- **یک فایل، بدون نصب** — `SyncPulseScaleBridge.exe` را کنار باسکول کپی و اجرا کنید.
|
||||
- **آمادهی محیط تولید** — قطع و وصل کابل USB و درگاه مشغول را تحمل میکند، درگاه فایروال را باز میکند و با یک دکمه
|
||||
همراه ویندوز اجرا میشود، کلید دسترسی دارد و گزارش کارش را در فایل نگه میدارد.
|
||||
|
||||
## شروع سریع (ویندوز)
|
||||
|
||||
۱. فایل `SyncPulseScaleBridge.exe` را از [آخرین نسخه](https://github.com/farshad-zamani/syncpulse-scale-bridge/releases/latest)
|
||||
بگیرید و روی رایانهای که باسکول به آن وصل است، ترجیحاً در پوشهی جداگانه مثل `C:\ScaleBridge\` کپی کنید (فایل
|
||||
تنظیمات `bridge.json` و گزارش کار کنار آن ساخته میشود).
|
||||
|
||||
۲. درگاه RS-232 باسکول را مستقیم یا با مبدل USB به سریال وصل کنید و خروجی سریال نمایشگر را روشن کنید.
|
||||
|
||||
۳. برنامه را با دو بار کلیک اجرا کنید. یک پنجرهی کنسول باز میشود (باز بماند) و صفحهی مدیریت در مرورگر با نشانی
|
||||
`http://127.0.0.1:8765/` باز میشود.
|
||||
|
||||
۴. **پیدا کردن باسکول ← شروع جستجو.** وقتی باسکول پیدا شد، نامی به آن بدهید (مثلاً `packing-1`) و **ذخیره** را بزنید.
|
||||
زبانهی **باسکولها** وزن زندهی آن را نشان میدهد.
|
||||
|
||||
۵. **دسترسی از شبکه:** نشانی و کلید دسترسی را بردارید، **باز کردن درگاه 8765 در فایروال** را بزنید و اگر باید
|
||||
بدون ورود کاربر هم کار کند، **اجرا همراه ویندوز** را بزنید.
|
||||
|
||||
بدون دستگاه هم میتوانید با باسکول شبیهسازیشده امتحان کنید:
|
||||
|
||||
<div dir="ltr">
|
||||
|
||||
```bat
|
||||
SyncPulseScaleBridge.exe --simulate mahak_mds,toledo_cont:4800:7E1,mt_sics
|
||||
```
|
||||
|
||||
</div>
|
||||
|
||||
## تشخیص خودکار چطور کار میکند
|
||||
|
||||
برای هر درگاه انتخابشده:
|
||||
|
||||
۱. **گوش دادن** با سرعتهای 9600، 2400، 4800، 19200، 1200، 38400، 57600 و 115200 (قالب 8N1). باسکولی که خودش
|
||||
پیوسته میفرستد اینجا دیده میشود. اگر بایتها فقط با صفر کردن بیت بالا خوانا شوند، خط ۷ بیت داده با پریتی دارد و
|
||||
دوباره با 7E1/7O1 گوش داده میشود. دادهی رسیده با همهی قالبهای پیوسته مقایسه میشود و قالبهای دارای checksum بر
|
||||
متن ساده مقدماند.
|
||||
|
||||
۲. **پرسیدن** — اگر چیز مفیدی شنیده نشد، هر درخواست خواندنی کتابخانه با هر سرعت و قالب فرستاده میشود (سریع: ۸ حالت؛
|
||||
کامل: ۱۴ حالت) و پاسخ با همان پروتکل بررسی میشود. پاسخ با یک پرسش دوباره تأیید میشود.
|
||||
|
||||
هر نتیجه درصد اطمینان، تنظیم دقیق خط، درخواست، نمونهی دادهی خام و خوانش فعلی را دارد. اگر دادهی خوانا ولی با قالب
|
||||
ناشناخته برسد، همان نمونه گزارش میشود تا در زبانهی **تنظیم دستی و مانیتور** تنظیم شود.
|
||||
|
||||
### باسکولهایی که فقط با کلید «چاپ» میفرستند
|
||||
|
||||
بسیاری از نمایشگرها — بهویژه آنهایی که به لیبلزن وصلاند — تا اپراتور «چاپ» نزند چیزی نمیفرستند و بعد کل
|
||||
برچسب را میفرستند. در «پیدا کردن باسکول» گزینهی **باسکول فقط با زدن کلید چاپ داده میفرستد** (و در صورت تمایل
|
||||
**فقط گوش بده**) را بزنید و وقتی صفحه خواست، چاپ بزنید. برای چنین باسکولی پل **همیشه** درگاه را باز نگه میدارد
|
||||
و هر برچسب را ثبت میکند: وزن، واحد و بقیهی مقادیر برچسب (شماره سفارش، شیفت، تاریخ …) در فایل
|
||||
`labels/<profile>-YYYY-MM-DD.jsonl` و ۵۰۰ مورد آخر از `GET /labels`. برای اینکه لیبلزن هم کار کند، رایانه را
|
||||
با **کابل Y** وصل کنید: TX باسکول (و زمین) هم به چاپگر و هم به RX رایانه؛ رایانه روی این خط چیزی نمیفرستد.
|
||||
|
||||
## قالبهای پشتیبانیشده
|
||||
|
||||
<div dir="ltr">
|
||||
|
||||
| ID | Format | Talks |
|
||||
|---|---|---|
|
||||
| `mt_sics` | Mettler Toledo MT-SICS (`SI`) | on request |
|
||||
| `toledo_cont` | Toledo Continuous (STX + status words, checksum) | continuous |
|
||||
| `and_std` | A&D standard (`ST`/`US`/`OL`, `Q`) | on request / continuous |
|
||||
| `sma` | SMA SCP-0499 (`<LF>W<CR>`) | on request |
|
||||
| `nci` | NCI 3835 (`W<CR>`) | on request |
|
||||
| `ohaus` | Ohaus (`IP`) | on request |
|
||||
| `sartorius` | Sartorius SBI (`ESC P`) | on request |
|
||||
| `cas_enq` | CAS ENQ/ACK/DC1 *(experimental)* | handshake |
|
||||
| `xk3190_tf0` | XK3190 continuous (tF=0, XOR checksum) | continuous |
|
||||
| `xk3190_reversed` | XK3190 `=` reversed-digit stream — tested on real hardware (YH-T7E) | continuous |
|
||||
| `mahak_mds` | Mahak MDS binary (`4D 09 04 07`) — tested on real hardware | on request |
|
||||
| `label_print` | label printer stream: TSPL / EPL2 / ZPL — tested on real hardware (PTC400) | on Print key |
|
||||
| `ascii_generic` | any readable line with a number and a unit | continuous |
|
||||
| `custom_binary` / `custom_ascii` | your own binary frame / regular expression | either |
|
||||
|
||||
</div>
|
||||
|
||||
قالبها بر پایهی مستندات منتشرشدهی سازندگاناند و با فریمهای نمونهی همان مستندات آزمایش شدهاند؛ `mahak_mds` روی
|
||||
باسکول واقعی (محک MDS 13000) آزموده شده است. نام برندها فقط برای توصیف قالب داده است و بسیاری از نمایشگرهای دیگر هم
|
||||
همین قالبها را به کار میبرند.
|
||||
|
||||
|
||||
## API برای هر سامانهی دیگر
|
||||
|
||||
همهی درخواستها بهجز `/health` سرآیند `X-Bridge-Token: <کلید دسترسی>` میخواهند.
|
||||
|
||||
<div dir="ltr">
|
||||
|
||||
```console
|
||||
GET /health
|
||||
GET /ports
|
||||
GET /profiles
|
||||
GET /weight?profile=packing-1
|
||||
GET /weight?port=COM7&protocol=mt_sics&baud=9600&framing=8N1
|
||||
POST /weight {"profile": "packing-1"}
|
||||
POST /read {serial, exchange, frames, max_age_ms, wait_ms}
|
||||
|
||||
$ curl -H "X-Bridge-Token: $KEY" "http://192.168.1.20:8765/weight?profile=packing-1"
|
||||
{"ok": true, "value": 550.0, "unit": "g", "stable": true, "stale": false, "age_ms": 84, ...}
|
||||
```
|
||||
|
||||
</div>
|
||||
|
||||
`stable` اگر قالب باسکول آن را بفرستد از خود باسکول است؛ وگرنه یعنی چند خوانش آخر (پیشفرض ۳) برابر بودهاند.
|
||||
جزئیات کامل در [README انگلیسی](README.md#http-api).
|
||||
|
||||
## امنیت
|
||||
|
||||
- **کلید دسترسی** در اولین اجرا ساخته و در `bridge.json` نگه داشته میشود؛ هر زمان میتوان کلید تازه ساخت.
|
||||
- **سامانههای مجاز** — میتوان فقط IP سرور خودتان را پذیرفت؛ قانون فایروال هم میتواند به یک نشانی محدود شود.
|
||||
- **صفحهی مدیریت فقط محلی است** — فقط روی خود رایانه (`127.0.0.1`) باز میشود و API آن سرآیند ویژه و Host محلی
|
||||
میخواهد تا صفحههای دیگر وب نتوانند آن را به کار بگیرند.
|
||||
- **نسبت به باسکول فقطخواندنی است** — هیچ فرمان صفر، تار، چاپ یا تنظیم فرستاده نمیشود.
|
||||
|
||||
## فایروال و اجرا در پسزمینه
|
||||
|
||||
فایروال ویندوز بهطور پیشفرض اتصالهای ورودی را میبندد؛ پس تا قانونی اجازه ندهد، رایانههای دیگر به درگاه 8765 این
|
||||
رایانه نمیرسد. دکمهی **باز کردن درگاه 8765 در فایروال** اجازهی مدیر میگیرد و این فرمان را اجرا میکند (برای انجام
|
||||
دستی هم میتوانید همین را در Command Prompt با دسترسی مدیر اجرا کنید):
|
||||
|
||||
<div dir="ltr">
|
||||
|
||||
```bat
|
||||
netsh advfirewall firewall add rule name="SyncPulse Scale Bridge" dir=in action=allow protocol=TCP localport=8765 profile=any
|
||||
```
|
||||
|
||||
</div>
|
||||
|
||||
اگر پرسش «Allow access؟» ویندوز در اولین اجرا لغو شده باشد، ویندوز قانون مسدودکننده برای برنامه میسازد که بر هر قانون
|
||||
اجازه مقدم است؛ این دکمه آن را هم پاک میکند.
|
||||
|
||||
**اجرا همراه ویندوز** وظیفهی زمانبندیشدهی *SyncPulse Scale Bridge* را میسازد: هنگام روشن شدن رایانه و پیش از ورود
|
||||
کاربر با حساب SYSTEM اجرا میشود، پس از ۷۲ ساعت متوقف نمیشود و اگر بسته شود هر دقیقه دوباره اجرا میشود.
|
||||
|
||||
## رفع اشکال
|
||||
|
||||
- **درگاه COM دیده نمیشود / «A device attached to the system is not functioning»** — بسیاری از مبدلهای ارزان تراشهی
|
||||
CH340 یا PL2303 تقلبی دارند که درایورهای تازه آن را نمیپذیرند. برای CH340 درایور **3.5.2019.1** (از Microsoft
|
||||
Update Catalog) را نصب کنید، برای PL2303 درایور قدیمیتر Prolific، یا از مبدل FTDI استفاده کنید.
|
||||
- **چیزی پیدا نشد** — خروجی سریال را در منوی نمایشگر روشن کنید (معمولاً `COM`، `rS`، `SEr`، `Serial`، `Continuous`
|
||||
یا `On request`)؛ کابل را بررسی کنید (نالمودم یا مستقیم — پایههای ۲، ۳ و ۵ کافی است)؛ هنگام جستجو چیزی روی باسکول
|
||||
بگذارید یا کلید چاپ را بزنید؛ جستجوی کامل را امتحان کنید؛ بایتهای خام را در **تنظیم دستی و مانیتور** ببینید.
|
||||
- **سرور وصل نمیشود** — قانون فایروال، IP و یکی بودن شبکه را بررسی کنید؛ `curl http://<ip>:8765/health` از سرور باید
|
||||
پاسخ دهد.
|
||||
- **هشدار آنتیویروس** — برنامههای تکفایلی ساختهشده با PyInstaller گاهی بهاشتباه شناسایی میشوند. checksum
|
||||
SHA-256 منتشرشده با نسخه را مقایسه کنید یا برنامه را خودتان از کد منبع بسازید.
|
||||
|
||||
## ساخت از کد منبع
|
||||
|
||||
<div dir="ltr">
|
||||
|
||||
```bat
|
||||
git clone https://github.com/farshad-zamani/syncpulse-scale-bridge
|
||||
cd syncpulse-scale-bridge
|
||||
scripts\build_exe.bat
|
||||
```
|
||||
|
||||
</div>
|
||||
|
||||
## مجوز
|
||||
|
||||
[GPL-3.0-or-later](LICENSE) با یک شرط افزوده طبق بند ۷(ب): نام و مشخصات سازنده که برنامه نمایش میدهد — در پانویس
|
||||
صفحه، صفحهی «درباره»، فرمان `about` و پاسخ `/health` — باید در همهی نسخهها و نسخههای تغییر یافته حفظ شود.
|
||||
[NOTICE.md](NOTICE.md) را ببینید.
|
||||
|
||||
## سازنده
|
||||
|
||||
**فرشاد زمانی** — [کلادتارت (Cloudtart)](https://cloudtart.com) ·
|
||||
[GitHub](https://github.com/farshad-zamani) ·
|
||||
[LinkedIn](https://www.linkedin.com/in/farshad-zamani92/)
|
||||
|
||||
در اصل برای پلتفرم SyncPulse توسعه داده شد.
|
||||
|
||||
</div>
|
||||
+272
@@ -0,0 +1,272 @@
|
||||
<p align="center"><img src="assets/icon.png" width="96" alt=""></p>
|
||||
|
||||
<h1 align="center">SyncPulse Scale Bridge</h1>
|
||||
|
||||
<p align="center">
|
||||
Plug an RS-232 weighing scale into any Windows PC, run one file, and it finds the port, the speed and
|
||||
the protocol by itself — then shows the live weight and serves it to your network as JSON.
|
||||
</p>
|
||||
|
||||
<p align="center">
|
||||
<a href="https://github.com/farshad-zamani/syncpulse-scale-bridge/actions/workflows/ci.yml"><img src="https://github.com/farshad-zamani/syncpulse-scale-bridge/actions/workflows/ci.yml/badge.svg" alt="CI"></a>
|
||||
<a href="https://github.com/farshad-zamani/syncpulse-scale-bridge/releases/latest"><img src="https://img.shields.io/github/v/release/farshad-zamani/syncpulse-scale-bridge" alt="Release"></a>
|
||||
<a href="LICENSE"><img src="https://img.shields.io/badge/license-GPL--3.0--or--later-blue" alt="License"></a>
|
||||
<img src="https://img.shields.io/badge/platform-Windows%20%7C%20Linux-informational" alt="Platform">
|
||||
</p>
|
||||
|
||||
<p align="center"><b>English</b> · <a href="README.fa.md">فارسی</a></p>
|
||||
|
||||
---
|
||||
|
||||
Built by **[Farshad Zamani](https://github.com/farshad-zamani)** at **[Cloudtart](https://cloudtart.com)**. Free
|
||||
software that works with any system — an ERP, a MES, a web form, a spreadsheet macro or your own script — through a
|
||||
small HTTP/JSON interface.
|
||||
|
||||
<p align="center">
|
||||
<img src="docs/screenshots/find.png" width="49%" alt="Finding a scale automatically">
|
||||
<img src="docs/screenshots/scales.png" width="49%" alt="Live weights">
|
||||
</p>
|
||||
|
||||
## Why
|
||||
|
||||
Most industrial scales and weighing indicators still talk over a serial port, and every brand uses its own
|
||||
format, speed and framing. Connecting one usually means finding the manual, guessing 9600 8N1 or 2400 7E1,
|
||||
writing a parser, and keeping a program running on the PC beside the scale. This project does all of that:
|
||||
|
||||
- **Finds the scale by itself** — listens on every COM port at every common speed, recognises 7-bit/parity
|
||||
framing, then asks the scale in the languages of the major manufacturers. Only read-only requests are sent:
|
||||
it never zeroes, tares or prints.
|
||||
- **Reads many formats** — Mettler Toledo MT-SICS and Toledo Continuous, A&D, SMA (Rice Lake, Avery
|
||||
Weigh-Tronix, Cardinal, Fairbanks…), NCI, Ohaus, Sartorius SBI, CAS, the Chinese XK3190 family, Mahak MDS, any
|
||||
readable text, and custom binary/text formats you describe.
|
||||
- **Shows and serves the weight** — a bilingual (English/Persian) page on the PC, and a JSON API with value,
|
||||
unit, stability, net/gross, overload and a checksum check, for any system on the network.
|
||||
- **One file, nothing to install** — `SyncPulseScaleBridge.exe`. Copy it next to the scale and run it.
|
||||
- **Production-ready** — survives unplugged USB cables and busy ports, opens the Windows Firewall port and
|
||||
starts with Windows from a button (UAC prompt), keeps an access key, and logs to a rotating file.
|
||||
|
||||
## Quick start (Windows)
|
||||
|
||||
1. Download `SyncPulseScaleBridge.exe` from the [latest release](https://github.com/farshad-zamani/syncpulse-scale-bridge/releases/latest)
|
||||
and copy it to the PC the scale is connected to — preferably into its own folder, e.g. `C:\ScaleBridge\`
|
||||
(its settings file `bridge.json` and log are kept beside it).
|
||||
2. Connect the scale's RS-232 port (directly, or through a USB-serial adapter) and switch the indicator's
|
||||
serial output on.
|
||||
3. Double-click the program. A console window opens (keep it open) and the control page opens in the browser
|
||||
at `http://127.0.0.1:8765/`.
|
||||
4. **Find my scale → Start search.** When the scale is found, give it a name (e.g. `packing-1`) and **Save**.
|
||||
The **Scales** tab now shows its live weight.
|
||||
5. **Network access:** note the address and the access key, press **Open port 8765 in the firewall**
|
||||
and, if the bridge should run without anyone logged in, **Start with Windows**.
|
||||
6. From any other machine: `GET http://<address>:8765/weight?profile=<name>` with the header
|
||||
`X-Bridge-Token: <access key>` — see [the HTTP API](#http-api).
|
||||
|
||||
No hardware at hand? Try it with simulated scales:
|
||||
|
||||
```bat
|
||||
SyncPulseScaleBridge.exe --simulate mahak_mds,toledo_cont:4800:7E1,mt_sics
|
||||
```
|
||||
|
||||
## How auto-detection works
|
||||
|
||||
For each selected port:
|
||||
|
||||
1. **Listen** at 9600, 2400, 4800, 19200, 1200, 38400, 57600 and 115200 baud (8N1). A scale that sends by
|
||||
itself appears here. If the bytes are only readable once their top bit is cleared, the line uses 7 data bits
|
||||
with parity, and the port is listened to again as 7E1/7O1. What arrives is matched against every
|
||||
continuous format; framed formats with checksums win over loose text.
|
||||
2. **Ask** — if nothing useful was heard, every read-only request in the library is sent at each speed and
|
||||
framing (quick: 8 combinations; thorough: 14) and the reply is checked by the protocol that was asked. A
|
||||
reply is confirmed by asking a second time.
|
||||
|
||||
Each result has a confidence score, the exact line settings, the request, a sample of the raw data and the
|
||||
current reading. A port that sent readable data in an unknown format is reported with that sample, so it can be
|
||||
configured by hand on the **Manual & monitor** tab.
|
||||
|
||||
Auto-detection reserves the ports it searches; reads of those ports answer `409 busy` until it finishes.
|
||||
|
||||
### Scales that send only when Print is pressed
|
||||
|
||||
Many indicators — especially those wired to a label printer — stay silent until the operator presses *Print*,
|
||||
then send the whole label. Tick **The scale sends only when Print is pressed** (and, if you like, **Listen only**)
|
||||
and press Print when the page asks: the port is held open at one speed until data arrives; unreadable data means
|
||||
another speed, and the next press is awaited at the next one. One press is enough for 7E1/7O1.
|
||||
|
||||
For such a scale the bridge keeps the port **open all the time** and records every label: weight, unit and the
|
||||
other values on the label (order number, shift, date …) in `labels/<profile>-YYYY-MM-DD.jsonl` beside
|
||||
`bridge.json`, and the last 500 through `GET /labels`. To keep the label printer working, connect the PC with a
|
||||
**Y cable**: scale TX (and ground) to both the printer and the PC's RX; the PC never transmits on that line.
|
||||
|
||||
## Supported formats
|
||||
|
||||
| ID | Format | Talks | Used by (examples) |
|
||||
|---|---|---|---|
|
||||
| `mt_sics` | Mettler Toledo MT-SICS (`SI`) | on request | Mettler Toledo terminals and balances |
|
||||
| `toledo_cont` | Toledo Continuous (STX + status words, checksum) | continuous | Mettler Toledo IND/Panther/Jaguar/Lynx and many compatible indicators |
|
||||
| `and_std` | A&D standard (`ST`/`US`/`OL`, `Q`) | on request / continuous | A&D and many Asian indicators |
|
||||
| `sma` | SMA SCP-0499 (`<LF>W<CR>`) | on request | Rice Lake, Avery Weigh-Tronix, Cardinal, Fairbanks… |
|
||||
| `nci` | NCI 3835 (`W<CR>`) | on request | NCI / Weigh-Tronix shipping scales |
|
||||
| `ohaus` | Ohaus (`IP`) | on request | Ohaus Defender, Ranger, Valor… |
|
||||
| `sartorius` | Sartorius SBI (`ESC P`) | on request | Sartorius balances, Combics/Signum |
|
||||
| `cas_enq` | CAS ENQ/ACK/DC1 *(experimental)* | handshake | CAS and compatibles |
|
||||
| `xk3190_tf0` | XK3190 continuous (tF=0, XOR checksum) | continuous | Yaohua XK3190-A9/A12 and compatibles |
|
||||
| `xk3190_reversed` | XK3190 `=` reversed-digit stream — **tested on real hardware** (YH-T7E) | continuous | Yaohua XK3190 series, YH-T7E, big displays |
|
||||
| `mahak_mds` | Mahak MDS binary (`4D 09 04 07`) — **tested on real hardware** | on request | Mahak MDS 13000 and related models |
|
||||
| `label_print` | Label printer stream: TSPL / EPL2 / ZPL — **tested on real hardware** | on Print key | indicators wired to a TSC, Zebra or Argox label printer (e.g. PTC400) |
|
||||
| `ascii_generic` | Any readable line with a number and a unit | continuous | everything else that streams text |
|
||||
| `custom_binary` | A binary frame you describe (pattern, offset, length, byte order) | either | — |
|
||||
| `custom_ascii` | A text format you describe (regular expression) | either | — |
|
||||
|
||||
The formats follow the manufacturers' published documents and are covered by tests with their sample frames;
|
||||
`mahak_mds` was verified on a working scale. Brand names only describe data formats — many other indicators
|
||||
copy these formats. Requests that change the scale (zero, tare, reset, print, display off) are never sent.
|
||||
|
||||
Missing your scale? Open the **Manual & monitor** tab, look at what arrives, and save a custom profile — or
|
||||
[open an issue](https://github.com/farshad-zamani/syncpulse-scale-bridge/issues) with the model and a sample of the
|
||||
raw data. See [CONTRIBUTING.md](CONTRIBUTING.md) for adding a protocol.
|
||||
|
||||
## HTTP API
|
||||
|
||||
Everything below needs the header `X-Bridge-Token: <access key>` except `/health`.
|
||||
|
||||
| Request | Answer |
|
||||
|---|---|
|
||||
| `GET /health` | `{ok, service, product, version, host, simulate, author, website, repository, capabilities}` |
|
||||
| `GET /ports` | the COM ports of the PC (name, description, USB IDs, chip, warnings) |
|
||||
| `GET /profiles` | the saved scale profiles |
|
||||
| `GET /weight?profile=packing-1` | the current weight of a saved profile |
|
||||
| `GET /labels?profile=label-1&after=SEQ&limit=100` | labels printed by a print-only scale, oldest first (`seq` grows by one per label) |
|
||||
| `GET /weight?port=COM7&protocol=mt_sics&baud=9600&framing=8N1` | the current weight without a profile |
|
||||
| `POST /weight` `{"profile": "packing-1"}` or a whole profile | same, as JSON |
|
||||
| `POST /read` `{serial, exchange, frames, max_age_ms, wait_ms}` | the raw frames, for systems that parse them themselves |
|
||||
|
||||
Optional on `/weight`: `max_age_ms` (default 1500 — older readings are `stale`) and `wait_ms` (default 2500 — how
|
||||
long to wait for a fresh reading when the port has just been opened).
|
||||
|
||||
```console
|
||||
$ curl -H "X-Bridge-Token: $KEY" "http://192.168.1.20:8765/weight?profile=packing-1"
|
||||
{"ok": true, "profile": "packing-1", "port": "COM7", "protocol": "mahak_mds", "open": true,
|
||||
"value": 550.0, "unit": "g", "stable": true, "net": null, "overload": false, "age_ms": 84,
|
||||
"stale": false, "measured_at": "2026-10-01T10:15:02.415+03:30", "raw_hex": "58 51 07 07 00 02 26",
|
||||
"checksum_ok": null}
|
||||
```
|
||||
|
||||
```python
|
||||
import requests
|
||||
r = requests.get("http://192.168.1.20:8765/weight", params={"profile": "packing-1"},
|
||||
headers={"X-Bridge-Token": KEY}, timeout=5).json()
|
||||
if r["ok"] and r["stable"] and not r["stale"]:
|
||||
print(r["value"], r["unit"])
|
||||
```
|
||||
|
||||
`stable` comes from the scale when its format says so; otherwise it means the last *N* readings were equal
|
||||
(`stable_samples`, default 3). Errors answer with `"ok": false` and an `"error"` text — `401` wrong key,
|
||||
`403` client not allowed, `404` unknown profile, `409` port busy, `400` invalid request.
|
||||
|
||||
## Security
|
||||
|
||||
- **Access key** — created on first start and kept in `bridge.json`; compared in constant time. Make a new one on
|
||||
the **Connect** tab at any time.
|
||||
- **Allowed clients** — optionally accept only your server's address(es); the firewall rule can be
|
||||
limited to one address too.
|
||||
- **The control page is local only** — it opens only on the PC itself (`127.0.0.1`). Its API also requires a
|
||||
custom header and a local `Host`, which protects it from other web pages and DNS rebinding. Other machines
|
||||
get a short information page instead.
|
||||
- **Read-only towards the scale** — detection and reading never send zero, tare, print or configuration
|
||||
commands.
|
||||
- Keep the bridge on a trusted local network; it speaks plain HTTP.
|
||||
|
||||
## Firewall and running in the background
|
||||
|
||||
Windows Firewall blocks incoming connections by default, so other machines cannot reach port 8765 until a
|
||||
rule allows it. **Open port 8765 in the firewall** asks for administrator permission and runs:
|
||||
|
||||
```bat
|
||||
netsh advfirewall firewall add rule name="SyncPulse Scale Bridge" dir=in action=allow protocol=TCP localport=8765 profile=any
|
||||
```
|
||||
|
||||
It also removes block rules Windows may have created for the program when its *Allow access?* question was
|
||||
cancelled (a block rule beats any allow rule).
|
||||
|
||||
**Start with Windows** registers the scheduled task *SyncPulse Scale Bridge*: runs as SYSTEM at boot (before
|
||||
anyone logs in), never stopped after 72 hours, restarted every minute if it fails. Opening the program while the
|
||||
background copy runs simply opens its page.
|
||||
|
||||
The same from the command line:
|
||||
|
||||
```bat
|
||||
SyncPulseScaleBridge.exe firewall [--remote-ip 192.168.1.10] [--remove]
|
||||
SyncPulseScaleBridge.exe autostart [--disable]
|
||||
```
|
||||
|
||||
## Command line
|
||||
|
||||
```text
|
||||
SyncPulseScaleBridge.exe run the bridge and open its page (default)
|
||||
SyncPulseScaleBridge.exe ports list COM ports
|
||||
SyncPulseScaleBridge.exe detect [--port COM7] [--thorough] [--wait-print 60] [--listen-only] [--save NAME] [--json]
|
||||
SyncPulseScaleBridge.exe monitor --port COM7 --baud 9600 --framing 8N1 [--request "53 49 0D 0A"]
|
||||
SyncPulseScaleBridge.exe weight --profile NAME | --port COM7 --protocol mt_sics
|
||||
SyncPulseScaleBridge.exe token [--new]
|
||||
SyncPulseScaleBridge.exe protocols | about | --version
|
||||
|
||||
Options: --config FILE --simulate SPEC --verbose --listen-host --listen-port --no-browser --service
|
||||
```
|
||||
|
||||
## Troubleshooting
|
||||
|
||||
- **No COM port / "A device attached to the system is not functioning"** — many cheap USB-serial adapters use
|
||||
clone CH340 or PL2303 chips that recent drivers refuse. For CH340 install driver **3.5.2019.1** (Microsoft
|
||||
Update Catalog); for PL2303 use an older Prolific driver; or use an FTDI-based adapter. The port list warns
|
||||
about these chips.
|
||||
- **Nothing found** — switch the serial output on in the indicator's menu (often `COM`, `rS`, `SEr`, `Serial`,
|
||||
`Continuous` or `On request`); check the cable (many indicators need a null-modem/crossed cable, some a
|
||||
straight one — pins 2, 3 and 5 are enough); put something on the scale or press *Print* while searching; try
|
||||
the thorough search; watch the raw bytes on **Manual & monitor**.
|
||||
- **Garbage characters** — wrong speed or framing; the monitor shows the bytes, detection finds the right ones.
|
||||
- **The server cannot connect** — check the firewall rule, the IP address, and that both machines are on the same
|
||||
network; `curl http://<ip>:8765/health` from the server must answer.
|
||||
- **Antivirus warning** — single-file programs built with PyInstaller are sometimes flagged by mistake. Compare the
|
||||
SHA-256 checksum published with the release, or build the program yourself from source.
|
||||
|
||||
## Build from source
|
||||
|
||||
```bat
|
||||
git clone https://github.com/farshad-zamani/syncpulse-scale-bridge
|
||||
cd syncpulse-scale-bridge
|
||||
scripts\build_exe.bat :: venv, tests, then dist\SyncPulseScaleBridge.exe
|
||||
```
|
||||
|
||||
Or run it directly with Python 3.9+ on Windows or Linux:
|
||||
|
||||
```bash
|
||||
pip install -r requirements.txt
|
||||
python -m scale_bridge # on Linux the ports are /dev/ttyUSB0, /dev/ttyS0 …
|
||||
python -m pytest # the test suite (simulated scales, no hardware needed)
|
||||
```
|
||||
|
||||
## Related projects
|
||||
|
||||
Useful projects that solve parts of the problem — none of them combines automatic detection, a multi-brand
|
||||
protocol library, a network API and a control page:
|
||||
|
||||
- [VbScalesReader](https://github.com/wqweto/VbScalesReader) — VB6 library reading CAS, Elicom, Dibal, Mettler and
|
||||
Delmac protocols.
|
||||
- [Weigh-Scale-To-PC](https://github.com/MaxAtoms/Weigh-Scale-To-PC) — Windows Forms display for an Arduino-based scale.
|
||||
- [RS232C_Scale](https://github.com/rhemitoth/RS232C_Scale) — Raspberry Pi reader that logs a scale's readings to CSV.
|
||||
- [232key](https://www.digitalscalesblog.com/free-software-scales-balances/) and similar free *keyboard wedge*
|
||||
tools — type the weight into the active window.
|
||||
|
||||
## License
|
||||
|
||||
[GPL-3.0-or-later](LICENSE) with one additional term under section 7(b): the author attribution shown by the
|
||||
program — in its page footer, *About* page, `about` command and `/health` answer — must be kept in all copies and
|
||||
modified versions. See [NOTICE.md](NOTICE.md).
|
||||
|
||||
## Author
|
||||
|
||||
**Farshad Zamani** — [Cloudtart](https://cloudtart.com) ·
|
||||
[GitHub](https://github.com/farshad-zamani) ·
|
||||
[LinkedIn](https://www.linkedin.com/in/farshad-zamani92/)
|
||||
|
||||
Originally developed for the SyncPulse platform. Copyright © 2026 Farshad Zamani — Cloudtart.
|
||||
BIN
Binary file not shown.
|
After Width: | Height: | Size: 36 KiB |
BIN
Binary file not shown.
|
After Width: | Height: | Size: 2.5 KiB |
Binary file not shown.
|
After Width: | Height: | Size: 106 KiB |
Binary file not shown.
|
After Width: | Height: | Size: 141 KiB |
Binary file not shown.
|
After Width: | Height: | Size: 41 KiB |
Binary file not shown.
|
After Width: | Height: | Size: 41 KiB |
+46
@@ -0,0 +1,46 @@
|
||||
[build-system]
|
||||
requires = ["setuptools>=77"]
|
||||
build-backend = "setuptools.build_meta"
|
||||
|
||||
[project]
|
||||
name = "syncpulse-scale-bridge"
|
||||
dynamic = ["version"]
|
||||
description = "Finds RS-232 weighing scales on any COM port, reads them, and serves the weight on the network."
|
||||
readme = "README.md"
|
||||
license = "GPL-3.0-or-later"
|
||||
license-files = ["LICENSE", "NOTICE.md"]
|
||||
authors = [{ name = "Farshad Zamani", email = "info@cloudtart.com" }]
|
||||
requires-python = ">=3.9"
|
||||
dependencies = ["pyserial>=3.5"]
|
||||
keywords = ["scale", "weighing", "rs232", "serial", "weight", "indicator", "mettler-toledo",
|
||||
"sics", "xk3190", "industrial", "bridge", "label-printer", "tspl"]
|
||||
classifiers = [
|
||||
"Development Status :: 5 - Production/Stable",
|
||||
"Environment :: Console",
|
||||
"Environment :: Web Environment",
|
||||
"Intended Audience :: Manufacturing",
|
||||
"Intended Audience :: Developers",
|
||||
"Operating System :: Microsoft :: Windows",
|
||||
"Operating System :: POSIX :: Linux",
|
||||
"Programming Language :: Python :: 3",
|
||||
"Topic :: System :: Hardware :: Hardware Drivers",
|
||||
"Topic :: Scientific/Engineering :: Interface Engine/Protocol Translator",
|
||||
]
|
||||
|
||||
[project.urls]
|
||||
Homepage = "https://github.com/farshad-zamani/syncpulse-scale-bridge"
|
||||
Author = "https://cloudtart.com"
|
||||
Issues = "https://github.com/farshad-zamani/syncpulse-scale-bridge/issues"
|
||||
|
||||
[project.scripts]
|
||||
scale-bridge = "scale_bridge.cli:main"
|
||||
|
||||
[tool.setuptools]
|
||||
packages = ["scale_bridge"]
|
||||
|
||||
[tool.setuptools.dynamic]
|
||||
version = { attr = "scale_bridge.__version__" }
|
||||
|
||||
[tool.pytest.ini_options]
|
||||
pythonpath = ["."]
|
||||
testpaths = ["tests"]
|
||||
@@ -0,0 +1,3 @@
|
||||
-r requirements.txt
|
||||
pytest>=8
|
||||
pyinstaller>=6.10
|
||||
@@ -0,0 +1 @@
|
||||
pyserial==3.5
|
||||
+9
@@ -0,0 +1,9 @@
|
||||
# SPDX-License-Identifier: GPL-3.0-or-later
|
||||
# Copyright (C) 2026 Farshad Zamani - Cloudtart (https://cloudtart.com)
|
||||
"""Entry point for the single-file program (PyInstaller) and for `python run_bridge.py`."""
|
||||
import sys
|
||||
|
||||
from scale_bridge.cli import main
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
@@ -0,0 +1,42 @@
|
||||
# SPDX-License-Identifier: GPL-3.0-or-later
|
||||
# Copyright (C) 2026 Farshad Zamani — Cloudtart (https://cloudtart.com)
|
||||
# Additional terms under GPLv3 section 7(b): see NOTICE.md.
|
||||
"""
|
||||
SyncPulse Scale Bridge — a universal RS-232 scale reader and network bridge.
|
||||
|
||||
Plug a weighing scale's serial cable into a Windows PC, run one program, and
|
||||
it finds the port, the speed and the protocol by itself, shows the live
|
||||
weight, and serves it on the local network for any other system to read.
|
||||
"""
|
||||
|
||||
__version__ = "1.1.2"
|
||||
|
||||
PRODUCT = "SyncPulse Scale Bridge"
|
||||
SERVICE_ID = "syncpulse-scale-bridge"
|
||||
EXE_NAME = "SyncPulseScaleBridge"
|
||||
|
||||
# Authorship. Keeping these visible in the user interface is a condition of
|
||||
# the licence (GPLv3 section 7(b), see NOTICE.md).
|
||||
AUTHOR = "Farshad Zamani"
|
||||
COMPANY = "Cloudtart"
|
||||
WEBSITE = "https://cloudtart.com"
|
||||
GITHUB = "https://github.com/farshad-zamani"
|
||||
LINKEDIN = "https://www.linkedin.com/in/farshad-zamani92/"
|
||||
REPOSITORY = "https://github.com/farshad-zamani/syncpulse-scale-bridge"
|
||||
PLATFORM = "SyncPulse"
|
||||
LICENSE_ID = "GPL-3.0-or-later"
|
||||
COPYRIGHT = f"Copyright (C) 2026 {AUTHOR} - {COMPANY}"
|
||||
|
||||
ABOUT = {
|
||||
"product": PRODUCT,
|
||||
"version": __version__,
|
||||
"author": AUTHOR,
|
||||
"company": COMPANY,
|
||||
"website": WEBSITE,
|
||||
"github": GITHUB,
|
||||
"linkedin": LINKEDIN,
|
||||
"repository": REPOSITORY,
|
||||
"platform": PLATFORM,
|
||||
"license": LICENSE_ID,
|
||||
"copyright": COPYRIGHT,
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
# SPDX-License-Identifier: GPL-3.0-or-later
|
||||
# Copyright (C) 2026 Farshad Zamani — Cloudtart (https://cloudtart.com)
|
||||
import sys
|
||||
|
||||
from scale_bridge.cli import main
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
+418
@@ -0,0 +1,418 @@
|
||||
# SPDX-License-Identifier: GPL-3.0-or-later
|
||||
# Copyright (C) 2026 Farshad Zamani — Cloudtart (https://cloudtart.com)
|
||||
"""
|
||||
Command line. Without a command the bridge starts and its page opens in the
|
||||
browser — that is what a double-click on the program does.
|
||||
|
||||
SyncPulseScaleBridge run, open http://127.0.0.1:8765/
|
||||
SyncPulseScaleBridge ports list COM ports
|
||||
SyncPulseScaleBridge detect [--port COM7] [--thorough] [--save NAME]
|
||||
SyncPulseScaleBridge monitor --port COM7 [--baud 9600 --framing 8N1 --request "SI\\r\\n" hex]
|
||||
SyncPulseScaleBridge weight --profile NAME | --port COM7 --protocol mt_sics
|
||||
SyncPulseScaleBridge token [--new]
|
||||
SyncPulseScaleBridge firewall [--remove] [--remote-ip 192.168.1.10]
|
||||
SyncPulseScaleBridge autostart [--disable]
|
||||
SyncPulseScaleBridge about
|
||||
|
||||
Common options: --config FILE, --simulate SPEC (e.g. mahak_mds,toledo_cont:4800:7E1),
|
||||
--verbose; for running: --listen-host, --listen-port, --no-browser, --service.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import json
|
||||
import logging
|
||||
import os
|
||||
import sys
|
||||
import time
|
||||
import urllib.request
|
||||
from logging.handlers import RotatingFileHandler
|
||||
from typing import Optional
|
||||
|
||||
from . import ABOUT, PRODUCT, SERVICE_ID, __version__, profiles, winutil
|
||||
from .config import Config
|
||||
from .detect import Detector
|
||||
from .protocols import PROTOCOLS, catalogue_info
|
||||
from .serialio import LineSettings, Registry, format_hex, list_serial_ports, now_ms, open_real, parse_hex, printable
|
||||
from .simulator import SimulatorBank
|
||||
|
||||
log = logging.getLogger("scale_bridge")
|
||||
|
||||
LOG_TEXT = {
|
||||
"port_start": "Searching {port} ...",
|
||||
"listen": " listening at {baud} {framing}",
|
||||
"heard": " heard {bytes} bytes at {baud} ({readable_pct}% readable)",
|
||||
"seven_bit": " 7 data bits with parity? listening again as 7E1/7O1",
|
||||
"reply": " reply to {protocol}: {text}",
|
||||
"found": " FOUND {protocol} at {baud} {framing}: {value} {unit}",
|
||||
"not_found": " nothing recognised on {port}",
|
||||
"open_failed": " cannot open {port}: {error}",
|
||||
"press_print": " >>> Press PRINT on the scale now (listening at {baud} for {seconds} s)",
|
||||
"print_wrong_speed": " data at {baud} was not readable - press PRINT again (next speed)",
|
||||
"print_timeout": " nothing arrived while waiting for PRINT",
|
||||
}
|
||||
|
||||
|
||||
def say(text: str = "") -> None:
|
||||
try:
|
||||
print(text, flush=True)
|
||||
except Exception: # noqa: BLE001
|
||||
try:
|
||||
sys.stdout.buffer.write((text + "\n").encode("ascii", "replace"))
|
||||
sys.stdout.flush()
|
||||
except Exception: # noqa: BLE001
|
||||
pass
|
||||
|
||||
|
||||
def setup_logging(directory: str, verbose: bool, quiet_console: bool = False) -> None:
|
||||
fmt = logging.Formatter("%(asctime)s %(levelname)s %(message)s")
|
||||
handlers: list[logging.Handler] = []
|
||||
if not quiet_console and sys.stderr is not None:
|
||||
console = logging.StreamHandler()
|
||||
console.setFormatter(fmt)
|
||||
handlers.append(console)
|
||||
try:
|
||||
os.makedirs(directory, exist_ok=True)
|
||||
file_handler = RotatingFileHandler(os.path.join(directory, "bridge.log"), maxBytes=1_000_000,
|
||||
backupCount=3, encoding="utf-8")
|
||||
file_handler.setFormatter(fmt)
|
||||
handlers.append(file_handler)
|
||||
except OSError:
|
||||
pass
|
||||
logging.basicConfig(level=logging.DEBUG if verbose else logging.INFO, handlers=handlers or None,
|
||||
force=True)
|
||||
|
||||
|
||||
def _opener(args):
|
||||
if args.simulate:
|
||||
return SimulatorBank(args.simulate).opener(open_real), SimulatorBank(args.simulate)
|
||||
return open_real, None
|
||||
|
||||
|
||||
def _ports(args) -> list[dict]:
|
||||
ports = list_serial_ports()
|
||||
if args.simulate:
|
||||
ports += SimulatorBank(args.simulate).ports()
|
||||
return ports
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Commands
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
def cmd_ports(args) -> int:
|
||||
ports = _ports(args)
|
||||
if not ports:
|
||||
say("No COM ports found. Plug in the USB-serial adapter and check its driver in Device Manager.")
|
||||
return 1
|
||||
for p in ports:
|
||||
chip = f" [{p['chip']}]" if p.get("chip") else ""
|
||||
say(f"{p['device']:8} {p.get('description') or ''}{chip} ({p.get('kind')})")
|
||||
if p.get("note"):
|
||||
say(f" note: {p['note']}")
|
||||
return 0
|
||||
|
||||
|
||||
def cmd_detect(args, config: Config) -> int:
|
||||
opener, _ = _opener(args)
|
||||
ports = args.ports or [p["device"] for p in _ports(args)
|
||||
if args.bluetooth or p.get("kind") != "bluetooth"]
|
||||
if not ports:
|
||||
say("No COM ports to search.")
|
||||
return 1
|
||||
|
||||
def show(code: str, **kw) -> None:
|
||||
text = LOG_TEXT.get(code)
|
||||
if text and (args.verbose or code != "listen"):
|
||||
kw.setdefault("readable_pct", round(float(kw.get("readable") or 0) * 100))
|
||||
if "protocol" in kw and kw["protocol"] in PROTOCOLS:
|
||||
kw["protocol"] = PROTOCOLS[kw["protocol"]].name
|
||||
try:
|
||||
say(text.format(**kw))
|
||||
except (KeyError, IndexError):
|
||||
say(f" {code} {kw}")
|
||||
|
||||
say(f"{PRODUCT} {__version__} - auto-detection ({'thorough' if args.thorough else 'quick'}); "
|
||||
+ ("listen only: nothing is sent." if args.listen_only else "read-only requests only."))
|
||||
results = Detector(opener, log=show, thorough=args.thorough, print_wait_s=args.wait_print,
|
||||
listen_only=args.listen_only).run(ports)
|
||||
say()
|
||||
found = [r for r in results if r.get("found")]
|
||||
for r in results:
|
||||
if r.get("found"):
|
||||
s = r["serial"]
|
||||
reading = r["reading"]
|
||||
fields = reading.get("fields") or {}
|
||||
if fields:
|
||||
say(f"{r['port']}: label fields: " + ", ".join(f"{k}={v}" for k, v in fields.items()))
|
||||
say(f"{r['port']}: {r['protocol_name']} {s['baudrate']} {s['bytesize']}{s['parity']}{s['stopbits']}"
|
||||
f" request={r['exchange']['request_hex'] or '-'} weight={reading['value']} {reading['unit']}"
|
||||
f" confidence={int(r['confidence'] * 100)}%")
|
||||
else:
|
||||
unknown = r.get("unknown")
|
||||
extra = f" (readable data at {unknown['baud']} {unknown['framing']}: {unknown['sample_text'][:60]})" \
|
||||
if unknown else ""
|
||||
say(f"{r['port']}: no scale recognised{extra}{' - ' + r['error'] if r.get('error') else ''}")
|
||||
if args.save and found:
|
||||
for i, r in enumerate(found):
|
||||
name = args.save if len(found) == 1 else f"{args.save}-{profiles.slug(r['port'])}"
|
||||
saved = config.save_profile(profiles.from_detection(r, name))
|
||||
say(f"saved profile '{saved['name']}' in {config.path}")
|
||||
if args.json:
|
||||
say(json.dumps(results, indent=2, ensure_ascii=False))
|
||||
return 0 if found else 1
|
||||
|
||||
|
||||
def cmd_monitor(args) -> int:
|
||||
opener, _ = _opener(args)
|
||||
framing = args.framing.upper()
|
||||
request = parse_hex(args.request or "")
|
||||
settings = LineSettings(args.port).with_line(args.baud, framing)
|
||||
say(f"{settings.port} {settings.baudrate} {settings.framing}, "
|
||||
f"{'request ' + format_hex(request) + ' every ' + str(args.poll) + ' ms' if request else 'listening'}"
|
||||
f" for {args.seconds} s (Ctrl+C stops)")
|
||||
ser = opener(settings)
|
||||
collected = bytearray()
|
||||
try:
|
||||
end = time.monotonic() + args.seconds
|
||||
next_request = 0.0
|
||||
buf, last = bytearray(), time.monotonic()
|
||||
while time.monotonic() < end:
|
||||
now = time.monotonic()
|
||||
if request and now >= next_request:
|
||||
ser.write(request)
|
||||
next_request = now + args.poll / 1000
|
||||
waiting = ser.in_waiting
|
||||
chunk = ser.read(waiting if waiting else 1)
|
||||
if chunk:
|
||||
buf += chunk
|
||||
last = time.monotonic()
|
||||
continue
|
||||
if buf and time.monotonic() - last > 0.05:
|
||||
say(f"{format_hex(bytes(buf))} | {printable(bytes(buf))}")
|
||||
collected += buf
|
||||
buf.clear()
|
||||
except KeyboardInterrupt:
|
||||
pass
|
||||
finally:
|
||||
ser.close()
|
||||
say()
|
||||
readable = [(pid, p) for pid, p in PROTOCOLS.items() if not pid.startswith("custom")]
|
||||
for pid, proto in readable:
|
||||
found = [r for r in proto.readings(bytes(collected)) if r.value is not None]
|
||||
if found:
|
||||
say(f"readable as {proto.name}: {found[-1].value} {found[-1].unit} (x{len(found)})")
|
||||
return 0
|
||||
|
||||
|
||||
def cmd_weight(args, config: Config) -> int:
|
||||
opener, _ = _opener(args)
|
||||
if args.profile:
|
||||
profile = config.profile(args.profile)
|
||||
if profile is None:
|
||||
say(f"no profile named {args.profile!r} in {config.path}")
|
||||
return 1
|
||||
elif args.port and args.protocol:
|
||||
serial_cfg = {"baudrate": args.baud}
|
||||
if args.framing:
|
||||
f = args.framing.upper()
|
||||
serial_cfg.update(bytesize=int(f[0]), parity=f[1], stopbits=int(f[2]))
|
||||
profile = profiles.ad_hoc(args.port, args.protocol, serial_cfg)
|
||||
else:
|
||||
say("give --profile NAME, or --port COMx --protocol ID")
|
||||
return 2
|
||||
registry = Registry(opener)
|
||||
try:
|
||||
worker = registry.worker_for(profiles.line_settings(profile))
|
||||
result = profiles.wait_for_reading(profile, worker, 1500, int(args.wait * 1000), now_ms)
|
||||
finally:
|
||||
registry.stop_all()
|
||||
say(json.dumps(result, indent=2, ensure_ascii=False))
|
||||
return 0 if result.get("ok") else 1
|
||||
|
||||
|
||||
def cmd_token(args, config: Config) -> int:
|
||||
say(config.rotate_token() if args.new else config.token)
|
||||
return 0
|
||||
|
||||
|
||||
def cmd_firewall(args, config: Config) -> int:
|
||||
result = winutil.firewall_close() if args.remove else winutil.firewall_open(config.listen_port, args.remote_ip)
|
||||
say(json.dumps(result, indent=2))
|
||||
return 0 if result.get("ok") else 1
|
||||
|
||||
|
||||
def cmd_autostart(args, config: Config) -> int:
|
||||
result = winutil.autostart_disable() if args.disable else winutil.autostart_enable(config.path)
|
||||
say(json.dumps(result, indent=2))
|
||||
return 0 if result.get("ok") else 1
|
||||
|
||||
|
||||
def cmd_about() -> int:
|
||||
for key in ("product", "version", "author", "company", "website", "github", "linkedin",
|
||||
"repository", "license"):
|
||||
say(f"{key:11} {ABOUT[key]}")
|
||||
say(ABOUT["copyright"])
|
||||
return 0
|
||||
|
||||
|
||||
def cmd_protocols() -> int:
|
||||
for p in catalogue_info():
|
||||
tested = " [field-tested]" if p["field_tested"] else ""
|
||||
say(f"{p['id']:16} {p['kind']:10} {p['request_hex'] or '-':14} {p['name']}{tested}")
|
||||
return 0
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Running the bridge
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
def _running_copy(port: int) -> Optional[dict]:
|
||||
try:
|
||||
with urllib.request.urlopen(f"http://127.0.0.1:{port}/health", timeout=2) as r:
|
||||
body = json.loads(r.read().decode("utf-8"))
|
||||
return body if body.get("service") == SERVICE_ID else None
|
||||
except Exception: # noqa: BLE001
|
||||
return None
|
||||
|
||||
|
||||
def cmd_run(args, config: Config) -> int:
|
||||
from .server import Bridge, make_server
|
||||
|
||||
host = args.listen_host or config.listen_host
|
||||
port = int(args.listen_port or config.listen_port)
|
||||
url = f"http://127.0.0.1:{port}/"
|
||||
open_page = not (args.no_browser or args.service)
|
||||
bridge = Bridge(config, simulate=args.simulate or "")
|
||||
try:
|
||||
httpd = make_server(bridge, host, port)
|
||||
except OSError as e:
|
||||
other = _running_copy(port)
|
||||
if other:
|
||||
say(f"{PRODUCT} is already running on this PC (version {other.get('version')}).")
|
||||
if open_page:
|
||||
say(f"Opening {url}")
|
||||
winutil.open_browser(url)
|
||||
return 0
|
||||
log.error("cannot listen on %s:%d: %s", host, port, e)
|
||||
say(f"Port {port} is used by another program. Close it, or start with --listen-port 8766.")
|
||||
return 1
|
||||
|
||||
bar = "=" * 68
|
||||
say(bar)
|
||||
say(f" {PRODUCT} {__version__}" + (" [SIMULATION]" if args.simulate else ""))
|
||||
say(f" {ABOUT['copyright']} - {ABOUT['website']}")
|
||||
say(f" {ABOUT['license']} - {ABOUT['repository']}")
|
||||
say(bar)
|
||||
say(f" Control page (this PC) : {url}")
|
||||
for ip in winutil.lan_addresses() or ["<this PC's IP address>"]:
|
||||
say(f" Bridge address : {ip} port {port}")
|
||||
say(f" Access key : {config.token}")
|
||||
say(f" Settings : {config.path}")
|
||||
say(bar)
|
||||
say(" Keep this window open while the scales are in use; closing it stops the bridge.")
|
||||
say(" To run in the background at startup, use 'Start with Windows' on the control page.")
|
||||
say(bar)
|
||||
log.info("listening on %s:%d", host, port)
|
||||
if open_page:
|
||||
winutil.open_browser(url)
|
||||
try:
|
||||
httpd.serve_forever(poll_interval=0.5)
|
||||
except KeyboardInterrupt:
|
||||
pass
|
||||
finally:
|
||||
httpd.server_close()
|
||||
bridge.registry.stop_all()
|
||||
return 0
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Arguments
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
def build_parser() -> argparse.ArgumentParser:
|
||||
common = argparse.ArgumentParser(add_help=False, argument_default=argparse.SUPPRESS)
|
||||
common.add_argument("--config", help="settings file (default: bridge.json beside the program)")
|
||||
common.add_argument("--simulate", metavar="SPEC",
|
||||
help="add simulated scales on COM90.. e.g. 'mahak_mds,toledo_cont:4800:7E1'")
|
||||
common.add_argument("--verbose", action="store_true", help="more detail in the log")
|
||||
|
||||
ap = argparse.ArgumentParser(
|
||||
prog="SyncPulseScaleBridge",
|
||||
description=f"{PRODUCT} {__version__} - finds RS-232 scales, reads them and serves the weight "
|
||||
f"on the network.",
|
||||
epilog=f"{ABOUT['copyright']} - {ABOUT['website']} - {ABOUT['repository']}")
|
||||
ap.add_argument("--version", action="version", version=f"{PRODUCT} {__version__}")
|
||||
ap.add_argument("--config", default=None)
|
||||
ap.add_argument("--simulate", default="", metavar="SPEC")
|
||||
ap.add_argument("--verbose", action="store_true")
|
||||
ap.add_argument("--listen-host", help="address to listen on (default 0.0.0.0)")
|
||||
ap.add_argument("--listen-port", type=int, help="port to listen on (default 8765)")
|
||||
ap.add_argument("--no-browser", action="store_true", help="do not open the control page")
|
||||
ap.add_argument("--service", action="store_true", help="background mode (used by 'Start with Windows')")
|
||||
sub = ap.add_subparsers(dest="command", metavar="command")
|
||||
|
||||
sub.add_parser("run", parents=[common], help="run the bridge (the default)")
|
||||
sub.add_parser("ports", parents=[common], help="list COM ports")
|
||||
d = sub.add_parser("detect", parents=[common], help="find the scale automatically")
|
||||
d.add_argument("--port", dest="ports", action="append", help="only this port (repeatable)")
|
||||
d.add_argument("--thorough", action="store_true", help="more speeds and framings (slower)")
|
||||
d.add_argument("--bluetooth", action="store_true", help="also search Bluetooth serial ports")
|
||||
d.add_argument("--wait-print", type=float, default=0, metavar="SECONDS",
|
||||
help="the scale sends only on its Print key: wait this long for a press")
|
||||
d.add_argument("--listen-only", action="store_true",
|
||||
help="never send anything to the device (skip asking)")
|
||||
d.add_argument("--save", metavar="NAME", help="save what is found as a profile")
|
||||
d.add_argument("--json", action="store_true", help="print the full results as JSON")
|
||||
m = sub.add_parser("monitor", parents=[common], help="show the raw bytes on a port")
|
||||
m.add_argument("--port", required=True)
|
||||
m.add_argument("--baud", type=int, default=9600)
|
||||
m.add_argument("--framing", default="8N1")
|
||||
m.add_argument("--request", default="", help="hex bytes to send, e.g. '53 49 0D 0A'")
|
||||
m.add_argument("--poll", type=int, default=500, help="request interval in ms")
|
||||
m.add_argument("--seconds", type=float, default=10)
|
||||
w = sub.add_parser("weight", parents=[common], help="read the weight once")
|
||||
w.add_argument("--profile")
|
||||
w.add_argument("--port")
|
||||
w.add_argument("--protocol", choices=sorted(PROTOCOLS))
|
||||
w.add_argument("--baud", type=int, default=9600)
|
||||
w.add_argument("--framing", default="")
|
||||
w.add_argument("--wait", type=float, default=3.0, help="seconds to wait for a reading")
|
||||
t = sub.add_parser("token", parents=[common], help="show the access key")
|
||||
t.add_argument("--new", action="store_true", help="make a new key")
|
||||
f = sub.add_parser("firewall", parents=[common], help="open the bridge port in Windows Firewall")
|
||||
f.add_argument("--remove", action="store_true")
|
||||
f.add_argument("--remote-ip", default=None, help="allow only this address")
|
||||
a = sub.add_parser("autostart", parents=[common], help="start with Windows (scheduled task)")
|
||||
a.add_argument("--disable", action="store_true")
|
||||
sub.add_parser("protocols", parents=[common], help="list the protocol library")
|
||||
sub.add_parser("about", parents=[common], help="author, licence and links")
|
||||
return ap
|
||||
|
||||
|
||||
def main(argv: Optional[list[str]] = None) -> int:
|
||||
args = build_parser().parse_args(argv)
|
||||
command = args.command or "run"
|
||||
if command == "about":
|
||||
return cmd_about()
|
||||
if command == "protocols":
|
||||
return cmd_protocols()
|
||||
if command == "ports":
|
||||
return cmd_ports(args)
|
||||
if command == "monitor":
|
||||
return cmd_monitor(args)
|
||||
|
||||
config = Config(args.config)
|
||||
setup_logging(os.path.dirname(config.path), args.verbose,
|
||||
quiet_console=command != "run" and not args.verbose)
|
||||
if command == "detect":
|
||||
return cmd_detect(args, config)
|
||||
if command == "weight":
|
||||
return cmd_weight(args, config)
|
||||
if command == "token":
|
||||
return cmd_token(args, config)
|
||||
if command == "firewall":
|
||||
return cmd_firewall(args, config)
|
||||
if command == "autostart":
|
||||
return cmd_autostart(args, config)
|
||||
return cmd_run(args, config)
|
||||
@@ -0,0 +1,195 @@
|
||||
# SPDX-License-Identifier: GPL-3.0-or-later
|
||||
# Copyright (C) 2026 Farshad Zamani — Cloudtart (https://cloudtart.com)
|
||||
"""
|
||||
bridge.json — the bridge's settings, access key and saved scale profiles.
|
||||
|
||||
It lives beside the program, so copying the folder copies the setup. When
|
||||
that folder is read-only (e.g. Program Files), %LOCALAPPDATA% is used.
|
||||
Files written by earlier versions (1.x) are read as they are.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import logging
|
||||
import os
|
||||
import secrets
|
||||
import sys
|
||||
import tempfile
|
||||
import threading
|
||||
from typing import Any, Optional
|
||||
|
||||
from . import EXE_NAME
|
||||
from .profiles import MAX_PROFILES, validate
|
||||
|
||||
log = logging.getLogger("scale_bridge")
|
||||
|
||||
DEFAULT_PORT = 8765
|
||||
DEFAULTS: dict[str, Any] = {
|
||||
"listen_host": "0.0.0.0",
|
||||
"listen_port": DEFAULT_PORT,
|
||||
"token": "",
|
||||
# Empty = any machine that has the key. Put the platform server's IP here
|
||||
# to refuse everybody else, e.g. ["192.168.1.10"].
|
||||
"allowed_clients": [],
|
||||
"profiles": [],
|
||||
}
|
||||
|
||||
|
||||
def app_dir() -> str:
|
||||
if getattr(sys, "frozen", False):
|
||||
return os.path.dirname(os.path.abspath(sys.executable))
|
||||
return os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
|
||||
|
||||
|
||||
def _writable(directory: str) -> bool:
|
||||
try:
|
||||
fd, probe = tempfile.mkstemp(prefix=".write-test-", dir=directory)
|
||||
os.close(fd)
|
||||
os.remove(probe)
|
||||
return True
|
||||
except OSError:
|
||||
return False
|
||||
|
||||
|
||||
def default_path() -> str:
|
||||
beside = os.path.join(app_dir(), "bridge.json")
|
||||
if os.path.exists(beside) or _writable(app_dir()):
|
||||
return beside
|
||||
base = os.environ.get("LOCALAPPDATA") or os.path.expanduser("~")
|
||||
folder = os.path.join(base, EXE_NAME)
|
||||
os.makedirs(folder, exist_ok=True)
|
||||
return os.path.join(folder, "bridge.json")
|
||||
|
||||
|
||||
def new_token() -> str:
|
||||
return secrets.token_urlsafe(24)
|
||||
|
||||
|
||||
class Config:
|
||||
def __init__(self, path: Optional[str] = None):
|
||||
self.path = os.path.abspath(path or default_path())
|
||||
self.lock = threading.RLock()
|
||||
self.data: dict[str, Any] = dict(DEFAULTS)
|
||||
self.load()
|
||||
|
||||
# -- file --------------------------------------------------------------
|
||||
def load(self) -> None:
|
||||
with self.lock:
|
||||
data = dict(DEFAULTS)
|
||||
if os.path.exists(self.path):
|
||||
try:
|
||||
with open(self.path, encoding="utf-8-sig") as f:
|
||||
loaded = json.load(f)
|
||||
if isinstance(loaded, dict):
|
||||
data.update(loaded)
|
||||
except (OSError, ValueError) as e:
|
||||
backup = self.path + ".broken"
|
||||
log.error("%s could not be read (%s); kept as %s and started fresh", self.path, e,
|
||||
backup)
|
||||
try:
|
||||
os.replace(self.path, backup)
|
||||
except OSError:
|
||||
pass
|
||||
profiles = []
|
||||
for raw in data.get("profiles") or []:
|
||||
try:
|
||||
profiles.append(validate(raw))
|
||||
except (ValueError, TypeError, KeyError) as e:
|
||||
log.warning("profile %r ignored: %s", (raw or {}).get("name"), e)
|
||||
data["profiles"] = profiles
|
||||
self.data = data
|
||||
if not data.get("token"):
|
||||
data["token"] = new_token()
|
||||
self.save()
|
||||
log.info("created %s with a new access key", self.path)
|
||||
|
||||
def save(self) -> None:
|
||||
with self.lock:
|
||||
folder = os.path.dirname(self.path)
|
||||
os.makedirs(folder, exist_ok=True)
|
||||
fd, tmp = tempfile.mkstemp(prefix=".bridge-", suffix=".json", dir=folder)
|
||||
try:
|
||||
with os.fdopen(fd, "w", encoding="utf-8") as f:
|
||||
json.dump(self.data, f, indent=2, ensure_ascii=False)
|
||||
os.replace(tmp, self.path)
|
||||
except BaseException:
|
||||
try:
|
||||
os.remove(tmp)
|
||||
except OSError:
|
||||
pass
|
||||
raise
|
||||
|
||||
# -- values ------------------------------------------------------------
|
||||
@property
|
||||
def token(self) -> str:
|
||||
return str(self.data.get("token") or "")
|
||||
|
||||
def rotate_token(self) -> str:
|
||||
with self.lock:
|
||||
self.data["token"] = new_token()
|
||||
self.save()
|
||||
return self.token
|
||||
|
||||
@property
|
||||
def listen_host(self) -> str:
|
||||
return str(self.data.get("listen_host") or "0.0.0.0")
|
||||
|
||||
@property
|
||||
def listen_port(self) -> int:
|
||||
try:
|
||||
return int(self.data.get("listen_port") or DEFAULT_PORT)
|
||||
except (TypeError, ValueError):
|
||||
return DEFAULT_PORT
|
||||
|
||||
@property
|
||||
def allowed_clients(self) -> list[str]:
|
||||
value = self.data.get("allowed_clients") or []
|
||||
return [str(v).strip() for v in value if str(v).strip()] if isinstance(value, list) else []
|
||||
|
||||
def set_allowed_clients(self, clients: list[str]) -> None:
|
||||
import ipaddress
|
||||
cleaned = []
|
||||
for c in clients:
|
||||
c = str(c).strip()
|
||||
if not c:
|
||||
continue
|
||||
ipaddress.ip_address(c) # raises ValueError
|
||||
cleaned.append(c)
|
||||
with self.lock:
|
||||
self.data["allowed_clients"] = cleaned
|
||||
self.save()
|
||||
|
||||
# -- profiles ----------------------------------------------------------
|
||||
def profiles(self) -> list[dict]:
|
||||
with self.lock:
|
||||
return [dict(p) for p in self.data.get("profiles") or []]
|
||||
|
||||
def profile(self, name: str) -> Optional[dict]:
|
||||
name = str(name or "").strip().lower()
|
||||
with self.lock:
|
||||
for p in self.data.get("profiles") or []:
|
||||
if p["name"].lower() == name:
|
||||
return dict(p)
|
||||
return None
|
||||
|
||||
def save_profile(self, raw: dict) -> dict:
|
||||
profile = validate(raw)
|
||||
with self.lock:
|
||||
items = [p for p in self.data.get("profiles") or []
|
||||
if p["name"].lower() != profile["name"].lower()]
|
||||
if len(items) >= MAX_PROFILES:
|
||||
raise ValueError(f"at most {MAX_PROFILES} profiles")
|
||||
items.append(profile)
|
||||
self.data["profiles"] = items
|
||||
self.save()
|
||||
return profile
|
||||
|
||||
def delete_profile(self, name: str) -> bool:
|
||||
with self.lock:
|
||||
items = self.data.get("profiles") or []
|
||||
kept = [p for p in items if p["name"].lower() != str(name).lower()]
|
||||
if len(kept) == len(items):
|
||||
return False
|
||||
self.data["profiles"] = kept
|
||||
self.save()
|
||||
return True
|
||||
@@ -0,0 +1,339 @@
|
||||
# SPDX-License-Identifier: GPL-3.0-or-later
|
||||
# Copyright (C) 2026 Farshad Zamani — Cloudtart (https://cloudtart.com)
|
||||
"""
|
||||
Auto-detection: find how the scale on a COM port talks.
|
||||
|
||||
1. LISTEN — at each common speed, in 8N1, for a moment. A scale that sends
|
||||
by itself shows up here. Readable text means the right speed; bytes that
|
||||
only become readable with their top bit cleared mean 7 data bits with
|
||||
parity (7E1/7O1), and the port is listened to again that way. Whatever
|
||||
arrives is matched against every continuous format in the library.
|
||||
|
||||
2. WAIT FOR PRINT (optional) — some indicators send only when their Print
|
||||
key is pressed (e.g. those wired to a label printer). The port is held
|
||||
open at one speed until something arrives; garbage means another speed,
|
||||
so the next press is awaited at the next one. Parity is read from the
|
||||
bytes themselves, so one press is enough for 7E1/7O1 too.
|
||||
|
||||
3. ASK — if nothing useful was heard, each read-only request in the library
|
||||
is sent at each speed and framing, and the reply is matched against the
|
||||
protocol that was asked. A reply is confirmed by asking a second time.
|
||||
`listen_only` skips this step: then nothing at all is sent to the device.
|
||||
|
||||
Everything is reported step by step through `log(code, **details)`, so the
|
||||
user interface can show (and translate) what is happening.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import time
|
||||
from dataclasses import dataclass
|
||||
from typing import Any, Callable, Optional
|
||||
|
||||
from .protocols import CONTINUOUS_IDS, POLL_IDS, PROTOCOLS, Reading
|
||||
from .serialio import LineSettings, Opener, format_hex, printable
|
||||
|
||||
PASSIVE_BAUDS = [9600, 2400, 4800, 19200, 1200, 38400, 57600, 115200]
|
||||
ACTIVE_QUICK = [(9600, "8N1"), (9600, "7E1"), (2400, "7E1"), (2400, "8N1"), (4800, "8N1"),
|
||||
(19200, "8N1"), (1200, "7E1"), (115200, "8N1")]
|
||||
ACTIVE_THOROUGH = [(9600, "8N1"), (9600, "7E1"), (9600, "7O1"), (2400, "8N1"), (2400, "7E1"),
|
||||
(4800, "8N1"), (4800, "7E1"), (19200, "8N1"), (19200, "7E1"), (1200, "8N1"),
|
||||
(1200, "7E1"), (38400, "8N1"), (57600, "8N1"), (115200, "8N1")]
|
||||
FRAMING_CHARS = {0x02, 0x03, 0x06, 0x0A, 0x0D, 0x09, 0x01, 0x04}
|
||||
|
||||
|
||||
@dataclass
|
||||
class Timings:
|
||||
passive_s: float = 1.3
|
||||
probe_s: float = 0.45
|
||||
confirm_s: float = 1.2
|
||||
drain_s: float = 0.06
|
||||
|
||||
|
||||
def readability(data: bytes, mask7: bool = False) -> float:
|
||||
if not data:
|
||||
return 0.0
|
||||
ok = 0
|
||||
for b in data:
|
||||
if mask7:
|
||||
b &= 0x7F
|
||||
if 0x20 <= b <= 0x7E or b in FRAMING_CHARS:
|
||||
ok += 1
|
||||
return ok / len(data)
|
||||
|
||||
|
||||
def _confidence(protocol_id: str, readings: list[Reading]) -> float:
|
||||
spec = PROTOCOLS[protocol_id].specificity
|
||||
base = {3: 0.9, 2: 0.8, 1: 0.6}.get(spec, 0.5)
|
||||
if any(r.checksum_ok for r in readings):
|
||||
base += 0.08
|
||||
if len(readings) >= 3:
|
||||
base += 0.02
|
||||
return round(min(base, 0.99), 2)
|
||||
|
||||
|
||||
class Detector:
|
||||
def __init__(self, opener: Opener, log: Callable[..., None] = lambda code, **kw: None,
|
||||
cancelled: Callable[[], bool] = lambda: False, thorough: bool = False,
|
||||
timings: Optional[Timings] = None, print_wait_s: float = 0,
|
||||
listen_only: bool = False):
|
||||
self.opener = opener
|
||||
self.print_wait_s = max(0.0, float(print_wait_s or 0))
|
||||
self.listen_only = listen_only
|
||||
self.log = log
|
||||
self.cancelled = cancelled
|
||||
self.thorough = thorough
|
||||
self.t = timings or Timings()
|
||||
self.active_combos = ACTIVE_THOROUGH if thorough else ACTIVE_QUICK
|
||||
self.steps_done = 0
|
||||
|
||||
# -- plumbing ----------------------------------------------------------
|
||||
def _step(self) -> None:
|
||||
self.steps_done += 1
|
||||
|
||||
@property
|
||||
def steps_per_port(self) -> int:
|
||||
return len(PASSIVE_BAUDS) + len(self.active_combos) * len(POLL_IDS)
|
||||
|
||||
@property
|
||||
def progress(self) -> float:
|
||||
"""How far the port being searched is, 0..1."""
|
||||
return min(1.0, self.steps_done / self.steps_per_port)
|
||||
|
||||
def _drain(self, ser: Any, seconds: float) -> bytes:
|
||||
buf = bytearray()
|
||||
end = time.monotonic() + seconds
|
||||
while time.monotonic() < end:
|
||||
waiting = ser.in_waiting
|
||||
buf += ser.read(waiting if waiting else 1)
|
||||
return bytes(buf)
|
||||
|
||||
def _listen(self, settings: LineSettings, seconds: float) -> bytes:
|
||||
ser = self.opener(settings)
|
||||
try:
|
||||
return self._drain(ser, seconds)
|
||||
finally:
|
||||
ser.close()
|
||||
|
||||
# -- the two phases ----------------------------------------------------
|
||||
def _match_continuous(self, data: bytes) -> Optional[tuple[str, list[Reading]]]:
|
||||
best = None
|
||||
for pid in CONTINUOUS_IDS:
|
||||
readings = PROTOCOLS[pid].readings(data)
|
||||
numeric = [r for r in readings if r.value is not None or r.overload]
|
||||
if len(numeric) < max(1, PROTOCOLS[pid].min_frames):
|
||||
continue
|
||||
key = (PROTOCOLS[pid].specificity, len(numeric))
|
||||
if best is None or key > best[0]:
|
||||
best = (key, pid, numeric)
|
||||
return (best[1], best[2]) if best else None
|
||||
|
||||
def _passive(self, port: str) -> tuple[Optional[dict], Optional[dict]]:
|
||||
"""Returns (result, unknown) — `unknown` describes readable data nobody recognised."""
|
||||
unknown = None
|
||||
for baud in PASSIVE_BAUDS:
|
||||
if self.cancelled():
|
||||
return None, unknown
|
||||
settings = LineSettings(port, baud)
|
||||
self.log("listen", port=port, baud=baud, framing="8N1")
|
||||
try:
|
||||
data = self._listen(settings, self.t.passive_s)
|
||||
except Exception as e: # noqa: BLE001
|
||||
self._step()
|
||||
self.log("open_failed", port=port, error=str(e))
|
||||
return {"error": str(e)}, None
|
||||
self._step()
|
||||
if not data:
|
||||
continue
|
||||
r8, r7 = readability(data), readability(data, mask7=True)
|
||||
self.log("heard", port=port, baud=baud, bytes=len(data), readable=round(r8, 2),
|
||||
readable7=round(r7, 2))
|
||||
attempts = []
|
||||
if r8 >= 0.85:
|
||||
attempts.append(("8N1", data))
|
||||
elif r7 >= 0.9:
|
||||
self.log("seven_bit", port=port, baud=baud)
|
||||
for framing in ("7E1", "7O1"):
|
||||
try:
|
||||
seven = self._listen(settings.with_line(baud, framing), self.t.passive_s)
|
||||
except Exception: # noqa: BLE001
|
||||
continue
|
||||
attempts.append((framing, seven))
|
||||
break
|
||||
else:
|
||||
# Framed binary formats can still be found in poorly readable data.
|
||||
attempts.append(("8N1", data))
|
||||
for framing, sample in attempts:
|
||||
match = self._match_continuous(sample)
|
||||
if match:
|
||||
pid, readings = match
|
||||
return self._result(port, pid, settings.with_line(baud, framing), readings,
|
||||
sample, mode="continuous"), None
|
||||
if readability(sample) >= 0.85 and unknown is None:
|
||||
unknown = {"baud": baud, "framing": framing, "sample_hex": format_hex(sample[:96]),
|
||||
"sample_text": printable(sample[:96])}
|
||||
return None, unknown
|
||||
|
||||
def _until_quiet(self, settings: LineSettings, wait_s: float, quiet_s: float = 0.8) -> bytes:
|
||||
"""Hold the port open until data arrives (or wait_s passes), then until it goes quiet."""
|
||||
ser = self.opener(settings)
|
||||
try:
|
||||
buf = bytearray()
|
||||
deadline = time.monotonic() + wait_s
|
||||
last = 0.0
|
||||
while not self.cancelled():
|
||||
waiting = ser.in_waiting
|
||||
chunk = ser.read(waiting if waiting else 1)
|
||||
now = time.monotonic()
|
||||
if chunk:
|
||||
buf += chunk
|
||||
last = now
|
||||
elif buf and now - last >= quiet_s:
|
||||
break
|
||||
elif not buf and now >= deadline:
|
||||
break
|
||||
return bytes(buf)
|
||||
finally:
|
||||
ser.close()
|
||||
|
||||
@staticmethod
|
||||
def _seven_bit(data: bytes) -> tuple[str, bytes]:
|
||||
"""7 data bits read as 8: bit 7 is the parity bit, which tells even from odd."""
|
||||
even = sum(1 for b in data if (bin(b & 0x7F).count("1") + (b >> 7)) % 2 == 0)
|
||||
framing = "7E1" if even >= len(data) / 2 else "7O1"
|
||||
return framing, bytes(b & 0x7F for b in data)
|
||||
|
||||
def _await_print(self, port: str) -> tuple[Optional[dict], Optional[dict]]:
|
||||
unknown = None
|
||||
for baud in PASSIVE_BAUDS:
|
||||
if self.cancelled():
|
||||
break
|
||||
settings = LineSettings(port, baud)
|
||||
self.log("press_print", port=port, baud=baud, seconds=int(self.print_wait_s))
|
||||
try:
|
||||
data = self._until_quiet(settings, self.print_wait_s)
|
||||
except Exception as e: # noqa: BLE001
|
||||
self.log("open_failed", port=port, error=str(e))
|
||||
return {"error": str(e)}, None
|
||||
if not data:
|
||||
if not self.cancelled():
|
||||
self.log("print_timeout", port=port)
|
||||
break
|
||||
r8, r7 = readability(data), readability(data, mask7=True)
|
||||
self.log("heard", port=port, baud=baud, bytes=len(data), readable=round(r8, 2),
|
||||
readable7=round(r7, 2))
|
||||
framing, sample = "8N1", data
|
||||
if r8 < 0.85 and r7 >= 0.9:
|
||||
framing, sample = self._seven_bit(data)
|
||||
match = self._match_continuous(sample)
|
||||
if match:
|
||||
pid, readings = match
|
||||
return self._result(port, pid, settings.with_line(baud, framing), readings, sample,
|
||||
mode="print"), None
|
||||
if readability(sample) >= 0.85:
|
||||
unknown = {"baud": baud, "framing": framing, "sample_hex": format_hex(sample[:96]),
|
||||
"sample_text": printable(sample[:96])}
|
||||
break
|
||||
self.log("print_wrong_speed", port=port, baud=baud)
|
||||
return None, unknown
|
||||
|
||||
def _active(self, port: str) -> tuple[Optional[dict], Optional[dict]]:
|
||||
unknown = None
|
||||
for baud, framing in self.active_combos:
|
||||
if self.cancelled():
|
||||
return None, unknown
|
||||
settings = LineSettings(port).with_line(baud, framing)
|
||||
try:
|
||||
ser = self.opener(settings)
|
||||
except Exception as e: # noqa: BLE001
|
||||
self.log("open_failed", port=port, error=str(e))
|
||||
return {"error": str(e)}, None
|
||||
try:
|
||||
for pid in POLL_IDS:
|
||||
if self.cancelled():
|
||||
return None, unknown
|
||||
proto = PROTOCOLS[pid]
|
||||
self.log("ask", port=port, baud=baud, framing=framing, protocol=pid,
|
||||
request=format_hex(proto.request))
|
||||
reply = self._ask(ser, proto)
|
||||
self._step()
|
||||
if not reply:
|
||||
continue
|
||||
readings = [r for r in proto.readings(reply) if r.value is not None or r.overload]
|
||||
self.log("reply", port=port, protocol=pid, bytes=len(reply),
|
||||
text=printable(reply[:48]), recognised=bool(readings))
|
||||
if readings:
|
||||
again = self._ask(ser, proto, seconds=self.t.confirm_s)
|
||||
confirm = [r for r in proto.readings(again) if r.value is not None or r.overload]
|
||||
if confirm:
|
||||
line = LineSettings(port, baud, request=proto.request,
|
||||
after_ack=proto.after_ack,
|
||||
poll_s=proto.default_poll_ms / 1000).with_line(baud, framing)
|
||||
return self._result(port, pid, line, readings + confirm, reply + again,
|
||||
mode="poll"), None
|
||||
elif unknown is None:
|
||||
unknown = {"baud": baud, "framing": framing, "request": format_hex(proto.request),
|
||||
"sample_hex": format_hex(reply[:96]), "sample_text": printable(reply[:96])}
|
||||
finally:
|
||||
ser.close()
|
||||
return None, unknown
|
||||
|
||||
def _ask(self, ser: Any, proto, seconds: Optional[float] = None) -> bytes:
|
||||
self._drain(ser, self.t.drain_s)
|
||||
ser.write(proto.request)
|
||||
reply = self._drain(ser, seconds or self.t.probe_s)
|
||||
if proto.after_ack and b"\x06" in reply:
|
||||
ser.write(proto.after_ack)
|
||||
reply += self._drain(ser, seconds or self.t.probe_s)
|
||||
return reply
|
||||
|
||||
# -- result ------------------------------------------------------------
|
||||
def _result(self, port: str, pid: str, settings: LineSettings, readings: list[Reading],
|
||||
sample: bytes, mode: str) -> dict:
|
||||
proto = PROTOCOLS[pid]
|
||||
latest = readings[-1]
|
||||
self.log("found", port=port, protocol=pid, baud=settings.baudrate, framing=settings.framing,
|
||||
value=latest.value, unit=latest.unit)
|
||||
return {
|
||||
"port": port,
|
||||
"found": True,
|
||||
"protocol": pid,
|
||||
"protocol_name": proto.name,
|
||||
"field_tested": proto.field_tested,
|
||||
"mode": mode,
|
||||
"serial": settings.serial_dict(),
|
||||
"exchange": settings.exchange_dict(),
|
||||
"readings": [r.as_dict() for r in readings[-6:]],
|
||||
"reading": latest.as_dict(),
|
||||
"sample_hex": format_hex(sample[:96]),
|
||||
"sample_text": printable(sample[:96]),
|
||||
"confidence": _confidence(pid, readings),
|
||||
}
|
||||
|
||||
def run_port(self, port: str) -> dict:
|
||||
self.steps_done = 0
|
||||
self.log("port_start", port=port)
|
||||
result, unknown = self._passive(port)
|
||||
if result and result.get("error"):
|
||||
return {"port": port, "found": False, "error": result["error"]}
|
||||
if result is None and self.print_wait_s and not unknown and not self.cancelled():
|
||||
result, unknown = self._await_print(port)
|
||||
if result and result.get("error"):
|
||||
return {"port": port, "found": False, "error": result["error"]}
|
||||
if result is None and not self.listen_only and not self.cancelled():
|
||||
result, unknown_active = self._active(port)
|
||||
if result and result.get("error"):
|
||||
return {"port": port, "found": False, "error": result["error"]}
|
||||
unknown = unknown or unknown_active
|
||||
if result:
|
||||
return result
|
||||
self.log("not_found", port=port, heard=bool(unknown))
|
||||
return {"port": port, "found": False, "unknown": unknown, "cancelled": self.cancelled()}
|
||||
|
||||
def run(self, ports: list[str]) -> list[dict]:
|
||||
results = []
|
||||
for port in ports:
|
||||
if self.cancelled():
|
||||
break
|
||||
results.append(self.run_port(port))
|
||||
self.log("done", found=sum(1 for r in results if r.get("found")), cancelled=self.cancelled())
|
||||
return results
|
||||
@@ -0,0 +1,146 @@
|
||||
# SPDX-License-Identifier: GPL-3.0-or-later
|
||||
# Copyright (C) 2026 Farshad Zamani - Cloudtart (https://cloudtart.com)
|
||||
"""
|
||||
Scales that send only when Print is pressed — keep listening, keep a log.
|
||||
|
||||
Such a scale (typically one wired to a label printer) sends one label per
|
||||
press and nothing in between, so a label printed while nobody had the port
|
||||
open would be lost. For every saved profile whose protocol is of that kind,
|
||||
the bridge keeps the port open all the time and records each label:
|
||||
|
||||
in memory the last LABELS_KEPT labels per profile -> GET /labels
|
||||
on disk labels/<profile>-YYYY-MM-DD.jsonl beside bridge.json
|
||||
|
||||
Each record: {"seq", "at", "profile", "port", "value", "unit", "fields", "raw_hex"}.
|
||||
`seq` grows by one per label since the bridge started, so a reader can ask
|
||||
for "everything after seq N" and never miss or repeat one.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import logging
|
||||
import os
|
||||
import re
|
||||
import threading
|
||||
from collections import deque
|
||||
from datetime import datetime
|
||||
from typing import Callable, Optional
|
||||
|
||||
from .profiles import line_settings
|
||||
from .protocols import PROTOCOLS, get_protocol
|
||||
from .serialio import PortBusy, PortWorker, Registry
|
||||
|
||||
log = logging.getLogger("scale_bridge")
|
||||
|
||||
LABELS_KEPT = 500
|
||||
PENDING_MAX = 16 * 1024
|
||||
KEEP_EVERY_S = 15
|
||||
|
||||
|
||||
def on_print(profile: dict) -> bool:
|
||||
proto = PROTOCOLS.get(profile.get("protocol") or "")
|
||||
return bool(proto and proto.kind == "print")
|
||||
|
||||
|
||||
class LabelLog:
|
||||
def __init__(self, folder: str):
|
||||
self.folder = folder
|
||||
self.lock = threading.Lock()
|
||||
self.records: dict[str, deque] = {}
|
||||
self.pending: dict[str, bytes] = {}
|
||||
self.seq = 0
|
||||
|
||||
# -- feeding -----------------------------------------------------------
|
||||
def feed(self, profile: dict, data: bytes) -> list[dict]:
|
||||
"""Bytes as they arrive; a label may come in more than one piece."""
|
||||
name = profile["name"]
|
||||
proto = get_protocol(profile["protocol"], profile.get("params"))
|
||||
with self.lock:
|
||||
buf = (self.pending.get(name, b"") + data)[-PENDING_MAX:]
|
||||
readings = proto.readings(buf)
|
||||
end_rx = getattr(proto, "_end", None)
|
||||
if readings and end_rx is not None:
|
||||
ends = list(end_rx.finditer(buf))
|
||||
buf = buf[ends[-1].end():] if ends else b""
|
||||
elif readings:
|
||||
buf = b""
|
||||
self.pending[name] = buf
|
||||
out = []
|
||||
for r in readings:
|
||||
if r.value is None:
|
||||
continue
|
||||
self.seq += 1
|
||||
rec = {"seq": self.seq, "at": datetime.now().astimezone().isoformat(timespec="seconds"),
|
||||
"profile": name, "port": profile["port"], "value": r.value,
|
||||
"unit": r.unit or profile.get("unit") or "", "fields": dict(r.fields or {}),
|
||||
"raw_hex": r.raw.hex(" ").upper()}
|
||||
self.records.setdefault(name, deque(maxlen=LABELS_KEPT)).append(rec)
|
||||
out.append(rec)
|
||||
for rec in out:
|
||||
log.info("label %s: %s %s %s", name, rec["value"], rec["unit"], rec["fields"])
|
||||
self._write(rec)
|
||||
return out
|
||||
|
||||
def _write(self, rec: dict) -> None:
|
||||
try:
|
||||
os.makedirs(self.folder, exist_ok=True)
|
||||
day = rec["at"][:10]
|
||||
safe = re.sub(r"[^A-Za-z0-9_-]", "_", rec["profile"])
|
||||
with open(os.path.join(self.folder, f"{safe}-{day}.jsonl"), "a", encoding="utf-8") as f:
|
||||
f.write(json.dumps(rec, ensure_ascii=False) + "\n")
|
||||
except OSError as e:
|
||||
log.warning("label log not written: %s", e)
|
||||
|
||||
# -- reading -----------------------------------------------------------
|
||||
def list(self, profile: Optional[str] = None, after: int = 0, limit: int = 100) -> list[dict]:
|
||||
with self.lock:
|
||||
names = [profile] if profile else list(self.records)
|
||||
items = [r for n in names for r in self.records.get(n, ()) if r["seq"] > after]
|
||||
items.sort(key=lambda r: r["seq"])
|
||||
return items[-max(1, min(limit, LABELS_KEPT)):]
|
||||
|
||||
|
||||
class Keeper(threading.Thread):
|
||||
"""Holds the ports of print-only scales open and feeds what they send to the log."""
|
||||
|
||||
def __init__(self, registry: Registry, profiles: Callable[[], list[dict]], labels: LabelLog):
|
||||
super().__init__(name="label-keeper", daemon=True)
|
||||
self.registry = registry
|
||||
self.profiles = profiles
|
||||
self.labels = labels
|
||||
self._halt = threading.Event()
|
||||
|
||||
def stop(self) -> None:
|
||||
self._halt.set()
|
||||
|
||||
def _hook(self, worker: PortWorker, profile: dict) -> None:
|
||||
if getattr(worker, "label_profile", None) == profile["name"]:
|
||||
return
|
||||
worker.listeners.append(lambda t, data, p=profile: self.labels.feed(p, data))
|
||||
worker.label_profile = profile["name"]
|
||||
|
||||
def tick(self) -> None:
|
||||
for profile in self.profiles():
|
||||
if not on_print(profile):
|
||||
continue
|
||||
try:
|
||||
worker = self.registry.worker_for(line_settings(profile))
|
||||
except PortBusy:
|
||||
continue # auto-detection has the port right now
|
||||
except Exception as e: # noqa: BLE001
|
||||
log.warning("cannot keep %s open: %s", profile.get("name"), e)
|
||||
continue
|
||||
self._hook(worker, profile)
|
||||
|
||||
def run(self) -> None:
|
||||
while not self._halt.is_set():
|
||||
try:
|
||||
self.tick()
|
||||
except Exception: # noqa: BLE001
|
||||
log.exception("label keeper")
|
||||
self._halt.wait(KEEP_EVERY_S)
|
||||
|
||||
|
||||
def labels_folder(config_path: str) -> str:
|
||||
return os.path.join(os.path.dirname(os.path.abspath(config_path)), "labels")
|
||||
|
||||
@@ -0,0 +1,237 @@
|
||||
# SPDX-License-Identifier: GPL-3.0-or-later
|
||||
# Copyright (C) 2026 Farshad Zamani — Cloudtart (https://cloudtart.com)
|
||||
"""
|
||||
Profiles: a saved answer to "how does the scale on this port talk".
|
||||
|
||||
A profile is what auto-detection found (or what was set by hand): the port,
|
||||
the line settings, the request, and the protocol that reads the reply. The
|
||||
bridge keeps profiles in bridge.json; anybody on the network with the access
|
||||
key can then ask `/weight?profile=<name>` and get a finished number.
|
||||
|
||||
{
|
||||
"name": "packing-1", letters, digits, - and _
|
||||
"label": "Packing line scale",
|
||||
"port": "COM7",
|
||||
"protocol": "mahak_mds",
|
||||
"params": {}, only for custom_binary / custom_ascii
|
||||
"serial": {...}, LineSettings.serial_dict()
|
||||
"exchange": {...}, LineSettings.exchange_dict()
|
||||
"unit": "", the unit when the frames carry none
|
||||
"output_unit": "", convert to this unit ("" = as sent)
|
||||
"stable_samples": 3 equal readings in a row = stable, when
|
||||
the protocol has no stability flag
|
||||
}
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import re
|
||||
import time
|
||||
from dataclasses import dataclass
|
||||
from datetime import datetime
|
||||
from typing import Any, Optional
|
||||
|
||||
from .protocols import GRAMS_PER, PROTOCOLS, Reading, convert, get_protocol, norm_unit
|
||||
from .serialio import LineSettings, PortWorker
|
||||
|
||||
NAME_RE = re.compile(r"^[A-Za-z0-9][A-Za-z0-9_-]{0,39}$")
|
||||
MAX_PROFILES = 64
|
||||
RECENT_CHUNKS = 24
|
||||
TAIL_BYTES = 64 # end of the previous chunk read together with the next
|
||||
|
||||
|
||||
def slug(text: str) -> str:
|
||||
s = re.sub(r"[^A-Za-z0-9_-]+", "-", str(text or "")).strip("-_").lower()
|
||||
return (s or "scale")[:40]
|
||||
|
||||
|
||||
def validate(raw: dict) -> dict:
|
||||
"""Check a profile that arrives from the user interface or from bridge.json."""
|
||||
if not isinstance(raw, dict):
|
||||
raise ValueError("profile must be an object")
|
||||
name = str(raw.get("name") or "").strip()
|
||||
if not NAME_RE.match(name):
|
||||
raise ValueError("profile name: 1-40 letters, digits, '-' or '_', starting with a letter or digit")
|
||||
protocol = str(raw.get("protocol") or "")
|
||||
if protocol not in PROTOCOLS:
|
||||
raise ValueError(f"unknown protocol: {protocol!r}")
|
||||
params = raw.get("params") or {}
|
||||
if not isinstance(params, dict):
|
||||
raise ValueError("params must be an object")
|
||||
if protocol == "custom_ascii":
|
||||
try:
|
||||
re.compile(str(params.get("regex") or "").encode("latin-1"))
|
||||
except (re.error, UnicodeEncodeError) as e:
|
||||
raise ValueError(f"invalid regular expression: {e}") from e
|
||||
if not params.get("regex"):
|
||||
raise ValueError("custom_ascii needs a regular expression")
|
||||
serial_cfg = dict(raw.get("serial") or {})
|
||||
port = str(raw.get("port") or serial_cfg.get("port") or "")
|
||||
line = LineSettings.from_dicts(serial_cfg, raw.get("exchange") or {}, port=port)
|
||||
unit = norm_unit(raw.get("unit") or "")
|
||||
output_unit = norm_unit(raw.get("output_unit") or "")
|
||||
if output_unit and output_unit not in GRAMS_PER:
|
||||
raise ValueError(f"unknown unit: {output_unit!r}")
|
||||
stable_samples = min(max(int(raw.get("stable_samples") or 3), 1), 20)
|
||||
return {
|
||||
"name": name,
|
||||
"label": str(raw.get("label") or "")[:80],
|
||||
"port": line.port,
|
||||
"protocol": protocol,
|
||||
"params": {k: params[k] for k in ("pattern", "value_offset", "value_length", "byte_order",
|
||||
"signed", "regex", "unit") if k in params},
|
||||
"serial": line.serial_dict(),
|
||||
"exchange": line.exchange_dict(),
|
||||
"unit": unit,
|
||||
"output_unit": output_unit,
|
||||
"stable_samples": stable_samples,
|
||||
"created": str(raw.get("created") or datetime.now().astimezone().isoformat(timespec="seconds")),
|
||||
}
|
||||
|
||||
|
||||
def from_detection(result: dict, name: str, label: str = "") -> dict:
|
||||
return validate({
|
||||
"name": name,
|
||||
"label": label,
|
||||
"port": result["port"],
|
||||
"protocol": result["protocol"],
|
||||
"serial": result["serial"],
|
||||
"exchange": result["exchange"],
|
||||
"unit": "" if (result.get("reading") or {}).get("unit") else "kg",
|
||||
})
|
||||
|
||||
|
||||
def line_settings(profile: dict) -> LineSettings:
|
||||
return LineSettings.from_dicts(profile["serial"], profile.get("exchange") or {},
|
||||
port=profile["port"])
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Turning the bytes a worker holds into one answer
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
@dataclass
|
||||
class Timed:
|
||||
t_ms: int
|
||||
reading: Reading
|
||||
|
||||
|
||||
def timed_readings(protocol_id: str, params: Optional[dict],
|
||||
chunks: list[tuple[int, bytes]]) -> list[Timed]:
|
||||
proto = get_protocol(protocol_id, params)
|
||||
out: list[Timed] = []
|
||||
if proto.kind == "print":
|
||||
# A label can arrive in more than one chunk: read them joined, and
|
||||
# date each reading by the chunk that completed it.
|
||||
buf = b""
|
||||
seen = 0
|
||||
for t, data in chunks:
|
||||
buf += data
|
||||
found = proto.readings(buf)
|
||||
out.extend(Timed(t, r) for r in found[seen:])
|
||||
seen = len(found)
|
||||
return out
|
||||
# Some formats only close a frame with the start of the next one (XK3190's
|
||||
# "=…=…" stream), and a device that pauses between frames puts each frame in
|
||||
# its own chunk. So read every chunk together with the end of the previous
|
||||
# one, and keep only the readings that this chunk added.
|
||||
tail = b""
|
||||
for t, data in chunks:
|
||||
before = len(proto.readings(tail)) if tail else 0
|
||||
out.extend(Timed(t, r) for r in proto.readings(tail + data)[before:])
|
||||
tail = (tail + data)[-TAIL_BYTES:]
|
||||
return out
|
||||
|
||||
|
||||
def evaluate(profile: dict, worker: PortWorker, max_age_ms: int, now: int) -> dict[str, Any]:
|
||||
"""The newest reading, with its stability and unit settled."""
|
||||
readings = timed_readings(profile["protocol"], profile.get("params"), worker.recent(RECENT_CHUNKS))
|
||||
printing = is_on_print(profile)
|
||||
base = {"ok": False, "profile": profile.get("name"), "port": profile["port"],
|
||||
"protocol": profile["protocol"], "open": worker.is_open, "on_print": printing}
|
||||
if not readings:
|
||||
if not worker.is_open:
|
||||
return {**base, "error": worker.last_error or "port is not open"}
|
||||
if printing:
|
||||
return {**base, "error": "waiting for the Print key on the scale"}
|
||||
return {**base, "error": "no data from the scale yet" if not worker.recent(1) else
|
||||
"data arrives but no weight could be read from it — check the protocol"}
|
||||
latest = readings[-1]
|
||||
age = now - latest.t_ms
|
||||
reading = latest.reading
|
||||
stale = age > max_age_ms
|
||||
if reading.value is None:
|
||||
return {**base, "ok": True, "value": None, "unit": reading.unit, "stable": False,
|
||||
"overload": reading.overload, "age_ms": age, "stale": stale,
|
||||
"raw_hex": reading.raw.hex(" ").upper()}
|
||||
|
||||
stable = reading.stable
|
||||
if stable is None:
|
||||
# No stability flag in this protocol: the same value several times in
|
||||
# a row, all of them recent, counts as stable.
|
||||
need = int(profile.get("stable_samples") or 3)
|
||||
poll_ms = int((profile.get("exchange") or {}).get("poll_interval_ms") or 500)
|
||||
window = max_age_ms + need * max(poll_ms, 250) * 2
|
||||
tail = [x.reading.value for x in readings[-need:] if now - x.t_ms <= window]
|
||||
stable = len(tail) >= need and all(v == tail[-1] for v in tail)
|
||||
unit = reading.unit or profile.get("unit") or ""
|
||||
value = reading.value
|
||||
output_unit = profile.get("output_unit") or ""
|
||||
if output_unit and unit and output_unit != unit:
|
||||
converted = convert(value, unit, output_unit)
|
||||
if converted is not None:
|
||||
value, unit = round(converted, 6), output_unit
|
||||
measured = datetime.now().astimezone().timestamp() - age / 1000
|
||||
return {
|
||||
**base,
|
||||
"ok": True,
|
||||
"value": value,
|
||||
"unit": unit,
|
||||
"stable": bool(stable) and not stale,
|
||||
"net": reading.net,
|
||||
"overload": reading.overload,
|
||||
"age_ms": age,
|
||||
"stale": stale,
|
||||
"measured_at": datetime.fromtimestamp(measured).astimezone().isoformat(timespec="milliseconds"),
|
||||
"raw_hex": reading.raw.hex(" ").upper(),
|
||||
"checksum_ok": reading.checksum_ok,
|
||||
# e.g. order number, shift and date printed on a label
|
||||
"fields": dict(reading.fields or {}),
|
||||
}
|
||||
|
||||
|
||||
def ad_hoc(port: str, protocol: str, serial_cfg: Optional[dict] = None,
|
||||
exchange_cfg: Optional[dict] = None, params: Optional[dict] = None) -> dict:
|
||||
"""A throw-away profile for `/weight?port=...` without a saved profile."""
|
||||
proto = PROTOCOLS.get(protocol)
|
||||
if proto is None:
|
||||
raise ValueError(f"unknown protocol: {protocol!r}")
|
||||
exchange = dict(exchange_cfg or {})
|
||||
if "request_hex" not in exchange:
|
||||
exchange["request_hex"] = proto.request.hex(" ")
|
||||
exchange["after_ack_hex"] = proto.after_ack.hex(" ")
|
||||
exchange.setdefault("poll_interval_ms", proto.default_poll_ms)
|
||||
return validate({"name": "adhoc", "port": port, "protocol": protocol, "params": params or {},
|
||||
"serial": serial_cfg or {}, "exchange": exchange})
|
||||
|
||||
|
||||
def is_on_print(profile: dict) -> bool:
|
||||
proto = PROTOCOLS.get(profile.get("protocol") or "")
|
||||
return bool(proto and proto.kind == "print")
|
||||
|
||||
|
||||
def wait_for_reading(profile: dict, worker: PortWorker, max_age_ms: int, wait_ms: int,
|
||||
now_fn) -> dict[str, Any]:
|
||||
"""Wait (up to wait_ms) until the newest reading is fresh, then evaluate."""
|
||||
if is_on_print(profile):
|
||||
# Nothing comes until somebody presses Print: do not hold the caller.
|
||||
wait_ms = min(wait_ms, 400)
|
||||
deadline = time.monotonic() + wait_ms / 1000
|
||||
while True:
|
||||
worker.wait_fresh(max_age_ms, int(max(0.0, deadline - time.monotonic()) * 1000))
|
||||
result = evaluate(profile, worker, max_age_ms, now_fn())
|
||||
if result.get("ok") and not result.get("stale"):
|
||||
return result
|
||||
if time.monotonic() >= deadline or (not worker.is_open and worker.last_error):
|
||||
return result
|
||||
# Data arrived but held no reading (a partial frame, a boot message …).
|
||||
time.sleep(0.05)
|
||||
@@ -0,0 +1,619 @@
|
||||
# SPDX-License-Identifier: GPL-3.0-or-later
|
||||
# Copyright (C) 2026 Farshad Zamani — Cloudtart (https://cloudtart.com)
|
||||
"""
|
||||
The protocol library: how scale indicators around the world put a weight on
|
||||
a serial line, and how to ask for it.
|
||||
|
||||
Each protocol turns raw bytes into `Reading`s. `kind` says how the device
|
||||
talks:
|
||||
|
||||
continuous it sends by itself, over and over — only listen
|
||||
poll it answers a request; `request` is that request
|
||||
handshake request -> ACK -> `after_ack` -> answer
|
||||
|
||||
Only READ-ONLY requests are used. Letters that zero, tare or switch off a
|
||||
display on some brand (Z, T, R, and P — display on/off on A&D) are never
|
||||
sent by auto-detection.
|
||||
|
||||
`field_tested` marks what has been verified on real hardware; the rest
|
||||
follows the manufacturers' published formats and is covered by tests with
|
||||
the sample frames those documents give.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import re
|
||||
from dataclasses import dataclass, field
|
||||
from typing import Any, Iterable, Optional
|
||||
|
||||
UNIT_ALIASES = {
|
||||
"kg": "kg", "kgs": "kg", "g": "g", "gr": "g", "t": "t", "ton": "t",
|
||||
"lb": "lb", "lbs": "lb", "#": "lb", "oz": "oz", "ozt": "ozt", "ct": "ct",
|
||||
}
|
||||
GRAMS_PER = {"g": 1.0, "kg": 1000.0, "t": 1_000_000.0, "lb": 453.59237, "oz": 28.349523125,
|
||||
"ozt": 31.1034768, "ct": 0.2}
|
||||
|
||||
|
||||
def norm_unit(text: Any) -> str:
|
||||
if text is None:
|
||||
return ""
|
||||
raw = text.decode("latin-1") if isinstance(text, (bytes, bytearray)) else str(text)
|
||||
raw = raw.strip()
|
||||
return UNIT_ALIASES.get(raw.lower(), raw)
|
||||
|
||||
|
||||
def convert(value: float, from_unit: str, to_unit: str) -> Optional[float]:
|
||||
"""Convert between mass units; None when either unit is not a mass unit."""
|
||||
a, b = GRAMS_PER.get(from_unit), GRAMS_PER.get(to_unit)
|
||||
if a is None or b is None:
|
||||
return None
|
||||
return value * a / b
|
||||
|
||||
|
||||
def _num(text: bytes) -> float:
|
||||
return float(text.replace(b" ", b"").replace(b",", b"."))
|
||||
|
||||
|
||||
def lines(data: bytes) -> list[bytes]:
|
||||
"""Complete lines: the text between terminators, empty ones dropped."""
|
||||
parts = re.split(rb"[\r\n\x03]+", data)
|
||||
return [p.strip(b"\x02\x00 ") for p in parts if p.strip(b"\x02\x00 ")]
|
||||
|
||||
|
||||
@dataclass
|
||||
class Reading:
|
||||
value: Optional[float] # None: the frame carries no number (overload, error)
|
||||
unit: str = ""
|
||||
stable: Optional[bool] = None # None: the protocol does not say
|
||||
net: Optional[bool] = None
|
||||
overload: bool = False
|
||||
raw: bytes = b""
|
||||
checksum_ok: Optional[bool] = None
|
||||
# Other values the frame carries (e.g. the order number on a label).
|
||||
fields: dict = field(default_factory=dict)
|
||||
|
||||
def as_dict(self) -> dict[str, Any]:
|
||||
out = {"value": self.value, "unit": self.unit, "stable": self.stable, "net": self.net,
|
||||
"overload": self.overload, "raw_hex": self.raw.hex(" ").upper(),
|
||||
"checksum_ok": self.checksum_ok}
|
||||
if self.fields:
|
||||
out["fields"] = dict(self.fields)
|
||||
return out
|
||||
|
||||
|
||||
@dataclass
|
||||
class Protocol:
|
||||
id: str
|
||||
name: str
|
||||
kind: str = "continuous"
|
||||
request: bytes = b""
|
||||
after_ack: bytes = b""
|
||||
families: str = ""
|
||||
reference: str = ""
|
||||
field_tested: bool = False
|
||||
specificity: int = 2 # 1 generic … 3 strictly framed (wins ties in detection)
|
||||
default_poll_ms: int = 500
|
||||
# Readings auto-detection needs to see. A device that only sends when its
|
||||
# Print key is pressed may send just one.
|
||||
min_frames: int = 2
|
||||
params: dict = field(default_factory=dict)
|
||||
|
||||
def readings(self, data: bytes) -> list[Reading]: # pragma: no cover - abstract
|
||||
raise NotImplementedError
|
||||
|
||||
def info(self) -> dict[str, Any]:
|
||||
return {"id": self.id, "name": self.name, "kind": self.kind,
|
||||
"on_print": self.kind == "print",
|
||||
"request_hex": self.request.hex(" ").upper(),
|
||||
"after_ack_hex": self.after_ack.hex(" ").upper(),
|
||||
"families": self.families, "reference": self.reference,
|
||||
"field_tested": self.field_tested}
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Mettler Toledo
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
class MtSics(Protocol):
|
||||
"""MT-SICS: 'SI' -> 'S S 0.550 kg' (S = stable, D = dynamic)."""
|
||||
_re = re.compile(rb"^S\s+([SD+\-])\s*([-+]?\s*\d+(?:[.,]\d+)?)?\s*([A-Za-z%#]{0,4})")
|
||||
|
||||
def readings(self, data: bytes) -> list[Reading]:
|
||||
out = []
|
||||
for line in lines(data):
|
||||
m = self._re.match(line)
|
||||
if not m:
|
||||
continue
|
||||
flag = m.group(1)
|
||||
if flag in (b"+", b"-"):
|
||||
out.append(Reading(None, overload=True, raw=line))
|
||||
elif m.group(2):
|
||||
out.append(Reading(_num(m.group(2)), norm_unit(m.group(3)),
|
||||
stable=flag == b"S", raw=line))
|
||||
return out
|
||||
|
||||
|
||||
class ToledoContinuous(Protocol):
|
||||
"""
|
||||
Toledo Continuous (Mettler Toledo standard continuous output, copied by
|
||||
many other indicators):
|
||||
|
||||
STX SWA SWB SWC W W W W W W T T T T T T CR [CHK]
|
||||
|
||||
SWA bits 0-2 place the decimal point (X00, X0, X, 0.X ... 0.0000X);
|
||||
SWB bit0 net, bit1 negative, bit2 over/under range, bit3 motion,
|
||||
bit4 kg (else lb); SWC bits 0-2 override the unit (1 g, 2 t, 3 oz).
|
||||
Bit 5 of each status byte is always set. CHK is the two's complement of
|
||||
the 7-bit sum of STX..CR.
|
||||
"""
|
||||
_re = re.compile(rb"\x02([\x20-\x7f])([\x20-\x7f])([\x20-\x7f])([0-9 ]{6})([0-9 ]{6})\r(.?)",
|
||||
re.S)
|
||||
_factor = {0: 100, 1: 10, 2: 1, 3: 0.1, 4: 0.01, 5: 0.001, 6: 0.0001, 7: 0.00001}
|
||||
_decimals = {0: 0, 1: 0, 2: 0, 3: 1, 4: 2, 5: 3, 6: 4, 7: 5}
|
||||
|
||||
def readings(self, data: bytes) -> list[Reading]:
|
||||
out = []
|
||||
for m in self._re.finditer(data):
|
||||
swa, swb, swc = m.group(1)[0], m.group(2)[0], m.group(3)[0]
|
||||
if not (swa & 0x20 and swb & 0x20 and swc & 0x20):
|
||||
continue
|
||||
dp = swa & 0x07
|
||||
value = round(int(m.group(4).replace(b" ", b"0")) * self._factor[dp], self._decimals[dp])
|
||||
if swb & 0x02:
|
||||
value = -value
|
||||
unit = {1: "g", 2: "t", 3: "oz"}.get(swc & 0x07, "kg" if swb & 0x10 else "lb")
|
||||
frame = data[m.start():m.end(5) + 1]
|
||||
checksum_ok = None
|
||||
if m.group(6) and m.group(6) != b"\x02":
|
||||
checksum_ok = ((-sum(b & 0x7F for b in frame)) & 0x7F) == (m.group(6)[0] & 0x7F)
|
||||
out.append(Reading(value, unit, stable=not (swb & 0x08), net=bool(swb & 0x01),
|
||||
overload=bool(swb & 0x04), raw=frame, checksum_ok=checksum_ok))
|
||||
return out
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# A&D and the many indicators that copy its format
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
class AndStandard(Protocol):
|
||||
"""'ST,+00000.55 kg', 'US,GS,+0012.34kg', 'OL,+9999999 kg' (ST stable, US unstable, OL overload)."""
|
||||
_re = re.compile(rb"^(ST|US|OL|QT|WT)\s*,\s*(?:(GS|NT|TR|G|N)\s*,\s*)?([-+])?\s*(\d+(?:[.,]\d+)?)?\s*"
|
||||
rb"([A-Za-z%#]{0,4})")
|
||||
|
||||
def readings(self, data: bytes) -> list[Reading]:
|
||||
out = []
|
||||
for line in lines(data):
|
||||
m = self._re.match(line)
|
||||
if not m:
|
||||
continue
|
||||
head = m.group(1)
|
||||
net = {b"NT": True, b"N": True, b"GS": False, b"G": False}.get(m.group(2))
|
||||
if head == b"OL" or not m.group(4):
|
||||
out.append(Reading(None, overload=head == b"OL", net=net, raw=line))
|
||||
continue
|
||||
value = _num(m.group(4)) * (-1 if m.group(3) == b"-" else 1)
|
||||
out.append(Reading(value, norm_unit(m.group(5)), stable=head in (b"ST", b"QT"),
|
||||
net=net, raw=line))
|
||||
return out
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# SMA (Scale Manufacturers Association) and NCI 3835
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
class Sma(Protocol):
|
||||
"""
|
||||
SMA SCP-0499: '<LF>W<CR>' -> '<LF><s><r><n><m><f><weight:10><unit:3><CR>'.
|
||||
s = Z/O/U/E/I/T/space, r = range, n = G/T/N, m = 'M' in motion.
|
||||
"""
|
||||
_re = re.compile(rb"\n([ ZOUEIT])([ 0-9])([GTNgtn])([M ])([ -~])([ -~]{10})([ -~]{1,3})\r")
|
||||
|
||||
def readings(self, data: bytes) -> list[Reading]:
|
||||
out = []
|
||||
for m in self._re.finditer(data):
|
||||
field_text = m.group(6).strip()
|
||||
status = m.group(1)
|
||||
try:
|
||||
value = _num(field_text) if re.fullmatch(rb"[-+]?\d+(?:\.\d+)?", field_text) else None
|
||||
except ValueError:
|
||||
value = None
|
||||
out.append(Reading(value, norm_unit(m.group(7)), stable=m.group(4) != b"M",
|
||||
net=m.group(3) in (b"N", b"n"), overload=status in (b"O", b"U"),
|
||||
raw=m.group(0)))
|
||||
return out
|
||||
|
||||
|
||||
class Nci(Protocol):
|
||||
"""NCI 3835: 'W<CR>' -> '<LF> 1.23lb<CR><LF>hh<CR><ETX>' (hh status, bit0 of h1 = motion)."""
|
||||
_re = re.compile(rb"\n\s*([-+]?\s*\d+(?:\.\d+)?)\s*(lb|kg|g|oz|LB|KG|G|OZ)\s*\r(?:\n(.)(.)\r)?", re.S)
|
||||
|
||||
def readings(self, data: bytes) -> list[Reading]:
|
||||
out = []
|
||||
for m in self._re.finditer(data):
|
||||
stable = None if m.group(3) is None else not (m.group(3)[0] & 0x01)
|
||||
out.append(Reading(_num(m.group(1)), norm_unit(m.group(2)), stable=stable, raw=m.group(0)))
|
||||
return out
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Ohaus, Sartorius
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
class Ohaus(Protocol):
|
||||
"""'IP' -> ' 0.550 kg ' ('?' after the unit when unstable, optional G/N)."""
|
||||
_re = re.compile(rb"^([-+]?\s*\d+(?:[.,]\d+)?)\s*([A-Za-z%#]{1,4})\s*(\?)?\s*([GNT])?\s*$")
|
||||
|
||||
def readings(self, data: bytes) -> list[Reading]:
|
||||
out = []
|
||||
for line in lines(data):
|
||||
m = self._re.match(line)
|
||||
if m:
|
||||
out.append(Reading(_num(m.group(1)), norm_unit(m.group(2)), stable=m.group(3) is None,
|
||||
net={b"N": True, b"G": False}.get(m.group(4)), raw=line))
|
||||
return out
|
||||
|
||||
|
||||
class Sartorius(Protocol):
|
||||
"""
|
||||
Sartorius SBI: 'ESC P' -> '+ 0.550 kg ' or 'N + 0.550 kg'.
|
||||
An unstable value is sent WITHOUT its unit — that is the stability flag.
|
||||
"""
|
||||
_re = re.compile(rb"^(?:([A-Za-z#]{1,6})\s+)?([-+])\s*(\d+(?:[.,]\d+)?)\s*([A-Za-z%]{0,4})\s*$")
|
||||
|
||||
def readings(self, data: bytes) -> list[Reading]:
|
||||
out = []
|
||||
for line in lines(data):
|
||||
m = self._re.match(line)
|
||||
if not m:
|
||||
continue
|
||||
value = _num(m.group(3)) * (-1 if m.group(2) == b"-" else 1)
|
||||
ident = (m.group(1) or b"").upper()
|
||||
out.append(Reading(value, norm_unit(m.group(4)), stable=bool(m.group(4)),
|
||||
net=True if ident.startswith(b"N") else (False if ident.startswith(b"G") else None),
|
||||
raw=line))
|
||||
return out
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# CAS (ENQ/ACK/DC1)
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
class CasEnq(Protocol):
|
||||
"""ENQ -> ACK, DC1 -> '...S/U ... weight unit...'. Parsed loosely; experimental."""
|
||||
_re = re.compile(rb"([SU])[ ,A-Z]*?([-+ ])?\s*(\d+(?:\.\d+)?)\s*(kg|g|lb|oz|KG|LB|OZ|G)")
|
||||
|
||||
def readings(self, data: bytes) -> list[Reading]:
|
||||
out = []
|
||||
for m in self._re.finditer(data):
|
||||
value = _num(m.group(3)) * (-1 if m.group(2) == b"-" else 1)
|
||||
out.append(Reading(value, norm_unit(m.group(4)), stable=m.group(1) == b"S", raw=m.group(0)))
|
||||
return out
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Chinese XK3190 family (Yaohua and compatibles)
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
class Xk3190Continuous(Protocol):
|
||||
"""
|
||||
XK3190 continuous mode (tF=0), 12 bytes:
|
||||
STX, sign, 6 digits (high first), decimals (0-4), XOR high nibble, XOR low nibble, ETX.
|
||||
XOR covers the sign through the decimals byte. No unit is sent.
|
||||
"""
|
||||
_re = re.compile(rb"\x02([+-])(\d{6})([0-4])(..)\x03", re.S)
|
||||
|
||||
def readings(self, data: bytes) -> list[Reading]:
|
||||
out = []
|
||||
for m in self._re.finditer(data):
|
||||
body = m.group(1) + m.group(2) + m.group(3)
|
||||
x = 0
|
||||
for b in body:
|
||||
x ^= b
|
||||
got = m.group(4)
|
||||
hex_form = f"{x >> 4:X}{x & 0xF:X}".encode()
|
||||
nibble_form = bytes([0x30 + (x >> 4), 0x30 + (x & 0xF)])
|
||||
decimals = int(m.group(3))
|
||||
value = round(int(m.group(2)) / (10 ** decimals), decimals) * (-1 if m.group(1) == b"-" else 1)
|
||||
out.append(Reading(value, "", raw=m.group(0),
|
||||
checksum_ok=got.upper() in (hex_form, nibble_form)))
|
||||
return out
|
||||
|
||||
|
||||
class Xk3190Reversed(Protocol):
|
||||
"""
|
||||
XK3190 'D2+' continuous modes (tF=2/3): the displayed weight with its
|
||||
characters REVERSED, frames separated by '='. 70.15 kg -> '51.07000='.
|
||||
"""
|
||||
_token = re.compile(rb"^[-0-9.]{5,10}$")
|
||||
|
||||
def readings(self, data: bytes) -> list[Reading]:
|
||||
if data.count(b"=") < 2:
|
||||
return []
|
||||
out = []
|
||||
for token in data.split(b"=")[1:-1]:
|
||||
token = token.strip()
|
||||
if not self._token.match(token) or token.count(b".") > 1:
|
||||
continue
|
||||
try:
|
||||
value = float(token[::-1])
|
||||
except ValueError:
|
||||
continue
|
||||
out.append(Reading(value, "", raw=b"=" + token))
|
||||
return out
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Mahak (Iran) — field-tested
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
class MahakMds(Protocol):
|
||||
"""
|
||||
Mahak MDS series (e.g. MDS 13000, older firmware): request 4D 09 04 07,
|
||||
reply 58 ?? 07 07 W2 W1 W0 — grams, 24-bit big-endian. The scale's menu
|
||||
must be set to Serial mode. Byte 1 varies and is ignored.
|
||||
"""
|
||||
_re = re.compile(rb"\x58.\x07\x07(...)", re.S)
|
||||
|
||||
def readings(self, data: bytes) -> list[Reading]:
|
||||
return [Reading(float(int.from_bytes(m.group(1), "big")), "g", raw=m.group(0))
|
||||
for m in self._re.finditer(data)]
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Label printer streams — indicators wired to a label printer
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
_KV = re.compile(r"([A-Za-z][A-Za-z0-9_.]*)\s*:\s*(.*?)(?=\s+[A-Za-z][A-Za-z0-9_.]*\s*:|$)")
|
||||
_DATE = re.compile(r"\b(\d{2,4}[/.-]\d{1,2}[/.-]\d{1,4})\b(?:\s*-?\s*(\d{1,2}:\d{2}(?::\d{2})?))?")
|
||||
_NUMBER = re.compile(r"^[-+]?\s*\d+(?:[.,]\d+)?$")
|
||||
_NUMBER_UNIT = re.compile(r"^([-+]?\s*\d+(?:[.,]\d+)?)\s*\(?\s*(kg|g|t|lb|lbs|oz)\s*\)?$", re.I)
|
||||
_WEIGHT_WORD = re.compile(r"(weight|wt|net|gross|n\.?w|g\.?w|\u0648\u0632\u0646)\s*[:=]?\s*([-+]?\d+(?:[.,]\d+)?)\s*\(?\s*(kg|g|t|lb|oz)?",
|
||||
re.I)
|
||||
|
||||
|
||||
def _unit_only(text: str) -> str:
|
||||
t = text.strip().strip("()[]").strip()
|
||||
return norm_unit(t) if norm_unit(t) in GRAMS_PER else ""
|
||||
|
||||
|
||||
class LabelPrinter(Protocol):
|
||||
"""
|
||||
An indicator that prints labels: on its Print key it sends the whole label
|
||||
program to a label printer — TSPL/TSPL2 (TSC and compatibles), EPL2 (Zebra/
|
||||
Eltron, Argox) or ZPL (Zebra). Listening to that line (a Y cable leaves the
|
||||
printer connected) gives the weight the operator printed, plus whatever
|
||||
else the label carries: order number, shift, date, thickness …
|
||||
|
||||
One reading per printed label (TSPL `PRINT`, EPL `P`, ZPL `^XZ`). The weight
|
||||
is the number printed next to a weight unit — "141.800" followed by "(Kg)",
|
||||
or "1.25 kg" in one text — or after a word such as Weight/Net/Gross/وزن.
|
||||
A printed weight counts as stable: indicators print settled weights.
|
||||
"""
|
||||
_tspl_text = re.compile(rb'^(?:TEXT|BLOCK)\s[^"]*"[^"]*"[^"]*?"(.*?)"?\s*$')
|
||||
_tspl_barcode = re.compile(rb'^BARCODE\s[^"]*"[^"]*"[^"]*?"(.*?)"?\s*$')
|
||||
_epl_text = re.compile(rb'^A\d+,\d+,[^"]*"(.*?)"?\s*$')
|
||||
_epl_barcode = re.compile(rb'^B\d+,\d+,[^"]*"(.*?)"?\s*$')
|
||||
_zpl_field = re.compile(rb"\^FD(.*?)\^FS", re.S)
|
||||
_end = re.compile(rb"(?:^|[\r\n])(?:PRINT\s+\d+(?:\s*,\s*\d+)?|P\d+(?:,\d+)?)\s*(?=[\r\n]|$)|\^XZ")
|
||||
|
||||
def _texts(self, label: bytes) -> tuple[list[str], list[str]]:
|
||||
texts: list[str] = []
|
||||
codes: list[str] = []
|
||||
if b"^FD" in label:
|
||||
for m in self._zpl_field.finditer(label):
|
||||
texts.append(m.group(1).decode("latin-1"))
|
||||
return texts, codes
|
||||
for line in re.split(rb"[\r\n]+", label):
|
||||
line = line.strip()
|
||||
for rx, bucket in ((self._tspl_text, texts), (self._tspl_barcode, codes),
|
||||
(self._epl_text, texts), (self._epl_barcode, codes)):
|
||||
m = rx.match(line)
|
||||
if m:
|
||||
bucket.append(m.group(1).decode("latin-1"))
|
||||
break
|
||||
return texts, codes
|
||||
|
||||
def _weight(self, texts: list[str]) -> Optional[tuple[float, str]]:
|
||||
clean = [t.strip() for t in texts]
|
||||
for i, t in enumerate(clean):
|
||||
m = _NUMBER_UNIT.match(t)
|
||||
if m:
|
||||
return _num(m.group(1).encode()), norm_unit(m.group(2))
|
||||
if _NUMBER.match(t):
|
||||
for j in (i + 1, i - 1):
|
||||
if 0 <= j < len(clean) and _unit_only(clean[j]):
|
||||
return _num(t.encode()), _unit_only(clean[j])
|
||||
for t in clean:
|
||||
m = _WEIGHT_WORD.search(t)
|
||||
if m:
|
||||
return _num(m.group(2).encode()), norm_unit(m.group(3) or "")
|
||||
return None
|
||||
|
||||
@staticmethod
|
||||
def _fields(texts: list[str], codes: list[str]) -> dict:
|
||||
fields: dict[str, str] = {}
|
||||
for t in texts:
|
||||
d = _DATE.search(t)
|
||||
if d and "date" not in fields:
|
||||
fields["date"] = d.group(1)
|
||||
if d.group(2):
|
||||
fields["time"] = d.group(2)
|
||||
continue
|
||||
for key, value in _KV.findall(t):
|
||||
value = value.strip().strip('"').strip()
|
||||
if value:
|
||||
fields.setdefault(key.strip(), value)
|
||||
if codes:
|
||||
fields["barcode"] = codes[0].replace("\t", " | ").strip()
|
||||
return fields
|
||||
|
||||
def readings(self, data: bytes) -> list[Reading]:
|
||||
out = []
|
||||
start = 0
|
||||
for end in self._end.finditer(data):
|
||||
label = data[start:end.end()]
|
||||
start = end.end()
|
||||
texts, codes = self._texts(label)
|
||||
found = self._weight(texts)
|
||||
if found is None:
|
||||
continue
|
||||
value, unit = found
|
||||
out.append(Reading(value, unit, stable=True, raw=label.strip(b"\r\n"),
|
||||
fields=self._fields(texts, codes)))
|
||||
return out
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Generic and custom
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
class GenericAscii(Protocol):
|
||||
"""Any readable line with a number in it — the last resort for continuous output."""
|
||||
_re = re.compile(rb"([-+]?\s*\d+(?:[.,]\d+)?)\s*(kg|g|lb|lbs|oz|t|KG|G|LB|OZ|T)?\b")
|
||||
_stable_words = re.compile(rb"\b(ST|S)\b")
|
||||
_unstable_words = re.compile(rb"\b(US|D|M|MOTION)\b|\?")
|
||||
|
||||
def readings(self, data: bytes) -> list[Reading]:
|
||||
out = []
|
||||
for line in lines(data):
|
||||
if len(line) > 80 or sum(32 <= b < 127 for b in line) < len(line) * 0.9:
|
||||
continue
|
||||
numbers = list(self._re.finditer(line))
|
||||
if not numbers:
|
||||
continue
|
||||
m = numbers[-1]
|
||||
stable = None
|
||||
if self._unstable_words.search(line):
|
||||
stable = False
|
||||
elif self._stable_words.search(line):
|
||||
stable = True
|
||||
out.append(Reading(_num(m.group(1)), norm_unit(m.group(2)), stable=stable, raw=line))
|
||||
return out
|
||||
|
||||
|
||||
class CustomBinary(Protocol):
|
||||
"""
|
||||
A binary frame described by hand: `pattern` (hex, '??' = any byte), then
|
||||
`value_length` bytes at `value_offset` from the pattern's first byte.
|
||||
"""
|
||||
|
||||
def readings(self, data: bytes) -> list[Reading]:
|
||||
p = self.params
|
||||
pattern = [None if t == "??" else int(t, 16) for t in str(p.get("pattern") or "").split()]
|
||||
offset = int(p.get("value_offset") or 0)
|
||||
length = int(p.get("value_length") or 1)
|
||||
order = "little" if p.get("byte_order") == "little" else "big"
|
||||
signed = bool(p.get("signed"))
|
||||
unit = norm_unit(p.get("unit") or "")
|
||||
out = []
|
||||
n = len(pattern)
|
||||
starts = [0] if not n else [
|
||||
i for i in range(0, len(data) - n + 1)
|
||||
if all(b is None or data[i + k] == b for k, b in enumerate(pattern))]
|
||||
for start in starts:
|
||||
end = start + offset + length
|
||||
if end > len(data):
|
||||
continue
|
||||
value = int.from_bytes(data[start + offset:end], order, signed=signed)
|
||||
out.append(Reading(float(value), unit, raw=data[start:max(end, start + n)]))
|
||||
return out
|
||||
|
||||
|
||||
class CustomAscii(Protocol):
|
||||
"""Any text format described by hand: the first group of `regex` is the number."""
|
||||
|
||||
def readings(self, data: bytes) -> list[Reading]:
|
||||
regex = str(self.params.get("regex") or "")
|
||||
if not regex:
|
||||
return []
|
||||
compiled = re.compile(regex.encode("latin-1"))
|
||||
unit = norm_unit(self.params.get("unit") or "")
|
||||
out = []
|
||||
for line in lines(data):
|
||||
m = compiled.search(line)
|
||||
if m and m.groups() and m.group(1):
|
||||
try:
|
||||
out.append(Reading(_num(m.group(1)), unit, raw=line))
|
||||
except ValueError:
|
||||
continue
|
||||
return out
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# The catalogue
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
def _catalogue() -> dict[str, Protocol]:
|
||||
items: Iterable[Protocol] = [
|
||||
MtSics("mt_sics", "Mettler Toledo MT-SICS", kind="poll", request=b"SI\r\n", specificity=3,
|
||||
families="Mettler Toledo terminals and balances (IND, ICS, XS, ML…)",
|
||||
reference="MT-SICS reference manual"),
|
||||
ToledoContinuous("toledo_cont", "Toledo Continuous (STX + status words)", specificity=3,
|
||||
families="Mettler Toledo IND/Panther/Jaguar/Lynx and many compatible indicators",
|
||||
reference="Mettler Toledo 'Standard continuous output' (e.g. IND425 manual 4.2)"),
|
||||
AndStandard("and_std", "A&D standard format (ST/US/OL)", kind="poll", request=b"Q\r\n",
|
||||
specificity=3,
|
||||
families="A&D indicators/balances and many Asian indicators (continuous or on request)",
|
||||
reference="A&D indicator manuals, data format section"),
|
||||
Sma("sma", "SMA standard (Scale Manufacturers Association)", kind="poll", request=b"\nW\r",
|
||||
specificity=3, families="Rice Lake, Avery Weigh-Tronix, Cardinal, Fairbanks and other SMA-compliant indicators",
|
||||
reference="SMA SCP-0499"),
|
||||
Nci("nci", "NCI 3835 / Weigh-Tronix", kind="poll", request=b"W\r", specificity=2,
|
||||
families="NCI / Avery Weigh-Tronix shipping and bench scales",
|
||||
reference="NCI 3835 protocol"),
|
||||
Ohaus("ohaus", "Ohaus", kind="poll", request=b"IP\r\n", specificity=2,
|
||||
families="Ohaus Defender, Ranger, Valor and compatible indicators",
|
||||
reference="Ohaus interface command table (IP = immediate print)"),
|
||||
Sartorius("sartorius", "Sartorius SBI", kind="poll", request=b"\x1bP\r\n", specificity=2,
|
||||
families="Sartorius balances and Combics/Signum indicators",
|
||||
reference="Sartorius SBI data output format"),
|
||||
CasEnq("cas_enq", "CAS (ENQ/ACK/DC1), experimental", kind="handshake", request=b"\x05",
|
||||
after_ack=b"\x11", specificity=2, families="CAS scales and compatibles",
|
||||
reference="CAS ENQ/ACK polling"),
|
||||
Xk3190Continuous("xk3190_tf0", "XK3190 continuous (tF=0)", specificity=3,
|
||||
families="Yaohua XK3190-A9/A12 and compatible Chinese indicators",
|
||||
reference="XK3190-A9+ user manual, serial output"),
|
||||
Xk3190Reversed("xk3190_reversed", "XK3190 '=' reversed-digit stream (tF=2/3)", specificity=2,
|
||||
field_tested=True,
|
||||
families="Yaohua XK3190 series (A9, A12, T7E / YH-T7E …) and compatible indicators/big displays",
|
||||
reference="XK3190-A9+ user manual (D2+ continuous mode); YH-T7E user manual V1.01, 3.3"),
|
||||
MahakMds("mahak_mds", "Mahak MDS binary (4D 09 04 07)", kind="poll",
|
||||
request=bytes.fromhex("4D090407"), specificity=3, field_tested=True,
|
||||
families="Mahak MDS 13000 and related Mahak scales (Iran), Serial mode",
|
||||
reference="Mahak developer guide + field test"),
|
||||
LabelPrinter("label_print", "Label printer stream (TSPL / EPL / ZPL)", kind="print",
|
||||
specificity=3, min_frames=1, field_tested=True,
|
||||
families="Indicators wired to a label printer (TSC, Zebra, Argox…); sends on Print. "
|
||||
"Tested on a PTC400 indicator (TSPL)",
|
||||
reference="TSC TSPL/TSPL2, Zebra EPL2 and ZPL programming manuals + field test"),
|
||||
GenericAscii("ascii_generic", "Generic text (number + unit)", specificity=1,
|
||||
families="Any indicator that streams readable weight text",
|
||||
reference="heuristic"),
|
||||
CustomBinary("custom_binary", "Custom binary frame", kind="poll", specificity=0,
|
||||
reference="configured by hand"),
|
||||
CustomAscii("custom_ascii", "Custom text (regular expression)", kind="poll", specificity=0,
|
||||
reference="configured by hand"),
|
||||
]
|
||||
return {p.id: p for p in items}
|
||||
|
||||
|
||||
PROTOCOLS: dict[str, Protocol] = _catalogue()
|
||||
|
||||
# Detection order. Continuous formats are tried on whatever a port sends by
|
||||
# itself; poll protocols are asked in turn when it sends nothing.
|
||||
CONTINUOUS_IDS = ["label_print", "toledo_cont", "xk3190_tf0", "and_std", "mt_sics", "sma",
|
||||
"xk3190_reversed", "ohaus", "sartorius", "ascii_generic"]
|
||||
POLL_IDS = ["mt_sics", "and_std", "sma", "nci", "ohaus", "sartorius", "mahak_mds", "cas_enq"]
|
||||
|
||||
|
||||
def get_protocol(protocol_id: str, params: Optional[dict] = None) -> Protocol:
|
||||
base = PROTOCOLS.get(protocol_id)
|
||||
if base is None:
|
||||
raise KeyError(f"unknown protocol: {protocol_id}")
|
||||
if params:
|
||||
clone = type(base)(**{**base.__dict__, "params": dict(params)})
|
||||
return clone
|
||||
return base
|
||||
|
||||
|
||||
def catalogue_info() -> list[dict[str, Any]]:
|
||||
return [p.info() for p in PROTOCOLS.values()]
|
||||
@@ -0,0 +1,431 @@
|
||||
# SPDX-License-Identifier: GPL-3.0-or-later
|
||||
# Copyright (C) 2026 Farshad Zamani — Cloudtart (https://cloudtart.com)
|
||||
"""
|
||||
Serial ports: listing them, describing a line, and keeping one open.
|
||||
|
||||
A `PortWorker` owns one COM port. While somebody keeps asking for data it
|
||||
holds the port open, sends the request (if the device must be asked) at
|
||||
the poll interval, cuts what comes back into chunks at silences, and keeps
|
||||
the recent chunks. Unplugging the USB cable, a driver hiccup or a busy port
|
||||
are all survived: the worker closes, waits, and opens again.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
import re
|
||||
import threading
|
||||
import time
|
||||
from collections import deque
|
||||
from dataclasses import dataclass
|
||||
from typing import Any, Callable, Optional
|
||||
|
||||
try:
|
||||
import serial
|
||||
from serial.tools import list_ports as _list_ports
|
||||
except ImportError: # pragma: no cover
|
||||
serial = None
|
||||
_list_ports = None
|
||||
|
||||
log = logging.getLogger("scale_bridge")
|
||||
|
||||
RING_SIZE = 64 # chunks kept per port
|
||||
MAX_CHUNK = 512 # a continuous stream without silences is cut here
|
||||
IDLE_CLOSE_S = 120 # a port nobody asked about for this long is released
|
||||
MAX_REQUEST_BYTES = 64
|
||||
|
||||
_PORT_RE = re.compile(r"^(COM\d{1,3}|/dev/[A-Za-z0-9_./-]+)$", re.IGNORECASE)
|
||||
|
||||
# USB-serial chips worth a word to the person choosing a port.
|
||||
KNOWN_CHIPS: dict[int, tuple[str, str]] = {
|
||||
0x1A86: ("WCH CH340/CH341",
|
||||
"Clone CH340 chips fail with WCH drivers 3.8 and newer on Windows "
|
||||
"('A device attached to the system is not functioning'). Install driver "
|
||||
"3.5.2019.1 or use an FTDI-based adapter."),
|
||||
0x067B: ("Prolific PL2303",
|
||||
"Counterfeit PL2303 chips are refused by newer Prolific drivers (Code 10). "
|
||||
"Use an older driver or an FTDI-based adapter."),
|
||||
0x0403: ("FTDI", ""),
|
||||
0x10C4: ("Silicon Labs CP210x", ""),
|
||||
0x0557: ("ATEN", ""),
|
||||
0x110A: ("Moxa", ""),
|
||||
}
|
||||
|
||||
|
||||
def now_ms() -> int:
|
||||
return int(time.monotonic() * 1000)
|
||||
|
||||
|
||||
def parse_hex(text: str) -> bytes:
|
||||
"""'4d0904 07', '0x4D 0x09', '4D-09' -> bytes. Raises ValueError."""
|
||||
cleaned = re.sub(r"0x", "", str(text or ""), flags=re.IGNORECASE)
|
||||
cleaned = re.sub(r"[\s,;:-]+", "", cleaned)
|
||||
return bytes.fromhex(cleaned)
|
||||
|
||||
|
||||
def format_hex(data: bytes) -> str:
|
||||
return data.hex(" ").upper()
|
||||
|
||||
|
||||
def printable(data: bytes) -> str:
|
||||
names = {0x02: "<STX>", 0x03: "<ETX>", 0x0D: "<CR>", 0x0A: "<LF>", 0x05: "<ENQ>",
|
||||
0x06: "<ACK>", 0x15: "<NAK>", 0x1B: "<ESC>", 0x11: "<DC1>"}
|
||||
out = []
|
||||
for b in data:
|
||||
if b in names:
|
||||
out.append(names[b])
|
||||
elif 32 <= b < 127:
|
||||
out.append(chr(b))
|
||||
else:
|
||||
out.append(f"<{b:02X}>")
|
||||
return "".join(out)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# One line's settings
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class LineSettings:
|
||||
port: str
|
||||
baudrate: int = 9600
|
||||
bytesize: int = 8
|
||||
parity: str = "N"
|
||||
stopbits: float = 1
|
||||
dtr: bool = True
|
||||
rts: bool = True
|
||||
request: bytes = b"" # sent every poll interval; empty = only listen
|
||||
after_ack: bytes = b"" # sent when the device answers the request with ACK
|
||||
poll_s: float = 0.5
|
||||
gap_s: float = 0.05 # silence that ends a chunk
|
||||
|
||||
@property
|
||||
def framing(self) -> str:
|
||||
stop = int(self.stopbits) if self.stopbits in (1, 2) else self.stopbits
|
||||
return f"{self.bytesize}{self.parity}{stop}"
|
||||
|
||||
def describe(self) -> str:
|
||||
req = f", request {format_hex(self.request)}" if self.request else ", listen only"
|
||||
return f"{self.port} {self.baudrate} {self.framing}{req}"
|
||||
|
||||
def with_line(self, baudrate: int, framing: str) -> "LineSettings":
|
||||
bits, parity, stop = int(framing[0]), framing[1], float(framing[2:])
|
||||
return LineSettings(self.port, baudrate, bits, parity, stop, self.dtr, self.rts,
|
||||
self.request, self.after_ack, self.poll_s, self.gap_s)
|
||||
|
||||
def serial_dict(self) -> dict[str, Any]:
|
||||
stop = int(self.stopbits) if self.stopbits in (1, 2) else self.stopbits
|
||||
return {"port": self.port, "baudrate": self.baudrate, "bytesize": self.bytesize,
|
||||
"parity": self.parity, "stopbits": stop, "dtr": self.dtr, "rts": self.rts}
|
||||
|
||||
def exchange_dict(self) -> dict[str, Any]:
|
||||
return {"request_hex": format_hex(self.request),
|
||||
"after_ack_hex": format_hex(self.after_ack),
|
||||
"poll_interval_ms": int(round(self.poll_s * 1000)),
|
||||
"frame_gap_ms": int(round(self.gap_s * 1000))}
|
||||
|
||||
@classmethod
|
||||
def from_dicts(cls, serial_cfg: dict, exchange_cfg: Optional[dict] = None,
|
||||
port: Optional[str] = None) -> "LineSettings":
|
||||
"""Validate settings that arrive over the network or from a file."""
|
||||
exchange_cfg = exchange_cfg or {}
|
||||
name = str(port or serial_cfg.get("port") or "").strip()
|
||||
if not _PORT_RE.match(name):
|
||||
raise ValueError(f"invalid port name: {name!r}")
|
||||
if name.upper().startswith("COM"):
|
||||
name = name.upper()
|
||||
baudrate = int(serial_cfg.get("baudrate") or 9600)
|
||||
if not 50 <= baudrate <= 921600:
|
||||
raise ValueError(f"invalid baudrate: {baudrate}")
|
||||
bytesize = int(serial_cfg.get("bytesize") or 8)
|
||||
if bytesize not in (5, 6, 7, 8):
|
||||
raise ValueError(f"invalid bytesize: {bytesize}")
|
||||
parity = str(serial_cfg.get("parity") or "N").upper()[:1]
|
||||
if parity not in "NEOMS":
|
||||
raise ValueError(f"invalid parity: {parity}")
|
||||
stopbits = float(serial_cfg.get("stopbits") or 1)
|
||||
if stopbits not in (1, 1.5, 2):
|
||||
raise ValueError(f"invalid stopbits: {stopbits}")
|
||||
try:
|
||||
request = parse_hex(exchange_cfg.get("request_hex") or "")
|
||||
after_ack = parse_hex(exchange_cfg.get("after_ack_hex") or "")
|
||||
except ValueError as e:
|
||||
raise ValueError(f"invalid request hex: {e}") from e
|
||||
if len(request) > MAX_REQUEST_BYTES or len(after_ack) > MAX_REQUEST_BYTES:
|
||||
raise ValueError("request too long")
|
||||
poll_ms = min(max(int(exchange_cfg.get("poll_interval_ms") or 500), 100), 10000)
|
||||
gap_ms = min(max(int(exchange_cfg.get("frame_gap_ms") or 50), 5), 1000)
|
||||
return cls(port=name, baudrate=baudrate, bytesize=bytesize, parity=parity,
|
||||
stopbits=int(stopbits) if stopbits in (1, 2) else stopbits,
|
||||
dtr=bool(serial_cfg.get("dtr", True)), rts=bool(serial_cfg.get("rts", True)),
|
||||
request=request, after_ack=after_ack,
|
||||
poll_s=poll_ms / 1000, gap_s=gap_ms / 1000)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Opening and listing
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
Opener = Callable[[LineSettings], Any]
|
||||
|
||||
|
||||
def open_real(s: LineSettings) -> Any:
|
||||
if serial is None:
|
||||
raise RuntimeError("pyserial is not installed")
|
||||
ser = serial.Serial(port=s.port, baudrate=s.baudrate, bytesize=s.bytesize,
|
||||
parity=s.parity, stopbits=s.stopbits, timeout=0.02, write_timeout=1.0)
|
||||
ser.dtr = s.dtr
|
||||
ser.rts = s.rts
|
||||
ser.reset_input_buffer()
|
||||
return ser
|
||||
|
||||
|
||||
def _port_sort_key(name: str) -> tuple:
|
||||
m = re.match(r"^COM(\d+)$", name, re.IGNORECASE)
|
||||
return (0, int(m.group(1)), "") if m else (1, 0, name)
|
||||
|
||||
|
||||
def list_serial_ports() -> list[dict[str, Any]]:
|
||||
if _list_ports is None:
|
||||
return []
|
||||
out = []
|
||||
for p in _list_ports.comports():
|
||||
chip, note = KNOWN_CHIPS.get(p.vid, (None, "")) if p.vid is not None else (None, "")
|
||||
text = f"{p.description or ''} {p.hwid or ''}".lower()
|
||||
kind = "bluetooth" if ("bluetooth" in text or "bthenum" in text) else (
|
||||
"usb" if p.vid is not None else "native")
|
||||
out.append({
|
||||
"device": p.device,
|
||||
"description": p.description,
|
||||
"hwid": p.hwid,
|
||||
"vid": f"{p.vid:04X}" if p.vid is not None else None,
|
||||
"pid": f"{p.pid:04X}" if p.pid is not None else None,
|
||||
"manufacturer": p.manufacturer,
|
||||
"chip": chip,
|
||||
"note": note,
|
||||
"kind": kind,
|
||||
})
|
||||
return sorted(out, key=lambda p: _port_sort_key(p["device"]))
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# A worker per port
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
class PortWorker(threading.Thread):
|
||||
def __init__(self, settings: LineSettings, opener: Opener):
|
||||
super().__init__(name=f"port-{settings.port}", daemon=True)
|
||||
self.settings = settings
|
||||
self.opener = opener
|
||||
self.chunks: deque[tuple[int, bytes]] = deque(maxlen=RING_SIZE)
|
||||
self.cond = threading.Condition()
|
||||
self.ser: Any = None
|
||||
self.last_error: Optional[str] = None
|
||||
self.last_used = time.monotonic()
|
||||
self.first_attempt = threading.Event()
|
||||
self._halt = threading.Event()
|
||||
# Called with (t_ms, bytes) for every chunk, outside the lock.
|
||||
self.listeners: list[Callable[[int, bytes], None]] = []
|
||||
self.stats = {"opened_at": None, "bytes_rx": 0, "frames_rx": 0, "requests_tx": 0,
|
||||
"open_failures": 0}
|
||||
|
||||
# -- lifecycle ---------------------------------------------------------
|
||||
def touch(self) -> None:
|
||||
self.last_used = time.monotonic()
|
||||
|
||||
def stop(self) -> None:
|
||||
self._halt.set()
|
||||
|
||||
@property
|
||||
def stopped(self) -> bool:
|
||||
return self._halt.is_set()
|
||||
|
||||
def _open(self) -> bool:
|
||||
try:
|
||||
self.ser = self.opener(self.settings)
|
||||
self.last_error = None
|
||||
self.stats["opened_at"] = time.strftime("%Y-%m-%dT%H:%M:%S")
|
||||
log.info("%s opened", self.settings.describe())
|
||||
return True
|
||||
except Exception as e: # noqa: BLE001
|
||||
self.ser = None
|
||||
self.stats["open_failures"] += 1
|
||||
message = f"could not open port {self.settings.port}: {e}"
|
||||
if message != self.last_error:
|
||||
log.warning("%s", message)
|
||||
self.last_error = message
|
||||
return False
|
||||
finally:
|
||||
self.first_attempt.set()
|
||||
with self.cond:
|
||||
self.cond.notify_all()
|
||||
|
||||
def _close(self) -> None:
|
||||
if self.ser is not None:
|
||||
try:
|
||||
self.ser.close()
|
||||
except Exception: # noqa: BLE001
|
||||
pass
|
||||
self.ser = None
|
||||
|
||||
def _push(self, data: bytes, t_ms: int) -> None:
|
||||
with self.cond:
|
||||
self.chunks.append((t_ms, data))
|
||||
self.stats["frames_rx"] += 1
|
||||
self.cond.notify_all()
|
||||
for listener in list(self.listeners):
|
||||
try:
|
||||
listener(t_ms, data)
|
||||
except Exception: # noqa: BLE001
|
||||
log.exception("chunk listener failed")
|
||||
|
||||
def run(self) -> None:
|
||||
s = self.settings
|
||||
buf = bytearray()
|
||||
last_rx = 0.0
|
||||
next_request = 0.0
|
||||
while not self._halt.is_set():
|
||||
if time.monotonic() - self.last_used > IDLE_CLOSE_S:
|
||||
log.info("%s idle for %ds, released", s.port, IDLE_CLOSE_S)
|
||||
break
|
||||
if self.ser is None:
|
||||
if not self._open():
|
||||
self._halt.wait(2.0)
|
||||
continue
|
||||
buf.clear()
|
||||
next_request = 0.0
|
||||
try:
|
||||
now = time.monotonic()
|
||||
if s.request and now >= next_request:
|
||||
self.ser.write(s.request)
|
||||
self.stats["requests_tx"] += 1
|
||||
next_request = now + s.poll_s
|
||||
waiting = self.ser.in_waiting
|
||||
chunk = self.ser.read(waiting if waiting else 1)
|
||||
now = time.monotonic()
|
||||
if chunk:
|
||||
if s.after_ack and b"\x06" in chunk:
|
||||
self.ser.write(s.after_ack)
|
||||
buf += chunk
|
||||
last_rx = now
|
||||
self.stats["bytes_rx"] += len(chunk)
|
||||
if len(buf) >= MAX_CHUNK:
|
||||
self._push(bytes(buf), int(now * 1000))
|
||||
buf.clear()
|
||||
continue
|
||||
if buf and now - last_rx >= s.gap_s:
|
||||
self._push(bytes(buf), int(last_rx * 1000))
|
||||
buf.clear()
|
||||
except Exception as e: # noqa: BLE001
|
||||
self.last_error = f"{s.port}: {e.__class__.__name__}: {e}"
|
||||
log.warning("%s lost: %s", s.port, e)
|
||||
self._close()
|
||||
self._halt.wait(1.0)
|
||||
self._close()
|
||||
self._halt.set()
|
||||
with self.cond:
|
||||
self.cond.notify_all()
|
||||
|
||||
# -- reading -----------------------------------------------------------
|
||||
def wait_fresh(self, max_age_ms: int, wait_ms: int) -> None:
|
||||
"""Return once a chunk younger than max_age_ms exists, or wait_ms passed."""
|
||||
self.first_attempt.wait(timeout=min(wait_ms, 3000) / 1000)
|
||||
deadline = time.monotonic() + wait_ms / 1000
|
||||
with self.cond:
|
||||
while True:
|
||||
if self.chunks and now_ms() - self.chunks[-1][0] <= max_age_ms:
|
||||
return
|
||||
if self.ser is None and self.last_error:
|
||||
return
|
||||
remaining = deadline - time.monotonic()
|
||||
if remaining <= 0 or self._halt.is_set():
|
||||
return
|
||||
self.cond.wait(timeout=remaining)
|
||||
|
||||
def recent(self, count: int) -> list[tuple[int, bytes]]:
|
||||
with self.cond:
|
||||
return list(self.chunks)[-count:] if count > 0 else []
|
||||
|
||||
@property
|
||||
def is_open(self) -> bool:
|
||||
return self.ser is not None
|
||||
|
||||
def snapshot(self, count: int) -> dict[str, Any]:
|
||||
chunks = self.recent(count)
|
||||
is_open = self.is_open
|
||||
return {
|
||||
"ok": is_open or bool(chunks and not self.last_error),
|
||||
"open": is_open,
|
||||
"error": None if is_open else self.last_error,
|
||||
"now": now_ms(),
|
||||
"port": self.settings.port,
|
||||
"frames": [{"t": t, "hex": format_hex(d)} for t, d in chunks],
|
||||
"stats": dict(self.stats),
|
||||
}
|
||||
|
||||
|
||||
class PortBusy(RuntimeError):
|
||||
"""The port is reserved (auto-detection is running on it)."""
|
||||
|
||||
|
||||
def port_key(port: str) -> str:
|
||||
return port.upper() if port.upper().startswith("COM") else port
|
||||
|
||||
|
||||
class Registry:
|
||||
"""At most one worker per port; new settings for a port reopen it."""
|
||||
|
||||
def __init__(self, opener: Opener):
|
||||
self.opener = opener
|
||||
self.lock = threading.Lock()
|
||||
self.workers: dict[str, PortWorker] = {}
|
||||
self.reserved: set[str] = set()
|
||||
|
||||
def reserve(self, ports: list[str]) -> None:
|
||||
"""Close these ports and keep them closed until `unreserve` (for auto-detection)."""
|
||||
with self.lock:
|
||||
self.reserved.update(port_key(p) for p in ports)
|
||||
for p in ports:
|
||||
self.release(p)
|
||||
|
||||
def unreserve(self, ports: list[str]) -> None:
|
||||
with self.lock:
|
||||
self.reserved.difference_update(port_key(p) for p in ports)
|
||||
|
||||
def worker_for(self, settings: LineSettings) -> PortWorker:
|
||||
with self.lock:
|
||||
if port_key(settings.port) in self.reserved:
|
||||
raise PortBusy(f"{settings.port} is busy: auto-detection is running on it")
|
||||
current = self.workers.get(settings.port)
|
||||
if current is not None and (current.stopped or current.settings != settings):
|
||||
if not current.stopped:
|
||||
log.info("%s settings changed, reopening", settings.port)
|
||||
current.stop()
|
||||
current.join(timeout=3)
|
||||
current = None
|
||||
if current is None:
|
||||
current = PortWorker(settings, self.opener)
|
||||
self.workers[settings.port] = current
|
||||
current.start()
|
||||
current.touch()
|
||||
return current
|
||||
|
||||
def release(self, port: str) -> None:
|
||||
"""Close a port so something else (auto-detect) can open it."""
|
||||
with self.lock:
|
||||
worker = self.workers.pop(port_key(port), None)
|
||||
if worker is not None:
|
||||
worker.stop()
|
||||
worker.join(timeout=3)
|
||||
|
||||
def active_ports(self) -> list[str]:
|
||||
with self.lock:
|
||||
return [p for p, w in self.workers.items() if not w.stopped]
|
||||
|
||||
def stop_all(self) -> None:
|
||||
with self.lock:
|
||||
workers = list(self.workers.values())
|
||||
self.workers.clear()
|
||||
for w in workers:
|
||||
w.stop()
|
||||
for w in workers:
|
||||
w.join(timeout=3)
|
||||
@@ -0,0 +1,572 @@
|
||||
# SPDX-License-Identifier: GPL-3.0-or-later
|
||||
# Copyright (C) 2026 Farshad Zamani — Cloudtart (https://cloudtart.com)
|
||||
"""
|
||||
The HTTP side of the bridge.
|
||||
|
||||
For the network (any system that needs the weight) — JSON, and
|
||||
the header `X-Bridge-Token: <access key>` on everything except /health:
|
||||
|
||||
GET /health service, version, host (no key needed)
|
||||
GET /ports COM ports on this PC
|
||||
POST /read raw frames for given line settings
|
||||
(the raw-frames contract of earlier versions)
|
||||
GET /profiles saved scale profiles
|
||||
GET /weight?profile=NAME the current weight, parsed and checked
|
||||
GET /weight?port=COM7&protocol=mt_sics[&baud=9600&framing=8N1]
|
||||
POST /weight {"profile": NAME} or a whole profile
|
||||
|
||||
For the page on this PC only (loopback address, and the header
|
||||
`X-Requested-With: ScaleBridge` so another web page cannot drive it):
|
||||
|
||||
GET / the user interface
|
||||
GET /api/state, /api/protocols, /api/weight, /api/monitor
|
||||
POST /api/detect, /api/detect/cancel, /api/profiles, /api/token,
|
||||
/api/allowed, /api/firewall, /api/autostart
|
||||
GET /api/detect progress and results of auto-detection
|
||||
DELETE /api/profiles/NAME
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import hmac
|
||||
import json
|
||||
import logging
|
||||
import socket
|
||||
import sys
|
||||
import threading
|
||||
import time
|
||||
import uuid
|
||||
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
|
||||
from typing import Any, Optional
|
||||
from urllib.parse import parse_qs, unquote, urlsplit
|
||||
|
||||
from . import ABOUT, PRODUCT, SERVICE_ID, __version__, profiles, winutil
|
||||
from .config import Config
|
||||
from .detect import Detector, Timings
|
||||
from .labels import Keeper, LabelLog, labels_folder, on_print
|
||||
from .protocols import PROTOCOLS, catalogue_info, get_protocol
|
||||
from .serialio import (RING_SIZE, LineSettings, Opener, PortBusy, Registry, format_hex,
|
||||
list_serial_ports, now_ms, open_real, printable)
|
||||
from .simulator import SimulatorBank
|
||||
from .webui import page, remote_page
|
||||
|
||||
log = logging.getLogger("scale_bridge")
|
||||
|
||||
MAX_BODY = 64 * 1024
|
||||
LOCAL_HEADER = ("X-Requested-With", "ScaleBridge")
|
||||
STATUS_CACHE_S = 15
|
||||
|
||||
|
||||
def _framing_ok(text: str) -> bool:
|
||||
return len(text) == 3 and text[0] in "5678" and text[1] in "NEOMS" and text[2] in "12"
|
||||
|
||||
|
||||
class DetectionJob:
|
||||
def __init__(self, bridge: "Bridge", ports: list[str], thorough: bool,
|
||||
print_wait_s: float = 0, listen_only: bool = False):
|
||||
self.id = uuid.uuid4().hex[:12]
|
||||
self.bridge = bridge
|
||||
self.ports = ports
|
||||
self.thorough = thorough
|
||||
self.cancel = threading.Event()
|
||||
self.lock = threading.Lock()
|
||||
self.log: list[dict] = []
|
||||
self.results: list[dict] = []
|
||||
self.running = True
|
||||
self.started = time.time()
|
||||
self.finished: Optional[float] = None
|
||||
self.detector = Detector(bridge.opener, log=self._add, cancelled=self.cancel.is_set,
|
||||
thorough=thorough, timings=bridge.detect_timings,
|
||||
print_wait_s=print_wait_s, listen_only=listen_only)
|
||||
self.print_wait_s = print_wait_s
|
||||
self.listen_only = listen_only
|
||||
self.thread = threading.Thread(target=self._run, name="detect", daemon=True)
|
||||
|
||||
def _add(self, code: str, **details: Any) -> None:
|
||||
with self.lock:
|
||||
self.log.append({"t": round(time.time() - self.started, 2), "code": code, **details})
|
||||
if code in ("found", "not_found", "open_failed"):
|
||||
log.info("detect %s %s", code, details)
|
||||
|
||||
def _run(self) -> None:
|
||||
registry = self.bridge.registry
|
||||
registry.reserve(self.ports)
|
||||
try:
|
||||
for port in self.ports:
|
||||
if self.cancel.is_set():
|
||||
break
|
||||
result = self.detector.run_port(port)
|
||||
with self.lock:
|
||||
self.results.append(result)
|
||||
self.detector.steps_done = 0
|
||||
self._add("done", found=sum(1 for r in self.results if r.get("found")),
|
||||
cancelled=self.cancel.is_set())
|
||||
except Exception as e: # noqa: BLE001
|
||||
log.exception("auto-detection failed")
|
||||
self._add("error", error=str(e))
|
||||
finally:
|
||||
registry.unreserve(self.ports)
|
||||
self.running = False
|
||||
self.finished = time.time()
|
||||
|
||||
def start(self) -> None:
|
||||
self.thread.start()
|
||||
|
||||
def status(self, since: int = 0) -> dict:
|
||||
with self.lock:
|
||||
if self.running:
|
||||
current = min(self.detector.progress, 0.99)
|
||||
progress = min(0.99, (len(self.results) + current) / max(1, len(self.ports)))
|
||||
else:
|
||||
progress = 1.0
|
||||
return {"id": self.id, "running": self.running, "ports": self.ports,
|
||||
"thorough": self.thorough, "print_wait_s": self.print_wait_s,
|
||||
"listen_only": self.listen_only, "progress": round(progress, 3),
|
||||
"log": self.log[since:], "log_size": len(self.log),
|
||||
"results": list(self.results),
|
||||
"elapsed_s": round((self.finished or time.time()) - self.started, 1)}
|
||||
|
||||
|
||||
class Bridge:
|
||||
"""Everything the handlers share."""
|
||||
|
||||
def __init__(self, config: Config, simulate: str = ""):
|
||||
self.config = config
|
||||
self.simulator = SimulatorBank(simulate) if simulate else None
|
||||
self.opener: Opener = self.simulator.opener(open_real) if self.simulator else open_real
|
||||
self.registry = Registry(self.opener)
|
||||
self.job: Optional[DetectionJob] = None
|
||||
self.job_lock = threading.Lock()
|
||||
self._status_cache: dict[str, tuple[float, dict]] = {}
|
||||
self.started = time.time()
|
||||
self.listen_port = config.listen_port
|
||||
self.detect_timings: Optional[Timings] = None
|
||||
# Print-only scales: keep their ports open and log every label.
|
||||
self.labels = LabelLog(labels_folder(config.path))
|
||||
self.keeper = Keeper(self.registry, config.profiles, self.labels)
|
||||
self.keeper.start()
|
||||
|
||||
# -- ports and status --------------------------------------------------
|
||||
def ports(self) -> list[dict]:
|
||||
ports = list_serial_ports()
|
||||
if self.simulator:
|
||||
ports += self.simulator.ports()
|
||||
return ports
|
||||
|
||||
def cached_status(self, key: str, fn, fresh: bool = False) -> dict:
|
||||
now = time.time()
|
||||
hit = self._status_cache.get(key)
|
||||
if hit and not fresh and now - hit[0] < STATUS_CACHE_S:
|
||||
return hit[1]
|
||||
value = fn()
|
||||
self._status_cache[key] = (now, value)
|
||||
return value
|
||||
|
||||
def forget_status(self) -> None:
|
||||
self._status_cache.clear()
|
||||
|
||||
# -- reading -----------------------------------------------------------
|
||||
def read_raw(self, body: dict) -> dict:
|
||||
"""POST /read: the frames as they arrived (raw-frames contract of earlier versions)."""
|
||||
settings = LineSettings.from_dicts(body.get("serial") or {}, body.get("exchange") or {})
|
||||
wait_ms = min(max(int(body.get("wait_ms") or 2500), 0), 10000)
|
||||
max_age_ms = min(max(int(body.get("max_age_ms") or 1500), 50), 60000)
|
||||
count = min(max(int(body.get("frames") or 5), 0), RING_SIZE)
|
||||
worker = self.registry.worker_for(settings)
|
||||
worker.wait_fresh(max_age_ms, wait_ms)
|
||||
worker.touch()
|
||||
return worker.snapshot(count)
|
||||
|
||||
def weight(self, profile: dict, max_age_ms: int = 1500, wait_ms: int = 2500) -> dict:
|
||||
worker = self.registry.worker_for(profiles.line_settings(profile))
|
||||
result = profiles.wait_for_reading(profile, worker, max_age_ms, wait_ms, now_ms)
|
||||
worker.touch()
|
||||
return result
|
||||
|
||||
def label_list(self, query: dict) -> dict:
|
||||
name = str(query.get("profile") or "").strip() or None
|
||||
if name and self.config.profile(name) is None:
|
||||
raise LookupError(f"no profile named {name!r}")
|
||||
if name:
|
||||
name = self.config.profile(name)["name"]
|
||||
after = int(query.get("after") or 0)
|
||||
limit = min(max(int(query.get("limit") or 100), 1), 500)
|
||||
records = self.labels.list(name, after, limit)
|
||||
return {"ok": True, "labels": records, "last_seq": self.labels.seq,
|
||||
"listening": [p["name"] for p in self.config.profiles() if on_print(p)]}
|
||||
|
||||
def resolve_profile(self, query: dict) -> dict:
|
||||
"""A saved profile by name, or one built from the request."""
|
||||
name = str(query.get("profile") or "").strip()
|
||||
if name:
|
||||
profile = self.config.profile(name)
|
||||
if profile is None:
|
||||
raise LookupError(f"no profile named {name!r}")
|
||||
return profile
|
||||
if isinstance(query.get("serial"), dict):
|
||||
return profiles.validate({"name": "request", **query})
|
||||
port = str(query.get("port") or "").strip()
|
||||
protocol = str(query.get("protocol") or "").strip()
|
||||
if not port or not protocol:
|
||||
raise ValueError("give ?profile=NAME, or ?port=COMx&protocol=ID")
|
||||
serial_cfg: dict[str, Any] = {}
|
||||
if query.get("baud"):
|
||||
serial_cfg["baudrate"] = int(query["baud"])
|
||||
framing = str(query.get("framing") or "").upper()
|
||||
if framing:
|
||||
if not _framing_ok(framing):
|
||||
raise ValueError(f"invalid framing: {framing!r} (e.g. 8N1, 7E1)")
|
||||
serial_cfg.update(bytesize=int(framing[0]), parity=framing[1], stopbits=int(framing[2]))
|
||||
exchange = {}
|
||||
if query.get("request_hex") is not None:
|
||||
exchange = {"request_hex": str(query["request_hex"]),
|
||||
"poll_interval_ms": int(query.get("poll_ms") or PROTOCOLS.get(protocol, PROTOCOLS["ascii_generic"]).default_poll_ms)}
|
||||
profile = profiles.ad_hoc(port, protocol, serial_cfg, exchange or None)
|
||||
if query.get("unit"):
|
||||
profile["unit"] = str(query["unit"])
|
||||
return profile
|
||||
|
||||
def monitor(self, query: dict) -> dict:
|
||||
port = str(query.get("port") or "")
|
||||
framing = str(query.get("framing") or "8N1").upper()
|
||||
if not _framing_ok(framing):
|
||||
raise ValueError(f"invalid framing: {framing!r}")
|
||||
serial_cfg = {"port": port, "baudrate": int(query.get("baud") or 9600),
|
||||
"bytesize": int(framing[0]), "parity": framing[1], "stopbits": int(framing[2])}
|
||||
exchange = {"request_hex": str(query.get("request_hex") or ""),
|
||||
"after_ack_hex": str(query.get("after_ack_hex") or ""),
|
||||
"poll_interval_ms": int(query.get("poll_ms") or 500)}
|
||||
settings = LineSettings.from_dicts(serial_cfg, exchange)
|
||||
worker = self.registry.worker_for(settings)
|
||||
worker.wait_fresh(1500, 1500)
|
||||
chunks = worker.recent(24)
|
||||
joined = b"".join(d for _, d in chunks)
|
||||
guesses = []
|
||||
for pid, proto in PROTOCOLS.items():
|
||||
if pid.startswith("custom"):
|
||||
continue
|
||||
found = [r for r in proto.readings(joined) if r.value is not None]
|
||||
if found:
|
||||
last = found[-1]
|
||||
guesses.append({"protocol": pid, "name": proto.name, "count": len(found),
|
||||
"value": last.value, "unit": last.unit, "stable": last.stable,
|
||||
"specificity": proto.specificity})
|
||||
guesses.sort(key=lambda g: (-g["specificity"], -g["count"]))
|
||||
now = now_ms()
|
||||
return {"ok": worker.is_open, "error": None if worker.is_open else worker.last_error,
|
||||
"settings": settings.describe(), "stats": dict(worker.stats),
|
||||
"frames": [{"age_ms": now - t, "hex": format_hex(d), "text": printable(d)}
|
||||
for t, d in chunks[-16:]],
|
||||
"guesses": guesses}
|
||||
|
||||
# -- auto-detection ----------------------------------------------------
|
||||
def start_detection(self, ports: Optional[list[str]], thorough: bool, bluetooth: bool,
|
||||
print_wait_s: float = 0, listen_only: bool = False) -> DetectionJob:
|
||||
with self.job_lock:
|
||||
if self.job and self.job.running:
|
||||
raise PortBusy("auto-detection is already running")
|
||||
available = self.ports()
|
||||
if ports:
|
||||
names = {p["device"].upper(): p["device"] for p in available}
|
||||
chosen = []
|
||||
for p in ports:
|
||||
key = str(p).upper()
|
||||
if key not in names:
|
||||
raise ValueError(f"no such port: {p}")
|
||||
chosen.append(names[key])
|
||||
else:
|
||||
chosen = [p["device"] for p in available if bluetooth or p.get("kind") != "bluetooth"]
|
||||
if not chosen:
|
||||
raise ValueError("no COM ports to search — is the USB-serial adapter plugged in "
|
||||
"and its driver installed?")
|
||||
self.job = DetectionJob(self, chosen, thorough, min(max(float(print_wait_s or 0), 0), 300),
|
||||
listen_only)
|
||||
self.job.start()
|
||||
return self.job
|
||||
|
||||
def state(self, fresh: bool = False) -> dict:
|
||||
port = self.listen_port
|
||||
return {
|
||||
"ok": True,
|
||||
"about": ABOUT,
|
||||
"service": SERVICE_ID,
|
||||
"host": socket.gethostname(),
|
||||
"addresses": winutil.lan_addresses(),
|
||||
"listen_port": port,
|
||||
"token": self.config.token,
|
||||
"config_path": self.config.path,
|
||||
"allowed_clients": self.config.allowed_clients,
|
||||
"simulate": bool(self.simulator),
|
||||
"is_admin": winutil.is_admin(),
|
||||
"is_windows": winutil.is_windows(),
|
||||
"firewall": self.cached_status("firewall", lambda: winutil.firewall_status(port), fresh),
|
||||
"autostart": self.cached_status("autostart", winutil.autostart_status, fresh),
|
||||
"profiles": self.config.profiles(),
|
||||
"active_ports": self.registry.active_ports(),
|
||||
"uptime_s": int(time.time() - self.started),
|
||||
}
|
||||
|
||||
|
||||
class Server(ThreadingHTTPServer):
|
||||
daemon_threads = True
|
||||
# On Windows SO_REUSEADDR lets a second program take the same port;
|
||||
# exclusive use makes a second copy of the bridge fail cleanly instead.
|
||||
allow_reuse_address = sys.platform != "win32"
|
||||
|
||||
def server_bind(self) -> None:
|
||||
if sys.platform == "win32" and hasattr(socket, "SO_EXCLUSIVEADDRUSE"):
|
||||
self.socket.setsockopt(socket.SOL_SOCKET, socket.SO_EXCLUSIVEADDRUSE, 1)
|
||||
super().server_bind()
|
||||
|
||||
|
||||
class Handler(BaseHTTPRequestHandler):
|
||||
server_version = f"{SERVICE_ID}/{__version__}"
|
||||
bridge: Bridge
|
||||
protocol_version = "HTTP/1.1"
|
||||
|
||||
def log_message(self, fmt: str, *args: Any) -> None:
|
||||
log.debug("%s %s", self.client_address[0], fmt % args)
|
||||
|
||||
# -- responses ---------------------------------------------------------
|
||||
def _headers(self, code: int, content_type: str, length: int) -> None:
|
||||
self.send_response(code)
|
||||
self.send_header("Content-Type", content_type)
|
||||
self.send_header("Content-Length", str(length))
|
||||
self.send_header("Cache-Control", "no-store")
|
||||
self.send_header("X-Content-Type-Options", "nosniff")
|
||||
self.send_header("X-Frame-Options", "DENY")
|
||||
self.send_header("Referrer-Policy", "no-referrer")
|
||||
|
||||
def _send(self, code: int, body: dict) -> None:
|
||||
data = json.dumps(body, ensure_ascii=False, default=str).encode("utf-8")
|
||||
self._headers(code, "application/json; charset=utf-8", len(data))
|
||||
self.end_headers()
|
||||
self.wfile.write(data)
|
||||
|
||||
def _send_html(self, html: str, code: int = 200) -> None:
|
||||
data = html.encode("utf-8")
|
||||
self._headers(code, "text/html; charset=utf-8", len(data))
|
||||
self.send_header("Content-Security-Policy",
|
||||
"default-src 'self'; script-src 'self' 'unsafe-inline'; "
|
||||
"style-src 'self' 'unsafe-inline'; img-src 'self' data:; "
|
||||
"connect-src 'self'; frame-ancestors 'none'; base-uri 'none'; form-action 'none'")
|
||||
self.end_headers()
|
||||
self.wfile.write(data)
|
||||
|
||||
def _error(self, code: int, message: str) -> None:
|
||||
self._send(code, {"ok": False, "error": message})
|
||||
|
||||
# -- who is asking -----------------------------------------------------
|
||||
@property
|
||||
def _client(self) -> str:
|
||||
return self.client_address[0]
|
||||
|
||||
def _is_loopback(self) -> bool:
|
||||
ip = self._client
|
||||
return ip.startswith("127.") or ip in ("::1", "::ffff:127.0.0.1")
|
||||
|
||||
def _host_is_local(self) -> bool:
|
||||
host = (self.headers.get("Host") or "").strip().lower()
|
||||
if host.startswith("["):
|
||||
name = host[1:host.find("]")] if "]" in host else host
|
||||
else:
|
||||
name = host.split(":")[0]
|
||||
return name in ("127.0.0.1", "localhost", "::1")
|
||||
|
||||
def _local_page_ok(self) -> bool:
|
||||
return self._is_loopback() and self._host_is_local()
|
||||
|
||||
def _local_api_ok(self) -> bool:
|
||||
if not self._local_page_ok() or self.headers.get(LOCAL_HEADER[0]) != LOCAL_HEADER[1]:
|
||||
self._error(403, "this part of the bridge is only for the page on this PC")
|
||||
return False
|
||||
return True
|
||||
|
||||
def _client_allowed(self) -> bool:
|
||||
allowed = self.bridge.config.allowed_clients
|
||||
if allowed and not self._is_loopback() and self._client not in allowed:
|
||||
self._error(403, f"client {self._client} is not in allowed_clients")
|
||||
return False
|
||||
return True
|
||||
|
||||
def _authorized(self) -> bool:
|
||||
given = (self.headers.get("X-Bridge-Token") or "").encode()
|
||||
expected = self.bridge.config.token.encode()
|
||||
if not expected or not hmac.compare_digest(given, expected):
|
||||
self._error(401, "invalid or missing X-Bridge-Token")
|
||||
return False
|
||||
return True
|
||||
|
||||
def _body(self) -> dict:
|
||||
length = int(self.headers.get("Content-Length") or 0)
|
||||
if length > MAX_BODY:
|
||||
raise ValueError("body too large")
|
||||
raw = self.rfile.read(length) if length else b""
|
||||
body = json.loads(raw or b"{}")
|
||||
if not isinstance(body, dict):
|
||||
raise ValueError("body must be a JSON object")
|
||||
return body
|
||||
|
||||
def _query(self) -> tuple[str, dict]:
|
||||
parts = urlsplit(self.path)
|
||||
query = {k: v[-1] for k, v in parse_qs(parts.query).items()}
|
||||
return parts.path.rstrip("/") or "/", query
|
||||
|
||||
# -- dispatch ----------------------------------------------------------
|
||||
def do_GET(self) -> None: # noqa: N802
|
||||
self._dispatch("GET")
|
||||
|
||||
def do_POST(self) -> None: # noqa: N802
|
||||
self._dispatch("POST")
|
||||
|
||||
def do_DELETE(self) -> None: # noqa: N802
|
||||
self._dispatch("DELETE")
|
||||
|
||||
def _dispatch(self, method: str) -> None:
|
||||
path, query = self._query()
|
||||
try:
|
||||
if path.startswith("/api/"):
|
||||
if self._local_api_ok():
|
||||
self._local_api(method, path, query)
|
||||
return
|
||||
if path == "/" and method == "GET":
|
||||
if self._local_page_ok():
|
||||
self._send_html(page())
|
||||
else:
|
||||
self._send_html(remote_page(self.bridge.listen_port))
|
||||
return
|
||||
if path == "/favicon.ico":
|
||||
self.send_response(204)
|
||||
self.send_header("Content-Length", "0")
|
||||
self.end_headers()
|
||||
return
|
||||
if not self._client_allowed():
|
||||
return
|
||||
self._network_api(method, path, query)
|
||||
except PortBusy as e:
|
||||
self._error(409, str(e))
|
||||
except LookupError as e:
|
||||
self._error(404, str(e))
|
||||
except (ValueError, TypeError, KeyError) as e:
|
||||
self._error(400, str(e))
|
||||
except Exception as e: # noqa: BLE001
|
||||
log.exception("%s %s failed", method, path)
|
||||
self._error(500, f"{e.__class__.__name__}: {e}")
|
||||
|
||||
def _network_api(self, method: str, path: str, query: dict) -> None:
|
||||
b = self.bridge
|
||||
if path == "/health" and method == "GET":
|
||||
self._send(200, {"ok": True, "service": SERVICE_ID, "product": PRODUCT,
|
||||
"version": __version__, "host": socket.gethostname(),
|
||||
"simulate": bool(b.simulator), "author": ABOUT["author"],
|
||||
"website": ABOUT["website"], "repository": ABOUT["repository"],
|
||||
"capabilities": ["read", "ports", "weight", "profiles", "detect"]})
|
||||
return
|
||||
if not self._authorized():
|
||||
return
|
||||
if path == "/ports" and method == "GET":
|
||||
self._send(200, {"ok": True, "ports": b.ports()})
|
||||
elif path == "/read" and method == "POST":
|
||||
self._send(200, b.read_raw(self._body()))
|
||||
elif path == "/profiles" and method == "GET":
|
||||
self._send(200, {"ok": True, "profiles": b.config.profiles()})
|
||||
elif path == "/labels" and method == "GET":
|
||||
self._send(200, b.label_list(query))
|
||||
elif path == "/weight" and method in ("GET", "POST"):
|
||||
body = query if method == "GET" else {**query, **self._body()}
|
||||
profile = b.resolve_profile(body)
|
||||
self._send(200, b.weight(profile, *self._timing(body)))
|
||||
else:
|
||||
self._error(404, "not found")
|
||||
|
||||
@staticmethod
|
||||
def _timing(q: dict) -> tuple[int, int]:
|
||||
max_age = min(max(int(q.get("max_age_ms") or 1500), 50), 60000)
|
||||
wait = min(max(int(q.get("wait_ms") or 2500), 0), 10000)
|
||||
return max_age, wait
|
||||
|
||||
def _local_api(self, method: str, path: str, query: dict) -> None:
|
||||
b = self.bridge
|
||||
if method == "GET":
|
||||
if path == "/api/state":
|
||||
self._send(200, b.state(fresh=query.get("fresh") == "1"))
|
||||
elif path == "/api/ports":
|
||||
self._send(200, {"ok": True, "ports": b.ports()})
|
||||
elif path == "/api/protocols":
|
||||
self._send(200, {"ok": True, "protocols": catalogue_info()})
|
||||
elif path == "/api/weight":
|
||||
profile = b.resolve_profile(query)
|
||||
self._send(200, b.weight(profile, *self._timing(query)))
|
||||
elif path == "/api/labels":
|
||||
self._send(200, b.label_list(query))
|
||||
elif path == "/api/monitor":
|
||||
self._send(200, b.monitor(query))
|
||||
elif path == "/api/detect":
|
||||
job = b.job
|
||||
since = int(query.get("since") or 0)
|
||||
self._send(200, {"ok": True, "job": job.status(since) if job else None})
|
||||
else:
|
||||
self._error(404, "not found")
|
||||
return
|
||||
|
||||
if method == "DELETE":
|
||||
if path.startswith("/api/profiles/"):
|
||||
name = unquote(path[len("/api/profiles/"):])
|
||||
if not b.config.delete_profile(name):
|
||||
raise LookupError(f"no profile named {name!r}")
|
||||
self._send(200, {"ok": True, "profiles": b.config.profiles()})
|
||||
else:
|
||||
self._error(404, "not found")
|
||||
return
|
||||
|
||||
body = self._body()
|
||||
if path == "/api/detect":
|
||||
job = b.start_detection(body.get("ports") or None, bool(body.get("thorough")),
|
||||
bool(body.get("bluetooth")), body.get("print_wait_s") or 0,
|
||||
bool(body.get("listen_only")))
|
||||
self._send(200, {"ok": True, "job": job.status()})
|
||||
elif path == "/api/detect/cancel":
|
||||
if b.job and b.job.running:
|
||||
b.job.cancel.set()
|
||||
self._send(200, {"ok": True})
|
||||
elif path == "/api/profiles":
|
||||
if isinstance(body.get("detection"), dict):
|
||||
profile = profiles.from_detection(body["detection"], str(body.get("name") or ""),
|
||||
str(body.get("label") or ""))
|
||||
if body.get("unit"):
|
||||
profile["unit"] = profiles.norm_unit(body["unit"])
|
||||
else:
|
||||
profile = body
|
||||
saved = b.config.save_profile(profile)
|
||||
b.registry.release(saved["port"])
|
||||
b.keeper.tick()
|
||||
self._send(200, {"ok": True, "profile": saved, "profiles": b.config.profiles()})
|
||||
elif path == "/api/token":
|
||||
self._send(200, {"ok": True, "token": b.config.rotate_token()})
|
||||
elif path == "/api/allowed":
|
||||
clients = body.get("clients") or []
|
||||
if not isinstance(clients, list):
|
||||
raise ValueError("clients must be a list")
|
||||
b.config.set_allowed_clients(clients)
|
||||
self._send(200, {"ok": True, "allowed_clients": b.config.allowed_clients})
|
||||
elif path == "/api/firewall":
|
||||
remote = str(body.get("remote_ip") or "").strip() or None
|
||||
if remote:
|
||||
import ipaddress
|
||||
ipaddress.ip_address(remote)
|
||||
result = (winutil.firewall_close() if body.get("remove")
|
||||
else winutil.firewall_open(b.listen_port, remote))
|
||||
b.forget_status()
|
||||
self._send(200, {**result, "state": b.state(fresh=True)})
|
||||
elif path == "/api/autostart":
|
||||
result = (winutil.autostart_enable(b.config.path) if body.get("enable")
|
||||
else winutil.autostart_disable())
|
||||
b.forget_status()
|
||||
self._send(200, {**result, "state": b.state(fresh=True)})
|
||||
else:
|
||||
self._error(404, "not found")
|
||||
|
||||
|
||||
def make_server(bridge: Bridge, host: str, port: int) -> Server:
|
||||
Handler.bridge = bridge
|
||||
bridge.listen_port = port
|
||||
return Server((host, port), Handler)
|
||||
@@ -0,0 +1,222 @@
|
||||
# SPDX-License-Identifier: GPL-3.0-or-later
|
||||
# Copyright (C) 2026 Farshad Zamani — Cloudtart (https://cloudtart.com)
|
||||
"""
|
||||
Simulated scales — every protocol in the library, on a fake COM port.
|
||||
|
||||
For trying the program without hardware and for the tests. A simulated
|
||||
device only understands the speed and framing it was configured with,
|
||||
exactly like a real one: at another speed a continuous device produces
|
||||
garbage and a polled one stays silent; a 7E1 device read as 8N1 shows its
|
||||
parity bit in the top bit of each byte.
|
||||
|
||||
--simulate mahak_mds COM90, 9600 8N1
|
||||
--simulate toledo_cont:4800:7E1,mt_sics COM90 and COM91
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import time
|
||||
from typing import Optional
|
||||
|
||||
from .serialio import LineSettings, Opener, open_real
|
||||
|
||||
FIRST_PORT = 90
|
||||
|
||||
# The weight walks through an empty scale, 550 g, a ~13 kg package that
|
||||
# settles, and 750 g — (seconds, [kg values], stable).
|
||||
SCHEDULE = [(6, [0.0], True), (8, [0.55], True), (3, [12.85, 13.15, 13.10], False),
|
||||
(8, [13.05], True), (6, [0.75], True)]
|
||||
|
||||
|
||||
def weight_now(t0: float) -> tuple[float, bool]:
|
||||
total = sum(s for s, _, _ in SCHEDULE)
|
||||
t = (time.monotonic() - t0) % total
|
||||
for seconds, values, stable in SCHEDULE:
|
||||
if t < seconds:
|
||||
return values[int(t * 3) % len(values)], stable
|
||||
t -= seconds
|
||||
return 0.0, True
|
||||
|
||||
|
||||
def _even_parity_bit(b: int) -> int:
|
||||
return (bin(b & 0x7F).count("1") & 1) << 7
|
||||
|
||||
|
||||
def frame_for(protocol: str, kg: float, stable: bool) -> bytes:
|
||||
"""What `protocol` sends for `kg` — the same shapes the parsers read."""
|
||||
if protocol == "mt_sics":
|
||||
return f"S {'S' if stable else 'D'} {kg:10.3f} kg\r\n".encode()
|
||||
if protocol == "and_std":
|
||||
return f"{'ST' if stable else 'US'},GS,{kg:+09.3f}kg\r\n".encode()
|
||||
if protocol == "toledo_cont":
|
||||
digits = f"{round(abs(kg) * 1000):06d}".encode()
|
||||
swa = 0x20 | 0x08 | 5 # count-by x1, 0.00X
|
||||
swb = 0x20 | 0x10 | (0 if stable else 0x08) | (0x02 if kg < 0 else 0)
|
||||
swc = 0x20
|
||||
body = bytes([0x02, swa, swb, swc]) + digits + b"000000" + b"\r"
|
||||
return body + bytes([(-sum(b & 0x7F for b in body)) & 0x7F])
|
||||
if protocol == "sma":
|
||||
return b"\n 1G" + (b" " if stable else b"M") + b" " + f"{kg:10.3f}".encode() + b"kg \r"
|
||||
if protocol == "nci":
|
||||
return b"\n" + f"{kg:8.3f}kg".encode() + b"\r\n" + (b"0" if stable else b"1") + b"0\r\x03"
|
||||
if protocol == "ohaus":
|
||||
return f"{kg:10.3f} kg{'' if stable else ' ?'}\r\n".encode()
|
||||
if protocol == "sartorius":
|
||||
return f"+{kg:10.3f} {'kg' if stable else ' '}\r\n".encode()
|
||||
if protocol == "cas_enq":
|
||||
return b"\x01\x02" + (b"S" if stable else b"U") + f" {kg:7.3f}kg".encode() + b"\x03\x04"
|
||||
if protocol == "xk3190_tf0":
|
||||
body = (b"-" if kg < 0 else b"+") + f"{round(abs(kg) * 1000):06d}".encode() + b"3"
|
||||
x = 0
|
||||
for b in body:
|
||||
x ^= b
|
||||
return b"\x02" + body + f"{x >> 4:X}{x & 0xF:X}".encode() + b"\x03"
|
||||
if protocol == "xk3190_reversed":
|
||||
return f"{kg:08.3f}"[::-1].encode() + b"="
|
||||
if protocol == "label_print":
|
||||
# What an indicator wired to a TSC label printer sends on Print (TSPL).
|
||||
w = f"{kg:7.3f}"
|
||||
return ('CLS\r\nSIZE 57 mm, 40 mm\r\nGAP 2 mm,0\r\nDIRECTION 1\r\nREFERENCE 0,0\r\n'
|
||||
'CODEPAGE IranII\r\nTEXT 300,250,"10",270,1,1,"No: 6 SHIFT:2"\r\n'
|
||||
'TEXT 030,235,"10",0,1,2,"Order.Co : 222\r\n'
|
||||
'TEXT 030,080,"10",0,1,2,"1405/07/19 - 16:44"\r\n'
|
||||
'TEXT 030,160,"10",0,1,2,"Thickness : 0.0"\r\n'
|
||||
f'TEXT 020,000,"10",0,2,2,"{w}"\r\nTEXT 200,015,"10",0,2,1,"(Kg)"\r\n'
|
||||
f'BARCODE 350,280, "128",070,1,270,2,2, " 222\t{w}"\r\nPRINT 1\r\n\r\n').encode()
|
||||
if protocol == "mahak_mds":
|
||||
grams = round(kg * 1000)
|
||||
return bytes([0x58, (grams * 7 + 0x51) & 0xFF, 0x07, 0x07]) + grams.to_bytes(3, "big")
|
||||
return f"G {kg:.3f} kg\r\n".encode()
|
||||
|
||||
|
||||
class SimulatedDevice:
|
||||
"""Quacks like a pyserial Serial for what the bridge uses."""
|
||||
|
||||
CONTINUOUS = {"toledo_cont", "xk3190_tf0", "xk3190_reversed", "ascii_generic"}
|
||||
# Sends only when somebody presses Print — here every PRINT_EVERY_S seconds.
|
||||
ON_PRINT = {"label_print"}
|
||||
PRINT_EVERY_S = 3.0
|
||||
REQUESTS = {"mt_sics": b"SI\r\n", "and_std": b"Q\r\n", "sma": b"\nW\r", "nci": b"W\r",
|
||||
"ohaus": b"IP\r\n", "sartorius": b"\x1bP\r\n", "mahak_mds": bytes.fromhex("4D090407"),
|
||||
"cas_enq": b"\x05"}
|
||||
BOOT = bytes.fromhex("42 03 04 01 42 4F 4F 54 0C 04 8C")
|
||||
|
||||
def __init__(self, protocol: str, baudrate: int, framing: str, opened: LineSettings):
|
||||
self.protocol = protocol
|
||||
self.device_baud = baudrate
|
||||
self.device_framing = framing
|
||||
self.opened = opened
|
||||
self.is_open = True
|
||||
self._t0 = time.monotonic()
|
||||
self._out = bytearray()
|
||||
self._due: list[tuple[float, bytes]] = []
|
||||
self._next_emit = time.monotonic() + (self.PRINT_EVERY_S if protocol in self.ON_PRINT else 0)
|
||||
self._next_boot = time.monotonic() + 60
|
||||
self._garbage_seed = 0x5A
|
||||
|
||||
# -- line matching -----------------------------------------------------
|
||||
@property
|
||||
def _baud_ok(self) -> bool:
|
||||
return self.opened.baudrate == self.device_baud
|
||||
|
||||
@property
|
||||
def _framing_ok(self) -> bool:
|
||||
return self.opened.framing == self.device_framing
|
||||
|
||||
def _as_received(self, data: bytes) -> bytes:
|
||||
"""What the host's UART makes of the device's bytes."""
|
||||
if not self._baud_ok:
|
||||
out = bytearray()
|
||||
for _ in range(max(1, len(data) // 3)):
|
||||
self._garbage_seed = (self._garbage_seed * 73 + 41) & 0xFF
|
||||
out.append(self._garbage_seed | 0x80)
|
||||
return bytes(out)
|
||||
if self._framing_ok:
|
||||
return data
|
||||
if self.device_framing.startswith("7") and self.opened.bytesize == 8:
|
||||
return bytes((b & 0x7F) | _even_parity_bit(b) for b in data)
|
||||
if self.device_framing.startswith("8") and self.opened.bytesize == 7:
|
||||
return bytes(b & 0x7F for b in data)
|
||||
return data
|
||||
|
||||
# -- pyserial surface --------------------------------------------------
|
||||
def _pump(self) -> None:
|
||||
now = time.monotonic()
|
||||
if self.protocol in self.CONTINUOUS and now >= self._next_emit:
|
||||
kg, stable = weight_now(self._t0)
|
||||
self._out += self._as_received(frame_for(self.protocol, kg, stable))
|
||||
self._next_emit = now + 0.2
|
||||
if self.protocol in self.ON_PRINT and now >= self._next_emit:
|
||||
kg, _ = weight_now(self._t0)
|
||||
self._out += self._as_received(frame_for(self.protocol, kg, True))
|
||||
self._next_emit = now + self.PRINT_EVERY_S
|
||||
if self.protocol == "mahak_mds" and now >= self._next_boot:
|
||||
self._out += self._as_received(self.BOOT)
|
||||
self._next_boot = now + 60
|
||||
ready = [d for d in self._due if d[0] <= now]
|
||||
self._due = [d for d in self._due if d[0] > now]
|
||||
for _, data in ready:
|
||||
self._out += self._as_received(data)
|
||||
|
||||
def write(self, data: bytes) -> int:
|
||||
if not (self._baud_ok and self._framing_ok):
|
||||
return len(data)
|
||||
data = bytes(data)
|
||||
request = self.REQUESTS.get(self.protocol)
|
||||
kg, stable = weight_now(self._t0)
|
||||
if self.protocol == "cas_enq":
|
||||
if b"\x05" in data:
|
||||
self._due.append((time.monotonic() + 0.03, b"\x06"))
|
||||
if b"\x11" in data:
|
||||
self._due.append((time.monotonic() + 0.04, frame_for("cas_enq", kg, stable)))
|
||||
elif request and request in data:
|
||||
self._due.append((time.monotonic() + 0.04, frame_for(self.protocol, kg, stable)))
|
||||
return len(data)
|
||||
|
||||
@property
|
||||
def in_waiting(self) -> int:
|
||||
self._pump()
|
||||
return len(self._out)
|
||||
|
||||
def read(self, n: int = 1) -> bytes:
|
||||
self._pump()
|
||||
if not self._out:
|
||||
time.sleep(0.02)
|
||||
self._pump()
|
||||
chunk = bytes(self._out[:n])
|
||||
del self._out[:n]
|
||||
return chunk
|
||||
|
||||
def reset_input_buffer(self) -> None:
|
||||
self._out.clear()
|
||||
|
||||
def close(self) -> None:
|
||||
self.is_open = False
|
||||
|
||||
|
||||
class SimulatorBank:
|
||||
"""Fake ports COM90, COM91 …; every other port opens for real."""
|
||||
|
||||
def __init__(self, spec: str):
|
||||
self.devices: dict[str, tuple[str, int, str]] = {}
|
||||
for i, item in enumerate(filter(None, (s.strip() for s in spec.split(",")))):
|
||||
parts = item.split(":")
|
||||
protocol = parts[0]
|
||||
baud = int(parts[1]) if len(parts) > 1 and parts[1] else 9600
|
||||
framing = (parts[2] if len(parts) > 2 and parts[2] else "8N1").upper()
|
||||
self.devices[f"COM{FIRST_PORT + i}"] = (protocol, baud, framing)
|
||||
|
||||
def opener(self, fallback: Optional[Opener] = None) -> Opener:
|
||||
real = fallback or open_real
|
||||
|
||||
def _open(settings: LineSettings):
|
||||
device = self.devices.get(settings.port.upper())
|
||||
if device is None:
|
||||
return real(settings)
|
||||
return SimulatedDevice(device[0], device[1], device[2], settings)
|
||||
return _open
|
||||
|
||||
def ports(self) -> list[dict]:
|
||||
return [{"device": port, "description": f"Simulated scale ({proto}, {baud} {framing})",
|
||||
"hwid": "SIMULATED", "vid": None, "pid": None, "manufacturer": "simulator",
|
||||
"chip": None, "note": "", "kind": "simulated"}
|
||||
for port, (proto, baud, framing) in self.devices.items()]
|
||||
+864
@@ -0,0 +1,864 @@
|
||||
# SPDX-License-Identifier: GPL-3.0-or-later
|
||||
# Copyright (C) 2026 Farshad Zamani — Cloudtart (https://cloudtart.com)
|
||||
# Additional terms under GPLv3 section 7(b): the author attribution shown in
|
||||
# this user interface must be kept (see NOTICE.md).
|
||||
"""The user interface: one self-contained page, English and Persian."""
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
|
||||
from . import ABOUT
|
||||
|
||||
ICON = ("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 64 64'%3E"
|
||||
"%3Crect width='64' height='64' rx='14' fill='%230f766e'/%3E"
|
||||
"%3Crect x='11' y='13' width='42' height='6' rx='2.5' fill='%23fff'/%3E"
|
||||
"%3Crect x='29' y='19' width='6' height='9' fill='%23fff'/%3E"
|
||||
"%3Cpath d='M18 27h28l5 24H13z' fill='%23fff'/%3E"
|
||||
"%3Crect x='23' y='34' width='18' height='8' rx='2' fill='%2308403c'/%3E"
|
||||
"%3Crect x='26' y='37' width='12' height='2' rx='1' fill='%23fff'/%3E%3C/svg%3E")
|
||||
|
||||
_STYLE = r"""
|
||||
:root{--bg:#f4f6f8;--card:#fff;--ink:#16202a;--muted:#5b6b7a;--line:#dde3e9;--brand:#0f766e;
|
||||
--brand-ink:#fff;--soft:#e6f4f2;--ok:#15803d;--warn:#b45309;--bad:#b91c1c;--mono:Consolas,"Cascadia Mono",monospace;
|
||||
--shadow:0 1px 2px rgba(16,24,40,.06),0 1px 3px rgba(16,24,40,.08)}
|
||||
@media (prefers-color-scheme:dark){:root{--bg:#0e1419;--card:#161e25;--ink:#e6edf3;--muted:#93a4b3;
|
||||
--line:#26323d;--brand:#2dd4bf;--brand-ink:#062b27;--soft:#12302d;--ok:#4ade80;--warn:#fbbf24;--bad:#f87171;
|
||||
--shadow:none}}
|
||||
*{box-sizing:border-box}
|
||||
html,body{margin:0;background:var(--bg);color:var(--ink);
|
||||
font:14px/1.55 "Segoe UI",Tahoma,system-ui,-apple-system,sans-serif}
|
||||
a{color:var(--brand)}
|
||||
header{background:var(--card);border-bottom:1px solid var(--line)}
|
||||
.bar{max-width:1080px;margin:0 auto;padding:12px 16px;display:flex;align-items:center;gap:12px;flex-wrap:wrap}
|
||||
.logo{width:36px;height:36px;border-radius:9px}
|
||||
.title{font-weight:700;font-size:17px}
|
||||
.sub{color:var(--muted);font-size:12.5px}
|
||||
.spacer{flex:1}
|
||||
.pill{display:inline-flex;align-items:center;gap:6px;border:1px solid var(--line);border-radius:999px;
|
||||
padding:2px 10px;font-size:12px;color:var(--muted);background:var(--card);white-space:nowrap}
|
||||
.pill.brand{border-color:var(--brand);color:var(--brand)}
|
||||
nav{max-width:1080px;margin:0 auto;padding:0 16px;display:flex;gap:4px;overflow-x:auto}
|
||||
nav button{border:0;background:none;color:var(--muted);padding:10px 12px;font:inherit;cursor:pointer;
|
||||
border-bottom:2px solid transparent;white-space:nowrap}
|
||||
nav button.on{color:var(--brand);border-bottom-color:var(--brand);font-weight:600}
|
||||
main{max-width:1080px;margin:0 auto;padding:18px 16px 32px}
|
||||
.card{background:var(--card);border:1px solid var(--line);border-radius:12px;padding:16px;margin-bottom:14px;
|
||||
box-shadow:var(--shadow)}
|
||||
h2{font-size:16px;margin:0 0 4px}
|
||||
h3{font-size:14px;margin:14px 0 6px}
|
||||
p{margin:6px 0}
|
||||
.muted{color:var(--muted)}
|
||||
.small{font-size:12.5px}
|
||||
.grid{display:grid;gap:14px;grid-template-columns:repeat(auto-fill,minmax(300px,1fr))}
|
||||
.row{display:flex;gap:8px;align-items:center;flex-wrap:wrap}
|
||||
.btn{border:1px solid var(--line);background:var(--card);color:var(--ink);border-radius:8px;padding:7px 14px;
|
||||
font:inherit;cursor:pointer}
|
||||
.btn:hover{border-color:var(--brand)}
|
||||
.btn.primary{background:var(--brand);border-color:var(--brand);color:var(--brand-ink);font-weight:600}
|
||||
.btn.danger{color:var(--bad)}
|
||||
.btn:disabled{opacity:.55;cursor:default}
|
||||
input,select{font:inherit;color:var(--ink);background:var(--card);border:1px solid var(--line);border-radius:8px;
|
||||
padding:6px 9px;min-width:0}
|
||||
input:focus,select:focus{outline:2px solid var(--soft);border-color:var(--brand)}
|
||||
label.f{display:flex;flex-direction:column;gap:3px;font-size:12.5px;color:var(--muted)}
|
||||
.mono,.ltr{direction:ltr;unicode-bidi:isolate}
|
||||
.mono{font-family:var(--mono);font-size:12.5px}
|
||||
.weight{font:600 44px/1.1 var(--mono);direction:ltr;text-align:center;margin:8px 0 2px;letter-spacing:.5px}
|
||||
.weight small{font-size:18px;color:var(--muted);margin-inline-start:6px}
|
||||
.state{display:flex;justify-content:center;gap:8px;align-items:center;font-size:12.5px;color:var(--muted)}
|
||||
.dot{width:10px;height:10px;border-radius:50%;background:var(--line);display:inline-block}
|
||||
.dot.ok{background:var(--ok)}.dot.warn{background:var(--warn)}.dot.bad{background:var(--bad)}
|
||||
.kv{display:grid;grid-template-columns:max-content 1fr;gap:4px 12px;font-size:13px}
|
||||
.kv b{font-weight:600;color:var(--muted)}
|
||||
.progress{height:8px;background:var(--line);border-radius:99px;overflow:hidden}
|
||||
.progress>div{height:100%;background:var(--brand);width:0;transition:width .3s}
|
||||
.log{background:var(--bg);border:1px solid var(--line);border-radius:8px;padding:8px 10px;max-height:240px;
|
||||
overflow:auto;font-size:12.5px}
|
||||
.log div{padding:1px 0;border-bottom:1px dashed var(--line)}
|
||||
.log .found{color:var(--ok);font-weight:600}.log .bad{color:var(--bad)}
|
||||
table{width:100%;border-collapse:collapse;font-size:13px}
|
||||
th,td{text-align:start;padding:6px 8px;border-bottom:1px solid var(--line);vertical-align:top}
|
||||
th{color:var(--muted);font-weight:600;font-size:12px}
|
||||
.tag{display:inline-block;padding:0 8px;border-radius:99px;font-size:11.5px;background:var(--soft);color:var(--brand)}
|
||||
.tag.warn{background:rgba(180,83,9,.12);color:var(--warn)}
|
||||
.note{border-inline-start:3px solid var(--brand);background:var(--soft);padding:8px 12px;border-radius:6px;margin:8px 0}
|
||||
.note.warn{border-color:var(--warn);background:rgba(180,83,9,.08)}
|
||||
.steps{margin:0;padding-inline-start:20px}.steps li{margin:6px 0}
|
||||
.empty{text-align:center;padding:28px 12px;color:var(--muted)}
|
||||
.hidden{display:none!important}
|
||||
.check{display:flex;gap:8px;align-items:flex-start;padding:6px 0;border-bottom:1px solid var(--line)}
|
||||
.check:last-child{border-bottom:0}
|
||||
.wrap{overflow-wrap:anywhere}
|
||||
footer{border-top:1px solid var(--line);background:var(--card)}
|
||||
footer .bar{font-size:12.5px;color:var(--muted);justify-content:center;text-align:center}
|
||||
footer a{text-decoration:none}
|
||||
h3 .num{display:inline-grid;place-items:center;width:22px;height:22px;border-radius:50%;background:var(--soft);
|
||||
color:var(--brand);font-size:12px;margin-inline-end:8px;vertical-align:1px}
|
||||
html[dir=rtl] .kv>.mono,html[dir=rtl] .kv>.ltr{text-align:right}
|
||||
.toast{position:fixed;inset-inline:0;bottom:18px;display:flex;justify-content:center;pointer-events:none}
|
||||
.toast div{background:var(--ink);color:var(--bg);padding:8px 16px;border-radius:8px;opacity:0;transition:opacity .2s}
|
||||
.toast div.show{opacity:.95}
|
||||
"""
|
||||
|
||||
_BODY = r"""
|
||||
<header>
|
||||
<div class="bar">
|
||||
<img class="logo" src="__ICON__" alt="">
|
||||
<div>
|
||||
<div class="title">SyncPulse Scale Bridge <span class="sub ltr" id="ver"></span></div>
|
||||
<div class="sub" data-t="tagline"></div>
|
||||
</div>
|
||||
<div class="spacer"></div>
|
||||
<span class="pill hidden" id="simPill" data-t="simulation"></span>
|
||||
<button class="btn" id="langBtn" type="button"></button>
|
||||
</div>
|
||||
<nav id="tabs">
|
||||
<button data-tab="scales" data-t="tab_scales"></button>
|
||||
<button data-tab="find" data-t="tab_find"></button>
|
||||
<button data-tab="connect" data-t="tab_connect"></button>
|
||||
<button data-tab="manual" data-t="tab_manual"></button>
|
||||
<button data-tab="protocols" data-t="tab_protocols"></button>
|
||||
<button data-tab="about" data-t="tab_about"></button>
|
||||
</nav>
|
||||
</header>
|
||||
<main>
|
||||
<section id="p-scales"></section>
|
||||
<section id="p-find" class="hidden"></section>
|
||||
<section id="p-connect" class="hidden"></section>
|
||||
<section id="p-manual" class="hidden"></section>
|
||||
<section id="p-protocols" class="hidden"></section>
|
||||
<section id="p-about" class="hidden"></section>
|
||||
</main>
|
||||
<footer><div class="bar" id="sign"></div></footer>
|
||||
<div class="toast"><div id="toast"></div></div>
|
||||
"""
|
||||
|
||||
_SCRIPT = r"""
|
||||
const ABOUT = __ABOUT__;
|
||||
const T = {
|
||||
en:{
|
||||
tagline:'Finds the scale on any COM port, shows the live weight and serves it to your network.',
|
||||
simulation:'Simulation', lang:'فارسی',
|
||||
tab_scales:'Scales', tab_find:'Find my scale', tab_connect:'Network access', tab_manual:'Manual & monitor',
|
||||
tab_protocols:'Protocols', tab_about:'About',
|
||||
no_scales:'No scale saved yet.', no_scales_hint:'Plug the scale into this PC and let the program find it.',
|
||||
find_now:'Find my scale', stable:'stable', moving:'moving', no_data:'no data', stale:'old reading',
|
||||
overload:'overload', delete:'Delete', confirm_delete:'Delete the profile "{name}"?',
|
||||
net:'net', gross:'gross', age:'{ms} ms ago', copied:'Copied', copy:'Copy', address_for:'Address for other systems',
|
||||
find_title:'Find the scale automatically',
|
||||
find_intro:'The program listens to each port at every common speed, then asks the scale in the languages of the major manufacturers. Only read-only requests are sent: it never zeroes, tares or prints.',
|
||||
ports:'COM ports', no_ports:'No COM port on this PC. Plug in the USB-serial adapter and check its driver in Device Manager.',
|
||||
refresh:'Refresh', thorough:'Thorough search (more speeds and framings, slower)',
|
||||
wait_print:'The scale sends only when Print is pressed (e.g. wired to a label printer) — wait for me to press it',
|
||||
listen_only:'Listen only — never send anything to the scale',
|
||||
log_press_print:'{port}: ▶ press PRINT on the scale now — listening at {baud} for {seconds} s',
|
||||
log_print_wrong_speed:'{port}: data at {baud} was not readable — press PRINT again (trying the next speed)',
|
||||
log_print_timeout:'{port}: nothing arrived while waiting for Print',
|
||||
mode_print:'sends when Print is pressed', printed:'printed {ago}', last_labels:'Last printed labels',
|
||||
listening_all_day:'Listening all the time: every printed label is recorded.',
|
||||
ago_s:'{n} s ago', ago_m:'{n} min ago', ago_h:'{n} h ago', no_labels:'No label printed yet.',
|
||||
start:'Start search', cancel:'Cancel', running:'Searching…', results:'Results',
|
||||
found_on:'Scale found on {port}', not_found_on:'No scale recognised on {port}', confidence:'confidence',
|
||||
protocol:'Protocol', line:'Line', mode:'Mode', reading:'Reading', sample:'What arrived',
|
||||
mode_continuous:'sends by itself', mode_poll:'answers a request', save_as:'Save as', label:'Description',
|
||||
save:'Save', saved:'Saved', field_tested:'tested on real hardware',
|
||||
heard_unknown:'Readable data arrived at {baud} {framing} but the format is not in the library yet:',
|
||||
tips_title:'If nothing is found',
|
||||
tip1:'Serial output must be switched on in the indicator\'s menu (often called COM, rS, SEr, Serial, Continuous or On request).',
|
||||
tip2:'Check the cable: many indicators need a null-modem (crossed) cable, some a straight one. Pins 2, 3 and 5 are enough.',
|
||||
tip3:'Put something on the scale or press its Print key while searching — some indicators only send then.',
|
||||
tip4:'Try the thorough search, or use “Manual & monitor” to watch the raw bytes.',
|
||||
ch340:'Driver warning', bt:'Bluetooth — skipped unless ticked',
|
||||
log_port_start:'Searching {port}…', log_listen:'{port}: listening at {baud} {framing}',
|
||||
log_heard:'{port}: {bytes} bytes at {baud} ({readable}% readable)',
|
||||
log_seven_bit:'{port}: looks like 7 data bits with parity — listening again as 7E1/7O1',
|
||||
log_ask:'{port}: asking {protocol} at {baud} {framing}', log_reply:'{port}: reply to {protocol}: {text}',
|
||||
log_found:'✔ {port}: {protocol} at {baud} {framing} — {value} {unit}', log_not_found:'{port}: nothing recognised',
|
||||
log_open_failed:'{port}: cannot open — {error}', log_done:'Finished: {found} scale(s) found',
|
||||
log_error:'Error: {error}',
|
||||
conn_title:'Make the scales on this PC available on the network', conn_intro:'Other systems — your server, an ERP, a script — read the scales on this PC over the network. Four things make that work:',
|
||||
step_address:'The address of this PC', step_key:'The access key', step_firewall:'An open port in Windows Firewall',
|
||||
step_autostart:'Start with Windows (optional, recommended)',
|
||||
port_label:'Port', addresses:'Addresses', key_hint:'Only systems that have this key can read the scales. Keep it private.',
|
||||
show:'Show', hide:'Hide', new_key:'New key', confirm_key:'Make a new key? Systems using the old key will stop working until you enter the new one.',
|
||||
fw_what:'Windows Firewall blocks incoming connections by default, so other machines cannot reach port {port} on this PC until a rule allows it. The button below asks Windows for administrator permission (a UAC prompt) and adds the inbound rule “SyncPulse Scale Bridge” for TCP port {port} on all network types. It also removes any block rule Windows added for this program if its “Allow access?” question was cancelled.',
|
||||
fw_open:'Open port {port} in the firewall', fw_remove:'Remove the rule', fw_is_open:'Port {port} is open in Windows Firewall.',
|
||||
fw_is_closed:'Port {port} is not open yet.', fw_only_from:'Allow only from (server IP, optional)',
|
||||
fw_manual:'To do it by hand, run in an administrator Command Prompt:',
|
||||
fw_not_windows:'Not on Windows — open TCP port {port} in this system\'s firewall.',
|
||||
as_what:'Runs the bridge in the background when the PC starts, before anyone logs in, and restarts it if it stops. Needs administrator permission once.',
|
||||
as_on:'Starts with Windows.', as_off:'Does not start with Windows.', as_other:'A task exists but points to another copy of the program.',
|
||||
as_enable:'Start with Windows', as_disable:'Stop starting with Windows',
|
||||
as_note:'After enabling it, close this window and restart the PC (or keep this window open until then). Opening the program again later shows this page for the background copy.',
|
||||
in_syncpulse:'Then, in the system that needs the weight', in_syncpulse_steps:'Send this request with the key above. The answer is JSON — value, unit, stable, age_ms … (documentation on GitHub):',
|
||||
allowed_title:'Allowed clients', allowed_hint:'Leave empty to accept any machine that has the key, or list the IP addresses of the machines that may read the scales (comma separated).',
|
||||
config_file:'Settings file', cancelled_uac:'Cancelled at the Windows prompt.', failed:'Failed: {error}', done:'Done',
|
||||
manual_title:'Manual settings and raw monitor', manual_intro:'Watch exactly what arrives on a port with the settings you choose. Useful for an unknown indicator, a cable test, or to check a setting.',
|
||||
baud:'Speed (baud)', framing:'Framing', request:'Request to send (hex, empty = only listen)', poll:'Every (ms)',
|
||||
preset:'Fill the request from a protocol', monitor_start:'Start monitor', monitor_stop:'Stop',
|
||||
frames:'Frames', guesses:'Protocols that can read this', none_yet:'Nothing received yet.', open_error:'Port error: {error}',
|
||||
save_manual:'Save these settings as a profile', unit_if_missing:'Unit when the scale sends none', output_unit:'Convert to',
|
||||
as_sent:'as sent', stable_samples:'Equal readings = stable',
|
||||
proto_title:'Protocol library', proto_intro:'Formats the program can read. Tested on real hardware are marked; the others follow the manufacturers\' published formats and are covered by tests with their sample frames. The same data format is used by many other brands.',
|
||||
families:'Used by', request_col:'Request', kind:'Type', reference:'Reference',
|
||||
kind_continuous:'continuous', kind_poll:'on request', kind_handshake:'handshake', kind_print:'on Print key',
|
||||
about_title:'About', about_text:'SyncPulse Scale Bridge connects weighing scales with an RS-232 serial port to computers and networks. Copy the single program file to the PC beside the scale, run it, and it finds the port, the speed and the protocol by itself, shows the live weight and serves it on the local network.',
|
||||
about_platform:'Free software that works with any system through its simple HTTP/JSON interface. Originally developed for the SyncPulse platform.',
|
||||
author:'Author', company:'Company', website:'Website', license:'License', source:'Source code', version:'Version',
|
||||
license_text:'Free software under the GNU General Public License v3 or later, with an additional term (section 7(b)): the author attribution shown in the program must be kept in copies and modified versions.',
|
||||
made_by:'Made by', err_name:'Choose a name: letters, digits, - or _.', already_saved:'saved as {names}'
|
||||
},
|
||||
fa:{
|
||||
tagline:'باسکول را روی هر درگاه COM پیدا میکند، وزن زنده را نشان میدهد و آن را روی شبکه در اختیار میگذارد.',
|
||||
simulation:'شبیهساز', lang:'English',
|
||||
tab_scales:'باسکولها', tab_find:'پیدا کردن باسکول', tab_connect:'دسترسی از شبکه', tab_manual:'تنظیم دستی و مانیتور',
|
||||
tab_protocols:'پروتکلها', tab_about:'درباره',
|
||||
no_scales:'هنوز باسکولی ذخیره نشده است.', no_scales_hint:'باسکول را به این رایانه وصل کنید تا برنامه آن را پیدا کند.',
|
||||
find_now:'پیدا کردن باسکول', stable:'پایدار', moving:'در حال تغییر', no_data:'بدون داده', stale:'خوانش قدیمی',
|
||||
overload:'بیش از ظرفیت', delete:'حذف', confirm_delete:'پروفایل «{name}» حذف شود؟',
|
||||
net:'خالص', gross:'ناخالص', age:'{ms} میلیثانیه پیش', copied:'کپی شد', copy:'کپی', address_for:'نشانی برای سامانههای دیگر',
|
||||
find_title:'پیدا کردن خودکار باسکول',
|
||||
find_intro:'برنامه روی هر درگاه با همهی سرعتهای رایج گوش میدهد و سپس با زبان سازندههای اصلی از باسکول وزن میخواهد. فقط درخواستهای خواندنی فرستاده میشود: هیچوقت صفر، تار یا چاپ نمیکند.',
|
||||
ports:'درگاههای COM', no_ports:'درگاه COM روی این رایانه نیست. مبدل USB به سریال را وصل کنید و درایور آن را در Device Manager بررسی کنید.',
|
||||
refresh:'بازخوانی', thorough:'جستجوی کامل (سرعتها و قالبهای بیشتر، کندتر)',
|
||||
wait_print:'باسکول فقط با زدن کلید چاپ داده میفرستد (مثلاً وصل به لیبلزن) — منتظر بمان تا چاپ بزنم',
|
||||
listen_only:'فقط گوش بده — هیچ چیزی به باسکول فرستاده نشود',
|
||||
log_press_print:'{port}: ▶ همین حالا کلید چاپ باسکول را بزنید — گوش دادن با {baud} تا {seconds} ثانیه',
|
||||
log_print_wrong_speed:'{port}: داده با سرعت {baud} خوانا نبود — دوباره چاپ بزنید (سرعت بعدی)',
|
||||
log_print_timeout:'{port}: در زمان انتظار برای چاپ چیزی نرسید',
|
||||
mode_print:'با زدن کلید چاپ میفرستد', printed:'چاپشده {ago}', last_labels:'آخرین برچسبهای چاپشده',
|
||||
listening_all_day:'همیشه در حال گوش دادن: هر برچسبی که چاپ شود ثبت میشود.',
|
||||
ago_s:'{n} ثانیه پیش', ago_m:'{n} دقیقه پیش', ago_h:'{n} ساعت پیش', no_labels:'هنوز برچسبی چاپ نشده است.',
|
||||
start:'شروع جستجو', cancel:'لغو', running:'در حال جستجو…', results:'نتیجه',
|
||||
found_on:'باسکول روی {port} پیدا شد', not_found_on:'روی {port} باسکولی شناخته نشد', confidence:'اطمینان',
|
||||
protocol:'پروتکل', line:'تنظیم خط', mode:'روش', reading:'خوانش', sample:'دادهی دریافتی',
|
||||
mode_continuous:'خودش پیوسته میفرستد', mode_poll:'به درخواست پاسخ میدهد', save_as:'ذخیره با نام', label:'توضیح',
|
||||
save:'ذخیره', saved:'ذخیره شد', field_tested:'روی دستگاه واقعی آزموده شده',
|
||||
heard_unknown:'با {baud} {framing} دادهی خوانا رسید اما این قالب هنوز در کتابخانه نیست:',
|
||||
tips_title:'اگر چیزی پیدا نشد',
|
||||
tip1:'خروجی سریال باید در منوی نمایشگر روشن باشد (معمولاً با نام COM، rS، SEr، Serial، Continuous یا On request).',
|
||||
tip2:'کابل را بررسی کنید: بسیاری از نمایشگرها کابل نالمودم (ضربدری) و برخی کابل مستقیم میخواهند. پایههای ۲، ۳ و ۵ کافی است.',
|
||||
tip3:'هنگام جستجو چیزی روی باسکول بگذارید یا کلید چاپ را بزنید؛ برخی نمایشگرها فقط در آن لحظه میفرستند.',
|
||||
tip4:'جستجوی کامل را امتحان کنید یا از «تنظیم دستی و مانیتور» بایتهای خام را ببینید.',
|
||||
ch340:'هشدار درایور', bt:'بلوتوث — مگر تیک بخورد، بررسی نمیشود',
|
||||
log_port_start:'جستجو در {port}…', log_listen:'{port}: گوش دادن با {baud} {framing}',
|
||||
log_heard:'{port}: {bytes} بایت با سرعت {baud} ({readable}٪ خوانا)',
|
||||
log_seven_bit:'{port}: بهنظر ۷ بیت داده با پریتی است — دوباره با 7E1/7O1 گوش میدهد',
|
||||
log_ask:'{port}: پرسش {protocol} با {baud} {framing}', log_reply:'{port}: پاسخ به {protocol}: {text}',
|
||||
log_found:'✔ {port}: {protocol} با {baud} {framing} — {value} {unit}', log_not_found:'{port}: چیزی شناخته نشد',
|
||||
log_open_failed:'{port}: باز نمیشود — {error}', log_done:'پایان: {found} باسکول پیدا شد',
|
||||
log_error:'خطا: {error}',
|
||||
conn_title:'در دسترس گذاشتن باسکولهای این رایانه روی شبکه', conn_intro:'سامانههای دیگر — سرور شما، ERP، یک اسکریپت — از راه شبکه باسکولهای این رایانه را میخوانند. برای این کار چهار چیز لازم است:',
|
||||
step_address:'نشانی این رایانه', step_key:'کلید دسترسی', step_firewall:'باز بودن درگاه در فایروال ویندوز',
|
||||
step_autostart:'اجرا همراه ویندوز (اختیاری، پیشنهادی)',
|
||||
port_label:'درگاه', addresses:'نشانیها', key_hint:'فقط سامانههایی که این کلید را دارند میتوانند باسکولها را بخوانند. آن را محرمانه نگه دارید.',
|
||||
show:'نمایش', hide:'پنهان', new_key:'کلید تازه', confirm_key:'کلید تازه ساخته شود؟ سامانههایی که کلید قبلی را دارند تا کلید تازه را وارد نکنید کار نمیکنند.',
|
||||
fw_what:'فایروال ویندوز بهطور پیشفرض اتصالهای ورودی را میبندد؛ بنابراین تا وقتی قانونی اجازه ندهد، رایانههای دیگر به درگاه {port} این رایانه نمیرسند. دکمهی زیر از ویندوز اجازهی مدیر (پنجرهی UAC) میگیرد و قانون ورودی «SyncPulse Scale Bridge» را برای TCP درگاه {port} روی همهی انواع شبکه میسازد. اگر پرسش «Allow access؟» ویندوز لغو شده باشد، قانون مسدودکنندهای را هم که ویندوز برای این برنامه ساخته پاک میکند.',
|
||||
fw_open:'باز کردن درگاه {port} در فایروال', fw_remove:'حذف قانون', fw_is_open:'درگاه {port} در فایروال ویندوز باز است.',
|
||||
fw_is_closed:'درگاه {port} هنوز باز نیست.', fw_only_from:'فقط از این نشانی (IP سرور، اختیاری)',
|
||||
fw_manual:'برای انجام دستی، در Command Prompt با دسترسی مدیر اجرا کنید:',
|
||||
fw_not_windows:'این سیستم ویندوز نیست — درگاه TCP {port} را در فایروال همین سیستم باز کنید.',
|
||||
as_what:'پل را هنگام روشن شدن رایانه، پیش از ورود هر کاربر، در پسزمینه اجرا میکند و اگر بسته شود دوباره راه میاندازد. یکبار اجازهی مدیر لازم دارد.',
|
||||
as_on:'همراه ویندوز اجرا میشود.', as_off:'همراه ویندوز اجرا نمیشود.', as_other:'وظیفهای هست ولی به نسخهی دیگری از برنامه اشاره میکند.',
|
||||
as_enable:'اجرا همراه ویندوز', as_disable:'لغو اجرا همراه ویندوز',
|
||||
as_note:'پس از فعال کردن، این پنجره را ببندید و رایانه را دوباره راهاندازی کنید (یا تا آن زمان این پنجره را باز نگه دارید). اگر بعداً برنامه را باز کنید، همین صفحه برای نسخهی پسزمینه باز میشود.',
|
||||
in_syncpulse:'سپس در سامانهای که وزن را لازم دارد', in_syncpulse_steps:'این درخواست را با کلید بالا بفرستید. پاسخ JSON است — value، unit، stable، age_ms … (مستندات در گیتهاب):',
|
||||
allowed_title:'سامانههای مجاز', allowed_hint:'خالی بگذارید تا هر دستگاهی که کلید را دارد پذیرفته شود، یا IP رایانههایی را که اجازهی خواندن دارند با ویرگول جدا بنویسید.',
|
||||
config_file:'فایل تنظیمات', cancelled_uac:'در پنجرهی ویندوز لغو شد.', failed:'ناموفق: {error}', done:'انجام شد',
|
||||
manual_title:'تنظیم دستی و مانیتور خام', manual_intro:'دقیقاً ببینید با تنظیمی که انتخاب میکنید چه چیزی روی درگاه میرسد. برای نمایشگر ناشناخته، آزمایش کابل یا بررسی یک تنظیم.',
|
||||
baud:'سرعت (baud)', framing:'قالب', request:'درخواست ارسالی (hex؛ خالی = فقط گوش دادن)', poll:'هر (میلیثانیه)',
|
||||
preset:'پر کردن درخواست از روی پروتکل', monitor_start:'شروع مانیتور', monitor_stop:'توقف',
|
||||
frames:'فریمها', guesses:'پروتکلهایی که این داده را میخوانند', none_yet:'هنوز چیزی نرسیده است.', open_error:'خطای درگاه: {error}',
|
||||
save_manual:'ذخیرهی این تنظیم بهعنوان پروفایل', unit_if_missing:'واحد، وقتی باسکول واحد نمیفرستد', output_unit:'تبدیل به',
|
||||
as_sent:'همانطور که میرسد', stable_samples:'تعداد خوانش برابر = پایدار',
|
||||
proto_title:'کتابخانهی پروتکلها', proto_intro:'قالبهایی که برنامه میخواند. موارد آزموده روی دستگاه واقعی علامت دارند؛ بقیه بر پایهی قالبهای منتشرشدهی سازندگاناند و با فریمهای نمونهی همان مستندات آزمایش شدهاند. بسیاری از برندهای دیگر هم از همین قالبها استفاده میکنند.',
|
||||
families:'کاربرد', request_col:'درخواست', kind:'نوع', reference:'مرجع',
|
||||
kind_continuous:'پیوسته', kind_poll:'با درخواست', kind_handshake:'دستدادن', kind_print:'با کلید چاپ',
|
||||
about_title:'درباره', about_text:'SyncPulse Scale Bridge باسکولهای دارای درگاه سریال RS-232 را به رایانه و شبکه وصل میکند. تنها فایل برنامه را روی رایانهی کنار باسکول کپی و اجرا کنید؛ درگاه، سرعت و پروتکل را خودش پیدا میکند، وزن زنده را نشان میدهد و روی شبکهی محلی در اختیار میگذارد.',
|
||||
about_platform:'نرمافزار آزاد است و با رابط سادهی HTTP/JSON با هر سامانهای کار میکند. در اصل برای پلتفرم SyncPulse توسعه داده شد.',
|
||||
author:'سازنده', company:'شرکت', website:'وبسایت', license:'مجوز', source:'کد منبع', version:'نسخه',
|
||||
license_text:'نرمافزار آزاد با مجوز GNU GPL نسخهی ۳ یا بالاتر، با یک شرط افزوده (بند ۷(ب)): نام و مشخصات سازنده که در برنامه نمایش داده میشود باید در همهی نسخهها و نسخههای تغییر یافته حفظ شود.',
|
||||
made_by:'ساختهی', err_name:'یک نام انتخاب کنید: حروف انگلیسی، عدد، - یا _.', already_saved:'ذخیرهشده با نام {names}'
|
||||
}};
|
||||
|
||||
const S = {lang:'en', tab:'scales', state:null, ports:[], protocols:[], job:null, jobSince:0, log:[],
|
||||
weights:{}, inflight:{}, showKey:false, monitor:null, monitorData:null, busy:false, sel:null, draft:{}, shownResults:-1, shownLog:0, shownRunning:false};
|
||||
try { S.lang = localStorage.getItem('sb.lang') || ((navigator.language||'').toLowerCase().startsWith('fa') ? 'fa' : 'en'); } catch (e) {}
|
||||
|
||||
const $ = (sel, el = document) => el.querySelector(sel);
|
||||
const esc = v => String(v ?? '').replace(/[&<>"']/g, c => ({'&':'&','<':'<','>':'>','"':'"',"'":'''}[c]));
|
||||
function t(key, vars) {
|
||||
let s = (T[S.lang] && T[S.lang][key]) ?? T.en[key] ?? key;
|
||||
if (vars) s = s.replace(/\{(\w+)\}/g, (m, k) => vars[k] ?? '');
|
||||
return s;
|
||||
}
|
||||
function toast(msg) {
|
||||
const el = $('#toast'); el.textContent = msg; el.classList.add('show');
|
||||
clearTimeout(toast.h); toast.h = setTimeout(() => el.classList.remove('show'), 1800);
|
||||
}
|
||||
async function api(path, opts = {}) {
|
||||
const headers = {'X-Requested-With': 'ScaleBridge'};
|
||||
if (opts.body !== undefined) headers['Content-Type'] = 'application/json';
|
||||
let data;
|
||||
try {
|
||||
const res = await fetch(path, {method: opts.method || (opts.body !== undefined ? 'POST' : 'GET'), headers,
|
||||
body: opts.body !== undefined ? JSON.stringify(opts.body) : undefined, cache: 'no-store'});
|
||||
try { data = await res.json(); } catch (e) { data = {ok: false, error: 'HTTP ' + res.status}; }
|
||||
if (!res.ok) data.ok = false;
|
||||
} catch (e) { data = {ok: false, error: String(e.message || e)}; }
|
||||
return data;
|
||||
}
|
||||
async function copy(text) {
|
||||
try { await navigator.clipboard.writeText(text); } catch (e) {
|
||||
const ta = document.createElement('textarea'); ta.value = text; document.body.appendChild(ta); ta.select();
|
||||
try { document.execCommand('copy'); } catch (e2) {} ta.remove();
|
||||
}
|
||||
toast(t('copied'));
|
||||
}
|
||||
function fmtValue(v) {
|
||||
if (v === null || v === undefined) return '—';
|
||||
const n = Number(v); if (!isFinite(n)) return esc(v);
|
||||
return n.toLocaleString('en-US', {maximumFractionDigits: 6});
|
||||
}
|
||||
function protoName(id) { const p = S.protocols.find(x => x.id === id); return p ? p.name : id; }
|
||||
function slug(s) { return String(s || '').replace(/[^A-Za-z0-9_-]+/g, '-').replace(/^[-_]+|[-_]+$/g, '').toLowerCase().slice(0, 40) || 'scale'; }
|
||||
function lineText(serial) { return serial ? `${serial.baudrate} ${serial.bytesize}${serial.parity}${serial.stopbits}` : ''; }
|
||||
|
||||
// ---------------------------------------------------------------- chrome
|
||||
function applyLang() {
|
||||
document.documentElement.lang = S.lang;
|
||||
document.documentElement.dir = S.lang === 'fa' ? 'rtl' : 'ltr';
|
||||
document.querySelectorAll('[data-t]').forEach(el => { el.textContent = t(el.dataset.t); });
|
||||
$('#langBtn').textContent = t('lang');
|
||||
$('#ver').textContent = 'v' + ABOUT.version;
|
||||
$('#sign').innerHTML = `<span>${esc(t('made_by'))} <b>${esc(ABOUT.author)}</b> · ${esc(ABOUT.company)}</span>
|
||||
<a href="${esc(ABOUT.website)}" target="_blank" rel="noopener">${esc(ABOUT.website.replace(/^https?:\/\//, ''))}</a>
|
||||
<a href="${esc(ABOUT.github)}" target="_blank" rel="noopener">GitHub</a>
|
||||
<a href="${esc(ABOUT.linkedin)}" target="_blank" rel="noopener">LinkedIn</a>
|
||||
<a href="${esc(ABOUT.repository)}" target="_blank" rel="noopener">${esc(t('source'))}</a>
|
||||
<span>${esc(ABOUT.license)}</span>`;
|
||||
renderAll();
|
||||
}
|
||||
function setTab(tab) {
|
||||
S.tab = tab;
|
||||
document.querySelectorAll('#tabs button').forEach(b => b.classList.toggle('on', b.dataset.tab === tab));
|
||||
document.querySelectorAll('main > section').forEach(s => s.classList.toggle('hidden', s.id !== 'p-' + tab));
|
||||
if (tab !== 'manual') stopMonitor();
|
||||
if (tab === 'find') loadPorts();
|
||||
if (location.hash !== '#' + tab) history.replaceState(null, '', '#' + tab);
|
||||
renderAll();
|
||||
}
|
||||
function renderAll(keepFind) {
|
||||
renderScales(); if (keepFind) paintResults(); else renderFind();
|
||||
renderConnect(); renderManual(); renderProtocols(); renderAbout();
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- scales
|
||||
function renderScales() {
|
||||
const el = $('#p-scales'); if (!S.state) { el.innerHTML = ''; return; }
|
||||
const profiles = S.state.profiles || [];
|
||||
if (!profiles.length) {
|
||||
el.innerHTML = `<div class="card empty"><h2>${esc(t('no_scales'))}</h2><p>${esc(t('no_scales_hint'))}</p>
|
||||
<p><button class="btn primary" data-go="find">${esc(t('find_now'))}</button></p></div>`;
|
||||
return;
|
||||
}
|
||||
const ip = (S.state.addresses || [])[0] || '127.0.0.1';
|
||||
el.innerHTML = '<div class="grid">' + profiles.map(p => `
|
||||
<div class="card" data-profile="${esc(p.name)}">
|
||||
<div class="row"><h2 class="wrap">${esc(p.label || p.name)}</h2><div class="spacer"></div>
|
||||
<span class="tag ltr">${esc(p.port)}</span></div>
|
||||
<div class="weight" id="w-${esc(p.name)}">—</div>
|
||||
<div class="state" id="s-${esc(p.name)}"><span class="dot"></span><span>${esc(t('no_data'))}</span></div>
|
||||
<div class="kv small" id="f-${esc(p.name)}" style="margin-top:8px"></div>
|
||||
${isPrint(p) ? `<p class="small muted" style="margin:8px 0 0">${esc(t('listening_all_day'))}</p>
|
||||
<details style="margin-top:6px"><summary class="small">${esc(t('last_labels'))}</summary><div class="small" id="l-${esc(p.name)}"></div></details>` : ''}
|
||||
<div class="kv small" style="margin-top:10px">
|
||||
<b>${esc(t('protocol'))}</b><span><bdi>${esc(protoName(p.protocol))}</bdi></span>
|
||||
<b>${esc(t('line'))}</b><span class="mono">${esc(lineText(p.serial))}</span>
|
||||
</div>
|
||||
<div class="small muted" style="margin-top:8px">${esc(t('address_for'))}</div>
|
||||
<div class="row" style="gap:6px;flex-wrap:nowrap"><span class="mono wrap ltr" style="flex:1">http://${esc(ip)}:${esc(S.state.listen_port)}/weight?profile=${esc(p.name)}</span>
|
||||
<button class="btn small" style="padding:2px 8px" data-copy="http://${esc(ip)}:${esc(S.state.listen_port)}/weight?profile=${esc(p.name)}">${esc(t('copy'))}</button></div>
|
||||
<div class="row" style="margin-top:10px"><span class="small muted mono">${esc(p.name)}</span><div class="spacer"></div>
|
||||
<button class="btn danger" data-del="${esc(p.name)}">${esc(t('delete'))}</button></div>
|
||||
</div>`).join('') + '</div>';
|
||||
profiles.forEach(p => paintWeight(p.name));
|
||||
}
|
||||
function paintWeight(name) {
|
||||
const w = S.weights[name]; const vEl = document.getElementById('w-' + name); const sEl = document.getElementById('s-' + name);
|
||||
if (!vEl || !sEl) return;
|
||||
if (!w) return;
|
||||
if (!w.ok) {
|
||||
vEl.innerHTML = '—';
|
||||
sEl.innerHTML = `<span class="dot bad"></span><span class="wrap">${esc(w.error || t('no_data'))}</span>`;
|
||||
return;
|
||||
}
|
||||
vEl.innerHTML = w.overload && (w.value === null || w.value === undefined) ? esc(t('overload'))
|
||||
: `${fmtValue(w.value)}<small>${esc(w.unit || '')}</small>`;
|
||||
const fEl = document.getElementById('f-' + name);
|
||||
if (fEl) fEl.innerHTML = Object.entries(w.fields || {}).filter(([k]) => k !== 'barcode')
|
||||
.map(([k, v]) => `<b class="ltr">${esc(k)}</b><span class="mono">${esc(v)}</span>`).join('');
|
||||
let cls = 'warn', label = t('moving');
|
||||
const profile = (S.state.profiles || []).find(p => p.name === name);
|
||||
if (profile && isPrint(profile)) { cls = 'ok'; label = t('printed', {ago: ago(w.age_ms)}); }
|
||||
else if (w.stale) { cls = ''; label = t('stale'); } else if (w.stable) { cls = 'ok'; label = t('stable'); }
|
||||
const extra = w.net === true ? ' · ' + t('net') : (w.net === false ? ' · ' + t('gross') : '');
|
||||
sEl.innerHTML = `<span class="dot ${cls}"></span><span>${esc(label + extra)}</span>`;
|
||||
}
|
||||
function isPrint(p) { const proto = S.protocols.find(x => x.id === p.protocol); return !!(proto && proto.kind === 'print'); }
|
||||
function ago(ms) {
|
||||
const s = Math.max(0, Math.round((ms || 0) / 1000));
|
||||
return s < 90 ? t('ago_s', {n: s}) : (s < 5400 ? t('ago_m', {n: Math.round(s / 60)}) : t('ago_h', {n: Math.round(s / 3600)}));
|
||||
}
|
||||
async function paintLabels(name) {
|
||||
const el = document.getElementById('l-' + name); if (!el) return;
|
||||
const r = await api('/api/labels?profile=' + encodeURIComponent(name) + '&limit=8');
|
||||
if (!r.ok) return;
|
||||
el.innerHTML = r.labels.length ? '<table><tbody>' + r.labels.slice().reverse().map(l => `<tr>
|
||||
<td class="mono">${esc(l.at.slice(11, 19))}</td><td class="mono"><b>${fmtValue(l.value)}</b> ${esc(l.unit)}</td>
|
||||
<td class="small">${esc(Object.entries(l.fields || {}).filter(([k]) => !['barcode', 'date', 'time'].includes(k)).map(([k, v]) => k + ': ' + v).join(' · '))}</td></tr>`).join('') + '</tbody></table>'
|
||||
: `<p class="muted">${esc(t('no_labels'))}</p>`;
|
||||
}
|
||||
async function pollWeights() {
|
||||
if (S.tab === 'scales' && S.state && !document.hidden) {
|
||||
for (const p of S.state.profiles || []) {
|
||||
if (S.inflight[p.name]) continue;
|
||||
S.inflight[p.name] = true;
|
||||
// A print-only scale is silent between labels: show the last label, however old.
|
||||
const extra = isPrint(p) ? '&wait_ms=200&max_age_ms=60000000' : '&wait_ms=1500';
|
||||
api('/api/weight?profile=' + encodeURIComponent(p.name) + extra).then(r => {
|
||||
S.weights[p.name] = r; paintWeight(p.name);
|
||||
if (isPrint(p)) return paintLabels(p.name);
|
||||
}).finally(() => { S.inflight[p.name] = false; });
|
||||
}
|
||||
}
|
||||
setTimeout(pollWeights, 700);
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- find
|
||||
async function loadPorts() {
|
||||
const r = await api('/api/ports');
|
||||
if (r.ok) { S.ports = r.ports; renderFind(); }
|
||||
}
|
||||
function renderFind() {
|
||||
const el = $('#p-find'); if (!S.state) return;
|
||||
const job = S.job; const running = job && job.running;
|
||||
const checked = S.sel || new Set(S.ports.filter(p => p.kind !== 'bluetooth').map(p => p.device));
|
||||
const thorough = $('#thorough') ? $('#thorough').checked : false;
|
||||
const waitPrint = $('#waitPrint') ? $('#waitPrint').checked : false;
|
||||
const listenOnly = $('#listenOnly') ? $('#listenOnly').checked : false;
|
||||
const ports = S.ports.length ? S.ports.map(p => `
|
||||
<label class="check"><input type="checkbox" name="port" value="${esc(p.device)}" ${checked.has(p.device) ? 'checked' : ''} ${running ? 'disabled' : ''}>
|
||||
<span><b class="ltr">${esc(p.device)}</b> <span class="muted">${esc(p.description || '')}</span>
|
||||
${p.kind === 'bluetooth' ? `<br><span class="tag warn">${esc(t('bt'))}</span>` : ''}
|
||||
${p.note ? `<br><span class="tag warn">${esc(t('ch340'))}</span> <span class="small muted">${esc(p.note)}</span>` : ''}</span></label>`).join('')
|
||||
: `<p class="note warn">${esc(t('no_ports'))}</p>`;
|
||||
el.innerHTML = `
|
||||
<div class="card"><h2>${esc(t('find_title'))}</h2><p class="muted">${esc(t('find_intro'))}</p>
|
||||
<h3>${esc(t('ports'))}</h3>${ports}
|
||||
<div class="row" style="margin-top:10px">
|
||||
<label class="row small"><input type="checkbox" id="thorough" ${thorough ? 'checked' : ''} ${running ? 'disabled' : ''}> ${esc(t('thorough'))}</label>
|
||||
<label class="row small"><input type="checkbox" id="waitPrint" ${waitPrint ? 'checked' : ''} ${running ? 'disabled' : ''}> ${esc(t('wait_print'))}</label>
|
||||
<label class="row small"><input type="checkbox" id="listenOnly" ${listenOnly ? 'checked' : ''} ${running ? 'disabled' : ''}> ${esc(t('listen_only'))}</label>
|
||||
<div class="spacer"></div>
|
||||
<button class="btn" id="refreshPorts" ${running ? 'disabled' : ''}>${esc(t('refresh'))}</button>
|
||||
${running ? `<button class="btn danger" id="cancelDetect">${esc(t('cancel'))}</button>`
|
||||
: `<button class="btn primary" id="startDetect" ${S.ports.length ? '' : 'disabled'}>${esc(t('start'))}</button>`}
|
||||
</div>
|
||||
<div id="findStatus"></div>
|
||||
</div>
|
||||
<div id="findResults"></div>`;
|
||||
S.shownResults = -1; S.shownRunning = running;
|
||||
paintProgress(); paintResults();
|
||||
}
|
||||
function logLine(e) {
|
||||
const cls = e.code === 'found' ? 'found' : (e.code === 'open_failed' || e.code === 'error' ? 'bad' : '');
|
||||
const vars = {...e, protocol: e.protocol ? protoName(e.protocol) : '', readable: e.readable !== undefined ? Math.round(e.readable * 100) : ''};
|
||||
return `<div class="${cls}"><span class="muted mono">${esc(Number(e.t).toFixed(1))}s</span> ${esc(t('log_' + e.code, vars))}</div>`;
|
||||
}
|
||||
function paintProgress() {
|
||||
const box = $('#findStatus'); const job = S.job; if (!box) return;
|
||||
if (!job) { box.innerHTML = ''; return; }
|
||||
const pct = Math.round((job.progress || 0) * 100);
|
||||
if (!$('#log')) {
|
||||
box.innerHTML = `<div style="margin-top:12px"><div class="row small muted"><span id="jobText"></span><div class="spacer"></div><span class="mono" id="jobPct"></span></div>
|
||||
<div class="progress"><div id="jobBar"></div></div><div class="log" id="log" style="margin-top:8px"></div></div>`;
|
||||
S.shownLog = 0;
|
||||
}
|
||||
$('#jobText').textContent = job.running ? t('running') : t('done');
|
||||
$('#jobPct').textContent = `${pct}% · ${job.elapsed_s}s`;
|
||||
$('#jobBar').style.width = pct + '%';
|
||||
const logEl = $('#log');
|
||||
const start = Math.max(S.shownLog || 0, S.log.length - 250);
|
||||
if (start < S.log.length) {
|
||||
logEl.insertAdjacentHTML('beforeend', S.log.slice(start).map(logLine).join(''));
|
||||
S.shownLog = S.log.length;
|
||||
while (logEl.childElementCount > 250) logEl.firstElementChild.remove();
|
||||
logEl.scrollTop = logEl.scrollHeight;
|
||||
}
|
||||
}
|
||||
function paintResults() {
|
||||
const box = $('#findResults'); const job = S.job; if (!box) return;
|
||||
const results = job ? (job.results || []) : [];
|
||||
const key = results.length + ':' + (job && job.running ? 1 : 0) + ':' + (S.state.profiles || []).length;
|
||||
if (S.shownResults === key) return;
|
||||
S.shownResults = key;
|
||||
box.innerHTML = (results.length ? `<h3>${esc(t('results'))}</h3>${results.map(renderResult).join('')}` : '')
|
||||
+ (job && !job.running && !results.some(r => r.found) ? tipsCard() : '');
|
||||
}
|
||||
function tipsCard() {
|
||||
return `<div class="card"><h3>${esc(t('tips_title'))}</h3><ul class="steps">
|
||||
<li>${esc(t('tip1'))}</li><li>${esc(t('tip2'))}</li><li>${esc(t('tip3'))}</li><li>${esc(t('tip4'))}</li></ul></div>`;
|
||||
}
|
||||
function renderResult(r) {
|
||||
if (!r.found) {
|
||||
const u = r.unknown;
|
||||
return `<div class="card"><h2>${esc(t('not_found_on', {port: r.port}))}</h2>
|
||||
${r.error ? `<p class="note warn">${esc(r.error)}</p>` : ''}
|
||||
${u ? `<p class="muted">${esc(t('heard_unknown', {baud: u.baud, framing: u.framing}))}</p>
|
||||
<div class="log mono">${esc(u.sample_text)}</div><div class="log mono small" style="margin-top:6px">${esc(u.sample_hex)}</div>` : ''}</div>`;
|
||||
}
|
||||
const rd = r.reading || {};
|
||||
const d = S.draft[r.port] || {};
|
||||
const same = (S.state.profiles || []).filter(p => p.port === r.port && p.protocol === r.protocol).map(p => p.name);
|
||||
return `<div class="card">
|
||||
<div class="row"><h2>${esc(t('found_on', {port: r.port}))}</h2><div class="spacer"></div>
|
||||
<span class="tag">${esc(t('confidence'))} ${Math.round((r.confidence || 0) * 100)}%</span>
|
||||
${r.field_tested ? `<span class="tag">${esc(t('field_tested'))}</span>` : ''}</div>
|
||||
<div class="kv" style="margin-top:8px">
|
||||
<b>${esc(t('protocol'))}</b><span><bdi>${esc(r.protocol_name)}</bdi></span>
|
||||
<b>${esc(t('line'))}</b><span class="mono">${esc(r.port)} · ${esc(lineText(r.serial))}${r.exchange && r.exchange.request_hex ? ' · ' + esc(r.exchange.request_hex) : ''}</span>
|
||||
<b>${esc(t('mode'))}</b><span>${esc(t('mode_' + r.mode))}</span>
|
||||
<b>${esc(t('reading'))}</b><span class="mono">${fmtValue(rd.value)} ${esc(rd.unit || '')}${rd.stable === true ? ' · ' + esc(t('stable')) : (rd.stable === false ? ' · ' + esc(t('moving')) : '')}</span>
|
||||
<b>${esc(t('sample'))}</b><span class="mono wrap">${esc(r.sample_text)}</span>
|
||||
</div>
|
||||
<div class="row" style="margin-top:12px">
|
||||
<label class="f">${esc(t('save_as'))}<input class="ltr" data-name="${esc(r.port)}" value="${esc(d.name ?? slug('scale-' + r.port))}" size="18"></label>
|
||||
<label class="f">${esc(t('label'))}<input data-label="${esc(r.port)}" value="${esc(d.label ?? '')}" size="22"></label>
|
||||
${rd.unit ? '' : `<label class="f">${esc(t('unit_if_missing'))}<select data-unit="${esc(r.port)}">${['kg','g','t','lb'].map(u => `<option ${d.unit === u ? 'selected' : ''}>${u}</option>`).join('')}</select></label>`}
|
||||
<div class="spacer"></div>
|
||||
${same.length ? `<span class="tag">${esc(t('already_saved', {names: same.join(', ')}))}</span>` : ''}
|
||||
<button class="btn primary" data-save-result="${esc(r.port)}">${esc(t('save'))}</button>
|
||||
</div></div>`;
|
||||
}
|
||||
async function startDetect() {
|
||||
const ports = [...document.querySelectorAll('input[name=port]:checked')].map(i => i.value);
|
||||
if (!ports.length) return;
|
||||
S.log = []; S.jobSince = 0; S.draft = {};
|
||||
const r = await api('/api/detect', {body: {ports, thorough: $('#thorough').checked, bluetooth: true,
|
||||
print_wait_s: $('#waitPrint').checked ? 60 : 0, listen_only: $('#listenOnly').checked}});
|
||||
if (!r.ok) { toast(t('failed', {error: r.error})); return; }
|
||||
S.job = r.job; renderFind(); setTimeout(pollDetect, 300);
|
||||
}
|
||||
async function pollDetect() {
|
||||
const r = await api('/api/detect?since=' + S.jobSince);
|
||||
if (r.ok && r.job) {
|
||||
S.log.push(...r.job.log); S.jobSince = r.job.log_size; S.job = r.job;
|
||||
if (S.shownRunning !== r.job.running) renderFind(); else { paintProgress(); paintResults(); }
|
||||
if (r.job.running) { setTimeout(pollDetect, 500); } else { refreshState(); }
|
||||
}
|
||||
}
|
||||
async function saveResult(port) {
|
||||
const r = (S.job.results || []).find(x => x.port === port); if (!r) return;
|
||||
const name = document.querySelector(`[data-name="${CSS.escape(port)}"]`).value.trim();
|
||||
if (!/^[A-Za-z0-9][A-Za-z0-9_-]{0,39}$/.test(name)) { toast(t('err_name')); return; }
|
||||
const label = document.querySelector(`[data-label="${CSS.escape(port)}"]`).value.trim();
|
||||
const unitEl = document.querySelector(`[data-unit="${CSS.escape(port)}"]`);
|
||||
const res = await api('/api/profiles', {body: {detection: r, name, label, unit: unitEl ? unitEl.value : ''}});
|
||||
if (!res.ok) { toast(t('failed', {error: res.error})); return; }
|
||||
S.state.profiles = res.profiles; toast(t('saved')); renderAll();
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- connect
|
||||
function renderConnect() {
|
||||
const el = $('#p-connect'); const st = S.state; if (!st) return;
|
||||
const port = st.listen_port; const fw = st.firewall || {}; const as = st.autostart || {};
|
||||
const key = S.showKey ? st.token : '•'.repeat(Math.min(24, (st.token || '').length));
|
||||
const addr = (st.addresses || []).map(a => `<span class="tag ltr">${esc(a)}</span>`).join(' ') || '<span class="muted">—</span>';
|
||||
const fwCmd = `netsh advfirewall firewall add rule name="SyncPulse Scale Bridge" dir=in action=allow protocol=TCP localport=${port} profile=any`;
|
||||
el.innerHTML = `
|
||||
<div class="card"><h2>${esc(t('conn_title'))}</h2><p class="muted">${esc(t('conn_intro'))}</p></div>
|
||||
<div class="card"><h3><span class="num">1</span>${esc(t('step_address'))}</h3>
|
||||
<div class="kv"><b>${esc(t('addresses'))}</b><span>${addr}</span><b>${esc(t('port_label'))}</b><span class="mono">${esc(port)}</span>
|
||||
<b>Host</b><span class="mono">${esc(st.host)}</span></div></div>
|
||||
<div class="card"><h3><span class="num">2</span>${esc(t('step_key'))}</h3>
|
||||
<div class="row"><span class="mono wrap" style="font-size:14px">${esc(key)}</span><div class="spacer"></div>
|
||||
<button class="btn" id="keyShow">${esc(S.showKey ? t('hide') : t('show'))}</button>
|
||||
<button class="btn" id="keyCopy">${esc(t('copy'))}</button>
|
||||
<button class="btn danger" id="keyNew">${esc(t('new_key'))}</button></div>
|
||||
<p class="small muted">${esc(t('key_hint'))}</p></div>
|
||||
<div class="card"><h3><span class="num">3</span>${esc(t('step_firewall'))}</h3>
|
||||
${fw.supported === false ? `<p>${esc(t('fw_not_windows', {port}))}</p>` : `
|
||||
<p class="${fw.port_ok ? 'note' : 'note warn'}"><span class="dot ${fw.port_ok ? 'ok' : 'warn'}"></span> ${esc(fw.port_ok ? t('fw_is_open', {port}) : t('fw_is_closed', {port}))}</p>
|
||||
<p class="small">${esc(t('fw_what', {port}))}</p>
|
||||
<div class="row"><label class="f">${esc(t('fw_only_from'))}<input class="ltr" id="fwRemote" placeholder="192.168.1.10" size="16"></label>
|
||||
<div class="spacer"></div>
|
||||
${fw.exists ? `<button class="btn" id="fwRemove">${esc(t('fw_remove'))}</button>` : ''}
|
||||
<button class="btn primary" id="fwOpen">${esc(t('fw_open', {port}))}</button></div>
|
||||
<p class="small muted" style="margin-top:10px">${esc(t('fw_manual'))}</p><div class="log mono small">${esc(fwCmd)}</div>`}
|
||||
</div>
|
||||
<div class="card"><h3><span class="num">4</span>${esc(t('step_autostart'))}</h3>
|
||||
${as.supported === false ? '' : `
|
||||
<p class="${as.enabled && as.this_program ? 'note' : 'note warn'}"><span class="dot ${as.enabled ? (as.this_program ? 'ok' : 'warn') : ''}"></span>
|
||||
${esc(as.enabled ? (as.this_program ? t('as_on') : t('as_other')) : t('as_off'))}</p>
|
||||
<p class="small">${esc(t('as_what'))}</p>
|
||||
<div class="row"><div class="spacer"></div>
|
||||
${as.enabled ? `<button class="btn" id="asOff">${esc(t('as_disable'))}</button>` : ''}
|
||||
${!as.enabled || !as.this_program ? `<button class="btn primary" id="asOn">${esc(t('as_enable'))}</button>` : ''}</div>
|
||||
<p class="small muted">${esc(t('as_note'))}</p>`}
|
||||
</div>
|
||||
<div class="card"><h3>${esc(t('in_syncpulse'))}</h3><p>${esc(t('in_syncpulse_steps', {port}))}</p>
|
||||
<div class="log mono ltr" style="text-align:left">GET http://${esc((st.addresses || [])[0] || '127.0.0.1')}:${esc(port)}/weight?profile=<name><br>X-Bridge-Token: <key></div></div>
|
||||
<div class="card"><h3>${esc(t('allowed_title'))}</h3><p class="small muted">${esc(t('allowed_hint'))}</p>
|
||||
<div class="row"><input class="ltr" id="allowed" style="flex:1" value="${esc((st.allowed_clients || []).join(', '))}">
|
||||
<button class="btn" id="allowedSave">${esc(t('save'))}</button></div>
|
||||
<p class="small muted" style="margin-top:10px">${esc(t('config_file'))}: <span class="mono wrap">${esc(st.config_path)}</span></p></div>`;
|
||||
}
|
||||
async function adminAction(path, body) {
|
||||
S.busy = true; document.body.style.cursor = 'progress';
|
||||
const r = await api(path, {body});
|
||||
S.busy = false; document.body.style.cursor = '';
|
||||
if (r.state) S.state = r.state;
|
||||
toast(r.ok ? t('done') : (r.cancelled ? t('cancelled_uac') : t('failed', {error: r.error || ('code ' + r.code)})));
|
||||
renderAll();
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- manual
|
||||
function renderManual() {
|
||||
const el = $('#p-manual'); if (!S.state) return;
|
||||
if (el.dataset.ready === S.lang + S.ports.length + S.protocols.length) { paintMonitor(); return; }
|
||||
const keep = {};
|
||||
el.querySelectorAll('[id^=m-]').forEach(i => { keep[i.id] = i.value; });
|
||||
const bauds = [1200, 2400, 4800, 9600, 19200, 38400, 57600, 115200];
|
||||
const framings = ['8N1', '7E1', '7O1', '8E1', '8O1', '8N2', '7N2'];
|
||||
el.innerHTML = `
|
||||
<div class="card"><h2>${esc(t('manual_title'))}</h2><p class="muted">${esc(t('manual_intro'))}</p>
|
||||
<div class="row">
|
||||
<label class="f">${esc(t('port_label'))}<select id="m-port">${S.ports.map(p => `<option value="${esc(p.device)}">${esc(p.device)}</option>`).join('')}</select></label>
|
||||
<label class="f">${esc(t('baud'))}<select id="m-baud">${bauds.map(b => `<option ${b === 9600 ? 'selected' : ''}>${b}</option>`).join('')}</select></label>
|
||||
<label class="f">${esc(t('framing'))}<select id="m-framing">${framings.map(f => `<option>${f}</option>`).join('')}</select></label>
|
||||
<label class="f">${esc(t('preset'))}<select id="m-proto"><option value="">—</option>${S.protocols.filter(p => !p.id.startsWith('custom')).map(p => `<option value="${esc(p.id)}">${esc(p.name)}</option>`).join('')}</select></label>
|
||||
</div>
|
||||
<div class="row" style="margin-top:8px">
|
||||
<label class="f" style="flex:1">${esc(t('request'))}<input class="ltr mono" id="m-request" placeholder="53 49 0D 0A"></label>
|
||||
<label class="f">${esc(t('poll'))}<input class="ltr" id="m-poll" type="number" min="100" max="10000" step="100" value="500" style="width:90px"></label>
|
||||
<button class="btn primary" id="monBtn"></button>
|
||||
</div>
|
||||
<div id="monOut" style="margin-top:12px"></div>
|
||||
</div>
|
||||
<div class="card"><h3>${esc(t('save_manual'))}</h3>
|
||||
<div class="row">
|
||||
<label class="f">${esc(t('save_as'))}<input class="ltr" id="m-name" value="scale-1" size="16"></label>
|
||||
<label class="f">${esc(t('label'))}<input id="m-label" size="20"></label>
|
||||
<label class="f">${esc(t('protocol'))}<select id="m-sproto">${S.protocols.map(p => `<option value="${esc(p.id)}">${esc(p.name)}</option>`).join('')}</select></label>
|
||||
<label class="f">${esc(t('unit_if_missing'))}<select id="m-unit"><option value="">—</option>${['kg','g','t','lb','oz'].map(u => `<option>${u}</option>`).join('')}</select></label>
|
||||
<label class="f">${esc(t('output_unit'))}<select id="m-ounit"><option value="">${esc(t('as_sent'))}</option>${['kg','g','t','lb','oz'].map(u => `<option>${u}</option>`).join('')}</select></label>
|
||||
<label class="f">${esc(t('stable_samples'))}<input class="ltr" id="m-stable" type="number" min="1" max="20" value="3" style="width:70px"></label>
|
||||
</div>
|
||||
<div class="row" id="m-custom" style="margin-top:8px"></div>
|
||||
<div class="row" style="margin-top:8px"><div class="spacer"></div><button class="btn primary" id="m-save">${esc(t('save'))}</button></div>
|
||||
</div>`;
|
||||
Object.entries(keep).forEach(([id, v]) => { const i = document.getElementById(id); if (i && v !== undefined) i.value = v; });
|
||||
el.dataset.ready = S.lang + S.ports.length + S.protocols.length;
|
||||
renderCustom(); paintMonitor();
|
||||
}
|
||||
function renderCustom() {
|
||||
const box = $('#m-custom'); if (!box) return;
|
||||
const id = $('#m-sproto').value;
|
||||
if (id === 'custom_binary') {
|
||||
box.innerHTML = `<label class="f">pattern (hex, ?? = any)<input class="ltr mono" id="c-pattern" value="58 ?? 07 07"></label>
|
||||
<label class="f">value_offset<input class="ltr" id="c-offset" type="number" value="4" style="width:70px"></label>
|
||||
<label class="f">value_length<input class="ltr" id="c-length" type="number" value="3" style="width:70px"></label>
|
||||
<label class="f">byte_order<select id="c-order"><option>big</option><option>little</option></select></label>
|
||||
<label class="row small"><input type="checkbox" id="c-signed"> signed</label>`;
|
||||
} else if (id === 'custom_ascii') {
|
||||
box.innerHTML = `<label class="f" style="flex:1">regex (group 1 = number)<input class="ltr mono" id="c-regex" value="([-+]?\\d+\\.?\\d*)"></label>`;
|
||||
} else box.innerHTML = '';
|
||||
}
|
||||
function monitorQuery() {
|
||||
const q = new URLSearchParams({port: $('#m-port').value, baud: $('#m-baud').value, framing: $('#m-framing').value,
|
||||
request_hex: $('#m-request').value, poll_ms: $('#m-poll').value || '500'});
|
||||
const proto = S.protocols.find(p => p.id === $('#m-proto').value);
|
||||
if (proto && proto.after_ack_hex) q.set('after_ack_hex', proto.after_ack_hex);
|
||||
return q;
|
||||
}
|
||||
function startMonitor() {
|
||||
stopMonitor(); S.monitorData = null;
|
||||
const tick = async () => {
|
||||
const r = await api('/api/monitor?' + monitorQuery());
|
||||
if (!S.monitor) return;
|
||||
S.monitorData = r; paintMonitor();
|
||||
S.monitor = setTimeout(tick, 1000);
|
||||
};
|
||||
S.monitor = setTimeout(tick, 0); paintMonitor();
|
||||
}
|
||||
function stopMonitor() { if (S.monitor) { clearTimeout(S.monitor); S.monitor = null; paintMonitor(); } }
|
||||
function paintMonitor() {
|
||||
const btn = $('#monBtn'); const out = $('#monOut'); if (!btn || !out) return;
|
||||
btn.textContent = S.monitor ? t('monitor_stop') : t('monitor_start');
|
||||
const r = S.monitorData; if (!r) { out.innerHTML = ''; return; }
|
||||
if (!r.ok && r.error) { out.innerHTML = `<p class="note warn">${esc(t('open_error', {error: r.error}))}</p>`; return; }
|
||||
const frames = (r.frames || []).slice().reverse();
|
||||
out.innerHTML = `<div class="small muted mono">${esc(r.settings || '')} · rx ${esc((r.stats || {}).bytes_rx ?? 0)} B</div>
|
||||
${frames.length ? `<table style="margin-top:6px"><thead><tr><th>ms</th><th>HEX</th><th>TEXT</th></tr></thead><tbody>
|
||||
${frames.map(f => `<tr><td class="mono">${esc(f.age_ms)}</td><td class="mono wrap">${esc(f.hex)}</td><td class="mono wrap">${esc(f.text)}</td></tr>`).join('')}</tbody></table>`
|
||||
: `<p class="muted">${esc(t('none_yet'))}</p>`}
|
||||
${(r.guesses || []).length ? `<h3>${esc(t('guesses'))}</h3><table><tbody>${r.guesses.map(g => `<tr><td>${esc(g.name)}</td><td class="mono">${fmtValue(g.value)} ${esc(g.unit || '')}</td><td class="muted">×${esc(g.count)}</td></tr>`).join('')}</tbody></table>` : ''}`;
|
||||
}
|
||||
async function saveManual() {
|
||||
const name = $('#m-name').value.trim();
|
||||
if (!/^[A-Za-z0-9][A-Za-z0-9_-]{0,39}$/.test(name)) { toast(t('err_name')); return; }
|
||||
const framing = $('#m-framing').value; const protocol = $('#m-sproto').value;
|
||||
const params = {};
|
||||
if (protocol === 'custom_binary') Object.assign(params, {pattern: $('#c-pattern').value, value_offset: +$('#c-offset').value,
|
||||
value_length: +$('#c-length').value, byte_order: $('#c-order').value, signed: $('#c-signed').checked});
|
||||
if (protocol === 'custom_ascii') params.regex = $('#c-regex').value;
|
||||
const proto = S.protocols.find(p => p.id === protocol) || {};
|
||||
const request = $('#m-request').value.trim();
|
||||
const body = {name, label: $('#m-label').value.trim(), port: $('#m-port').value, protocol, params,
|
||||
serial: {baudrate: +$('#m-baud').value, bytesize: +framing[0], parity: framing[1], stopbits: +framing[2]},
|
||||
exchange: {request_hex: request, after_ack_hex: proto.after_ack_hex || '', poll_interval_ms: +$('#m-poll').value || 500},
|
||||
unit: $('#m-unit').value, output_unit: $('#m-ounit').value, stable_samples: +$('#m-stable').value || 3};
|
||||
stopMonitor();
|
||||
const r = await api('/api/profiles', {body});
|
||||
if (!r.ok) { toast(t('failed', {error: r.error})); return; }
|
||||
S.state.profiles = r.profiles; toast(t('saved')); renderAll();
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- protocols & about
|
||||
function renderProtocols() {
|
||||
const el = $('#p-protocols');
|
||||
el.innerHTML = `<div class="card"><h2>${esc(t('proto_title'))}</h2><p class="muted">${esc(t('proto_intro'))}</p>
|
||||
<div style="overflow-x:auto"><table><thead><tr><th>${esc(t('protocol'))}</th><th>${esc(t('kind'))}</th><th>${esc(t('request_col'))}</th><th>${esc(t('families'))}</th><th>${esc(t('reference'))}</th></tr></thead><tbody>
|
||||
${S.protocols.map(p => `<tr><td><b><bdi>${esc(p.name)}</bdi></b><br><span class="mono small muted">${esc(p.id)}</span>${p.field_tested ? `<br><span class="tag">${esc(t('field_tested'))}</span>` : ''}</td>
|
||||
<td>${esc(t('kind_' + p.kind))}</td><td class="mono small">${esc(p.request_hex || '—')}${p.after_ack_hex ? ' → ' + esc(p.after_ack_hex) : ''}</td>
|
||||
<td class="small">${esc(p.families)}</td><td class="small muted">${esc(p.reference)}</td></tr>`).join('')}
|
||||
</tbody></table></div></div>`;
|
||||
}
|
||||
function renderAbout() {
|
||||
const el = $('#p-about'); const a = ABOUT;
|
||||
el.innerHTML = `<div class="card"><h2>${esc(t('about_title'))}</h2><p>${esc(t('about_text'))}</p><p>${esc(t('about_platform'))}</p>
|
||||
<div class="kv" style="margin-top:12px">
|
||||
<b>${esc(t('version'))}</b><span class="mono">${esc(a.version)}</span>
|
||||
<b>${esc(t('author'))}</b><span>${esc(a.author)}</span>
|
||||
<b>${esc(t('company'))}</b><span>${esc(a.company)}</span>
|
||||
<b>${esc(t('website'))}</b><a class="ltr" href="${esc(a.website)}" target="_blank" rel="noopener">${esc(a.website)}</a>
|
||||
<b>GitHub</b><a class="ltr" href="${esc(a.github)}" target="_blank" rel="noopener">${esc(a.github)}</a>
|
||||
<b>LinkedIn</b><a class="ltr" href="${esc(a.linkedin)}" target="_blank" rel="noopener">${esc(a.linkedin)}</a>
|
||||
<b>${esc(t('source'))}</b><a class="ltr" href="${esc(a.repository)}" target="_blank" rel="noopener">${esc(a.repository)}</a>
|
||||
<b>${esc(t('license'))}</b><span>${esc(a.license)}</span>
|
||||
</div>
|
||||
<p class="small muted" style="margin-top:12px">${esc(t('license_text'))}</p>
|
||||
<p class="small muted">${esc(a.copyright)}</p></div>`;
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- events & boot
|
||||
document.addEventListener('click', async ev => {
|
||||
const b = ev.target.closest('button'); if (!b || b.disabled) return;
|
||||
if (b.dataset.tab) return setTab(b.dataset.tab);
|
||||
if (b.dataset.go) return setTab(b.dataset.go);
|
||||
if (b.id === 'langBtn') { S.lang = S.lang === 'fa' ? 'en' : 'fa'; try { localStorage.setItem('sb.lang', S.lang); } catch (e) {} return applyLang(); }
|
||||
if (b.dataset.del) {
|
||||
if (!confirm(t('confirm_delete', {name: b.dataset.del}))) return;
|
||||
const r = await api('/api/profiles/' + encodeURIComponent(b.dataset.del), {method: 'DELETE'});
|
||||
if (r.ok) { S.state.profiles = r.profiles; delete S.weights[b.dataset.del]; renderAll(); } else toast(t('failed', {error: r.error}));
|
||||
return;
|
||||
}
|
||||
if (b.dataset.saveResult) return saveResult(b.dataset.saveResult);
|
||||
if (b.dataset.copy) return copy(b.dataset.copy);
|
||||
switch (b.id) {
|
||||
case 'startDetect': return startDetect();
|
||||
case 'cancelDetect': await api('/api/detect/cancel', {body: {}}); return;
|
||||
case 'refreshPorts': return loadPorts();
|
||||
case 'keyShow': S.showKey = !S.showKey; return renderConnect();
|
||||
case 'keyCopy': return copy(S.state.token);
|
||||
case 'keyNew':
|
||||
if (!confirm(t('confirm_key'))) return;
|
||||
{ const r = await api('/api/token', {body: {}}); if (r.ok) { S.state.token = r.token; S.showKey = true; renderConnect(); } }
|
||||
return;
|
||||
case 'fwOpen': return adminAction('/api/firewall', {remote_ip: $('#fwRemote').value.trim()});
|
||||
case 'fwRemove': return adminAction('/api/firewall', {remove: true});
|
||||
case 'asOn': return adminAction('/api/autostart', {enable: true});
|
||||
case 'asOff': return adminAction('/api/autostart', {enable: false});
|
||||
case 'allowedSave': {
|
||||
const clients = $('#allowed').value.split(/[,\s]+/).filter(Boolean);
|
||||
const r = await api('/api/allowed', {body: {clients}});
|
||||
if (r.ok) { S.state.allowed_clients = r.allowed_clients; toast(t('saved')); } else toast(t('failed', {error: r.error}));
|
||||
return;
|
||||
}
|
||||
case 'monBtn': return S.monitor ? stopMonitor() : startMonitor();
|
||||
case 'm-save': return saveManual();
|
||||
}
|
||||
});
|
||||
document.addEventListener('input', ev => {
|
||||
const el = ev.target; const port = el.dataset && (el.dataset.name || el.dataset.label || el.dataset.unit);
|
||||
if (!port) return;
|
||||
const d = S.draft[port] = S.draft[port] || {};
|
||||
if (el.dataset.name) d.name = el.value; else if (el.dataset.label) d.label = el.value; else d.unit = el.value;
|
||||
});
|
||||
document.addEventListener('change', ev => {
|
||||
if (ev.target.name === 'port') {
|
||||
S.sel = new Set([...document.querySelectorAll('input[name=port]:checked')].map(i => i.value));
|
||||
}
|
||||
if (ev.target.id === 'm-proto') {
|
||||
const p = S.protocols.find(x => x.id === ev.target.value);
|
||||
if (p) { $('#m-request').value = p.request_hex; const s = $('#m-sproto'); if (s) { s.value = p.id; renderCustom(); } }
|
||||
}
|
||||
if (ev.target.id === 'm-sproto') renderCustom();
|
||||
});
|
||||
async function refreshState(fresh) {
|
||||
const r = await api('/api/state' + (fresh ? '?fresh=1' : ''));
|
||||
if (r.ok) {
|
||||
S.state = r; $('#simPill').classList.toggle('hidden', !r.simulate);
|
||||
const typing = document.activeElement && document.activeElement.closest && document.activeElement.closest('#p-find');
|
||||
renderAll(!!typing);
|
||||
}
|
||||
}
|
||||
async function boot() {
|
||||
const [state, protos, ports, job] = await Promise.all([api('/api/state'), api('/api/protocols'), api('/api/ports'), api('/api/detect')]);
|
||||
if (protos.ok) S.protocols = protos.protocols;
|
||||
if (ports.ok) S.ports = ports.ports;
|
||||
if (state.ok) { S.state = state; $('#simPill').classList.toggle('hidden', !state.simulate); }
|
||||
if (job.ok && job.job) { S.job = job.job; S.log = job.job.log; S.jobSince = job.job.log_size; if (job.job.running) pollDetect(); }
|
||||
applyLang();
|
||||
const tab = location.hash.replace('#', '');
|
||||
setTab(['scales','find','connect','manual','protocols','about'].includes(tab) ? tab : ((state.profiles || []).length ? 'scales' : 'find'));
|
||||
pollWeights();
|
||||
}
|
||||
boot();
|
||||
"""
|
||||
|
||||
_REMOTE = r"""<!doctype html><html lang="en"><head><meta charset="utf-8">
|
||||
<meta name="viewport" content="width=device-width,initial-scale=1"><title>SyncPulse Scale Bridge</title>
|
||||
<link rel="icon" href="__ICON__"><style>body{font:15px/1.6 "Segoe UI",Tahoma,sans-serif;max-width:640px;margin:40px auto;
|
||||
padding:0 16px;color:#16202a;background:#f4f6f8}.card{background:#fff;border:1px solid #dde3e9;border-radius:12px;padding:20px}
|
||||
a{color:#0f766e}small{color:#5b6b7a}</style></head><body><div class="card">
|
||||
<h2>SyncPulse Scale Bridge __VERSION__</h2>
|
||||
<p>This bridge serves the scales connected to this PC to the network (JSON over HTTP, see
|
||||
<a href="__REPO__">the documentation</a>). Its control page opens only on the PC itself:
|
||||
<b>http://127.0.0.1:__PORT__/</b></p>
|
||||
<p dir="rtl">این پل وزن باسکولهای وصل به این رایانه را روی شبکه در اختیار میگذارد. صفحهی مدیریت فقط روی خود همین رایانه باز میشود.</p>
|
||||
<p><small>__AUTHOR__ · <a href="__WEBSITE__">__WEBSITE__</a> · <a href="__GITHUB__">GitHub</a> ·
|
||||
<a href="__LINKEDIN__">LinkedIn</a> · __LICENSE__</small></p></div></body></html>"""
|
||||
|
||||
|
||||
def page() -> str:
|
||||
head = ('<!doctype html><html lang="en"><head><meta charset="utf-8">'
|
||||
'<meta name="viewport" content="width=device-width,initial-scale=1">'
|
||||
'<meta name="author" content="' + ABOUT["author"] + ' — ' + ABOUT["company"] + '">'
|
||||
'<title>SyncPulse Scale Bridge</title><link rel="icon" href="' + ICON + '">'
|
||||
'<style>' + _STYLE + '</style></head><body>')
|
||||
about = json.dumps(ABOUT, ensure_ascii=False).replace("</", "<\\/")
|
||||
return (head + _BODY.replace("__ICON__", ICON)
|
||||
+ "<script>" + _SCRIPT.replace("__ABOUT__", about) + "</script></body></html>")
|
||||
|
||||
|
||||
def remote_page(port: int = 8765) -> str:
|
||||
values = {"__ICON__": ICON, "__VERSION__": ABOUT["version"], "__REPO__": ABOUT["repository"],
|
||||
"__PORT__": str(port), "__AUTHOR__": f'{ABOUT["author"]} — {ABOUT["company"]}',
|
||||
"__WEBSITE__": ABOUT["website"], "__GITHUB__": ABOUT["github"],
|
||||
"__LINKEDIN__": ABOUT["linkedin"], "__LICENSE__": ABOUT["license"]}
|
||||
html = _REMOTE
|
||||
for k, v in values.items():
|
||||
html = html.replace(k, v)
|
||||
return html
|
||||
@@ -0,0 +1,294 @@
|
||||
# SPDX-License-Identifier: GPL-3.0-or-later
|
||||
# Copyright (C) 2026 Farshad Zamani — Cloudtart (https://cloudtart.com)
|
||||
"""
|
||||
Windows chores the bridge can do by itself, each behind one button:
|
||||
|
||||
* open the firewall for the bridge port (so other machines can reach it),
|
||||
* start the bridge with Windows, before anyone logs in (a scheduled task that
|
||||
runs as SYSTEM, never stops after 72 hours, and restarts if it fails).
|
||||
|
||||
Both need administrator rights; Windows shows its usual UAC prompt.
|
||||
Everything returns plain dictionaries for the user interface.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import ctypes
|
||||
import logging
|
||||
import os
|
||||
import socket
|
||||
import subprocess
|
||||
import sys
|
||||
import tempfile
|
||||
import webbrowser
|
||||
from typing import Optional
|
||||
|
||||
from . import PRODUCT
|
||||
|
||||
log = logging.getLogger("scale_bridge")
|
||||
|
||||
RULE_NAME = PRODUCT
|
||||
TASK_NAME = PRODUCT
|
||||
CREATE_NO_WINDOW = 0x08000000
|
||||
ERROR_CANCELLED = 1223
|
||||
|
||||
|
||||
def is_windows() -> bool:
|
||||
return sys.platform == "win32"
|
||||
|
||||
|
||||
def is_admin() -> bool:
|
||||
if not is_windows():
|
||||
return os.geteuid() == 0 if hasattr(os, "geteuid") else False
|
||||
try:
|
||||
return bool(ctypes.windll.shell32.IsUserAnAdmin())
|
||||
except Exception: # noqa: BLE001
|
||||
return False
|
||||
|
||||
|
||||
def is_frozen() -> bool:
|
||||
return bool(getattr(sys, "frozen", False))
|
||||
|
||||
|
||||
def program_command(extra: str) -> tuple[str, str, str]:
|
||||
"""(executable, arguments, working directory) that start this program again."""
|
||||
if is_frozen():
|
||||
exe = os.path.abspath(sys.executable)
|
||||
return exe, extra, os.path.dirname(exe)
|
||||
root = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
|
||||
return os.path.abspath(sys.executable), f"-m scale_bridge {extra}", root
|
||||
|
||||
|
||||
def _run(args: list[str], timeout: float = 20) -> subprocess.CompletedProcess:
|
||||
return subprocess.run(args, capture_output=True, timeout=timeout,
|
||||
creationflags=CREATE_NO_WINDOW if is_windows() else 0)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Elevation
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
def run_elevated(exe: str, params: str, timeout: float = 120) -> dict:
|
||||
"""Run a command as administrator (UAC prompt) and wait for it."""
|
||||
if not is_windows():
|
||||
return {"ok": False, "error": "Windows only"}
|
||||
if is_admin():
|
||||
try:
|
||||
proc = subprocess.run(f'"{exe}" {params}', capture_output=True, timeout=timeout,
|
||||
creationflags=CREATE_NO_WINDOW)
|
||||
return {"ok": proc.returncode == 0, "code": proc.returncode}
|
||||
except (OSError, subprocess.SubprocessError) as e:
|
||||
return {"ok": False, "error": str(e)}
|
||||
|
||||
from ctypes import wintypes
|
||||
|
||||
class SHELLEXECUTEINFOW(ctypes.Structure):
|
||||
_fields_ = [("cbSize", wintypes.DWORD), ("fMask", ctypes.c_ulong), ("hwnd", wintypes.HWND),
|
||||
("lpVerb", wintypes.LPCWSTR), ("lpFile", wintypes.LPCWSTR),
|
||||
("lpParameters", wintypes.LPCWSTR), ("lpDirectory", wintypes.LPCWSTR),
|
||||
("nShow", ctypes.c_int), ("hInstApp", wintypes.HINSTANCE),
|
||||
("lpIDList", ctypes.c_void_p), ("lpClass", wintypes.LPCWSTR),
|
||||
("hkeyClass", wintypes.HKEY), ("dwHotKey", wintypes.DWORD),
|
||||
("hIconOrMonitor", wintypes.HANDLE), ("hProcess", wintypes.HANDLE)]
|
||||
|
||||
SEE_MASK_NOCLOSEPROCESS = 0x00000040
|
||||
SEE_MASK_NO_CONSOLE = 0x00008000
|
||||
info = SHELLEXECUTEINFOW()
|
||||
info.cbSize = ctypes.sizeof(info)
|
||||
info.fMask = SEE_MASK_NOCLOSEPROCESS | SEE_MASK_NO_CONSOLE
|
||||
info.lpVerb = "runas"
|
||||
info.lpFile = exe
|
||||
info.lpParameters = params
|
||||
info.nShow = 0 # SW_HIDE
|
||||
shell32 = ctypes.windll.shell32
|
||||
kernel32 = ctypes.windll.kernel32
|
||||
shell32.ShellExecuteExW.argtypes = [ctypes.POINTER(SHELLEXECUTEINFOW)]
|
||||
if not shell32.ShellExecuteExW(ctypes.byref(info)):
|
||||
err = ctypes.GetLastError()
|
||||
if err == ERROR_CANCELLED:
|
||||
return {"ok": False, "cancelled": True, "error": "cancelled at the Windows prompt"}
|
||||
return {"ok": False, "error": f"Windows error {err}"}
|
||||
try:
|
||||
kernel32.WaitForSingleObject(info.hProcess, int(timeout * 1000))
|
||||
code = wintypes.DWORD()
|
||||
kernel32.GetExitCodeProcess(info.hProcess, ctypes.byref(code))
|
||||
return {"ok": code.value == 0, "code": code.value}
|
||||
finally:
|
||||
kernel32.CloseHandle(info.hProcess)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Firewall
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
def firewall_status(port: int) -> dict:
|
||||
if not is_windows():
|
||||
return {"supported": False}
|
||||
try:
|
||||
proc = _run(["netsh", "advfirewall", "firewall", "show", "rule", f"name={RULE_NAME}"])
|
||||
except (OSError, subprocess.SubprocessError) as e:
|
||||
return {"supported": True, "exists": False, "error": str(e)}
|
||||
exists = proc.returncode == 0
|
||||
return {"supported": True, "exists": exists,
|
||||
"port_ok": exists and str(port).encode() in proc.stdout, "rule": RULE_NAME}
|
||||
|
||||
|
||||
def firewall_open(port: int, remote_ip: Optional[str] = None) -> dict:
|
||||
"""Allow inbound TCP `port` on every network profile (optionally from one address only).
|
||||
|
||||
When Windows asked "allow access?" the first time the program listened and
|
||||
somebody clicked Cancel, Windows added BLOCK rules for the program, and a
|
||||
block rule beats any allow rule — so those are removed as well.
|
||||
"""
|
||||
if not is_windows():
|
||||
return {"ok": False, "error": "Windows only"}
|
||||
port = int(port)
|
||||
remote = f" remoteip={remote_ip}" if remote_ip else ""
|
||||
steps = [f'netsh advfirewall firewall delete rule name="{RULE_NAME}" >nul 2>&1']
|
||||
if is_frozen():
|
||||
steps.append(f'netsh advfirewall firewall delete rule name=all program="{sys.executable}" >nul 2>&1')
|
||||
steps.append(f'netsh advfirewall firewall add rule name="{RULE_NAME}" dir=in action=allow '
|
||||
f'protocol=TCP localport={port} profile=any{remote} '
|
||||
f'description="{PRODUCT}: lets other machines read the scales on this PC"')
|
||||
result = run_elevated(os.environ.get("COMSPEC", "cmd.exe"), "/c " + " & ".join(steps))
|
||||
result["status"] = firewall_status(port)
|
||||
result["ok"] = bool(result["status"].get("port_ok"))
|
||||
return result
|
||||
|
||||
|
||||
def firewall_close() -> dict:
|
||||
if not is_windows():
|
||||
return {"ok": False, "error": "Windows only"}
|
||||
return run_elevated("netsh", f'advfirewall firewall delete rule name="{RULE_NAME}"')
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Start with Windows
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
def _xml_escape(text: str) -> str:
|
||||
return (text.replace("&", "&").replace("<", "<").replace(">", ">")
|
||||
.replace('"', """))
|
||||
|
||||
|
||||
def task_xml(exe: str, arguments: str, workdir: str) -> str:
|
||||
return f"""<?xml version="1.0" encoding="UTF-16"?>
|
||||
<Task version="1.2" xmlns="http://schemas.microsoft.com/windows/2004/02/mit/task">
|
||||
<RegistrationInfo>
|
||||
<Description>{_xml_escape(PRODUCT)}: serves the scales on this PC to the network.</Description>
|
||||
</RegistrationInfo>
|
||||
<Triggers>
|
||||
<BootTrigger>
|
||||
<Enabled>true</Enabled>
|
||||
<Delay>PT20S</Delay>
|
||||
</BootTrigger>
|
||||
</Triggers>
|
||||
<Principals>
|
||||
<Principal id="Author">
|
||||
<UserId>S-1-5-18</UserId>
|
||||
<RunLevel>HighestAvailable</RunLevel>
|
||||
</Principal>
|
||||
</Principals>
|
||||
<Settings>
|
||||
<MultipleInstancesPolicy>IgnoreNew</MultipleInstancesPolicy>
|
||||
<DisallowStartIfOnBatteries>false</DisallowStartIfOnBatteries>
|
||||
<StopIfGoingOnBatteries>false</StopIfGoingOnBatteries>
|
||||
<AllowHardTerminate>true</AllowHardTerminate>
|
||||
<StartWhenAvailable>true</StartWhenAvailable>
|
||||
<RunOnlyIfNetworkAvailable>false</RunOnlyIfNetworkAvailable>
|
||||
<IdleSettings>
|
||||
<StopOnIdleEnd>false</StopOnIdleEnd>
|
||||
<RestartOnIdle>false</RestartOnIdle>
|
||||
</IdleSettings>
|
||||
<AllowStartOnDemand>true</AllowStartOnDemand>
|
||||
<Enabled>true</Enabled>
|
||||
<Hidden>false</Hidden>
|
||||
<RunOnlyIfIdle>false</RunOnlyIfIdle>
|
||||
<WakeToRun>false</WakeToRun>
|
||||
<ExecutionTimeLimit>PT0S</ExecutionTimeLimit>
|
||||
<Priority>6</Priority>
|
||||
<RestartOnFailure>
|
||||
<Interval>PT1M</Interval>
|
||||
<Count>999</Count>
|
||||
</RestartOnFailure>
|
||||
</Settings>
|
||||
<Actions Context="Author">
|
||||
<Exec>
|
||||
<Command>{_xml_escape(exe)}</Command>
|
||||
<Arguments>{_xml_escape(arguments)}</Arguments>
|
||||
<WorkingDirectory>{_xml_escape(workdir)}</WorkingDirectory>
|
||||
</Exec>
|
||||
</Actions>
|
||||
</Task>
|
||||
"""
|
||||
|
||||
|
||||
def autostart_status() -> dict:
|
||||
if not is_windows():
|
||||
return {"supported": False}
|
||||
try:
|
||||
proc = _run(["schtasks", "/Query", "/TN", TASK_NAME, "/XML"])
|
||||
except (OSError, subprocess.SubprocessError) as e:
|
||||
return {"supported": True, "enabled": False, "error": str(e)}
|
||||
if proc.returncode != 0:
|
||||
return {"supported": True, "enabled": False, "task": TASK_NAME}
|
||||
xml = proc.stdout.decode("utf-16", errors="ignore") if proc.stdout[:2] in (b"\xff\xfe", b"\xfe\xff") \
|
||||
else proc.stdout.decode("utf-8", errors="ignore")
|
||||
exe, _, _ = program_command("")
|
||||
return {"supported": True, "enabled": True, "task": TASK_NAME,
|
||||
"this_program": exe.lower() in xml.lower()}
|
||||
|
||||
|
||||
def autostart_enable(config_path: str) -> dict:
|
||||
if not is_windows():
|
||||
return {"ok": False, "error": "Windows only"}
|
||||
exe, arguments, workdir = program_command(f'--service --config "{config_path}"')
|
||||
fd, xml_path = tempfile.mkstemp(prefix="scale-bridge-task-", suffix=".xml")
|
||||
with os.fdopen(fd, "wb") as f:
|
||||
f.write(task_xml(exe, arguments, workdir).encode("utf-16"))
|
||||
try:
|
||||
result = run_elevated("schtasks", f'/Create /TN "{TASK_NAME}" /XML "{xml_path}" /F')
|
||||
finally:
|
||||
try:
|
||||
os.remove(xml_path)
|
||||
except OSError:
|
||||
pass
|
||||
result["status"] = autostart_status()
|
||||
result["ok"] = bool(result["status"].get("enabled"))
|
||||
return result
|
||||
|
||||
|
||||
def autostart_disable() -> dict:
|
||||
if not is_windows():
|
||||
return {"ok": False, "error": "Windows only"}
|
||||
result = run_elevated("schtasks", f'/Delete /TN "{TASK_NAME}" /F')
|
||||
result["status"] = autostart_status()
|
||||
result["ok"] = not result["status"].get("enabled")
|
||||
return result
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Network and desktop
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
def lan_addresses() -> list[str]:
|
||||
found = set()
|
||||
try:
|
||||
with socket.socket(socket.AF_INET, socket.SOCK_DGRAM) as s:
|
||||
s.connect(("10.255.255.255", 1))
|
||||
found.add(s.getsockname()[0])
|
||||
except OSError:
|
||||
pass
|
||||
try:
|
||||
for ip in socket.gethostbyname_ex(socket.gethostname())[2]:
|
||||
if not ip.startswith("127."):
|
||||
found.add(ip)
|
||||
except OSError:
|
||||
pass
|
||||
return sorted(found)
|
||||
|
||||
|
||||
def open_browser(url: str) -> None:
|
||||
try:
|
||||
webbrowser.open(url, new=1)
|
||||
except Exception: # noqa: BLE001
|
||||
log.info("open %s in a browser", url)
|
||||
+77
@@ -0,0 +1,77 @@
|
||||
# SPDX-License-Identifier: GPL-3.0-or-later
|
||||
# Copyright (C) 2026 Farshad Zamani - Cloudtart (https://cloudtart.com)
|
||||
"""
|
||||
Build dist/SyncPulseScaleBridge.exe — one file, nothing to install.
|
||||
|
||||
python scripts/build.py (needs: pip install -r requirements-dev.txt)
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import hashlib
|
||||
import os
|
||||
import subprocess
|
||||
import sys
|
||||
|
||||
ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
|
||||
sys.path.insert(0, ROOT)
|
||||
|
||||
from scale_bridge import ABOUT, COMPANY, EXE_NAME, PRODUCT, __version__ # noqa: E402
|
||||
|
||||
|
||||
def version_file(path: str) -> None:
|
||||
parts = [int(p) for p in __version__.split(".")[:3]] + [0]
|
||||
numbers = ", ".join(str(n) for n in (parts + [0, 0, 0, 0])[:4])
|
||||
strings = {
|
||||
"CompanyName": COMPANY,
|
||||
"FileDescription": f"{PRODUCT} - RS-232 scale reader and network bridge",
|
||||
"FileVersion": __version__,
|
||||
"InternalName": EXE_NAME,
|
||||
"LegalCopyright": f"{ABOUT['copyright']}. Licensed under {ABOUT['license']}.",
|
||||
"OriginalFilename": f"{EXE_NAME}.exe",
|
||||
"ProductName": PRODUCT,
|
||||
"ProductVersion": __version__,
|
||||
"Comments": f"Author: {ABOUT['author']} - {ABOUT['website']} - {ABOUT['repository']}",
|
||||
}
|
||||
entries = ",\n".join(f" StringStruct({k!r}, {v!r})" for k, v in strings.items())
|
||||
text = f"""# UTF-8
|
||||
VSVersionInfo(
|
||||
ffi=FixedFileInfo(filevers=({numbers}), prodvers=({numbers}), mask=0x3f, flags=0x0,
|
||||
OS=0x40004, fileType=0x1, subtype=0x0, date=(0, 0)),
|
||||
kids=[
|
||||
StringFileInfo([
|
||||
StringTable('040904B0', [
|
||||
{entries}
|
||||
])
|
||||
]),
|
||||
VarFileInfo([VarStruct('Translation', [1033, 1200])])
|
||||
]
|
||||
)
|
||||
"""
|
||||
with open(path, "w", encoding="utf-8") as f:
|
||||
f.write(text)
|
||||
|
||||
|
||||
def main() -> int:
|
||||
build = os.path.join(ROOT, "build")
|
||||
os.makedirs(build, exist_ok=True)
|
||||
icon = os.path.join(ROOT, "assets", "icon.ico")
|
||||
if not os.path.exists(icon):
|
||||
subprocess.check_call([sys.executable, os.path.join(ROOT, "scripts", "make_icon.py")])
|
||||
vfile = os.path.join(build, "version_info.txt")
|
||||
version_file(vfile)
|
||||
cmd = [sys.executable, "-m", "PyInstaller", "--noconfirm", "--clean", "--onefile", "--console",
|
||||
"--name", EXE_NAME, "--icon", icon, "--version-file", vfile,
|
||||
"--distpath", os.path.join(ROOT, "dist"), "--workpath", os.path.join(build, "pyinstaller"),
|
||||
"--specpath", build, os.path.join(ROOT, "run_bridge.py")]
|
||||
subprocess.check_call(cmd, cwd=ROOT)
|
||||
exe = os.path.join(ROOT, "dist", EXE_NAME + (".exe" if os.name == "nt" else ""))
|
||||
with open(exe, "rb") as f:
|
||||
digest = hashlib.sha256(f.read()).hexdigest()
|
||||
with open(exe + ".sha256", "w", encoding="ascii", newline="\n") as f:
|
||||
f.write(f"{digest} {os.path.basename(exe)}\n")
|
||||
print(f"\nbuilt {exe}\nSHA-256 {digest}")
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
@@ -0,0 +1,26 @@
|
||||
@echo off
|
||||
rem SyncPulse Scale Bridge - build dist\SyncPulseScaleBridge.exe
|
||||
rem Copyright (C) 2026 Farshad Zamani - Cloudtart (https://cloudtart.com) - GPL-3.0-or-later
|
||||
setlocal
|
||||
cd /d "%~dp0\.."
|
||||
|
||||
if "%PYTHON%"=="" (
|
||||
where py >nul 2>&1 && (set "PYTHON=py -3") || (set "PYTHON=python")
|
||||
)
|
||||
|
||||
if not exist .venv\Scripts\python.exe (
|
||||
echo Creating .venv ...
|
||||
%PYTHON% -m venv .venv || goto :error
|
||||
)
|
||||
.venv\Scripts\python.exe -m pip install --quiet --upgrade pip || goto :error
|
||||
.venv\Scripts\python.exe -m pip install --quiet -r requirements-dev.txt || goto :error
|
||||
.venv\Scripts\python.exe -m pytest -q || goto :error
|
||||
.venv\Scripts\python.exe scripts\build.py || goto :error
|
||||
echo.
|
||||
echo Done: dist\SyncPulseScaleBridge.exe
|
||||
exit /b 0
|
||||
|
||||
:error
|
||||
echo.
|
||||
echo Build failed.
|
||||
exit /b 1
|
||||
+114
@@ -0,0 +1,114 @@
|
||||
# SPDX-License-Identifier: GPL-3.0-or-later
|
||||
# Copyright (C) 2026 Farshad Zamani - Cloudtart (https://cloudtart.com)
|
||||
"""Draw the program icon (a platform scale with a display) into assets/icon.ico — standard library only."""
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
import struct
|
||||
import sys
|
||||
import zlib
|
||||
|
||||
TEAL = (15, 118, 110)
|
||||
DARK = (8, 64, 60)
|
||||
WHITE = (255, 255, 255)
|
||||
|
||||
|
||||
def _in_round_rect(x, y, x0, y0, x1, y1, r):
|
||||
if not (x0 <= x <= x1 and y0 <= y <= y1):
|
||||
return False
|
||||
cx = min(max(x, x0 + r), x1 - r)
|
||||
cy = min(max(y, y0 + r), y1 - r)
|
||||
return (x - cx) ** 2 + (y - cy) ** 2 <= r * r
|
||||
|
||||
|
||||
def _in_trapezoid(x, y, top, bottom, top_x0, top_x1, bottom_x0, bottom_x1):
|
||||
if not (top <= y <= bottom):
|
||||
return False
|
||||
f = (y - top) / (bottom - top)
|
||||
return top_x0 + (bottom_x0 - top_x0) * f <= x <= top_x1 + (bottom_x1 - top_x1) * f
|
||||
|
||||
|
||||
def colour_at(x, y):
|
||||
"""Colour of the 64x64 design at (x, y), or None outside the icon."""
|
||||
if not _in_round_rect(x, y, 0, 0, 64, 64, 14):
|
||||
return None
|
||||
if _in_round_rect(x, y, 23, 34, 41, 42, 2): # display window
|
||||
if _in_round_rect(x, y, 26, 37, 38, 39, 1): # the reading
|
||||
return WHITE
|
||||
return DARK
|
||||
if _in_round_rect(x, y, 11, 13, 53, 19, 2.5): # weighing plate
|
||||
return WHITE
|
||||
if 29 <= x <= 35 and 19 <= y <= 28: # column
|
||||
return WHITE
|
||||
if _in_trapezoid(x, y, 27, 51, 18, 46, 13, 51): # body
|
||||
return WHITE
|
||||
return TEAL
|
||||
|
||||
|
||||
def render(size: int, samples: int = 4) -> list[list[tuple[int, int, int, int]]]:
|
||||
rows = []
|
||||
step = 64 / size
|
||||
for py in range(size):
|
||||
row = []
|
||||
for px in range(size):
|
||||
acc = [0, 0, 0]
|
||||
covered = 0
|
||||
for sy in range(samples):
|
||||
for sx in range(samples):
|
||||
c = colour_at((px + (sx + 0.5) / samples) * step, (py + (sy + 0.5) / samples) * step)
|
||||
if c is not None:
|
||||
covered += 1
|
||||
acc[0] += c[0]
|
||||
acc[1] += c[1]
|
||||
acc[2] += c[2]
|
||||
if covered:
|
||||
row.append((acc[0] // covered, acc[1] // covered, acc[2] // covered,
|
||||
round(255 * covered / samples ** 2)))
|
||||
else:
|
||||
row.append((0, 0, 0, 0))
|
||||
rows.append(row)
|
||||
return rows
|
||||
|
||||
|
||||
def png(rows) -> bytes:
|
||||
h, w = len(rows), len(rows[0])
|
||||
raw = b"".join(b"\x00" + bytes(v for px in row for v in px) for row in rows)
|
||||
|
||||
def chunk(tag, data):
|
||||
return struct.pack(">I", len(data)) + tag + data + struct.pack(">I", zlib.crc32(tag + data) & 0xFFFFFFFF)
|
||||
return (b"\x89PNG\r\n\x1a\n" + chunk(b"IHDR", struct.pack(">IIBBBBB", w, h, 8, 6, 0, 0, 0))
|
||||
+ chunk(b"IDAT", zlib.compress(raw, 9)) + chunk(b"IEND", b""))
|
||||
|
||||
|
||||
def dib(rows) -> bytes:
|
||||
h, w = len(rows), len(rows[0])
|
||||
header = struct.pack("<IiiHHIIiiII", 40, w, h * 2, 1, 32, 0, 0, 0, 0, 0, 0)
|
||||
pixels = b"".join(bytes((b, g, r, a)) for row in reversed(rows) for (r, g, b, a) in row)
|
||||
mask_row = ((w + 31) // 32) * 4
|
||||
return header + pixels + b"\x00" * mask_row * h
|
||||
|
||||
|
||||
def ico(sizes=(16, 24, 32, 48, 64, 256)) -> bytes:
|
||||
images = [(s, png(render(s)) if s >= 256 else dib(render(s))) for s in sizes]
|
||||
out = struct.pack("<HHH", 0, 1, len(images))
|
||||
offset = 6 + 16 * len(images)
|
||||
for s, data in images:
|
||||
out += struct.pack("<BBBBHHII", s % 256, s % 256, 0, 0, 1, 32, len(data), offset)
|
||||
offset += len(data)
|
||||
return out + b"".join(d for _, d in images)
|
||||
|
||||
|
||||
def main() -> int:
|
||||
root = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
|
||||
target = os.path.join(root, "assets", "icon.ico")
|
||||
os.makedirs(os.path.dirname(target), exist_ok=True)
|
||||
with open(target, "wb") as f:
|
||||
f.write(ico())
|
||||
with open(os.path.join(root, "assets", "icon.png"), "wb") as f:
|
||||
f.write(png(render(256)))
|
||||
print(target)
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
@@ -0,0 +1,12 @@
|
||||
43 4C 53 0D 0A 53 49 5A 45 20 35 37 20 6D 6D 2C 20 34 30 20 6D 6D 0D 0A 47 41 50 20 32 20 6D 6D 2C 30 0D 0A 44 49 52 45 43 54 49 4F 4E 20 31 0D 0A 52 45 46 45 52 45 4E 43 45 20 30 2C 30 0D 0A 43 4F 44 45 50 41 47 45 20 49 72 61 6E 49 49 0D 0A 54 45 58 54 20 33 30 30 2C 32 35 30 2C 22 31 30 22 2C 32 37 30 2C 31 2C 31 2C 22 4E 6F 3A 20 36 20 53 48 49 46 54 3A 32 22 0D 0A 54 45 58 54 20 30 33 30 2C 32 33 35 2C 22 31 30 22 2C 30 2C 31 2C 32 2C 22 4F 72 64 65 72 2E 43 6F 20 3A 20 20 20 32 32 32 0D 0A 54 45 58 54 20 30 33 30 2C 30 38 30 2C 22 31 30 22 2C 30 2C 31 2C 32 2C 22 31 34 30 35 2F 30 37 2F 31 39 20 2D 20 31 36 3A 33 39 22 0D 0A 54 45 58 54 20 30 33 30 2C 31 36 30 2C 22 31 30 22 2C 30 2C 31 2C 32 2C 22 54 68 69 63 6B 6E 65 73 73 20 3A 20 30 2E 30 22 0D 0A 43 4F 44 45 50 41 47 45 20 31 32 35 33 0D 0A 54 45 58 54 20 32 32 30 2C 31 36 30 2C 22 31 30 22 2C 30 2C 31 2C 32 2C 22 E6 22 0D 0A 43 4F 44 45 50 41 47 45 20 49 72 61 6E 49 49 0D 0A 54 45 58 54 20 30 32 30 2C 30 30 30 2C 22 31 30 22 2C 30 2C 32 2C 32 2C 22 31 30 32 2E 33 30 30 22 0D 0A 54 45 58 54 20 32 30 30 2C 30 31 35 2C 22 31 30 22 2C 30 2C 32 2C 31 2C 22 28 4B 67 29 22 0D 0A 42 41 52 43 4F 44 45 20 33 35 30 2C 32 38 30 2C 20 22 31 32 38 22 2C 30 37 30 2C 31 2C 32 37 30 2C 32 2C 32 2C 20 22 20 20 32 32 32 09 31 30 32 2E 33 30 30 22 0D 0A 50 52 49 4E 54 20 31 0D 0A 0D 0A
|
||||
43 4C 53 0D 0A 53 49 5A 45 20 35 37 20 6D 6D 2C 20 34 30 20 6D 6D 0D 0A 47 41 50 20 32 20 6D 6D 2C 30 0D 0A 44 49 52 45 43 54 49 4F 4E 20 31 0D 0A 52 45 46 45 52 45 4E 43 45 20 30 2C 30 0D 0A 43 4F 44 45 50 41 47 45 20 49 72 61 6E 49 49 0D 0A 54 45 58 54 20 33 30 30 2C 32 35 30 2C 22 31 30 22 2C 32 37 30 2C 31 2C 31 2C 22 4E 6F 3A 20 36 20 53 48 49 46 54 3A 32 22 0D 0A 54 45 58 54 20 30 33 30 2C 32 33 35 2C 22 31 30 22 2C 30 2C 31 2C 32 2C 22 4F 72 64 65 72 2E 43 6F 20 3A 20 20 20 20 20 30 0D 0A 54 45 58 54 20 30 33 30 2C 30 38 30 2C 22 31 30 22 2C 30 2C 31 2C 32 2C 22 31 34 30 35 2F 30 37 2F 31 39 20 2D 20 31 36 3A 34 31 22 0D 0A 54 45 58 54 20 30 33 30 2C 31 36 30 2C 22 31 30 22 2C 30 2C 31 2C 32 2C 22 54 68 69 63 6B 6E 65 73 73 20 3A 20 30 2E 30 22 0D 0A 43 4F 44 45 50 41 47 45 20 31 32 35 33 0D 0A 54 45 58 54 20 32 32 30 2C 31 36 30 2C 22 31 30 22 2C 30 2C 31 2C 32 2C 22 E6 22 0D 0A 43 4F 44 45 50 41 47 45 20 49 72 61 6E 49 49 0D 0A 54 45 58 54 20 30 32 30 2C 30 30 30 2C 22 31 30 22 2C 30 2C 32 2C 32 2C 22 31 34 31 2E 38 30 30 22 0D 0A 54 45 58 54 20 32 30 30 2C 30 31 35 2C 22 31 30 22 2C 30 2C 32 2C 31 2C 22 28 4B 67 29 22 0D 0A 42 41 52 43 4F 44 45 20 33 35 30 2C 32 38 30 2C 20 22 31 32 38 22 2C 30 37 30 2C 31 2C 32 37 30 2C 32 2C 32 2C 20 22 20 20 20 20 30 09 31 34 31 2E 38 30 30 22 0D 0A 50 52 49 4E 54 20 31 0D 0A 0D 0A
|
||||
43 4C 53 0D 0A 53 49 5A 45 20 35 37 20 6D 6D 2C 20 34 30 20 6D 6D 0D 0A 47 41 50 20 32 20 6D 6D 2C 30 0D 0A 44 49 52 45 43 54 49 4F 4E 20 31 0D 0A 52 45 46 45 52 45 4E 43 45 20 30 2C 30 0D 0A 43 4F 44 45 50 41 47 45 20 49 72 61 6E 49 49 0D 0A 54 45 58 54 20 33 30 30 2C 32 35 30 2C 22 31 30 22 2C 32 37 30 2C 31 2C 31 2C 22 4E 6F 3A 20 36 20 53 48 49 46 54 3A 32 22 0D 0A 54 45 58 54 20 30 33 30 2C 32 33 35 2C 22 31 30 22 2C 30 2C 31 2C 32 2C 22 4F 72 64 65 72 2E 43 6F 20 3A 20 20 20 20 20 30 0D 0A 54 45 58 54 20 30 33 30 2C 30 38 30 2C 22 31 30 22 2C 30 2C 31 2C 32 2C 22 31 34 30 35 2F 30 37 2F 31 39 20 2D 20 31 36 3A 34 31 22 0D 0A 54 45 58 54 20 30 33 30 2C 31 36 30 2C 22 31 30 22 2C 30 2C 31 2C 32 2C 22 54 68 69 63 6B 6E 65 73 73 20 3A 20 33 2E 33 22 0D 0A 43 4F 44 45 50 41 47 45 20 31 32 35 33 0D 0A 54 45 58 54 20 32 32 30 2C 31 36 30 2C 22 31 30 22 2C 30 2C 31 2C 32 2C 22 E6 22 0D 0A 43 4F 44 45 50 41 47 45 20 49 72 61 6E 49 49 0D 0A 54 45 58 54 20 30 32 30 2C 30 30 30 2C 22 31 30 22 2C 30 2C 32 2C 32 2C 22 31 34 31 2E 32 30 30 22 0D 0A 54 45 58 54 20 32 30 30 2C 30 31 35 2C 22 31 30 22 2C 30 2C 32 2C 31 2C 22 28 4B 67 29 22 0D 0A 42 41 52 43 4F 44 45 20 33 35 30 2C 32 38 30 2C 20 22 31 32 38 22 2C 30 37 30 2C 31 2C 32 37 30 2C 32 2C 32 2C 20 22 20 20 20 20 30 09 31 34 31 2E 32 30 30 22 0D 0A 50 52 49 4E 54 20 31 0D 0A 0D 0A
|
||||
43 4C 53 0D 0A 53 49 5A 45 20 35 37 20 6D 6D 2C 20 34 30 20 6D 6D 0D 0A 47 41 50 20 32 20 6D 6D 2C 30 0D 0A 44 49 52 45 43 54 49 4F 4E 20 31 0D 0A 52 45 46 45 52 45 4E 43 45 20 30 2C 30 0D 0A 43 4F 44 45 50 41 47 45 20 49 72 61 6E 49 49 0D 0A 54 45 58 54 20 33 30 30 2C 32 35 30 2C 22 31 30 22 2C 32 37 30 2C 31 2C 31 2C 22 4E 6F 3A 20 36 20 53 48 49 46 54 3A 32 22 0D 0A 54 45 58 54 20 30 33 30 2C 32 33 35 2C 22 31 30 22 2C 30 2C 31 2C 32 2C 22 4F 72 64 65 72 2E 43 6F 20 3A 20 20 20 32 32 32 0D 0A 54 45 58 54 20 30 33 30 2C 30 38 30 2C 22 31 30 22 2C 30 2C 31 2C 32 2C 22 31 34 30 35 2F 30 37 2F 31 39 20 2D 20 31 36 3A 34 34 22 0D 0A 54 45 58 54 20 30 33 30 2C 31 36 30 2C 22 31 30 22 2C 30 2C 31 2C 32 2C 22 54 68 69 63 6B 6E 65 73 73 20 3A 20 30 2E 30 22 0D 0A 43 4F 44 45 50 41 47 45 20 31 32 35 33 0D 0A 54 45 58 54 20 32 32 30 2C 31 36 30 2C 22 31 30 22 2C 30 2C 31 2C 32 2C 22 E6 22 0D 0A 43 4F 44 45 50 41 47 45 20 49 72 61 6E 49 49 0D 0A 54 45 58 54 20 30 32 30 2C 30 30 30 2C 22 31 30 22 2C 30 2C 32 2C 32 2C 22 20 20 31 2E 34 30 30 22 0D 0A 54 45 58 54 20 32 30 30 2C 30 31 35 2C 22 31 30 22 2C 30 2C 32 2C 31 2C 22 28 4B 67 29 22 0D 0A 42 41 52 43 4F 44 45 20 33 35 30 2C 32 38 30 2C 20 22 31 32 38 22 2C 30 37 30 2C 31 2C 32 37 30 2C 32 2C 32 2C 20 22 20 20 32 32 32 09 20 20 31 2E 34 30 30 22 0D 0A 50 52 49 4E 54 20 31 0D 0A 0D 0A
|
||||
43 4C 53 0D 0A 53 49 5A 45 20 35 37 20 6D 6D 2C 20 34 30 20 6D 6D 0D 0A 47 41 50 20 32 20 6D 6D 2C 30 0D 0A 44 49 52 45 43 54 49 4F 4E 20 31 0D 0A 52 45 46 45 52 45 4E 43 45 20 30 2C 30 0D 0A 43 4F 44 45 50 41 47 45 20 49 72 61 6E 49 49 0D 0A 54 45 58 54 20 33 30 30 2C 32 35 30 2C 22 31 30 22 2C 32 37 30 2C 31 2C 31 2C 22 4E 6F 3A 20 36 20 53 48 49 46 54 3A 32 22 0D 0A 54 45 58 54 20 30 33 30 2C 32 33 35 2C 22 31 30 22 2C 30 2C 31 2C 32 2C 22 4F 72 64 65 72 2E 43 6F 20 3A 20 20 20 32 32 32 0D 0A 54 45 58 54 20 30 33 30 2C 30 38 30 2C 22 31 30 22 2C 30 2C 31 2C 32 2C 22 31 34 30 35 2F 30 37 2F 31 39 20 2D 20 31 36 3A 34 34 22 0D 0A 54 45 58 54 20 30 33 30 2C 31 36 30 2C 22 31 30 22 2C 30 2C 31 2C 32 2C 22 54 68 69 63 6B 6E 65 73 73 20 3A 20 30 2E 30 22 0D 0A 43 4F 44 45 50 41 47 45 20 31 32 35 33 0D 0A 54 45 58 54 20 32 32 30 2C 31 36 30 2C 22 31 30 22 2C 30 2C 31 2C 32 2C 22 E6 22 0D 0A 43 4F 44 45 50 41 47 45 20 49 72 61 6E 49 49 0D 0A 54 45 58 54 20 30 32 30 2C 30 30 30 2C 22 31 30 22 2C 30 2C 32 2C 32 2C 22 20 20 31 2E 34 30 30 22 0D 0A 54 45 58 54 20 32 30 30 2C 30 31 35 2C 22 31 30 22 2C 30 2C 32 2C 31 2C 22 28 4B 67 29 22 0D 0A 42 41 52 43 4F 44 45 20 33 35 30 2C 32 38 30 2C 20 22 31 32 38 22 2C 30 37 30 2C 31 2C 32 37 30 2C 32 2C 32 2C 20 22 20 20 32 32 32 09 20 20 31 2E 34 30 30 22 0D 0A 50 52 49 4E 54 20 31 0D 0A 0D 0A
|
||||
43 4C 53 0D 0A 53 49 5A 45 20 35 37 20 6D 6D 2C 20 34 30 20 6D 6D 0D 0A 47 41 50 20 32 20 6D 6D 2C 30 0D 0A 44 49 52 45 43 54 49 4F 4E 20 31 0D 0A 52 45 46 45 52 45 4E 43 45 20 30 2C 30 0D 0A 43 4F 44 45 50 41 47 45 20 49 72 61 6E 49 49 0D 0A 54 45 58 54 20 33 30 30 2C 32 35 30 2C 22 31 30 22 2C 32 37 30 2C 31 2C 31 2C 22 4E 6F 3A 20 36 20 53 48 49 46 54 3A 32 22 0D 0A 54 45 58 54 20 30 33 30 2C 32 33 35 2C 22 31 30 22 2C 30 2C 31 2C 32 2C 22 4F 72 64 65 72 2E 43 6F 20 3A 20 20 20 32 32 32 0D 0A 54 45 58 54 20 30 33 30 2C 30 38 30 2C 22 31 30 22 2C 30 2C 31 2C 32 2C 22 31 34 30 35 2F 30 37 2F 31 39 20 2D 20 31 36 3A 34 34 22 0D 0A 54 45 58 54 20 30 33 30 2C 31 36 30 2C 22 31 30 22 2C 30 2C 31 2C 32 2C 22 54 68 69 63 6B 6E 65 73 73 20 3A 20 30 2E 30 22 0D 0A 43 4F 44 45 50 41 47 45 20 31 32 35 33 0D 0A 54 45 58 54 20 32 32 30 2C 31 36 30 2C 22 31 30 22 2C 30 2C 31 2C 32 2C 22 E6 22 0D 0A 43 4F 44 45 50 41 47 45 20 49 72 61 6E 49 49 0D 0A 54 45 58 54 20 30 32 30 2C 30 30 30 2C 22 31 30 22 2C 30 2C 32 2C 32 2C 22 20 20 31 2E 33 35 30 22 0D 0A 54 45 58 54 20 32 30 30 2C 30 31 35 2C 22 31 30 22 2C 30 2C 32 2C 31 2C 22 28 4B 67 29 22 0D 0A 42 41 52 43 4F 44 45 20 33 35 30 2C 32 38 30 2C 20 22 31 32 38 22 2C 30 37 30 2C 31 2C 32 37 30 2C 32 2C 32 2C 20 22 20 20 32 32 32 09 20 20 31 2E 33 35 30 22 0D 0A 50 52 49 4E 54 20 31 0D 0A 0D 0A
|
||||
43 4C 53 0D 0A 53 49 5A 45 20 35 37 20 6D 6D 2C 20 34 30 20 6D 6D 0D 0A 47 41 50 20 32 20 6D 6D 2C 30 0D 0A 44 49 52 45 43 54 49 4F 4E 20 31 0D 0A 52 45 46 45 52 45 4E 43 45 20 30 2C 30 0D 0A 43 4F 44 45 50 41 47 45 20 49 72 61 6E 49 49 0D 0A 54 45 58 54 20 33 30 30 2C 32 35 30 2C 22 31 30 22 2C 32 37 30 2C 31 2C 31 2C 22 4E 6F 3A 20 36 20 53 48 49 46 54 3A 32 22 0D 0A 54 45 58 54 20 30 33 30 2C 32 33 35 2C 22 31 30 22 2C 30 2C 31 2C 32 2C 22 4F 72 64 65 72 2E 43 6F 20 3A 20 20 20 32 32 32 0D 0A 54 45 58 54 20 30 33 30 2C 30 38 30 2C 22 31 30 22 2C 30 2C 31 2C 32 2C 22 31 34 30 35 2F 30 37 2F 31 39 20 2D 20 31 36 3A 34 34 22 0D 0A 54 45 58 54 20 30 33 30 2C 31 36 30 2C 22 31 30 22 2C 30 2C 31 2C 32 2C 22 54 68 69 63 6B 6E 65 73 73 20 3A 20 30 2E 30 22 0D 0A 43 4F 44 45 50 41 47 45 20 31 32 35 33 0D 0A 54 45 58 54 20 32 32 30 2C 31 36 30 2C 22 31 30 22 2C 30 2C 31 2C 32 2C 22 E6 22 0D 0A 43 4F 44 45 50 41 47 45 20 49 72 61 6E 49 49 0D 0A 54 45 58 54 20 30 32 30 2C 30 30 30 2C 22 31 30 22 2C 30 2C 32 2C 32 2C 22 20 20 31 2E 33 30 30 22 0D 0A 54 45 58 54 20 32 30 30 2C 30 31 35 2C 22 31 30 22 2C 30 2C 32 2C 31 2C 22 28 4B 67 29 22 0D 0A 42 41 52 43 4F 44 45 20 33 35 30 2C 32 38 30 2C 20 22 31 32 38 22 2C 30 37 30 2C 31 2C 32 37 30 2C 32 2C 32 2C 20 22 20 20 32 32 32 09 20 20 31 2E 33 30 30 22 0D 0A 50 52 49 4E 54 20 31 0D 0A 0D 0A
|
||||
43 4C 53 0D 0A 53 49 5A 45 20 35 37 20 6D 6D 2C 20 34 30 20 6D 6D 0D 0A 47 41 50 20 32 20 6D 6D 2C 30 0D 0A 44 49 52 45 43 54 49 4F 4E 20 31 0D 0A 52 45 46 45 52 45 4E 43 45 20 30 2C 30 0D 0A 43 4F 44 45 50 41 47 45 20 49 72 61 6E 49 49 0D 0A 54 45 58 54 20 33 30 30 2C 32 35 30 2C 22 31 30 22 2C 32 37 30 2C 31 2C 31 2C 22 4E 6F 3A 20 36 20 53 48 49 46 54 3A 32 22 0D 0A 54 45 58 54 20 30 33 30 2C 32 33 35 2C 22 31 30 22 2C 30 2C 31 2C 32 2C 22 4F 72 64 65 72 2E 43 6F 20 3A 20 20 20 32 32 32 0D 0A 54 45 58 54 20 30 33 30 2C 30 38 30 2C 22 31 30 22 2C 30 2C 31 2C 32 2C 22 31 34 30 35 2F 30 37 2F 31 39 20 2D 20 31 36 3A 34 35 22 0D 0A 54 45 58 54 20 30 33 30 2C 31 36 30 2C 22 31 30 22 2C 30 2C 31 2C 32 2C 22 54 68 69 63 6B 6E 65 73 73 20 3A 20 30 2E 30 22 0D 0A 43 4F 44 45 50 41 47 45 20 31 32 35 33 0D 0A 54 45 58 54 20 32 32 30 2C 31 36 30 2C 22 31 30 22 2C 30 2C 31 2C 32 2C 22 E6 22 0D 0A 43 4F 44 45 50 41 47 45 20 49 72 61 6E 49 49 0D 0A 54 45 58 54 20 30 32 30 2C 30 30 30 2C 22 31 30 22 2C 30 2C 32 2C 32 2C 22 20 20 31 2E 32 35 30 22 0D 0A 54 45 58 54 20 32 30 30 2C 30 31 35 2C 22 31 30 22 2C 30 2C 32 2C 31 2C 22 28 4B 67 29 22 0D 0A 42 41 52 43 4F 44 45 20 33 35 30 2C 32 38 30 2C 20 22 31 32 38 22 2C 30 37 30 2C 31 2C 32 37 30 2C 32 2C 32 2C 20 22 20 20 32 32 32 09 20 20 31 2E 32 35 30 22 0D 0A 50 52 49 4E 54 20 31 0D 0A 0D 0A
|
||||
43 4C 53 0D 0A 53 49 5A 45 20 35 37 20 6D 6D 2C 20 34 30 20 6D 6D 0D 0A 47 41 50 20 32 20 6D 6D 2C 30 0D 0A 44 49 52 45 43 54 49 4F 4E 20 31 0D 0A 52 45 46 45 52 45 4E 43 45 20 30 2C 30 0D 0A 43 4F 44 45 50 41 47 45 20 49 72 61 6E 49 49 0D 0A 54 45 58 54 20 33 30 30 2C 32 35 30 2C 22 31 30 22 2C 32 37 30 2C 31 2C 31 2C 22 4E 6F 3A 20 36 20 53 48 49 46 54 3A 32 22 0D 0A 54 45 58 54 20 30 33 30 2C 32 33 35 2C 22 31 30 22 2C 30 2C 31 2C 32 2C 22 4F 72 64 65 72 2E 43 6F 20 3A 20 20 20 32 32 32 0D 0A 54 45 58 54 20 30 33 30 2C 30 38 30 2C 22 31 30 22 2C 30 2C 31 2C 32 2C 22 31 34 30 35 2F 30 37 2F 31 39 20 2D 20 31 36 3A 34 35 22 0D 0A 54 45 58 54 20 30 33 30 2C 31 36 30 2C 22 31 30 22 2C 30 2C 31 2C 32 2C 22 54 68 69 63 6B 6E 65 73 73 20 3A 20 30 2E 30 22 0D 0A 43 4F 44 45 50 41 47 45 20 31 32 35 33 0D 0A 54 45 58 54 20 32 32 30 2C 31 36 30 2C 22 31 30 22 2C 30 2C 31 2C 32 2C 22 E6 22 0D 0A 43 4F 44 45 50 41 47 45 20 49 72 61 6E 49 49 0D 0A 54 45 58 54 20 30 32 30 2C 30 30 30 2C 22 31 30 22 2C 30 2C 32 2C 32 2C 22 20 20 30 2E 39 35 30 22 0D 0A 54 45 58 54 20 32 30 30 2C 30 31 35 2C 22 31 30 22 2C 30 2C 32 2C 31 2C 22 28 4B 67 29 22 0D 0A 42 41 52 43 4F 44 45 20 33 35 30 2C 32 38 30 2C 20 22 31 32 38 22 2C 30 37 30 2C 31 2C 32 37 30 2C 32 2C 32 2C 20 22 20 20 32 32 32 09 20 20 30 2E 39 35 30 22 0D 0A 50 52 49 4E 54 20 31 0D 0A 0D 0A
|
||||
43 4C 53 0D 0A 53 49 5A 45 20 35 37 20 6D 6D 2C 20 34 30 20 6D 6D 0D 0A 47 41 50 20 32 20 6D 6D 2C 30 0D 0A 44 49 52 45 43 54 49 4F 4E 20 31 0D 0A 52 45 46 45 52 45 4E 43 45 20 30 2C 30 0D 0A 43 4F 44 45 50 41 47 45 20 49 72 61 6E 49 49 0D 0A 54 45 58 54 20 33 30 30 2C 32 35 30 2C 22 31 30 22 2C 32 37 30 2C 31 2C 31 2C 22 4E 6F 3A 20 36 20 53 48 49 46 54 3A 32 22 0D 0A 54 45 58 54 20 30 33 30 2C 32 33 35 2C 22 31 30 22 2C 30 2C 31 2C 32 2C 22 4F 72 64 65 72 2E 43 6F 20 3A 20 20 20 20 20 30 0D 0A 54 45 58 54 20 30 33 30 2C 30 38 30 2C 22 31 30 22 2C 30 2C 31 2C 32 2C 22 31 34 30 35 2F 30 37 2F 31 39 20 2D 20 31 36 3A 34 35 22 0D 0A 54 45 58 54 20 30 33 30 2C 31 36 30 2C 22 31 30 22 2C 30 2C 31 2C 32 2C 22 54 68 69 63 6B 6E 65 73 73 20 3A 20 30 2E 30 22 0D 0A 43 4F 44 45 50 41 47 45 20 31 32 35 33 0D 0A 54 45 58 54 20 32 32 30 2C 31 36 30 2C 22 31 30 22 2C 30 2C 31 2C 32 2C 22 E6 22 0D 0A 43 4F 44 45 50 41 47 45 20 49 72 61 6E 49 49 0D 0A 54 45 58 54 20 30 32 30 2C 30 30 30 2C 22 31 30 22 2C 30 2C 32 2C 32 2C 22 20 20 31 2E 32 30 30 22 0D 0A 54 45 58 54 20 32 30 30 2C 30 31 35 2C 22 31 30 22 2C 30 2C 32 2C 31 2C 22 28 4B 67 29 22 0D 0A 42 41 52 43 4F 44 45 20 33 35 30 2C 32 38 30 2C 20 22 31 32 38 22 2C 30 37 30 2C 31 2C 32 37 30 2C 32 2C 32 2C 20 22 20 20 20 20 30 09 20 20 31 2E 32 30 30 22 0D 0A 50 52 49 4E 54 20 31 0D 0A 0D 0A
|
||||
43 4C 53 0D 0A 53 49 5A 45 20 35 37 20 6D 6D 2C 20 34 30 20 6D 6D 0D 0A 47 41 50 20 32 20 6D 6D 2C 30 0D 0A 44 49 52 45 43 54 49 4F 4E 20 31 0D 0A 52 45 46 45 52 45 4E 43 45 20 30 2C 30 0D 0A 43 4F 44 45 50 41 47 45 20 49 72 61 6E 49 49 0D 0A 54 45 58 54 20 33 30 30 2C 32 35 30 2C 22 31 30 22 2C 32 37 30 2C 31 2C 31 2C 22 4E 6F 3A 20 36 20 53 48 49 46 54 3A 32 22 0D 0A 54 45 58 54 20 30 33 30 2C 32 33 35 2C 22 31 30 22 2C 30 2C 31 2C 32 2C 22 4F 72 64 65 72 2E 43 6F 20 3A 20 20 20 32 32 32 0D 0A 54 45 58 54 20 30 33 30 2C 30 38 30 2C 22 31 30 22 2C 30 2C 31 2C 32 2C 22 31 34 30 35 2F 30 37 2F 31 39 20 2D 20 31 36 3A 34 35 22 0D 0A 54 45 58 54 20 30 33 30 2C 31 36 30 2C 22 31 30 22 2C 30 2C 31 2C 32 2C 22 54 68 69 63 6B 6E 65 73 73 20 3A 20 30 2E 30 22 0D 0A 43 4F 44 45 50 41 47 45 20 31 32 35 33 0D 0A 54 45 58 54 20 32 32 30 2C 31 36 30 2C 22 31 30 22 2C 30 2C 31 2C 32 2C 22 E6 22 0D 0A 43 4F 44 45 50 41 47 45 20 49 72 61 6E 49 49 0D 0A 54 45 58 54 20 30 32 30 2C 30 30 30 2C 22 31 30 22 2C 30 2C 32 2C 32 2C 22 20 20 31 2E 32 35 30 22 0D 0A 54 45 58 54 20 32 30 30 2C 30 31 35 2C 22 31 30 22 2C 30 2C 32 2C 31 2C 22 28 4B 67 29 22 0D 0A 42 41 52 43 4F 44 45 20 33 35 30 2C 32 38 30 2C 20 22 31 32 38 22 2C 30 37 30 2C 31 2C 32 37 30 2C 32 2C 32 2C 20 22 20 20 32 32 32 09 20 20 31 2E 32 35 30 22 0D 0A 50 52 49 4E 54 20 31 0D 0A 0D 0A
|
||||
43 4C 53 0D 0A 53 49 5A 45 20 35 37 20 6D 6D 2C 20 34 30 20 6D 6D 0D 0A 47 41 50 20 32 20 6D 6D 2C 30 0D 0A 44 49 52 45 43 54 49 4F 4E 20 31 0D 0A 52 45 46 45 52 45 4E 43 45 20 30 2C 30 0D 0A 43 4F 44 45 50 41 47 45 20 49 72 61 6E 49 49 0D 0A 54 45 58 54 20 33 30 30 2C 32 35 30 2C 22 31 30 22 2C 32 37 30 2C 31 2C 31 2C 22 4E 6F 3A 20 36 20 53 48 49 46 54 3A 32 22 0D 0A 54 45 58 54 20 30 33 30 2C 32 33 35 2C 22 31 30 22 2C 30 2C 31 2C 32 2C 22 4F 72 64 65 72 2E 43 6F 20 3A 20 20 20 32 32 32 0D 0A 54 45 58 54 20 30 33 30 2C 30 38 30 2C 22 31 30 22 2C 30 2C 31 2C 32 2C 22 31 34 30 35 2F 30 37 2F 31 39 20 2D 20 31 36 3A 34 35 22 0D 0A 54 45 58 54 20 30 33 30 2C 31 36 30 2C 22 31 30 22 2C 30 2C 31 2C 32 2C 22 54 68 69 63 6B 6E 65 73 73 20 3A 20 30 2E 30 22 0D 0A 43 4F 44 45 50 41 47 45 20 31 32 35 33 0D 0A 54 45 58 54 20 32 32 30 2C 31 36 30 2C 22 31 30 22 2C 30 2C 31 2C 32 2C 22 E6 22 0D 0A 43 4F 44 45 50 41 47 45 20 49 72 61 6E 49 49 0D 0A 54 45 58 54 20 30 32 30 2C 30 30 30 2C 22 31 30 22 2C 30 2C 32 2C 32 2C 22 20 20 31 2E 31 35 30 22 0D 0A 54 45 58 54 20 32 30 30 2C 30 31 35 2C 22 31 30 22 2C 30 2C 32 2C 31 2C 22 28 4B 67 29 22 0D 0A 42 41 52 43 4F 44 45 20 33 35 30 2C 32 38 30 2C 20 22 31 32 38 22 2C 30 37 30 2C 31 2C 32 37 30 2C 32 2C 32 2C 20 22 20 20 32 32 32 09 20 20 31 2E 31 35 30 22 0D 0A 50 52 49 4E 54 20 31 0D 0A 0D 0A
|
||||
+112
@@ -0,0 +1,112 @@
|
||||
# SPDX-License-Identifier: GPL-3.0-or-later
|
||||
"""Auto-detection against simulated scales that only understand their own settings."""
|
||||
import time
|
||||
|
||||
import pytest
|
||||
|
||||
from scale_bridge.detect import Detector, Timings, readability
|
||||
from scale_bridge.simulator import SimulatorBank
|
||||
|
||||
FAST = Timings(passive_s=0.5, probe_s=0.15, confirm_s=0.4, drain_s=0.02)
|
||||
|
||||
|
||||
class Silent:
|
||||
"""A port with nothing connected."""
|
||||
in_waiting = 0
|
||||
|
||||
def __init__(self, settings):
|
||||
self.settings = settings
|
||||
|
||||
def read(self, n=1):
|
||||
time.sleep(0.01)
|
||||
return b""
|
||||
|
||||
def write(self, data):
|
||||
return len(data)
|
||||
|
||||
def close(self):
|
||||
pass
|
||||
|
||||
|
||||
class Chatter(Silent):
|
||||
"""Readable text without any weight in it."""
|
||||
|
||||
def read(self, n=1):
|
||||
time.sleep(0.01)
|
||||
return b"HELLO WORLD\r\n" if self.settings.baudrate == 9600 else b""
|
||||
|
||||
@property
|
||||
def in_waiting(self):
|
||||
return 0
|
||||
|
||||
|
||||
def detect(spec, port="COM90", thorough=False):
|
||||
bank = SimulatorBank(spec)
|
||||
events = []
|
||||
result = Detector(bank.opener(), log=lambda code, **kw: events.append(code), thorough=thorough,
|
||||
timings=FAST).run_port(port)
|
||||
return result, events
|
||||
|
||||
|
||||
@pytest.mark.parametrize("spec,protocol,baud,framing,mode", [
|
||||
("mahak_mds", "mahak_mds", 9600, "8N1", "poll"),
|
||||
("toledo_cont:4800:7E1", "toledo_cont", 4800, "7E1", "continuous"),
|
||||
("xk3190_tf0:2400", "xk3190_tf0", 2400, "8N1", "continuous"),
|
||||
("xk3190_reversed:1200", "xk3190_reversed", 1200, "8N1", "continuous"),
|
||||
("mt_sics", "mt_sics", 9600, "8N1", "poll"),
|
||||
("and_std:19200", "and_std", 19200, "8N1", "poll"),
|
||||
("sma:9600:7E1", "sma", 9600, "7E1", "poll"),
|
||||
("sartorius:1200:7E1", "sartorius", 1200, "7E1", "poll"),
|
||||
("cas_enq", "cas_enq", 9600, "8N1", "poll"),
|
||||
])
|
||||
def test_finds_protocol_speed_and_framing(spec, protocol, baud, framing, mode):
|
||||
result, events = detect(spec)
|
||||
assert result["found"], events
|
||||
assert result["protocol"] == protocol
|
||||
assert result["serial"]["baudrate"] == baud
|
||||
s = result["serial"]
|
||||
assert f"{s['bytesize']}{s['parity']}{s['stopbits']}" == framing
|
||||
assert result["mode"] == mode
|
||||
assert 0 < result["confidence"] <= 0.99
|
||||
assert events[0] == "port_start" and "found" in events
|
||||
|
||||
|
||||
def test_thorough_search_reaches_7o1():
|
||||
result, _ = detect("ohaus:9600:7O1", thorough=True)
|
||||
assert result["found"] and result["protocol"] == "ohaus"
|
||||
assert result["serial"]["parity"] == "O"
|
||||
|
||||
|
||||
def test_nothing_connected():
|
||||
detector = Detector(lambda s: Silent(s), timings=FAST)
|
||||
result = detector.run_port("COM5")
|
||||
assert result["found"] is False and result["unknown"] is None
|
||||
|
||||
|
||||
def test_unknown_readable_data_is_reported():
|
||||
detector = Detector(lambda s: Chatter(s), timings=FAST)
|
||||
result = detector.run_port("COM5")
|
||||
assert result["found"] is False
|
||||
assert result["unknown"]["baud"] == 9600
|
||||
assert "HELLO" in result["unknown"]["sample_text"]
|
||||
|
||||
|
||||
def test_cancel_stops_quickly():
|
||||
detector = Detector(lambda s: Silent(s), cancelled=lambda: True, timings=FAST)
|
||||
started = time.monotonic()
|
||||
result = detector.run_port("COM5")
|
||||
assert time.monotonic() - started < 0.5
|
||||
assert result["found"] is False and result["cancelled"] is True
|
||||
|
||||
|
||||
def test_open_failure_is_reported():
|
||||
def refuse(settings):
|
||||
raise OSError("Access is denied")
|
||||
result = Detector(refuse, timings=FAST).run_port("COM5")
|
||||
assert result["found"] is False and "Access is denied" in result["error"]
|
||||
|
||||
|
||||
def test_readability():
|
||||
assert readability(b"ST,+0.55 kg\r\n") == 1.0
|
||||
assert readability(bytes([0xD3, 0xD4])) == 0.0
|
||||
assert readability(bytes([0xD3, 0xD4]), mask7=True) == 1.0
|
||||
+137
@@ -0,0 +1,137 @@
|
||||
# SPDX-License-Identifier: GPL-3.0-or-later
|
||||
"""Indicators that print labels: the PTC400 capture, other label languages, the label log."""
|
||||
import json
|
||||
import os
|
||||
import time
|
||||
|
||||
import pytest
|
||||
|
||||
from scale_bridge import profiles
|
||||
from scale_bridge.detect import Detector, Timings
|
||||
from scale_bridge.labels import LabelLog
|
||||
from scale_bridge.protocols import PROTOCOLS
|
||||
from scale_bridge.simulator import SimulatorBank
|
||||
|
||||
HERE = os.path.dirname(os.path.abspath(__file__))
|
||||
FAST = Timings(passive_s=0.4, probe_s=0.1, confirm_s=0.3, drain_s=0.02)
|
||||
|
||||
|
||||
def capture() -> list[bytes]:
|
||||
with open(os.path.join(HERE, "captures", "ptc400_tspl_labels.hex"), encoding="ascii") as f:
|
||||
return [bytes.fromhex(line) for line in f if line.strip()]
|
||||
|
||||
|
||||
def test_ptc400_capture_all_labels():
|
||||
# Recorded from a PTC400 indicator (TSPL to a TSC label printer), a 1.4 kg
|
||||
# test weight moved around the platform after three other weighings.
|
||||
readings = PROTOCOLS["label_print"].readings(b"".join(capture()))
|
||||
assert [r.value for r in readings] == [102.3, 141.8, 141.2, 1.4, 1.4, 1.35, 1.3, 1.25, 0.95,
|
||||
1.2, 1.25, 1.15]
|
||||
first = readings[0]
|
||||
assert first.unit == "kg" and first.stable is True
|
||||
assert first.fields["Order.Co"] == "222" and first.fields["SHIFT"] == "2"
|
||||
assert first.fields["date"] == "1405/07/19" and first.fields["time"] == "16:39"
|
||||
assert first.fields["Thickness"] == "0.0" and first.fields["No"] == "6"
|
||||
assert readings[2].fields["Thickness"] == "3.3"
|
||||
|
||||
|
||||
def test_label_split_over_two_chunks_is_read_once():
|
||||
label = capture()[0]
|
||||
chunks = [(1000, label[:200]), (1020, label[200:])]
|
||||
timed = profiles.timed_readings("label_print", None, chunks)
|
||||
assert len(timed) == 1 and timed[0].t_ms == 1020 and timed[0].reading.value == 102.3
|
||||
|
||||
|
||||
@pytest.mark.parametrize("label,value,unit", [
|
||||
(b'^XA^FO50,50^A0N,40,40^FDNet: 12.34 kg^FS^FO50,120^FDLOT 7^FS^XZ', 12.34, "kg"),
|
||||
(b'N\r\nA50,0,0,4,1,1,N,"Weight"\r\nA50,40,0,4,1,1,N,"2.500"\r\nA200,40,0,4,1,1,N,"kg"\r\nP1\r\n',
|
||||
2.5, "kg"),
|
||||
(b'CLS\r\nTEXT 10,10,"3",0,1,1,"GROSS 15.6 kg"\r\nPRINT 1,1\r\n', 15.6, "kg"),
|
||||
])
|
||||
def test_other_label_languages(label, value, unit):
|
||||
r = PROTOCOLS["label_print"].readings(label)[-1]
|
||||
assert (r.value, r.unit) == (value, unit)
|
||||
|
||||
|
||||
def test_label_without_weight_is_ignored():
|
||||
assert PROTOCOLS["label_print"].readings(b'CLS\r\nTEXT 1,1,"3",0,1,1,"Hello"\r\nPRINT 1\r\n') == []
|
||||
|
||||
|
||||
@pytest.mark.parametrize("spec,baud,parity,wrong", [
|
||||
("label_print", 9600, "N", 0), ("label_print:4800", 4800, "N", 2), ("label_print:9600:7E1", 9600, "E", 0),
|
||||
])
|
||||
def test_wait_for_print_detection(spec, baud, parity, wrong):
|
||||
bank = SimulatorBank(spec)
|
||||
events = []
|
||||
detector = Detector(bank.opener(), log=lambda code, **kw: events.append(code), timings=FAST,
|
||||
print_wait_s=5, listen_only=True)
|
||||
result = detector.run_port("COM90")
|
||||
assert result["found"] and result["protocol"] == "label_print" and result["mode"] == "print"
|
||||
assert result["serial"]["baudrate"] == baud and result["serial"]["parity"] == parity
|
||||
assert result["reading"]["fields"]["Order.Co"] == "222"
|
||||
assert events.count("print_wrong_speed") == wrong
|
||||
assert "ask" not in events # listen only: nothing was sent
|
||||
|
||||
|
||||
def test_listen_only_sends_nothing():
|
||||
written = []
|
||||
|
||||
class Quiet:
|
||||
in_waiting = 0
|
||||
|
||||
def __init__(self, s):
|
||||
pass
|
||||
|
||||
def read(self, n=1):
|
||||
time.sleep(0.01)
|
||||
return b""
|
||||
|
||||
def write(self, data):
|
||||
written.append(data)
|
||||
return len(data)
|
||||
|
||||
def close(self):
|
||||
pass
|
||||
|
||||
result = Detector(lambda s: Quiet(s), timings=FAST, print_wait_s=0.3, listen_only=True).run_port("COM5")
|
||||
assert result["found"] is False and written == []
|
||||
|
||||
|
||||
def test_label_log_feeds_pieces_and_writes_files(tmp_path):
|
||||
log = LabelLog(str(tmp_path))
|
||||
profile = profiles.validate({"name": "label-1", "port": "COM8", "protocol": "label_print",
|
||||
"serial": {"baudrate": 9600}})
|
||||
a, b = capture()[3], capture()[4]
|
||||
assert log.feed(profile, a[:100]) == []
|
||||
got = log.feed(profile, a[100:] + b)
|
||||
assert [r["value"] for r in got] == [1.4, 1.4] and [r["seq"] for r in got] == [1, 2]
|
||||
assert [r["seq"] for r in log.list("label-1", after=1)] == [2]
|
||||
files = list(tmp_path.iterdir())
|
||||
assert len(files) == 1 and files[0].name.startswith("label-1-")
|
||||
lines = files[0].read_text(encoding="utf-8").splitlines()
|
||||
assert json.loads(lines[0])["fields"]["Order.Co"] == "222"
|
||||
|
||||
|
||||
def test_bridge_keeps_print_scale_open_and_logs_labels(tmp_path):
|
||||
from scale_bridge.config import Config
|
||||
from scale_bridge.server import Bridge
|
||||
config = Config(str(tmp_path / "bridge.json"))
|
||||
bridge = Bridge(config, simulate="label_print")
|
||||
try:
|
||||
config.save_profile({"name": "label-1", "port": "COM90", "protocol": "label_print",
|
||||
"serial": {"baudrate": 9600}})
|
||||
bridge.keeper.tick()
|
||||
deadline = time.time() + 12
|
||||
while time.time() < deadline and not bridge.labels.list("label-1"):
|
||||
time.sleep(0.3)
|
||||
listed = bridge.label_list({"profile": "label-1"})
|
||||
assert listed["labels"] and listed["listening"] == ["label-1"]
|
||||
assert listed["labels"][-1]["fields"]["SHIFT"] == "2"
|
||||
started = time.monotonic()
|
||||
answer = bridge.weight(config.profile("label-1"), max_age_ms=60000, wait_ms=2500)
|
||||
assert time.monotonic() - started < 1.5 # a print scale never holds the caller
|
||||
assert answer["ok"] and answer["on_print"] and answer["stable"] and answer["unit"] == "kg"
|
||||
assert (tmp_path / "labels").is_dir()
|
||||
finally:
|
||||
bridge.keeper.stop()
|
||||
bridge.registry.stop_all()
|
||||
@@ -0,0 +1,132 @@
|
||||
# SPDX-License-Identifier: GPL-3.0-or-later
|
||||
import json
|
||||
|
||||
import pytest
|
||||
|
||||
from scale_bridge import profiles
|
||||
from scale_bridge.config import Config
|
||||
from scale_bridge.protocols import Reading
|
||||
|
||||
|
||||
def base(**over):
|
||||
raw = {"name": "packing-1", "port": "com7", "protocol": "mahak_mds",
|
||||
"serial": {"baudrate": 9600}, "exchange": {"request_hex": "4d090407"}}
|
||||
raw.update(over)
|
||||
return raw
|
||||
|
||||
|
||||
def test_validate_normalises():
|
||||
p = profiles.validate(base())
|
||||
assert p["port"] == "COM7"
|
||||
assert p["serial"]["baudrate"] == 9600 and p["serial"]["parity"] == "N"
|
||||
assert p["exchange"]["request_hex"] == "4D 09 04 07"
|
||||
assert p["stable_samples"] == 3
|
||||
|
||||
|
||||
@pytest.mark.parametrize("bad", [
|
||||
{"name": ""}, {"name": "bad name"}, {"name": "-x"}, {"protocol": "nope"}, {"port": "LPT1"},
|
||||
{"serial": {"baudrate": 9}}, {"exchange": {"request_hex": "zz"}}, {"output_unit": "pcs"},
|
||||
{"protocol": "custom_ascii", "params": {"regex": "("}}, {"protocol": "custom_ascii", "params": {}},
|
||||
])
|
||||
def test_validate_rejects(bad):
|
||||
with pytest.raises(ValueError):
|
||||
profiles.validate(base(**bad))
|
||||
|
||||
|
||||
class FakeWorker:
|
||||
def __init__(self, chunks, is_open=True, last_error=None):
|
||||
self.chunks = chunks
|
||||
self.is_open = is_open
|
||||
self.last_error = last_error
|
||||
|
||||
def recent(self, count):
|
||||
return self.chunks[-count:]
|
||||
|
||||
|
||||
MAHAK = lambda grams: bytes([0x58, 0x51, 7, 7]) + grams.to_bytes(3, "big") # noqa: E731
|
||||
|
||||
|
||||
def test_evaluate_flagless_stability_needs_equal_recent_readings():
|
||||
p = profiles.validate(base())
|
||||
now = 100_000
|
||||
moving = FakeWorker([(now - 1000, MAHAK(540)), (now - 500, MAHAK(550)), (now - 10, MAHAK(550))])
|
||||
r = profiles.evaluate(p, moving, 1500, now)
|
||||
assert r["ok"] and r["value"] == 550 and r["unit"] == "g" and r["stable"] is False
|
||||
steady = FakeWorker([(now - 1000, MAHAK(550)), (now - 500, MAHAK(550)), (now - 10, MAHAK(550))])
|
||||
assert profiles.evaluate(p, steady, 1500, now)["stable"] is True
|
||||
old = FakeWorker([(now - 60_000, MAHAK(550)), (now - 59_000, MAHAK(550)), (now - 10, MAHAK(550))])
|
||||
assert profiles.evaluate(p, old, 1500, now)["stable"] is False
|
||||
|
||||
|
||||
def test_evaluate_stale_and_conversion():
|
||||
p = profiles.validate(base(output_unit="kg"))
|
||||
now = 100_000
|
||||
r = profiles.evaluate(p, FakeWorker([(now - 5000, MAHAK(550))] * 3), 1500, now)
|
||||
assert r["stale"] is True and r["stable"] is False
|
||||
assert r["value"] == pytest.approx(0.55) and r["unit"] == "kg"
|
||||
|
||||
|
||||
def test_evaluate_unit_fallback_for_unitless_protocols():
|
||||
p = profiles.validate(base(protocol="xk3190_reversed", unit="kg", exchange={}))
|
||||
r = profiles.evaluate(p, FakeWorker([(1000, b"05.21000=05.21000=05.21000=")]), 1500, 1010)
|
||||
assert r["value"] == 12.5 and r["unit"] == "kg"
|
||||
|
||||
|
||||
def test_evaluate_errors():
|
||||
p = profiles.validate(base())
|
||||
r = profiles.evaluate(p, FakeWorker([], is_open=False, last_error="could not open port COM7"), 1500, 0)
|
||||
assert r["ok"] is False and "COM7" in r["error"]
|
||||
r = profiles.evaluate(p, FakeWorker([(0, b"garbage")]), 1500, 10)
|
||||
assert r["ok"] is False and "protocol" in r["error"]
|
||||
|
||||
|
||||
def test_from_detection_and_ad_hoc():
|
||||
detection = {"port": "COM9", "protocol": "xk3190_tf0",
|
||||
"serial": {"port": "COM9", "baudrate": 2400, "bytesize": 8, "parity": "N", "stopbits": 1},
|
||||
"exchange": {"request_hex": "", "poll_interval_ms": 500}, "reading": {"unit": ""}}
|
||||
p = profiles.from_detection(detection, "line-2")
|
||||
assert p["unit"] == "kg" and p["serial"]["baudrate"] == 2400
|
||||
q = profiles.ad_hoc("COM3", "mt_sics")
|
||||
assert q["exchange"]["request_hex"] == "53 49 0D 0A"
|
||||
|
||||
|
||||
def test_config_round_trip_and_legacy_file(tmp_path):
|
||||
path = tmp_path / "bridge.json"
|
||||
# a file written by an earlier version (1.x)
|
||||
path.write_text(json.dumps({"listen_host": "0.0.0.0", "listen_port": 8765, "token": "abc",
|
||||
"allowed_clients": []}), encoding="utf-8")
|
||||
c = Config(str(path))
|
||||
assert c.token == "abc" and c.profiles() == []
|
||||
c.save_profile(base())
|
||||
assert Config(str(path)).profile("PACKING-1")["port"] == "COM7"
|
||||
assert c.delete_profile("packing-1") and not c.delete_profile("packing-1")
|
||||
with pytest.raises(ValueError):
|
||||
c.set_allowed_clients(["not-an-ip"])
|
||||
|
||||
|
||||
def test_config_creates_token_and_survives_a_broken_file(tmp_path):
|
||||
path = tmp_path / "bridge.json"
|
||||
path.write_text("{broken", encoding="utf-8")
|
||||
c = Config(str(path))
|
||||
assert len(c.token) >= 24
|
||||
assert (tmp_path / "bridge.json.broken").exists()
|
||||
old = c.token
|
||||
assert c.rotate_token() != old
|
||||
|
||||
|
||||
def test_reversed_stream_one_frame_per_chunk():
|
||||
# A Yaohua YH-T7E sends "=081.100" about nine times a second with a pause
|
||||
# between frames, so every frame lands in its own chunk (field capture, 1.18 kg).
|
||||
p = profiles.validate(base(protocol="xk3190_reversed", unit="kg", exchange={}))
|
||||
now = 10_000
|
||||
chunks = [(now - 400 + i * 100, b"=081.100") for i in range(5)]
|
||||
timed = profiles.timed_readings("xk3190_reversed", None, chunks)
|
||||
assert [x.reading.value for x in timed] == [1.18] * 4
|
||||
r = profiles.evaluate(p, FakeWorker(chunks), 1500, now)
|
||||
assert r["ok"] and r["value"] == 1.18 and r["unit"] == "kg" and r["stable"] is True
|
||||
|
||||
|
||||
def test_chunk_boundaries_do_not_repeat_readings():
|
||||
frame = bytes([0x58, 0x51, 7, 7]) + (550).to_bytes(3, "big")
|
||||
timed = profiles.timed_readings("mahak_mds", None, [(1, frame), (2, frame), (3, frame)])
|
||||
assert [x.t_ms for x in timed] == [1, 2, 3]
|
||||
@@ -0,0 +1,193 @@
|
||||
# SPDX-License-Identifier: GPL-3.0-or-later
|
||||
"""Every parser against sample frames in the shapes the manufacturers document."""
|
||||
import pytest
|
||||
|
||||
from scale_bridge.protocols import PROTOCOLS, convert, get_protocol, lines, norm_unit
|
||||
from scale_bridge.simulator import frame_for
|
||||
|
||||
|
||||
def one(protocol_id, data, params=None):
|
||||
readings = get_protocol(protocol_id, params).readings(data)
|
||||
assert readings, f"{protocol_id} read nothing from {data!r}"
|
||||
return readings[-1]
|
||||
|
||||
|
||||
def toledo_frame(swa, swb, swc, digits, tare=b"000000"):
|
||||
body = bytes([0x02, swa, swb, swc]) + digits + tare + b"\r"
|
||||
return body + bytes([(-sum(b & 0x7F for b in body)) & 0x7F])
|
||||
|
||||
|
||||
# -- Mettler Toledo ----------------------------------------------------------
|
||||
|
||||
def test_mt_sics_stable_and_dynamic():
|
||||
r = one("mt_sics", b"S S 0.550 kg\r\n")
|
||||
assert (r.value, r.unit, r.stable) == (0.55, "kg", True)
|
||||
r = one("mt_sics", b"S D 12.345 g\r\n")
|
||||
assert (r.value, r.unit, r.stable) == (12.345, "g", False)
|
||||
|
||||
|
||||
def test_mt_sics_overload_and_error():
|
||||
assert one("mt_sics", b"S +\r\n").overload
|
||||
assert PROTOCOLS["mt_sics"].readings(b"S I\r\nES\r\n") == []
|
||||
|
||||
|
||||
def test_toledo_continuous_decimal_point_units_and_checksum():
|
||||
# SWA: bit5 + count-by x1 (bit3) + dp code 3 (XXXXX.X); SWB: bit5 + kg (bit4)
|
||||
r = one("toledo_cont", toledo_frame(0x2B, 0x30, 0x20, b"012345"))
|
||||
assert (r.value, r.unit, r.stable, r.net, r.checksum_ok) == (1234.5, "kg", True, False, True)
|
||||
# motion + negative + net, grams in SWC
|
||||
r = one("toledo_cont", toledo_frame(0x2A, 0x20 | 0x08 | 0x02 | 0x01, 0x21, b"000550"))
|
||||
assert (r.value, r.unit, r.stable, r.net) == (-550, "g", False, True)
|
||||
# lb when SWB bit4 is clear, dp code 5 (X.XXX)
|
||||
r = one("toledo_cont", toledo_frame(0x2D, 0x20, 0x20, b"001210"))
|
||||
assert (r.value, r.unit) == (1.21, "lb")
|
||||
|
||||
|
||||
def test_toledo_continuous_bad_checksum_is_flagged():
|
||||
frame = bytearray(toledo_frame(0x2B, 0x30, 0x20, b"012345"))
|
||||
frame[-1] ^= 0x01
|
||||
assert one("toledo_cont", bytes(frame)).checksum_ok is False
|
||||
|
||||
|
||||
# -- A&D and friends -----------------------------------------------------------
|
||||
|
||||
@pytest.mark.parametrize("frame,value,unit,stable,net", [
|
||||
(b"ST,+00000.550 kg\r\n", 0.55, "kg", True, None),
|
||||
(b"US,-00001.20 kg\r\n", -1.2, "kg", False, None),
|
||||
(b"ST,GS,+0012.34kg\r\n", 12.34, "kg", True, False),
|
||||
(b"ST,NT,+0001.500 lb\r\n", 1.5, "lb", True, True),
|
||||
(b"QT,+000123.4 g\r\n", 123.4, "g", True, None),
|
||||
])
|
||||
def test_and_standard(frame, value, unit, stable, net):
|
||||
r = one("and_std", frame)
|
||||
assert (r.value, r.unit, r.stable, r.net) == (value, unit, stable, net)
|
||||
|
||||
|
||||
def test_and_standard_overload():
|
||||
r = one("and_std", b"OL,+9999999 kg\r\n")
|
||||
assert r.overload and r.value is None
|
||||
|
||||
|
||||
def test_sma_frames():
|
||||
r = one("sma", b"\n 1G 0.550kg \r") # s r n m f, then the weight in 10 characters
|
||||
assert (r.value, r.unit, r.stable, r.net) == (0.55, "kg", True, False)
|
||||
r = one("sma", b"\n 1NM 12.500lb \r")
|
||||
assert (r.value, r.unit, r.stable, r.net) == (12.5, "lb", False, True)
|
||||
assert one("sma", b"\nO1G ----------lb \r").overload
|
||||
|
||||
|
||||
def test_nci():
|
||||
r = one("nci", b"\n 1.23lb\r\n00\r\x03")
|
||||
assert (r.value, r.unit, r.stable) == (1.23, "lb", True)
|
||||
r = one("nci", b"\n 1.23lb\r\n10\r\x03")
|
||||
assert r.stable is False
|
||||
|
||||
|
||||
def test_ohaus():
|
||||
r = one("ohaus", b" 0.550 kg \r\n")
|
||||
assert (r.value, r.unit, r.stable) == (0.55, "kg", True)
|
||||
assert one("ohaus", b" 0.550 kg ? \r\n").stable is False
|
||||
assert one("ohaus", b" 1.234 kg N\r\n").net is True
|
||||
|
||||
|
||||
def test_sartorius_unit_missing_means_unstable():
|
||||
r = one("sartorius", b"+ 0.550 kg \r\n")
|
||||
assert (r.value, r.unit, r.stable) == (0.55, "kg", True)
|
||||
r = one("sartorius", b"+ 0.550 \r\n")
|
||||
assert (r.value, r.stable) == (0.55, False)
|
||||
r = one("sartorius", b"N + 1.234 kg\r\n")
|
||||
assert (r.value, r.net) == (1.234, True)
|
||||
|
||||
|
||||
def test_cas_enq():
|
||||
r = one("cas_enq", b"\x06\x01\x02S 0.550kg\x03\x04")
|
||||
assert (r.value, r.unit, r.stable) == (0.55, "kg", True)
|
||||
|
||||
|
||||
# -- XK3190 ---------------------------------------------------------------------
|
||||
|
||||
def test_xk3190_tf0_with_checksum():
|
||||
body = b"+0012342"
|
||||
x = 0
|
||||
for b in body:
|
||||
x ^= b
|
||||
frame = b"\x02" + body + f"{x >> 4:X}{x & 0xF:X}".encode() + b"\x03"
|
||||
r = one("xk3190_tf0", frame * 2)
|
||||
assert (r.value, r.checksum_ok) == (12.34, True)
|
||||
r = one("xk3190_tf0", b"\x02-0005003" + b"00" + b"\x03")
|
||||
assert r.value == -0.5 and r.checksum_ok is False
|
||||
|
||||
|
||||
def test_xk3190_reversed_stream():
|
||||
r = one("xk3190_reversed", b"05.21000=05.21000=05.21000=")
|
||||
assert r.value == 12.5
|
||||
assert PROTOCOLS["xk3190_reversed"].readings(b"05.21000=") == []
|
||||
|
||||
|
||||
# -- Mahak (field-tested) -----------------------------------------------------------
|
||||
|
||||
def test_mahak_field_capture():
|
||||
# Captured on a Mahak MDS 13000 with a 550 g weight: 58 ?? 07 07 00 02 26
|
||||
r = one("mahak_mds", bytes.fromhex("58 51 07 07 00 02 26"))
|
||||
assert (r.value, r.unit) == (550.0, "g")
|
||||
r = one("mahak_mds", bytes.fromhex("58 A3 07 07 00 02 EE"))
|
||||
assert r.value == 750.0
|
||||
|
||||
|
||||
def test_mahak_ignores_boot_message():
|
||||
assert PROTOCOLS["mahak_mds"].readings(bytes.fromhex("42 03 04 01 42 4F 4F 54 0C 04 8C")) == []
|
||||
|
||||
|
||||
# -- generic and custom ----------------------------------------------------------------
|
||||
|
||||
def test_generic_ascii():
|
||||
r = one("ascii_generic", b"G 12.50 kg\r\n")
|
||||
assert (r.value, r.unit) == (12.5, "kg")
|
||||
assert one("ascii_generic", b"US 3.2 kg\r\n").stable is False
|
||||
|
||||
|
||||
def test_custom_binary_and_ascii():
|
||||
params = {"pattern": "58 ?? 07 07", "value_offset": 4, "value_length": 3, "unit": "g"}
|
||||
r = one("custom_binary", bytes.fromhex("58 51 07 07 00 02 26"), params)
|
||||
assert (r.value, r.unit) == (550.0, "g")
|
||||
r = one("custom_ascii", b"W: 12.5\r\n", {"regex": r"W:\s*([-\d.]+)", "unit": "kg"})
|
||||
assert (r.value, r.unit) == (12.5, "kg")
|
||||
assert get_protocol("custom_ascii").readings(b"W: 1\r\n") == []
|
||||
|
||||
|
||||
# -- the simulator speaks what the parsers read --------------------------------------------
|
||||
|
||||
@pytest.mark.parametrize("pid", ["mt_sics", "and_std", "toledo_cont", "sma", "nci", "ohaus", "sartorius",
|
||||
"cas_enq", "xk3190_tf0", "xk3190_reversed", "mahak_mds"])
|
||||
@pytest.mark.parametrize("kg,stable", [(0.55, True), (13.1, False)])
|
||||
def test_simulator_round_trip(pid, kg, stable):
|
||||
frame = frame_for(pid, kg, stable)
|
||||
data = frame * 3 if pid == "xk3190_reversed" else frame
|
||||
r = PROTOCOLS[pid].readings(data)[-1]
|
||||
expected = kg * 1000 if pid == "mahak_mds" else kg
|
||||
assert r.value == pytest.approx(expected)
|
||||
if r.stable is not None and pid != "sartorius":
|
||||
assert r.stable == stable
|
||||
|
||||
|
||||
# -- helpers ----------------------------------------------------------------------------
|
||||
|
||||
def test_units():
|
||||
assert norm_unit(b" KG ") == "kg" and norm_unit("lbs") == "lb" and norm_unit(None) == ""
|
||||
assert convert(550, "g", "kg") == pytest.approx(0.55)
|
||||
assert convert(1, "lb", "g") == pytest.approx(453.59237)
|
||||
assert convert(1, "kg", "pcs") is None
|
||||
|
||||
|
||||
def test_lines_split_on_terminators():
|
||||
assert lines(b"\x02abc\r\ndef\x03\r\n\r\n") == [b"abc", b"def"]
|
||||
|
||||
|
||||
def test_catalogue_is_consistent():
|
||||
from scale_bridge.protocols import CONTINUOUS_IDS, POLL_IDS
|
||||
for pid in CONTINUOUS_IDS + POLL_IDS:
|
||||
assert pid in PROTOCOLS
|
||||
for pid in POLL_IDS:
|
||||
assert PROTOCOLS[pid].request, pid
|
||||
# read-only: never zero / tare / reset / print-off letters on their own
|
||||
assert PROTOCOLS[pid].request.strip(b"\r\n") not in (b"Z", b"T", b"R", b"P")
|
||||
+156
@@ -0,0 +1,156 @@
|
||||
# SPDX-License-Identifier: GPL-3.0-or-later
|
||||
"""The HTTP interface, end to end, with simulated scales."""
|
||||
import json
|
||||
import threading
|
||||
import time
|
||||
import urllib.error
|
||||
import urllib.request
|
||||
|
||||
import pytest
|
||||
|
||||
from scale_bridge.config import Config
|
||||
from scale_bridge.detect import Timings
|
||||
from scale_bridge.server import Bridge, make_server
|
||||
|
||||
LOCAL = {"X-Requested-With": "ScaleBridge"}
|
||||
|
||||
|
||||
@pytest.fixture(scope="module")
|
||||
def bridge_url(tmp_path_factory):
|
||||
config = Config(str(tmp_path_factory.mktemp("bridge") / "bridge.json"))
|
||||
bridge = Bridge(config, simulate="mahak_mds,toledo_cont:4800:7E1")
|
||||
bridge.detect_timings = Timings(passive_s=0.5, probe_s=0.15, confirm_s=0.4, drain_s=0.02)
|
||||
server = make_server(bridge, "127.0.0.1", 0)
|
||||
thread = threading.Thread(target=server.serve_forever, daemon=True)
|
||||
thread.start()
|
||||
yield f"http://127.0.0.1:{server.server_address[1]}", config
|
||||
server.shutdown()
|
||||
bridge.registry.stop_all()
|
||||
|
||||
|
||||
def call(url, method="GET", body=None, headers=None):
|
||||
req = urllib.request.Request(url, method=method,
|
||||
data=json.dumps(body).encode() if body is not None else None,
|
||||
headers={"Content-Type": "application/json", **(headers or {})})
|
||||
try:
|
||||
with urllib.request.urlopen(req, timeout=15) as r:
|
||||
return r.status, json.loads(r.read())
|
||||
except urllib.error.HTTPError as e:
|
||||
return e.code, json.loads(e.read() or b"{}")
|
||||
|
||||
|
||||
def test_health_is_open_and_identifies_the_author(bridge_url):
|
||||
url, _ = bridge_url
|
||||
code, body = call(url + "/health")
|
||||
assert code == 200 and body["service"] == "syncpulse-scale-bridge"
|
||||
assert body["author"] == "Farshad Zamani" and "weight" in body["capabilities"]
|
||||
|
||||
|
||||
def test_key_is_required(bridge_url):
|
||||
url, config = bridge_url
|
||||
assert call(url + "/ports")[0] == 401
|
||||
assert call(url + "/ports", headers={"X-Bridge-Token": "wrong"})[0] == 401
|
||||
code, body = call(url + "/ports", headers={"X-Bridge-Token": config.token})
|
||||
assert code == 200 and any(p["device"] == "COM90" for p in body["ports"])
|
||||
|
||||
|
||||
def test_legacy_read_contract(bridge_url):
|
||||
url, config = bridge_url
|
||||
code, body = call(url + "/read", "POST", {
|
||||
"serial": {"port": "COM90", "baudrate": 9600, "bytesize": 8, "parity": "N", "stopbits": 1},
|
||||
"exchange": {"request_hex": "4D 09 04 07", "poll_interval_ms": 300}, "frames": 3},
|
||||
headers={"X-Bridge-Token": config.token})
|
||||
assert code == 200 and body["ok"] and body["open"]
|
||||
assert body["frames"] and body["frames"][-1]["hex"].startswith("58")
|
||||
assert {"t", "hex"} <= set(body["frames"][-1]) and "now" in body
|
||||
|
||||
|
||||
def test_weight_by_port_and_protocol(bridge_url):
|
||||
url, config = bridge_url
|
||||
code, body = call(url + "/weight?port=COM91&protocol=toledo_cont&baud=4800&framing=7E1",
|
||||
headers={"X-Bridge-Token": config.token})
|
||||
assert code == 200 and body["ok"] and body["unit"] == "kg" and body["checksum_ok"] is True
|
||||
assert isinstance(body["value"], float) and "measured_at" in body
|
||||
|
||||
|
||||
def test_weight_errors(bridge_url):
|
||||
url, config = bridge_url
|
||||
h = {"X-Bridge-Token": config.token}
|
||||
assert call(url + "/weight?profile=missing", headers=h)[0] == 404
|
||||
assert call(url + "/weight?port=COM90", headers=h)[0] == 400
|
||||
assert call(url + "/weight?port=COM90&protocol=mt_sics&framing=9X9", headers=h)[0] == 400
|
||||
|
||||
|
||||
def test_local_api_needs_header_and_local_host(bridge_url):
|
||||
url, _ = bridge_url
|
||||
assert call(url + "/api/state")[0] == 403
|
||||
assert call(url + "/api/state", headers={**LOCAL, "Host": "evil.example"})[0] == 403
|
||||
code, state = call(url + "/api/state", headers=LOCAL)
|
||||
assert code == 200 and state["about"]["author"] == "Farshad Zamani" and state["token"]
|
||||
|
||||
|
||||
def test_page_is_served_with_signature(bridge_url):
|
||||
url, _ = bridge_url
|
||||
with urllib.request.urlopen(url + "/", timeout=5) as r:
|
||||
html = r.read().decode("utf-8")
|
||||
assert "Content-Security-Policy" in r.headers
|
||||
assert "Farshad Zamani" in html and "linkedin.com/in/farshad-zamani92" in html
|
||||
assert "cloudtart.com" in html and "SyncPulse" in html
|
||||
|
||||
|
||||
def test_detect_save_read_delete(bridge_url):
|
||||
url, config = bridge_url
|
||||
code, body = call(url + "/api/detect", "POST", {"ports": ["COM90"]}, headers=LOCAL)
|
||||
assert code == 200 and body["job"]["running"]
|
||||
# a second search while the first runs is refused, and the port is reserved
|
||||
assert call(url + "/api/detect", "POST", {"ports": ["COM90"]}, headers=LOCAL)[0] == 409
|
||||
busy = call(url + "/weight?port=COM90&protocol=mahak_mds", headers={"X-Bridge-Token": config.token})
|
||||
assert busy[0] == 409
|
||||
deadline = time.time() + 60
|
||||
job = None
|
||||
while time.time() < deadline:
|
||||
job = call(url + "/api/detect", headers=LOCAL)[1]["job"]
|
||||
if not job["running"]:
|
||||
break
|
||||
time.sleep(0.3)
|
||||
assert job and job["results"][0]["found"] and job["results"][0]["protocol"] == "mahak_mds"
|
||||
assert job["progress"] == 1.0
|
||||
|
||||
code, saved = call(url + "/api/profiles", "POST",
|
||||
{"detection": job["results"][0], "name": "packing-1", "label": "Packing"},
|
||||
headers=LOCAL)
|
||||
assert code == 200 and saved["profile"]["name"] == "packing-1"
|
||||
|
||||
code, listed = call(url + "/profiles", headers={"X-Bridge-Token": config.token})
|
||||
assert [p["name"] for p in listed["profiles"]] == ["packing-1"]
|
||||
|
||||
deadline = time.time() + 10
|
||||
body = {}
|
||||
while time.time() < deadline:
|
||||
body = call(url + "/weight?profile=packing-1", headers={"X-Bridge-Token": config.token})[1]
|
||||
if body.get("stable"):
|
||||
break
|
||||
time.sleep(0.4)
|
||||
assert body["ok"] and body["unit"] == "g" and body["stable"] is True
|
||||
|
||||
code, _ = call(url + "/api/profiles/packing-1", "DELETE", headers=LOCAL)
|
||||
assert code == 200 and config.profiles() == []
|
||||
|
||||
|
||||
def test_allowed_clients_do_not_lock_out_this_pc(bridge_url):
|
||||
url, config = bridge_url
|
||||
code, _ = call(url + "/api/allowed", "POST", {"clients": ["10.1.2.3"]}, headers=LOCAL)
|
||||
assert code == 200
|
||||
try:
|
||||
assert call(url + "/ports", headers={"X-Bridge-Token": config.token})[0] == 200
|
||||
finally:
|
||||
call(url + "/api/allowed", "POST", {"clients": []}, headers=LOCAL)
|
||||
|
||||
|
||||
def test_bad_json_is_a_400(bridge_url):
|
||||
url, config = bridge_url
|
||||
req = urllib.request.Request(url + "/read", method="POST", data=b"{nope",
|
||||
headers={"X-Bridge-Token": config.token})
|
||||
with pytest.raises(urllib.error.HTTPError) as e:
|
||||
urllib.request.urlopen(req, timeout=5)
|
||||
assert e.value.code == 400
|
||||
Reference in New Issue
Block a user