, , , , , , , , , , ,

LYWSD03MMC BLE Climate Bridge API | Raspberry Pi IoT Projesi

LYWSD03MMC BLE Climate Bridge API | Raspberry Pi IoT Projesi

Loruv LYWSD03MMC BLE Climate Bridge API

Github Repo: https://github.com/emrecagri/Loruv-LYWSD03MMC-Ble-Climate-Bridge-Api

Türkçe

Bluetooth Sensörlerini REST API’ye Dönüştüren Bir IoT Köprüsü

Loruv LYWSD03MMC BLE Climate Bridge API, Xiaomi LYWSD03MMC Bluetooth Low Energy sıcaklık ve nem sensörlerinden alınabilen verileri otomatik olarak toplayıp modern bir REST API / JSON servisi üzerinden sunmak amacıyla geliştirdiğim açık kaynak bir IoT projesidir.

Projenin temel amacı; Bluetooth tabanlı sensörleri yalnızca üreticinin mobil uygulamasına bağlı kalmadan, Raspberry Pi üzerinde çalışan merkezi ve hafif bir servis aracılığıyla web siteleri, dashboard’lar, otomasyon sistemleri ve farklı uygulamalar tarafından kullanılabilir hale getirmektir.


Projenin Amacı

LYWSD03MMC sensörleri sıcaklık ve nem ölçümü yapabilen oldukça küçük BLE cihazlarıdır. Ancak bu verilerin doğrudan web uygulamalarında veya kendi geliştirdiğim servislerde kullanılabilmesi için arada Bluetooth ile iletişim kuran bir katmana ihtiyaç vardır.

Bu projede Raspberry Pi üzerindeki Bluetooth donanımını kullanarak sensörleri otomatik keşfeden, cihazlardan okunabilen verileri toplayan ve bunları standart HTTP endpoint’leri üzerinden sunan bağımsız bir servis geliştirdim.

Genel mimari şu şekilde çalışmaktadır:

LYWSD03MMC Sensörleri
        ↓
Bluetooth Low Energy
        ↓
Raspberry Pi / BlueZ
        ↓
Loruv BLE Climate Bridge API
        ↓
REST API / JSON
        ↓
Homepage / Web Sitesi / Script / Otomasyon

Öne Çıkan Özellikler

Dinamik Sensör Keşfi

Sistem belirli MAC adreslerine veya sabit sayıda sensöre bağlı değildir.

Çevrede bulunan tüm uyumlu:

LYWSD03MMC

cihazları otomatik olarak keşfeder.

Yeni bir sensör sisteme eklendiğinde uygulama kodunda değişiklik yapmaya gerek kalmadan API çıktısına dahil edilir.

MAC adresleri yalnızca istenirse cihazlara:

  • Ev
  • Çatı
  • Salon
  • Ofis

gibi kullanıcı dostu isimler vermek amacıyla kullanılabilir.


Read-Only Bluetooth Tasarımı

Projeyi mümkün olduğunca güvenli ve sensörlere müdahale etmeyen bir yapıda geliştirdim.

API yalnızca okunabilir BLE/GATT verilerini toplar.

Servis bilinçli olarak:

  • cihaz ayarlarını değiştirmez,
  • sıcaklık birimini değiştirmez,
  • firmware yüklemez,
  • cihaz saatini değiştirmez,
  • geçmiş kayıtlarını silmez,
  • sensöre GATT write işlemi göndermez.

Bu sayede servis yalnızca bir veri okuma ve köprü katmanı olarak çalışır.


Sensörlerden Alınan Veriler

API yalnızca sıcaklık ve nemi değil, sensörden doğrudan okunabilen mümkün olduğunca fazla veriyi döndürmektedir.

Bunlardan bazıları:

  • Güncel sıcaklık
  • Bağıl nem
  • Pil voltajı
  • Sensörün raporladığı pil yüzdesi
  • Bluetooth sinyal seviyesi (RSSI)
  • Cihaz modeli
  • Firmware sürümü
  • Hardware sürümü
  • Software sürümü
  • Üretici bilgisi
  • Bluetooth cihaz adı
  • Ekran sıcaklık birimi
  • Cihaz zamanı
  • Comfort profile değerleri
  • Geçmiş kayıt indeksleri
  • Son bir saate ait maksimum sıcaklık
  • Son bir saate ait minimum sıcaklık
  • Son bir saate ait maksimum nem
  • Son bir saate ait minimum nem
  • BLE advertisement verileri
  • Okunabilen GATT characteristic değerleri
  • Okunabilen GATT descriptor değerleri
  • Ham HEX ve byte verileri

