Home / Blog / Reverse Engineering My Coway Air in Production: Performance, Scalabi
Engineering Blueprint • Nov 14, 2026

Reverse Engineering My Coway Air in Production: Performance, Scalabi

Practical engineering guide and architectural blueprint for Reverse Engineering My Coway Air in Production: Performance, Scalabi.

UPTO 50% OFF
Trending:
BrickTry

AI is analyzing your requirement...

Generating custom modules, implementation options, and dynamic clarification questions.

Add Custom Requirement or Module

Add your own specific features, integrations, or components. AI will incorporate them to dynamically generate the next relevant options.

1. Progressive Clarifications

Click to expand & answer

2. Scope Modules & Features (/ Selected)

Click row to expand details · Customize options
✓
✕

Connecting consumer smart home infrastructure to enterprise monitoring systems presents a core engineering challenge: consumer IoT ecosystems are deliberately built as closed gardens, relying on cloud-dependent polling loops, high-latency vendor HTTP APIs, and opaque telemetry payloads.

When operating smart hardware—such as the Coway Airmega series—at scale across commercial environments (data centers, modular office space, cleanrooms), vendor-hosted cloud APIs introduce critical bottlenecks. Latency spikes exceed 2,000ms, rate limits throttle sampling frequency, and unexpected cloud outages leave air quality state machines blind.

To achieve sub-50ms telemetry ingestion, deterministic control, and local resilience during internet partition events, we reverse-engineered the Coway IoCare network protocol. This blueprint covers the protocol mechanics, proxy architecture, state persistence, performance benchmarks, and production-grade code required to run local-first IoT telemetry pipelines at scale.


Protocol Reverse Engineering Mechanics

The Coway IoCare platform relies on two main protocol pathways:

  1. REST/OAuth2 Cloud API: Used by mobile applications for authentication, initial device provisioning, user management, and low-frequency state reads via an AWS Cognito back-end.
  2. AWS IoT Core MQTT Stream: A persistent TLS v1.2 session (Port 8883) established by the physical device directly to an AWS IoT endpoint (a1...-ats.iot.[region].amazonaws.com).
+------------------+         mTLS (Port 8883)          +-----------------------+
|  Coway Airmega   | <-------------------------------> |   AWS IoT Core Endpoint|
|  Physical Device |                                   | (Cloud Infrastructure)|
+------------------+                                   +-----------------------+
         |                                                         |
         | mDNS / Local Proxy Intercept                            | HTTPS / OAuth2
         v                                                         v
+------------------------------------------------------------------------------+
|                    Local Telemetry Proxy & Ingestion Engine                   |
|   - Frida / mitmproxy for Certificate Pinning Bypass                         |
|   - Decoupled MQTT/NATS Ingestion Pipeline                                  |
|   - Redis In-Memory State Cache & TSDB Sync                                  |
+------------------------------------------------------------------------------+

1. Interception and SSL Pinning Bypass

To intercept initial handshake parameters and extract device authorization tokens, we deployed a dynamic instrumented environment:

  • Mobile Traffic Interception: Instrumented the Android IoCare APK inside an Android Virtual Device (AVD) running frida-server.
  • Bypassing Certificate Pinning: Injected custom Frida scripts to hook SSL_verifypeer and Java TrustManagerImpl classes, allowing standard HTTP/HTTPS proxies (mitmproxy) to decrypt traffic passing to api-smart.coway.com.
  • Credential Extraction: Intercepted token payloads yielded an OAuth2 bearer token, device DSN (Data Serial Number), and an AWS Cognito identity pool ID. The app fetches temporary AWS IAM credentials (AccessKeyId, SecretKey, SessionToken) to authenticate directly against AWS IoT MQTT topics.

2. MQTT Topic Topology and Payload Structure

The telemetry payload stream operates over topic patterns structured by device DSN:

# Telemetry Data Stream (Device -> Cloud)
$aws/things/COWAY_{DSN}/shadow/update

