嵌入式幼儿园刷卡系统 (C#实现)

嵌入式幼儿园刷卡系统解决方案,使用C#开发,包含刷卡管理、签到签退、家长通知和家长查询等功能。

系统架构

用户终端
后端系统
终端设备
USB/串口
网络通信
数据同步
通知推送
本地存储
云端存储
刷卡终端
主控系统
中心服务器
家长APP
短信网关
SQLite数据库
MySQL数据库

完整源代码

1. 数据库模型 (Models.cs)

csharp 复制代码
using System;
using SQLite;

namespace KindergartenCardSystem.Models
{
    // 幼儿信息
    public class Child
    {
        [PrimaryKey, AutoIncrement]
        public int Id { get; set; }
        
        [NotNull]
        public string Name { get; set; }
        
        [NotNull]
        public string CardId { get; set; } // 卡号
        
        public string ClassName { get; set; }
        public string Teacher { get; set; }
        public string ParentName { get; set; }
        public string ParentPhone { get; set; }
        public string PhotoPath { get; set; }
        public DateTime EnrollmentDate { get; set; }
        public bool Active { get; set; } = true;
    }

    // 考勤记录
    public class AttendanceRecord
    {
        [PrimaryKey, AutoIncrement]
        public int Id { get; set; }
        
        [NotNull]
        public int ChildId { get; set; }
        
        [NotNull]
        public DateTime Timestamp { get; set; }
        
        [NotNull]
        public string Type { get; set; } // "CheckIn" 或 "CheckOut"
        
        public string Notes { get; set; }
    }

    // 通知记录
    public class Notification
    {
        [PrimaryKey, AutoIncrement]
        public int Id { get; set; }
        
        [NotNull]
        public int ChildId { get; set; }
        
        [NotNull]
        public DateTime Timestamp { get; set; }
        
        [NotNull]
        public string Type { get; set; } // "CheckIn" 或 "CheckOut"
        
        public string Message { get; set; }
        public bool Sent { get; set; }
        public string Method { get; set; } // SMS, APP, WeChat
    }

    // 系统用户
    public class User
    {
        [PrimaryKey, AutoIncrement]
        public int Id { get; set; }
        
        [NotNull]
        public string Username { get; set; }
        
        [NotNull]
        public string Password { get; set; } // 实际应用中应存储哈希值
        
        [NotNull]
        public string Role { get; set; } // Admin, Teacher, Parent
        
        public int? ChildId { get; set; } // 家长关联的孩子ID
        public bool Active { get; set; } = true;
    }
}

2. 数据库服务 (DatabaseService.cs)

csharp 复制代码
using System;
using System.Collections.Generic;
using System.IO;
using SQLite;
using KindergartenCardSystem.Models;

namespace KindergartenCardSystem.Services
{
    public class DatabaseService
    {
        private SQLiteConnection _connection;
        private readonly string _dbPath;

        public DatabaseService(string dbPath = null)
        {
            // 嵌入式设备使用本地SQLite数据库
            _dbPath = dbPath ?? Path.Combine(
                Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData),
                "KindergartenCardSystem.db");
            
            InitializeDatabase();
        }

        private void InitializeDatabase()
        {
            _connection = new SQLiteConnection(_dbPath);
            _connection.CreateTable<Child>();
            _connection.CreateTable<AttendanceRecord>();
            _connection.CreateTable<Notification>();
            _connection.CreateTable<User>();
            
            // 创建默认管理员账户
            if (_connection.Table<User>().Count() == 0)
            {
                _connection.Insert(new User
                {
                    Username = "admin",
                    Password = "admin123",
                    Role = "Admin",
                    Active = true
                });
            }
        }

        // 幼儿管理
        public List<Child> GetAllChildren() => _connection.Table<Child>().ToList();
        public Child GetChildById(int id) => _connection.Table<Child>().FirstOrDefault(c => c.Id == id);
        public Child GetChildByCardId(string cardId) => _connection.Table<Child>().FirstOrDefault(c => c.CardId == cardId);
        public int AddChild(Child child) => _connection.Insert(child);
        public int UpdateChild(Child child) => _connection.Update(child);
        public int DeleteChild(int id) => _connection.Delete<Child>(id);

        // 考勤记录
        public int AddAttendanceRecord(AttendanceRecord record) => _connection.Insert(record);
        public List<AttendanceRecord> GetAttendanceRecords(int childId, DateTime startDate, DateTime endDate)
        {
            return _connection.Table<AttendanceRecord>()
                .Where(r => r.ChildId == childId && r.Timestamp >= startDate && r.Timestamp <= endDate)
                .OrderBy(r => r.Timestamp)
                .ToList();
        }

        // 通知管理
        public int AddNotification(Notification notification) => _connection.Insert(notification);
        public List<Notification> GetUnsentNotifications() => 
            _connection.Table<Notification>().Where(n => !n.Sent).ToList();

        // 用户管理
        public User AuthenticateUser(string username, string password)
        {
            return _connection.Table<User>()
                .FirstOrDefault(u => u.Username == username && u.Password == password && u.Active);
        }
        
        public List<User> GetUsersByRole(string role) => 
            _connection.Table<User>().Where(u => u.Role == role).ToList();
    }
}

