PerBang.dk https://www.perbang.dk Per Bang's Personal Toolbox: Lab, Archive and Blog Fri, 02 Oct 2026 13:16:21 +0000 en-US hourly 1 https://wordpress.org/?v=7.1.2 https://www.perbang.dk/wp-content/themes/pbdk/assets/images/pbdk-favicon.png?1.17.3 PerBang.dk https://www.perbang.dk 32 32 Project: ESP32 BLE Presence, Device Learning & Location System https://www.perbang.dk/esp32-ble-detection-system/ Fri, 02 Oct 2026 13:05:02 +0000 https://www.perbang.dk/?p=329 1. Project purpose

Build a distributed Bluetooth Low Energy (BLE) detection system integrated with Home Assistant.

The system will use one or more ESP32 devices running ESPHome as BLE scanners. Each ESP32 is assigned a physical location, such as:

  • Kitchen
  • Living room
  • Bedroom
  • Garage
  • Main entrance
  • Hallway

The ESP32 devices detect nearby BLE devices and report observations to Home Assistant.

Home Assistant is responsible for:

  • Maintaining the device database
  • Learning which devices are familiar
  • Allowing devices to be manually classified as known or ignored
  • Tracking when devices were last seen
  • Managing device expiration/downgrading/deletion
  • Determining device presence
  • Estimating which physical zone a device is closest to
  • Exposing useful sensors and states
  • Driving automations and notifications

The ESP32s should remain relatively simple BLE observation devices. The main intelligence and persistent state should reside in Home Assistant.


2. Main objectives

The system should provide five major capabilities.

A. BLE device discovery

Detect nearby BLE devices and report information such as:

  • Device identifier/address when available
  • Advertised name when available
  • RSSI
  • Timestamp
  • ESP32 that detected the device
  • Physical location of that ESP32
  • Other useful advertisement information where available

B. Device learning

The system should automatically learn about devices that repeatedly appear.

A newly detected device should not necessarily be considered suspicious or permanently unknown immediately.

The system should maintain a lifecycle such as:

NEW
 ↓
OBSERVED
 ↓
FAMILIAR
 ↓
KNOWN

with additional states such as:

IGNORED
STALE
DELETED

C. Presence detection

The system should be able to determine whether devices are currently present.

Examples:

  • iPad present
  • iPhone absent
  • Unknown BLE device present
  • No known devices present

Presence must tolerate temporary gaps in BLE advertisements.

A device disappearing for a few seconds should not immediately be considered absent.

D. Approximate location

With multiple ESP32 receivers, the system should compare RSSI measurements and determine which receiver/zone a device is probably closest to.

For example:

iPad

Kitchen:        -43 dBm
Living room:    -59 dBm
Garage:         -79 dBm
Main entrance:  -67 dBm

Estimated location: Kitchen

The system should use the concept of “closest/most likely zone” rather than attempting to provide precise coordinates.

E. Home Assistant automation

The resulting information should be exposed as normal Home Assistant entities so it can be used by automations.

Examples:

  • Turn kitchen lights on when a known household device enters the kitchen.
  • Turn garage lights on when an unknown BLE device is detected strongly in the garage.
  • Notify when a completely new BLE device appears.
  • Turn lights off when all known household devices have been absent for a configurable period.

3. Hardware

Initial hardware

The first prototype will use an existing:

ESP32-WROOM-32

running ESPHome.

No SD card is required for the initial system.

The ESP32 should primarily perform BLE scanning and transmit observations to Home Assistant.

Future hardware

Additional ESP32 devices can be added as required.

Each ESP32 should have a meaningful physical location.

Examples:

ble_kitchen
ble_living_room
ble_garage
ble_main_entrance
ble_hallway
ble_bedroom

The physical location should be part of the device’s configuration and should be included with observations.

External antennas

External-antenna ESP32 hardware may be useful for locations where coverage is poor, particularly:

  • Garage
  • Outdoor areas
  • Locations separated by thick walls
  • Locations where the ESP32 must be installed inside an RF-unfriendly enclosure

However, maximum range is not necessarily desirable.

The objective is not to make every ESP32 detect every BLE device as strongly as possible.

For location estimation, having several receivers with distinguishable RSSI measurements is more useful.

Therefore the initial recommendation is to test the normal onboard antenna before purchasing specialized external-antenna hardware.


4. Fundamental architecture

The architecture should be:

                  BLE devices
              phones / tablets /
             watches / headphones
                       │
                       │ BLE
                       ▼
          ┌─────────────────────────┐
          │        ESP32             │
          │      ESPHome             │
          │      BLE scanner         │
          └────────────┬────────────┘
                       │
                       │ Wi-Fi
                       ▼
             ┌─────────────────────┐
             │   Home Assistant    │
             │                     │
             │ Device registry     │
             │ Observations        │
             │ Presence            │
             │ Location            │
             │ Familiarity         │
             │ Automations         │
             └─────────────────────┘

With multiple ESP32s:

                  Home Assistant
                         │
          ┌──────────────┼──────────────┐
          │              │              │
          ▼              ▼              ▼
       Kitchen         Garage       Main Entrance
       ESP32            ESP32           ESP32
          │              │              │
          └──────────── BLE observations ────────────┘

Home Assistant is the central authority.


5. ESP32 responsibilities

ESP32 devices should perform as little business logic as possible.

Their primary responsibilities are:

  1. Scan for BLE advertisements.
  2. Identify the advertiser as far as BLE permits.
  3. Measure RSSI.
  4. Timestamp observations.
  5. Associate observations with the ESP32’s configured location.
  6. Send the observations to Home Assistant.

The ESP32 should not be responsible for determining:

  • Whether a device is known
  • Whether a device is familiar
  • Whether a device should be deleted
  • Whether a device is suspicious
  • Whether a person is home
  • Which room a device is in

Those decisions belong in Home Assistant.

This allows the rules to be changed without reflashing ESP32 devices.


6. BLE scanning configuration

The scan behavior should be configurable.

At minimum, the system should allow adjustment of:

Scan interval

How frequently the scanner performs a scan cycle.

Example:

1 second
5 seconds
10 seconds
30 seconds

Scan window

How much of each interval the ESP32 actually listens.

This should be configurable separately from the interval where practical.

Presence timeout

How long a device can go without being observed before being considered absent.

Example:

5 minutes

These are separate concepts.

A scan interval of 5 seconds does not mean that a device should be declared absent after 5 seconds without an advertisement.


7. Configurable system parameters

All important time thresholds should be configurable from Home Assistant rather than hard-coded.

Potential configuration parameters include:

BLE scan interval
BLE scan window

Presence timeout
Unknown-device alert delay
New-device grace period

Familiarity observation threshold
Familiarity time period

Known-device expiry
Stale-device period
Deletion period

Unknown-device notification cooldown

Minimum RSSI for location confidence
Minimum RSSI for security automations

Minimum location RSSI difference
Location smoothing period

Security-light activation delay
Security-light timeout

The exact values should be determined experimentally.

Example initial values:

Scan interval:                 5 seconds
Presence timeout:              5 minutes

New-device grace period:       30 seconds
Familiarity period:            7 days
Familiarity threshold:         20 observations

Stale-device period:           30 days
Deletion period:               180 days

Unknown notification cooldown: 30 minutes

Minimum location difference:   8 dB

These are examples only and should remain user-configurable.


8. Device identity considerations

BLE device identification must not rely blindly on a single Bluetooth MAC address.

Modern BLE devices can use address randomization and may change their observable identity.

Some devices may also:

  • Advertise intermittently
  • Change advertisement behavior
  • Use different identifiers for different functions
  • Stop advertising when idle
  • Advertise different information depending on operating-system behavior

Therefore the system should treat the BLE identifier as an observation identity rather than guaranteeing that it represents a permanent physical device.

The device registry should be designed so that the identity strategy can be improved later without rebuilding the whole system.


9. Device lifecycle

The system should distinguish between automatic learning and explicit user approval.

Recommended states:

NEW
OBSERVED
FAMILIAR
KNOWN
IGNORED
STALE

NEW

A device has been detected for the first time.

Example:

First seen:
2026-10-02 14:00

Observations:
1

OBSERVED

The device has been seen repeatedly, but has not yet met the familiarity criteria.

Example:

Observations:
17

First seen:
12 days ago

Last seen:
2 minutes ago

FAMILIAR

The device has been observed repeatedly over a meaningful period.

This means:

The system recognizes this device as frequently encountered.

It does NOT necessarily mean:

The user has explicitly approved this device.

KNOWN

The user has explicitly approved the device.

Known devices can be used for trusted presence automations.

IGNORED

The user has explicitly decided that the device should not generate alerts.

Examples could include:

  • Neighbor’s device
  • Known vehicle
  • Permanent nearby BLE beacon
  • Device that isn’t relevant to the household

Ignored devices may still be retained in the database for informational purposes.

STALE

The device has not been seen for a configurable period.

A stale device is retained temporarily rather than immediately deleted.

DELETED

The device record and/or historical observations are removed after the configured retention period.


10. Familiar versus known

These concepts must remain separate.

Familiar

Automatically inferred by the system.

Meaning:

“This device has appeared frequently enough that it is no longer particularly unusual.”

Known

Explicitly approved by the user.

Meaning:

“I recognize this device and want the system to treat it as a trusted device.”

This distinction allows the system to discover patterns without automatically granting trust.


11. Manual device management

Home Assistant should provide a way to manually manage devices.

Possible actions:

Make Known
Make Familiar
Ignore
Unignore
Rename
Forget
Delete
Reset learning

A device should be renameable.

Example:

BLE identifier:
AA:BB:CC:DD:EE:FF

Name:
Dad's iPad

The raw identifier should remain available internally even if the user gives it a friendly name.


12. Device history

The system should retain useful historical information.

Each device record should ideally contain:

Device ID
Friendly name
Current state
Classification
First seen
Last seen
Number of observations
Number of days observed
Last known location
Current estimated location
Approval time
Familiarity time
Last state change

Historical observations should contain information such as:

Timestamp
Device ID
ESP32 ID
ESP32 location
RSSI
Advertised name
BLE metadata

13. Observation retention

Raw observations should not necessarily be kept forever.

A sensible model is:

Detailed observations:
retain for X days

Device registry:
retain for Y days

Known device:
retain until manually removed

For example:

Raw observations: 14 days
Stale devices:    30 days
Delete unknown:   180 days
Known devices:    manual deletion

These periods should be configurable.

This reduces database growth while preserving useful device history.


14. Per-location sensors

Each ESP32 represents a physical BLE detection zone.

For example:

Kitchen BLE
Garage BLE
Main Entrance BLE
Living Room BLE
Bedroom BLE

Each location should expose aggregate information to Home Assistant.

Numeric sensors

At minimum:

Unknown devices
Familiar devices
Known devices
Ignored devices
Total devices

Potential additional sensors:

Strongest device RSSI
Strongest unknown RSSI
Number of observations
Last scan timestamp
Scanner status

15. Per-location binary sensors

Each ESP32/location should expose convenient binary states.

Recommended:

Unknown device present
Familiar device present
Known device present
Any BLE device present
New unknown device detected

For example:

Garage BLE

Unknown device present: ON
Familiar device present: OFF
Known device present: ON
Any BLE device present: ON

These should be easy to use directly in Home Assistant automations.


16. Unknown-device detection

There should be a distinction between:

Unknown device present

A device currently classified as unknown is currently being detected.

This remains active for as long as the device is considered present.

New unknown device

A device has been detected that has not previously been observed.

This can trigger a notification.

This distinction prevents repeated notifications.

Example:

New unknown device:
→ send notification

Unknown device remains present:
→ keep security light on
→ do not send another notification every few seconds

17. Unknown-device alerting

Notifications should be configurable.

Possible alert conditions:

New unknown device detected
Unknown device present for > X seconds
Unknown device with RSSI stronger than X
Unknown device repeatedly detected over X minutes
Unknown device detected in a specific zone

