Laravel 12 如何实现简单物联网系统?

Laravel 12 实现简单物联网系统

在 Laravel 12 中构建一个简单的物联网(IoT)系统是可行的。下面我将介绍一个基本的实现方案:

系统架构概述

  1. 设备端:使用微控制器(如ESP8266/ESP32)或Raspberry Pi
  2. 通信协议:HTTP/REST API 或 MQTT
  3. 服务器端:Laravel 12 作为后端
  4. 前端:可选 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();
        }
    }
}

安全考虑

  1. 使用API认证 (Laravel Sanctum/Passport)
  2. 实现设备认证
  3. 使用HTTPS
  4. 限制API访问频率

扩展功能

  1. 设备管理面板
  2. 数据可视化
  3. 报警通知
  4. 历史数据存储和分析

这个实现提供了一个基本的物联网系统框架,可以根据具体需求进行扩展和优化。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值