3. 刷卡服务 (CardReaderService.cs)

csharp 复制代码
using System;
using System.IO.Ports;
using System.Threading;
using System.Threading.Tasks;

namespace KindergartenCardSystem.Services
{
    public class CardReaderService : IDisposable
    {
        private SerialPort _serialPort;
        private string _portName;
        private int _baudRate;
        private Action<string> _cardDetectedCallback;
        private bool _isRunning;
        private Thread _readThread;

        public CardReaderService(string portName = "COM3", int baudRate = 9600)
        {
            _portName = portName;
            _baudRate = baudRate;
        }

        public void Start(Action<string> cardDetectedCallback)
        {
            _cardDetectedCallback = cardDetectedCallback;
            _isRunning = true;
            
            _serialPort = new SerialPort(_portName, _baudRate)
            {
                Parity = Parity.None,
                DataBits = 8,
                StopBits = StopBits.One,
                Handshake = Handshake.None
            };

            try
            {
                _serialPort.Open();
                _readThread = new Thread(ReadData);
                _readThread.Start();
            }
            catch (Exception ex)
            {
                Console.WriteLine($"串口打开失败: {ex.Message}");
            }
        }

        private void ReadData()
        {
            while (_isRunning)
            {
                try
                {
                    if (_serialPort.IsOpen && _serialPort.BytesToRead > 0)
                    {
                        string data = _serialPort.ReadLine().Trim();
                        if (!string.IsNullOrEmpty(data))
                        {
                            _cardDetectedCallback?.Invoke(data);
                        }
                    }
                    Thread.Sleep(100);
                }
                catch (Exception ex)
                {
                    Console.WriteLine($"读取数据错误: {ex.Message}");
                }
            }
        }

        public void Stop()
        {
            _isRunning = false;
            _readThread?.Join(1000);
            if (_serialPort != null && _serialPort.IsOpen)
            {
                _serialPort.Close();
            }
        }

        public void Dispose()
        {
            Stop();
            _serialPort?.Dispose();
        }
    }
}

4. 通知服务 (NotificationService.cs)

csharp 复制代码
using System;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using Newtonsoft.Json;
using KindergartenCardSystem.Models;

namespace KindergartenCardSystem.Services
{
    public class NotificationService
    {
        private readonly string _apiKey;
        private readonly string _apiUrl = "https://api.smsprovider.com/send";
        private readonly DatabaseService _dbService;

        public NotificationService(string apiKey, DatabaseService dbService)
        {
            _apiKey = apiKey;
            _dbService = dbService;
        }