There should be an alert cooldown to avoid notification spam.

Example:

Unknown-device notification cooldown:
30 minutes

18. Location estimation

Multiple ESP32 receivers should be used to estimate the location of a device.

Example:

iPad

Kitchen:        -43 dBm
Living room:    -59 dBm
Garage:         -79 dBm
Main entrance:  -67 dBm

Estimated location:

Kitchen

The system should primarily think in terms of:

“Which receiver/zone is the device closest to?”

rather than:

“What are the exact coordinates of the device?”


19. RSSI smoothing

Individual RSSI readings should not be trusted blindly.

RSSI can change significantly due to:

  • Human bodies
  • Walls
  • Furniture
  • Device orientation
  • Multipath effects
  • Radio interference
  • Device antenna orientation

Therefore the location system should use a rolling average, median, exponential smoothing, or another filtering mechanism.

The exact algorithm can be determined during implementation/testing.


20. Location confidence

The system should not always force a location.

Example:

Kitchen:       -51 dBm
Living room:   -52 dBm

This should be considered ambiguous.

But:

Kitchen:       -41 dBm
Living room:   -67 dBm
Garage:        -81 dBm

is much stronger evidence for Kitchen.

A configurable minimum RSSI difference should therefore be used.

Example:

Minimum location confidence difference:
8 dB

If the strongest receiver is not sufficiently stronger than the next receiver, the location can be:

Unknown

rather than incorrectly choosing a room.


21. Location sensor

Each recognized device can have a calculated location.

Example:

sensor.ipad_location

Possible states:

Kitchen
Living Room
Garage
Main Entrance
Bedroom
Unknown
Away

Attributes can contain:

Kitchen RSSI
Living Room RSSI
Garage RSSI
Main Entrance RSSI

Confidence
Last update
Number of receivers

22. “Closest to” logic

The preferred abstraction is:

device → closest zone

For example:

iPad → Kitchen
Phone → Main Entrance
Watch → Bedroom
Unknown device → Garage

This makes Home Assistant automations very straightforward.

Example:

IF iPad location == Kitchen
THEN turn Kitchen lights on

23. Person/device association

The BLE device registry should remain separate from Home Assistant person logic.

Eventually a user can associate several devices with one person.

Example:

Person: User A

Devices:
- iPhone
- Apple Watch
- iPad

Then presence can be calculated from multiple devices.

For example:

Any trusted device associated with Person A present
        ↓
Person A probably home

This avoids relying on one phone.


24. Presence logic

Presence should have hysteresis.

Do NOT use:

BLE seen
→ HOME

BLE not seen
→ AWAY

because BLE advertisements can disappear temporarily.

Instead:

Device observed
       ↓
Present
       ↓
No observations for X minutes
       ↓
Absent

The timeout should be configurable.


25. Security/light automation example

One intended use case is improving visibility for CCTV.

Example:

IF
    Garage unknown devices > 0
AND
    strongest unknown RSSI > configurable threshold
AND
    unknown device has been present for > configurable duration

THEN
    turn garage lights on

Possible configuration:

Minimum RSSI:       -70 dBm
Activation delay:   10 seconds
Light timeout:      5 minutes

The actual values must be tested at the property.

This allows the system to distinguish a strong nearby device from a weak BLE signal originating farther away.


26. Other possible automations

Examples include:

Known device enters kitchen

IF
    iPad location becomes Kitchen

THEN
    turn kitchen lights on

Household device enters garage

IF
    known device location becomes Garage

THEN
    turn garage lights on

Unknown device appears

IF
    new unknown BLE device detected

THEN
    notify user

Everyone leaves

IF
    all trusted household devices are absent
    for X minutes

THEN
    turn selected lights off

Unknown garage activity

IF
    unknown devices > 0
    AND garage door is closed
    AND nobody is home

THEN
    activate garage lighting
    optionally notify user

The system should not automatically assume that an unknown BLE device represents a person. It is simply an additional sensor input.


27. Learning mode

A dedicated learning mode should be provided.

Example:

LEARNING MODE
Duration: 30 minutes

During learning mode, Home Assistant should present newly observed devices prominently.

Example:

BLE Learning Mode

iPad
47 observations
Seen at:
  Kitchen
  Living Room

AirPods
21 observations
Seen at:
  Kitchen

Unknown Device A
6 observations
Seen at:
  Garage

[Make Known]
[Ignore]

This makes initial setup significantly easier.


28. Per-zone dashboard

Home Assistant should eventually have a dashboard similar to:

BLE MONITOR
──────────────────────────────────────

Kitchen
  Known:       2
  Familiar:    1
  Unknown:     0
  Location activity: Normal

Living Room
  Known:       1
  Familiar:    0
  Unknown:     0

Garage
  Known:       0
  Familiar:    0
  Unknown:     2
  ⚠ Unknown BLE activity

Main Entrance
  Known:       1
  Familiar:    0
  Unknown:     1

A separate device-management view should show the full registry.


29. Device management dashboard

Example:

BLE DEVICES
────────────────────────────────────────────

Device          State      Location       Last seen
----------------------------------------------------
My iPhone       KNOWN      Kitchen        20 sec
My iPad         KNOWN      Garage         1 min
AirPods         FAMILIAR   Kitchen        2 min
Device A        UNKNOWN    Garage         10 sec
Device B        UNKNOWN    Main Entrance  4 min
Neighbor BLE    IGNORED    Main Entrance  2 min

Actions:

[Make Known]
[Make Familiar]
[Ignore]
[Forget]
[Rename]

30. Device expiry and downgrading

The system must support automatic aging.

Example:

Known
  ↓
not seen for X days
  ↓
Stale

Familiar devices can similarly be downgraded if they stop appearing.

Unknown devices can eventually be deleted if they have not been seen for a long period.

The exact lifecycle should be configurable.

Important distinction:

Automatically learned states may be automatically downgraded.

Manually approved KNOWN devices should preferably not be silently deleted unless the user explicitly enables that behavior.