Bu yapı sayesinde API hem basit uygulamalar için okunabilir alanlar hem de daha gelişmiş projeler için düşük seviyeli BLE verileri sunmaktadır.


Akıllı Cache Sistemi

Bluetooth sensörlerinin gereksiz yere sürekli sorgulanmasını istemediğim için servis içerisinde RAM tabanlı bir TTL cache sistemi geliştirdim.

Varsayılan olarak sensör verileri:

60 saniye

cache üzerinde tutulmaktadır.

Örneğin ilk API isteğinde sensörler Bluetooth üzerinden okunur.

Sonraki istekler cache süresi dolmadığı sürece doğrudan RAM üzerinden cevaplanır ve Bluetooth bağlantısı yeniden kurulmaz.

Bu yaklaşım:

  • gereksiz BLE trafiğini azaltır,
  • sensörlerle yapılan bağlantı sayısını düşürür,
  • API cevap süresini hızlandırır,
  • Raspberry Pi üzerindeki Bluetooth yükünü azaltır.

Eşzamanlı İstek Koruması

API’ye aynı anda birden fazla istek geldiğinde her istek ayrı Bluetooth taraması başlatmaz.

Projede asyncio.Lock tabanlı bir single-flight refresh mekanizması bulunmaktadır.

Örneğin aynı anda 10 API isteği gelirse:

10 API isteği
      ↓
1 Bluetooth yenilemesi
      ↓
1 RAM cache
      ↓
Tüm isteklere aynı snapshot

şeklinde çalışır.

Bu nedenle uygulama bilinçli olarak tek Uvicorn worker ile çalıştırılmaktadır.


REST API

Servis FastAPI kullanılarak geliştirildi.

Temel endpoint’ler:

GET /api/v1/lywsd03mmc-devices

Çevrede bulunan tüm uyumlu sensörleri ve verilerini döndürür.

GET /api/v1/lywsd03mmc-devices/{device_id}

Belirli bir sensöre ait verileri döndürür.

GET /api/v1/bridge-status

API servis ve cache durumunu gösterir.

GET /api/v1/bridge-info

Servisin desteklediği özellikler ve teknik bilgiler hakkında bilgi verir.

FastAPI sayesinde ayrıca otomatik olarak:

/docs

üzerinden Swagger arayüzü ve:

/openapi.json

üzerinden OpenAPI şeması sunulmaktadır.


Homepage Dashboard Entegrasyonu

Projeyi kendi Raspberry Pi dashboard yapımda kullandığım Homepage ile de entegre ettim.

Homepage üzerinde sensörler yan yana iki ayrı kart şeklinde gösterilebilmektedir.

Kartlarda örneğin:

Ev
25.9 °C
%45 Nem
2.57 V
-69 dBm

Son 1 Saat
Max: 26.1 °C
Min: 26.0 °C
Nem Max: %45
Nem Min: %45

gibi bilgiler görüntülenebilir.

Bu sayede Bluetooth sensörleri doğrudan kişisel sunucu dashboard’unun bir parçası haline gelmektedir.


Docker ve Portainer

Proje tamamen Docker container içerisinde çalışabilecek şekilde hazırlanmıştır.

Container, Raspberry Pi üzerinde çalışan BlueZ servisine Linux D-Bus üzerinden bağlanmaktadır.

Bu nedenle container içerisinde ayrı bir Bluetooth servisi çalıştırılması gerekmez.

Uygulama:

  • Docker
  • Docker Compose
  • Portainer

üzerinden çalıştırılabilir.

Ayrıca GitHub Actions kullanılarak otomatik Docker image üretim süreci oluşturdum.

Image hem:

linux/amd64

hem de:

linux/arm64

mimarileri için oluşturulmaktadır.

Bu sayede aynı Docker image Raspberry Pi 5 gibi ARM64 cihazlarda veya standart x86 Linux sunucularda kullanılabilmektedir.


GitHub Container Registry

Docker image GitHub Container Registry üzerinden dağıtılmaktadır:

ghcr.io/emrecagri/loruv-lywsd03mmc-ble-climate-bridge-api

Yeni bir sürüm GitHub’a gönderildiğinde GitHub Actions otomatik olarak:

Source Code
↓
Docker Build
↓
AMD64 + ARM64
↓
GHCR Publish

sürecini gerçekleştirmektedir.


Kullanılan Teknolojiler

