diff --git a/.gitattributes b/.gitattributes new file mode 100644 index 0000000..ba92ec7 --- /dev/null +++ b/.gitattributes @@ -0,0 +1,16 @@ +* text=auto eol=lf +*.md text eol=lf +*.py text eol=lf +*.java text eol=lf +*.cpp text eol=lf +*.h text eol=lf +*.yml text eol=lf +gradlew text eol=lf +*.ps1 text eol=crlf +*.png binary +*.jpg binary +*.gif binary +*.mp4 binary +*.apk binary +*.epro2 binary +*.stl binary diff --git a/.github/ISSUE_TEMPLATE/bug_report.yml b/.github/ISSUE_TEMPLATE/bug_report.yml new file mode 100644 index 0000000..ba6cf7f --- /dev/null +++ b/.github/ISSUE_TEMPLATE/bug_report.yml @@ -0,0 +1,21 @@ +name: Bug report / 问题反馈 +description: Report a reproducible app, firmware or build problem. +body: + - type: textarea + id: versions + attributes: + label: Versions / 版本 + description: App, firmware commit, hardware revision, Android version and phone model. + validations: + required: true + - type: textarea + id: reproduce + attributes: + label: Steps, expected and actual behavior / 复现步骤与结果 + validations: + required: true + - type: textarea + id: evidence + attributes: + label: Logs or photos / 日志或照片 + description: Redact personal identifiers. State whether a real print was attempted. diff --git a/.github/dependabot.yml b/.github/dependabot.yml new file mode 100644 index 0000000..3a626c3 --- /dev/null +++ b/.github/dependabot.yml @@ -0,0 +1,6 @@ +version: 2 +updates: + - package-ecosystem: github-actions + directory: / + schedule: + interval: monthly diff --git a/.github/pull_request_template.md b/.github/pull_request_template.md new file mode 100644 index 0000000..8318f96 --- /dev/null +++ b/.github/pull_request_template.md @@ -0,0 +1,13 @@ +## Problem and behavior + +Describe the concrete trigger and resulting behavior. + +## Validation + +- Checks run: +- Versions affected: +- Physical validation performed or outstanding: + +## Documentation and compatibility + +Explain protocol, hardware, bilingual documentation and source-notice changes. diff --git a/.github/workflows/android.yml b/.github/workflows/android.yml new file mode 100644 index 0000000..2faa90c --- /dev/null +++ b/.github/workflows/android.yml @@ -0,0 +1,45 @@ +name: Android + +on: + push: + paths: ['software/android/**', '.github/workflows/android.yml'] + pull_request: + paths: ['software/android/**', '.github/workflows/android.yml'] + workflow_dispatch: + +permissions: + contents: read + +jobs: + build: + runs-on: ubuntu-latest + timeout-minutes: 25 + defaults: + run: + working-directory: software/android + steps: + - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4 + - uses: actions/setup-java@cf277c60eb25467037889841efdb72551f06f6c3 # v4 + with: + distribution: temurin + java-version: '17' + - uses: actions/setup-python@a26af69be951a213d495a4c3e4e4022e16d87065 # v5 + with: + python-version: '3.11' + - uses: android-actions/setup-android@9fc6c4e9069bf8d3d10b2204b1fb8f6ef7065407 # v3 + with: + packages: platform-tools + - name: Install pinned Android SDK components + run: sdkmanager 'platforms;android-32' 'build-tools;30.0.3' + - name: Host protocol and failure-boundary checks + run: python test-host.py + - name: Build and lint + run: | + chmod +x gradlew + ./gradlew --no-daemon assembleDebug lintDebug + - uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4 + with: + name: foli-android-debug + path: | + software/android/app/build/outputs/apk/debug/app-debug.apk + software/android/app/build/reports/lint-results-debug.html diff --git a/.github/workflows/firmware.yml b/.github/workflows/firmware.yml new file mode 100644 index 0000000..48f6da7 --- /dev/null +++ b/.github/workflows/firmware.yml @@ -0,0 +1,25 @@ +name: Firmware +on: + push: + paths: ['software/firmware/**', '.github/workflows/firmware.yml'] + pull_request: + paths: ['software/firmware/**', '.github/workflows/firmware.yml'] + workflow_dispatch: +permissions: + contents: read +jobs: + firmware: + runs-on: ubuntu-24.04 + steps: + - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4 + - uses: actions/setup-python@a26af69be951a213d495a4c3e4e4022e16d87065 # v5 + with: + python-version: '3.11' + - name: Host protocol and queue regression tests + run: | + g++ -std=c++11 -Wall -Wextra -Werror -I software/firmware/src software/firmware/tests/protocol_test.cpp -o /tmp/foli-protocol-tests + /tmp/foli-protocol-tests + - name: Install pinned build tool + run: python -m pip install platformio==6.2.0 + - name: Compile ESP32 firmware + run: pio run --project-dir software/firmware diff --git a/.github/workflows/quality.yml b/.github/workflows/quality.yml new file mode 100644 index 0000000..7383f45 --- /dev/null +++ b/.github/workflows/quality.yml @@ -0,0 +1,20 @@ +name: Documentation and assets +on: + push: + pull_request: + workflow_dispatch: +permissions: + contents: read +jobs: + integrity: + runs-on: ubuntu-24.04 + timeout-minutes: 10 + steps: + - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4 + - uses: actions/setup-python@a26af69be951a213d495a4c3e4e4022e16d87065 # v5 + with: + python-version: '3.11' + - run: python tools/check_docs.py + - run: python tools/check_assets.py + - name: Parse Python tooling + run: python -m compileall -q tools software/android/test-host.py diff --git a/.gitignore b/.gitignore index 0fd21d3..f78b639 100644 --- a/.gitignore +++ b/.gitignore @@ -1,9 +1,24 @@ .pio/ -.pioenvs/ -.piolibdeps/ -.vscode/ +.gradle/ +**/build/ +**/__pycache__/ +*.py[cod] +.venv/ .idea/ -*.o -*.bin -*.elf +.vscode/ +local.properties .DS_Store +Thumbs.db +*.jks +*.keystore +.env +.env.* +!.env.example +tools/runtime/ +media/source/work/ +mechanical/cad/*.step +mechanical/cad/*.STEP +*.blend1 + +*.log +media/rendered/ diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md new file mode 100644 index 0000000..5c972c8 --- /dev/null +++ b/CONTRIBUTING.md @@ -0,0 +1,13 @@ +# Contributing / 参与贡献 + +Read [getting started](docs/en/getting-started.md) and [verification](docs/en/verification.md). Keep changes focused and describe affected app, firmware and hardware revisions. + +1. Explain the problem and resulting behavior. +2. Coordinate Android/firmware protocol changes and document compatibility. +3. Run relevant checks: `python tools/check_docs.py`, `python tools/check_assets.py`, `python software/android/test-host.py`, Android build/Lint, or firmware build/host tests. +4. Update corresponding English/Chinese guidance and retain source notices. +5. State what was verified and what remains outstanding. Compiling firmware is not a physical printer test. + +Do not commit SDKs, caches, local paths, signing keys, personal device logs or intermediate frames. Report potential vulnerabilities via [SECURITY.md](SECURITY.md). + +中文:请先阅读[入门](docs/zh-CN/getting-started.md)与[验证](docs/zh-CN/verification.md)。提交写明版本、变化、检查结果和未验证范围;协议变更需考虑两端兼容,更新双语说明,保留来源。不提交密钥、个人日志、SDK、缓存或媒体中间帧。 diff --git a/NOTICE.md b/NOTICE.md new file mode 100644 index 0000000..a85ae67 --- /dev/null +++ b/NOTICE.md @@ -0,0 +1,9 @@ +# Sources and notices / 来源说明 + +The existing [MIT license](LICENSE) is retained for this repository's software. Preserve original notices in inherited code and dependencies. Android notices are listed in [THIRD_PARTY_NOTICES.md](software/android/THIRD_PARTY_NOTICES.md). + +Hardware and mechanical source materials were supplied by the project owner, who confirms purchasing rights to the original Mini-Printer project. Source credits identify the inherited platform; new FOLI Android implementation, integration changes and presentation work are documented separately. This notice does not erase third-party terms or invent an additional upstream license grant. + +Generated lifestyle concepts, actual CAD renders, historical photos, UI captures/reconstructions and original synthesized music are itemized in [provenance](docs/en/provenance.md) and the [media manifest](media/manifest.json). System fonts are not bundled. Do not describe synthesized media as physical test evidence. + +中文:保留原 MIT 文件及上游、依赖与素材说明。项目所有者提供硬件/机械资料并确认已购买原项目权利;新增实现与既有基础分别记录,不凭此文件编造其他上游授权。详见[中文来源说明](docs/zh-CN/provenance.md)。 diff --git a/README.md b/README.md index 06e4a4c..24508ac 100644 --- a/README.md +++ b/README.md @@ -1,112 +1,72 @@ -# MINI PRINTER — 便携式蓝牙热敏打印机 +

FOLI

+

Little prints. Everyday joy.

+

A little thought. Made tangible.

+

English · 简体中文

+

Get Android · Get started · Explore the engineering