31. Data retention and privacy

The system should minimize historical BLE data where practical.

BLE observations may represent devices belonging to people who are not members of the household.

Therefore:

  • Retain detailed observations only as long as necessary.
  • Allow the retention period to be configured.
  • Provide a way to delete a device and its historical observations.
  • Avoid storing unnecessary BLE information.
  • Keep the system local to Home Assistant where possible.

32. Important technical limitations

The system must account for BLE limitations.

Address randomization

Some devices can change their BLE address.

Therefore MAC/address matching is not guaranteed to identify a physical device permanently.

Intermittent advertising

A device may not advertise continuously.

Not seeing a device does not necessarily mean that it has physically left.

RSSI is not distance

RSSI should be treated as a relative signal-strength measurement, not a precise distance measurement.

RSSI is not direction

A normal ESP32-WROOM-32 receiver cannot directly determine the direction of a BLE signal.

Direction/location is instead approximated using multiple receivers.

BLE range is variable

Range depends on:

  • Device
  • Antenna
  • Walls
  • Construction
  • Interference
  • Device orientation
  • Receiver placement

The system should therefore be calibrated using actual measurements at the property.


33. Development strategy

Development should proceed incrementally.

Phase 1 — Single ESP32

Use the existing ESP32-WROOM-32.

Implement:

  • ESPHome BLE scanning
  • Configurable scan interval
  • Device observation
  • RSSI collection
  • ESP32 location/name
  • Home Assistant integration

Do not initially implement complicated location logic.

Phase 2 — Device registry

Implement:

  • New
  • Observed
  • Familiar
  • Known
  • Ignored
  • Stale
  • Deleted

Implement configurable lifecycle timers.

Phase 3 — Home Assistant entities

Create:

  • Device counts
  • Unknown count
  • Familiar count
  • Known count
  • Presence sensors
  • New-device sensor
  • Scanner status
  • Last scan
  • RSSI sensors

Phase 4 — Learning interface

Add:

  • Make Known
  • Make Familiar
  • Ignore
  • Rename
  • Forget
  • Learning mode

Phase 5 — Multiple ESP32s

Deploy additional receivers.

Each receives a unique physical location.

Example:

Kitchen
Living Room
Garage
Main Entrance

Phase 6 — Location estimation

Implement:

  • RSSI smoothing
  • Receiver comparison
  • Closest-zone calculation
  • Minimum confidence margin
  • Unknown/ambiguous location state

Phase 7 — Automation

Implement Home Assistant automations for:

  • Lighting
  • Presence
  • Security illumination
  • Notifications
  • Zone-based actions

34. Initial test methodology

Before purchasing many additional ESP32 devices, use the existing WROOM-32 to gather real measurements.

Test a known device such as an iPad at fixed locations.

Record:

Location
ESP32
RSSI
Time

Example:

Location        RSSI
---------------------
Kitchen         -40
Living Room     -54
Hallway         -62
Main Entrance   -68
Garage          -79
Outside         -84

Repeat measurements several times.

The objective is to determine whether the RSSI differences between zones are sufficiently distinct to make location estimation practical.

If locations have highly overlapping RSSI values, additional receivers or different hardware placement may be required.


35. Design principles

The project should follow these principles:

  1. ESP32s are sensors, not the central database.
  2. Home Assistant owns persistent state and intelligence.
  3. All important time thresholds are configurable.
  4. Device learning is separate from manual approval.
  5. Known, familiar, unknown and ignored are separate concepts.
  6. Raw observations are separate from the device registry.
  7. Historical data should expire independently from device records.
  8. Presence should tolerate intermittent BLE advertisements.
  9. RSSI should be smoothed before location decisions.
  10. Location should be expressed primarily as a zone, not exact coordinates.
  11. Location confidence should be available.
  12. Multiple receivers are more important for location than simply maximizing one receiver’s range.
  13. Security automations should use configurable thresholds and delays.
  14. The system should be useful even with only one ESP32.
  15. Additional ESP32s should be easy to add later without redesigning the data model.

36. Target end state

The finished system should behave conceptually like this:

                    BLE ENVIRONMENT
                           │
                           ▼
              ┌───────────────────────┐
              │     ESP32 receivers   │
              │                       │
              │ Kitchen               │
              │ Living Room           │
              │ Garage                │
              │ Main Entrance         │
              └───────────┬───────────┘
                          │
                          ▼
                  BLE observations
                          │
                          ▼
              ┌───────────────────────┐
              │    Home Assistant     │
              │                       │
              │ Device Registry       │
              │ Observation History   │
              │ Familiarity           │
              │ Presence              │
              │ Location              │
              │ Confidence            │
              │ Retention             │
              └───────────┬───────────┘
                          │
             ┌────────────┼─────────────┐
             ▼            ▼             ▼
          KNOWN        FAMILIAR       UNKNOWN
             │            │             │
             └────────────┼─────────────┘
                          │
                          ▼
                  Zone determination
                          │
             ┌────────────┼────────────┐
             ▼            ▼            ▼
          Kitchen       Garage      Entrance
             │            │            │
             └────────────┼────────────┘
                          │
                          ▼
                    HA Automations

The ultimate goal is a flexible BLE-based presence and zone-awareness system for Home Assistant, capable of learning the normal BLE environment over time while allowing explicit user control over which devices are trusted.

The system should be designed so that adding another ESP32, changing scan intervals, changing retention periods, changing familiarity rules, or changing automation behavior does not require redesigning the entire system.

]]>
Howto: Setup a vinyl cutter / plotter in Linux using Inkscape https://www.perbang.dk/setup-a-vinyl-cutter-in-linux/ Sun, 19 Apr 2026 17:15:49 +0000 https://www.perbang.dk/?p=286 This Linux setup guide is tested with a Redsail RS720C on Ubuntu and Linux Mint.

Note on Inkscape extensions (Inkcut / others)

No additional Inkscape extensions were required for this setup. Some guides recommend installing tools like Inkcut for sending jobs to vinyl cutters or plotters. However, in this setup with the Redsail RS720C, this was not necessary.