        public async Task SendSmsNotificationAsync(string phoneNumber, string message)
        {
            try
            {
                using (var client = new HttpClient())
                {
                    var payload = new
                    {
                        api_key = _apiKey,
                        to = phoneNumber,
                        message = message
                    };

                    var content = new StringContent(JsonConvert.SerializeObject(payload), 
                                                   Encoding.UTF8, "application/json");
                    
                    var response = await client.PostAsync(_apiUrl, content);
                    response.EnsureSuccessStatusCode();
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine($"短信发送失败: {ex.Message}");
            }
        }

        public async Task ProcessPendingNotificationsAsync()
        {
            var notifications = _dbService.GetUnsentNotifications();
            
            foreach (var notification in notifications)
            {
                var child = _dbService.GetChildById(notification.ChildId);
                if (child == null) continue;
                
                bool sent = false;
                
                if (notification.Method == "SMS" && !string.IsNullOrEmpty(child.ParentPhone))
                {
                    string message = $"【幼儿园通知】您的孩子{child.Name}已于{notification.Timestamp:HH:mm}完成{(notification.Type == "CheckIn" ? "入园" : "离园")}。";
                    await SendSmsNotificationAsync(child.ParentPhone, message);
                    sent = true;
                }
                // 这里可以添加APP推送和微信通知的实现
                
                if (sent)
                {
                    notification.Sent = true;
                    _dbService.UpdateNotification(notification);
                }
            }
        }
    }
}

5. 主界面 (MainForm.cs)

csharp 复制代码
using System;
using System.Drawing;
using System.Linq;
using System.Windows.Forms;
using KindergartenCardSystem.Models;
using KindergartenCardSystem.Services;

namespace KindergartenCardSystem.UI
{
    public partial class MainForm : Form
    {
        private readonly DatabaseService _dbService;
        private readonly CardReaderService _cardReader;
        private readonly NotificationService _notificationService;
        private User _currentUser;

        public MainForm()
        {
            InitializeComponent();
            
            // 初始化服务
            _dbService = new DatabaseService();
            _cardReader = new CardReaderService();
            _notificationService = new NotificationService("your_api_key", _dbService);
            
            // 设置界面
            SetupUI();
            
            // 启动刷卡服务
            _cardReader.Start(OnCardDetected);
            
            // 启动通知处理线程
            Task.Run(() => ProcessNotificationsLoop());
        }

        private void SetupUI()
        {
            // 登录界面
            var loginForm = new LoginForm(_dbService);
            if (loginForm.ShowDialog() != DialogResult.OK)
            {
                Application.Exit();
                return;
            }
            
            _currentUser = loginForm.LoggedInUser;
            
            // 根据用户角色显示不同界面
            if (_currentUser.Role == "Admin" || _currentUser.Role == "Teacher")
            {
                ShowTeacherInterface();
            }
            else if (_currentUser.Role == "Parent")
            {
                ShowParentInterface();
            }
            
            // 显示当前时间和日期
            lblDateTime.Text = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
            timerDateTime.Start();
        }

        private void ShowTeacherInterface()
        {
            // 隐藏登录控件
            lblLoginPrompt.Visible = false;
            
            // 显示刷卡区域
            panelCardArea.Visible = true;
            lblWelcome.Text = $"欢迎, {_currentUser.Username} ({_currentUser.Role})";
            
            // 添加刷卡结果显示区域
            txtCardResult.Visible = true;
            lblCardResult.Visible = true;
            
            // 添加最近刷卡记录
            lstRecentCards.Visible = true;
            lblRecentCards.Visible = true;
            RefreshRecentCards();
        }

        private void ShowParentInterface()
        {
            // 隐藏登录控件
            lblLoginPrompt.Visible = false;
            
            // 显示家长界面
            panelParent.Visible = true;
            lblWelcome.Text = $"欢迎, {_currentUser.Username} (家长)";
            
            // 显示孩子信息
            if (_currentUser.ChildId.HasValue)
            {
                var child = _dbService.GetChildById(_currentUser.ChildId.Value);
                if (child != null)
                {
                    lblChildName.Text = child.Name;
                    lblChildClass.Text = child.ClassName;
                    lblChildTeacher.Text = child.Teacher;
                    
                    // 加载头像
                    if (!string.IsNullOrEmpty(child.PhotoPath) && File.Exists(child.PhotoPath))
                    {
                        picChildPhoto.Image = Image.FromFile(child.PhotoPath);
                    }
                    
                    // 加载今日考勤
                    RefreshTodayAttendance(child.Id);
                }
            }
        }

        private void RefreshRecentCards()
        {
            lstRecentCards.Items.Clear();
            var records = _dbService.GetAttendanceRecords(0, DateTime.Today.AddDays(-7), DateTime.Now)
                                  .OrderByDescending(r => r.Timestamp)
                                  .Take(10);
            
            foreach (var record in records)
            {
                var child = _dbService.GetChildById(record.ChildId);
                if (child != null)
                {
                    lstRecentCards.Items.Add($"{record.Timestamp:HH:mm:ss} - {child.Name} ({child.Class}) - {(record.Type == "CheckIn" ? "入园" : "离园")}");
                }
            }
        }