Backend

  • Python
  • FastAPI
  • Uvicorn
  • Pydantic

Bluetooth

  • Bluetooth Low Energy
  • Bleak
  • BlueZ
  • Linux D-Bus
  • GATT

Container

  • Docker
  • Docker Compose
  • Portainer

CI/CD

  • GitHub
  • GitHub Actions
  • GitHub Container Registry
  • Docker Buildx
  • QEMU

Dashboard

  • Homepage
  • Custom API Widget

Donanım

  • Raspberry Pi 5
  • LYWSD03MMC BLE sıcaklık ve nem sensörleri

Projenin Kazandırdıkları

Bu projede özellikle;

  • BLE cihazlarla düşük seviyeli haberleşme,
  • GATT servis ve characteristic analizi,
  • binary verilerin decode edilmesi,
  • asenkron Python programlama,
  • API mimarisi,
  • cache ve concurrency yönetimi,
  • Docker container geliştirme,
  • Linux BlueZ / D-Bus entegrasyonu,
  • ARM64 container oluşturma,
  • GitHub Actions ile CI/CD,
  • IoT verilerinin dashboard sistemlerine aktarılması

konularında uçtan uca bir yapı geliştirdim.

Proje aynı zamanda daha sonra geliştireceğim alarm, takip ve otomasyon servisleri için merkezi bir sensör API katmanı oluşturmaktadır.


Proje Durumu

Durum: Aktif / Çalışır durumda
Dağıtım: Raspberry Pi + Docker + Portainer
Lisans: MIT License
API: FastAPI / REST / JSON
Kaynak Kod: GitHub
Container: GitHub Container Registry

Bu proje bağımsız ve resmi olmayan bir açık kaynak projesidir. Xiaomi tarafından geliştirilmemiş, desteklenmemiş veya onaylanmamıştır. Ürün ve model isimleri yalnızca cihaz uyumluluğunu belirtmek amacıyla kullanılmaktadır.


English

Lightweight BLE-to-REST Bridge for Climate Sensors

Loruv LYWSD03MMC BLE Climate Bridge API is an open-source IoT project I developed to automatically collect data from LYWSD03MMC Bluetooth Low Energy temperature and humidity monitors and expose that information through a modern REST API / JSON service.

The main goal of the project is to make Bluetooth-based climate sensors available to websites, dashboards, automation systems and custom applications without depending entirely on the manufacturer’s mobile application.


Project Goal

LYWSD03MMC monitors are compact BLE devices capable of measuring temperature and humidity.

However, using their data directly inside web applications or custom services requires an intermediate layer capable of communicating with Bluetooth devices.

For this project, I developed a lightweight service running on Raspberry Pi that automatically discovers compatible BLE sensors, collects directly readable data and exposes it through standard HTTP endpoints.

The architecture is:

LYWSD03MMC Sensors
        ↓
Bluetooth Low Energy
        ↓
Raspberry Pi / BlueZ
        ↓
Loruv BLE Climate Bridge API
        ↓
REST API / JSON
        ↓
Homepage / Website / Scripts / Automation

Key Features

Dynamic Sensor Discovery

The system is not limited to specific MAC addresses or a fixed number of devices.

It automatically discovers all nearby compatible:

LYWSD03MMC

devices.

If another compatible monitor is added later, it can automatically appear in the API without changing the application source code.

MAC addresses are optionally used only to provide user-friendly names such as:

  • Living Room
  • Roof
  • Office
  • Bedroom

They are not used as an allow-list.


Read-Only Bluetooth Design

The project was intentionally designed as a read-only BLE client.

The application does not intentionally:

  • modify device configuration,
  • change temperature units,
  • update device time,
  • erase history,
  • flash firmware,
  • install custom firmware,
  • perform GATT write operations.

Its responsibility is simply to discover sensors, read available information and provide that data to other applications.


Sensor Data

The API does not only return temperature and humidity.

It attempts to expose as much directly readable information as possible, including:

  • Current temperature
  • Relative humidity
  • Battery voltage
  • Firmware-reported battery percentage
  • RSSI signal strength
  • Device model
  • Firmware revision
  • Hardware revision
  • Software revision
  • Manufacturer information
  • Bluetooth device name
  • Display temperature unit
  • Device clock
  • Comfort profile
  • History indexes
  • Last-hour maximum temperature
  • Last-hour minimum temperature
  • Last-hour maximum humidity
  • Last-hour minimum humidity
  • BLE advertisement data
  • Readable GATT characteristics
  • Readable GATT descriptors
  • Raw HEX and byte data