The cutter works directly using the built-in Inkscape plot/export functionality.

1. Remove Snap version of Inkscape (important if installed via Snap, e.g. Ubuntu)

sudo snap remove inkscape

Ensures Inkscape is not sandboxed. Snap can block USB/serial access and cause: “Could not open serial port”

2. Install required software

sudo apt update
sudo apt install inkscape python3-serial

Installs:

  • Inkscape (vector design tool used to create and send cut files)
  • Python serial support (required for USB communication with the cutter)

3. Fix USB permissions

sudo usermod -a -G dialout $USER

Allows your user account to access serial devices like /dev/ttyUSB0.

IMPORTANT: You must log out and log in again (or reboot) after this step.

4. Find the cutter connection

dmesg | grep ttyUSB

Shows which USB serial port the cutter is using.

Typical result:

  • /dev/ttyUSB0 → cutter connection (most common)

5. Configure Inkscape plotter settings

Open Inkscape →
Extensions → Export → Plot…

Use these settings:

  • Serial Port: /dev/ttyUSB0
    USB connection to the cutter
  • Baud Rate: 9600
    Communication speed (must match cutter firmware)
  • Flow Control: RTS/CTS (Hardware)
    Prevents data loss during long cuts
  • Command Language: HPGL
    Standard vector language used by vinyl cutters
  • Rotate: 90°
    Aligns output with screen orientation

6. Done

Your vinyl cutter is now ready to cut reliably on Linux.

Enjoy!

]]>
Exploring the CLC Color Space in 3D https://www.perbang.dk/exploring-the-clc-color-space-in-3d/ Fri, 28 Nov 2025 01:51:14 +0000 https://www.perbang.dk/?p=258 The CLC (Chroma–Luma Cone) Color Space is a geometric, RGB-derived model designed to make color visualization more intuitive. Unlike traditional 2D representations like HSV or HSL, CLC maps colors into a 3D double-cone structure, allowing you to explore relationships between hue, chroma, and brightness in a visually meaningful way.

How CLC Works

1. Inputs
CLC starts with standard RGB colors, with each channel ranging from 0 to 255. These values are converted to HSV for easier manipulation:

  • H — Hue angle (0–360°)
  • S — Saturation (0–100)
  • V — Value/Brightness (0–100)

2. Geometry
The CLC model arranges colors in a double-cone around a central neutral axis:

  • Horizontal position (x, z) — determined by the color’s chroma radius, which increases with saturation and brightness.
  • Vertical position (y) — represents brightness adjusted by chroma for perceptual neutrality.
    This creates two cones: the upper cone for bright colors, the lower cone for dark colors, with neutral grays forming a smooth central axis.

3. Structure
The resulting 3D structure is:

  • A symmetric, centered double-cone
  • Circular hue wheel around the vertical axis
  • Chromatic colors radiating outward
  • Neutral colors aligned along the center

This design allows CLC to effectively visualize:

  • Color distances and differences
  • Brightness and chroma relationships
  • Large RGB datasets and palettes
  • Palette clustering and analysis

Why CLC is Useful

By translating RGB values into a spatial, 3D representation, CLC makes it easier to understand:

  • Which colors are perceptually similar
  • How brightness and saturation interact
  • The overall distribution of a color palette

It’s an intuitive alternative to standard color spaces and provides a clear, structured view of complex color relationships.

Explore CLC Yourself

You can interact with a live 3D model of CLC colors here: 3D Color Wheel
Double-click any sphere to see detailed information about the color it represents. Switch between CLC, RGB, HSV, and HSL modes to explore different perspectives of your color data.

]]>
Restoration Workflow – Tackling a Severely Damaged and Faded Photo https://www.perbang.dk/restoration-workflow-tackling-a-severely-damaged-and-faded-photo/ Thu, 18 Sep 2025 17:18:06 +0000 https://www.perbang.dk/?p=188 For the second test in my restoration workflow, I intentionally picked a much tougher challenge. This photo wasn’t just damaged — it was heavily faded, and large portions of the image were completely missing. Restoring it took more than just basic clean-up; it required serious experimentation and creative problem-solving.

Why This One Was So Challenging

Unlike the first image, this one lacked clear structure in several areas. The facial features were barely visible, and much of the background detail was lost. It forced me to push my AI workflow — especially inpainting and prompt tuning — much further.

How I Handled the Restoration

  • Enhanced contrast and structure using preprocessing before sending it through ComfyUI.
  • Used custom inpainting prompts to reconstruct large missing sections while keeping the results believable.
  • Fine-tuned restoration strength — striking a balance between creative fill-in and preserving what little original data remained.
  • Iterated with multiple runs, comparing outcomes until I found a result that felt both faithful and complete.

The Result

After some back-and-forth tweaking, I was able to bring the image back to life. It’s not just about making it “look nice” — it’s about restoring emotional and historical value that would otherwise be lost.

What I Learned

This test taught me a lot about handling edge cases — images where traditional restoration tools fall short. My workflow now has better flexibility, and I’ve developed a clearer sense of when to use subtle tweaks vs. full reconstructions.

If you want to give i a shot yourself, here is the file:

]]>
Restoration Workflow – Using an Old Damaged Photo to Perfect it https://www.perbang.dk/using-an-old-damaged-photo-to-perfect-my-ai-restoration-workflow/ Thu, 18 Sep 2025 16:49:23 +0000 https://www.perbang.dk/?p=180 I found this old, damaged photo online — it had stains, bends, scratches, and even some small missing parts. Instead of just restoring it, I decided to use it as a test subject to fine-tune and perfect my AI-powered restoration workflow with ComfyUI.

Why This Image Was Perfect for Workflow Testing

Because the photo had a mix of common restoration challenges — discoloration, physical damage, missing details — it was a great real-world example to work through. I wanted to create a reliable, repeatable process that could handle photos like this consistently and efficiently.

