本文将详细介绍如何使用C#和LiteDB实现一个设备运行状态追踪系统。该系统可以记录和监控设备的运行状态、故障信息以及维护记录等数据。LiteDB是一个轻量级的NoSQL数据库,完全基于.NET实现,非常适合小型应用程序和嵌入式系统。
环境准备
- Visual Studio 2022
- .NET 6.0 或更高版本
项目实现
数据模型设计
首先,我们需要定义几个核心的数据模型:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using LiteDB;
namespace App17.Models
{
// 设备信息模型
publicclass Device
{
[BsonId] // 设置主键
publicint Id { get; set; }
publicstring DeviceName { get; set; }
publicstring SerialNumber { get; set; }
public DateTime InstallationDate { get; set; }
publicstring Location { get; set; }
publicbool IsActive { get; set; }
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using LiteDB;
namespace App17.Models
{
// 设备状态记录模型
publicclass DeviceStatus
{
[BsonId]
public ObjectId Id { get; set; }
publicint DeviceId { get; set; }
public DateTime Timestamp { get; set; }
publicstring Status { get; set; } // Running, Idle, Error, Maintenance
publicdouble Temperature { get; set; }
publicdouble PowerConsumption { get; set; }
publicstring ErrorCode { get; set; }
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using LiteDB;
namespace App17.Models
{
// 维护记录模型
publicclass MaintenanceRecord
{
[BsonId]
public ObjectId Id { get; set; }
publicint DeviceId { get; set; }
public DateTime MaintenanceDate { get; set; }
publicstring MaintenanceType { get; set; }
publicstring Description { get; set; }
publicstring Technician { get; set; }
public decimal Cost { get; set; }
}
}
数据访问层实现
创建一个数据访问类来处理与LiteDB的交互:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using App17.Models;
using LiteDB;
namespace App17.Data
{
publicclass DeviceDataAccess : IDisposable
{
private readonly LiteDatabase _db;
private readonly string _dbPath;
public DeviceDataAccess(string dbPath = "DeviceTracking.db")
{
_dbPath = dbPath;
_db = new LiteDatabase(_dbPath);
}
// 添加新设备
public int AddDevice(Device device)
{
var collection = _db.GetCollection<Device>("devices");
collection.Insert(device);
return device.Id;
}
// 记录设备状态
public void RecordDeviceStatus(DeviceStatus status)
{
var collection = _db.GetCollection<DeviceStatus>("device_status");
collection.Insert(status);
}
// 添加维护记录
public void AddMaintenanceRecord(MaintenanceRecord record)
{
var collection = _db.GetCollection<MaintenanceRecord>("maintenance_records");
collection.Insert(record);
}
// 获取设备最新状态
public DeviceStatus GetLatestDeviceStatus(int deviceId)
{
var collection = _db.GetCollection<DeviceStatus>("device_status");
return collection.Find(x => x.DeviceId == deviceId)
.OrderByDescending(x => x.Timestamp)
.FirstOrDefault();
}
// 获取设备维护历史
public IEnumerable<MaintenanceRecord> GetDeviceMaintenanceHistory(int deviceId)
{
var collection = _db.GetCollection<MaintenanceRecord>("maintenance_records");
return collection.Find(x => x.DeviceId == deviceId)
.OrderByDescending(x => x.MaintenanceDate);
}
// 获取所有活跃设备
public IEnumerable<Device> GetActiveDevices()
{
var collection = _db.GetCollection<Device>("devices");
return collection.Find(x => x.IsActive);
}
// 更新设备信息
public bool UpdateDevice(Device device)
{
var collection = _db.GetCollection<Device>("devices");
return collection.Update(device);
}
public void Dispose()
{
_db?.Dispose();
}
}
}
业务逻辑层实现
创建一个设备管理服务类来处理业务逻辑:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using App17.Data;
using App17.Models;
namespace App17.Services
{
publicclass DeviceManagementService
{
private readonly DeviceDataAccess _dataAccess;
public DeviceManagementService(string dbPath = "DeviceTracking.db")
{
_dataAccess = new DeviceDataAccess(dbPath);
}
// 注册新设备
public int RegisterDevice(string deviceName, string serialNumber, string location)
{
var device = new Device
{
DeviceName = deviceName,
SerialNumber = serialNumber,
Location = location,
InstallationDate = DateTime.Now,
IsActive = true
};
return _dataAccess.AddDevice(device);
}
// 更新设备状态
public void UpdateDeviceStatus(int deviceId, double temperature, double powerConsumption, string status, string errorCode = null)
{
var deviceStatus = new DeviceStatus
{
DeviceId = deviceId,
Timestamp = DateTime.Now,
Temperature = temperature,
PowerConsumption = powerConsumption,
Status = status,
ErrorCode = errorCode
};
_dataAccess.RecordDeviceStatus(deviceStatus);
}
// 记录维护工作
public void RecordMaintenance(int deviceId, string maintenanceType, string description, string technician, decimal cost)
{
var maintenance = new MaintenanceRecord
{
DeviceId = deviceId,
MaintenanceDate = DateTime.Now,
MaintenanceType = maintenanceType,
Description = description,
Technician = technician,
Cost = cost
};
_dataAccess.AddMaintenanceRecord(maintenance);
}
// 获取设备状态报告
public DeviceStatusReport GetDeviceReport(int deviceId)
{
var device = _dataAccess.GetActiveDevices().FirstOrDefault(d => d.Id == deviceId);
if (device == null) return null;
var latestStatus = _dataAccess.GetLatestDeviceStatus(deviceId);
var maintenanceHistory = _dataAccess.GetDeviceMaintenanceHistory(deviceId).Take(5);
returnnew DeviceStatusReport
{
Device = device,
CurrentStatus = latestStatus,
RecentMaintenance = maintenanceHistory.ToList()
};
}
}
// 设备状态报告类
publicclass DeviceStatusReport
{
public Device Device { get; set; }
public DeviceStatus CurrentStatus { get; set; }
public List<MaintenanceRecord> RecentMaintenance { get; set; }
}
}
3.4 使用示例
下面是一个完整的使用示例:
using DeviceStatusTracking.Services;
class Program
{
static void Main(string[] args)
{
// 创建设备管理服务实例
var deviceService = new DeviceManagementService();
try
{
// 注册新设备
int deviceId = deviceService.RegisterDevice(
deviceName: "生产线机器人-A1",
serialNumber: "ROB-2024-001",
location: "生产车间1号"
);
Console.WriteLine($"设备注册成功,ID: {deviceId}");
// 模拟设备状态更新
deviceService.UpdateDeviceStatus(
deviceId: deviceId,
temperature: 45.5,
powerConsumption: 2.8,
status: "Running"
);
// 模拟记录维护工作
deviceService.RecordMaintenance(
deviceId: deviceId,
maintenanceType: "定期保养",
description: "更换润滑油,检查传动部件",
technician: "张工",
cost: 500.00M
);
// 获取设备状态报告
var report = deviceService.GetDeviceReport(deviceId);
// 打印报告
if (report != null)
{
Console.WriteLine("\n设备状态报告:");
Console.WriteLine($"设备名称: {report.Device.DeviceName}");
Console.WriteLine($"当前状态: {report.CurrentStatus.Status}");
Console.WriteLine($"温度: {report.CurrentStatus.Temperature}°C");
Console.WriteLine($"功耗: {report.CurrentStatus.PowerConsumption}kW");
Console.WriteLine("\n最近维护记录:");
foreach (var maintenance in report.RecentMaintenance)
{
Console.WriteLine($"日期: {maintenance.MaintenanceDate:yyyy-MM-dd}");
Console.WriteLine($"类型: {maintenance.MaintenanceType}");
Console.WriteLine($"描述: {maintenance.Description}");
Console.WriteLine($"技术员: {maintenance.Technician}");
Console.WriteLine($"费用: ¥{maintenance.Cost}");
Console.WriteLine();
}
}
}
catch (Exception ex)
{
Console.WriteLine($"发生错误: {ex.Message}");
}
}
}

总结
本文介绍的设备运行状态追踪系统使用LiteDB实现了一个完整的设备管理解决方案。系统具有良好的可扩展性和维护性,适合小型工厂或实验室使用。通过合理的架构设计和数据模型,系统可以方便地进行功能扩展和定制化开发。
阅读原文:原文链接
该文章在 2025/3/24 17:21:48 编辑过