This allows the API to serve both simple applications and more advanced Bluetooth integrations.


Intelligent RAM Cache

To avoid unnecessarily querying Bluetooth sensors continuously, I implemented an in-memory TTL cache.

The default cache lifetime is:

60 seconds

The first API request performs a BLE scan and reads the sensors.

Subsequent requests within the TTL are returned directly from RAM without reconnecting to the Bluetooth devices.

This reduces:

  • unnecessary BLE traffic,
  • sensor connections,
  • API response times,
  • Bluetooth workload on the Raspberry Pi.

Concurrent Request Protection

The API also implements an asynchronous single-flight refresh mechanism using asyncio.Lock.

If multiple API clients request fresh data at the same time, the service does not start multiple independent BLE scans.

Instead:

Multiple API requests
        ↓
Single BLE refresh
        ↓
Shared RAM cache
        ↓
Same snapshot returned to clients

For this reason, the production container intentionally runs with a single Uvicorn worker.


REST API

The backend was developed with FastAPI.

Main endpoints include:

GET /api/v1/lywsd03mmc-devices

Returns all discovered compatible monitors.

GET /api/v1/lywsd03mmc-devices/{device_id}

Returns information for a specific device.

GET /api/v1/bridge-status

Returns service and cache status without triggering a Bluetooth scan.

GET /api/v1/bridge-info

Returns technical information and supported features.

FastAPI also automatically provides:

/docs

for Swagger UI and:

/openapi.json

for the OpenAPI schema.


Homepage Dashboard Integration

The bridge is also integrated with the Homepage dashboard running on my Raspberry Pi environment.

Sensor information can be displayed as two side-by-side climate cards containing:

  • Current temperature
  • Humidity
  • Battery voltage
  • RSSI
  • Last-hour maximum temperature
  • Last-hour minimum temperature
  • Last-hour maximum humidity
  • Last-hour minimum humidity

This makes the BLE monitors a native part of the home-server dashboard.


Docker and Portainer

The entire service is containerized.

The Docker container communicates with the host Linux BlueZ service through D-Bus, allowing the host operating system to remain responsible for the physical Bluetooth adapter.

The project supports:

  • Docker
  • Docker Compose
  • Portainer

The production image is built for both:

linux/amd64
linux/arm64

making it suitable for ARM64 Raspberry Pi systems as well as standard x86-64 Linux servers.


CI/CD and GitHub Container Registry

I also implemented an automated multi-platform container build pipeline using GitHub Actions.

The workflow automatically:

Git Push
↓
GitHub Actions
↓
Docker Buildx
↓
AMD64 + ARM64 Builds
↓
GitHub Container Registry

The published image is available from:

ghcr.io/emrecagri/loruv-lywsd03mmc-ble-climate-bridge-api

Technologies

Backend

  • Python
  • FastAPI
  • Uvicorn
  • Pydantic

Bluetooth / IoT

  • Bluetooth Low Energy
  • Bleak
  • BlueZ
  • Linux D-Bus
  • GATT

Infrastructure

  • Docker
  • Docker Compose
  • Portainer

CI/CD

  • GitHub
  • GitHub Actions
  • GitHub Container Registry
  • Docker Buildx
  • QEMU

Dashboard

  • Homepage
  • Custom API Widget

Hardware

  • Raspberry Pi 5
  • LYWSD03MMC BLE climate monitors

What I Built and Learned

This project combines multiple areas of software and infrastructure development, including:

  • Low-level BLE communication
  • GATT service and characteristic analysis
  • Binary data decoding
  • Asynchronous Python
  • REST API design
  • Cache and concurrency management
  • Docker container development
  • Linux BlueZ and D-Bus integration
  • ARM64 container builds
  • CI/CD with GitHub Actions
  • IoT dashboard integration

It also provides a reusable central sensor-data layer for future monitoring, notification and automation services.


Project Information

Status: Active / Working
Deployment: Raspberry Pi + Docker + Portainer
License: MIT License
API: FastAPI / REST / JSON
Source Code: GitHub
Container Registry: GitHub Container Registry

This is an independent and unofficial open-source project. It is not affiliated with, sponsored by or endorsed by Xiaomi. Product and model names are used solely to describe device compatibility.

Bir yanıt yazın

E-posta adresiniz yayınlanmayacak. Gerekli alanlar * ile işaretlenmişlerdir



    Şimdi Ara +90 551 000 17 59