
在树莓派上,我们首先需要从本地文件读取数据(例如mac地址和rssi值),将其组织成python字典,然后转换为json格式。关键在于,当需要将数据作为请求体发送到服务器时,应使用http post方法,并确保设置正确的content-type头部。
以下是优化后的Python代码,它读取指定路径的文本文件,将内容解析为MAC地址字典,然后以JSON格式通过POST请求发送到Laravel后端:
import json
import requests
import os
def send_mac_data_to_laravel(laravel_base_url, data_file_path="/home/pi/Desktop/Progetti SIoTD/Bluetooth/device.txt"):
"""
读取MAC地址数据,转换为JSON,并通过POST请求发送至Laravel。
Args:
laravel_base_url (str): Laravel API的基URL,例如 "http://your_laravel_ip_or_domain"。
data_file_path (str): 包含MAC地址和RSSI值的文本文件路径。
"""
mac_dict = {}
if not os.path.exists(data_file_path):
print(f"错误: 数据文件未找到于 {data_file_path}")
return
try:
with open(data_file_path, "r") as file:
for line_content in file:
parts = line_content.strip().split()
if parts:
mac = parts[0]
values = parts[1:] # RSSI值列表
if mac in mac_dict:
mac_dict[mac].extend(values) # 将新的RSSI值添加到现有列表
else:
mac_dict[mac] = values
print("已处理数据:", mac_dict)
# 将Python字典转换为JSON字符串
json_obj = json.dumps(mac_dict, indent=4)
# 定义请求头部,声明发送的是JSON数据
headers = {'Content-Type': 'application/json'}
# 使用POST方法发送JSON数据作为请求体
# 目标URL应指向Laravel API路由,例如 /api/dictionary
response = requests.post(f"{laravel_base_url}/api/dictionary", data=json_obj, headers=headers)
print("Laravel 响应状态码:", response.status_code)
print("Laravel 响应体:", response.text)
except FileNotFoundError:
print(f"错误: 数据文件未找到于 {data_file_path}")
except json.JSONDecodeError:
print("错误: 无法将数据编码为JSON。")
except requests.exceptions.RequestException as e:
print(f"发送数据到Laravel时发生网络错误: {e}")
except Exception as e:
print(f"发生意外错误: {e}")
# 示例用法:
# 假设Laravel运行在IP为192.168.1.100的服务器上
# laravel_base_url = "http://192.168.1.100"
# send_mac_data_to_laravel(laravel_base_url)代码说明:
Laravel提供了一套强大的机制来处理传入的HTTP请求,包括JSON数据。我们需要配置路由以监听POST请求,并在控制器中解析和处理这些数据。
在routes/api.php文件中定义一个POST路由,以便接收来自树莓派的JSON数据。由于是API请求,通常放在api.php中,它会自动带有/api前缀。
立即学习“Python免费学习笔记(深入)”;
// routes/api.php
<?php
use App\Http\Controllers\DictionaryController;
use Illuminate\Support\Facades\Route;
// 定义一个POST路由来接收MAC地址数据
Route::post('dictionary', [DictionaryController::class, 'store'])->name('dictionary.store');
// 如果你还需要一个GET路由来展示数据(例如从数据库中读取),可以这样定义:
Route::get('dictionary', [DictionaryController::class, 'index'])->name('dictionary.index');在app/Http/Controllers/DictionaryController.php中,store方法将负责接收和处理POST请求发送的JSON数据。
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Log; // 用于日志记录
class DictionaryController extends Controller
{
/**
* 接收并处理来自树莓派的MAC地址JSON数据。
*
* @param \Illuminate\Http\Request $request
* @return \Illuminate\Http\JsonResponse
*/
public function store(Request $request)
{
// 1. 验证请求是否为JSON格式
if (!$request->isJson()) {
Log::warning('收到非JSON格式请求到 dictionary store。', ['ip' => $request->ip()]);
return response()->json(['message' => '请求必须是JSON格式。'], 400);
}
// 2. 获取JSON请求体中的所有数据
$jsonData = $request->json()->all();
// 3. 对接收到的数据进行验证(可选但强烈推荐)
// 例如,检查数据是否为空或是否包含预期字段
if (empty($jsonData)) {
Log::warning('收到空的JSON数据。', ['ip' => $request->ip()]);
return response()->json(['message' => '未提供任何数据。'], 400);
}
// 4. 在这里可以对数据进行业务逻辑处理,例如存储到数据库
// 示例:遍历数据并进行存储
foreach ($jsonData as $macAddress => $rssiValues) {
// 假设你有一个MacAddress模型来存储这些数据
// MacAddress::create([
// 'mac_address' => $macAddress,
// 'rssi_values' => json_encode($rssiValues), // 如果数据库字段是文本类型,可能需要再次编码
// 'received_at' => now()
// ]);
Log::info("处理MAC地址: {$macAddress}, RSSI值: " . implode(', ', $rssiValues));
}
Log::info('成功接收并处理来自树莓派的MAC数据。', ['data' => $jsonData]);
// 5. 返回成功的JSON响应
return response()->json([
'message' => '数据接收成功!',
'received_data' => $jsonData // 可以选择返回接收到的数据以供调试
], 200);
}
/**
* 从存储中获取数据并在Blade模板中展示。
* 这是一个GET请求方法,用于前端页面展示。
*
* @return \Illuminate\View\View
*/
public function index()
{
// 假设这里从数据库或其他存储中获取了数据
// 实际应用中,这里会从数据库查询已存储的MAC地址数据
$macs = [
'AA:BB:CC:DD:EE:F1' => ['-60', '-62', '-59'],
'AA:BB:CC:DD:EE:F2' => ['-70', '-68', '-71'],
'FF:EE:DD:CC:BB:AA' => ['-55']
];
// 将数据传递给Blade视图
return view('backend.auth.user.dictionary', compact('macs'));
}
}代码说明:
一旦数据在控制器中被处理并准备
以上就是树莓派Python向Laravel发送与展示JSON数据教程的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号