        private void RefreshTodayAttendance(int childId)
        {
            lstTodayAttendance.Items.Clear();
            var today = DateTime.Today;
            var records = _dbService.GetAttendanceRecords(childId, today, today.AddDays(1));
            
            foreach (var record in records)
            {
                lstTodayAttendance.Items.Add($"{record.Timestamp:HH:mm:ss} - {(record.Type == "CheckIn" ? "入园" : "离园")}");
            }
        }

        private void OnCardDetected(string cardId)
        {
            // 确保在UI线程执行
            this.Invoke((MethodInvoker)delegate {
                ProcessCard(cardId);
            });
        }

        private void ProcessCard(string cardId)
        {
            var child = _dbService.GetChildByCardId(cardId);
            
            if (child == null)
            {
                lblCardResult.Text = "未知卡号";
                lblCardResult.ForeColor = Color.Red;
                txtCardResult.Text = cardId;
                return;
            }
            
            if (!child.Active)
            {
                lblCardResult.Text = "卡片已停用";
                lblCardResult.ForeColor = Color.Orange;
                txtCardResult.Text = $"{child.Name} ({cardId})";
                return;
            }
            
            // 确定签到还是签退
            var now = DateTime.Now;
            var today = now.Date;
            var lastRecord = _dbService.GetAttendanceRecords(child.Id, today, today.AddDays(1))
                                      .OrderByDescending(r => r.Timestamp)
                                      .FirstOrDefault();
            
            string type = "CheckIn";
            if (lastRecord != null && lastRecord.Type == "CheckIn" && now.TimeOfDay > new TimeSpan(12, 0, 0))
            {
                type = "CheckOut";
            }
            
            // 记录考勤
            var record = new AttendanceRecord
            {
                ChildId = child.Id,
                Timestamp = now,
                Type = type,
                Notes = $"刷卡{(type == "CheckIn" ? "入园" : "离园")}"
            };
            
            _dbService.AddAttendanceRecord(record);
            
            // 发送通知
            var notification = new Notification
            {
                ChildId = child.Id,
                Timestamp = now,
                Type = type,
                Message = $"孩子{child.Name}已于{now:HH:mm}完成{(type == "CheckIn" ? "入园" : "离园")}",
                Sent = false,
                Method = "SMS" // 可以配置为SMS, APP, WeChat
            };
            _dbService.AddNotification(notification);
            
            // 更新UI
            lblCardResult.Text = $"{(type == "CheckIn" ? "入园" : "离园")}成功";
            lblCardResult.ForeColor = Color.Green;
            txtCardResult.Text = $"{child.Name} ({child.Class}) - {cardId}";
            
            // 播放提示音
            System.Media.SystemSounds.Beep.Play();
            
            // 刷新最近记录
            RefreshRecentCards();
        }

        private async Task ProcessNotificationsLoop()
        {
            while (true)
            {
                try
                {
                    await _notificationService.ProcessPendingNotificationsAsync();
                }
                catch (Exception ex)
                {
                    Console.WriteLine($"处理通知错误: {ex.Message}");
                }
                
                // 每5分钟检查一次
                await Task.Delay(5 * 60 * 1000);
            }
        }

        private void timerDateTime_Tick(object sender, EventArgs e)
        {
            lblDateTime.Text = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
        }

        // 其他UI事件处理方法...
    }
}

6. 登录界面 (LoginForm.cs)

csharp 复制代码
using System;
using System.Windows.Forms;
using KindergartenCardSystem.Models;
using KindergartenCardSystem.Services;

namespace KindergartenCardSystem.UI
{
    public partial class LoginForm : Form
    {
        private readonly DatabaseService _dbService;
        public User LoggedInUser { get; private set; }

        public LoginForm(DatabaseService dbService)
        {
            InitializeComponent();
            _dbService = dbService;
        }