# Control Command Topic (Cloud -> Device)
$aws/things/COWAY_{DSN}/shadow/update/delta

The payload utilizes JSON encoded strings containing continuous indoor air quality (IAQ) metrics:

{
  "state": {
    "reported": {
      "dust_pm25": 12,
      "dust_pm10": 28,
      "voc_index": 1,
      "fan_speed": "2",
      "mode": "AUTO",
      "light_status": "ON",
      "filter_life_percentage": 84,
      "error_code": "NONE",
      "rssi": -62
    }
  }
}

Architectural Comparison: Ingestion Models

When deploying IoT controls into enterprise environments, engineering teams must evaluate three distinct integration paths:

Architectural Metric Official Vendor Cloud REST API Reverse-Engineered Cloud MQTT Local Edge Proxy / Local Broker
Ingestion Latency 1,500ms – 5,000ms 150ms – 400ms < 15ms
Network Partition Tolerance None (Fails on WAN outage) None (Fails on WAN outage) Complete (Local LAN operation)
Rate Limit Overhead Strict (e.g., 60 req/min) AWS IoT limits (~100 msgs/sec) Hardware NIC limits only
Auth Volatility High (Cognito token refresh) Moderate (AWS IAM STS refresh) Zero (Static mTLS / LAN Local)
CPU Memory Footprint Low (Stateless HTTP clients) Medium (Long-polling WS/MQTT) Minimal (< 25MB Go binary)
State Synchronization Polling Lag / Eventual Real-time push (/shadow) Real-time atomic memory mirror

Production Implementations

Snippet 1: High-Throughput Go MQTT Telemetry Ingestion Worker

This Go service establishes a persistent, auto-reconnecting MQTT client pipeline using extracted AWS IAM credentials or local proxy streams. It deserializes incoming device updates, calculates moving averages for air quality metrics, and streams structured state changes directly to a Redis state cache.

package main

import (
	"context"
	"crypto/tls"
	"encoding/json"
	"fmt"
	"log"
	"os"
	"os/signal"
	"syscall"
	"time"

	mqtt "github.com/eclipse/paho.mqtt.golang"
	"github.com/redis/go-redis/v9"
)

type DeviceReportedState struct {
	DustPM25     int    `json:"dust_pm25"`
	DustPM10     int    `json:"dust_pm10"`
	VOCIndex     int    `json:"voc_index"`
	FanSpeed     string `json:"fan_speed"`
	Mode         string `json:"mode"`
	FilterLife   int    `json:"filter_life_percentage"`
	ErrorCode    string `json:"error_code"`
}

type ShadowPayload struct {
	State struct {
		Reported DeviceReportedState `json:"reported"`
	} `json:"state"`
}

type TelemetryEngine struct {
	mqttClient mqtt.Client
	redisClient *redis.Client
	deviceDSN  string
}

func NewTelemetryEngine(brokerURI, deviceDSN, redisAddr string) *TelemetryEngine {
	rdb := redis.NewClient(&redis.Options{
		Addr:         redisAddr,
		DialTimeout:  5 * time.Second,
		ReadTimeout:  3 * time.Second,
		WriteTimeout: 3 * time.Second,
	})

	opts := mqtt.NewClientOptions()
	opts.AddBroker(brokerURI)
	opts.SetClientID(fmt.Sprintf("coway_ingest_%s_%d", deviceDSN, time.Now().Unix()))
	opts.SetKeepAlive(30 * time.Second)
	opts.SetPingTimeout(10 * time.Second)
	opts.SetAutoReconnect(true)
	opts.SetMaxReconnectInterval(15 * time.Second)

	// TLS configuration for AWS IoT / Private Edge TLS
	opts.SetTLSConfig(&tls.Config{
		InsecureSkipVerify: false,
		MinVersion:         tls.VersionTLS12,
	})

	engine := &TelemetryEngine{
		redisClient: rdb,
		deviceDSN:  deviceDSN,
	}

	opts.SetDefaultPublishHandler(engine.handleIncomingTelemetry)
	engine.mqttClient = mqtt.NewClient(opts)

	return engine
}

