Skip to content

Commit

Permalink
Major code clean up; new features:
Browse files Browse the repository at this point in the history
Test unknown devices (scan everything)
Rework of Web FE Event & Dispatch
Fix major performance problem
Better image processing algorithm
New Halftone-like dither algo., namingly "Pattern"
Some fixes to CSS
Fix potential misc problems by manual testing
  • Loading branch information
NaitLee committed Jul 14, 2022
1 parent 502a572 commit 500971a
Show file tree
Hide file tree
Showing 25 changed files with 700 additions and 392 deletions.
2 changes: 2 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,8 @@ www/main.comp.js
www/vconsole.js
# https://github.com/delight-im/Android-AdvancedWebView
build-android/advancedwebview
# cd wasm && npm install
wasm/node_modules
# python bytecode
*.pyc
# releases
Expand Down
3 changes: 2 additions & 1 deletion .vscode/settings.json
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
{
"js/ts.implicitProjectConfig.strictNullChecks": false,
"js/ts.implicitProjectConfig.checkJs": false
"js/ts.implicitProjectConfig.checkJs": false,
"js/ts.implicitProjectConfig.experimentalDecorators": true
}
17 changes: 10 additions & 7 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,17 +4,14 @@ English | [Deutsch](./readme.i18n/README.de_DE.md) | [简体中文](./readme.i18

🐱🖨 A project that provides support to some Bluetooth "Cat Printer" models, on *many* platforms!

[![cat-printer-poster](https://repository-images.githubusercontent.com/403563361/ad018f6e-3a6e-4028-84b2-205f7d35c22b)](https://repository-images.githubusercontent.com/403563361/ad018f6e-3a6e-4028-84b2-205f7d35c22b)
[![cat-printer-poster](https://repository-images.githubusercontent.com/403563361/93e32942-856c-4552-a8b0-b03c0976a3a7)](https://repository-images.githubusercontent.com/403563361/93e32942-856c-4552-a8b0-b03c0976a3a7)

## Models

Currently:
Known to support: `GB0X, GT01, YT01` (`X` represents any digit)

| | |
|----|----|
| Known to support | `GB0X, GT01, YT01` |

\* `X` represents any digit
You can test other models with the Web UI, in `Settings -> Test Unknown Device`
It may work!

## Features

Expand Down Expand Up @@ -63,18 +60,24 @@ Get the newest apk release and install, then well done!
It may ask for background location permission, you can deny it safely.
(Foreground) Location permission is required for scanning Bluetooth devices in newer Android system.

Recommend to set scan time to 1 second.

### Windows

Get the newest release archive with "windows" in the file name,
extract to somewhere and run `start.bat`

Windows typically needs longer scan time. Defaults to 4 seconds, try to find your case.

### GNU/Linux

You can get the "pure" release, extract it, fire a terminal inside and run:
```bash
python3 server.py
```

Recommend to set scan time to 2 seconds.

On Arch Linux based distros you may first install `bluez`, as it's often missing
```bash
sudo pacman -S bluez bluez-utils
Expand Down
12 changes: 12 additions & 0 deletions dev-diary.txt
Original file line number Diff line number Diff line change
Expand Up @@ -184,3 +184,15 @@ Tried to "fix" it, used at least 4 hours, finally found it's a matter of didn't
So the Internet JavaScript memes are damned true.
https://programmerhumor.io/javascript-memes/why-is-it-like-this-2/
https://programmerhumor.io/javascript-memes/sorry-dad-_-2/

14th

... How silly is the above approach. This time I simply changed to Uint32Array. That became much more trivial.

So, I've re-written the image processing "lib". I wanted to go for WebAssembly (with AssemblyScript), so made it separate (in dir `wasm`).
After finish, it really worked -- but it's ~100% slower than the equivalent JavaScript (`asc` versus `tsc`)
And that may involve unacceptable change to scripting structure (ESModule etc.), thus Wasm was given up.
But hey, in this rewrite some algorithm practial overhead was removed, thus much more efficient! Enjoy the blazing speed!

In main.js the event handler was reworked too. No more double event dispatches.
Thanks to this, another image processing performance problem is fixed.
20 changes: 12 additions & 8 deletions printer.py
Original file line number Diff line number Diff line change
Expand Up @@ -270,7 +270,7 @@ class PrinterDriver(Commander):
model: Model = None
'The printer model'

scan_timeout: float = 4.0
scan_time: float = 4.0

connection_timeout : float = 5.0

Expand Down Expand Up @@ -351,15 +351,19 @@ def notify(_char, data):
self.device.start_notify(self.rx_characteristic, notify)
)

def scan(self, identifier: str=None, *, use_result=False):
def scan(self, identifier: str=None, *, use_result=False, everything=False):
''' Scan for supported devices, optionally filter with `identifier`,
which can be device model (bluetooth name), and optionally MAC address, after a comma.
If `use_result` is True, connect to the first available device to driver instantly.
If `everything` is True, return all bluetooth devices found.
Note: MAC address doesn't work on Apple MacOS. In place with it,
You need an UUID of BLE device dynamically given by MacOS.
'''
if self.fake:
return
return []
if everything:
devices = self.loop(BleakScanner.discover(self.scan_time))
return devices
if identifier:
if identifier.find(',') != -1:
name, address = identifier.split(',')
Expand All @@ -370,12 +374,12 @@ def scan(self, identifier: str=None, *, use_result=False):
if use_result:
self.connect(name, address)
return [BLEDevice(address, name)]
elif (identifier not in Models and
if (identifier not in Models and
identifier[2::3] != ':::::' and len(identifier.replace('-', '')) != 32):
error('model-0-is-not-supported-yet', identifier, exception=PrinterError)
# scanner = BleakScanner()
devices = [x for x in self.loop(
BleakScanner.discover(self.scan_timeout)
BleakScanner.discover(self.scan_time)
) if x.name in Models]
if identifier:
if identifier in Models:
Expand All @@ -397,7 +401,7 @@ def print(self, file: io.BufferedIOBase, *, mode='default',
self.scan(identifier, use_result=True)
if self.device is None and not self.fake:
error('no-available-devices-found', exception=PrinterError)
if mode == 'pbm' or mode == 'default':
if mode in ('pbm', 'default'):
printer_data = PrinterData(self.model.paper_width, file)
self._print_bitmap(printer_data)
elif mode == 'text':
Expand Down Expand Up @@ -443,7 +447,7 @@ def _prepare(self):
if self.quality: # well, slower makes stable heating
self.set_speed(self.quality)
if self.energy is not None:
self.set_energy(self.energy * 0xff)
self.set_energy(self.energy * 0x100)
self.apply_energy()
self.update_device()
self.flush()
Expand Down Expand Up @@ -648,7 +652,7 @@ def _main():
printer = PrinterDriver()

scan_param = args.scan.split(',')
printer.scan_timeout = float(scan_param[0])
printer.scan_time = float(scan_param[0])
identifier = ','.join(scan_param[1:])
if args.energy is not None:
printer.energy = int(args.energy * 0xff)
Expand Down
2 changes: 1 addition & 1 deletion printer_lib/commander.py
Original file line number Diff line number Diff line change
Expand Up @@ -137,7 +137,7 @@ def set_speed(self, value: int):

def set_energy(self, amount: int):
''' Set thermal energy, max to `0xffff`
By default, it's seems around `0x3000`, aka 1 / 5.
By default, it's seems around `0x3000` (1 / 5)
'''
self.send( self.make_command(0xaf, int_to_bytes(amount)) )

Expand Down
2 changes: 1 addition & 1 deletion readme.i18n/README.de_DE.md
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@

🐱🖨 Ein Projekt, das Unterstützung für einige Bluetooth-"Cat Printer"-Modelle auf *vielen* Plattformen bietet!

[![cat-printer-poster](https://repository-images.githubusercontent.com/403563361/ad018f6e-3a6e-4028-84b2-205f7d35c22b)](https://repository-images.githubusercontent.com/403563361/ad018f6e-3a6e-4028-84b2-205f7d35c22b)
[![cat-printer-poster](https://repository-images.githubusercontent.com/403563361/93e32942-856c-4552-a8b0-b03c0976a3a7)](https://repository-images.githubusercontent.com/403563361/93e32942-856c-4552-a8b0-b03c0976a3a7)

## unterstützte Geräte

Expand Down
17 changes: 10 additions & 7 deletions readme.i18n/README.zh_CN.md
Original file line number Diff line number Diff line change
Expand Up @@ -3,17 +3,14 @@

🐱🖨 猫咪打印机:此应用*跨平台地*对一些蓝牙“喵喵机”提供支持!

[![cat-printer-poster](https://repository-images.githubusercontent.com/403563361/ad018f6e-3a6e-4028-84b2-205f7d35c22b)](https://repository-images.githubusercontent.com/403563361/ad018f6e-3a6e-4028-84b2-205f7d35c22b)
[![cat-printer-poster](https://repository-images.githubusercontent.com/403563361/93e32942-856c-4552-a8b0-b03c0976a3a7)](https://repository-images.githubusercontent.com/403563361/93e32942-856c-4552-a8b0-b03c0976a3a7)

## 型号

目前有:
已知支持:`GB0X, GT01, YT01``X` 表示任意数字)

| | |
|----|----|
| 已知支持 | `GB0X, GT01, YT01` |

\* `X` 表示任意数字
可在 Web 界面测试未列出的型号。在 `设置 -> 测试未知设备`
有概率成功!

## 特性

Expand Down Expand Up @@ -60,18 +57,24 @@
应用可能请求“后台位置”权限,您可以拒绝它。
(前台)位置权限是较新版安卓系统扫描蓝牙设备所需要的。

建议将扫描时间设为 1 秒。

### Windows

获取名称中有 "windows" 的版本,
解压并运行 `start.bat`

Windows 通常需要较长的扫描时间。默认为 4 秒,可按需调整。

### GNU/Linux

您可以获取“纯净(pure)”版,解压、在其中打开终端并输入:
```bash
python3 server.py
```

建议将扫描时间设为 2 秒。

在 Arch Linux 等发行版您可能需要首先安装 `bluez`
```bash
sudo pacman -S bluez bluez-utils
Expand Down
16 changes: 10 additions & 6 deletions server.py
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,7 @@ class PrinterServerError(PrinterError):
'json': 'application/json;charset=utf-8',
'png': 'image/png',
'svg': 'image/svg+xml;charset=utf-8',
'wasm': 'application/wasm',
'octet-stream': 'application/octet-stream'
}
def mime(url: str):
Expand All @@ -72,10 +73,10 @@ class PrinterServerHandler(BaseHTTPRequestHandler):

settings = DictAsObject({
'config_path': 'config.json',
'version': 2,
'version': 3,
'first_run': True,
'is_android': False,
'scan_timeout': 4.0,
'scan_time': 4.0,
'dry_run': False,
'energy': 0.2
})
Expand Down Expand Up @@ -193,11 +194,13 @@ def save_config(self):
def update_printer(self):
'Update `PrinterDriver` state/config'
self.printer.dry_run = self.settings.dry_run
self.printer.scan_timeout = self.settings.scan_timeout
self.printer.scan_time = self.settings.scan_time
self.printer.fake = self.settings.fake
self.printer.dump = self.settings.dump
self.printer.energy = self.settings.energy
self.printer.quality = self.settings.quality
if self.settings.energy is not None:
self.printer.energy = int(self.settings.energy)
if self.settings.quality is not None:
self.printer.quality = int(self.settings.quality)
self.printer.flip_h = self.settings.flip_h or self.settings.flip
self.printer.flip_v = self.settings.flip_v or self.settings.flip
self.printer.rtl = self.settings.force_rtl
Expand All @@ -218,7 +221,7 @@ def handle_api(self):
devices_list = [{
'name': device.name,
'address': device.address
} for device in self.printer.scan()]
} for device in self.printer.scan(everything=data.get('everything'))]
self.api_success({
'devices': devices_list
})
Expand Down Expand Up @@ -313,6 +316,7 @@ def __init__(self, server_address, RequestHandlerClass):
def finish_request(self, request, client_address):
if self.handler is None:
self.handler = self.handler_class(request, client_address, self)
self.handler.load_config()
with open(os.path.join('www', 'all_js.txt'), 'r', encoding='utf-8') as file:
for path in file.read().split('\n'):
if path != '':
Expand Down
2 changes: 1 addition & 1 deletion version
Original file line number Diff line number Diff line change
@@ -1 +1 @@
0.6.0.1
0.6.0.2
6 changes: 6 additions & 0 deletions wasm/0-compile.sh
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
#!/bin/sh
if [[ $1 == 1 ]]; then
npm run asbuild:release;
else
npm run asbuild:debug;
fi
24 changes: 24 additions & 0 deletions wasm/asconfig.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
{
"targets": {
"debug": {
"outFile": "../www/image-wasm.wasm",
"textFile": "../www/image-wasm.wat",
"sourceMap": true,
"debug": true
},
"release": {
"outFile": "../www/image-wasm.wasm",
"textFile": "../www/image-wasm.wat",
"sourceMap": true,
"optimizeLevel": 3,
"shrinkLevel": 0,
"converge": false,
"noAssert": false
}
},
"options": {
"exportRuntime": true,
"baseDir": ".",
"bindings": "esm"
}
}
Loading

0 comments on commit 500971a

Please sign in to comment.