How I Used This Photo to Refine My Process

  • I experimented with different prompt formulations to get the best detail recovery.
  • Tweaked inpainting nodes to fill missing or damaged areas convincingly.
  • Balanced clean-up and upscaling steps to avoid artifacts while restoring texture.
  • Tested batch processing potential, aiming to save hours on future restorations.

The Result

Within a surprisingly short time, I achieved a restored version I was happy with. More importantly, I now have a solid baseline workflow that I can confidently reuse and improve over time for other images.

What’s Next

This photo was my stepping stone. Moving forward, I’ll keep refining the pipeline and applying it to more challenging restorations — turning old, damaged memories into vivid, beautiful images with minimal manual effort.

]]>
Restoring Old Photos with AI – How ComfyUI Changed My Workflow Forever https://www.perbang.dk/restoring-old-photos-with-ai-how-comfyui-changed-my-workflow-forever/ Thu, 18 Sep 2025 16:40:26 +0000 https://www.perbang.dk/?p=177 Restoring old photographs used to be a time-consuming task — hours spent manually cleaning scratches, rebuilding faded areas, and trying to recover lost detail pixel by pixel. Traditional tools like Photoshop (or in my case, GIMP) were powerful, but slow and often repetitive.

Then I discovered ComfyUI — and everything changed.

What Is ComfyUI?

ComfyUI is a powerful, modular interface for working with Stable Diffusion and other AI models. Think of it as a visual programming tool for AI image workflows. You build your process once, and then use it over and over — no scripting needed (but you can if you want to).

Why I Switched My Photo Restoration Workflow to ComfyUI

Here’s what makes it a game-changer:

  • Batch Processing: I can restore 10, 50, or 100 old images with minimal effort.
  • Prompt-Based Detail Generation: With a carefully crafted prompt, ComfyUI fills in missing detail beautifully — from skin texture to background reconstruction.
  • Non-Destructive Workflow: Every node is reproducible. I can go back and tweak a step without losing my progress.
  • Time Saved: What used to take hours now takes minutes.

To me, this kind of power makes older editing tools feel… well, obsolete.

My Typical Workflow

  1. Scan or photograph the original image
  2. Pre-process: Basic cleanup using GIMP (cropping, leveling)
  3. Load into ComfyUI with a prompt like: “Restore vintage photo, enhance facial detail, remove scratches, natural lighting”
  4. Run my custom workflow: Upscaling, inpainting, detail enhancement
  5. Export before/after images for comparison

Real Examples

I’ll be posting several before-and-after comparisons so you can see the results for yourself.

Each of these images was restored using my AI workflow in ComfyUI — no manual retouching, no Photoshop. Just a smart pipeline and a bit of prompt magic.

Is Photoshop Dead?

Not entirely — but for me, it kind of is. I still use GIMP for touch-ups or annotations, but when it comes to restoring life to old, damaged photos, ComfyUI has taken over.

Want to Try It Yourself?

If you’re comfortable with running local AI models (or want to learn), I highly recommend giving ComfyUI a shot. The learning curve is there, but once you get the hang of it, you’ll wonder how you ever worked without it.

Final Thoughts

AI isn’t here to replace creativity — it’s here to amplify it. With tools like ComfyUI, we’re no longer just retouchers — we’re building intelligent restoration pipelines.

What used to take me all afternoon now takes 5 minutes — and often looks better.

Stay tuned for before/after image galleries and a behind-the-scenes look at my workflow

]]>
Enhancing WordPress Website Security https://www.perbang.dk/enhancing-wordpress-website-security/ Sat, 28 Sep 2024 11:37:41 +0000 https://www.perbang.dk/?p=161 – The Importance of Strong Usernames and Passwords

In today’s digital landscape, ensuring the security of our websites is more crucial than ever, especially when considering the potential vulnerabilities that come with poor password choices. Recent analysis of brute force login attempts on our WordPress sites revealed a staggering total of over 148,122 login attempts targeting a single real user account, with even more attempts across various accounts – during a 4-day period. None of these attempts were successful, thanks to security measures already in place. However, this incident emphasizes the urgent need to focus on improving our website security further.

Key Findings

  • Username Targeting: Common usernames were frequently targeted during these attacks. Notably, usernames like admin, wwwadmin, wadminw, john (and other first names), username, and other predictable names were under constant threat.
  • Aggressive Brute Force Attempts: Multiple IP addresses attempted to breach our sites, demonstrating a high level of malicious intent.

Despite the high volume of attempts, our proactive measures – including logging all login activity, removing users/usernames from sitemap.xml and the wp-json endpoint, and disabling xmlrpc.php – played a significant role in maintaining security.

Username Recommendations

To enhance security, consider the following recommendations regarding usernames:

  • Avoid Admin: The username admin is by far the most used in brute force attacks. By not having a user account with this username is a significant security measure.
  • Avoid Common Usernames: Steer clear of predictable usernames like admin, user, test, or any simple variations of personal names.
  • Use Unique Usernames: Encourage the use of unique usernames that are not easily guessable to reduce the risk of targeted attacks.

The Importance of Strong Passwords

Even more critical than usernames is the choice of passwords. Many users tend to select passwords that are easily compromised. Below are examples of weak passwords that people often choose, which should be avoided at all costs (these are identified during recent brute force attacks):

  • 123456
  • 123456789
  • 0192837465
  • 0192837465z
  • 000000
  • 0000
  • 111111
  • 1111
  • [USERNAME]2024 – where USERNAME is a real username revealed on the site / by WordPress. The year varies and may also represent a date.
  • !@#admin
  • admin@2024, admin@2023, admin@2022 – and so on
  • password
  • password123
  • pass
  • qwerty
  • abc123
  • letmein
  • letmein123
  • monkey
  • iloveyou
  • F*uckYou
  • admin
  • welcome
  • 123123123
  • 123123
  • wordpress
  • 12344321
  • 0192837465z
  • 1234[SITENAME] / 123[SITENAME] / 1234@[SITENAME] … – where SITENAME may be the domain name with or without TLD like .com/com
  • admin!
  • admin!@
  • root
  • admin888
  • adminadmin
  • administrator or Administrator
  • webmaster
  • administrador or Administrador
  • Adminp@ssw0rd
  • banana1
  • blah
  • blahblah
  • blogger

