Laravel 12 实现简单物联网系统
在 Laravel 12 中构建一个简单的物联网(IoT)系统是可行的。下面我将介绍一个基本的实现方案:
系统架构概述
- 设备端:使用微控制器(如ESP8266/ESP32)或Raspberry Pi
- 通信协议:HTTP/REST API 或 MQTT
- 服务器端:Laravel 12 作为后端
- 前端:可选 Blade 模板或 Vue.js/React
实现步骤
1. 创建 Laravel 项目
composer create-project laravel/laravel iot-system
cd iot-system
2. 数据库设置
创建设备数据表迁移:
php artisan make:migration create_devices_table
在迁移文件中定义表结构:
Schema::create('devices', function (Blueprint $table) {
$table->id();
$table->string('name');
$table->string('device_id')->unique();
$table->string('type');
$table->string('location')->nullable();
$table->boolean('status')->default(false);
$table->json('data')->nullable(); // 存储传感器数据
$table->timestamps();
});
3. 创建设备模型和控制器
php artisan make:model Device -mcr
4. 实现API路由
在 routes/api.php
中添加:
Route::prefix('iot')->group(function () {
Route::post('/register', [DeviceController::class, 'register']);
Route::post('/update/{device}', [DeviceController::class, 'update']);
Route::get('/status/{device}', [DeviceController::class, 'status']);
Route::post('/command/{device}', [DeviceController::class, 'command']);
});
5. 设备控制器实现
class DeviceController extends Controller
{
public function register(Request $request)
{
$validated = $request->validate([
'device_id' => 'required|unique:devices',
'type' => 'required',
'name' => 'required'
]);
$device = Device::create($validated);
return response()->json([
'message' => 'Device registered',
'device' => $device
], 201);
}
public function update(Request $request, Device $device)
{
$validated = $request->validate([
'status' => 'sometimes|boolean',
'data' => 'sometimes|json'
]);
$device->update($validated);
return response()->json([
'message' => 'Device updated',
'device' => $device
]);
}
// 其他方法...
}
6. 设备端代码示例 (ESP8266 Arduino)
#include <ESP8266WiFi.h>
#include <ESP8266HTTPClient.h>
#include <WiFiClient.h>
#include <ArduinoJson.h>
const char* ssid = "your_SSID";
const char* password = "your_PASSWORD";
const char* serverUrl = "http://your-laravel-app.com/api/iot";
void setup() {
Serial.begin(115200);
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(1000);
Serial.println("Connecting to WiFi...");
}
// 注册设备
registerDevice();
}
void loop() {
// 读取传感器数据
float temperature = readTemperature();
// 更新数据到服务器
updateDeviceData(temperature);
delay(5000); // 每5秒更新一次
}
void registerDevice() {
if (WiFi.status() == WL_CONNECTED) {
HTTPClient http;
http.begin(serverUrl + "/register");
http.addHeader("Content-Type", "application/json");
String payload = "{\"device_id\":\"ESP8266_001\",\"type\":\"temperature\",\"name\":\"Living Room Sensor\"}";
int httpCode = http.POST(payload);
if (httpCode > 0) {
String response = http.getString();
Serial.println(response);
}
http.end();
}
}
void updateDeviceData(float temp) {
if (WiFi.status() == WL_CONNECTED) {
HTTPClient http;
http.begin(serverUrl + "/update/ESP8266_001");
http.addHeader("Content-Type", "application/json");
String payload = "{\"data\":{\"temperature\":" + String(temp) + "}}";
int httpCode = http.POST(payload);
if (httpCode > 0) {
String response = http.getString();
Serial.println(response);
}
http.end();
}
}
7. 实时通信 (可选)
对于实时性要求高的场景,可以集成MQTT:
composer require bluerhinos/phpmqtt
创建MQTT服务:
use Bluerhinos\phpMQTT;
class MqttService {
public function publish($topic, $message) {
$mqtt = new phpMQTT("mqtt.example.com", 1883, "laravel-client");
if ($mqtt->connect()) {
$mqtt->publish($topic, $message, 0);
$mqtt->close();
}
}
}
安全考虑
- 使用API认证 (Laravel Sanctum/Passport)
- 实现设备认证
- 使用HTTPS
- 限制API访问频率
扩展功能
- 设备管理面板
- 数据可视化
- 报警通知
- 历史数据存储和分析
这个实现提供了一个基本的物联网系统框架,可以根据具体需求进行扩展和优化。