func (te *TelemetryEngine) Start(ctx context.Context) error {
	if token := te.mqttClient.Connect(); token.Wait() && token.Error() != nil {
		return fmt.Errorf("MQTT connection failed: %w", token.Error())
	}

	topic := fmt.Sprintf("$aws/things/COWAY_%s/shadow/update", te.deviceDSN)
	if token := te.mqttClient.Subscribe(topic, 1, nil); token.Wait() && token.Error() != nil {
		return fmt.Errorf("MQTT subscription failed: %w", token.Error())
	}

	log.Printf("[INGEST] Successfully subscribed to topic: %s", topic)
	return nil
}

func (te *TelemetryEngine) handleIncomingTelemetry(client mqtt.Client, msg mqtt.Message) {
	var payload ShadowPayload
	if err := json.Unmarshal(msg.Payload(), &payload); err != nil {
		log.Printf("[ERROR] Telemetry payload decode failed: %v", err)
		return
	}

	state := payload.State.Reported
	ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second)
	defer cancel()

	pipe := te.redisClient.Pipeline()
	redisKey := fmt.Sprintf("coway:device:%s:state", te.deviceDSN)

	pipe.HSet(ctx, redisKey, map[string]interface{}{
		"pm25":        state.DustPM25,
		"pm10":        state.DustPM10,
		"voc":         state.VOCIndex,
		"fan_speed":   state.FanSpeed,
		"mode":        state.Mode,
		"filter_life": state.FilterLife,
		"last_seen":   time.Now().UTC().Format(time.RFC3339),
	})

	// Publish state change to high-speed internal event bus
	pipe.Publish(ctx, "events:air_quality:update", fmt.Sprintf("%s|PM25:%d|VOC:%d", te.deviceDSN, state.DustPM25, state.VOCIndex))

	_, err := pipe.Exec(ctx)
	if err != nil {
		log.Printf("[ERROR] Redis write failed for device %s: %v", te.deviceDSN, err)
		return
	}

	log.Printf("[TELEMETRY] Device %s -> PM2.5: %d µg/m³ | Fan: %s | Mode: %s",
		te.deviceDSN, state.DustPM25, state.FanSpeed, state.Mode)
}

func main() {
	broker := os.Getenv("MQTT_BROKER_URL") // tls://a1xxx.iot.us-east-1.amazonaws.com:8883
	dsn := os.Getenv("COWAY_DEVICE_DSN")
	redisHost := os.Getenv("REDIS_HOST")

	if broker == "" || dsn == "" || redisHost == "" {
		log.Fatal("Missing required environment variables: MQTT_BROKER_URL, COWAY_DEVICE_DSN, REDIS_HOST")
	}

	engine := NewTelemetryEngine(broker, dsn, redisHost)
	ctx, cancel := context.WithCancel(context.Background())
	defer cancel()

	if err := engine.Start(ctx); err != nil {
		log.Fatalf("Fatal execution error: %v", err)
	}

	sigChan := make(chan os.Signal, 1)
	signal.Notify(sigChan, syscall.SIGINT, syscall.SIGTERM)
	<-sigChan

	log.Println("[SHUTDOWN] Gracefully terminating ingestion pipeline...")
	engine.mqttClient.Disconnect(250)
}

Snippet 2: Production Multi-Stage Dockerfile with Edge Telemetry Proxy Daemon

To run this telemetry edge service in high-density production environments, we utilize a minimal multi-stage Alpine/Scratch image containing static CA certificates, non-root system users, and tight memory limits.

# Stage 1: Build static Go binary
FROM golang:1.23-alpine AS builder

RUN apk add --no-cache ca-certificates git tzdata

WORKDIR /app