Best Practices for Strong Passwords

To create strong passwords, consider the following tips:

  • Length Matters: Passwords should be at least 12 characters long.
  • Mix It Up: Use a combination of uppercase and lowercase letters, numbers, and special characters.
  • Avoid Personal Information: Do not include easily accessible information such as birthdays or names.

As guardians of our websites, we must take every precaution to protect them – especially for the sites belonging to our children, who may unknowingly choose easily compromised passwords. While WordPress does share some user information, implementing additional security measures and promoting best practices for usernames and passwords can significantly bolster our defenses.

By prioritizing the security of our websites, we create a safer online environment for everyone. Let’s work together to educate our users on the importance of using unique usernames and strong passwords to enhance overall security.

]]>
How Do I Calculate Color Gradients? https://www.perbang.dk/how-do-i-calculate-color-gradients/ Sat, 28 Sep 2024 09:15:13 +0000 https://www.perbang.dk/?p=159 Ah, the art of color gradients. At first glance, they might seem like a fancy way to spice up a design, but there’s more to gradients than just making things look pretty. Whether you’re designing a website, creating digital art, or simply trying to find that perfect transition from “slightly less offensive yellow” to “kinda tolerable green,” calculating color gradients is both an art and a science. So, how do you calculate them – and why should you care?

The “How” Behind Color Gradients

At its core, calculating a color gradient means finding a smooth transition between two colors. To achieve this, you need to break the journey between your two hex RGB values into manageable steps. Think of it like plotting the stops on a colorful road trip, where each stop is a color between your starting point and destination. The more stops (or “steps”) you make, the smoother your transition will be.

On the handy Gradient Maker, you can do exactly that! You can choose to generate gradients based on:

  • RGB increments: This approach calculates the difference between each color channel (red, green, and blue) and divides them by the number of steps you specify.
  • HSV (Clockwise and Counterclockwise): This method shifts hues around the color wheel, either clockwise or counterclockwise, to create harmonious, hue-based transitions. HSV is great when you want a more natural-feeling gradient, especially for designs that require transitions between different tones and shades.

Simply input two hex RGB values, choose your number of steps (between 3 and 64), and let the Gradient Maker calculate the intermediate colors for you.

The “Why” of Gradients

Why bother calculating gradients at all? Glad you asked! Color gradients are the secret sauce in many digital designs, and their applications are far-reaching:

  • Web Design: Gradients add depth, dimension, and visual interest to websites. By calculating custom gradients, you can create a unique aesthetic that enhances user experience and adds modern flair.
  • Branding: Companies use gradients to make logos, banners, and ads pop. A well-crafted gradient can give your brand a trendy, fresh look without overwhelming your audience.
  • Art & Illustration: Gradients are a powerful tool for creating smooth transitions, adding texture to illustrations, or blending colors in digital artwork. Think of them as the bridge between colors that make your designs more cohesive.
  • Data Visualization: Color gradients are often used to represent ranges or scales in charts, maps, and infographics. For example, heat maps use color transitions to visually indicate differences in data values.

Export Your Results – Or Convert to CSS!

Once your gradient is calculated, the Gradient Maker will display it visually for all types – RGB, HSV Clockwise, and HSV Counterclockwise. But that’s not all. You can easily export the result as a palette, in any of the formats you know and love:

  • GIMP Palette
  • PNG Palette Image
  • Adobe ASE Palette
  • Plain Text (RGB)
  • JSON Format
  • XML (aRGB)

Or, if you’re a web designer looking to apply these gradients to your backgrounds, you can convert your custom gradient directly to CSS backgrounds. Whether you’re using linear or radial gradients, you can copy-paste the CSS and integrate it into your site without breaking a sweat.

So, Why Not?

Gradients are everywhere, from the subtlest backgrounds to bold and colorful designs. They create visual interest, draw attention, and add professionalism to your work. And now, thanks to the Gradient Maker, calculating the perfect gradient is just a few clicks away.

Whether you’re a color connoisseur or just looking to experiment with smooth color transitions, our tool makes it effortless. After all, who doesn’t want a little extra splash of color in their day?

]]>
“Groundbreaking” Color Search and Palette Export https://www.perbang.dk/groundbreaking-color-search-and-palette-export/ Fri, 27 Sep 2024 23:48:33 +0000 https://www.perbang.dk/?p=156 Hold on to your paint buckets, folks! Today marks a historic moment for the site – the color search function (first introduced almost 20 years ago at this site) is now integrated in WordPress and just got even better. Sure, you might argue that a color search tool, which not only helps you find colors by name or hex code but also changes the entire website theme to match the first and best match, is utterly useless. And you’d be right! But in the spirit of embracing life’s little absurdities, it is delightful.

Imagine typing in “coral” or “#ff7f50“, and before you know it, the website transforms into a dazzling display of that hue. Could this feature help you make better life choices? No. Will it improve your productivity? Absolutely not. But it sure does bring your browsing experience into perfect (dis)harmony with the overall chaotic “charm” of the site.

But wait, there’s more! Because who doesn’t want more meaningless, colorful fun? Now, if you search for multiple hex colors, the magic goes even further. The system will identify your colors as a palette, as if by some miracle of modern technology, and will proudly offer you the chance to export that palette in a variety of formats that, in a surprising twist, might actually be useful. Behold your options:

  • GIMP Palette: For the GIMP aficionados, export your palette to work seamlessly with the open-source editor. If you don’t have it already get GIMP here.
  • PNG Palette Image: Sure, it’s just a pretty picture of your palette, but this PNG can also be imported into several apps, including GIMP, as a palette. Double win!
  • Adobe ASE Palette: Fancy using Adobe products? The Adobe Swatch Exchange (.ase) file is a binary file that works with all the posh Adobe tools.
  • Plain Text (RGB): Need those RGB values in a basic text file? Done. It’s simple, it’s effective, and it’s probably the least exciting option -but hey, it’s there.
  • JSON Format: Now we’re talking data! Get all the juicy details – description, RGB, XYZ, and CIELAB values for each color – in a neat JSON file. For when you need to sound smart at parties.
  • XML (aRGB): And here’s the kicker – a surprisingly useful XML resource file with color values in aRGB format. This one actually might have practical value, which, frankly, caught me all off guard.