        private void btnLogin_Click(object sender, EventArgs e)
        {
            string username = txtUsername.Text.Trim();
            string password = txtPassword.Text;

            if (string.IsNullOrEmpty(username) || string.IsNullOrEmpty(password))
            {
                MessageBox.Show("请输入用户名和密码", "登录失败", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }

            var user = _dbService.AuthenticateUser(username, password);
            if (user == null)
            {
                MessageBox.Show("用户名或密码错误", "登录失败", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }

            LoggedInUser = user;
            DialogResult = DialogResult.OK;
            Close();
        }
    }
}

7. 设备管理界面 (DeviceManagementForm.cs)

csharp 复制代码
using System;
using System.Windows.Forms;
using KindergartenCardSystem.Models;
using KindergartenCardSystem.Services;

namespace KindergartenCardSystem.UI
{
    public partial class DeviceManagementForm : Form
    {
        private readonly DatabaseService _dbService;

        public DeviceManagementForm(DatabaseService dbService)
        {
            InitializeComponent();
            _dbService = dbService;
            LoadDevices();
        }

        private void LoadDevices()
        {
            // 实际应用中从数据库加载设备列表
            lstDevices.Items.Add(new ListViewItem(new[] { "DT001", "大厅入口", "COM3", "正常" }));
            lstDevices.Items.Add(new ListViewItem(new[] { "DT002", "教室入口", "COM4", "正常" }));
            lstDevices.Items.Add(new ListViewItem(new[] { "DT003", "出口", "COM5", "离线" }));
        }

        private void btnAddDevice_Click(object sender, EventArgs e)
        {
            // 打开添加设备对话框
            var dialog = new AddDeviceForm();
            if (dialog.ShowDialog() == DialogResult.OK)
            {
                // 添加到列表
                lstDevices.Items.Add(new ListViewItem(new[] { 
                    dialog.DeviceId, 
                    dialog.Location, 
                    dialog.Port, 
                    "正常" 
                }));
            }
        }

        private void btnConfigure_Click(object sender, EventArgs e)
        {
            if (lstDevices.SelectedItems.Count == 0) return;
            
            var selected = lstDevices.SelectedItems[0];
            var dialog = new ConfigureDeviceForm(
                selected.SubItems[0].Text, 
                selected.SubItems[1].Text, 
                selected.SubItems[2].Text);
                
            if (dialog.ShowDialog() == DialogResult.OK)
            {
                selected.SubItems[1].Text = dialog.Location;
                selected.SubItems[2].Text = dialog.Port;
            }
        }

        private void btnTest_Click(object sender, EventArgs e)
        {
            if (lstDevices.SelectedItems.Count == 0) return;
            
            var selected = lstDevices.SelectedItems[0];
            MessageBox.Show($"正在测试设备 {selected.SubItems[0].Text}...", 
                            "设备测试", MessageBoxButtons.OK, MessageBoxIcon.Information);
            
            // 实际应用中发送测试指令到设备
            // 模拟测试结果
            selected.SubItems[3].Text = "正常";
        }
    }
}

8. 报表生成器 (ReportGenerator.cs)

csharp 复制代码
using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Linq;
using KindergartenCardSystem.Models;
using KindergartenCardSystem.Services;

namespace KindergartenCardSystem.Reports
{
    public class ReportGenerator
    {
        private readonly DatabaseService _dbService;

        public ReportGenerator(DatabaseService dbService)
        {
            _dbService = dbService;
        }

        public DataTable GenerateDailyAttendanceReport(DateTime date)
        {
            var reportData = new DataTable();
            reportData.Columns.Add("班级", typeof(string));
            reportData.Columns.Add("应到人数", typeof(int));
            reportData.Columns.Add("实到人数", typeof(int));
            reportData.Columns.Add("迟到人数", typeof(int));
            reportData.Columns.Add("早退人数", typeof(int));
            reportData.Columns.Add("出勤率", typeof(string));

            // 获取所有班级
            var classes = _dbService.GetAllChildren()
                                  .Where(c => c.Active)
                                  .Select(c => c.ClassName)
                                  .Distinct()
                                  .OrderBy(c => c)
                                  .ToList();

            foreach (var className in classes)
            {
                var children = _dbService.GetAllChildren()
                                       .Where(c => c.ClassName == className && c.Active)
                                       .ToList();

                int total = children.Count;
                int present = 0;
                int late = 0;
                int earlyLeave = 0;

                foreach (var child in children)
                {
                    var records = _dbService.GetAttendanceRecords(child.Id, date, date.AddDays(1));
                    bool hasCheckIn = false;
                    bool hasCheckOut = false;

                    foreach (var record in records)
                    {
                        if (record.Type == "CheckIn")
                        {
                            hasCheckIn = true;
                            // 判断是否迟到(假设9:00后算迟到)
                            if (record.Timestamp.TimeOfDay > new TimeSpan(9, 0, 0))
                                late++;
                        }
                        else if (record.Type == "CheckOut")
                        {
                            hasCheckOut = true;
                            // 判断是否早退(假设16:00前算早退)
                            if (record.Timestamp.TimeOfDay < new TimeSpan(16, 0, 0))
                                earlyLeave++;
                        }
                    }

                    if (hasCheckIn) present++;
                }

                double attendanceRate = total > 0 ? (double)present / total * 100 : 0;
                reportData.Rows.Add(className, total, present, late, earlyLeave, $"{attendanceRate:F2}%");
            }

            return reportData;
        }