# Optimize layer caching
COPY go.mod go.sum ./
RUN go mod download

COPY . .

# Compile fully static executable
RUN CGO_ENABLED=0 GOOS=linux GOARCH=amd64 go build \
    -ldflags="-w -s -X main.Version=1.4.0" \
    -o /app/coway_telemetry_proxy ./cmd/main.go

# Stage 2: Runtime Container
FROM scratch

# Import system dependencies from builder
COPY --from=builder /etc/ssl/certs/ca-certificates.crt /etc/ssl/certs/
COPY --from=builder /usr/share/zoneinfo /usr/share/zoneinfo
COPY --from=builder /etc/passwd /etc/passwd

COPY --from=builder /app/coway_telemetry_proxy /usr/local/bin/coway_telemetry_proxy

# Unprivileged security context
USER 10001:10001

ENV MQTT_BROKER_URL="" \
    COWAY_DEVICE_DSN="" \
    REDIS_HOST="127.0.0.1:6379"

ENTRYPOINT ["/usr/local/bin/coway_telemetry_proxy"]

Performance, Failure Modes, and Edge Case Mitigation

Building production IoT integrations on top of reverse-engineered protocols requires defensive software design to handle common physical and network failure modes:

+-------------------+      TCP Idle Timeout       +-----------------------+
|  Local Ingestion  | --------------------------> | AWS IoT Gateway       |
|  Daemon (Go)      | <-------------------------- | (Cloud Broker)        |
+-------------------+   PingResp (Keep-Alive)     +-----------------------+
          |                                                   |
          | Connection Lost (WAN Partition)                   |
          v                                                   v
+-------------------------------------------------------------------------+
|                  Exponential Backoff & Buffer Circuit                   |
|  1. Detached Network Recovery (Interval: 1s -> 2s -> 4s -> max 60s)     |
|  2. Fallback to Local mDNS/CoAP Broadcast Discovery                     |
|  3. Drain Ring-Buffer State Snapshot to Persistent Cache                |
+-------------------------------------------------------------------------+

1. Token Expiration and AWS STS Credentials Refresh

AWS Cognito tokens generated by Coway expire every hour. If your ingestion proxy authenticates using temporary AWS IAM keys (STS:AssumeRoleWithWebIdentity), the proxy will face MQTT_CONNECT_REFUSED_NOT_AUTHORIZED errors upon reconnection attempts after 3600 seconds.

  • Mitigation: Wrap the MQTT client initialization inside a credential provider pipeline that intercepts reconnect events, checks STS token TTL, re-authenticates against the Coway Cognito endpoint, and updates the TLS configuration on the fly before initiating the TCP socket handshake.

2. TCP Keep-Alive and Quiet Disconnections

Mobile IoT hardware behind home NAT gateways frequently suffers from silent TCP connection drops. AWS IoT Core drops inactive sockets after 1.5 times the configured MQTT keep-alive interval.

  • Mitigation: Explicitly configure Paho MQTT client keep-alive timers to 30s with a tight ping response timeout of 10s. Force explicit socket teardowns if two consecutive PINGRESP packets fail to return.

3. State Desynchronization During WAN Partitions

When network connectivity breaks, physical interactions with the Coway device (such as pressing the manual fan speed button) update the local appliance state, but cloud shadow updates fail. When WAN connectivity resumes, the AWS IoT shadow might publish stale state deltas back to the device.

  • Mitigation: Implement a local state versioning timestamp (last_updated_epoch). Ignore state updates from the cloud broker if the reported payload timestamp is older than the current local Redis mirror timestamp.

How BrickTry Helps You Build and Scale This