So, what are you waiting for? Go ahead, search for “hot pink” or “#00FF00 #FF9900 #0099FF“, throw in a few more hex codes, and watch in awe as the site molds itself into your custom palette – because sometimes, the most beautiful things in life are the ones that make the least sense… until suddenly, they do.

]]>
The Importance of Protecting Your Website https://www.perbang.dk/the-importance-of-protecting-your-website/ Tue, 24 Sep 2024 16:20:50 +0000 https://www.perbang.dk/?p=149 Running a website in today’s digital world comes with a host of challenges. One of the most significant threats is the constant barrage of login attempts by bad actors trying to compromise your site. While this might sound like something only major corporations or high-profile websites face, the reality is much different. Even a small WordPress site can be the target of thousands of login attempts daily. Just today, my own WordPress installation registered 1,522 login attempts from the same IP in Indonesia within a mere 13 minutes. A similar attack was registered from Bulgaria including 256 attempts in less than 3 minutes. Do you log login activity?

This incident serves as a wake-up call: if you own a website, no matter how small, it’s crucial to protect it. Let’s talk about why this happens, what the risks are, and how you can fortify your site against these threats.

Why Are Hackers Targeting Your Website?

  1. Automated Attacks
    Hackers often use bots to scan the internet for vulnerable websites, regardless of their size or popularity. These bots can automatically attempt brute-force attacks—trying hundreds or thousands of username-password combinations in a short time.
  2. Low-Hanging Fruit
    Many attackers are opportunists, looking for websites with weak passwords, outdated software, or unprotected login forms. A WordPress site with weak security measures becomes a prime target.
  3. Monetary Gain
    Successful breaches can lead to theft of sensitive data, redirecting your traffic, injecting malware, or even using your server to distribute spam or launch further attacks.
  4. Compromise at Scale
    Hackers don’t need to care about your content. They care about gaining control of as many sites as possible to use them as part of a broader scheme. Your site could be used as part of a botnet to launch attacks against other websites.

What Are the Risks?

  • Data Breaches
    A successful brute-force attack could expose your users’ data, leading to loss of trust and potential legal consequences.
  • Downtime and Damage to Reputation
    Once compromised, your website may be taken down, defaced, or filled with malicious content, leading to a negative experience for visitors.
  • SEO Penalties
    Search engines like Google penalize sites hosting malware or spam content, tanking your site’s rankings and visibility.
  • Financial Loss
    Recovering from a hack can be costly—not just in terms of fixing the vulnerabilities, but also in terms of lost business, especially if your site is down for a prolonged period.

How Can You Protect Your Website?

1. Limit Login Attempts

As seen in today’s brute-force attempt on my site, limiting login attempts is essential. After three failed login attempts, my WordPress installation automatically blocks further attempts from the same IP. This feature alone can thwart the majority of brute-force attacks. You can use plugins to implement this.

2. Use Strong Passwords and Two-Factor Authentication (2FA)

Weak passwords are a hacker’s best friend. Ensure all users, especially admins, use strong, unique passwords. Adding two-factor authentication (2FA) creates an extra layer of protection. With 2FA, even if a hacker cracks the password, they can’t access your site without the secondary authentication code.

3. Install a Security Plugin

There are excellent security plugins like Wordfence and iThemes Security that monitor login attempts, scan for malware, and block known bad actors. These plugins provide detailed logs, so you can stay on top of security events like today’s attack.

4. Keep Your Software Up-to-Date

Whether you’re using WordPress, Joomla, or custom-built software, ensure all components—core software, plugins, and themes—are always up-to-date. Hackers frequently exploit vulnerabilities in outdated software. A single missed update can open the door to an attack.

5. Use HTTPS (SSL/TLS Encryption)

Secure your site with an SSL certificate to encrypt the data transferred between your site and your visitors. This protects against “man-in-the-middle” attacks and boosts your site’s credibility (and SEO ranking).

6. Implement a Web Application Firewall (WAF)

A Web Application Firewall sits between your server and incoming traffic, filtering out malicious requests before they reach your site. Cloudflare offers a basic WAF for free, but there are also premium options from services like Sucuri and Imperva.

7. Backup Regularly

Backups are your safety net in case of an attack. Set up automated daily backups to ensure that, even if the worst happens, you can restore your site quickly. Plugins can help manage this.

8. Block Suspicious IPs and Countries

If your site doesn’t serve visitors from certain regions, consider blocking traffic from those countries entirely. In today’s case, for instance, you might want to block the IPs from Indonesia that attempted the brute-force attack. This can be done via your firewall or security plugins.

9. Harden WordPress (or your CMS)

WordPress security hardening means taking extra steps like disabling file editing within the WordPress dashboard, changing the default login URL, and restricting access to sensitive files like wp-config.php. These measures make it harder for hackers to find weaknesses to exploit.

10. Monitor Activity

Set up logging to monitor user activity, login attempts, and file changes. This will help you spot suspicious activity early and take action before things escalate.

Conclusion: Security is Not Optional

Every website is a potential target, whether it’s a small blog or a major e-commerce platform. Hackers are becoming more sophisticated, and the tools they use to compromise sites are more readily available than ever. While no system can be 100% secure, taking these steps can drastically reduce your chances of being hacked.

The incident today underscores just how crucial these measures are. Even though my site was targeted by over a thousand login attempts in a matter of minutes, the protections I had in place—limiting login attempts and blocking IP addresses—ensured that it remained secure.

Security is not just an IT concern—it’s an essential part of running a website. By implementing the right protection measures, you can make the online world a safer place, one website at a time.

]]>