# Lambda-IoT Core

This repository contains a minimal Go REST service used as the backend for the Lambda-IoT project.

Repository: https://git.piskot.si/SeminarM2/lambdaiot-core

## Features ✅

- HTTP API with health, greeting, auth, device CRUD, sensor creation, MQTT ping, and stored message retrieval
- JWT-based auth middleware with demo login (`admin`/`password`)
- MQTT client with startup publish and best-effort subscription to persist `state:` topics into SQLite
- SQLite sidecar (file) for recent MQTT state messages
- Multi-stage `Dockerfile` (CGO-enabled for sqlite3) and `Makefile` for common tasks
- `test/docker-compose.yml` spins up MySQL, Mosquitto, phpMyAdmin, and the server for local integration

---

## Quickstart 🔧

Build and run locally:

```bash
make build
./bin/server
```

Run tests:

```bash
make test
```

Build Docker image:

```bash
make docker-build
```

Then run it:

```bash
docker run -p 8080:8080 lambdaiot-core:latest
```

Integration stack (MySQL + Mosquitto + server):

```bash
cd test
docker compose up -d --build
```

The compose file seeds the database from `ai-improved.sql` and exposes:
- API on http://localhost:8080
- MySQL on localhost:3306 (root/rootpass)
- Mosquitto on localhost:1883
- phpMyAdmin on http://localhost:8081

### Endpoints

- `GET /health` — returns `{ "status": "ok" }`
- `GET /hello` — greeting JSON
- `POST /login` — demo login, body `{ "username": "admin", "password": "password" }`, returns `{ "token": "..." }`
- `GET /protected` — JWT required
- `GET /devices` — list devices (public) / `POST /devices`, `GET/PUT/DELETE /devices/:id` (JWT)
- Sensors (JWT): `GET /sensors`, `GET /sensors/:id`, `POST /sensors`, `PUT /sensors/:id`, `DELETE /sensors/:id`
- Actors (JWT): `GET /actors`, `GET /actors/:id`, `POST /actors`, `PUT /actors/:id`, `DELETE /actors/:id`
- Sensor readings (JWT): `GET /sensor-readings`, `GET /sensor-readings/:id`, `POST /sensor-readings`, `PUT /sensor-readings/:id`, `DELETE /sensor-readings/:id` (optional `sensor_id` filter and pagination via `limit`, `page`)
- `GET /mqttping` — publish timestamp to MQTT default topic (JWT)
- `GET /messages` — last stored MQTT state messages from SQLite (JWT)

### Environment

- `JWT_SECRET` — (optional) secret used to sign tokens; defaults to `secret` for local/dev use
- `MQTT_*` — configure broker, client ID, topic, username/password
- `DB_*` — MySQL connection overrides; see `config.toml` defaults in `internal/config`

---