        public void ExportToCsv(DataTable data, string filePath)
        {
            using (var writer = new StreamWriter(filePath))
            {
                // 写入标题行
                for (int i = 0; i < data.Columns.Count; i++)
                {
                    writer.Write(data.Columns[i]);
                    if (i < data.Columns.Count - 1)
                        writer.Write(",");
                }
                writer.WriteLine();

                // 写入数据行
                foreach (DataRow row in data.Rows)
                {
                    for (int i = 0; i < data.Columns.Count; i++)
                    {
                        writer.Write(row[i].ToString());
                        if (i < data.Columns.Count - 1)
                            writer.Write(",");
                    }
                    writer.WriteLine();
                }
            }
        }

        public void PrintReport(DataTable data)
        {
            // 实际应用中调用打印机打印报表
            Console.WriteLine("打印报表...");
            foreach (DataRow row in data.Rows)
            {
                Console.WriteLine(string.Join(", ", row.ItemArray));
            }
        }
    }
}

参考代码 嵌入式幼儿园刷卡系统 www.youwenfan.com/contentcst/122315.html

系统功能说明

1. 核心功能模块

  1. 刷卡管理

    • 支持RFID卡、IC卡等多种刷卡方式
    • 实时识别持卡人身份(幼儿、教师、家长)
    • 自动区分签到/签退操作
  2. 考勤管理

    • 自动记录签到/签退时间
    • 生成每日/每周/每月考勤报表
    • 异常情况预警(迟到、早退、缺勤)
  3. 通知系统

    • 短信通知家长接送情况
    • APP推送通知
    • 微信小程序通知
  4. 家长查询

    • 实时查看孩子考勤记录
    • 接收孩子进出园通知
    • 查看接送人照片(可选)
  5. 系统管理

    • 幼儿信息管理(姓名、班级、照片等)
    • 教师信息管理
    • 设备管理(刷卡终端配置)
    • 用户权限管理

2. 嵌入式设备集成

csharp 复制代码
// 嵌入式设备初始化示例
public class EmbeddedDeviceInitializer
{
    public static void InitializeDevice()
    {
        // 初始化触摸屏
        TouchScreen.Initialize();
        
        // 初始化刷卡器
        CardReader.Initialize(port: "COM3", baudRate: 9600);
        
        // 初始化摄像头(用于拍照)
        Camera.Initialize(deviceIndex: 0);
        
        // 初始化网络
        Network.InitializeWiFi(ssid: "KindergartenWiFi", password: "securepassword");
        
        // 启动本地数据库
        Database.Initialize("kindergarten.db");
    }
}

3. 安全机制

  1. 数据加密

    csharp 复制代码
    // 敏感数据加密存储
    public static string Encrypt(string plainText, string key)
    {
        using (var aes = Aes.Create())
        {
            aes.Key = Encoding.UTF8.GetBytes(key.PadRight(32).Substring(0, 32));
            aes.IV = new byte[16];
            
            var encryptor = aes.CreateEncryptor(aes.Key, aes.IV);
            using (var ms = new MemoryStream())
            using (var cs = new CryptoStream(ms, encryptor, CryptoStreamMode.Write))
            {
                using (var sw = new StreamWriter(cs))
                {
                    sw.Write(plainText);
                }
                return Convert.ToBase64String(ms.ToArray());
            }
        }
    }
  2. 访问控制