-![硬件测试](docs/images/hardware-test-bench.jpg) +[![Android](https://github.com/TYF009/Mini-Printer/actions/workflows/android.yml/badge.svg)](https://github.com/TYF009/Mini-Printer/actions/workflows/android.yml) +[![Firmware](https://github.com/TYF009/Mini-Printer/actions/workflows/firmware.yml/badge.svg)](https://github.com/TYF009/Mini-Printer/actions/workflows/firmware.yml) +[![Documentation](https://github.com/TYF009/Mini-Printer/actions/workflows/quality.yml/badge.svg)](https://github.com/TYF009/Mini-Printer/actions/workflows/quality.yml) -电池供电的小型蓝牙热敏打印机:手机通过 BLE 发送单色位图,ESP32 流式缓存并逐行驱动热敏打印头打印。硬件为两层板,锂电池供电,集成充电、升压、电机驱动与多种传感器监测。 +[![Watch FOLI — Made Tangible](media/images/hero.jpg)](media/video/FOLI-Made-Tangible-90s.mp4) -**打印测试页**(全字符集 + 校验色块,实测参数:VH 8101mV / 打印头温度 28℃): +**[Watch the 90-second film →](media/video/FOLI-Made-Tangible-90s.mp4)** -![打印测试页](docs/images/print-test-page.jpg) +FOLI is a complete mini thermal-printer project: battery-powered ESP32 electronics, embedded control, a printable enclosure and a native Android companion. Together, they turn notes, lists and little messages into monochrome paper you can keep close. -**PCB 3D 视图**: +A short list beside your keyboard. A few words tucked into a gift. A reminder for the day ahead. -| 顶面 | 底面 | -|---|---| -| ![PCB顶面](docs/images/pcb-3d-top.png) | ![PCB底面](docs/images/pcb-3d-bottom.png) | - -> 项目性质:个人复刻/学习项目。硬件参考原始设计(V4 引脚版本)完成,固件经逐行阅读梳理并记录已知问题,手机 App 使用小智学长开源的 Mini-Printer App。 - -## 文档导航(按阅读顺序) - -**一、项目总览**:产品定义、需求拆解、主控选型、系统架构 → [docs/01-项目总览.md](docs/01-项目总览.md) +*Lifestyle concept visuals, actual CAD geometry, reconstructed app interactions and illustrative paper-feed animation.* -**二、硬件设计**([docs/02-硬件设计/](docs/02-硬件设计/)): +## One little flow, three places -| 章节 | 内容 | -|---|---| -| [01-最小系统](docs/02-硬件设计/01-最小系统.md) | Type-C 供电/烧录电路、CH340C、DTR/RTS 交叉耦合自动下载电路 | -| [02-电源架构](docs/02-硬件设计/02-电源架构.md) | 充电管理、LDO 稳压、AP2005 升压 VH 及 Layout 要点 | -| [03-电量检测与输入指示](docs/02-硬件设计/03-电量检测与输入指示.md) | 分压采样、按键、LED 状态设计 | -| [04-打印模组](docs/02-硬件设计/04-打印模组.md) | 一体化机芯、NTC 测温、光电缺纸检测、TC1508S 电机驱动、FPC 接口 | -| [05-PCB-Layout](docs/02-硬件设计/05-PCB-Layout.md) | 结构约束布局、电源走线、铺铜与 DRC 检查 | +![Create, Templates and Device](media/gifs/app-tour.gif) -**三、软件设计**([docs/03-软件设计/](docs/03-软件设计/)): +| Create | Templates | Device | +|---|---|---| +| Shape your words, choose a paper style and inspect the monochrome preview | Start with eight templates, filter, save and make one yours | Discover the printer, inspect reported state and find printing help | -| 章节 | 内容 | -|---|---| -| [01-工程结构与任务模型](docs/03-软件设计/01-工程结构与任务模型.md) | 分层架构、FreeRTOS 三任务 + 定时器 + 中断 | -| [02-消息队列](docs/03-软件设计/02-消息队列.md) | 环形打印缓冲(1000 行×48B)与并发安全 | -| [03-LED与按键](docs/03-软件设计/03-LED与按键.md) | 四态指示、消抖状态机 | -| [04-电量采集](docs/03-软件设计/04-电量采集.md) | ADC eFuse 校准、电压→电量换算 | -| [05-BLE通信](docs/03-软件设计/05-BLE通信.md) | Service/Characteristic 模型、收发流程、防丢包设计 | -| [06-缺纸与温度](docs/03-软件设计/06-缺纸与温度.md) | 中断检测、NTC B 值公式、过热保护 | -| [07-步进电机](docs/03-软件设计/07-步进电机.md) | 四相八拍、2ms 节拍、4 步=行高 | -| [08-打印驱动](docs/03-软件设计/08-打印驱动.md) | SPI→LAT→STB 分时加热时序、动态加热补偿、电源时序规则 | - -**四、项目整合**([docs/04-项目整合/](docs/04-项目整合/)): - -| 章节 | 内容 | -|---|---| -| [01-App与整机联调](docs/04-项目整合/01-App与整机联调.md) | 开源 App 对接、图片二值化、A6 开始打印指令的由来 | -| [02-已知问题与修复记录](docs/04-项目整合/02-已知问题与修复记录.md) | 17 条已知问题清单与修复进展 | +No account is required. Editing and preview work offline; physical printing needs matching hardware. The tour combines actual captures with interaction visualization; Device is reconstructed from current source in the disconnected state. -**速查参考**:[引脚分配表](docs/pinout.md) · [BLE 协议](docs/ble-protocol.md) · [架构总览](docs/architecture.md) +[Download 0.2.1 development APK](releases/android/FOLI-0.2.1-debug.apk) · [Android source and build guide](software/android/README.md) -## 仓库结构 +## From the screen to the paper -``` -mini-printer/ -├── hardware/ -│ ├── EDA-project/ # 嘉立创EDA专业版工程(.epro2) -│ └── exports/ # Gerber 生产文件 / 原理图 / BOM(可直接打样) -├── software/firmware/ # PlatformIO 工程(ESP32 + Arduino + FreeRTOS) -└── docs/ # 全部设计文档与图片 -``` +![Software-to-paper system architecture](media/images/system-architecture.png) -## 系统概览 +The Android renderer turns a layout into a 384-dot monochrome raster. Each row occupies 48 bytes. BLE carries row data to firmware that coordinates the thermal head and paper feed. The enclosure brings the battery, board, roll and mechanism together. -- **主控**:ESP32-S 模组(BLE 4.2) -- **打印头**:384 点/行热敏打印头,6 路 STB 分时加热,32Pin FPC 连接 -- **走纸**:两相步进电机 + TC1508S 双 H 桥 -- **供电**:2000mAh 动力锂电池(Type-C 充电,ME4054),PMOS 软开关机,AP2005 升压 7.2V 供打印头,XC6210 LDO 3.3V 供数字 -- **监测**:电池电量(分压+ADC eFuse 校准)、打印头温度(NTC + B 值公式,>65℃ 保护)、缺纸(LM393 + GPIO 中断) +![Annotated CAD assembly](media/images/assembly-explained.jpg) -**数据流**:手机 App 编辑排版 --BLE--> ESP32 接收入环形缓冲 --> 打印任务逐行取数 --> SPI 送数 / LAT 锁存 / 6 路 STB 分时加热 + 步进电机走纸 --> 热敏纸成像;全程由电量、温度、缺纸三类监测保护。 +[Architecture and protocol](docs/en/architecture.md) · [Hardware](hardware/README.md) · [Mechanical and assembly](mechanical/README.md) · [Firmware](software/firmware/) -### 软件任务模型 +## Decisions behind the experience -| 任务/中断 | 优先级 | 周期/触发 | 职责 | -|---|---|---|---| -| 打印主任务(loop) | 1 | 常驻 | 打印状态机、打印头时序驱动 | -| 上报任务 | 1 | 100ms | 传感器采集 + BLE 上报;缺纸事件处理 | -| 按键任务 | 0 | 10ms | 消抖、短按(自检)/长按(走纸) | -| Ticker 定时器 | — | 2ms/10s/20s | 电机步进 / 状态刷新 / 打印超时 | -| GPIO 中断 | — | 上升沿 | 缺纸检测 | +- **Preview the raster that will be sent.** Preview and transmission share the encoder, so the paper view reflects monochrome output. +- **Design for an older phone.** Xiaomi Mi 6 checks informed keyboard layout, editor controls and explicit checklist rendering. +- **Separate connection, transfer and completion.** Interrupted or unconfirmed jobs use conservative recovery. Firmware hardening addresses command framing and fault shutdown paths. -## 编译与烧录 +[Read the engineering case study](docs/en/product-case-study.md) · [Verification and known limits](docs/en/verification.md) -```bash -cd software/firmware -pio run # 编译 -pio run -t upload # 烧录(Type-C 直插,板载 CH340C + 自动下载电路) -pio device monitor # 串口监视 -``` +## Built, wired, on paper -环境:PlatformIO,`[env:esp32dev]`,Arduino 框架(依赖 Arduino-ESP32 2.x,3.x 已移除 `ledcSetup` 等接口,建议锁定 espressif32 平台版本)。 +![Historical hardware and print-test photographs](media/images/hardware-evidence.jpg) -## 待办与改进 +Physical hardware has been assembled and previously print-tested. Android 0.2.0 was inspected on Xiaomi Mi 6 for UI and BLE state. Version 0.2.1 adds BLE exception recovery with software checks. The hardened firmware and new app have not been revalidated together in a fresh physical print. -- [x] ~~实物照片 / 打印效果照片~~(docs/images/) -- [x] ~~原理图、Gerber、BOM 导出~~(hardware/exports/,Gerber 可直接下单打样) -- [ ] 修复 [已知问题](docs/04-项目整合/02-已知问题与修复记录.md) 高优先级四项(按键任务饿死 / A6 误入队 / 低电量显示 / 缓冲残留) -- [ ] 打印耗时实测(验证动态加热收益) -- [ ] 状态包增加包头与校验 +## Explore the build -## 致谢 +| Your next step | Start here | +|---|---| +| Try the app without a printer | [Installation and usage](docs/en/getting-started.md) | +| Build Android | [JDK, SDK and build commands](software/android/README.md) | +| Build and flash firmware | [PlatformIO project](software/firmware/README.md) | +| Inspect or manufacture the board | [Final project, BOM and exports](hardware/README.md) | +| Make the enclosure | [STLs, source mapping and assembly](mechanical/README.md) | +| Reuse the product media | [Provenance and rebuild guide](media/README.md) | -- 手机 App:小智学长开源的 Mini-Printer App -- 本项目硬件在原始设计(V4 引脚版本)基础上复刻完成,仅用于个人学习。如有侵权请联系删除。 +## Open development -## License +This repository retains the Mini-Printer history and integrates the FOLI Android app, product design, mechanical assets, presentation media and reliability work. [Sources and contributions](docs/en/provenance.md) distinguish the inherited platform from new implementation. -MIT +[Roadmap](ROADMAP.md) · [Contributing](CONTRIBUTING.md) · [Versions and downloads](releases/README.md) · [License](LICENSE) · [Third-party and media notices](NOTICE.md) diff --git a/README.zh-CN.md b/README.zh-CN.md new file mode 100644 index 0000000..b594651 --- /dev/null +++ b/README.zh-CN.md @@ -0,0 +1,72 @@ +

FOLI

+

Little prints. Everyday joy.

+

让一份小小的想法,从手机走到纸上。

+

English · 简体中文

+

下载 Android · 快速开始 · 工程文档

+ +[![Android](https://github.com/TYF009/Mini-Printer/actions/workflows/android.yml/badge.svg)](https://github.com/TYF009/Mini-Printer/actions/workflows/android.yml) +[![固件](https://github.com/TYF009/Mini-Printer/actions/workflows/firmware.yml/badge.svg)](https://github.com/TYF009/Mini-Printer/actions/workflows/firmware.yml) +[![文档](https://github.com/TYF009/Mini-Printer/actions/workflows/quality.yml/badge.svg)](https://github.com/TYF009/Mini-Printer/actions/workflows/quality.yml) + +[![FOLI 产品展示视频](media/images/hero.jpg)](media/video/FOLI-Made-Tangible-90s.mp4) + +**[观看 90 秒产品片 →](media/video/FOLI-Made-Tangible-90s.mp4)** + +FOLI 是一个完整的便携热敏打印机项目:电池供电的 ESP32 电路、嵌入式控制、可打印外壳和原生 Android 应用,共同将便签、清单与心意变成小小的黑白纸条。 + +一张待办放在键盘旁,一段鼓励夹进礼物,一份清单随身带走。 + +*生活场景为概念视觉,产品结构基于实际 CAD;影片含交互重建和三维出纸示意。* + +## 一份内容,三个入口 + +![Create、Templates、Device 三屏演示](media/gifs/app-tour.gif) + +| Create | Templates | Device | +|---|---|---| +| 编辑文字、选择纸面风格、检查黑白预览 | 从八个模板出发,筛选、收藏与应用 | 发现设备、查看上报状态与打印帮助 | + +无需账户,编辑和预览可离线使用;实际打印需要匹配设备。演示采用真实界面与交互重建,Device 为当前源码重建的未连接页面。 + +[下载 0.2.1 开发版](releases/android/FOLI-0.2.1-debug.apk) · [Android 源码与构建](software/android/README.zh-CN.md) + +## 从软件到纸张 + +![系统链路](media/images/system-architecture.png) + +同一份排版先生成 384 点宽的单色光栅,再以每行 48 字节通过 BLE 发送到固件,由固件协调打印头与走纸。外壳把电源、电路、纸卷和机构整合为完整产品。 + +![结构展开](media/images/assembly-explained.jpg) + +[架构与协议](docs/zh-CN/architecture.md) · [硬件文件](hardware/README.zh-CN.md) · [机械与装配](mechanical/README.zh-CN.md) · [固件源码](software/firmware/) + +## 让体验成立的工程选择 + +- **预览要反映实际光栅。** 纸面预览和发送数据共用编码路径,避免把美化稿当成打印结果。 +- **低配置手机也是设计条件。** 小米 6 的实际检查推动了键盘布局、编辑控件和复选框绘制的改进。 +- **连接、发送与完成是不同状态。** 中断和未确认任务采用保守恢复策略;固件加固覆盖命令组行和故障停止路径。 + +[完整工程案例](docs/zh-CN/product-case-study.md) · [验证范围与已知限制](docs/zh-CN/verification.md) + +## 真实硬件,真实纸张 + +![已有硬件与历史打印结果](media/images/hardware-evidence.jpg) + +实物硬件已装配并历史打印成功。Android 0.2.0 曾在小米 6 上检查界面与 BLE 状态;0.2.1 包含蓝牙异常恢复修复和软件检查。此次加固后的固件与新 App 尚未重新完成整机打印验证。 + +## 开始探索 + +| 你想做什么 | 入口 | +|---|---| +| 先试应用,无需打印机 | [安装和使用](docs/zh-CN/getting-started.md) | +| 构建 Android | [JDK、SDK 与构建命令](software/android/README.zh-CN.md) | +| 编译、烧录固件 | [PlatformIO 工程](software/firmware/README.md) | +| 查看或制造电路 | [最终工程、BOM 与制造导出](hardware/README.zh-CN.md) | +| 制作外壳 | [STL、文件映射与装配说明](mechanical/README.zh-CN.md) | +| 复用产品媒体 | [素材来源与重建](media/README.zh-CN.md) | + +## 项目维护 + +本仓库保留原 Mini-Printer 历史,并整合 FOLI 原生 App、产品设计、机械文件、媒体与可靠性改进。[来源与贡献说明](docs/zh-CN/provenance.md)区分已有基础与新增实现。 + +[路线图](ROADMAP.md) · [参与贡献](CONTRIBUTING.md) · [发布与版本](releases/README.zh-CN.md) · [许可](LICENSE) · [第三方与素材说明](NOTICE.md) diff --git a/ROADMAP.md b/ROADMAP.md new file mode 100644 index 0000000..a94a418 --- /dev/null +++ b/ROADMAP.md @@ -0,0 +1,22 @@ +# Roadmap / 路线图 + +## Included in this integration + +- English-first presentation and matching Chinese guidance. +- Android 0.2.1, regression checks and BLE exception recovery. +- Firmware framing/fault-exit hardening with explicit verification scope. +- Final supplied board source, existing exports and named enclosure STLs. +- Product film, app tour and engineering evidence with provenance. + +## Next milestones + +- Physically validate the hardened firmware and latest Android together when hardware testing resumes. +- Reconcile final battery/BOM/FPC specifications against actual purchased parts. +- Record assembled-device photography, slicer settings and numbered assembly steps. +- Resolve idle temperature and strengthen print completion/flow control. +- Evaluate typed Android job events and separate editor/navigation/device responsibilities. +- Evaluate signed release distribution and a current target SDK separately from this development APK. + +These are planned improvements, not completed features or promised dates. + +中文:后续优先完成联合实物验证、最终参数/BOM核对、整机照片与切片装配记录、温度与完成状态完善,再评估正式签名发行与 App 架构拆分。以上为计划,不代表已实现或交付日期承诺。 diff --git a/SECURITY.md b/SECURITY.md new file mode 100644 index 0000000..e99ccf2 --- /dev/null +++ b/SECURITY.md @@ -0,0 +1,9 @@ +# Security reporting / 安全问题反馈 + +This open hardware project includes a development Android build. It does not claim commercial certification, an authenticated BLE transport or a security audit. + +Use GitHub private vulnerability reporting if available. Otherwise open a minimal issue requesting a private contact route; omit exploit details, device identifiers and personal data until a private route is agreed. No response-time SLA is promised. + +Ordinary bugs and build failures belong in public issues. Never publish keys, tokens or unredacted personal logs. + +中文:涉及隐私或可利用行为的问题,优先使用仓库可用的私密漏洞报告入口;否则先创建仅请求私下联系渠道的问题,不公开利用细节或个人设备信息。普通问题可公开反馈,本项目不承诺安全审计或企业服务 SLA。 diff --git "a/docs/01-\351\241\271\347\233\256\346\200\273\350\247\210.md" "b/docs/01-\351\241\271\347\233\256\346\200\273\350\247\210.md" index 329c99a..9496263 100644 --- "a/docs/01-\351\241\271\347\233\256\346\200\273\350\247\210.md" +++ "b/docs/01-\351\241\271\347\233\256\346\200\273\350\247\210.md" @@ -1,3 +1,5 @@ +> 历史参考:本页保留原项目设计与问题记录,可能描述修复前行为。当前版本请从 [FOLI 中文文档](zh-CN/index.md) 进入。 + # 01 · 项目总览 ## 1. 项目背景 diff --git "a/docs/02-\347\241\254\344\273\266\350\256\276\350\256\241/01-\346\234\200\345\260\217\347\263\273\347\273\237.md" "b/docs/02-\347\241\254\344\273\266\350\256\276\350\256\241/01-\346\234\200\345\260\217\347\263\273\347\273\237.md" index 93c27ea..6981bb6 100644 --- "a/docs/02-\347\241\254\344\273\266\350\256\276\350\256\241/01-\346\234\200\345\260\217\347\263\273\347\273\237.md" +++ "b/docs/02-\347\241\254\344\273\266\350\256\276\350\256\241/01-\346\234\200\345\260\217\347\263\273\347\273\237.md" @@ -1,3 +1,5 @@ +> 历史参考:本页保留原项目设计与问题记录,可能描述修复前行为。当前版本请从 [FOLI 中文文档](../zh-CN/index.md) 进入。 + # ESP32 最小系统:供电 / 烧录 / 调试 ![Type-C 接口电路](../images/hw-minsys-typec.png) diff --git "a/docs/02-\347\241\254\344\273\266\350\256\276\350\256\241/02-\347\224\265\346\272\220\346\236\266\346\236\204.md" "b/docs/02-\347\241\254\344\273\266\350\256\276\350\256\241/02-\347\224\265\346\272\220\346\236\266\346\236\204.md" index 87c632b..804ac2d 100644 --- "a/docs/02-\347\241\254\344\273\266\350\256\276\350\256\241/02-\347\224\265\346\272\220\346\236\266\346\236\204.md" +++ "b/docs/02-\347\241\254\344\273\266\350\256\276\350\256\241/02-\347\224\265\346\272\220\346\236\266\346\236\204.md" @@ -1,3 +1,5 @@ +> 历史参考:本页保留原项目设计与问题记录,可能描述修复前行为。当前版本请从 [FOLI 中文文档](../zh-CN/index.md) 进入。 + # 电源架构 ## 先看全景:一棵两分支的电源树 diff --git "a/docs/02-\347\241\254\344\273\266\350\256\276\350\256\241/03-\347\224\265\351\207\217\346\243\200\346\265\213\344\270\216\344\272\272\346\234\272\344\272\244\344\272\222.md" "b/docs/02-\347\241\254\344\273\266\350\256\276\350\256\241/03-\347\224\265\351\207\217\346\243\200\346\265\213\344\270\216\344\272\272\346\234\272\344\272\244\344\272\222.md" index a6848e4..323a9a3 100644 --- "a/docs/02-\347\241\254\344\273\266\350\256\276\350\256\241/03-\347\224\265\351\207\217\346\243\200\346\265\213\344\270\216\344\272\272\346\234\272\344\272\244\344\272\222.md" +++ "b/docs/02-\347\241\254\344\273\266\350\256\276\350\256\241/03-\347\224\265\351\207\217\346\243\200\346\265\213\344\270\216\344\272\272\346\234\272\344\272\244\344\272\222.md" @@ -1,3 +1,5 @@ +> 历史参考:本页保留原项目设计与问题记录,可能描述修复前行为。当前版本请从 [FOLI 中文文档](../zh-CN/index.md) 进入。 + # 电量检测与人机交互 一台没有屏幕的设备,用户能感知它的方式只有三种:还剩多少电、按了有没有反应、灯亮不亮。这三个交互分别对应本节的三小块电路。共同点是便宜、省电、够用——每块的器件数都在三颗以内。 diff --git "a/docs/02-\347\241\254\344\273\266\350\256\276\350\256\241/04-\346\211\223\345\215\260\346\250\241\347\273\204.md" "b/docs/02-\347\241\254\344\273\266\350\256\276\350\256\241/04-\346\211\223\345\215\260\346\250\241\347\273\204.md" index 2a2c23b..30cdfda 100644 --- "a/docs/02-\347\241\254\344\273\266\350\256\276\350\256\241/04-\346\211\223\345\215\260\346\250\241\347\273\204.md" +++ "b/docs/02-\347\241\254\344\273\266\350\256\276\350\256\241/04-\346\211\223\345\215\260\346\250\241\347\273\204.md" @@ -1,3 +1,5 @@ +> 历史参考:本页保留原项目设计与问题记录,可能描述修复前行为。当前版本请从 [FOLI 中文文档](../zh-CN/index.md) 进入。 + # 打印模组 ![打印模组结构](../images/hw-print-module.png) diff --git "a/docs/02-\347\241\254\344\273\266\350\256\276\350\256\241/05-PCB-Layout.md" "b/docs/02-\347\241\254\344\273\266\350\256\276\350\256\241/05-PCB-Layout.md" index dc90bee..65f83dc 100644 --- "a/docs/02-\347\241\254\344\273\266\350\256\276\350\256\241/05-PCB-Layout.md" +++ "b/docs/02-\347\241\254\344\273\266\350\256\276\350\256\241/05-PCB-Layout.md" @@ -1,3 +1,5 @@ +> 历史参考:本页保留原项目设计与问题记录,可能描述修复前行为。当前版本请从 [FOLI 中文文档](../zh-CN/index.md) 进入。 + # PCB Layout ![顶层布局](../images/hw-pcb-top.png) diff --git "a/docs/03-\350\275\257\344\273\266\350\256\276\350\256\241/01-\345\267\245\347\250\213\347\273\223\346\236\204\344\270\216\344\273\273\345\212\241\346\250\241\345\236\213.md" "b/docs/03-\350\275\257\344\273\266\350\256\276\350\256\241/01-\345\267\245\347\250\213\347\273\223\346\236\204\344\270\216\344\273\273\345\212\241\346\250\241\345\236\213.md" index a5f8a30..31a0bb7 100644 --- "a/docs/03-\350\275\257\344\273\266\350\256\276\350\256\241/01-\345\267\245\347\250\213\347\273\223\346\236\204\344\270\216\344\273\273\345\212\241\346\250\241\345\236\213.md" +++ "b/docs/03-\350\275\257\344\273\266\350\256\276\350\256\241/01-\345\267\245\347\250\213\347\273\223\346\236\204\344\270\216\344\273\273\345\212\241\346\250\241\345\236\213.md" @@ -1,3 +1,5 @@ +> 历史参考:本页保留原项目设计与问题记录,可能描述修复前行为。当前版本请从 [FOLI 中文文档](../zh-CN/index.md) 进入。 + # 03-软件设计 · 01 · 工程结构与任务模型 ## 1. 工程结构 diff --git "a/docs/03-\350\275\257\344\273\266\350\256\276\350\256\241/02-\346\266\210\346\201\257\351\230\237\345\210\227.md" "b/docs/03-\350\275\257\344\273\266\350\256\276\350\256\241/02-\346\266\210\346\201\257\351\230\237\345\210\227.md" index 5269533..51be0bb 100644 --- "a/docs/03-\350\275\257\344\273\266\350\256\276\350\256\241/02-\346\266\210\346\201\257\351\230\237\345\210\227.md" +++ "b/docs/03-\350\275\257\344\273\266\350\256\276\350\256\241/02-\346\266\210\346\201\257\351\230\237\345\210\227.md" @@ -1,3 +1,5 @@ +> 历史参考:本页保留原项目设计与问题记录,可能描述修复前行为。当前版本请从 [FOLI 中文文档](../zh-CN/index.md) 进入。 + # 03-软件设计 · 02 · 消息队列(环形打印缓冲) ## 1. 为什么需要队列 diff --git "a/docs/03-\350\275\257\344\273\266\350\256\276\350\256\241/03-LED\344\270\216\346\214\211\351\224\256.md" "b/docs/03-\350\275\257\344\273\266\350\256\276\350\256\241/03-LED\344\270\216\346\214\211\351\224\256.md" index 8779bfd..a217e7e 100644 --- "a/docs/03-\350\275\257\344\273\266\350\256\276\350\256\241/03-LED\344\270\216\346\214\211\351\224\256.md" +++ "b/docs/03-\350\275\257\344\273\266\350\256\276\350\256\241/03-LED\344\270\216\346\214\211\351\224\256.md" @@ -1,3 +1,5 @@ +> 历史参考:本页保留原项目设计与问题记录,可能描述修复前行为。当前版本请从 [FOLI 中文文档](../zh-CN/index.md) 进入。 + # 03-软件设计 · 03 · LED 指示与按键状态机 > 实验 安全提示:非打印头相关的实验(LED、按键、电量)不要接打印头。 diff --git "a/docs/03-\350\275\257\344\273\266\350\256\276\350\256\241/04-\347\224\265\351\207\217\351\207\207\351\233\206.md" "b/docs/03-\350\275\257\344\273\266\350\256\276\350\256\241/04-\347\224\265\351\207\217\351\207\207\351\233\206.md" index 8cef359..d9e0f0f 100644 --- "a/docs/03-\350\275\257\344\273\266\350\256\276\350\256\241/04-\347\224\265\351\207\217\351\207\207\351\233\206.md" +++ "b/docs/03-\350\275\257\344\273\266\350\256\276\350\256\241/04-\347\224\265\351\207\217\351\207\207\351\233\206.md" @@ -1,3 +1,5 @@ +> 历史参考:本页保留原项目设计与问题记录,可能描述修复前行为。当前版本请从 [FOLI 中文文档](../zh-CN/index.md) 进入。 + # 03-软件设计 · 04 · 电量采集 ## 1. 需求与原理 diff --git "a/docs/03-\350\275\257\344\273\266\350\256\276\350\256\241/05-BLE\351\200\232\344\277\241.md" "b/docs/03-\350\275\257\344\273\266\350\256\276\350\256\241/05-BLE\351\200\232\344\277\241.md" index 9aa3bba..b5f8838 100644 --- "a/docs/03-\350\275\257\344\273\266\350\256\276\350\256\241/05-BLE\351\200\232\344\277\241.md" +++ "b/docs/03-\350\275\257\344\273\266\350\256\276\350\256\241/05-BLE\351\200\232\344\277\241.md" @@ -1,3 +1,5 @@ +> 历史参考:本页保留原项目设计与问题记录,可能描述修复前行为。当前版本请从 [FOLI 中文文档](../zh-CN/index.md) 进入。 + # 03-软件设计 · 05 · BLE 蓝牙通信 ## 1. 需求与选型 diff --git "a/docs/03-\350\275\257\344\273\266\350\256\276\350\256\241/06-\347\274\272\347\272\270\344\270\216\346\270\251\345\272\246.md" "b/docs/03-\350\275\257\344\273\266\350\256\276\350\256\241/06-\347\274\272\347\272\270\344\270\216\346\270\251\345\272\246.md" index 5d521db..2e9fcfe 100644 --- "a/docs/03-\350\275\257\344\273\266\350\256\276\350\256\241/06-\347\274\272\347\272\270\344\270\216\346\270\251\345\272\246.md" +++ "b/docs/03-\350\275\257\344\273\266\350\256\276\350\256\241/06-\347\274\272\347\272\270\344\270\216\346\270\251\345\272\246.md" @@ -1,3 +1,5 @@ +> 历史参考:本页保留原项目设计与问题记录,可能描述修复前行为。当前版本请从 [FOLI 中文文档](../zh-CN/index.md) 进入。 + # 03-软件设计 · 06 · 缺纸检测与打印头温度 ## 1. 缺纸检测(GPIO35) diff --git "a/docs/03-\350\275\257\344\273\266\350\256\276\350\256\241/07-\346\255\245\350\277\233\347\224\265\346\234\272.md" "b/docs/03-\350\275\257\344\273\266\350\256\276\350\256\241/07-\346\255\245\350\277\233\347\224\265\346\234\272.md" index cb93dce..1fe05b8 100644 --- "a/docs/03-\350\275\257\344\273\266\350\256\276\350\256\241/07-\346\255\245\350\277\233\347\224\265\346\234\272.md" +++ "b/docs/03-\350\275\257\344\273\266\350\256\276\350\256\241/07-\346\255\245\350\277\233\347\224\265\346\234\272.md" @@ -1,3 +1,5 @@ +> 历史参考:本页保留原项目设计与问题记录,可能描述修复前行为。当前版本请从 [FOLI 中文文档](../zh-CN/index.md) 进入。 + # 03-软件设计 · 07 · 步进电机驱动 ## 1. 需求 diff --git "a/docs/03-\350\275\257\344\273\266\350\256\276\350\256\241/08-\346\211\223\345\215\260\351\251\261\345\212\250.md" "b/docs/03-\350\275\257\344\273\266\350\256\276\350\256\241/08-\346\211\223\345\215\260\351\251\261\345\212\250.md" index 8f530f1..0944bb7 100644 --- "a/docs/03-\350\275\257\344\273\266\350\256\276\350\256\241/08-\346\211\223\345\215\260\351\251\261\345\212\250.md" +++ "b/docs/03-\350\275\257\344\273\266\350\256\276\350\256\241/08-\346\211\223\345\215\260\351\251\261\345\212\250.md" @@ -1,3 +1,5 @@ +> 历史参考:本页保留原项目设计与问题记录,可能描述修复前行为。当前版本请从 [FOLI 中文文档](../zh-CN/index.md) 进入。 + # 03-软件设计 · 08 · 打印驱动(核心模块) ## 1. 初始化 diff --git "a/docs/04-\351\241\271\347\233\256\346\225\264\345\220\210/01-App\344\270\216\346\225\264\346\234\272\350\201\224\350\260\203.md" "b/docs/04-\351\241\271\347\233\256\346\225\264\345\220\210/01-App\344\270\216\346\225\264\346\234\272\350\201\224\350\260\203.md" index ec95af0..395bffe 100644 --- "a/docs/04-\351\241\271\347\233\256\346\225\264\345\220\210/01-App\344\270\216\346\225\264\346\234\272\350\201\224\350\260\203.md" +++ "b/docs/04-\351\241\271\347\233\256\346\225\264\345\220\210/01-App\344\270\216\346\225\264\346\234\272\350\201\224\350\260\203.md" @@ -1,3 +1,5 @@ +> 历史参考:本页保留原项目设计与问题记录,可能描述修复前行为。当前版本请从 [FOLI 中文文档](../zh-CN/index.md) 进入。 + # 04-项目整合 · 01 · 手机 App 与整机联调 ## 1. App 说明 diff --git "a/docs/04-\351\241\271\347\233\256\346\225\264\345\220\210/02-\345\267\262\347\237\245\351\227\256\351\242\230\344\270\216\344\277\256\345\244\215\350\256\260\345\275\225.md" "b/docs/04-\351\241\271\347\233\256\346\225\264\345\220\210/02-\345\267\262\347\237\245\351\227\256\351\242\230\344\270\216\344\277\256\345\244\215\350\256\260\345\275\225.md" index 3ff19d7..96967ca 100644 --- "a/docs/04-\351\241\271\347\233\256\346\225\264\345\220\210/02-\345\267\262\347\237\245\351\227\256\351\242\230\344\270\216\344\277\256\345\244\215\350\256\260\345\275\225.md" +++ "b/docs/04-\351\241\271\347\233\256\346\225\264\345\220\210/02-\345\267\262\347\237\245\351\227\256\351\242\230\344\270\216\344\277\256\345\244\215\350\256\260\345\275\225.md" @@ -1,3 +1,5 @@ +> 历史参考:本页保留原项目设计与问题记录,可能描述修复前行为。当前版本请从 [FOLI 中文文档](../zh-CN/index.md) 进入。 + # 已知问题与改进记录 静态代码审查发现的问题清单,按优先级排列。修复后将在此文件记录变更。 diff --git a/docs/architecture.md b/docs/architecture.md index 72bcb19..ed06067 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -1,3 +1,5 @@ +> 历史参考:本页保留原项目设计与问题记录,可能描述修复前行为。当前版本请从 [FOLI 中文文档](zh-CN/index.md) 进入。 + # 软硬件架构 ## 硬件电源架构(两层板,网表核对) diff --git a/docs/ble-protocol.md b/docs/ble-protocol.md index 2393fe4..9f7ce7e 100644 --- a/docs/ble-protocol.md +++ b/docs/ble-protocol.md @@ -1,3 +1,5 @@ +> 历史参考:本页保留原项目设计与问题记录,可能描述修复前行为。当前版本请从 [FOLI 中文文档](zh-CN/index.md) 进入。 + # BLE 应用层协议 ## 传输载体 diff --git a/docs/en/architecture.md b/docs/en/architecture.md new file mode 100644 index 0000000..7111913 --- /dev/null +++ b/docs/en/architecture.md @@ -0,0 +1,46 @@ +# From layout to paper + +[简体中文](../zh-CN/architecture.md) · [Documentation](index.md) + +![FOLI system architecture](../../media/images/system-architecture.png) + +## Android: one raster for preview and transfer + +`PaperRenderer` lays out notes or imported photos. `PrinterProtocol` converts pixels into a 384-dot-wide monochrome raster; each row occupies 48 bytes, black is 1, and the most significant bit represents the first dot in each byte. The preview is reconstructed from the encoded output, so it describes the bytes being prepared rather than an unrelated decorative thumbnail. + +The current app accepts at most 768 raster rows. This is a bounded input limit, not a guaranteed print duration. Excessive text is rejected; tall photos are fitted rather than silently cropped by the encoder. + +Relevant classes are in [the Android source](../../software/android/app/src/main/java/studio/foli/android/): `MainActivity`, `PaperRenderer`, `PrinterProtocol`, `BlePrinter`, `TemplateCatalog` and `ZoomPaperView`. + +## BLE: transport acceptance is not a finished print + +| Field | Value | +|---|---| +| Service | `4fafc201-1fb5-459e-8fcc-c5c9c331914b` | +| Characteristic | `beb5483e-36e1-4688-b7f5-ea07361b26a8` | +| Density | `A5 A5 A5 A5 01/02/03` | +| End of transfer / start trigger | `A6 A6 A6 A6 01` | +| Status payload | Four bytes: battery, temperature, paper, print state | +| Unavailable temperature | 255 in hardened firmware; heating is blocked | +| Paper | 0 loaded; 1 missing | +| Print state | 0 initial; 1 start; 2 working; 3 finished-or-stopped | + +FOLI sends whole raster rows using acknowledged GATT writes and requires a negotiated MTU of at least 51 bytes. The protocol guide in [Android documentation](../../software/android/README.md) describes pacing and current limits. Older upstream guidance about arbitrary 20-byte splitting should not be substituted for this app's row-based transfer contract. + +A GATT write callback establishes transport acceptance. The legacy wire format has no job ID, per-row sequence number or application-level checksum. The UI distinguishes connection, sending and device-reported printing. Even an observed start-to-terminal sequence remains STOPPED_UNCONFIRMED: state 3 does not distinguish physical success from an error stop. The app asks the user to inspect the paper and confirm a printer restart before another job. Reconnecting alone does not establish that a partially received job was cleared. + +## Firmware: buffer, heat and feed + +The [firmware](../../software/firmware/) receives commands and raster rows, buffers them, shifts data into the thermal head, latches it, enables heating groups and advances the paper with the motor driver. Battery, paper and head-temperature information feeds status handling. Exact timing and pin mapping belong to the selected firmware configuration and final board revision. + +Repository hardening addresses legacy command fall-through and failure-state handling separately from the historical hardware test. Compile/host-test results must not be read as physical qualification of those changes. See [verification](verification.md) for the boundary. + +## Electronics and enclosure + +The board integrates control, charging/regulation, print-head supply, motor drive and sensor connections. The [final editable hardware project](../../hardware/EDA-project/foli-mainboard.epro2) is the authority when older diagrams or documentation disagree. + +The enclosure positions the board, cell, print mechanism and paper roll. [Assembly documentation](assembly.md) links the printable parts and lists missing manufacturing details. The annotated CAD image illustrates component relationships; its separated positions are not assembly instructions or a validated motion mechanism. + +## Local data + +The app has no account, backend, analytics or Internet permission. Notes, favorites and a downsampled selected-photo copy are local. Android permissions are used for Bluetooth discovery/connection and the system document picker supplies images. This describes the current implementation, not a security certification. Broader accessibility, lifecycle and compatibility checks remain in the verification plan. diff --git a/docs/en/assembly.md b/docs/en/assembly.md new file mode 100644 index 0000000..914fa8f --- /dev/null +++ b/docs/en/assembly.md @@ -0,0 +1,52 @@ +# Mechanical files and assembly preparation + +[简体中文](../zh-CN/assembly.md) · [Documentation](index.md) + +![Annotated CAD assembly](../../media/images/assembly-explained.jpg) + +The supplied enclosure set is based on the 2023-09-18 assembly. The separated CAD view explains the relationship between parts. It is not a proven step-by-step build sequence, a tolerance report or a demonstration of how the lid moves. + +## Printable parts + +| Part | Source | +|---|---| +| Enclosure body | [body.stl](../../mechanical/stl/body.stl) | +| Upper cover | [upper-cover.stl](../../mechanical/stl/upper-cover.stl) | +| Lower cover | [lower-cover.stl](../../mechanical/stl/lower-cover.stl) | +| Retaining plate | [retainer.stl](../../mechanical/stl/retainer.stl) | + +The original names include part dates: body 230727; upper/lower cover and retainer 230719. The full STEP assembly is approximately 224 MB and is managed separately from lightweight README media. Consult the mechanical download/source information before expecting the full assembly in a standard clone. + +## Supplied assembly reference + +The owner-provided visual BOM lists the following quantities. Treat it as a reference and verify against the final mechanical revision before purchasing. + +| Item | Quantity | +|---|---:| +| Control board, body, upper cover, lower cover, retainer | One each | +| M3 × 6.4 mm light guide | 3 | +| M2 × 10 countersunk self-tapping screw | 4 | +| M2 × 8 pan-head self-tapping screw | 4 | +| M2 × 6 knurled shaft | 2 | +| Cutter | 1 | +| Feet | 4 | +| Thermal print mechanism | 1 | +| Battery | 1 | +| 57 × 30 paper roll reference | 1 | + +Battery lead: XH 2.54 mm 2-pin; owner-specified cell rating: 5C. Capacity, polarity, actual cell dimensions and the exact procurement part number must be matched to the installed hardware. The historical BOM is not a substitute for an electrical BOM. + +## Preparation workflow + +1. Inspect all four STL files and the assembly model in a CAD/slicer viewer. Confirm units, part extents and revision correspondence before slicing. +2. Check the board outline, mounting holes, connector openings and paper path against the parts you actually have. The supplied individual STL files use different local coordinates; do not infer the assembled positions from their origins. +3. Inspect a dry fit of the housing, board and mechanism before fastening. Keep the battery disconnected while routing wiring and fitting the mechanism. Confirm ribbon/connector orientation against the final electrical design. +4. Check light-guide, cutter, shaft and retainer locations in the original assembly. Fastener placement and depth must be checked against the geometry; the quantity table alone does not establish where each screw belongs. +5. Confirm that the roll, feed path, cover and exposed cutter do not interfere. Record the chosen paper orientation and final assembly photos for a reproducible guide. +6. Apply the selected hardware/firmware verification procedure before treating a changed assembly as qualified. + +## Manufacturing details still to record + +No verified filament/resin, nozzle size, layer height, wall count, support arrangement, part orientation, shrinkage compensation or fit tolerance is supplied with the current project record. The visual finish studies do not establish a material specification. A contributor should record those settings together with printer model, part revision and fit findings when producing a new enclosure. + +The current repository provides the geometry and assembly reference, not a production-ready manufacturing package. Historical hardware printing and current software checks are documented separately in [verification](verification.md). diff --git a/docs/en/getting-started.md b/docs/en/getting-started.md new file mode 100644 index 0000000..7824a68 --- /dev/null +++ b/docs/en/getting-started.md @@ -0,0 +1,66 @@ +# Get started with FOLI + +[简体中文](../zh-CN/getting-started.md) · [Documentation](index.md) + +FOLI combines a native Android app, ESP32 firmware, battery-powered electronics and a printable enclosure. You can create and inspect a paper without owning the printer. Physical printing requires the matching hardware and firmware. + +## Explore in five minutes + +1. Watch the [90-second product film](../../media/video/FOLI-Made-Tangible-90s.mp4). +2. See [Create, Templates and Device](../../media/gifs/app-tour.gif). +3. Open the [Android guide](../../software/android/README.md) for the available build and installation instructions. +4. Choose **Templates → Today's three → Make this yours**. Edit the words, explore **Layout**, and inspect the monochrome paper preview. Drafts are stored on the phone. +5. Read the [system architecture](architecture.md) to follow the same paper into raster bytes and the print mechanism. + +The app is a development build for direct installation, not a Google Play release. Android 7.0/API 24 is the minimum runtime version. The recorded physical-phone checks used Xiaomi Mi 6, Android 8.0/API 26; they do not establish compatibility with every Android version. + +## Build the Android app + +Install JDK 17 and Android SDK Platform 32 with compatible build tools. Configure your local SDK path; do not commit `local.properties`. From `software/android`: + +```powershell +$env:JAVA_HOME = 'C:\path\to\jdk-17' +.\build.ps1 +.\test-protocol.ps1 +``` + +On a Unix-like system the standard wrapper is available: + +```sh +cd software/android +chmod +x gradlew +./gradlew assembleDebug lintDebug +``` + +The APK is produced at `app/build/outputs/apk/debug/app-debug.apk`. The [Android guide](../../software/android/README.md) is authoritative for current build and test commands. Build success and protocol tests are separate from hardware verification. + +## Prepare the hardware + +Use the [final JLCEDA source](../../hardware/EDA-project/foli-mainboard.epro2), the selected firmware and the [enclosure files](assembly.md) as one versioned set. Read existing hardware notes before ordering or wiring parts. Confirm component/BOM revision and connector orientation against the board; similar Mini-Printer names alone do not establish compatibility. + +The owner specified an XH 2.54 mm 2-pin battery lead and a 5C battery rating. Capacity and exact cell model have not been consolidated into a final verified specification. Do not substitute the historical 1200/2000 mAh examples as a current product claim. + +## Build and flash firmware + +From the repository root, with PlatformIO installed: + +```sh +cd software/firmware +pio run +pio run -t upload +pio device monitor +``` + +Check the selected environment in [platformio.ini](../../software/firmware/platformio.ini). Set the upload port for your machine if detection fails. A successful firmware build does not mean that the resulting binary has been exercised on the physical printer. Consult [verification](verification.md) before replacing a previously working device image. + +## Connect from Android + +1. Install paper, power on the compatible printer and close other apps connected to it. +2. Open **Device → Find your printer**. Grant the permission requested by Android and select the device. +3. On Android 12+, BLE uses Nearby devices permissions. On Android 7–11, discovery requires location permission and enabled system location services; the app does not collect location. +4. Inspect reported battery, paper and print-head state. Unknown values are not readiness confirmation. The historical idle `0 °C` observation remains unresolved. +5. Create a short note, inspect its preview and enter the print review flow. Keep FOLI foregrounded during transfer. This is an operating procedure, not a claim that a new print was validated in this repository update. + +After an interrupted or unconfirmed transfer, follow the app's restart guidance. Reconnecting is not proof that the device queue was cleared. The legacy protocol does not offer a cancel command that can guarantee stopping a print already in progress. + +For unexpected output, record app version, firmware commit, hardware revision, phone/Android version, the content used and the last observed state. See [verification and open limits](verification.md). diff --git a/docs/en/index.md b/docs/en/index.md new file mode 100644 index 0000000..d687f5f --- /dev/null +++ b/docs/en/index.md @@ -0,0 +1,14 @@ +# FOLI documentation + +[简体中文](../zh-CN/index.md) · [Product overview](../../README.md) + +| Guide | Purpose | +|---|---| +| [Get started](getting-started.md) | Explore the app, build software and prepare a compatible printer | +| [System architecture](architecture.md) | Follow layout, raster bytes, BLE, firmware and paper | +| [Mechanical and assembly](assembly.md) | Obtain printable parts and identify missing manufacturing details | +| [Verification](verification.md) | Understand recorded results and remaining integration limits | +| [Product case study](product-case-study.md) | See concrete product/engineering decisions and tradeoffs | +| [Sources and media](provenance.md) | Separate new work, inherited materials, visualization and evidence | + +The older Chinese module notes in the parent documentation directory are retained as historical technical references. When they disagree with selected source files or the current verification record, resolve the discrepancy rather than assuming the newest-looking prose is correct. diff --git a/docs/en/product-case-study.md b/docs/en/product-case-study.md new file mode 100644 index 0000000..00ec40a --- /dev/null +++ b/docs/en/product-case-study.md @@ -0,0 +1,35 @@ +# FOLI: making the whole product legible + +[简体中文](../zh-CN/product-case-study.md) · [Documentation](index.md) + +FOLI is an English-first companion experience built around an existing physical Mini-Printer platform. The project connects a real board and print mechanism, embedded firmware, a supplied enclosure design and a new native Android app. The portfolio objective is to show how product decisions cross those boundaries, while making the design understandable and reproducible. + +## A small, concrete use case + +A short list beside a keyboard is enough to expose the whole chain: choose a template, change the words, inspect the monochrome result, connect and send it, then keep the paper nearby. Gift notes and portable lists extend the same capability without requiring a cloud account or a complex content service. + +Warm Chalk surfaces, Mint accents and a paper-centered interface establish a consistent visual language. The lifestyle imagery presents this intended experience; actual hardware photographs establish that the underlying electronics and printing work existed. Their evidence roles remain separate. + +## Decision 1: preview the bytes, not an approximation + +A decorative preview could look attractive while hiding thresholding, dithering and line-width effects. FOLI instead encodes a 384-dot-wide raster and builds the preview from that output. This makes the editor's core object meaningful: users inspect the representation being prepared for transmission. + +The tradeoff is bounded content and real processing work. `PrinterProtocol` enforces width and row limits; `PaperRenderer` handles layout. UI updates preserve the previous paper while preparing the next preview rather than replacing the screen with empty content. See [architecture](architecture.md) and the [Android source](../../software/android/app/src/main/java/studio/foli/android/). + +## Decision 2: design against an older physical phone + +The Mi 6 exposed issues that a large desktop mockup did not: keyboard obstruction, checklist outlines lost during binarization, and editor movement when feedback appeared. The implementation moved text entry to a full-screen composer, renders checkbox geometry explicitly and separates feedback from the paper viewport. + +Template filters, local favorites, larger previews, Cancel/Undo and retained scroll positions reduce the number of times a user must reconstruct context. These are implemented interactions with scoped device observations, not a claim of measured animation FPS or complete usability research. The [verification record](verification.md) identifies what was actually exercised. + +## Decision 3: uncertainty is a product state + +Bluetooth connection, successful data transfer and finished paper output are different events. The inherited protocol offers limited end-to-end evidence. FOLI presents transfer state separately. Even an observed start-to-terminal sequence becomes STOPPED_UNCONFIRMED because state 3 can also mean an error stop. The app asks the user to inspect the paper and confirm a printer restart before another job, protecting against blindly resending partly received content. + +This can require an explicit printer restart after an uncertain transfer. It is less convenient than automatic retry, but avoids silently duplicating or corrupting a physical job when the protocol cannot establish what was printed. Firmware fixes and future protocol improvements must preserve this distinction. + +## What the repository contributes + +The FOLI work includes the native Android experience, template/editor behavior, raster/protocol integration, identity, product visualization and consolidated engineering documentation. Existing hardware, firmware and mechanical inputs are retained with their source context. Purchased rights, upstream authorship and new implementation work are described separately in [provenance](provenance.md). + +The release is a development project with explicit limits: historical hardware printing exists; App UI checks and protocol assertions exist; a new end-to-end physical print with all updated components has not been repeated. The useful next evidence is final assembled-device photography, manufacturing settings and a versioned integration record—not invented speed, endurance or production-readiness claims. diff --git a/docs/en/provenance.md b/docs/en/provenance.md new file mode 100644 index 0000000..b05267b --- /dev/null +++ b/docs/en/provenance.md @@ -0,0 +1,42 @@ +# Sources, authorship and presentation media + +[简体中文](../zh-CN/provenance.md) · [Documentation](index.md) + +FOLI builds on Mini-Printer hardware and mechanical materials supplied under the owner's purchased project rights. Source credits and dependency notices are retained. This documentation identifies the platform, new Android implementation, integration changes and presentation work. + +## Engineering materials + +| Material | Origin and handling | +|---|---| +| Mainboard | Owner-selected final JLCEDA project, retained as [foli-mainboard.epro2](../../hardware/EDA-project/foli-mainboard.epro2) | +| Legacy firmware | Mini-Printer code and existing repository history; hardening changes must be identified by commit and verification scope | +| Mechanical design | Supplied 230918 assembly and dated STL parts; English filenames do not imply new geometry authorship | +| FOLI Android | Native Java app created for this product experience; legacy protocol inspected for interoperability | +| Android dependencies | AndroidX ExifInterface and build tooling; see [third-party notices](../../software/android/THIRD_PARTY_NOTICES.md) | +| Historical photographs | Supplied hardware bench and thermal test-page photographs; not new tests of the complete updated stack | + +The original teaching materials are associated with 小智学长's Mini-Printer project. Their narrative and examples are background sources; final board files and selected code determine the implemented configuration. Unrelated ESP32-S3 AI-terminal materials in the working collection are not part of FOLI. + +## Media register + +| Media | What it depicts | +|---|---| +| Hero/lifestyle scenes | AI-generated concept images referencing the actual CAD; possible small geometry/material differences | +| CAD product/assembly motion | Imported supplied assembly with visualization materials and illustrative separation | +| Paper-feed animation | Textured CG paper illustration; no measured printing-speed claim | +| App tour | Existing phone captures with reconstructed motion; current Device screen redrawn from source, disconnected | +| Engineering diagram | Conceptual system flow supported by the raster/protocol code; not live telemetry | +| Evidence sheet | Historical photos, rotated for readable presentation; original test content retained | +| Music and action sounds | Original procedural composition and synthesized Foley; no external music/sample pack or field-recording claim | + +The product film is [available here](../../media/video/FOLI-Made-Tangible-90s.mp4). Presentation labels should remain accurate when reusing individual clips outside the full film. Reconstructed UI animation is not evidence of device FPS. + +System fonts used during original production include Segoe UI and Georgia; font files are not redistributed. Media source scripts and generation prompts should be retained with the production assets. A rendered file being easy to view does not guarantee that every optional media-generation dependency is installed. + +## Identity + +FOLI and “Little prints. Everyday joy.” are the selected project identity. Chalk/Mint and other color studies describe visual proposals, not independently manufactured product variants. + +## Reuse + +Consult the repository license and retained dependency notices for the material you intend to reuse. Hardware, mechanical inputs, generated media and software should not be assumed to have identical upstream terms solely because they are displayed on one README. Preserve source attribution and do not describe concept renders as photographs or historical testing as qualification of a newer release. diff --git a/docs/en/verification.md b/docs/en/verification.md new file mode 100644 index 0000000..2938b82 --- /dev/null +++ b/docs/en/verification.md @@ -0,0 +1,57 @@ +# Verification and remaining limits + +[简体中文](../zh-CN/verification.md) · [Documentation](index.md) + +Evidence is grouped by what it actually establishes. An attractive render is not hardware evidence, a successful compile is not a radio test, and historical printing does not qualify every newer software revision. + +## Recorded baseline + +| Area | Recorded evidence | What it does not establish | +|---|---|---| +| Hardware | Supplied board/mechanism photographs and a physical thermal test page | Production yield, endurance, battery capacity or new app compatibility | +| Android 0.2.0 | Build and Lint; 158 protocol assertions; APK signature; installation and scoped UI checks | Every photo path, lifecycle path, Android version or physical print | +| Android 0.2.1 | Build/Lint/signature; encoder, access-change and terminal-outcome host checks | New phone installation, real permission revocation or physical printing | +| UI device | Xiaomi Mi 6, Android 8/API 26 | General performance/FPS or broad accessibility qualification | +| BLE baseline | Connected state and received four-byte packet; battery about 75–76%; missing paper matched the empty printer | Battery calibration, reliable head temperature or physical output | +| Repository hardening | Build and automated checks recorded with the changed source | Hardware qualification of new firmware fixes | +| Product media | CAD motion, reconstructed UI, AI lifestyle concepts and original synthesized sound | Live-action use, measured interaction smoothness or a new print test | + +The [detailed Android record](../../software/android/VERIFICATION.md) contains chronological observations and limitations. Its earliest table describes the original build handoff; read the subsequent physical-phone and 0.2.0 sections as well. + +![Historical hardware evidence](../../media/images/hardware-evidence.jpg) + +The photographed test page reads `TM_Test: 24 °C`. Do not reuse an older README's 28 °C figure for this image without another supporting record. + +## What was observed on the phone + +The 0.2.0 gallery, Focus filtering, template preview/application, Clean-to-Journal live preview, Keep changes, Undo, local favorites and saved filtering were exercised. The full-screen composer kept Cancel/Done above the keyboard; cancelling a temporary title edit restored the prior content. Full-screen paper inspection opened successfully. The scoped final process-log sample contained no fatal exception. + +One startup raster duration is a single observation, not a sustained-performance benchmark. Multi-touch behavior, every photo import/transform, enlarged fonts, accessibility services, process recreation and newer Android releases still require broader checks. + +## Unresolved physical integration + +The connected empty printer reported `0 °C`. The owner suggested idle temperature updates may explain this; that is a hypothesis, not a confirmed sensor result. Do not interpret zero as a calibrated safe temperature. No print was sent during that connection observation. + +The historical protocol lacks job identifiers, row acknowledgments/checksums and a guaranteed cancel command. Interrupted transfers can leave buffered data. Old firmware completion/timeout behavior and A6 fall-through are known limitations. Changes addressing those issues must retain separate build/host-test evidence and physical-device follow-up status. + +No new end-to-end print with the FOLI 0.2.0 app or repository-hardening firmware was performed in this work session. The owner chose not to repeat hardware testing. That decision does not prevent source release, but it limits compatibility claims. + +## Reproduction record for future checks + +Record the hardware revision, firmware commit, App version/hash, phone/API level, battery/paper condition and exact input. For each case record expected behavior, observed behavior, logs/photos and pass/fail/uncertain result. Keep these distinct: + +- Build and static analysis. +- Host-side encoder/protocol tests. +- Phone UI and permission/discovery behavior. +- Actual print quality and preview/output agreement. +- Missing paper, hot-head, low battery and interrupted-job recovery. + +A future test should update the matching source revision's record rather than retroactively marking older work as fully tested. + +## Integration software checks + +Android 0.2.1 passed build/Lint (zero errors, one dependency-version advisory), 158 encoder assertions, BLE exception-boundary checks, eight shared terminal-outcome cases plus seven temperature cases and APK v2 signature verification. State 3 is treated as stopped/unconfirmed, never proof of physical success; confirmation after a printer restart clears the recovery latch. + +Firmware compiled with PlatformIO Core 6.2.0, espressif32 7.0.1 and Arduino-ESP32 2.0.17. Shared C++ regression tests covered command routing, six fragment sizes, row completion, overflow, copy-out independence and 10,000 ring-buffer wraparounds. RAM: 88,012 / 327,680 bytes; flash: 1,151,529 / 1,310,720 bytes. These are build sizes, not runtime performance measurements. + +No firmware was flashed and no new physical print was attempted. Legacy timing/sensor calibration and the new fault shutdown behavior still require physical follow-up. diff --git a/docs/known-issues.md b/docs/known-issues.md index 3ff19d7..f480f44 100644 --- a/docs/known-issues.md +++ b/docs/known-issues.md @@ -1,3 +1,5 @@ +> 历史参考:本页保留原项目设计与问题记录,可能描述修复前行为。当前版本请从 [FOLI 中文文档](zh-CN/index.md) 进入。 + # 已知问题与改进记录 静态代码审查发现的问题清单,按优先级排列。修复后将在此文件记录变更。 diff --git a/docs/pinout.md b/docs/pinout.md index 4fdbd91..46a8f23 100644 --- a/docs/pinout.md +++ b/docs/pinout.md @@ -1,3 +1,5 @@ +> 历史参考:本页保留原项目设计与问题记录,可能描述修复前行为。当前版本请从 [FOLI 中文文档](zh-CN/index.md) 进入。 + # 引脚分配表(ESP32-S) 以下引脚分配由嘉立创工程网表(PAD_NET)与固件 `src/em_config.h`(V4 引脚组)逐脚核对一致。 diff --git a/docs/zh-CN/architecture.md b/docs/zh-CN/architecture.md new file mode 100644 index 0000000..95bad73 --- /dev/null +++ b/docs/zh-CN/architecture.md @@ -0,0 +1,46 @@ +# 从排版到纸张 + +[English](../en/architecture.md) · [文档导航](index.md) + +![系统链路](../../media/images/system-architecture.png) + +## Android:预览与传输共用光栅 + +`PaperRenderer` 排版文字或导入图片,`PrinterProtocol` 转换为 384 点宽的黑白光栅,每行 48 字节、黑点为 1,每字节最高位对应第一个点。预览根据编码结果生成,而不是另画一张与打印数据无关的装饰缩略图。 + +当前 App 最多接受 768 行。这是输入上限,不是打印时间保证。过长文本被拒绝;高图片缩放适配,不由编码器静默截断。 + +[Android 源码目录](../../software/android/app/src/main/java/studio/foli/android/)包含 `MainActivity`、`PaperRenderer`、`PrinterProtocol`、`BlePrinter`、`TemplateCatalog` 和 `ZoomPaperView`。 + +## BLE:收到数据不等于打印完成 + +| 字段 | 内容 | +|---|---| +| Service | `4fafc201-1fb5-459e-8fcc-c5c9c331914b` | +| Characteristic | `beb5483e-36e1-4688-b7f5-ea07361b26a8` | +| 浓度 | `A5 A5 A5 A5 01/02/03` | +| 发送结束/启动触发 | `A6 A6 A6 A6 01` | +| 状态 | 电量、温度、纸状态、打印状态,共四字节 | +| 温度不可用 | 加固固件以255表示,禁止加热 | +| 纸状态 | 0 有纸;1 缺纸 | +| 打印状态 | 0 初始;1 启动;2 工作;3 完成或停止 | + +FOLI 使用带响应的 GATT 写入发送完整光栅行,要求协商 MTU 至少为 51。节拍和限制见 [Android 指南](../../software/android/README.md)。不能把旧资料中任意 20 字节拆包的建议直接替换为当前 App 的整行传输约定。 + +GATT 写入回调说明传输被接收,旧协议没有任务 ID、逐行序号和应用级校验。界面区分连接、发送与设备上报的打印状态;即便观察到开始至终态序列,也仅判为 STOPPED_UNCONFIRMED,因为状态3不能区分成功与异常停止。应用提示检查纸张,并在下一任务前重启打印机后明确确认;单纯重连不能证明缓存已清空。 + +## 固件:缓存、加热、走纸 + +[固件](../../software/firmware/)接收命令与光栅行,缓存后将数据移入打印头、锁存、分组加热并驱动电机走纸,电量、缺纸和温度参与状态处理。准确时序和引脚映射以选定配置和最终板卡为准。 + +仓库加固将旧版命令继续入队与故障状态问题和历史实物测试分开记录。构建或主机测试通过,不代表这些修改已完成实物验证,边界见[验证记录](verification.md)。 + +## 电路与结构 + +板卡集成控制、充电与稳压、打印头电源、电机驱动和检测接口。旧图与文档有差异时,应以[最终硬件工程](../../hardware/EDA-project/foli-mainboard.epro2)核实,不能根据文件名猜测。 + +外壳定位控制板、电池、打印机构和纸卷。[装配文档](assembly.md)链接打印件并列出尚未记录的制造信息。带标注的展开图用于解释部件关系,不代表实际装配顺序或已验证的运动机构。 + +## 本地数据 + +App 无账号、后端、分析服务或 Internet 权限。文字、收藏和降采样图片副本保存在本机;蓝牙权限用于发现与连接,图片通过系统文档选择器导入。这是实现说明,不是安全认证。无障碍、生命周期和兼容性仍有待扩大验证。 diff --git a/docs/zh-CN/assembly.md b/docs/zh-CN/assembly.md new file mode 100644 index 0000000..fe6e748 --- /dev/null +++ b/docs/zh-CN/assembly.md @@ -0,0 +1,52 @@ +# 机械文件与装配准备 + +[English](../en/assembly.md) · [文档导航](index.md) + +![带标注的 CAD 展开图](../../media/images/assembly-explained.jpg) + +外壳资料基于 2023-09-18 装配体。展开图说明部件关系,不代表已验证的逐步装配流程、配合公差或上盖实际运动方式。 + +## 打印件 + +| 零件 | 文件 | +|---|---| +| 外壳主体 | [body.stl](../../mechanical/stl/body.stl) | +| 上盖 | [upper-cover.stl](../../mechanical/stl/upper-cover.stl) | +| 下盖 | [lower-cover.stl](../../mechanical/stl/lower-cover.stl) | +| 卡板 | [retainer.stl](../../mechanical/stl/retainer.stl) | + +原文件日期为:主体 230727,上盖、下盖、卡板 230719。完整 STEP 约 224 MB,与轻量展示媒体分开管理;完整装配体是否随克隆提供,以机械下载/来源说明为准。 + +## 用户提供的装配参考 + +以下数量来自视觉 BOM,仅供参考;采购前应与最终结构版本核对。 + +| 配件 | 数量 | +|---|---:| +| 控制板、主体、上盖、下盖、卡板 | 各 1 | +| M3 × 6.4 mm 导光柱 | 3 | +| M2 × 10 沉头自攻螺丝 | 4 | +| M2 × 8 盘头自攻螺丝 | 4 | +| M2 × 6 滚花轴 | 2 | +| 齿刀 | 1 | +| 脚垫 | 4 | +| 打印机构 | 1 | +| 电池 | 1 | +| 57 × 30 打印纸参考卷 | 1 | + +电池出线为 XH 2.54 mm 2P,用户指定倍率 5C。容量、极性、实物尺寸和准确采购型号需要匹配实际硬件;结构 BOM 不能代替电气 BOM。 + +## 装配准备流程 + +1. 在 CAD/切片软件中检查四个 STL 和装配体,确认单位、零件尺寸与版本对应后再切片。 +2. 对照实物核对 PCB 外形、安装孔、接口开口与走纸路径。独立 STL 使用不同局部坐标,不能按原点直接判断装配位置。 +3. 紧固前试装主体、控制板和打印机构。布线和安装机构时断开电池,FPC 与连接器方向以最终电路设计为准。 +4. 参考原装配体确认导光柱、齿刀、轴和卡板位置。螺丝位置与进入深度须结合模型核对,数量表并不说明每颗螺丝安装在哪里。 +5. 检查纸卷、走纸路径、上盖与齿刀是否干涉,记录纸卷方向与最终装配照片。 +6. 改变装配方案后,依选定硬件/固件验证流程确认,不以试装成功替代完整资格验证。 + +## 尚未记录的制造信息 + +现有记录没有核实耗材、喷嘴、层高、壁数、支撑、摆放方向、收缩补偿或配合公差。配色渲染不是材料规格。后续打印外壳时应一并记录打印机型号、结构版本、切片参数和试装结果。 + +仓库提供几何源文件与装配参考,当前不将其称为生产制造包。历史实物打印和当前软件检查的范围见[验证记录](verification.md)。 diff --git a/docs/zh-CN/getting-started.md b/docs/zh-CN/getting-started.md new file mode 100644 index 0000000..ebfee18 --- /dev/null +++ b/docs/zh-CN/getting-started.md @@ -0,0 +1,63 @@ +# 开始使用 FOLI + +[English](../en/getting-started.md) · [文档导航](index.md) + +FOLI 包含原生 Android App、ESP32 固件、电池供电电路与可打印外壳。没有打印机也能创建纸条、修改文字和查看预览;实际打印需要配套硬件及固件。 + +## 先了解产品 + +1. 查看 [90 秒产品视频](../../media/video/FOLI-Made-Tangible-90s.mp4)与[三屏功能 GIF](../../media/gifs/app-tour.gif)。 +2. 按 [Android 指南](../../software/android/README.md)获取或构建开发版 APK。 +3. 在 **Templates → Today's three → Make this yours** 中应用模板,编辑文字、打开 **Layout** 并查看黑白纸面。草稿保存在手机本地。 +4. 阅读[系统架构](architecture.md),理解同一份纸面如何成为字节并进入打印机构。 + +App 是直接安装的开发版,尚非 Google Play 发布版本。最低运行系统为 Android 7/API 24;已记录的真机检查使用小米 6、Android 8/API 26,不代表所有系统版本均已验证。 + +## 构建 Android + +安装 JDK 17、Android SDK Platform 32 及兼容构建工具,设置本机 SDK 路径,勿提交 `local.properties`。在 `software/android` 中执行: + +```powershell +$env:JAVA_HOME = 'C:\path\to\jdk-17' +.\build.ps1 +.\test-protocol.ps1 +``` + +类 Unix 系统可用标准 wrapper: + +```sh +cd software/android +chmod +x gradlew +./gradlew assembleDebug lintDebug +``` + +APK 输出为 `app/build/outputs/apk/debug/app-debug.apk`。当前构建和测试命令以 [Android 指南](../../software/android/README.md)为准。编译、协议检查与实物验证是不同层面的证据。 + +## 准备硬件与固件 + +将[最终嘉立创工程](../../hardware/EDA-project/foli-mainboard.epro2)、选定固件与[机械文件](assembly.md)作为配套版本使用。订购或接线前核对原理图、BOM 版本和连接器方向,不能仅凭 Mini-Printer 名称判断兼容。 + +用户指定电池出线为 XH 2.54 mm 2P,电池倍率为 5C;容量及准确型号尚未形成统一核实规格。历史资料的 1200/2000 mAh 示例不能直接当作当前产品参数。 + +在已安装 PlatformIO 的环境中,从仓库根目录执行: + +```sh +cd software/firmware +pio run +pio run -t upload +pio device monitor +``` + +环境以 [platformio.ini](../../software/firmware/platformio.ini) 为准,自动识别失败时设置本机串口。固件可编译不代表该二进制已在实物运行;替换现有工作固件前查看[验证记录](verification.md)。 + +## 从手机连接 + +1. 装入打印纸、开启兼容打印机,关闭占用它的其他蓝牙 App。 +2. 进入 **Device → Find your printer**,按系统要求授予权限并选择设备。 +3. Android 12 及以上使用附近设备权限;Android 7–11 的 BLE 扫描要求定位权限与系统定位服务,App 本身不收集位置。 +4. 查看设备上报的电量、纸张与打印头状态。未知值不能视为就绪;历史空闲 `0 °C` 读数仍未解决。 +5. 编辑短纸条、查看预览并进入打印确认流程,传输时保持 App 前台运行。这是操作说明,不表示本轮仓库更新进行了新的实物打印验证。 + +传输中断或完成状态不确定时,遵循 App 的重启指引。重新连接不能证明设备缓冲已清空;旧协议没有能保证停止已启动打印的取消命令。 + +反馈异常时请记录 App 版本、固件提交、硬件版本、手机及系统、使用内容和最后观察到的状态,并参考[验证与已知边界](verification.md)。 diff --git a/docs/zh-CN/index.md b/docs/zh-CN/index.md new file mode 100644 index 0000000..99e77b3 --- /dev/null +++ b/docs/zh-CN/index.md @@ -0,0 +1,14 @@ +# FOLI 文档导航 + +[English](../en/index.md) · [产品首页](../../README.zh-CN.md) + +| 文档 | 内容 | +|---|---| +| [开始使用](getting-started.md) | 体验 App、构建软件、准备兼容打印机 | +| [系统架构](architecture.md) | 排版、光栅、BLE、固件到纸张的链路 | +| [机械与装配](assembly.md) | 打印件、装配参考和待记录制造信息 | +| [验证范围](verification.md) | 已观察结果及尚未解决的联调边界 | +| [产品案例](product-case-study.md) | 具体产品/工程判断与取舍 | +| [来源与媒体](provenance.md) | 区分新增实现、既有资料、概念视觉和真实证据 | + +上级目录的旧中文模块文档保留为历史技术参考。与选定源码或当前验证记录冲突时应核实差异,不能仅按文字更新时间判断正确性。 diff --git a/docs/zh-CN/product-case-study.md b/docs/zh-CN/product-case-study.md new file mode 100644 index 0000000..59592b8 --- /dev/null +++ b/docs/zh-CN/product-case-study.md @@ -0,0 +1,35 @@ +# FOLI:把完整产品讲清楚 + +[English](../en/product-case-study.md) · [文档导航](index.md) + +FOLI 围绕已有 Mini-Printer 实物平台,建立英文优先的产品体验,将真实控制板与打印机构、嵌入式固件、现有外壳设计和新原生 Android App 连接起来。展示重点是跨软硬件的产品判断,并让别人能够理解与复现。 + +## 一个具体场景贯穿系统 + +键盘旁的一张清单便能串起整条链路:选模板、改文字、查看黑白效果、连接并发送、把纸条放在手边。礼物留言与随身清单复用相同能力,不依赖云端账号或复杂内容服务。 + +暖白、薄荷与纸面编辑器建立统一视觉。生活概念图表达预期体验,真实硬件照片说明电路与纸面输出确实存在;两类素材承担不同证据作用。 + +## 决策一:预览真正准备发送的内容 + +装饰预览可能很好看,却掩盖阈值、抖动和行宽造成的输出变化。FOLI 编码出 384 点光栅,再根据编码结果生成预览,使用户查看的是准备发送的数据表示。 + +代价是内容有界限,也确实需要处理时间。`PrinterProtocol` 检查宽度与行数,`PaperRenderer` 负责排版。生成下一次预览时保留上一张纸面,避免编辑区变空。实现见[系统架构](architecture.md)和 [Android 源码](../../software/android/app/src/main/java/studio/foli/android/)。 + +## 决策二:用旧手机暴露真实布局问题 + +小米 6 暴露了桌面大屏效果图看不到的问题:键盘挡住操作、复选框细线在二值化后缺失、反馈提示让编辑区域移动。实现因此采用全屏文字编辑、明确的复选框几何和不挤压纸面的反馈。 + +模板筛选、本地收藏、大预览、Cancel/Undo 与滚动位置保留减少了重复寻找上下文。它们是已实现的功能,并有部分真机观察;这不代表已经测得动画 FPS 或完成用户研究。实际检查范围见[验证记录](verification.md)。 + +## 决策三:把不确定当作产品状态 + +蓝牙连接、发送成功和打印完成不是同一事件。继承协议的端到端证据有限,因此 FOLI 分别显示传输与打印状态。即便观察到开始到终态的完整序列,也仅判为 STOPPED_UNCONFIRMED,因为状态3还可能表示异常停止。应用提示检查纸张,并在下一任务前重启打印机后明确确认,阻止盲目重发部分接收内容。 + +不确定传输后可能需要用户明确重启打印机。这不如自动重试方便,但在协议无法证明已打印内容时,可以避免悄悄重复或破坏实体任务。固件修复与未来协议升级也应维持这一区分。 + +## 仓库工作与成果边界 + +FOLI 阶段工作包括原生 Android 体验、模板编辑交互、光栅/协议整合、品牌、产品可视化和工程文档整合。已有硬件、固件与机械基础保留来源上下文。购买授权、上游作者与新增实现分别见[来源说明](provenance.md)。 + +项目按开发状态发布:有历史实物打印,有 App 交互与协议测试;没有重复验证全部更新组件的端到端纸面输出。下一步有价值的证据是最终整机照片、制造参数和版本化联调记录,而非虚构速度、耐久或量产成熟度。 diff --git a/docs/zh-CN/provenance.md b/docs/zh-CN/provenance.md new file mode 100644 index 0000000..e6b7716 --- /dev/null +++ b/docs/zh-CN/provenance.md @@ -0,0 +1,34 @@ +# 来源、作者与展示素材 + +[English](../en/provenance.md) · [文档导航](index.md) + +FOLI 基于用户提供的 Mini-Printer 资料。项目负责人声明已购买原项目相关权利;该声明不替代依赖自身的许可证,也不意味着所有继承设计均由 FOLI 独立创作。仓库区分既有平台、新实现和产品展示工作。 + +| 资料 | 来源与处理 | +|---|---| +| 控制板 | 用户指定最终嘉立创工程,保存为 [foli-mainboard.epro2](../../hardware/EDA-project/foli-mainboard.epro2) | +| 既有固件 | Mini-Printer 源码与仓库历史;加固修改应对应提交与验证范围 | +| 机械设计 | 用户提供的 230918 装配体和日期命名 STL;英文重命名不代表重新设计几何 | +| FOLI Android | 为本产品体验制作的原生 Java App;通过阅读既有协议建立互通 | +| Android 依赖 | AndroidX ExifInterface 与构建工具,见[第三方说明](../../software/android/THIRD_PARTY_NOTICES.md) | +| 历史照片 | 用户提供的测试台与热敏测试页,不是全部新组件的复测 | + +原教学资料关联小智学长 Mini-Printer 项目,其说明与示例提供背景;最终配置应以选定电路文件和代码为准。工作资料中的 ESP32-S3 AI terminal 等无关工程不属于 FOLI。 + +## 媒体类型 + +- 主视觉与生活场景:依据实际 CAD 参考生成的 AI 概念图,可能存在细微结构或材质差异。 +- CAD 镜头:导入已有装配体后添加材质、灯光与示意展开。 +- 出纸:贴有文字的三维纸面示意,不证明打印速度。 +- App GIF:真机截图与运动重建;当前 Device 页根据源码重绘为离线状态,不是实际操作录屏或 FPS 证据。 +- 系统图:由光栅/协议源码支持的概念链路,不是实时遥测。 +- 硬件证据图:历史照片旋转排版,保留原测试内容。 +- 声音:原创程序编排与合成拟音,无第三方配乐/采样包,不称为现场录音。 + +[产品视频](../../media/video/FOLI-Made-Tangible-90s.mp4)拆分使用时仍应保留准确来源说明。原制作使用系统 Segoe UI 与 Georgia,字体文件不随项目分发。脚本与生成提示词应随制作源资料保存;能观看成片不代表安装了全部可选制作依赖。 + +## 品牌与复用 + +FOLI 和 “Little prints. Everyday joy.” 为选定项目身份。暖白、薄荷等配色是设计提案,不代表所有配色均已生产。名字未完成商业清查,初步资料发现另一个 Foli 品牌 App;不承诺商标、商店名称或域名可用。 + +复用前查看仓库许可证与保留的第三方说明。硬件、机械、生成媒体与软件展示在同一 README 中,不意味着其上游条款完全一致。保留来源,不把概念渲染称为实拍,也不把历史测试称为新版全部验证。 diff --git a/docs/zh-CN/verification.md b/docs/zh-CN/verification.md new file mode 100644 index 0000000..8e5326b --- /dev/null +++ b/docs/zh-CN/verification.md @@ -0,0 +1,49 @@ +# 验证范围与剩余边界 + +[English](../en/verification.md) · [文档导航](index.md) + +证据按实际能证明的范围分类。渲染不是硬件证据,编译不是无线联调,历史打印成功也不能验证所有新软件版本。 + +| 范围 | 已记录证据 | 不能由此推导 | +|---|---|---| +| 硬件 | 现有控制板/机构照片与实物热敏测试页 | 量产良率、耐久、容量或新版 App 兼容 | +| Android 0.2.0 | 构建、Lint、158 条协议断言、APK 签名、安装及部分交互检查 | 所有图片路径、生命周期、系统版本或实物打印 | +| Android 0.2.1 | 构建、Lint、签名、编码/权限异常/终态判定主机检查 | 新版真机安装、实际撤销权限或实物打印 | +| 手机 | 小米 6,Android 8/API 26 | 通用 FPS、性能或完整无障碍认证 | +| BLE 基线 | 连接及四字节状态接收;约 75–76% 电量;缺纸状态符合空机 | 电量标定、可靠温度或纸面输出 | +| 仓库加固 | 与变更源码对应的构建及自动检查 | 新固件修复的实物资格验证 | +| 产品媒体 | CAD、UI 重建、AI 生活概念和原创合成声音 | 实拍使用、真实动画性能或新增打印测试 | + +[Android 详细记录](../../software/android/VERIFICATION.md)按时间保存观察。开头表格属于初始构建交接,应继续阅读后面的真机与 0.2.0 章节。 + +![历史硬件证据](../../media/images/hardware-evidence.jpg) + +该照片的测试页显示 `TM_Test: 24 °C`。没有另一份证据时,不能为此图沿用旧 README 中的 28 °C。 + +## 已观察的交互 + +0.2.0 检查了模板列表、Focus 筛选、模板预览与应用、Clean→Journal 实时预览、Keep changes、Undo、收藏和 Saved 筛选;全屏编辑器在键盘上方保留 Cancel/Done,取消临时标题修改恢复原内容;全屏纸面查看可以打开。最终限定范围内的进程日志未出现致命异常。 + +单次启动光栅耗时不是持续性能测试。多点触摸、全部图片导入/变换、大字体、无障碍服务、进程重建及新系统仍需扩大验证。 + +## 未解决的实物联调 + +空机连接时打印头温度上报为 `0 °C`。用户提出可能仅打印时更新温度,这是待核实解释,不是传感器正常的证据,零不能当作已标定的安全温度。该次观察没有发送打印。 + +历史协议缺少任务标识、逐行序号与应用级校验,也没有能保证停止已开始打印的取消命令。中断可能遗留缓冲;旧固件完成/超时行为与 A6 继续入队是已知限制。对这些问题的修复需单独记录构建、主机测试与后续实物状态。 + +本轮没有重新验证 FOLI 0.2.0 或仓库加固固件的完整纸面输出。用户选择不重复硬件测试;这不阻止开放源码,但限制兼容性承诺。 + +## 后续验证如何记录 + +记录硬件版本、固件提交、App 版本/校验值、手机与 API、电池/纸张条件和准确输入。每项保存预期、观察、日志/照片及通过/失败/不确定结论,分别归类构建静态检查、编码协议测试、手机权限/发现、实际输出和异常恢复。 + +新增测试应更新对应源码版本,不能把历史工作追溯标为“全部测试通过”。 + +## 本次整合的软件检查 + +Android 0.2.1 构建/Lint通过(0错误、1条依赖版本建议),158条编码断言、蓝牙异常边界、8种共享终态判定与7种温度场景及APK v2签名检查通过。状态3仅作为停止/未确认,不证明打印成功;重启打印机后显式确认才清除恢复标志。 + +固件使用PlatformIO Core6.2.0、espressif32 7.0.1、Arduino-ESP32 2.0.17编译通过。共享C++检查覆盖命令、6种分片、整行、溢出、复制独立性与10000次环形回绕。RAM 88012/327680字节,Flash 1151529/1310720字节,为构建大小而非运行性能。 + +未烧录、未新增实物打印。传感器校准、时序与新的故障停止行为仍待实物验证。 diff --git a/hardware/EDA-project/MINI-PRINTER_JLC.epro2 b/hardware/EDA-project/foli-mainboard.epro2 similarity index 100% rename from hardware/EDA-project/MINI-PRINTER_JLC.epro2 rename to hardware/EDA-project/foli-mainboard.epro2 diff --git a/hardware/README.md b/hardware/README.md new file mode 100644 index 0000000..af4f593 --- /dev/null +++ b/hardware/README.md @@ -0,0 +1,18 @@ +# Hardware + +[简体中文](README.zh-CN.md) · [Assembly](../docs/en/assembly.md) + +The owner-selected final source is [foli-mainboard.epro2](EDA-project/foli-mainboard.epro2), a JLCEDA Professional project. Its SHA-256 matches the original upstream `MINI-PRINTER_JLC.epro2`; only the publication filename changed. + +| File | Purpose | +|---|---| +| [Mainboard source](EDA-project/foli-mainboard.epro2) | Editable electrical/PCB project | +| [Gerber archive](exports/Gerber_Mini-printer.zip) | Existing manufacturing export | +| [BOM spreadsheet](exports/Mini-Printer-BOM.xlsx) | Existing parts list | +| [Schematic image](exports/schematic.png) | Readable reference schematic | + +The existing exports are retained with the upstream project. Their export time and exact manufacturing/BOM correspondence have not been independently re-established in this integration; verify against the editable final source before placing an order. The assembly/reference BOM may include parts outside the PCB BOM. + +The system uses ESP32 control, rechargeable battery power, charging/regulation, a print-head supply and motor/sensor interfaces. The owner specified an XH 2.54 mm 2-pin battery lead and 5C rating. Final battery capacity/model and mechanism FPC pin count require source/part reconciliation; no unverified marketing specification is published here. + +Historical technical chapters remain under [hardware design notes](../docs/02-硬件设计/). Treat these as inherited design explanations; [current architecture](../docs/en/architecture.md) and final files define this integration. diff --git a/hardware/README.zh-CN.md b/hardware/README.zh-CN.md new file mode 100644 index 0000000..eec7675 --- /dev/null +++ b/hardware/README.zh-CN.md @@ -0,0 +1,15 @@ +# 硬件 + +[English](README.md) · [装配说明](../docs/zh-CN/assembly.md) + +最终源文件为[foli-mainboard.epro2](EDA-project/foli-mainboard.epro2),使用嘉立创 EDA 专业版。其 SHA-256 与原仓库 MINI-PRINTER_JLC.epro2 相同,本次仅规范文件名。 + +- [Gerber](exports/Gerber_Mini-printer.zip) +- [PCB BOM](exports/Mini-Printer-BOM.xlsx) +- [原理图](exports/schematic.png) + +制造导出保留自上游,导出时间和与最终源文件的完全对应关系未在此次重新验证,下单前应对照可编辑工程核对。装配参考 BOM 与 PCB BOM 不是同一份清单。 + +系统包含 ESP32、电池、充电与稳压、打印头供电及电机/传感器接口。用户已确认电池线头为 XH 2.54 mm 2P、5C;最终容量/型号与 FPC 位数仍待按实物和最终文件统一,不发布猜测参数。 + +[历史硬件设计章节](../docs/02-硬件设计/)作为来源参考保留,当前入口为[系统架构](../docs/zh-CN/architecture.md)。 diff --git a/hardware/EDA-project/exports/Gerber_Mini-printer.zip b/hardware/exports/Gerber_Mini-printer.zip similarity index 100% rename from hardware/EDA-project/exports/Gerber_Mini-printer.zip rename to hardware/exports/Gerber_Mini-printer.zip diff --git a/hardware/EDA-project/exports/Mini-Printer-BOM.xlsx b/hardware/exports/Mini-Printer-BOM.xlsx similarity index 100% rename from hardware/EDA-project/exports/Mini-Printer-BOM.xlsx rename to hardware/exports/Mini-Printer-BOM.xlsx diff --git a/hardware/EDA-project/exports/schematic.png b/hardware/exports/schematic.png similarity index 100% rename from hardware/EDA-project/exports/schematic.png rename to hardware/exports/schematic.png diff --git a/hardware/source-manifest.json b/hardware/source-manifest.json new file mode 100644 index 0000000..fb30f0e --- /dev/null +++ b/hardware/source-manifest.json @@ -0,0 +1,18 @@ +[ + { + "file": "EDA-project/foli-mainboard.epro2", + "sha256": "8540bc616b7152b04b58db57eb089fb17cf5b8c8156b47617f75cecbef09284d" + }, + { + "file": "exports/Gerber_Mini-printer.zip", + "sha256": "10035b5eb9d5f731973524cf69be557ef61e92ab4009ac9299383b27465ad887" + }, + { + "file": "exports/Mini-Printer-BOM.xlsx", + "sha256": "b39588da61dd97e827cb533f00c58150903a4c4e3810bc786972614cb8d9e33d" + }, + { + "file": "exports/schematic.png", + "sha256": "c50a6151599bb9509dfa804fd23cdfe277a0f639c929e91d50f02437b093467c" + } +] diff --git a/mechanical/README.md b/mechanical/README.md new file mode 100644 index 0000000..eb6bdc2 --- /dev/null +++ b/mechanical/README.md @@ -0,0 +1,16 @@ +# Mechanical files + +[简体中文](README.zh-CN.md) · [Assembly guide](../docs/en/assembly.md) + +| Printable part | File | +|---|---| +| Body | [body.stl](stl/body.stl) | +| Upper cover | [upper-cover.stl](stl/upper-cover.stl) | +| Lower cover | [lower-cover.stl](stl/lower-cover.stl) | +| Retaining plate | [retainer.stl](stl/retainer.stl) | + +[source-map.json](source-map.json) records original supplied filenames and SHA-256. Geometry is unchanged. Independent STL coordinate systems are not an assembly-position reference. + +The complete supplied 230918 STEP is packaged separately as `FOLI-mechanical-source.zip` in a release bundle rather than placed directly in the source tree. [Download status](../releases/README.md) lists what is published. Optional media builds expect the extracted assembly at `cad/assembly.step`; see [CAD input](cad/README.md). + +The part set is published for inspection and fabrication, with [reference fasteners and assembly limits](../docs/en/assembly.md). Slicer profile, print orientation, tolerances and final material were not recorded in the supplied evidence; the repository does not invent validated settings. The exploded render illustrates structure, not a numbered assembly procedure. diff --git a/mechanical/README.zh-CN.md b/mechanical/README.zh-CN.md new file mode 100644 index 0000000..9f62571 --- /dev/null +++ b/mechanical/README.zh-CN.md @@ -0,0 +1,9 @@ +# 机械文件 + +[English](README.md) · [装配说明](../docs/zh-CN/assembly.md) + +四个原始零件已统一英文文件名:[主体](stl/body.stl)、[上盖](stl/upper-cover.stl)、[下盖](stl/lower-cover.stl)、[卡板](stl/retainer.stl)。[映射与校验值](source-map.json)保留原文件名,几何未修改。独立 STL 坐标不能当作装配位置。 + +完整 230918 STEP 作为 FOLI-mechanical-source.zip 单独打包,发布状态见[下载说明](../releases/README.zh-CN.md)。媒体重建时解压为 cad/assembly.step,见[CAD 输入说明](cad/README.md)。 + +参考紧固件与装配边界见[装配文档](../docs/zh-CN/assembly.md)。原始证据未记录切片、方向、配合公差和最终材质,不编造已验证打印配置。展开图是结构展示,不代替逐步装配手册。 diff --git a/mechanical/cad/README.md b/mechanical/cad/README.md new file mode 100644 index 0000000..31324ec --- /dev/null +++ b/mechanical/cad/README.md @@ -0,0 +1,7 @@ +# Optional assembly input / 可选装配输入 + +Extract `assembly.step` from the mechanical-source release bundle into this directory. It is intentionally ignored by Git because the supplied file is large; the printable STLs remain in the repository. The exact original file is `迷你打印机装配体230918.STEP`. + +Checksums and download availability are listed in [release downloads](../../releases/README.md). The optional media pipeline reads this file and derives meshes without changing it. A release bundle must be available before advertising a one-click complete CAD download. + +中文:完整 STEP 从机械源文件发布包获取并放在本目录,文件名为 assembly.step。Git 不直接追踪此大文件,STL 已在仓库。下载可用性与校验值见发布说明,不能把尚未发布的下载写成已上线。 diff --git a/mechanical/source-map.json b/mechanical/source-map.json new file mode 100644 index 0000000..61315f0 --- /dev/null +++ b/mechanical/source-map.json @@ -0,0 +1,26 @@ +[ + { + "file": "stl/body.stl", + "original_name": "外壳主体230727.STL", + "sha256": "602f486902fb1f0b8e0854b81ca82f6a33c0e55c1ff96b4a1b56b811346c4b6f", + "bytes": 2212784 + }, + { + "file": "stl/upper-cover.stl", + "original_name": "上盖230719.STL", + "sha256": "21cedd86a40b00cec80506be1b3b6aa61d17a374c12f64cc794425d8e5c9c0e5", + "bytes": 877084 + }, + { + "file": "stl/lower-cover.stl", + "original_name": "下盖230719.STL", + "sha256": "3b0cc7d0d5d298ba161e29cf3f7147d18ffb882fcd635fd91de805f1b4edff14", + "bytes": 871084 + }, + { + "file": "stl/retainer.stl", + "original_name": "卡板230719.STL", + "sha256": "d65bb0aa48f9050a537fd894f5fef413de3a90271d7eacd134626f043b4a6bae", + "bytes": 85684 + } +] diff --git a/mechanical/stl/body.stl b/mechanical/stl/body.stl new file mode 100644 index 0000000..03a64bc Binary files /dev/null and b/mechanical/stl/body.stl differ diff --git a/mechanical/stl/lower-cover.stl b/mechanical/stl/lower-cover.stl new file mode 100644 index 0000000..baf9445 Binary files /dev/null and b/mechanical/stl/lower-cover.stl differ diff --git a/mechanical/stl/retainer.stl b/mechanical/stl/retainer.stl new file mode 100644 index 0000000..e92bfdd Binary files /dev/null and b/mechanical/stl/retainer.stl differ diff --git a/mechanical/stl/upper-cover.stl b/mechanical/stl/upper-cover.stl new file mode 100644 index 0000000..4601fe8 Binary files /dev/null and b/mechanical/stl/upper-cover.stl differ diff --git a/media/README.md b/media/README.md new file mode 100644 index 0000000..79e4a15 --- /dev/null +++ b/media/README.md @@ -0,0 +1,24 @@ +# Product media + +[简体中文](README.zh-CN.md) · [Provenance](../docs/en/provenance.md) + +`images/`, `gifs/` and `video/` hold selected publication assets. The film is 90 seconds, 1920×1080/24fps, H.264/AAC stereo; CAD source frames were rendered at 1600×900 and scaled into the edit. The app tour is a 15-second, 1560×1040 GIF. [manifest.json](manifest.json) classifies each asset and records its checksum. + +## Sources + +`source/assets/` contains generated lifestyle concepts, their exact imagegen prompts and the monochrome paper texture. `source/evidence/` contains the original supplied photographs. `source/screens/` contains selected existing Android captures. Fonts and third-party music are not redistributed; music/Foley is generated from the included score script. + +## Optional rebuild + +Android and firmware builds do not require the media toolchain. To rebuild media, install Python 3.11, the pinned [Python requirements](../tools/media/requirements.txt), Blender 4.2, FFmpeg and FFprobe. Extract the complete assembly to [mechanical/cad](../mechanical/cad/README.md). Then run: + +```sh +python -m pip install -r tools/media/requirements.txt +python tools/media/build.py --blender /path/to/blender +``` + +The pipeline derives meshes from STEP, creates the studio from those meshes, renders camera/assembly/paper motion, generates score/Foley, edits the film and creates repository graphics. Outputs go to ignored `media/rendered/`; intermediates go to ignored `media/source/work/`. It does not depend on an old Blender file or the external original-material folder. The AI concept images are retained inputs; rebuilding does not rerun image generation. + +`FOLI_FONT_REGULAR`, `FOLI_FONT_BOLD`, `FOLI_FONT_SERIF` and `FOLI_FONT_SERIF_BOLD` can point to installed font files. Windows Segoe/Georgia and common Linux/macOS fonts are detected. Different fonts, Blender versions or encoder builds can alter pixels; rerun visual QA before replacing publication assets. + +For repository graphics after CG frames exist: `python tools/media/build.py --repo-assets-only`. For a fresh checkout, the full CAD pipeline must run first. Rendering can be resource intensive. No video-generation SaaS or secret API key is required to replay the included deterministic pipeline. diff --git a/media/README.zh-CN.md b/media/README.zh-CN.md new file mode 100644 index 0000000..354181b --- /dev/null +++ b/media/README.zh-CN.md @@ -0,0 +1,11 @@ +# 产品媒体 + +[English](README.md) · [来源说明](../docs/zh-CN/provenance.md) + +images、gifs、video 为精选发布资产。视频为90秒、1080p/24fps、立体声;三维源帧1600×900缩放合成。三屏GIF为15秒、1560×1040。[manifest.json](manifest.json)记录分类与校验值。 + +source/assets保留生活概念图、精确提示词和纸面纹理;source/evidence保留原始照片;source/screens保留选定真机截图。声音由源码合成,无第三方音乐;系统字体不随仓库分发。 + +完整媒体重建需要Python3.11、[固定依赖](../tools/media/requirements.txt)、Blender4.2、FFmpeg/FFprobe,以及解压到[mechanical/cad](../mechanical/cad/README.md)的STEP。运行 `python tools/media/build.py --blender /path/to/blender`。输出为忽略提交的media/rendered,中间文件为media/source/work,不依赖旧工作目录或旧Blender工程。AI概念图作为已保存输入,不会自动重新生图。 + +字体可通过FOLI_FONT_REGULAR/BOLD/SERIF/SERIF_BOLD设置,支持系统字体查找。字体、渲染器与编码器版本差异可能改变画面,替换发布素材前需重新视觉检查。仅重建仓库图时可用--repo-assets-only,但需先运行三维管线得到帧。本工具链与App/固件构建独立,不需要API密钥。 diff --git a/media/brand/foli-brand-board.png b/media/brand/foli-brand-board.png new file mode 100644 index 0000000..ac137c5 Binary files /dev/null and b/media/brand/foli-brand-board.png differ diff --git a/media/brand/foli-brand-board.svg b/media/brand/foli-brand-board.svg new file mode 100644 index 0000000..65079ed --- /dev/null +++ b/media/brand/foli-brand-board.svg @@ -0,0 +1 @@ +FOLI / VISUAL DIRECTION 01Small object. A distinct personality.Three identity studies. One calm, colorful product family.01 / RECOMMENDEDFOLIThe paper loopA continuous line. A little piece of paper.02 / ALTERNATIVEFOLIThe folded cornerA familiar page, reduced to its essentials.03 / ALTERNATIVEFOLIThe little rollA softer, more playful paper silhouette.A little color goes a long way.Chalk#F4F1E8Mint#C9E8D7Sky#B9D9EDCoral#EFA18DTypography: system sans-serif / clear hierarchy / sentence case / restrained colorCONCEPT STUDY diff --git a/media/brand/foli-mark.svg b/media/brand/foli-mark.svg new file mode 100644 index 0000000..59da1d2 --- /dev/null +++ b/media/brand/foli-mark.svg @@ -0,0 +1 @@ + diff --git a/media/brand/foli-wordmark.svg b/media/brand/foli-wordmark.svg new file mode 100644 index 0000000..fcd696a --- /dev/null +++ b/media/brand/foli-wordmark.svg @@ -0,0 +1 @@ +FOLI diff --git a/media/gifs/app-tour.gif b/media/gifs/app-tour.gif new file mode 100644 index 0000000..39f6f52 Binary files /dev/null and b/media/gifs/app-tour.gif differ diff --git a/media/gifs/assembly.gif b/media/gifs/assembly.gif new file mode 100644 index 0000000..f11c89d Binary files /dev/null and b/media/gifs/assembly.gif differ diff --git a/media/gifs/screen-to-paper.gif b/media/gifs/screen-to-paper.gif new file mode 100644 index 0000000..530d3ea Binary files /dev/null and b/media/gifs/screen-to-paper.gif differ diff --git a/media/images/app-overview.png b/media/images/app-overview.png new file mode 100644 index 0000000..af30a8c Binary files /dev/null and b/media/images/app-overview.png differ diff --git a/media/images/assembly-explained.jpg b/media/images/assembly-explained.jpg new file mode 100644 index 0000000..0ffd899 Binary files /dev/null and b/media/images/assembly-explained.jpg differ diff --git a/media/images/hardware-evidence.jpg b/media/images/hardware-evidence.jpg new file mode 100644 index 0000000..4827f74 Binary files /dev/null and b/media/images/hardware-evidence.jpg differ diff --git a/media/images/hero.jpg b/media/images/hero.jpg new file mode 100644 index 0000000..abfd2d7 Binary files /dev/null and b/media/images/hero.jpg differ diff --git a/media/images/system-architecture.png b/media/images/system-architecture.png new file mode 100644 index 0000000..3acda33 Binary files /dev/null and b/media/images/system-architecture.png differ diff --git a/media/manifest.json b/media/manifest.json new file mode 100644 index 0000000..acfa6fa --- /dev/null +++ b/media/manifest.json @@ -0,0 +1,80 @@ +{ + "source_notes": "docs/en/provenance.md", + "assets": [ + { + "file": "media/images/app-overview.png", + "kind": "presentation-image", + "sha256": "fe1a358834f2f4d49b395b98c38be41e4c783e1da7c9c03fa67df4f2d9fa2c42" + }, + { + "file": "media/images/assembly-explained.jpg", + "kind": "presentation-image", + "sha256": "0add8413daa276c2b0999a844116553650b8982b90d506ac38a333981e332196" + }, + { + "file": "media/images/hardware-evidence.jpg", + "kind": "presentation-image", + "sha256": "68bf51fcf53651d1241acf4e3e96d72df582d114768711f9bf3b29356dbb936e" + }, + { + "file": "media/images/hero.jpg", + "kind": "presentation-image", + "sha256": "fc5f1b0829f695bb005e8ed8ef4f8fcfa62f5cc97c61deea33a8d3da0acc0664" + }, + { + "file": "media/images/system-architecture.png", + "kind": "presentation-image", + "sha256": "f351ca843f72a8bca941ea23516dbc04bdf9ec3455a0db2c18915e5ff3ccb33e" + }, + { + "file": "media/gifs/app-tour.gif", + "kind": "interaction-or-CAD-animation", + "sha256": "f5a9ddb7a24c0a78dcc33c12b1d1f35c119e3bd46556ea0df1c000863557fa8d" + }, + { + "file": "media/gifs/assembly.gif", + "kind": "interaction-or-CAD-animation", + "sha256": "e3c203dbbb8d5adef3c96afc83de445b3dc687a2f6a17097844f0a8d54143354" + }, + { + "file": "media/gifs/screen-to-paper.gif", + "kind": "interaction-or-CAD-animation", + "sha256": "f4f9fbdc6c442eb4855d9e32bf6ce0d9c5d829e12fad361a45d85d5fdf67cd9d" + }, + { + "file": "media/video/FOLI-Made-Tangible-90s.mp4", + "kind": "product-film", + "sha256": "2ddcaedeb1cf238ebd33abe83edfe642b9450e6058402145b2772b81529af29a" + }, + { + "file": "media/video/FOLI-Made-Tangible.en.srt", + "kind": "product-film", + "sha256": "fc796edbd22dff2893838c965d66cc4a241027dad983847289619a0280e0f570" + }, + { + "file": "media/video/verification.json", + "kind": "product-film", + "sha256": "94a204551b0e6007e1dd2f0a0824ba81682a3fb0a06b36bf1d916efe8fcccf90" + }, + { + "file": "media/brand/foli-brand-board.png", + "kind": "brand-identity", + "sha256": "f89cb4c2aadccd7064cb5b60e5c41128102c34e9690d9ad2ca30982987c7f79d" + }, + { + "file": "media/brand/foli-brand-board.svg", + "kind": "brand-identity", + "sha256": "f82c9d184cd5c4c6da37f56b71e8b0ccd716d2bec7d734db7b8e840691e0c328" + }, + { + "file": "media/brand/foli-mark.svg", + "kind": "brand-identity", + "sha256": "6c0a5c295a96b09a4ef0a4112d626dde5faf31fe171ec41ae2f090426692634f" + }, + { + "file": "media/brand/foli-wordmark.svg", + "kind": "brand-identity", + "sha256": "92c03fd77e6b69bc705ed4117030ef704dfbe7e65e67d07d0220be69ca1267df" + } + ] +} diff --git a/media/source/assets/image-prompts.json b/media/source/assets/image-prompts.json new file mode 100644 index 0000000..18b3891 --- /dev/null +++ b/media/source/assets/image-prompts.json @@ -0,0 +1,9 @@ +{ + "tool": "built-in image_gen", + "reference": "media/film/work/renders/mint.png", + "prompts": [ + "Create one premium editorial lifestyle photograph for FOLI mini thermal printer product launch, landscape 16:9 wide. Reference image is the actual CAD geometry: preserve squat rounded square body, lid seam, narrow paper exit, small front power switch, circular indicator, USB-C near base, no display/no invented controls. Warm daylight, creamy chalk and mint product color, pale oak desk, elegant laptop keyboard at left foreground, small ceramic coffee cup upper left, soft linen, subtle plant shadow. Printer at right middle, small blank narrow white thermal receipt lies on desk beside it angled slightly clockwise. Product substantial and recognizable, no bulky redesign. Sophisticated warm consumer electronics advertising, realistic smooth matte polymer, crisp silhouette, natural shadows, restrained shallow depth of field. Large negative space upper left for future text overlay. No text, logos, UI, watermark, hands or people. Photograph must feel tactile and alive, not grey CAD. Reference is for geometry only; improve lighting and material greatly. This is a concept lifestyle visualization.", + "Premium editorial lifestyle still, landscape 16:9, warm late-morning sunlight. A small kraft gift wrapped with thin cotton ribbon, an open linen-covered book, a pale peach ceramic vase with one stem. A narrow blank white thermal paper note tucked under the ribbon, big enough for subsequent video overlay, no writing. On the far right, a small CHALK warm-white FOLI mini printer matching the supplied reference exactly: rounded squat square body, lid with narrow slot, small power switch/circular indicator/USB at bottom front. Preserve geometry, no display or invented feature. Warm refined youthful consumer electronics campaign, subtle peach and mint accents. Keep left third calm and empty for headline. Crisp tactile material, natural shadows. No hands, people, lettering, logos, watermarks. Concept visualization, not documentary.", + "Premium editorial lifestyle photograph landscape 16:9: a calm travel packing scene on warm pale oak table in gentle daylight. Unbranded sage canvas tote bag at back right, an open cream notebook at center-right with a narrow completely blank white thermal paper checklist resting inside, sunglasses, keys, plain water bottle partially seen. Small mint FOLI mini printer at far right matches reference exact squat rounded square body, lid seam, small switch, circle indicator, USB low front, no display. Minimal youthful refined styling. Broad empty calm cream area on left for typography. Natural texture, soft but dimensional sunlight, no grey CAD look. No people, hands, text, brands, watermark. Concept visualization." + ] +} diff --git a/media/source/assets/kindness.png b/media/source/assets/kindness.png new file mode 100644 index 0000000..44599e6 Binary files /dev/null and b/media/source/assets/kindness.png differ diff --git a/media/source/assets/morning.png b/media/source/assets/morning.png new file mode 100644 index 0000000..e22295c Binary files /dev/null and b/media/source/assets/morning.png differ diff --git a/media/source/assets/thermal-note.png b/media/source/assets/thermal-note.png new file mode 100644 index 0000000..74bdb7e Binary files /dev/null and b/media/source/assets/thermal-note.png differ diff --git a/media/source/assets/travel.png b/media/source/assets/travel.png new file mode 100644 index 0000000..c712ba1 Binary files /dev/null and b/media/source/assets/travel.png differ diff --git a/media/source/evidence/hardware-test-bench.jpg b/media/source/evidence/hardware-test-bench.jpg new file mode 100644 index 0000000..70eb216 Binary files /dev/null and b/media/source/evidence/hardware-test-bench.jpg differ diff --git a/media/source/evidence/print-test-page.jpg b/media/source/evidence/print-test-page.jpg new file mode 100644 index 0000000..d093344 Binary files /dev/null and b/media/source/evidence/print-test-page.jpg differ diff --git a/media/source/screens/android-v011/home-final.png b/media/source/screens/android-v011/home-final.png new file mode 100644 index 0000000..3b6bb95 Binary files /dev/null and b/media/source/screens/android-v011/home-final.png differ diff --git a/media/source/screens/android-v020/editor_final.png b/media/source/screens/android-v020/editor_final.png new file mode 100644 index 0000000..bd3c3f9 Binary files /dev/null and b/media/source/screens/android-v020/editor_final.png differ diff --git a/media/source/screens/android-v020/final_gallery.png b/media/source/screens/android-v020/final_gallery.png new file mode 100644 index 0000000..2ebb7cf Binary files /dev/null and b/media/source/screens/android-v020/final_gallery.png differ diff --git a/media/source/screens/android-v020/journal_editor.png b/media/source/screens/android-v020/journal_editor.png new file mode 100644 index 0000000..bbc8c9d Binary files /dev/null and b/media/source/screens/android-v020/journal_editor.png differ diff --git a/media/source/screens/android-v020/journal_live.png b/media/source/screens/android-v020/journal_live.png new file mode 100644 index 0000000..a06345b Binary files /dev/null and b/media/source/screens/android-v020/journal_live.png differ diff --git a/media/source/screens/android-v020/template_preview.png b/media/source/screens/android-v020/template_preview.png new file mode 100644 index 0000000..6f5d4cb Binary files /dev/null and b/media/source/screens/android-v020/template_preview.png differ diff --git a/media/video/FOLI-Made-Tangible-90s.mp4 b/media/video/FOLI-Made-Tangible-90s.mp4 new file mode 100644 index 0000000..4fe91c1 Binary files /dev/null and b/media/video/FOLI-Made-Tangible-90s.mp4 differ diff --git a/media/video/FOLI-Made-Tangible.en.srt b/media/video/FOLI-Made-Tangible.en.srt new file mode 100644 index 0000000..7800d66 --- /dev/null +++ b/media/video/FOLI-Made-Tangible.en.srt @@ -0,0 +1,77 @@ +1 +00:00:00,000 --> 00:00:03,800 +A little thought. Made tangible. + +2 +00:00:04,000 --> 00:00:09,800 +Meet FOLI. Little prints. Everyday joy. + +3 +00:00:10,000 --> 00:00:14,800 +Start with your paper and the Android app. + +4 +00:00:15,000 --> 00:00:17,800 +Connect your phone and printer over Bluetooth Low Energy. + +5 +00:00:18,000 --> 00:00:23,800 +Choose a template and make it personal. + +6 +00:00:24,000 --> 00:00:26,800 +Edit the words you want to keep. + +7 +00:00:27,000 --> 00:00:29,800 +Find your paper's style: Clean, Journal or Postcard. + +8 +00:00:30,000 --> 00:00:33,800 +Preview. Connect. Print. + +9 +00:00:34,000 --> 00:00:37,800 +A little focus for your day. + +10 +00:00:38,000 --> 00:00:41,800 +A little kindness for someone you love. + +11 +00:00:42,000 --> 00:00:45,800 +A little less to forget. + +12 +00:00:46,000 --> 00:00:53,800 +Behind every little print, a whole system works together. + +13 +00:00:54,000 --> 00:00:57,800 +The layout becomes a monochrome raster. + +14 +00:00:58,000 --> 00:01:01,800 +384 dots, packed eight per byte: 48 bytes per row. + +15 +00:01:02,000 --> 00:01:09,800 +Android sends row data over BLE. +Firmware coordinates the thermal print mechanism and paper feed. + +16 +00:01:10,000 --> 00:01:15,800 +Power, control and printing, housed in one product. + +17 +00:01:16,000 --> 00:01:17,800 +A printable enclosure built around the system. + +18 +00:01:18,000 --> 00:01:23,800 +Explore the hardware, firmware, enclosure and Android app. + +19 +00:01:24,000 --> 00:01:29,500 +FOLI. Little prints. Everyday joy. +github.com/TYF009/Mini-Printer diff --git a/media/video/verification.json b/media/video/verification.json new file mode 100644 index 0000000..957cd69 --- /dev/null +++ b/media/video/verification.json @@ -0,0 +1,39 @@ +{ + "file": "FOLI-Made-Tangible-90s.mp4", + "probe": { + "programs": [], + "stream_groups": [], + "streams": [ + { + "codec_name": "h264", + "width": 1920, + "height": 1080, + "r_frame_rate": "24/1" + }, + { + "codec_name": "aac", + "sample_rate": "48000", + "channels": 2, + "r_frame_rate": "0/0" + } + ], + "format": { + "duration": "90.000000", + "size": "16337520" + } + }, + "full_decode": "passed", + "measured_audio": { + "input_i": "-14.90", + "input_tp": "-1.52", + "input_lra": "4.90", + "input_thresh": "-25.24", + "output_i": "-15.28", + "output_tp": "-1.31", + "output_lra": "2.40", + "output_thresh": "-25.51", + "normalization_type": "dynamic", + "target_offset": "0.28" + }, + "sha256": "2ddcaedeb1cf238ebd33abe83edfe642b9450e6058402145b2772b81529af29a" +} diff --git a/releases/CHANGELOG.md b/releases/CHANGELOG.md new file mode 100644 index 0000000..fadbf2b --- /dev/null +++ b/releases/CHANGELOG.md @@ -0,0 +1,17 @@ +# Changelog / 版本记录 + +## FOLI integration / Android 0.2.1 + +- Integrate native Android, mechanical sources and product media with existing board/firmware history. +- Harden Android asynchronous BLE permission/adapter failures and connection cleanup. +- Harden firmware A6 command handling, fragmented row assembly, queue ownership, task yield and fault shutdown. +- Add bilingual documentation, host regression checks and CI workflows. +- Pin firmware platform and verify the Gradle wrapper distribution checksum. + +Build and host validation do not establish new physical printing or broad Android device compatibility. See component verification records. + +### Earlier Android work + +0.2.0 introduced the refined template/editor experience and was checked on Xiaomi Mi 6. 0.1.x records establish initial install/UI/BLE observations. Historical APKs and media studies are not included as current downloads. + +中文:本次整合加入原生 App、机械和媒体,修复 Android BLE 异常恢复与固件命令/队列/故障停止问题,提供双语文档与自动检查。保留历史验证范围,不宣称新增实物打印成功。 diff --git a/releases/README.md b/releases/README.md new file mode 100644 index 0000000..51e95ce --- /dev/null +++ b/releases/README.md @@ -0,0 +1,27 @@ +# Downloads and version compatibility + +[简体中文](README.zh-CN.md) + +## Android 0.2.1 development build + +[Download APK](android/FOLI-0.2.1-debug.apk) · [SHA-256](android/FOLI-0.2.1-debug.apk.sha256) · [Changes](CHANGELOG.md) + +Requires Android 7/API 24 or later. This is a debug-signed sideload build, not a store release. Review [setup](../docs/en/getting-started.md) before using physical hardware. Development signatures can differ between builders; a signature mismatch may require uninstalling an old build, which removes its local data. + +| Component | Integration identity | Validation | +|---|---|---| +| Mainboard | Supplied 2026-09-04 JLCEDA project; same bytes as upstream source | Historical hardware/printing evidence | +| Firmware | Pinned PlatformIO environment plus hardening in this branch | Compile + host tests; not flashed here | +| Android | 0.2.1 / code 4 | Build, Lint, host checks, signature; no new device run | +| Mechanical | Supplied 230918 assembly; 230727/230719 STLs | Source integrity, no new fit test | +| Presentation | 90-second FOLI film, three-screen app tour | Decode/stream/audio checks; visualizations labeled | + +## Mechanical source bundle + +The [0.2.1 development preview](https://github.com/TYF009/Mini-Printer/releases/tag/v0.2.1-preview.1) is published with the APK, film and full mechanical sources. + +[Download FOLI-mechanical-source.zip](https://github.com/TYF009/Mini-Printer/releases/download/v0.2.1-preview.1/FOLI-mechanical-source.zip) · [Mechanical SHA-256](https://github.com/TYF009/Mini-Printer/releases/download/v0.2.1-preview.1/FOLI-mechanical-source.zip.sha256) + +The bundle contains the complete original STEP, printable STLs and source mapping. It is not required for building Android or firmware. Its SHA-256 is `ddcff17953f4c73a32fa87a5d25a1ede443b001c99b25fda2ba5865e2f13f47b`. + +The repository does not treat older physical printing as proof of a fresh end-to-end print with these software revisions. [Verification scope](../docs/en/verification.md) is part of the version record. diff --git a/releases/README.zh-CN.md b/releases/README.zh-CN.md new file mode 100644 index 0000000..5623517 --- /dev/null +++ b/releases/README.zh-CN.md @@ -0,0 +1,11 @@ +# 下载与版本对应 + +[English](README.md) + +[Android 0.2.1 开发版 APK](android/FOLI-0.2.1-debug.apk) · [SHA-256](android/FOLI-0.2.1-debug.apk.sha256) · [版本变化](CHANGELOG.md) + +支持 Android 7/API24 起,为 debug 签名侧载构建,非应用商店发行。不同构建者的开发签名可能不同;覆盖安装若签名不匹配,卸载旧版会清除本地数据。连接前阅读[入门](../docs/zh-CN/getting-started.md)。 + +当前组合为用户指定的 2026-09-04 嘉立创工程、此次加固的固件、Android 0.2.1/code4、提供的230918装配与230727/230719零件。硬件有历史实物与打印证据;固件仅编译/主机检查,新 App 仅构建/Lint/主机检查/签名,新组合未追加真机打印验证。 + +完整 STEP、STL 与映射已在[0.2.1 开发预览](https://github.com/TYF009/Mini-Printer/releases/tag/v0.2.1-preview.1)发布:[下载机械源文件包](https://github.com/TYF009/Mini-Printer/releases/download/v0.2.1-preview.1/FOLI-mechanical-source.zip) · [SHA-256](https://github.com/TYF009/Mini-Printer/releases/download/v0.2.1-preview.1/FOLI-mechanical-source.zip.sha256)。它不影响 App/固件构建。详见[验证范围](../docs/zh-CN/verification.md)。 diff --git a/releases/android/FOLI-0.2.1-debug.apk b/releases/android/FOLI-0.2.1-debug.apk new file mode 100644 index 0000000..930fcd9 Binary files /dev/null and b/releases/android/FOLI-0.2.1-debug.apk differ diff --git a/releases/android/FOLI-0.2.1-debug.apk.sha256 b/releases/android/FOLI-0.2.1-debug.apk.sha256 new file mode 100644 index 0000000..210741c --- /dev/null +++ b/releases/android/FOLI-0.2.1-debug.apk.sha256 @@ -0,0 +1 @@ +232982a1ffa0f2968ade912db2ca84e979b513d7816e99a831075859370e9aff FOLI-0.2.1-debug.apk diff --git a/software/android/.gitignore b/software/android/.gitignore new file mode 100644 index 0000000..5102c45 --- /dev/null +++ b/software/android/.gitignore @@ -0,0 +1,6 @@ +.gradle/ +**/build/ +local.properties +*.jks +*.keystore +.idea/ diff --git a/software/android/README.md b/software/android/README.md new file mode 100644 index 0000000..6329c61 --- /dev/null +++ b/software/android/README.md @@ -0,0 +1,126 @@ +# FOLI for Android + +**Little prints. Everyday joy.** + +A native, English-first Android companion for the existing ESP32 Mini-Printer hardware. The app follows the approved FOLI visual direction: Chalk surfaces, Mint accents, original outline icons, and a paper-centered editor. + +This is a **0.2.1 development build**. Build and static-check results are recorded in the release notes. Hardware validation is a separate requirement; no connected-printer test is implied by compilation. + +[简体中文](README.zh-CN.md) + +## Features implemented + +- Create: note, photo and template entry points. +- Eight original editable templates, category filters, local favorites and full paper previews; Clean, Journal and Postcard styles, checklist/simple layouts, alignment and three type sizes. +- Focused editor with fixed back/undo and print controls; live bottom-sheet style previews, full-screen text composition, cancel-to-restore, session undo and full-screen zoom/pan inspection. +- Retained page scroll positions, local preview updates, debounced image processing, prewarmed thumbnail caching, native ripple feedback and reduced-motion-aware transitions. +- Photo import through Android's document picker; EXIF orientation handling, centered square/portrait crops, rotation, brightness, threshold or Floyd–Steinberg dithering. +- Real 384-dot monochrome preview generated from the exact bytes to be sent. +- Local draft persistence, including a downsampled copy of the selected photo in app-private storage. +- BLE discovery, connection, MTU negotiation, service validation, notification subscription and real device-state display. +- Three print densities, serialized acknowledged writes, transfer progress, device-state-based stop reporting, timeout handling and interrupted-job protection. +- No account, server, analytics or Internet permission. Printer compatibility is based on UUIDs and capabilities, not cosmetic device names alone. + +There is no simulated connection, fake battery value, automatic retry, background-printing claim, or demo-mode success message. + +## Requirements and build + +- JDK 17. +- Android SDK Platform 32 and compatible build tools; Gradle 7.4 / Android Gradle Plugin 7.3.1 are pinned. +- Android 7.0 / API 24 or later at runtime, with BLE for physical printing. +- `local.properties` containing your SDK directory, e.g. `sdk.dir=E:/Android SDK`. Do not commit this machine-specific file. + +Windows PowerShell: + +```powershell +$env:JAVA_HOME = 'C:\path\to\jdk-17' +.\build.ps1 +python test-host.py +``` + +`build.ps1` invokes the standard Gradle wrapper through Java directly to preserve Unicode Windows paths. It runs `assembleDebug` and `lintDebug`. The normal wrapper remains available on other systems: + +```sh +chmod +x gradlew +./gradlew assembleDebug lintDebug +python3 test-host.py +``` + +Output: `app/build/outputs/apk/debug/app-debug.apk`. + +This development build intentionally uses the existing installed API 32 toolchain. It is for direct-install development testing. A current compile/target SDK migration, Android-version validation and release signing are required before a store release. No private signing key belongs in the repository. + +## Connect and print + +1. Charge the compatible printer battery, install paper correctly and power on the printer. +2. Close the old printer app or any other BLE app connected to it. +3. In FOLI, open Device → Find your printer. Grant the requested runtime permission and select your printer. +4. Wait for actual paper, temperature and battery status before sending a job. Unknown data is shown as unknown. +5. Open a template or import a photo. Edit it, inspect Print preview, select density, then Send to printer. +6. Keep FOLI in the foreground and the phone near the printer. FOLI keeps the screen on during an active job. +7. “Sending” means BLE transfer. After an observed START/WORKING → state 3 transition, FOLI says “Printer stopped. Check your paper.” State 3 also represents some timeout/error stops, so the app never treats it as proof of physical success. Inspect the paper, power-cycle the printer and explicitly confirm that restart before sending another job. + +Android 12+: Nearby devices permissions (`BLUETOOTH_SCAN`, `BLUETOOTH_CONNECT`). Android 7–11: Android requires fine-location permission and enabled location services for BLE scanning; the app does not collect or transmit location. Photos use the system document picker without broad storage permission. + +## Protocol and constraints + +| Item | Value | +| --- | --- | +| Service UUID | `4fafc201-1fb5-459e-8fcc-c5c9c331914b` | +| Characteristic UUID | `beb5483e-36e1-4688-b7f5-ea07361b26a8` | +| Monochrome line | 384 pixels, 48 bytes, black = 1, MSB first | +| Density command | `A5 A5 A5 A5 01/02/03` for Light/Medium/Dark | +| Start after transfer | `A6 A6 A6 A6 01` | +| Status | battery, temperature, paper enum, print enum: exactly 4 bytes | +| Temperature sentinel | 255 = sensor unavailable in revised firmware; never displayed as 255 degrees | +| Paper enum | 0 = loaded, 1 = missing | +| Print enum | 0 = initial, 1 = start, 2 = working, 3 = finished or stopped (not success acknowledgement) | +| Transfer | Acknowledged GATT writes with at least 20 ms between packets | +| Minimum negotiated MTU | 51 (48-byte row plus ATT overhead) | +| App queue limit | 768 rows; excessive text is rejected, tall photos are fitted without truncating content | + +MTU negotiation can be affected by other GATT clients and OS versions. FOLI checks the resulting size and rejects connections that cannot transmit a whole row. Acknowledged GATT writes establish transport acceptance, not application-level proof that every line was printed; the legacy protocol has no per-line sequence numbers or checksums. + +Firmware compatibility and remaining limits: + +- Older upstream firmware lets A6 fall through into the image queue and may append a stray/corrupted row. The hardened firmware in this repository returns after command handling and rejects partial/overflowed jobs; these fixes have build/host-test evidence, not a new physical print validation. +- The firmware uses a fixed 20-second print timeout. A 768-row buffer bound is not a promise that all dense prints will finish within that timer. Dense/long-image validation and an appropriate firmware change are required before release. +- Firmware state 3 means finished or stopped and does not distinguish all error causes. Even a nominal started-to-stopped transition remains unconfirmed. FOLI preserves the restart requirement and never declares physical print success from this packet. A terminal packet without an observed start also cannot identify the current job. +- There is no cancel command. Stopping the app's transfer does not stop a print that has already begun. +- After interrupted/unconfirmed transfers, the app blocks another job until the user power-cycles the printer and explicitly acknowledges that reset. Reconnecting alone does not clear the printer's queue. +- Older firmware battery calculation can produce invalid percentages. The hardened source clamps the computed value, while physical calibration and other sensor limits remain. The app validates packet shape/ranges but cannot calibrate hardware remotely. + +## Source map + +- `MainActivity.java`: native views, navigation, runtime permissions, document picker, editing and lifecycle. +- `BlePrinter.java`: main-looper-confined BLE connection and transfer state. +- `PaperRenderer.java`: note/photo layout and exact monochrome preview. +- `PrinterProtocol.java`: Android-independent raster encoding, commands and status validation. +- `FoliIcon.java`: original vector-style UI icon drawing. +- `TemplateCatalog.java`: original offline template content and categories. +- `ZoomPaperView.java`: inspection of the actual output bitmap without changing print data. +- `tests/ProtocolTest.java`: host-side regression checks without Android dependencies. + +## Verification before release + +Run the build, Lint and host tests, then validate a physical phone and printer. The important cases are: first launch without permissions, denial/regrant, Bluetooth off, scan/reconnect, image import and orientation, note editing, app recreation and draft recovery, preview/output agreement, densities, dense images, paper-out, hot-head status, interrupted transfer, restart recovery and completion reporting. Check layouts at small widths and enlarged font sizes. + +This project does not reuse the old app's photo editor or BLE library; the old app and firmware were read to establish compatibility. AndroidX ExifInterface handles photo orientation. Gradle wrapper scripts/JAR retain their upstream provenance and license notices. All FOLI branding is a concept pending resolution of the previously recorded name collision. + +Official API references: [Bluetooth permissions](https://developer.android.com/develop/connectivity/bluetooth/bt-permissions), [BluetoothGatt](https://developer.android.com/reference/android/bluetooth/BluetoothGatt). + +## Repository integration update — 0.2.1 + +BLE callbacks and queued read/write operations now recover when Bluetooth access changes, instead of allowing permission/adapter exceptions to crash the activity. Recovery closes the GATT session and retains interrupted-job protection. Closing a session attempts GATT close even if disconnect throws. `BleOperationTest` checks successful execution, access-revocation recovery, adapter-state recovery and propagation of programming errors; it is a host boundary test, not an Android radio simulation. + +`test-host.py` runs on Windows, Linux and macOS with JDK 17 and Python 3. The original encoder suite reports 158 assertions, including byte-by-byte checks; this count does not mean 158 distinct integration scenarios. CI builds API 32 and runs build/Lint plus host checks. Existing physical UI checks describe 0.2.0; the 0.2.1 changes have not been revalidated on a phone or printer. + +The wrapper distribution checksum is pinned to the official [Gradle 7.4 binary checksum](https://services.gradle.org/distributions/gradle-7.4-bin.zip.sha256). + +### Legacy terminal-state correction + +`PrintOutcome` is shared by the actual BLE receive path and host tests. A nominal terminal packet becomes `STOPPED_UNCONFIRMED`; paper-out, overheat or a previous failure cannot become success. An unstarted job remains pending. Interrupted/unconfirmed jobs retain their recovery requirement until an explicit printer-restart acknowledgement. `MainActivity` uses this typed outcome rather than parsing UI text to manage persisted uncertainty. Seven host scenarios cover this decision boundary; there is still no new physical verification. + +### Unavailable print-head sensor + +Revised firmware reserves temperature byte 255 for an unavailable/invalid sensor and refuses heating. Android displays Sensor unavailable, blocks printing, and treats the value during an active job as failure requiring inspection and restart rather than a cooldown. Legacy firmware does not implement this sentinel; its observed idle zero reading remains a historical limitation, not a confirmed valid sensor reading. Seven shared temperature helper cases and eight outcome cases cover the sentinel and stop semantics on the host; no sensor hardware test is implied. diff --git a/software/android/README.zh-CN.md b/software/android/README.zh-CN.md new file mode 100644 index 0000000..7203363 --- /dev/null +++ b/software/android/README.zh-CN.md @@ -0,0 +1,52 @@ +# FOLI Android + +[English](README.md) + +原生 Java Android 应用,支持文字、照片、8 个离线模板、纸面风格、真实黑白光栅预览与 BLE 传输。当前 0.2.1 为开发侧载版本,不是商店发行版。 + +## 构建 + +准备 JDK 17、Python 3、Android SDK Platform 32。Gradle 7.4 / AGP 7.3.1 已固定,Gradle 分发校验值来自官方校验文件。AGP 当前默认使用 Build Tools 30.0.3;CI 安装已验证的 30.0.3。设置 SDK 环境或本地 `local.properties`,后者不提交仓库。 + +```powershell +$env:JAVA_HOME = 'C:\path\to\jdk-17' +.\build.ps1 +python test-host.py +``` + +Linux/macOS: + +```sh +chmod +x gradlew +./gradlew --no-daemon assembleDebug lintDebug +python3 test-host.py +``` + +输出 `app/build/outputs/apk/debug/app-debug.apk`。CI 执行构建、Lint、协议和 BLE 异常边界检查。158 条协议断言含逐字节检查,不代表 158 个独立集成场景。 + +## 连接与使用 + +可以离线编辑和预览。实物打印需要装纸并开机,在 Device 页发现设备,授权蓝牙,等待设备真实状态,再检查纸面并发送。保持应用前台;应用进入后台会终止发送/等待并要求检查设备。连接成功和传输完成均不等于实际打印成功。 + +Android 12 及以上需要附近设备权限;Android 7–11 的 BLE 扫描需要定位权限及系统定位服务。应用不采集定位,无网络权限、账号、分析或服务端。照片通过系统选择器读取,降采样副本保存在应用私有目录;备份和设备迁移已排除这些应用数据。 + +## 0.2.1 可靠性改动 + +异步 GATT 回调和读写操作在权限撤销或蓝牙状态变化时进入错误恢复,关闭连接并保留任务中断标记。即使断开调用失败,也会继续尝试关闭 GATT。纯 Java 测试覆盖该恢复边界与正常错误传播,不等于模拟了真实 Android 蓝牙环境。 + +历史真机检查对应小米 6 上的 0.2.0。0.2.1 改动仅完成本地构建、Lint 与主机测试;没有追加手机或打印机验证。完整 BLE 协议、兼容性限制与源码地图见英文文档。固件没有远程取消指令,历史固件存在 A6 入队、固定超时及状态上报问题;不能自动重试不确定的任务。 + +## 重要文件 + +- `app/src/main/java/studio/foli/android/`:界面、纸面渲染、协议与 BLE。 +- `tests/`:纯 Java 编码与异常边界检查。 +- `VERIFICATION.md`:已记录的历史验证与当前改动检查。 +- `THIRD_PARTY_NOTICES.md`:依赖来源与许可说明。 + +## 旧协议终态语义 + +固件状态 3 表示完成或停止,缺纸、过热或超时也可能走到这个状态,不能据此宣布打印成功。应用现在显示“Printer stopped. Check your paper.”,保留任务不确定与重启恢复要求。即使名义正常终态也应检查实际纸张,并在下一任务前重启打印机后确认。缺少已观察到的开始状态时,单独终态不会识别为当前任务结束。持久化恢复通过显式 `PrintOutcome` 判定,不再解析界面文案。共享判定代码新增 7 个主机测试场景,未新增实物测试。 + +## 温度传感器不可用约定 + +修订固件约定温度字节 255 表示传感器无效/不可用并拒绝加热。Android 显示 Sensor unavailable,禁止打印;任务中收到该值视为失败、保留中断恢复,并提示检查传感器后重启,不误导为等待降温。旧固件没有这个约定;历史空闲 0℃ 仍是已记录局限,不代表读数有效。主机测试新增 7 个共享温度辅助判定场景,终态场景增至 8 个;没有传感器实测。 diff --git a/software/android/THIRD_PARTY_NOTICES.md b/software/android/THIRD_PARTY_NOTICES.md new file mode 100644 index 0000000..d4a72de --- /dev/null +++ b/software/android/THIRD_PARTY_NOTICES.md @@ -0,0 +1,24 @@ +# Third-party notices + +## AndroidX ExifInterface 1.3.7 + +Copyright The Android Open Source Project. Licensed under the Apache License, Version 2.0. + +Used for safe, cross-version image metadata and orientation reading. No photo-editor or BLE library from the old app is bundled. + +- Project: https://developer.android.com/jetpack/androidx/releases/exifinterface +- License: https://www.apache.org/licenses/LICENSE-2.0 +- Source: https://android.googlesource.com/platform/frameworks/support/+/androidx-main/exifinterface/ + +Transitive AndroidX annotations are also supplied by the Android Open Source Project under Apache License 2.0. + +## Gradle wrapper and Android build tooling + +The Gradle wrapper JAR and generated wrapper scripts are upstream Gradle build infrastructure. The copied wrapper scripts retain their original copyright and Apache 2.0 license headers. Android Gradle Plugin and other build-time dependencies are resolved through the standard Google and Maven Central repositories; they are not represented as FOLI-authored software. + +- Gradle: https://gradle.org/ +- Gradle licensing: https://github.com/gradle/gradle/blob/master/LICENSE + +## Brand and project references + +The FOLI visual direction and UI source were created for this project. The legacy Mini-Printer firmware and app were inspected to establish the existing BLE protocol. Authorization of project materials does not replace licenses attached to third-party dependencies. The preliminary FOLI name-collision finding remains recorded in `brand/README.md` at the workspace root. diff --git a/software/android/VERIFICATION.md b/software/android/VERIFICATION.md new file mode 100644 index 0000000..139020c --- /dev/null +++ b/software/android/VERIFICATION.md @@ -0,0 +1,74 @@ +# Verification record — 2026-10-29 + +The first table records the initial 0.1.0 build. Later sections record physical-device and 0.2.0 results. + +| Check | Result | +| --- | --- | +| Native Java / Android resource compilation | Passed | +| Debug APK packaging | Passed | +| Android Lint | Passed: 0 errors, 1 dependency-version advisory | +| Host-side raster/protocol regression checks | Passed: 158 assertions | +| Final delivered APK v2 signature | Passed | +| Application ID / launcher / SDK manifest inspection | Passed | +| Android phone visible to ADB | No device at handoff | +| Install, launch and actual UI verification | Pending phone | +| Real BLE / printer / paper-output test | Pending phone and powered printer | + +The dependency advisory is for the pinned compile-only AndroidX annotation 1.2.0 (Lint suggests 1.3.0). It is not a runtime failure. The Gradle plugin also emits an experimental-path-option message because the workspace contains Chinese characters on Windows. The build uses that supported override and direct Java wrapper invocation; it does not relocate project output outside the requested workspace. + +Protocol assertions cover full-row framing, MSB-first boundaries, all-white/all-black output, transparent-pixel compositing, dither behavior, density/start commands, status shape/ranges, and rejection of oversized or malformed images. They do not prove BLE radio behavior or paper-output quality. + +Final APK and its SHA-256 are recorded in `../../releases/android/README.md`. On-device results should be added here as each physical test is actually performed. + +## Physical-phone smoke test — 2026-10-29, version 0.1.1 + +Device: Xiaomi Mi 6 (`sagit`), Android 8.0.0 / API 26, 1080×1920. USB authorization and installation were enabled by the owner. + +- APK installation and native Activity launch: passed; final cold launch reported 424 ms Activity time (one observation, not a performance benchmark). +- Create/home screen: inspected on the physical display via screenshot. +- Note editor and real raster preview: opened successfully. +- Text editing: appended a temporary `MI6` suffix to the built-in sample title, applied the preview and saved it. +- Draft persistence: the edited title survived APK update/process restart and appeared in the actual raster preview. +- Templates: navigated to the template list and selected Today's three; default sample content restored. +- Device page: verified disconnected state and unknown battery/paper/temperature rather than simulated values. +- Final app-process log sample contained no `FATAL EXCEPTION`; this is a scoped smoke check, not proof of all runtime paths. +- Fixed a real-device defect: unicode checkbox outlines lost thin edges during thresholding. Checkboxes now use explicit raster geometry, including correct alignment of wrapped text. +- Centered bottom-navigation and editor-tool captions after inspecting the native layout. +- Rebuilt with `assembleDebug` and `lintDebug`: passed (same one annotation-version advisory). Final delivered APK signature verified. + +Selected historical screenshots are retained in `verification/evidence/`; the full intermediate history and UI trees remain in the original working materials. `home-final.png`, `templates-final.png` and `editor-final.png` show the final installed build; earlier files document the discovered checkbox defect and its first correction. These contain phone status-bar details and are local verification evidence, not automatically approved public marketing assets. + +Still pending: photo picker/import and image-transform smoke tests, permissions/scan/reconnect testing, real BLE device states, actual paper output, abnormal print recovery, large-font layout and broader Android compatibility. No physical print command was sent during this session. + +## Connected printer / no paper — 2026-10-29 + +The owner connected the printer and explicitly stated that no paper was installed. FOLI's actual Device screen showed `Connected via Bluetooth LE`, battery around `75–76%` across the UI snapshot and later screenshot, paper `Out of paper`, print-head temperature `0 °C`, and the corresponding paper-loading message. Screenshot: `verification/evidence/ble-no-paper.png`. + +This verifies connection readiness and receipt/display of a valid four-byte device status packet for this session. Battery accuracy is not calibrated by this observation. Temperature `0 °C` is an unresolved reading, not proof of functioning temperature sensing; investigate the connected mechanism/NTC and firmware's raw ADC/conversion before heating tests. + +No physical print was sent. An attempted UI-only guard check did not produce a captured paper-out rejection dialog (the phone moved to the help screen during navigation), so the runtime print-block test remains pending. Source-level preflight checks reject `paper == 1`; that is separate from an observed on-device test. Permission granting and discovery were performed by the owner, not independently validated as a full automated flow. + +## 0.2.0 UX upgrade — physical phone + +Build/Android Lint passed (0 errors, 1 pre-existing annotation-version advisory); 158 protocol assertions passed after the UX changes. Final APK v2 signature passed. Installed and launched on the same Mi 6 after each device-driven refinement. + +Observed on device: eight-card gallery; Focus filters to two items; template preview and application; live Clean-to-Journal preview; Keep changes; header Undo restoring the previous style; favorite heart transition; Saved filtering to one item; favorite surviving the final APK update; full-screen composer with keyboard and Cancel/Done visible; temporary `UX` suffix entry and Cancel restoring the prior sample; full-screen paper inspector opening. Selected 0.2.0 captures: `verification/evidence/final_gallery.png` and `verification/evidence/journal_live.png`. + +Resolved findings: non-prewarmed thumbnail blanks, keyboard covering floating text-sheet actions (replaced by a full-screen composer), undo notice resizing the editor viewport, selected category falling out of view, stale selected-option typography, and small-screen preview sizing. The screenshot `text_sheet.png` documents the earlier keyboard problem; `composer_keyboard.png` shows the corrected pattern. `final_gallery.png` records the final installed gallery. + +No fatal exception appeared in the final scoped process-log sample. It recorded one 214 ms startup raster render; no sustained FPS or performance conclusion is inferred. The printer was off, and no print or firmware update was performed. Remaining validation includes physical printing, all photo paths, actual multi-touch gestures, enlarged fonts, broader accessibility and process/recreation edge cases. + +## Repository integration — Android 0.2.1 + +The integrated application adds a tested Bluetooth access-change boundary to asynchronous callbacks and queued GATT read/write operations. Cleanup attempts close even if disconnect fails. Protocol host checks (158 assertions) and the new failure-boundary suite passed on JDK 17. `assembleDebug` and `lintDebug` passed against the integrated 0.2.1 source (0 errors, one advisory for pinned compile-only AndroidX annotation 1.2.0); this does not extend historical 0.2.0 phone UI checks to 0.2.1. No radio or physical printing validation was performed for these changes. Historical screenshots remain in the original working materials; selected public product media is maintained separately at the repository level. + + +The 0.2.1 permission-related checks exercise the host-side recovery boundary only. Permission revocation on a real Android device has not been tested in this integration. + +## Legacy terminal-state semantics correction — 0.2.1 + +The actual receive path now uses shared `PrintOutcome.fromStatus`. State 3 is finished-or-stopped, never physical-success acknowledgement. A nominal observed start→terminal transition stops waiting but retains `dirty` and restart recovery; paper-out, overheat or previous failure cannot clear an interrupted job. A terminal without observed start remains pending. `MainActivity.changed()` uses typed outcome/restart confirmation rather than an English status prefix to manage persistence. Seven host outcome scenarios passed in addition to 158 encoder assertions and the BLE access boundary suite. These are source/host checks, not device or physical-print tests. + +## Temperature-unavailable sentinel — 0.2.1 + +Temperature byte 255 is reserved by revised firmware for an invalid/unavailable sensor. Shared protocol helpers drive both the UI label and printing guards; active jobs fail with inspection/restart guidance, not cooldown. Host checks pass 158 encoder assertions, the BLE access boundary, eight outcome cases and seven temperature cases. Legacy idle zero readings remain a separate historical limitation. No new sensor, phone or printer test was performed. diff --git a/software/android/app/build.gradle b/software/android/app/build.gradle new file mode 100644 index 0000000..75bca0e --- /dev/null +++ b/software/android/app/build.gradle @@ -0,0 +1,28 @@ +plugins { id 'com.android.application' } + +android { + namespace 'studio.foli.android' + compileSdk 32 + defaultConfig { + applicationId 'studio.foli.android' + minSdk 24 + targetSdk 32 + versionCode 4 + versionName '0.2.1' + } + compileOptions { + sourceCompatibility JavaVersion.VERSION_1_8 + targetCompatibility JavaVersion.VERSION_1_8 + } + buildTypes { + release { + minifyEnabled false + } + } + lint { abortOnError true } +} + +dependencies { + implementation 'androidx.exifinterface:exifinterface:1.3.7' + compileOnly 'androidx.annotation:annotation:1.2.0' +} diff --git a/software/android/app/src/main/AndroidManifest.xml b/software/android/app/src/main/AndroidManifest.xml new file mode 100644 index 0000000..6e50d22 --- /dev/null +++ b/software/android/app/src/main/AndroidManifest.xml @@ -0,0 +1,19 @@ + + + + + + + + + + + + + + + + + + diff --git a/software/android/app/src/main/java/studio/foli/android/BleOperation.java b/software/android/app/src/main/java/studio/foli/android/BleOperation.java new file mode 100644 index 0000000..cccee30 --- /dev/null +++ b/software/android/app/src/main/java/studio/foli/android/BleOperation.java @@ -0,0 +1,10 @@ +package studio.foli.android; + +/** Platform calls can fail after a permission or adapter-state change. */ +public final class BleOperation { + private BleOperation() {} + public static void run(Runnable operation, Runnable unavailable) { + try { operation.run(); } + catch (SecurityException | IllegalStateException changedAccess) { unavailable.run(); } + } +} diff --git a/software/android/app/src/main/java/studio/foli/android/BlePrinter.java b/software/android/app/src/main/java/studio/foli/android/BlePrinter.java new file mode 100644 index 0000000..77db377 --- /dev/null +++ b/software/android/app/src/main/java/studio/foli/android/BlePrinter.java @@ -0,0 +1,243 @@ +package studio.foli.android; + +import android.annotation.SuppressLint; +import android.bluetooth.*; +import android.bluetooth.le.*; +import android.content.Context; +import android.os.Handler; +import android.os.Looper; +import java.util.*; + +/** Activity-owned BLE session. All mutable session state is confined to the main looper. */ +// Runtime access changes are recovered by runBle/postBle and cleanup guards. +@SuppressLint("MissingPermission") +public final class BlePrinter { + static final UUID SERVICE=UUID.fromString("4fafc201-1fb5-459e-8fcc-c5c9c331914b"); + static final UUID CHARACTERISTIC=UUID.fromString("beb5483e-36e1-4688-b7f5-ea07361b26a8"); + static final UUID CCCD=UUID.fromString("00002902-0000-1000-8000-00805f9b34fb"); + public interface Listener { void changed(); void message(String text); } + private final Context context; + private final Handler main=new Handler(Looper.getMainLooper()); + private final Listener listener; + public final LinkedHashMap devices=new LinkedHashMap<>(); + private BluetoothGatt gatt; + private BluetoothGattCharacteristic characteristic; + private BluetoothLeScanner scanner; + private Runnable timeout, scanStop, watchdog, poll; + private boolean closed, pending, scanning, started, failedJob; + public boolean ready, connecting, sending, awaiting, dirty; + public PrintOutcome jobOutcome=PrintOutcome.IDLE; + public int battery=-1, temperature=-1, paper=-1, printState=-1, progress; + public int mtu=23; + public String status="Not connected", deviceName="Your FOLI", address=""; + private byte[][] rows; + private int index, density; + private long session; + + public BlePrinter(Context context,Listener listener) { this.context=context; this.listener=listener; } + public boolean busy() { return sending||awaiting; } + public boolean isScanning() { return scanning; } + private BluetoothAdapter adapter() { + BluetoothManager manager=(BluetoothManager)context.getSystemService(Context.BLUETOOTH_SERVICE); + return manager==null?null:manager.getAdapter(); + } + public boolean available() { try { BluetoothAdapter a=adapter(); return a!=null&&a.isEnabled(); } catch(SecurityException|IllegalStateException e) { return false; } } + private void runBle(Runnable operation) { + BleOperation.run(operation, () -> { + stopScan(); + fail("Bluetooth access changed. Check permissions and reconnect."); + }); + } + private void postBle(Runnable operation) { main.post(() -> runBle(operation)); } + private void change() { if (!closed) listener.changed(); } + private void say(String value) { status=value; change(); } + private void arm(String operation) { + pending=true; + if(timeout!=null) main.removeCallbacks(timeout); + timeout=()->fail(operation+" timed out. Reconnect and try again."); + main.postDelayed(timeout,12000); + } + private void disarm() { pending=false; if(timeout!=null)main.removeCallbacks(timeout); } + public void scan() { + stopScan(); + if(!available()){listener.message("Turn on Bluetooth to find your printer.");return;} + if(connecting||busy()){listener.message("Finish the current connection or print first.");return;} + devices.clear(); + try { scanner=adapter().getBluetoothLeScanner(); } catch(SecurityException|IllegalStateException e) { fail("Bluetooth access changed. Check permissions and reconnect."); return; } + if(scanner==null){listener.message("Bluetooth scanning is unavailable.");return;} + scanning=true; say("Looking for your FOLI…"); + try { + scanner.startScan(null,new ScanSettings.Builder().setScanMode(ScanSettings.SCAN_MODE_LOW_LATENCY).build(),scanCallback); + scanStop=()->{stopScan();say(devices.isEmpty()?"No printer found. Check power and try again.":"Choose your printer below.");}; + main.postDelayed(scanStop,12000); + } catch(SecurityException|IllegalStateException e){stopScan();say("Bluetooth permission or scanning is unavailable.");} + } + private final ScanCallback scanCallback=new ScanCallback(){ + @Override public void onScanResult(int type, ScanResult result){ + postBle(()->{ + if(!scanning||closed)return; + BluetoothDevice d=result.getDevice(); + String name=result.getScanRecord()==null?null:result.getScanRecord().getDeviceName(); + if(name==null)name=d.getName(); + boolean match=name!=null&&(name.equals("Mini-Printer")||name.toLowerCase(Locale.ROOT).startsWith("foli")); + if(result.getScanRecord()!=null&&result.getScanRecord().getServiceUuids()!=null) + for(android.os.ParcelUuid id:result.getScanRecord().getServiceUuids())if(SERVICE.equals(id.getUuid()))match=true; + if(match&&!devices.containsKey(d.getAddress())){devices.put(d.getAddress(),d);change();} + }); + } + @Override public void onScanFailed(int error){postBle(()->{stopScan();say("Scan failed ("+error+"). Wait a moment and try again.");});} + }; + public void stopScan(){ + if(scanStop!=null)main.removeCallbacks(scanStop); + if(scanner!=null&&scanning)try{scanner.stopScan(scanCallback);}catch(SecurityException|IllegalStateException ignored){} + scanning=false; + } + public void connect(BluetoothDevice device){ + if(busy())return; + stopScan(); disconnect(); + deviceName="FOLI"; + connecting=true; say("Connecting to your printer…"); + try {address=device.getAddress();gatt=device.connectGatt(context,false,callback,BluetoothDevice.TRANSPORT_LE);arm("Connection");} + catch(SecurityException|IllegalArgumentException|IllegalStateException e){fail("Could not connect. Check Bluetooth permissions.");} + } + private final BluetoothGattCallback callback=new BluetoothGattCallback(){ + @Override public void onConnectionStateChange(BluetoothGatt g,int result,int state){postBle(()->{ + if(g!=gatt||closed)return; + disarm(); + if(result!=BluetoothGatt.GATT_SUCCESS||state==BluetoothProfile.STATE_DISCONNECTED){fail("Printer disconnected. Check power and reconnect.");return;} + if(state==BluetoothProfile.STATE_CONNECTED){ + say("Preparing a reliable connection…");arm("MTU negotiation"); + if(!g.requestMtu(185))fail("Could not request a larger BLE packet size."); + } + });} + @Override public void onMtuChanged(BluetoothGatt g,int value,int result){postBle(()->{ + if(g!=gatt||closed)return; + disarm(); mtu=value; + if(result!=BluetoothGatt.GATT_SUCCESS||mtu<51){fail("This connection cannot carry a full print row. Reconnect; an MTU of at least 51 is required.");return;} + arm("Service discovery");if(!g.discoverServices())fail("Could not discover printer services."); + });} + @Override public void onServicesDiscovered(BluetoothGatt g,int result){postBle(()->{ + if(g!=gatt||closed)return; + disarm();BluetoothGattService service=g.getService(SERVICE); + characteristic=service==null?null:service.getCharacteristic(CHARACTERISTIC); + if(result!=0||characteristic==null){fail("This device does not expose the FOLI-compatible printing service.");return;} + int props=characteristic.getProperties(); + if((props&BluetoothGattCharacteristic.PROPERTY_WRITE)==0||(props&BluetoothGattCharacteristic.PROPERTY_NOTIFY)==0){fail("Printer must support acknowledged writes and status notifications.");return;} + BluetoothGattDescriptor descriptor=characteristic.getDescriptor(CCCD); + if(descriptor==null||!g.setCharacteristicNotification(characteristic,true)){fail("Printer status notifications are unavailable.");return;} + descriptor.setValue(BluetoothGattDescriptor.ENABLE_NOTIFICATION_VALUE); + arm("Status subscription");if(!g.writeDescriptor(descriptor))fail("Could not subscribe to printer status."); + });} + @Override public void onDescriptorWrite(BluetoothGatt g,BluetoothGattDescriptor descriptor,int result){postBle(()->{ + if(g!=gatt||closed)return; + disarm();if(result!=0){fail("Could not enable printer status.");return;} + ready=true;connecting=false;say(dirty?"Connected. Power-cycle the printer before another job.":"Connected. Waiting for device status…"); + readStatus(); + });} + @Override public void onCharacteristicRead(BluetoothGatt g,BluetoothGattCharacteristic c,int result){ + byte[] value=c.getValue()==null?null:c.getValue().clone(); + postBle(()->{if(g!=gatt||closed)return;disarm();if(result==0)receive(value);else say("Connected. Status could not be read yet.");}); + } + @Override public void onCharacteristicChanged(BluetoothGatt g,BluetoothGattCharacteristic c){ + byte[] value=c.getValue()==null?null:c.getValue().clone(); + postBle(()->{if(g==gatt&&!closed)receive(value);}); + } + @Override public void onCharacteristicWrite(BluetoothGatt g,BluetoothGattCharacteristic c,int result){postBle(()->{ + if(g!=gatt||closed||!sending)return; + disarm();if(result!=0){fail("A print packet was not accepted. Restart the printer before retrying.");return;} + index++; + if(index>rows.length){ + sending=false;awaiting=true;rows=null;progress=100; + say(started?"Printing…":"Sent. Waiting for the printer to report progress…"); + watchdog=()->{if(awaiting){awaiting=false;dirty=true;jobOutcome=PrintOutcome.STOPPED_UNCONFIRMED;say("Completion not confirmed. Check the paper result; do not resend automatically.");}}; + main.postDelayed(watchdog,90000); + schedulePoll(); + }else{ + progress=Math.min(99,Math.max(0,index-1)*100/rows.length);change(); + long token=session; + main.postDelayed(()->{if(token==session&&sending)writeNext();},20); + } + });} + }; + private void receive(byte[] value){ + int[] s=PrinterProtocol.decodeStatus(value);if(s==null)return; + battery=s[0];temperature=s[1];paper=s[2];printState=s[3]; + if(busy()&&(paper==1||PrinterProtocol.temperatureBlocksPrinting(temperature))){ + fail(PrinterProtocol.temperatureUnavailable(temperature)?"Print-head sensor unavailable. Stop using the printer, check the sensor, then restart before retrying.":paper==1?"Out of paper. Load paper, then restart the printer before retrying.":"Print head is hot. Let it cool; check the print before retrying.");return; + } + if(busy()&&(printState==1||printState==2)){started=true;if(awaiting)status="Printing…";} + PrintOutcome reported=PrintOutcome.fromStatus(awaiting,started,failedJob,paper,temperature,printState); + if(reported==PrintOutcome.STOPPED_UNCONFIRMED){ + awaiting=false;dirty=true;jobOutcome=reported; + if(watchdog!=null)main.removeCallbacks(watchdog); + if(poll!=null)main.removeCallbacks(poll); + status="Printer stopped. Check your paper. Completion is not confirmed; restart the printer before another job."; + } + else if(!busy()&&!dirty)status=PrinterProtocol.temperatureUnavailable(temperature)?"Print-head sensor unavailable. Check the sensor before printing.":paper==1?"Out of paper. Load a fresh roll.":temperature>=65?"Print head is hot. Give it a moment to cool.":"Ready for your next little idea."; + change(); + } + private void readStatus(){ + if(!ready||pending||sending||gatt==null||characteristic==null)return; + if((characteristic.getProperties()&BluetoothGattCharacteristic.PROPERTY_READ)==0)return; + arm("Status read");runBle(() -> { if(!gatt.readCharacteristic(characteristic))disarm(); }); + } + public void refresh(){if(!busy())readStatus();} + private void schedulePoll(){ + if(poll!=null)main.removeCallbacks(poll); + poll=()->{if(awaiting&&ready){readStatus();schedulePoll();}}; + main.postDelayed(poll,3000); + } + public String canPrint(){ + if(!ready)return "Connect your printer first."; + if(dirty)return "The previous job was interrupted or unconfirmed. Restart the printer to clear its buffer, then confirm that restart in Your device."; + if(busy())return "A print is already in progress."; + if(pending)return "Synchronizing device status. Wait a moment, then try again."; + if(paper<0||temperature<0||battery<0)return "Waiting for real device status. Refresh status or wait for the next notification."; + if(paper==1)return "Out of paper. Load paper before printing."; + if(PrinterProtocol.temperatureUnavailable(temperature))return "Print-head sensor unavailable. Check the sensor before printing."; + if(temperature>=65)return "The print head is hot. Let it cool before printing."; + if(printState==1||printState==2)return "The printer is already working. Wait for it to finish."; + return null; + } + public void print(byte[][] data,int level){ + String error=canPrint();if(error!=null){listener.message(error);return;} + if(data==null||data.length==0||data.length>PrinterProtocol.MAX_ROWS){listener.message("This paper is too long. Shorten it before printing.");return;} + for(byte[] row:data)if(row.length!=48)throw new IllegalArgumentException("Rows must be exactly 48 bytes"); + rows=data;density=level;index=-1;progress=0;started=false;failedJob=false;jobOutcome=PrintOutcome.IN_PROGRESS;sending=true;awaiting=false; + session++;say("Sending to printer…");writeNext(); + } + private void writeNext(){ + if(!sending||gatt==null||characteristic==null)return; + byte[] packet=index<0?PrinterProtocol.density(density):index { if(!gatt.writeCharacteristic(characteristic))fail("Could not send a print packet. Restart the printer before retrying."); }); + } + public void stopSending(){if(busy())fail("Transfer stopped. A started print may continue; there is no remote stop command. Restart the printer before retrying.");} + public void acknowledgeRestart(){ + if(busy())return; + dirty=false;started=false;failedJob=false;jobOutcome=PrintOutcome.RESTART_CONFIRMED;say("Printer restart confirmed. Refreshing status…");readStatus(); + } + private void fail(String message){ + if(busy()){dirty=true;failedJob=true;jobOutcome=PrintOutcome.FAILED;} + session++;sending=false;awaiting=false;rows=null; + if(watchdog!=null)main.removeCallbacks(watchdog);if(poll!=null)main.removeCallbacks(poll); + disarm();releaseGatt();say(message); + } + private void releaseGatt(){ + BluetoothGatt old=gatt;gatt=null;characteristic=null;ready=false;connecting=false;mtu=23; + battery=-1;temperature=-1;paper=-1;printState=-1; + if(old!=null){ + try{old.disconnect();}catch(SecurityException|IllegalStateException ignored){} + try{old.close();}catch(SecurityException|IllegalStateException ignored){} + } + } + public void disconnect(){ + if(busy()){dirty=true;failedJob=true;jobOutcome=PrintOutcome.FAILED;} + session++;sending=false;awaiting=false;rows=null;disarm(); + if(watchdog!=null)main.removeCallbacks(watchdog);if(poll!=null)main.removeCallbacks(poll); + releaseGatt();say("Not connected"); + } + public void close(){stopScan();disconnect();closed=true;main.removeCallbacksAndMessages(null);} +} diff --git a/software/android/app/src/main/java/studio/foli/android/FoliIcon.java b/software/android/app/src/main/java/studio/foli/android/FoliIcon.java new file mode 100644 index 0000000..6c41647 --- /dev/null +++ b/software/android/app/src/main/java/studio/foli/android/FoliIcon.java @@ -0,0 +1,35 @@ +package studio.foli.android; + +import android.content.Context; +import android.graphics.*; +import android.view.View; + +/** Original small outline icons; interactive parents supply accessible labels. */ +final class FoliIcon extends View { + final String kind;final int color; + private final Paint p=new Paint(3); + private final Path path=new Path(); + public FoliIcon(Context c){this(c,"note",MainActivity.INK);} + FoliIcon(Context c,String kind,int color){super(c);this.kind=kind;this.color=color;setImportantForAccessibility(IMPORTANT_FOR_ACCESSIBILITY_NO);} + @Override protected void onDraw(Canvas c){super.onDraw(c);c.save();c.scale(getWidth()/24f,getHeight()/24f); + p.setColor(color);p.setStyle(Paint.Style.STROKE);p.setStrokeWidth(1.6f);p.setStrokeCap(Paint.Cap.ROUND);p.setStrokeJoin(Paint.Join.ROUND); + path.reset(); + switch(kind){ + case "home":path.moveTo(3,11);path.lineTo(12,3);path.lineTo(21,11);path.lineTo(21,21);path.lineTo(15,21);path.lineTo(15,15);path.lineTo(9,15);path.lineTo(9,21);path.lineTo(3,21);path.close();break; + case "photo":c.drawRect(3,4,21,20,p);c.drawCircle(16,8,1,p);path.moveTo(3,17);path.lineTo(9,11);path.lineTo(14,16);path.lineTo(17,13);path.lineTo(21,17);break; + case "grid":for(int i=0;i<2;i++)for(int j=0;j<2;j++)c.drawRoundRect(3+i*11,3+j*11,10+i*11,10+j*11,1,1,p);break; + case "printer":c.drawRoundRect(3,8,21,17,2,2,p);c.drawRect(6,3,18,8,p);c.drawRect(6,13,18,22,p);c.drawPoint(17,11,p);break; + case "back":path.moveTo(15,5);path.lineTo(8,12);path.lineTo(15,19);break; + case "undo":path.moveTo(8,5);path.lineTo(3,10);path.lineTo(8,15);path.moveTo(3,10);path.lineTo(14,10);path.cubicTo(23,10,23,22,13,21);break; + case "arrow":path.moveTo(4,12);path.lineTo(20,12);path.moveTo(14,6);path.lineTo(20,12);path.lineTo(14,18);break; + case "battery":c.drawRect(2,6,20,18,p);c.drawLine(22,10,22,14,p);c.drawLine(5,10,14,10,p);c.drawLine(5,14,14,14,p);break; + case "heart":path.moveTo(12,20);path.cubicTo(-4,10,5,-2,12,6);path.cubicTo(19,-2,28,10,12,20);break; + case "rotate":c.drawArc(4,4,21,21,220,300,false,p);path.moveTo(3,2);path.lineTo(3,8);path.lineTo(9,8);break; + case "style":for(int x=5;x<=19;x+=7)c.drawLine(x,3,x,21,p);c.drawLine(2,8,8,8,p);c.drawLine(9,16,15,16,p);c.drawLine(16,10,22,10,p);break; + case "bluetooth":path.moveTo(7,6);path.lineTo(17,17);path.lineTo(12,22);path.lineTo(12,2);path.lineTo(17,7);path.lineTo(7,18);break; + case "mark":path.moveTo(7,4);path.lineTo(17,4);path.quadTo(21,4,21,8);path.lineTo(21,18);path.quadTo(21,22,17,22);path.lineTo(6,22);path.lineTo(6,10);path.quadTo(6,7,10,7);path.lineTo(16,7);path.moveTo(10,12);path.lineTo(17,12);path.moveTo(10,17);path.lineTo(15,17);path.moveTo(6,22);path.quadTo(1,22,1,18);path.lineTo(6,18);break; + default:c.drawRect(5,3,19,22,p);c.drawLine(9,9,16,9,p);c.drawLine(9,14,16,14,p);c.drawLine(9,18,14,18,p); + } + c.drawPath(path,p);c.restore(); + } +} diff --git a/software/android/app/src/main/java/studio/foli/android/MainActivity.java b/software/android/app/src/main/java/studio/foli/android/MainActivity.java new file mode 100644 index 0000000..d19bb54 --- /dev/null +++ b/software/android/app/src/main/java/studio/foli/android/MainActivity.java @@ -0,0 +1,540 @@ +package studio.foli.android; + +import android.Manifest; +import android.app.*; +import android.bluetooth.*; +import android.content.*; +import android.content.pm.PackageManager; +import android.content.res.ColorStateList; +import android.graphics.*; +import android.graphics.drawable.GradientDrawable; +import android.graphics.drawable.RippleDrawable; +import android.graphics.drawable.ColorDrawable; +import android.location.LocationManager; +import androidx.exifinterface.media.ExifInterface; +import android.net.Uri; +import android.os.*; +import android.provider.Settings; +import android.text.InputType; +import android.text.Editable; +import android.text.TextWatcher; +import android.view.animation.DecelerateInterpolator; +import android.view.*; +import android.widget.*; +import java.io.*; +import java.util.*; +import java.util.concurrent.*; + +/** Native Android UI. No web runtime, network service, account or third-party SDK. */ +public final class MainActivity extends Activity implements BlePrinter.Listener { + static final int INK=Color.rgb(33,60,53), GREEN=Color.rgb(48,91,73), MUTED=Color.rgb(94,111,102); + static final int CANVAS=Color.rgb(252,252,248), MINT=Color.rgb(201,232,215), CARD=Color.rgb(239,242,233); + private static final int PICK_PHOTO=10, PERMISSIONS=11, ENABLE_BT=12; + private BlePrinter printer; + private final ExecutorService worker=Executors.newSingleThreadExecutor(); + private final Handler ui=new Handler(Looper.getMainLooper()); + private LinearLayout root, content, nav; + private FrameLayout pageHost, headerHost, footerHost, noticeHost; + private ScrollView pageScroll; + private String renderedScreen="", editorOrigin="home", templateFilter="All"; + private final Map scrollPositions=new HashMap<>(); + private ImageView paperImage; + private TextView paperInfo, editorTitle, footerInfo, footerAction, undoAction, previewStatus; + private TextView batteryValue,paperValue,temperatureValue,deviceCopy; + private final ArrayList densityChoices=new ArrayList<>(); + private int paperStyle, paperAlignment; + private final ExecutorService thumbWorker=Executors.newFixedThreadPool(2); + private final Map templateThumbnails=new HashMap<>(); + private final Map> thumbnailWaiters=new HashMap<>(); + private final Set thumbnailsInFlight=new HashSet<>(); + private final Set favorites=new HashSet<>(); + private final ArrayDeque undoHistory=new ArrayDeque<>(); + private Runnable pendingRender; + private long latestRenderMs; + private Dialog activePanel; + private ImageView sheetPreview; + private TextView stateText, progressText, chip; + private ProgressBar progressBar; + private AlertDialog devicesDialog; + private ArrayAdapter devicesAdapter; + private TextView scanStatus; + private ArrayList scanDevices=new ArrayList<>(); + private String screen="home", title="Today's three.", body="Finish something good\nTake a proper break\nMake time to create"; + private boolean photoMode=false, checklist=true, dither=true, rendering; + private volatile boolean destroyed; + private Bitmap photo; + private PaperRenderer.Paper paper; + private int crop=0, turns=0, brightness=0, density=2, typeSize=22; + private volatile int renderVersion; + private String renderError=""; + private boolean uncertainPrint; + private String deviceSnapshot=""; + + @Override public void onCreate(Bundle state){ + super.onCreate(state); + printer=new BlePrinter(this,this); + android.content.SharedPreferences prefs=getPreferences(MODE_PRIVATE); + title=prefs.getString("title",title);body=prefs.getString("body",body); + checklist=prefs.getBoolean("checklist",true);photoMode=prefs.getBoolean("photoMode",false); + dither=prefs.getBoolean("dither",true);brightness=prefs.getInt("brightness",0); + density=prefs.getInt("density",2);typeSize=prefs.getInt("typeSize",22);crop=prefs.getInt("crop",0);turns=prefs.getInt("turns",0); + paperStyle=prefs.getInt("paperStyle",0);paperAlignment=prefs.getInt("paperAlignment",0); + favorites.addAll(prefs.getStringSet("favorites",Collections.emptySet())); + printer.dirty=prefs.getBoolean("uncertainPrint",false);uncertainPrint=printer.dirty; + if(photoMode)photo=BitmapFactory.decodeFile(new File(getFilesDir(),"photo.png").getPath()); + if(photo==null)photoMode=false; + if(state!=null){screen=state.getString("screen","home");editorOrigin=state.getString("editorOrigin","home");templateFilter=state.getString("filter","All");for(String route:new String[]{"home","templates","editor","device"})scrollPositions.put(route,state.getInt("scroll_"+route,0));} + show();renderPaper();for(TemplateCatalog.Template t:TemplateCatalog.ALL)ensureThumbnail(t); + } + int dp(float n){return Math.round(n*getResources().getDisplayMetrics().density);} + private LinearLayout col(){LinearLayout l=new LinearLayout(this);l.setOrientation(LinearLayout.VERTICAL);return l;} + private LinearLayout row(){LinearLayout l=new LinearLayout(this);l.setOrientation(LinearLayout.HORIZONTAL);l.setGravity(Gravity.CENTER_VERTICAL);return l;} + private GradientDrawable bg(int color,int radius){GradientDrawable g=new GradientDrawable();g.setColor(color);g.setCornerRadius(dp(radius));return g;} + private void pad(View v,int a,int b,int c,int d){v.setPadding(dp(a),dp(b),dp(c),dp(d));} + private void gap(LinearLayout l,int size){View v=new View(this);l.addView(v,new LinearLayout.LayoutParams(1,dp(size)));} + private TextView label(String value,float size,int color,boolean bold){ + TextView t=new TextView(this);t.setText(value);t.setTextSize(size);t.setTextColor(color); + t.setTypeface(Typeface.create("sans-serif",bold?Typeface.BOLD:Typeface.NORMAL));t.setIncludeFontPadding(false);return t; + } + private TextView heading(String value,float size){return label(value,size,INK,true);} + private boolean motion(){return Build.VERSION.SDK_INT<26||android.animation.ValueAnimator.areAnimatorsEnabled();} + private void feedback(View view,Runnable action){ + view.setBackground(new RippleDrawable(ColorStateList.valueOf(0x20305B49),view.getBackground(),bg(Color.WHITE,20))); + view.setFocusable(true);view.setOnClickListener(v->action.run()); + } + private TextView pill(String value,boolean selected,Runnable action){ + TextView t=label(value,12,selected?Color.WHITE:GREEN,selected);t.setGravity(Gravity.CENTER);pad(t,17,12,17,12);t.setMinHeight(dp(48));t.setBackground(bg(selected?INK:CARD,24));t.setSelected(selected);feedback(t,action);return t; + } + private void paragraph(LinearLayout l,String value){TextView t=label(value,14,MUTED,false);t.setLineSpacing(dp(4),1);l.addView(t);} + private TextView button(String value,boolean primary,Runnable action){ + TextView b=label(value,14,primary?Color.WHITE:GREEN,true);b.setGravity(Gravity.CENTER);pad(b,16,13,16,13); + b.setMinHeight(dp(48));b.setBackground(bg(primary?INK:MINT,24));feedback(b,action);b.setClickable(true);b.setFocusable(true); + b.setContentDescription(value);return b; + } + private void fullButton(LinearLayout l,String value,boolean primary,Runnable action){l.addView(button(value,primary,action),new LinearLayout.LayoutParams(-1,-2));} + private void iconButton(LinearLayout parent,String icon,String name,Runnable action){ + LinearLayout box=col();box.setGravity(Gravity.CENTER);pad(box,5,8,5,8);box.setMinimumHeight(dp(58)); + box.addView(new FoliIcon(this,icon,GREEN),new LinearLayout.LayoutParams(dp(23),dp(23)));gap(box,7); + TextView caption=label(name,11,MUTED,false);caption.setGravity(Gravity.CENTER);box.addView(caption);box.setContentDescription(name);box.setImportantForAccessibility(View.IMPORTANT_FOR_ACCESSIBILITY_YES); + feedback(box,()->{if(printer.busy()){message("Let this print finish before editing the next paper.");return;}action.run();});parent.addView(box,new LinearLayout.LayoutParams(0,-2,1)); + } + private void card(LinearLayout parent,View child,int color){ + LinearLayout box=col();pad(box,18,18,18,18);box.setBackground(bg(color,20));box.addView(child);parent.addView(box,new LinearLayout.LayoutParams(-1,-2)); + } + private String connectionLabel(){return printer.ready?"FOLI connected":printer.connecting?"Connecting…":"Connect FOLI";} + private void show(){ + if(destroyed)return; + boolean routeChanged=!screen.equals(renderedScreen); + if(pageScroll!=null)scrollPositions.put(renderedScreen,pageScroll.getScrollY()); + stateText=null;progressText=null;progressBar=null;chip=null; + paperImage=null;paperInfo=null;previewStatus=null;footerInfo=null;footerAction=null;editorTitle=null;undoAction=null; + batteryValue=paperValue=temperatureValue=deviceCopy=null;densityChoices.clear(); + if(root==null){ + root=col();root.setBackgroundColor(CANVAS);root.setFitsSystemWindows(true); + headerHost=new FrameLayout(this);pageHost=new FrameLayout(this);noticeHost=new FrameLayout(this);footerHost=new FrameLayout(this);nav=row(); + root.addView(headerHost,new LinearLayout.LayoutParams(-1,-2));root.addView(pageHost,new LinearLayout.LayoutParams(-1,0,1)); + root.addView(footerHost,new LinearLayout.LayoutParams(-1,-2));root.addView(nav,new LinearLayout.LayoutParams(-1,-2));setContentView(root); + } + headerHost.removeAllViews();footerHost.removeAllViews();noticeHost.removeAllViews(); + pageScroll=new ScrollView(this);pageScroll.setFillViewport(true);pageScroll.setClipToPadding(false);pageScroll.setOverScrollMode(View.OVER_SCROLL_IF_CONTENT_SCROLLS); + content=col();pad(content,24,screen.equals("editor")?8:20,24,24);pageScroll.addView(content,new ScrollView.LayoutParams(-1,-2)); + switch(screen){case "editor":editor();break;case "templates":templates();break;case "device":device();break;default:home();} + pageHost.removeAllViews();pageHost.addView(pageScroll,new FrameLayout.LayoutParams(-1,-1));FrameLayout.LayoutParams noticePosition=new FrameLayout.LayoutParams(-1,-2,Gravity.BOTTOM);pageHost.addView(noticeHost,noticePosition); + nav.removeAllViews();nav.setBackgroundColor(CANVAS);pad(nav,8,3,8,3);nav.setVisibility(screen.equals("editor")?View.GONE:View.VISIBLE); + navItem("home","Create","home");navItem("grid","Templates","templates");navItem("printer","Device","device"); + int restore=scrollPositions.getOrDefault(screen,0);pageScroll.post(()->{if(pageScroll!=null)pageScroll.scrollTo(0,restore);}); + if(routeChanged&&motion()){pageScroll.setAlpha(0);pageScroll.setTranslationY(dp(8));pageScroll.animate().alpha(1).translationY(0).setDuration(180).setInterpolator(new DecelerateInterpolator()).start();} + renderedScreen=screen; + updateStatus(); + } + private void navItem(String ic,String text,String route){ + boolean selected=screen.equals(route)||("home".equals(route)&&"editor".equals(screen)); + LinearLayout box=col();box.setGravity(Gravity.CENTER);pad(box,8,8,8,8);box.setMinimumHeight(dp(60)); + box.addView(new FoliIcon(this,ic,selected?GREEN:MUTED),new LinearLayout.LayoutParams(dp(22),dp(22)));gap(box,6); + TextView caption=label(text,11,selected?GREEN:MUTED,selected);caption.setGravity(Gravity.CENTER);box.addView(caption);box.setContentDescription(text);box.setSelected(selected);box.setFocusable(true); + feedback(box,()->{if(!screen.equals(route)){saveDraft();screen=route;show();}});nav.addView(box,new LinearLayout.LayoutParams(0,-2,1)); + } + private void top(String name){ + LinearLayout top=row();top.addView(heading(name,name.equals("FOLI")?28:24),new LinearLayout.LayoutParams(0,-2,1)); + chip=label(connectionLabel(),10,GREEN,true);pad(chip,12,10,12,10);chip.setMinHeight(dp(48));chip.setGravity(Gravity.CENTER);chip.setBackground(bg(CARD,20)); + feedback(chip,()->{screen="device";show();});top.addView(chip);content.addView(top);gap(content,24); + } + private void home(){ + top("FOLI");TextView h=heading("Make a little\nroom for joy.",35);h.setLineSpacing(dp(2),1);content.addView(h);gap(content,12); + paragraph(content,"A thought. A list. A little surprise.");gap(content,25); + LinearLayout hero=col();hero.addView(label("START WITH SOMETHING SIMPLE",10,GREEN,true));gap(hero,18); + LinearLayout heroRow=row();LinearLayout words=col();words.addView(heading("Today, on paper.",22));gap(words,17); + words.addView(button("Make a note →",true,()->{photoMode=false;screen="editor";renderPaper();show();})); + heroRow.addView(words,new LinearLayout.LayoutParams(0,-2,1)); + LinearLayout tiny=col();pad(tiny,10,13,10,13);tiny.setBackground(bg(Color.rgb(255,254,248),3));tiny.setRotation(7); + tiny.addView(label("TODAY",9,INK,true));gap(tiny,10);tiny.addView(label("□ A little focus\n\n□ A fresh idea\n\n□ Time for you",9,MUTED,false)); + LinearLayout.LayoutParams tp=new LinearLayout.LayoutParams(dp(98),dp(126));tp.setMargins(dp(10),0,0,0);heroRow.addView(tiny,tp);hero.addView(heroRow);card(content,hero,MINT);gap(content,18); + LinearLayout shortcuts=row();shortcut(shortcuts,"note","Notes",Color.rgb(241,238,229),()->{photoMode=false;screen="editor";renderPaper();show();}); + shortcut(shortcuts,"photo","Photos",Color.rgb(231,239,244),this::pickPhoto); + shortcut(shortcuts,"grid","Templates",Color.rgb(246,229,222),()->{screen="templates";show();});content.addView(shortcuts);gap(content,28); + content.addView(heading("A little inspiration",20));gap(content,12); + LinearLayout inspiration=row();inspiration.addView(new FoliIcon(this,"heart",GREEN),new LinearLayout.LayoutParams(dp(27),dp(27))); + LinearLayout copy=col();pad(copy,16,0,0,0);copy.addView(heading("Leave a little kindness.",15));gap(copy,7);copy.addView(label("A note can make someone's day.",12,MUTED,false));inspiration.addView(copy);card(content,inspiration,CARD); + View parent=content.getChildAt(content.getChildCount()-1);parent.setOnClickListener(v->useTemplate(2));parent.setFocusable(true);parent.setContentDescription("Create a kindness note"); + gap(content,24);TextView resume=label("Continue your saved paper →",13,GREEN,true);pad(resume,0,12,0,12);resume.setMinHeight(dp(48));resume.setOnClickListener(v->{screen="editor";show();});resume.setFocusable(true);content.addView(resume); + } + private void shortcut(LinearLayout parent,String ic,String name,int color,Runnable action){ + LinearLayout box=col();pad(box,14,14,10,14);box.setBackground(bg(color,17)); + box.addView(new FoliIcon(this,ic,INK),new LinearLayout.LayoutParams(dp(25),dp(25)));gap(box,17);box.addView(label(name,12,INK,true)); + LinearLayout.LayoutParams p=new LinearLayout.LayoutParams(0,dp(98),1);if(parent.getChildCount()>0)p.setMargins(dp(10),0,0,0);parent.addView(box,p); + box.setOnClickListener(v->action.run());box.setFocusable(true);box.setContentDescription(name); + } + private void templates(){ + top("Templates");content.addView(heading("A little inspiration.\nMade yours.",29));gap(content,10);paragraph(content,"Pick a paper. Make it personal.");gap(content,18); + HorizontalScrollView filters=new HorizontalScrollView(this);filters.setHorizontalScrollBarEnabled(false);LinearLayout chips=row();final TextView[] activeFilter={null}; + for(String name:new String[]{"All","Focus","Notes","Kindness","Lists","Saved"}){ + TextView filter=pill(name,templateFilter.equals(name),()->{templateFilter=name;scrollPositions.put("templates",0);if(pageScroll!=null)pageScroll.scrollTo(0,0);show();}); + if(templateFilter.equals(name))activeFilter[0]=filter; + LinearLayout.LayoutParams fp=new LinearLayout.LayoutParams(-2,-2);fp.setMargins(0,0,dp(8),0);chips.addView(filter,fp); + } + filters.addView(chips);content.addView(filters);filters.post(()->{if(activeFilter[0]!=null)filters.scrollTo(Math.max(0,activeFilter[0].getLeft()-dp(16)),0);});gap(content,20); + ArrayList selected=new ArrayList<>(); + for(TemplateCatalog.Template t:TemplateCatalog.ALL)if(templateFilter.equals("All")||templateFilter.equals(t.category)||(templateFilter.equals("Saved")&&favorites.contains(""+t.id)))selected.add(t); + if(selected.isEmpty()){gap(content,35);content.addView(heading("Your favorites live here.",22));gap(content,10);paragraph(content,"Save a template with the heart button to keep it close.");return;} + content.addView(label(selected.size()+(selected.size()==1?" LITTLE STARTER":" LITTLE STARTERS"),10,MUTED,true));gap(content,12); + for(int index=0;index=selected.size()){pair.addView(new View(this),cp);continue;} + TemplateCatalog.Template t=selected.get(index+side);LinearLayout tile=col();tile.setBackground(bg(Color.WHITE,20)); + LinearLayout art=col();art.setGravity(Gravity.CENTER);pad(art,13,16,13,16);art.setBackground(bg(t.color,18)); + ImageView thumb=new ImageView(this);thumb.setScaleType(ImageView.ScaleType.FIT_CENTER);thumb.setContentDescription("Preview: "+t.name);art.addView(thumb,new LinearLayout.LayoutParams(-1,dp(142)));templateThumb(t,thumb); + tile.addView(art);LinearLayout words=col();pad(words,12,12,12,10);TextView name=heading(t.name,15);name.setMinHeight(dp(40));words.addView(name); + LinearLayout meta=row();meta.addView(label(t.category,11,MUTED,false),new LinearLayout.LayoutParams(0,-2,1)); + TextView heart=label(favorites.contains(""+t.id)?"♥":"♡",24,GREEN,false);heart.setGravity(Gravity.CENTER);heart.setMinHeight(dp(48));heart.setMinWidth(dp(48));heart.setContentDescription((favorites.contains(""+t.id)?"Unsave ":"Save ")+t.name); + feedback(heart,()->{if(!favorites.add(""+t.id))favorites.remove(""+t.id);saveDraft();if(templateFilter.equals("Saved"))show();else{heart.setText(favorites.contains(""+t.id)?"♥":"♡");heart.setContentDescription((favorites.contains(""+t.id)?"Unsave ":"Save ")+t.name);}});meta.addView(heart);words.addView(meta);tile.addView(words); + tile.setContentDescription("Preview "+t.name);feedback(tile,()->previewTemplate(t));pair.addView(tile,cp); + } + content.addView(pair);gap(content,14); + } + } + private void templateThumb(TemplateCatalog.Template t,ImageView target){ + Bitmap cached=templateThumbnails.get(t.id);if(cached!=null){target.setImageBitmap(cached);return;} + target.setTag(t.id);target.setImageResource(R.drawable.template_placeholder);target.setContentDescription("Preparing preview: "+t.name); + ArrayList waiters=thumbnailWaiters.get(t.id);if(waiters==null){waiters=new ArrayList<>();thumbnailWaiters.put(t.id,waiters);}waiters.add(target);ensureThumbnail(t); + } + private void ensureThumbnail(TemplateCatalog.Template t){ + if(templateThumbnails.containsKey(t.id)||!thumbnailsInFlight.add(t.id))return; + thumbWorker.execute(()->{try{ + Bitmap raster=PaperRenderer.note(t.name,t.body,20,t.checklist,t.style,t.style==2?1:0); + Bitmap image=PaperRenderer.finish(raster,false,0).bitmap; + ui.post(()->{if(destroyed)return;thumbnailsInFlight.remove(t.id);templateThumbnails.put(t.id,image);ArrayList waiting=thumbnailWaiters.remove(t.id);if(waiting!=null)for(ImageView target:waiting)if(Integer.valueOf(t.id).equals(target.getTag())){target.setImageBitmap(image);target.setContentDescription("Preview: "+t.name);if(motion()&&target.isAttachedToWindow()){target.setAlpha(0);target.animate().alpha(1).setDuration(160).start();}}}); + }catch(RuntimeException|OutOfMemoryError ignored){ui.post(()->{if(!destroyed){thumbnailsInFlight.remove(t.id);thumbnailWaiters.remove(t.id);}});}}); + } + private Dialog sheet(String name,String subtitle,LinearLayout bodyView){ + Dialog dialog=new Dialog(this);activePanel=dialog;dialog.requestWindowFeature(Window.FEATURE_NO_TITLE); + LinearLayout shell=col();pad(shell,24,10,24,20);shell.setBackground(bg(CANVAS,26)); + View handle=new View(this);handle.setBackground(bg(0xFFCDD5CB,3));LinearLayout.LayoutParams hp=new LinearLayout.LayoutParams(dp(38),dp(4));hp.gravity=Gravity.CENTER;hp.bottomMargin=dp(20);shell.addView(handle,hp); + shell.addView(heading(name,23));if(!subtitle.isEmpty()){gap(shell,8);paragraph(shell,subtitle);}gap(shell,20); + ScrollView sc=new ScrollView(this);sc.setFillViewport(false);sc.addView(bodyView);shell.addView(sc,new LinearLayout.LayoutParams(-1,0,1)); + dialog.setContentView(shell);Window w=dialog.getWindow(); + if(w!=null){w.setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));w.setDimAmount(.24f);w.addFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND);w.setGravity(Gravity.BOTTOM);w.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE);} + dialog.setOnShowListener(d->{if(w!=null)w.setLayout(-1,(int)(getResources().getDisplayMetrics().heightPixels*.78f));if(motion()){shell.setTranslationY(dp(32));shell.setAlpha(.6f);shell.animate().translationY(0).alpha(1).setDuration(190).setInterpolator(new DecelerateInterpolator()).start();}}); + return dialog; + } + private void previewTemplate(TemplateCatalog.Template t){ + LinearLayout panel=col();LinearLayout art=col();art.setGravity(Gravity.CENTER);pad(art,20,18,20,18);art.setBackground(bg(t.color,20)); + ImageView preview=new ImageView(this);preview.setScaleType(ImageView.ScaleType.FIT_CENTER);preview.setContentDescription("Template preview: "+t.name);art.addView(preview,new LinearLayout.LayoutParams(-1,dp(210)));templateThumb(t,preview);panel.addView(art);gap(panel,18); + paragraph(panel,"Fully editable · Black & white · Saved on your phone");gap(panel,20); + Dialog dialog=sheet(t.name,t.description,panel);LinearLayout actions=fixedSheetActions(panel); + TextView save=button(favorites.contains(""+t.id)?"Saved ♥":"Save ♡",false,()->{if(!favorites.add(""+t.id))favorites.remove(""+t.id);saveDraft();dialog.dismiss();show();});actions.addView(save,new LinearLayout.LayoutParams(-2,dp(50))); + LinearLayout.LayoutParams use=new LinearLayout.LayoutParams(0,dp(50),1);use.setMargins(dp(10),0,0,0);actions.addView(button("Make this yours",true,()->{dialog.dismiss();useTemplate(t.id);}),use);dialog.show(); + } + private void useTemplate(int i){ + if(printer.busy()){message("You can edit after the current print finishes.");return;} + remember();TemplateCatalog.Template t=TemplateCatalog.get(i); + photoMode=false;brightness=0;typeSize=22;checklist=t.checklist;paperStyle=t.style;paperAlignment=t.style==2?1:0;title=t.name;body=t.body; + editorOrigin=screen.equals("templates")?"templates":"home";screen="editor";saveDraft();show();renderPaper();notice("Template applied",this::undo); + } + private void editor(){ + LinearLayout bar=row();pad(bar,16,8,16,8);TextView back=button("‹",false,()->{saveDraft();screen=editorOrigin;show();});back.setContentDescription("Back to "+editorOrigin);bar.addView(back,new LinearLayout.LayoutParams(dp(48),dp(48))); + editorTitle=heading(photoMode?"Your photo":"Your note",18);editorTitle.setGravity(Gravity.CENTER);bar.addView(editorTitle,new LinearLayout.LayoutParams(0,-2,1)); + undoAction=button("Undo",false,this::undo);undoAction.setContentDescription("Undo last edit");undoAction.setEnabled(!undoHistory.isEmpty());undoAction.setAlpha(undoHistory.isEmpty()?.4f:1);bar.addView(undoAction);headerHost.addView(bar); + LinearLayout preview=col();preview.setGravity(Gravity.CENTER);pad(preview,18,14,18,18);preview.setBackground(bg(Color.rgb(236,238,229),20)); + TextView eyebrow=label("YOUR PAPER · LIVE PREVIEW",10,MUTED,true);eyebrow.setGravity(Gravity.CENTER);preview.addView(eyebrow);gap(preview,15); + paperImage=new ImageView(this);paperImage.setScaleType(ImageView.ScaleType.FIT_CENTER);paperImage.setContentDescription("Actual monochrome print preview"); + int previewHeight=Math.max(176,Math.min(240,Math.round(getResources().getDisplayMetrics().heightPixels/getResources().getDisplayMetrics().density*.32f))); + preview.addView(paperImage,new LinearLayout.LayoutParams(-1,dp(previewHeight)));paperImage.setOnClickListener(v->largePreview());paperImage.setFocusable(true);gap(preview,10); + previewStatus=label("",12,GREEN,false);previewStatus.setGravity(Gravity.CENTER);preview.addView(previewStatus); + paperInfo=label("",10,MUTED,false);paperInfo.setGravity(Gravity.CENTER);gap(preview,8);preview.addView(paperInfo); + content.addView(preview,new LinearLayout.LayoutParams(-1,-2));gap(content,14); + LinearLayout tools=row(); + if(photoMode){iconButton(tools,"photo","Replace",this::pickPhoto);iconButton(tools,"grid","Crop",this::cropPhoto);iconButton(tools,"style","Style",this::stylePhoto);iconButton(tools,"rotate","Rotate",()->{remember();turns=(turns+1)%4;renderPaper();});} + else{iconButton(tools,"note","Text",this::editText);iconButton(tools,"grid","Layout",this::layoutNote);iconButton(tools,"style","Type size",this::fontSize);iconButton(tools,"heart","Templates",()->{screen="templates";show();});} + content.addView(tools);gap(content,14); + TextView tip=label(photoMode?"Tap the paper to see every detail.":"Tap the paper to zoom. All changes save automatically.",12,MUTED,false);tip.setGravity(Gravity.CENTER);content.addView(tip);gap(content,22); + LinearLayout densityRow=row();densityRow.addView(label("Print density",12,MUTED,false),new LinearLayout.LayoutParams(0,-2,1)); + String[] levels={"Light","Medium","Dark"}; + for(int i=1;i<=3;i++){final int level=i;TextView choice=label(levels[i-1],11,INK,i==density);pad(choice,10,13,10,13);choice.setMinHeight(dp(48));choice.setGravity(Gravity.CENTER);choice.setBackground(bg(i==density?MINT:CARD,22));feedback(choice,()->{if(printer.busy()){message("Density is fixed for the current print.");return;}if(density==level)return;remember();density=level;saveDraft();updateDensity();});choice.setSelected(i==density);densityChoices.add(choice); + LinearLayout.LayoutParams cp=new LinearLayout.LayoutParams(-2,-2);cp.setMargins(dp(5),0,0,0);densityRow.addView(choice,cp);} + content.addView(densityRow);gap(content,18);jobPanel(content); + LinearLayout footer=col();pad(footer,24,12,24,14);footer.setBackground(bg(CANVAS,0)); + footerInfo=label("",11,MUTED,false);footerInfo.setGravity(Gravity.CENTER);footer.addView(footerInfo);gap(footer,9); + footerAction=button("",true,this::sendPrint);footer.addView(footerAction,new LinearLayout.LayoutParams(-1,dp(50)));footerHost.addView(footer); + updatePreview(); + } + private void updateDensity(){ + for(int i=0;i=20)undoHistory.removeFirst();undoHistory.addLast(new DraftState());updateDensity();} + private void undo(){ + if(printer.busy()){message("Let this print finish before changing the paper.");return;} + if(undoHistory.isEmpty()){toast("You're at the beginning.");return;} + boolean previousMode=photoMode;undoHistory.removeLast().restore();saveDraft(); + if(previousMode!=photoMode&&screen.equals("editor"))show();renderPaper();notice("Previous edit restored.",null); + } + private void notice(String value,Runnable action){ + noticeHost.removeAllViews();LinearLayout bar=row();pad(bar,18,10,12,10);bar.setBackground(bg(INK,14)); + TextView copy=label(value,12,Color.WHITE,false);bar.addView(copy,new LinearLayout.LayoutParams(0,-2,1)); + if(action!=null){TextView undo=label("Undo",13,MINT,true);pad(undo,14,12,10,12);undo.setMinHeight(dp(48));feedback(undo,action);bar.addView(undo);} + FrameLayout.LayoutParams bp=new FrameLayout.LayoutParams(-1,-2);bp.setMargins(dp(16),dp(3),dp(16),dp(5));noticeHost.addView(bar,bp); + ui.postDelayed(()->{if(bar.getParent()==noticeHost)noticeHost.removeView(bar);},4000); + } + private void largePreview(){ + if(paper==null)return;Dialog dialog=new Dialog(this,android.R.style.Theme_Material_Light_NoActionBar);activePanel=dialog;LinearLayout layout=col();layout.setBackgroundColor(CARD); + LinearLayout bar=row();pad(bar,18,12,18,12);bar.addView(heading("Your paper, up close.",18),new LinearLayout.LayoutParams(0,-2,1));bar.addView(button("Done",false,dialog::dismiss));layout.addView(bar); + ZoomPaperView zoom=new ZoomPaperView(this,paper.bitmap);layout.addView(zoom,new LinearLayout.LayoutParams(-1,0,1)); + TextView hint=label("Pinch to zoom · Drag to explore · Double-tap to reset",12,MUTED,false);hint.setGravity(Gravity.CENTER);pad(hint,20,12,20,24);layout.addView(hint);dialog.setContentView(layout);dialog.show(); + } + private void jobPanel(LinearLayout parent){ + stateText=label(printer.status,13,MUTED,false);stateText.setLineSpacing(dp(3),1);stateText.setAccessibilityLiveRegion(View.ACCESSIBILITY_LIVE_REGION_POLITE);parent.addView(stateText); + progressBar=new ProgressBar(this,null,android.R.attr.progressBarStyleHorizontal);progressBar.setProgressTintList(ColorStateList.valueOf(GREEN));parent.addView(progressBar,new LinearLayout.LayoutParams(-1,dp(8))); + progressText=label("",11,MUTED,false);parent.addView(progressText);gap(parent,8); + TextView help=label("Printing help →",12,GREEN,true);pad(help,0,12,0,12);help.setMinHeight(dp(48));help.setOnClickListener(v->help());help.setFocusable(true);parent.addView(help); + } + private void editText(){ + DraftState before=new DraftState();LinearLayout fields=col(); + fields.addView(label("TITLE",10,MUTED,true));gap(fields,8); + EditText titleInput=new EditText(this);titleInput.setText(title);titleInput.setHint("A title for your note");titleInput.setSingleLine(true);titleInput.setTextSize(17);titleInput.setBackground(bg(CARD,12));pad(titleInput,14,12,14,12);titleInput.setFilters(new android.text.InputFilter[]{new android.text.InputFilter.LengthFilter(50)});fields.addView(titleInput);gap(fields,18); + fields.addView(label(checklist?"ONE ITEM PER LINE":"YOUR WORDS",10,MUTED,true));gap(fields,8); + EditText contentInput=new EditText(this);contentInput.setText(body);contentInput.setHint("Make a little room for your words…");contentInput.setGravity(Gravity.TOP);contentInput.setMinLines(5);contentInput.setMaxLines(9); + contentInput.setTextSize(16);contentInput.setBackground(bg(CARD,12));pad(contentInput,14,12,14,12); + contentInput.setInputType(InputType.TYPE_CLASS_TEXT|InputType.TYPE_TEXT_FLAG_MULTI_LINE|InputType.TYPE_TEXT_FLAG_CAP_SENTENCES);contentInput.setFilters(new android.text.InputFilter[]{new android.text.InputFilter.LengthFilter(1600)});fields.addView(contentInput);gap(fields,10); + TextView count=label(body.length()+" / 1600 · Changes preview automatically",11,MUTED,false);fields.addView(count);gap(fields,20); + Dialog dialog=new Dialog(this,android.R.style.Theme_Material_Light_NoActionBar);activePanel=dialog; + LinearLayout composer=col();composer.setBackgroundColor(CANVAS);LinearLayout bar=row();pad(bar,16,8,16,8); + bar.addView(button("Cancel",false,()->{before.restore();dialog.dismiss();renderPaper();}));TextView caption=heading("Your words",18);caption.setGravity(Gravity.CENTER);bar.addView(caption,new LinearLayout.LayoutParams(0,-2,1)); + bar.addView(button("Done",true,()->{if(!before.isCurrent()){if(undoHistory.size()>=20)undoHistory.removeFirst();undoHistory.addLast(before);}dialog.dismiss();renderPaper();}));composer.addView(bar); + ScrollView scroll=new ScrollView(this);pad(fields,24,18,24,24);scroll.addView(fields);composer.addView(scroll,new LinearLayout.LayoutParams(-1,0,1));dialog.setContentView(composer); + Window window=dialog.getWindow();if(window!=null){window.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE|WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);window.setStatusBarColor(CANVAS);window.getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR);} + TextWatcher watcher=new TextWatcher(){public void beforeTextChanged(CharSequence s,int start,int n,int after){}public void onTextChanged(CharSequence s,int start,int before,int n){} + public void afterTextChanged(Editable e){title=titleInput.getText().toString().trim();if(title.isEmpty())title="A little note.";body=contentInput.getText().toString();count.setText(getString(R.string.editor_count,body.length()));queueRender();}}; + titleInput.addTextChangedListener(watcher);contentInput.addTextChangedListener(watcher); + dialog.setOnCancelListener(d->{before.restore();renderPaper();});dialog.show();if(window!=null)window.setLayout(-1,-1); + } + private void queueRender(){if(pendingRender!=null)ui.removeCallbacks(pendingRender);pendingRender=this::renderPaper;ui.postDelayed(pendingRender,180);} + private void options(LinearLayout parent,String name,String[] choices,int selected,java.util.function.IntConsumer choose){ + parent.addView(label(name,11,MUTED,true));gap(parent,9);LinearLayout row=row();ArrayList controls=new ArrayList<>(); + for(int i=0;i{choose.accept(value);for(int j=0;j0)op.setMargins(dp(7),0,0,0);row.addView(t,op);} + parent.addView(row);gap(parent,20); + } + private void panelPreview(LinearLayout parent){ + sheetPreview=new ImageView(this);sheetPreview.setScaleType(ImageView.ScaleType.FIT_CENTER);sheetPreview.setBackground(bg(CARD,16));pad(sheetPreview,16,12,16,12);sheetPreview.setContentDescription("Live paper preview");if(paper!=null)sheetPreview.setImageBitmap(paper.bitmap);parent.addView(sheetPreview,new LinearLayout.LayoutParams(-1,dp(150)));gap(parent,18); + } + private void sheetActions(LinearLayout fields,Dialog dialog,DraftState before){ + LinearLayout actions=fixedSheetActions(fields); + TextView cancel=button("Cancel",false,()->{before.restore();dialog.dismiss();sheetPreview=null;renderPaper();});actions.addView(cancel,new LinearLayout.LayoutParams(-2,dp(50))); + LinearLayout.LayoutParams keep=new LinearLayout.LayoutParams(0,dp(50),1);keep.setMargins(dp(10),0,0,0); + actions.addView(button("Keep changes",true,()->{if(!before.isCurrent()){if(undoHistory.size()>=20)undoHistory.removeFirst();undoHistory.addLast(before);}dialog.dismiss();sheetPreview=null;renderPaper();}),keep); + dialog.setOnCancelListener(d->{before.restore();sheetPreview=null;renderPaper();});dialog.setOnDismissListener(d->{sheetPreview=null;android.view.inputmethod.InputMethodManager im=(android.view.inputmethod.InputMethodManager)getSystemService(INPUT_METHOD_SERVICE);im.hideSoftInputFromWindow(root.getWindowToken(),0);}); + } + private LinearLayout fixedSheetActions(LinearLayout bodyView){ + LinearLayout shell=(LinearLayout)((View)bodyView.getParent()).getParent();LinearLayout actions=row();pad(actions,0,12,0,0);shell.addView(actions,new LinearLayout.LayoutParams(-1,-2));return actions; + } + private void layoutNote(){ + DraftState before=new DraftState();LinearLayout panel=col();panelPreview(panel); + options(panel,"PAPER STYLE",new String[]{"Clean","Journal","Postcard"},paperStyle,i->{paperStyle=i;renderPaper();}); + options(panel,"CONTENT",new String[]{"Checklist","Simple note"},checklist?0:1,i->{checklist=i==0;renderPaper();}); + options(panel,"ALIGNMENT",new String[]{"Left","Center"},paperAlignment,i->{paperAlignment=i;renderPaper();}); + paragraph(panel,"Checklist items stay left-aligned for easier reading.");gap(panel,17);Dialog dialog=sheet("Find your paper's style.","A few thoughtful choices. A very different feeling.",panel);sheetActions(panel,dialog,before);dialog.show(); + } + private void fontSize(){ + DraftState before=new DraftState();LinearLayout panel=col();panelPreview(panel);options(panel,"TYPE SIZE",new String[]{"Small","Medium","Large"},typeSize==16?0:typeSize==22?1:2,i->{typeSize=new int[]{16,22,28}[i];renderPaper();}); + paragraph(panel,"The preview shows the exact black & white output.");gap(panel,18);Dialog dialog=sheet("Room for your words.","Choose the size that feels right.",panel);sheetActions(panel,dialog,before);dialog.show(); + } + private void cropPhoto(){ + DraftState before=new DraftState();LinearLayout panel=col();panelPreview(panel);options(panel,"FRAMING",new String[]{"Full image","Square","Portrait"},crop,i->{crop=i;renderPaper();}); + paragraph(panel,"Square and portrait use a centered crop. Full image keeps the whole frame.");gap(panel,18);Dialog dialog=sheet("A fresh perspective.","Find the frame before it finds the paper.",panel);sheetActions(panel,dialog,before);dialog.show(); + } + private void stylePhoto(){ + DraftState before=new DraftState();LinearLayout fields=col();panelPreview(fields); + Switch dithering=new Switch(this);dithering.setText(R.string.fine_detail);dithering.setChecked(dither);dithering.setMinHeight(dp(48));fields.addView(dithering);gap(fields,16); + fields.addView(label("Brightness",14,INK,true));SeekBar seek=new SeekBar(this);seek.setMax(160);seek.setProgress(brightness+80);fields.addView(seek); + dithering.setOnCheckedChangeListener((v,checked)->{dither=checked;renderPaper();});seek.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener(){public void onStartTrackingTouch(SeekBar s){}public void onStopTrackingTouch(SeekBar s){renderPaper();}public void onProgressChanged(SeekBar s,int progress,boolean fromUser){if(fromUser){brightness=progress-80;queueRender();}}}); + gap(fields,18);Dialog dialog=sheet("Find your black & white.","Keep the detail. Set the mood.",fields);sheetActions(fields,dialog,before);dialog.show(); + } + private void pickPhoto(){ + if(printer.busy()){message("Finish the current print before replacing your image.");return;} + Intent intent=new Intent(Intent.ACTION_OPEN_DOCUMENT);intent.addCategory(Intent.CATEGORY_OPENABLE);intent.setType("image/*"); + try{startActivityForResult(intent,PICK_PHOTO);}catch(ActivityNotFoundException e){message("No photo picker is available on this device.");} + } + private void loadPhoto(Uri uri){ + undoHistory.clear();rendering=true;editorOrigin=screen.equals("templates")?"templates":"home";screen="editor";paper=null;show();int request=++renderVersion; + worker.execute(()->{ + try{ + BitmapFactory.Options opts=new BitmapFactory.Options();opts.inJustDecodeBounds=true; + try(InputStream in=getContentResolver().openInputStream(uri)){BitmapFactory.decodeStream(in,null,opts);} + if(opts.outWidth<1||opts.outHeight<1)throw new IOException("Unsupported image format"); + opts.inSampleSize=1;while(Math.max(opts.outWidth,opts.outHeight)/opts.inSampleSize>2048)opts.inSampleSize*=2; + opts.inJustDecodeBounds=false;Bitmap result; + try(InputStream in=getContentResolver().openInputStream(uri)){result=BitmapFactory.decodeStream(in,null,opts);} + if(result==null)throw new IOException("Could not read image"); + int orientation=1; + try(InputStream in=getContentResolver().openInputStream(uri)){orientation=new ExifInterface(in).getAttributeInt(ExifInterface.TAG_ORIENTATION,1);}catch(IOException ignored){} + Matrix m=new Matrix();switch(orientation){case 2:m.setScale(-1,1);break;case 3:m.setRotate(180);break;case 4:m.setScale(1,-1);break;case 5:m.setRotate(90);m.postScale(-1,1);break;case 6:m.setRotate(90);break;case 7:m.setRotate(270);m.postScale(-1,1);break;case 8:m.setRotate(270);break;} + if(!m.isIdentity())result=Bitmap.createBitmap(result,0,0,result.getWidth(),result.getHeight(),m,true); + File file=new File(getFilesDir(),"photo.png");try(OutputStream out=new FileOutputStream(file)){if(!result.compress(Bitmap.CompressFormat.PNG,100,out))throw new IOException("Could not save photo");} + Bitmap chosen=result;ui.post(()->{if(destroyed||request!=renderVersion)return;photo=chosen;photoMode=true;crop=turns=brightness=0;saveDraft();show();renderPaper();}); + }catch(Exception|OutOfMemoryError e){ui.post(()->{if(destroyed||request!=renderVersion)return;rendering=false;photoMode=false;renderError="That photo could not be opened. Try a smaller JPG or PNG.";show();message(renderError);});} + }); + } + private void renderPaper(){ + if(pendingRender!=null)ui.removeCallbacks(pendingRender); + saveDraft();final int request=++renderVersion;rendering=true;renderError=""; + final boolean isPhoto=photoMode, detail=dither, list=checklist;final Bitmap source=photo; + final int c=crop,t=turns,b=brightness,size=typeSize,style=paperStyle,align=paperAlignment;final String titleCopy=title,bodyCopy=body; + updatePreview();long began=android.os.SystemClock.elapsedRealtime(); + worker.execute(()->{ + if(destroyed||request!=renderVersion)return; + try{ + Bitmap sourcePaper=isPhoto&&source!=null?PaperRenderer.photo(source,c,t):PaperRenderer.note(titleCopy,bodyCopy,size,list,style,align); + PaperRenderer.Paper result=PaperRenderer.finish(sourcePaper,isPhoto&&detail,isPhoto?b:0); + ui.post(()->{if(destroyed||request!=renderVersion)return;paper=result;rendering=false;latestRenderMs=android.os.SystemClock.elapsedRealtime()-began;if(BuildConfig.DEBUG)android.util.Log.d("FoliPreview","renderMs="+latestRenderMs);updatePreview();}); + }catch(Exception|OutOfMemoryError e){ui.post(()->{if(destroyed||request!=renderVersion)return;paper=null;rendering=false;renderError=e instanceof IllegalArgumentException?e.getMessage():"This paper could not be prepared. Try a smaller image or shorter note.";updatePreview();});} + }); + } + private void device(){ + deviceSnapshot=printer.ready+":"+printer.connecting+":"+printer.dirty+":"+printer.busy(); + content.addView(heading("Your FOLI",29));gap(content,10);paragraph(content,"A little connection. A world of little ideas.");gap(content,20); + LinearLayout product=col();LinearLayout summary=row();summary.addView(new FoliIcon(this,"mark",GREEN),new LinearLayout.LayoutParams(dp(42),dp(42)));LinearLayout words=col();pad(words,16,0,0,0); + deviceCopy=heading(printer.ready?"Connected via Bluetooth LE":printer.connecting?"Connecting…":"Let's find your FOLI.",17);words.addView(deviceCopy);gap(words,6);words.addView(label("Your paper companion",12,MUTED,false));summary.addView(words,new LinearLayout.LayoutParams(0,-2,1));product.addView(summary);gap(product,18); + fullButton(product,printer.ready?"Refresh status":"Find your printer",true,()->{if(printer.ready)printer.refresh();else findPrinter();});card(content,product,MINT);gap(content,20); + content.addView(label("REPORTED BY YOUR PRINTER",10,MUTED,true));gap(content,12); + batteryValue=deviceStat("battery","Battery",printer.battery<0?"—":printer.battery+"%"); + paperValue=deviceStat("note","Paper",printer.paper<0?"Unknown":printer.paper==0?"Loaded":"Out of paper"); + temperatureValue=deviceStat("printer","Print head",PrinterProtocol.temperatureText(printer.temperature));gap(content,8); + jobPanel(content);gap(content,10); + if(printer.ready||printer.connecting)fullButton(content,"Disconnect",false,()->{if(printer.busy())confirmStop();else{printer.disconnect();show();}}); + if(printer.busy()){gap(content,12);fullButton(content,"Stop sending / disconnect",false,this::confirmStop);} + if(printer.dirty){gap(content,15);fullButton(content,"I restarted the printer",false,()->new AlertDialog.Builder(this).setTitle("Clear the previous job?").setMessage("Turn the printer off, then on. This clears any partially received data. Confirm only after restarting it; reconnect if needed.").setNegativeButton("Not yet",null).setPositiveButton("Restarted",(d,w)->{printer.acknowledgeRestart();uncertainPrint=false;saveDraft();show();}).show());} + gap(content,24);TextView privacy=label("Private by design · No account needed\nYour notes and photos stay on this phone.\nFOLI "+BuildConfig.VERSION_NAME+" · Development build",12,MUTED,false);privacy.setLineSpacing(dp(5),1);content.addView(privacy); + } + private TextView deviceStat(String ic,String name,String value){ + LinearLayout r=row();pad(r,16,15,16,15);r.setBackground(bg(CARD,15));r.addView(new FoliIcon(this,ic,GREEN),new LinearLayout.LayoutParams(dp(23),dp(23))); + TextView key=label(name,13,MUTED,false);pad(key,15,0,0,0);r.addView(key,new LinearLayout.LayoutParams(0,-2,1));TextView readout=label(value,14,INK,true);r.addView(readout);content.addView(r);gap(content,10);return readout; + } + private boolean permissions(){ + String[] required=Build.VERSION.SDK_INT>=31?new String[]{Manifest.permission.BLUETOOTH_SCAN,Manifest.permission.BLUETOOTH_CONNECT}:new String[]{Manifest.permission.ACCESS_FINE_LOCATION}; + for(String p:required)if(checkSelfPermission(p)!=PackageManager.PERMISSION_GRANTED){requestPermissions(required,PERMISSIONS);return false;} + return true; + } + private void findPrinter(){ + if(!permissions())return; + if(Build.VERSION.SDK_INT>=31&&checkSelfPermission(Manifest.permission.BLUETOOTH_CONNECT)!=PackageManager.PERMISSION_GRANTED)return; + BluetoothManager manager=(BluetoothManager)getSystemService(BLUETOOTH_SERVICE);BluetoothAdapter adapter=manager==null?null:manager.getAdapter(); + if(adapter==null){message("This device does not support Bluetooth LE. You can still create and preview papers.");return;} + if(!adapter.isEnabled()){try{startActivityForResult(new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE),ENABLE_BT);}catch(Exception e){message("Turn on Bluetooth in your phone settings, then try again.");}return;} + if(Build.VERSION.SDK_INT<31){LocationManager lm=(LocationManager)getSystemService(LOCATION_SERVICE); + if(lm!=null&&!lm.isProviderEnabled(LocationManager.GPS_PROVIDER)&&!lm.isProviderEnabled(LocationManager.NETWORK_PROVIDER)){ + new AlertDialog.Builder(this).setTitle("Enable location services").setMessage("Android 11 and earlier require location services for BLE discovery. FOLI does not collect your location.").setNegativeButton("Cancel",null).setPositiveButton("Open settings",(d,w)->startActivity(new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS))).show();return; + } + } + scanDevices.clear();devicesAdapter=new ArrayAdapter<>(this,android.R.layout.simple_list_item_1,new ArrayList<>()); + LinearLayout scanPanel=col();pad(scanPanel,22,10,22,10); + scanStatus=label("Power on your printer. Close other apps connected to it.\nLooking nearby…",14,MUTED,false);scanPanel.addView(scanStatus); + ListView list=new ListView(this);list.setAdapter(devicesAdapter);scanPanel.addView(list,new LinearLayout.LayoutParams(-1,dp(240))); + devicesDialog=new AlertDialog.Builder(this).setTitle("Find your FOLI").setView(scanPanel) + .setNegativeButton("Close",null).setNeutralButton("Scan again",null).create(); + list.setOnItemClickListener((parent,view,index,id)->{if(index>=0&&indexprinter.stopScan());devicesDialog.show(); + devicesDialog.getButton(AlertDialog.BUTTON_NEUTRAL).setOnClickListener(v->printer.scan());printer.scan(); + } + @Override public void changed(){ + if(destroyed)return; + if(printer.busy()||printer.dirty)uncertainPrint=true; + else if(printer.jobOutcome==PrintOutcome.RESTART_CONFIRMED)uncertainPrint=false; + saveDraft(); + if(devicesDialog!=null&&devicesDialog.isShowing()&&devicesAdapter!=null){ + scanDevices=new ArrayList<>(printer.devices.values());devicesAdapter.clear(); + for(BluetoothDevice d:scanDevices){String name; + try{name=d.getName();devicesAdapter.add((name==null?"FOLI-compatible printer":name)+"\n"+d.getAddress());}catch(SecurityException ignored){} + } + devicesAdapter.notifyDataSetChanged();scanStatus.setText(getString(R.string.scan_status,printer.status)); + } + String snapshot=printer.ready+":"+printer.connecting+":"+printer.dirty+":"+printer.busy(); + if(screen.equals("device")&&!snapshot.equals(deviceSnapshot))show();else updateStatus(); + } + private void updateStatus(){ + if(batteryValue!=null)batteryValue.setText(printer.battery<0?"—":printer.battery+"%"); + if(paperValue!=null)paperValue.setText(printer.paper<0?"Unknown":printer.paper==0?"Loaded":"Out of paper"); + if(temperatureValue!=null)temperatureValue.setText(PrinterProtocol.temperatureText(printer.temperature)); + if(footerAction!=null)footerAction.setText(printer.busy()?"View print progress":printer.ready?"Review & print":"Connect to print"); + if(stateText!=null)stateText.setText(printer.status); + if(chip!=null)chip.setText(connectionLabel()); + if(progressBar!=null){progressBar.setVisibility(printer.sending?View.VISIBLE:View.GONE);progressBar.setProgress(printer.progress);} + if(progressText!=null){progressText.setText(printer.sending?printer.progress+"% sent · Keep FOLI open and nearby.":printer.awaiting?"Transfer accepted. Waiting for device confirmation.":"");progressText.setVisibility(printer.busy()?View.VISIBLE:View.GONE);} + if(printer.busy())getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);else getWindow().clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON); + } + private void sendPrint(){ + if(printer.busy()){new AlertDialog.Builder(this).setTitle("Your print").setMessage(printer.status).setNegativeButton("Keep going",null).setPositiveButton("Stop / disconnect",(d,w)->confirmStop()).show();return;} + if(rendering){message("Your preview is still being prepared.");return;} + if(paper==null){message(renderError.isEmpty()?"Create a paper first.":renderError);return;} + if(!printer.ready){new AlertDialog.Builder(this).setTitle("Connect your FOLI").setMessage("Your paper is ready. Connect a compatible printer to send it.").setNegativeButton("Later",null).setPositiveButton("Find printer",(d,w)->findPrinter()).show();return;} + String error=printer.canPrint();if(error!=null){message(error);return;} + new AlertDialog.Builder(this).setTitle("Ready to print?").setMessage("Check the paper roll and keep the app open.\n\n"+paper.rows.length+" rows · "+new String[]{"Light","Medium","Dark"}[density-1]+" density\n\nThe printer may start as soon as the transfer finishes.") + .setNegativeButton("Cancel",null).setPositiveButton("Print",(d,w)->{printer.print(paper.rows,density);updateStatus();}).show(); + } + private void confirmStop(){new AlertDialog.Builder(this).setTitle("Stop this connection?").setMessage("FOLI can stop sending data, but the current firmware has no remote stop command. A print already started may continue. Restart the printer before retrying to clear its buffer.").setNegativeButton("Keep going",null).setPositiveButton("Stop sending",(d,w)->{printer.stopSending();printer.disconnect();show();}).show();} + private void help(){new AlertDialog.Builder(this).setTitle("A little help").setMessage("1. Install the paper with its thermal side facing the print head.\n\n2. Power the printer from its battery; use a charged, compatible pack.\n\n3. Connect inside FOLI. Close the old printer app first.\n\n4. Keep FOLI visible during transfer. Interrupted transfers require a printer restart.\n\n5. If a print is sent but completion is unconfirmed, check the actual paper. Do not resend automatically.\n\n6. The legacy firmware may append a stray line and has limited completion/error reporting. Hardware verification is still required for this development build.").setPositiveButton("Got it",null).show();} + @Override public void message(String value){if(!destroyed)new AlertDialog.Builder(this).setTitle("FOLI").setMessage(value).setPositiveButton("Got it",null).show();} + private void toast(String value){Toast.makeText(this,value,Toast.LENGTH_SHORT).show();} + private void saveDraft(){ + if(printer==null)return; + getPreferences(MODE_PRIVATE).edit().putString("title",title).putString("body",body).putBoolean("checklist",checklist).putBoolean("photoMode",photoMode) + .putBoolean("dither",dither).putInt("brightness",brightness).putInt("density",density).putInt("typeSize",typeSize).putInt("crop",crop).putInt("turns",turns) + .putInt("paperStyle",paperStyle).putInt("paperAlignment",paperAlignment).putStringSet("favorites",new HashSet<>(favorites)) + .putBoolean("uncertainPrint",uncertainPrint||printer.dirty||printer.busy()).apply(); + } + @Override public void onRequestPermissionsResult(int request,String[] permissions,int[] grants){ + super.onRequestPermissionsResult(request,permissions,grants); + if(request==PERMISSIONS){boolean ok=grants.length>0;for(int g:grants)ok&=g==PackageManager.PERMISSION_GRANTED; + if(ok)findPrinter();else new AlertDialog.Builder(this).setTitle("Nearby devices permission").setMessage("Allow Bluetooth access to discover and connect to your FOLI. Editing and preview work without it.").setNegativeButton("Not now",null).setPositiveButton("App settings",(d,w)->startActivity(new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS,Uri.parse("package:"+getPackageName())))).show();} + } + @Override protected void onActivityResult(int request,int result,Intent data){super.onActivityResult(request,result,data); + if(request==PICK_PHOTO&&result==RESULT_OK&&data!=null&&data.getData()!=null)loadPhoto(data.getData()); + if(request==ENABLE_BT&&result==RESULT_OK)findPrinter(); + } + @Override public void onBackPressed(){if(screen.equals("editor")){screen=editorOrigin;show();}else if(!screen.equals("home")){screen="home";show();}else if(printer.busy())confirmStop();else super.onBackPressed();} + @Override protected void onSaveInstanceState(Bundle out){out.putString("screen",screen);out.putString("editorOrigin",editorOrigin);out.putString("filter",templateFilter);if(pageScroll!=null)scrollPositions.put(screen,pageScroll.getScrollY());for(Map.Entry entry:scrollPositions.entrySet())out.putInt("scroll_"+entry.getKey(),entry.getValue());super.onSaveInstanceState(out);saveDraft();} + @Override protected void onPause(){saveDraft();super.onPause();} + @Override protected void onStop(){ + printer.stopScan();if(printer.busy()){printer.stopSending();saveDraft();}super.onStop(); + } + @Override protected void onDestroy(){destroyed=true;renderVersion++;if(activePanel!=null&&activePanel.isShowing())activePanel.dismiss();if(devicesDialog!=null&&devicesDialog.isShowing())devicesDialog.dismiss();printer.close();saveDraft();worker.shutdownNow();thumbWorker.shutdownNow();ui.removeCallbacksAndMessages(null);super.onDestroy();} +} diff --git a/software/android/app/src/main/java/studio/foli/android/PaperRenderer.java b/software/android/app/src/main/java/studio/foli/android/PaperRenderer.java new file mode 100644 index 0000000..aeb550c --- /dev/null +++ b/software/android/app/src/main/java/studio/foli/android/PaperRenderer.java @@ -0,0 +1,83 @@ +package studio.foli.android; + +import android.graphics.*; +import android.text.Layout; +import android.text.StaticLayout; +import android.text.TextPaint; + +final class PaperRenderer { + static final class Paper { + final Bitmap bitmap; + final byte[][] rows; + Paper(Bitmap bitmap,byte[][] rows){this.bitmap=bitmap;this.rows=rows;} + } + static Bitmap note(String title,String content,int size,boolean checklist){ + return note(title,content,size,checklist,0,0); + } + static Bitmap note(String title,String content,int size,boolean checklist,int style,int alignment){ + TextPaint body=new TextPaint(Paint.ANTI_ALIAS_FLAG); + body.setColor(Color.BLACK);body.setTextSize(size);body.setTypeface(Typeface.create(style==1?"serif":"sans-serif",Typeface.NORMAL)); + String value=content.trim(); + if(checklist){ + StringBuilder out=new StringBuilder(); + for(String s:value.split("\n"))if(!s.trim().isEmpty()){ + if(out.length()>0)out.append('\n'); + out.append(s.trim()); + } + value=out.toString(); + } + StaticLayout layout=StaticLayout.Builder.obtain(value,0,value.length(),body,checklist?296:320) + .setAlignment(!checklist&&alignment==1?Layout.Alignment.ALIGN_CENTER:Layout.Alignment.ALIGN_NORMAL).setLineSpacing(9,1.05f).setIncludePad(false).build(); + int height=Math.max(300,132+layout.getHeight()+56); + if(height>PrinterProtocol.MAX_ROWS)throw new IllegalArgumentException("This note is too long. Shorten the text or choose a smaller type size."); + Bitmap bitmap=Bitmap.createBitmap(384,height,Bitmap.Config.ARGB_8888);Canvas c=new Canvas(bitmap);c.drawColor(Color.WHITE); + Paint p=new Paint(Paint.ANTI_ALIAS_FLAG);p.setColor(Color.BLACK);p.setTextSize(12);p.setTypeface(Typeface.create("sans-serif",Typeface.BOLD)); + String eyebrow=style==1?"EVERYDAY, ON PAPER":style==2?"A NOTE FOR YOU":checklist?"A LITTLE FOCUS":"A LITTLE NOTE"; + c.drawText(eyebrow,32,37,p);p.setTextSize(27);p.setTypeface(Typeface.create(style==1?"serif":"sans-serif",Typeface.BOLD)); + // Keep the title inside the printable content area, including wide unicode titles. + float width=p.measureText(title);if(width>320)p.setTextSize(27*320/width); + c.drawText(title,32,79,p);p.setStrokeWidth(style==1?2:1);c.drawLine(32,101,352,101,p); + if(style==2){p.setStyle(Paint.Style.STROKE);p.setStrokeWidth(1.5f);c.drawRoundRect(15,15,369,height-14,8,8,p);p.setStyle(Paint.Style.FILL);} + c.save();c.translate(checklist?56:32,124);layout.draw(c);c.restore(); + if(checklist){ + // Draw real raster geometry: font fallback glyphs can lose thin edges + // when the final print image is thresholded on older Android builds. + p.setStyle(Paint.Style.STROKE);p.setStrokeWidth(1.8f); + for(int i=0;i=value.length())continue; + if(i==0||value.charAt(start-1)=='\n'){ + float y=124+layout.getLineBaseline(i)-size*0.72f; + c.drawRect(32,y,44,y+12,p); + } + } + p.setStyle(Paint.Style.FILL); + } + p.setTypeface(Typeface.create("sans-serif",Typeface.NORMAL));p.setTextSize(11);c.drawText("Made with FOLI",32,height-22,p); + return bitmap; + } + static Bitmap photo(Bitmap source,int crop,int turns){ + Bitmap working=source; + if(turns%4!=0){Matrix m=new Matrix();m.postRotate((turns%4)*90);working=Bitmap.createBitmap(source,0,0,source.getWidth(),source.getHeight(),m,true);} + int w=working.getWidth(),h=working.getHeight(); + if(crop>0){float ratio=crop==1?1f:0.75f;int cw=w,ch=h; + if(w/(float)h>ratio)cw=Math.max(1,(int)(h*ratio));else ch=Math.max(1,(int)(w/ratio)); + working=Bitmap.createBitmap(working,(w-cw)/2,(h-ch)/2,cw,ch);w=cw;h=ch; + } + int targetH=Math.max(1,(int)Math.round(h*384.0/w)); + float scale=Math.min(1f,(PrinterProtocol.MAX_ROWS-40)/(float)targetH); + int contentW=Math.max(1,Math.round(384*scale)),contentH=Math.max(1,Math.round(targetH*scale)); + Bitmap output=Bitmap.createBitmap(384,contentH+40,Bitmap.Config.ARGB_8888); + Canvas c=new Canvas(output);c.drawColor(Color.WHITE); + c.drawBitmap(working,null,new Rect((384-contentW)/2,20,(384+contentW)/2,contentH+20),new Paint(Paint.FILTER_BITMAP_FLAG)); + return output; + } + static Paper finish(Bitmap source,boolean dither,int brightness){ + int width=source.getWidth(),height=source.getHeight();int[] pixels=new int[width*height]; + source.getPixels(pixels,0,width,0,0,width,height); + byte[][] rows=PrinterProtocol.encode(pixels,width,height,dither,brightness); + for(int y=0;y>(x%8)))!=0?Color.BLACK:Color.WHITE; + Bitmap output=Bitmap.createBitmap(pixels,width,height,Bitmap.Config.ARGB_8888); + return new Paper(output,rows); + } +} diff --git a/software/android/app/src/main/java/studio/foli/android/PrintOutcome.java b/software/android/app/src/main/java/studio/foli/android/PrintOutcome.java new file mode 100644 index 0000000..e1bd2cc --- /dev/null +++ b/software/android/app/src/main/java/studio/foli/android/PrintOutcome.java @@ -0,0 +1,15 @@ +package studio.foli.android; + +/** Legacy state 3 means stopped, including timeout/error; it cannot prove success. */ +public enum PrintOutcome { + IDLE, IN_PROGRESS, STOPPED_UNCONFIRMED, FAILED, RESTART_CONFIRMED; + + public static PrintOutcome fromStatus(boolean awaiting, boolean started, + boolean failed, int paper, int temperature, int state) { + if (failed) return FAILED; + if (!awaiting) return IDLE; + if (paper == 1 || PrinterProtocol.temperatureBlocksPrinting(temperature)) return FAILED; + if (started && state == 3) return STOPPED_UNCONFIRMED; + return IN_PROGRESS; + } +} diff --git a/software/android/app/src/main/java/studio/foli/android/PrinterProtocol.java b/software/android/app/src/main/java/studio/foli/android/PrinterProtocol.java new file mode 100644 index 0000000..cc61581 --- /dev/null +++ b/software/android/app/src/main/java/studio/foli/android/PrinterProtocol.java @@ -0,0 +1,54 @@ +package studio.foli.android; + +/** Pure Java encoding shared by the app and host-side regression tests. */ +public final class PrinterProtocol { + public static final int TEMPERATURE_UNAVAILABLE = 255; + public static boolean temperatureUnavailable(int value) { return value == TEMPERATURE_UNAVAILABLE; } + public static boolean temperatureBlocksPrinting(int value) { return temperatureUnavailable(value) || value >= 65; } + public static String temperatureText(int value) { + return value < 0 ? "—" : temperatureUnavailable(value) ? "Sensor unavailable" : value + " °C"; + } + public static final int WIDTH = 384; + public static final int ROW_BYTES = 48; + // Legacy queue holds 1000 rows and accidentally enqueues the A6 command. + // Leave headroom, never truncate silently, and never split a 48-byte row. + public static final int MAX_ROWS = 768; + private PrinterProtocol() {} + + public static byte[] density(int level) { + if (level < 1 || level > 3) throw new IllegalArgumentException("Density must be 1, 2 or 3"); + return new byte[]{(byte)0xA5,(byte)0xA5,(byte)0xA5,(byte)0xA5,(byte)level}; + } + public static byte[] finish() { + return new byte[]{(byte)0xA6,(byte)0xA6,(byte)0xA6,(byte)0xA6,1}; + } + public static byte[][] encode(int[] argb, int width, int height, boolean dither, int brightness) { + if (width != WIDTH || height < 1 || height > MAX_ROWS || argb.length != width * height) + throw new IllegalArgumentException("Image must be 384 pixels wide and at most 768 rows"); + if (brightness < -80 || brightness > 80) throw new IllegalArgumentException("Brightness out of range"); + byte[][] rows = new byte[height][ROW_BYTES]; + float[] current = new float[width + 2], next = new float[width + 2]; + for (int y=0; y>>24; + float luminance=(((p>>16)&255)*0.299f+((p>>8)&255)*0.587f+(p&255)*0.114f); + float value=Math.max(0,Math.min(255,(luminance*alpha+255*(255-alpha))/255f+brightness+(dither?current[x+1]:0))); + boolean black=value<128; + if (black) rows[y][x/8]|=(byte)(0x80>>(x%8)); + if (dither) { + float error=value-(black?0:255); + current[x+2]+=error*7/16f; + next[x]+=error*3/16f; next[x+1]+=error*5/16f; next[x+2]+=error/16f; + } + } + float[] old=current; current=next; next=old; java.util.Arrays.fill(next,0); + } + return rows; + } + public static int[] decodeStatus(byte[] bytes) { + if (bytes == null || bytes.length != 4) return null; + int[] s=new int[]{bytes[0]&255,bytes[1]&255,bytes[2]&255,bytes[3]&255}; + if (s[0]>100 || s[2]>1 || s[3]>3) return null; + return s; + } +} diff --git a/software/android/app/src/main/java/studio/foli/android/TemplateCatalog.java b/software/android/app/src/main/java/studio/foli/android/TemplateCatalog.java new file mode 100644 index 0000000..bad69c7 --- /dev/null +++ b/software/android/app/src/main/java/studio/foli/android/TemplateCatalog.java @@ -0,0 +1,24 @@ +package studio.foli.android; + +/** Original, offline templates. Preview and print use the same renderer. */ +final class TemplateCatalog { + static final class Template { + final int id, style, color; + final String name, category, description, body; + final boolean checklist; + Template(int id,String name,String category,String description,String body,boolean checklist,int style,int color){ + this.id=id;this.name=name;this.category=category;this.description=description;this.body=body;this.checklist=checklist;this.style=style;this.color=color; + } + } + static final Template[] ALL={ + new Template(0,"Today's three.","Focus","A little less, a little better.","Finish something good\nTake a proper break\nMake time to create",true,0,0xFFDCEDE0), + new Template(1,"A fresh thought.","Notes","Give a good idea a place to land.","A small idea can be\nthe start of something good.",false,1,0xFFE2EBF2), + new Template(2,"Just for you.","Kindness","Say the little things that matter.","You make ordinary days\na little brighter.\n\nI'm glad you're here.",false,2,0xFFF4DFD5), + new Template(3,"A little list.","Lists","For whatever the day calls for.","Something fresh\nSomething useful\nA little treat",true,0,0xFFEDE9DC), + new Template(4,"One good thing.","Notes","Keep a small moment from today.","Something that made me smile:\n\nA moment I want to remember:\n\nSomething to look forward to:",false,1,0xFFEAE3F0), + new Template(5,"You've got this.","Kindness","A small reminder. A little courage.","You don't have to do it all.\n\nJust take the next small step.\n\nI'm cheering for you.",false,2,0xFFF0E6C9), + new Template(6,"A fresh start.","Focus","Make space for what matters.","One thing to finish\nOne thing to let go\nOne thing just for me",true,1,0xFFDCE9E9), + new Template(7,"Take a little trip.","Lists","Less forgetting. More exploring.","Keys and wallet\nPhone and charger\nSomething to read\nRoom for a little adventure",true,0,0xFFE0E8F4) + }; + static Template get(int id){return ALL[Math.max(0,Math.min(ALL.length-1,id))];} +} diff --git a/software/android/app/src/main/java/studio/foli/android/ZoomPaperView.java b/software/android/app/src/main/java/studio/foli/android/ZoomPaperView.java new file mode 100644 index 0000000..c68b3a4 --- /dev/null +++ b/software/android/app/src/main/java/studio/foli/android/ZoomPaperView.java @@ -0,0 +1,39 @@ +package studio.foli.android; + +import android.content.Context; +import android.graphics.*; +import android.view.*; + +/** Full-screen inspection of the actual output bitmap; never mutates print data. */ +final class ZoomPaperView extends View { + private final Bitmap bitmap; + private final Paint paint=new Paint(Paint.ANTI_ALIAS_FLAG|Paint.FILTER_BITMAP_FLAG); + private final RectF destination=new RectF(); + private final ScaleGestureDetector scale; + private final GestureDetector gestures; + private float zoom=1,offsetX,offsetY; + private boolean moved; + public ZoomPaperView(Context context){this(context,null);} + ZoomPaperView(Context context,Bitmap bitmap){ + super(context);this.bitmap=bitmap;setContentDescription("Print preview. Pinch to zoom, drag to pan, double tap to reset."); + scale=new ScaleGestureDetector(context,new ScaleGestureDetector.SimpleOnScaleGestureListener(){ + @Override public boolean onScale(ScaleGestureDetector d){moved=true;zoom=Math.max(1,Math.min(6,zoom*d.getScaleFactor()));if(zoom==1)offsetX=offsetY=0;invalidate();return true;} + }); + gestures=new GestureDetector(context,new GestureDetector.SimpleOnGestureListener(){ + @Override public boolean onDown(MotionEvent event){return true;} + @Override public boolean onScroll(MotionEvent first,MotionEvent current,float dx,float dy){moved=true;if(zoom>1&&!scale.isInProgress()){offsetX-=dx;offsetY-=dy;invalidate();}return true;} + @Override public boolean onDoubleTap(MotionEvent event){zoom=zoom>1?1:2.5f;offsetX=offsetY=0;invalidate();return true;} + });setFocusable(true); + } + @Override public boolean performClick(){super.performClick();return true;} + @Override public boolean onTouchEvent(MotionEvent event){if(event.getActionMasked()==MotionEvent.ACTION_DOWN)moved=false;scale.onTouchEvent(event);gestures.onTouchEvent(event);if(event.getActionMasked()==MotionEvent.ACTION_UP&&!moved)performClick();return true;} + @Override protected void onDraw(Canvas canvas){ + super.onDraw(canvas);if(bitmap==null)return;float margin=24*getResources().getDisplayMetrics().density; + float fit=Math.min((getWidth()-margin*2)/bitmap.getWidth(),(getHeight()-margin*2)/bitmap.getHeight());if(fit<=0)return; + float w=bitmap.getWidth()*fit*zoom,h=bitmap.getHeight()*fit*zoom; + float maxX=Math.max(0,(w-getWidth())/2+margin),maxY=Math.max(0,(h-getHeight())/2+margin); + offsetX=Math.max(-maxX,Math.min(maxX,offsetX));offsetY=Math.max(-maxY,Math.min(maxY,offsetY)); + float left=(getWidth()-w)/2+offsetX,top=(getHeight()-h)/2+offsetY; + destination.set(left,top,left+w,top+h);canvas.drawBitmap(bitmap,null,destination,paint); + } +} diff --git a/software/android/app/src/main/res/drawable/ic_launcher.xml b/software/android/app/src/main/res/drawable/ic_launcher.xml new file mode 100644 index 0000000..625d8ec --- /dev/null +++ b/software/android/app/src/main/res/drawable/ic_launcher.xml @@ -0,0 +1,4 @@ + + + + diff --git a/software/android/app/src/main/res/drawable/template_placeholder.xml b/software/android/app/src/main/res/drawable/template_placeholder.xml new file mode 100644 index 0000000..26e2ab8 --- /dev/null +++ b/software/android/app/src/main/res/drawable/template_placeholder.xml @@ -0,0 +1,4 @@ + + + + diff --git a/software/android/app/src/main/res/values-v27/styles.xml b/software/android/app/src/main/res/values-v27/styles.xml new file mode 100644 index 0000000..9cee241 --- /dev/null +++ b/software/android/app/src/main/res/values-v27/styles.xml @@ -0,0 +1,6 @@ + + + diff --git a/software/android/app/src/main/res/values/strings.xml b/software/android/app/src/main/res/values/strings.xml new file mode 100644 index 0000000..4ff356d --- /dev/null +++ b/software/android/app/src/main/res/values/strings.xml @@ -0,0 +1,6 @@ + + FOLI + Fine detail (dithering) + %1$s\nKeep the printer nearby and powered on. + %1$d / 1600 · Changes preview automatically + diff --git a/software/android/app/src/main/res/values/styles.xml b/software/android/app/src/main/res/values/styles.xml new file mode 100644 index 0000000..e4f36c7 --- /dev/null +++ b/software/android/app/src/main/res/values/styles.xml @@ -0,0 +1,12 @@ + + +