Deploying non-standard IoT protocols, reverse-engineered microservices, and edge processing engines requires rapid iteration, automated code scaffolding, and zero friction between architecture and runtime execution. BrickTry provides the complete engineering workspace to accelerate these implementations:

  • Interactive In-Browser Lab Sandbox (/lab): Instantly test, scaffold, and preview Go/Node/Python edge daemons inside a browser runtime. Test custom MQTT traffic, decode binary/JSON streams, and run mock Redis instances without setting up local Docker environments.
  • Autonomous AI Dev Pairing: Scaffolds boilerplate integration code, converts opaque API JSON responses into fully typed TypeScript/Go structs, generates production Dockerfiles, and runs automated AST refactoring to clean up custom code paths.
  • Senior Full-Stack Platform Engineering Pods: Work alongside senior systems architects who assist with enterprise hardware protocol isolation, reverse-engineering protocol audits, security vulnerability remediation, and production readiness checks.
  • Unified Importer: Import third-party IoT wrappers, legacy node libraries, or GitHub repositories directly into your project workspace with one click.
  • 100% IP & Source Code Ownership: Retain absolute control of your codebases, Docker build manifests, deployment pipelines, and database schemas with no vendor lock-in—delivered straight to your private GitHub repos.

Frequently Asked Questions

1. How do you bypass SSL Certificate Pinning on modern Coway mobile apps running TLS v1.3?

Modern Android/iOS applications implement certificate pinning using native libraries (e.g., OkHttp CertificatePinner or BoringSSL). We bypass this by executing dynamic binary instrumentation via Frida. On an Android emulator running x86_64 image with root access, Frida hooks the underlying C/C++ SSL_CTX_set_custom_verify or Java TrustManagerImpl methods at runtime, replacing the app's custom certificate verification logic with a permissive trust manager that accepts intercepting CA certificates from tools like mitmproxy.

2. Is local control possible without routing traffic through Coway's AWS IoT Core servers?

Yes, but with caveats. Coway devices running recent firmware maintain local UDP/mDNS discovery listeners on the local subnetwork (Port 8888 or 5683 CoAP). By broadcasting structured discovery strings over UDP port 8888, you can discover local Coway appliances, retrieve local IP bindings, and issue basic command frames directly over the LAN without passing through AWS IoT—providing complete immunity against WAN outages.

3. How does local MQTT ingestion scale when monitoring hundreds of devices across multiple sites?

When scaling past individual devices to multi-site enterprise monitoring, running individual MQTT connections per device introduces network management overhead. The standard architectural solution is deploying local edge gateways (e.g., lightweight Mosquitto or EMQX brokers running on edge nodes) that aggregate local device streams, normalize payloads into protobuf or JSON streams, and forward aggregated telemetry back to a centralized NATS or Kafka cluster using a single mTLS bridge connection.

Build, Test, and Scale This on BrickTry

BrickTry pairs you with autonomous AI scaffolding supervised by dedicated senior full-stack software engineers in an interactive in-browser development sandbox (/lab). Test, build, and deploy production-grade software with 100% source code ownership and zero vendor lock-in.

Launch Interactive Requirement Builder →

❤️

Support BrickTry Platform & Engineering Development

Help us build, maintain, and advance our AI engineering platform. Every donation fuels open-source tooling, infrastructure, and continuous improvements.

$
Donor Details
Promote Your Brand / Link Wall

UPI / Credit & Debit Cards / Netbanking
Razorpay
Secure 256-bit encrypted checkout
View Leaderboard & Wall

Hey!

Welcome, Let's chat —
start a new conversation
below.

Recent conversations
See all

We’re online to assist you with your project...

Abhishek A Agrawal • Just now

Start a conversation

Quick contact setup

Please share your details below so our team can reach you.

Worldwide supported

🔒 Your info is only used to connect with our support team.

Abhishek A Agrawal

Online & Ready to Assist

BrickTry

Select a Date & Time Enter Details You are Scheduled

Technical Consultation

Video link provided upon confirmation
SUN
MON
TUE
WED
THU
FRI
SAT
Time zone:

,

•

Google Meet
Default HD Video
Calendar invitations with direct video links will be sent here.

You are scheduled

A calendar invitation has been sent to your email address.