    csharp 复制代码
    // 基于角色的访问控制
    public bool HasPermission(User user, string requiredRole)
    {
        if (user == null) return false;
        
        switch (requiredRole)
        {
            case "Admin":
                return user.Role == "Admin";
            case "Teacher":
                return user.Role == "Admin" || user.Role == "Teacher";
            case "Parent":
                return user.Role == "Admin" || user.Role == "Teacher" || user.Role == "Parent";
            default:
                return false;
        }
    }
  3. 数据备份

    csharp 复制代码
    // 自动备份数据库
    public void BackupDatabase(string backupPath)
    {
        var dbPath = Path.Combine(
            Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData),
            "KindergartenCardSystem.db");
        
        File.Copy(dbPath, Path.Combine(backupPath, $"backup_{DateTime.Now:yyyyMMddHHmmss}.db"), true);
    }

部署方案

1. 硬件配置

设备类型 推荐型号 说明
主控终端 树莓派4B (4GB RAM) 运行嵌入式系统,处理刷卡逻辑
刷卡器 MFRC522 RFID模块 支持13.56MHz RFID卡
触摸屏 7英寸电容触摸屏 1024×600分辨率
摄像头 USB摄像头模块 720P分辨率,用于拍照
网络设备 USB WiFi适配器 支持802.11n
电源 5V/3A直流电源 稳定供电

2. 软件部署

  1. 嵌入式系统安装

    bash 复制代码
    # 安装.NET Core运行时
    sudo apt-get update
    sudo apt-get install -y libunwind8 libc6-dev
    wget https://dot.net/v1/dotnet-install.sh -O dotnet-install.sh
    chmod +x dotnet-install.sh
    ./dotnet-install.sh --runtime dotnet --version 6.0.0
    
    # 部署应用程序
    scp -r KindergartenCardSystem pi@raspberrypi:/home/pi/app
    ssh pi@raspberrypi "cd /home/pi/app && dotnet KindergartenCardSystem.dll"
  2. 数据库初始化

    sql 复制代码
    -- 创建数据库表
    CREATE TABLE Children (
        Id INTEGER PRIMARY KEY AUTOINCREMENT,
        Name TEXT NOT NULL,
        CardId TEXT NOT NULL UNIQUE,
        ClassName TEXT,
        Teacher TEXT,
        ParentName TEXT,
        ParentPhone TEXT,
        PhotoPath TEXT,
        EnrollmentDate DATETIME DEFAULT CURRENT_TIMESTAMP,
        Active BOOLEAN DEFAULT 1
    );
    
    CREATE TABLE AttendanceRecords (
        Id INTEGER PRIMARY KEY AUTOINCREMENT,
        ChildId INTEGER NOT NULL,
        Timestamp DATETIME NOT NULL,
        Type TEXT NOT NULL CHECK(Type IN ('CheckIn', 'CheckOut')),
        Notes TEXT,
        FOREIGN KEY(ChildId) REFERENCES Children(Id)
    );

3. 系统配置

json 复制代码
// appsettings.json
{
  "Database": {
    "Path": "/home/pi/app/data/kindergarten.db"
  },
  "CardReader": {
    "Port": "COM3",
    "BaudRate": 9600
  },
  "Notification": {
    "SmsApiKey": "your_api_key",
    "SmsApiUrl": "https://api.smsprovider.com/send"
  },
  "Security": {
    "EncryptionKey": "your_32_byte_encryption_key_here"
  }
}

使用流程

1. 日常管理流程

家长手机 家长APP 教师 系统 刷卡终端 家长 家长手机 家长APP 教师 系统 刷卡终端 家长 刷卡 发送卡号 验证卡号有效性 记录考勤(签到/签退) 生成通知 发送短信通知 推送通知 查看实时考勤 处理异常考勤 查看考勤记录

2. 家长使用流程

  1. 孩子入园时刷卡 → 系统记录签到时间 → 发送通知给家长
  2. 孩子离园时刷卡 → 系统记录签退时间 → 发送通知给家长
  3. 家长通过APP查看:
    • 当日考勤记录
    • 历史考勤统计
    • 接送人照片(如配置了摄像头)
    • 学校通知公告

系统特点

  1. 嵌入式优化

    • 轻量级SQLite数据库
    • 低功耗设计(适合7×24小时运行)
    • 断网本地存储,联网自动同步
  2. 安全可靠

    • 数据加密存储
    • 刷卡双重验证(卡号+有效期)
    • 操作日志审计
  3. 易用性

    • 触摸屏友好界面
    • 大字体显示
    • 语音提示功能
  4. 可扩展性

    • 支持多种刷卡设备
    • 可扩展生物识别(指纹、人脸)
    • 支持多园区统一管理

扩展功能建议

  1. 人脸识别集成

    csharp 复制代码
    // 人脸识别和刷卡双重验证
    public class FaceRecognitionService
    {
        public bool VerifyIdentity(string cardId, Bitmap faceImage)
        {
            // 1. 通过卡号获取幼儿信息
            var child = _dbService.GetChildByCardId(cardId);
            if (child == null) return false;
            
            // 2. 加载幼儿注册照片
            var registeredPhoto = new Bitmap(child.PhotoPath);
            
            // 3. 使用人脸识别算法比对
            float similarity = FaceRecognitionEngine.Compare(registeredPhoto, faceImage);
            
            // 4. 相似度超过阈值则验证通过
            return similarity > 0.85f;
        }
    }
  2. 健康检测集成

    csharp 复制代码
    // 体温检测集成
    public class HealthCheckService
    {
        public void RecordTemperature(string cardId, float temperature)
        {
            var child = _dbService.GetChildByCardId(cardId);
            if (child == null) return;
            
            // 记录体温
            var healthRecord = new HealthRecord
            {
                ChildId = child.Id,
                Timestamp = DateTime.Now,
                Temperature = temperature,
                IsNormal = temperature >= 36.0f && temperature <= 37.5f
            };
            
            _dbService.AddHealthRecord(healthRecord);
            
            // 异常体温通知
            if (!healthRecord.IsNormal)
            {
                SendAlert($"孩子{child.Name}体温异常: {temperature}℃");
            }
        }
    }
  3. 访客管理系统

    csharp 复制代码
    // 访客登记系统
    public class VisitorSystem
    {
        public void RegisterVisitor(string name, string phone, string visitPurpose)
        {
            var visitor = new Visitor
            {
                Name = name,
                Phone = phone,
                VisitPurpose = visitPurpose,
                CheckInTime = DateTime.Now,
                BadgeId = GenerateBadgeId()
            };
            
            _dbService.AddVisitor(visitor);
            
            // 打印访客证
            PrintBadge(visitor);
        }
        
        public void CheckoutVisitor(string badgeId)
        {
            var visitor = _dbService.GetVisitorByBadgeId(badgeId);
            if (visitor != null)
            {
                visitor.CheckOutTime = DateTime.Now;
                _dbService.UpdateVisitor(visitor);
            }
        }
    }

总结

这个嵌入式幼儿园刷卡系统提供了完整的解决方案,包括:

  1. 核心功能

    • 刷卡签到/签退
    • 考勤记录管理
    • 家长通知
    • 数据报表
  2. 技术实现

    • 嵌入式设备集成(树莓派+刷卡器)
    • 本地SQLite数据库
    • 多线程处理
    • 网络通信
    • 数据加密
  3. 系统特点

    • 高可靠性(7×24小时运行)
    • 易用性(触摸屏界面)
    • 安全性(数据加密、访问控制)
    • 可扩展性(支持多种外设)
相关推荐
qq_454245034 小时前
通用引用管理框架
数据结构·架构·c#
aq55356004 小时前
三大编程语言深度对比:C# vs 易语言 vs 汇编
开发语言·汇编·c#
光泽雨4 小时前
c# 文件编译的过程
开发语言·c#
zxy28472253014 小时前
使用正运动的仿真软件C#
c#·仿真·运动控制·正运动·无硬件
三省持敬5 小时前
异步并发的“流量警察”:在C#中使用SemaphoreSlim进行并发控制的最佳实践
c#
唐青枫5 小时前
C#.NET IL 中间码 深入解析:从 C# 编译结果到 CLR 执行链路
c#·.net
xiaoshuaishuai87 小时前
C# 方言识别
开发语言·windows·c#
波波0078 小时前
写出稳定C#系统的关键:不可变性思想解析
开发语言·c#·wpf
willhuo8 小时前
基于Playwright的抖音网页自动化浏览器项目使用指南
爬虫·c#·.netcore·webview