Khoá học web cho nhà máy, bài 10: xây phân hệ MES, lệnh sản xuất, dừng máy, OEE và dashboard thời gian thực

Phân hệ điều hành sản xuất: lệnh sản xuất và nhật ký sản lượng, sự kiện dừng máy với chỉ mục có lọc, bộ tính OEE có kiểm thử, đẩy dữ liệu thời gian thực bằng SignalR và biểu đồ Pareto bằng Recharts.

· 13 phút đọc#khoá học#MES#OEE#SignalR#Recharts#thời gian thực

MES là phân hệ mà trưởng ca nhìn vào mỗi giờ. Dữ liệu đến nhanh, cần hiển thị gần như tức thời, và con số phải đúng. Bài này gồm bốn phần: nghiệp vụ lệnh sản xuất, dừng máy, bộ tính OEE, và màn hình thời gian thực.

1. Nghiệp vụ

Planned ──(Bắt đầu)──► Running ──(Kết thúc)──► Completed
   └────────────(Huỷ)───────────────────────► Cancelled

Trong khi Running:

  • Người vận hành (hoặc thiết bị, bài 12) ghi sản lượng theo lô: số đạt, số loại.
  • Khi máy ngừng, hệ ghi sự kiện dừng với mã lý do; khi chạy lại thì đóng sự kiện.
  • OEE được tính từ hai nguồn này, theo công thức ở bài 2 và 5.

Quy tắc nghiệp vụ ta đảm bảo:

  1. Mỗi dây chuyền chỉ có một lệnh Running tại một thời điểm.
  2. Mỗi thiết bị chỉ có một sự kiện dừng đang mở.
  3. Chỉ lệnh Running mới nhận sản lượng.

Quy tắc 1 và 2 được bảo vệ bằng chỉ mục duy nhất có lọc ở cơ sở dữ liệu, không chỉ bằng if trong C#:

USE FactoryDb;
GO
CREATE UNIQUE INDEX UX_ProdOrders_RunningPerLine
  ON mes.ProductionOrders (Line) WHERE Status = N'Running';
GO
CREATE UNIQUE INDEX UX_Downtime_OpenPerAsset
  ON mes.DowntimeEvents (AssetId) WHERE EndedAt IS NULL;
GO

-- Bảng mã lý do dừng (bài tập bài 4)
CREATE TABLE mes.DowntimeReasons (
  Code    nvarchar(30) PRIMARY KEY,
  Name    nvarchar(100) NOT NULL,
  Planned bit NOT NULL DEFAULT 0
);
INSERT mes.DowntimeReasons (Code, Name, Planned) VALUES
 (N'JAM',    N'Kẹt sản phẩm',          0),
 (N'SENSOR', N'Hỏng cảm biến',         0),
 (N'NOMAT',  N'Thiếu nguyên liệu',     0),
 (N'BREAK',  N'Hỏng cơ khí/điện',      0),
 (N'CLEAN',  N'Vệ sinh',               1),
 (N'CHANGE', N'Đổi sản phẩm',          1),
 (N'SHIFT',  N'Giao ca',               1);
GO
ALTER TABLE mes.DowntimeEvents
  ADD CONSTRAINT FK_Downtime_Reason FOREIGN KEY (ReasonCode) REFERENCES mes.DowntimeReasons(Code);
GO

2. Thực thể

Data/Entities/Mes.cs:

namespace Factory.Api.Data.Entities;

public class ProductionOrder
{
    public int Id { get; set; }
    public string OrderNo { get; set; } = "";
    public int ProductId { get; set; }
    public string Line { get; set; } = "";
    public decimal PlannedQty { get; set; }
    public string Status { get; set; } = "Planned";
    public DateTime? PlannedStart { get; set; }
    public DateTime? ActualStart { get; set; }
    public DateTime? ActualEnd { get; set; }
}

public class ProductionLog
{
    public long Id { get; set; }
    public int OrderId { get; set; }
    public int AssetId { get; set; }
    public DateTime LoggedAt { get; set; }
    public decimal GoodQty { get; set; }
    public decimal RejectQty { get; set; }
}

public class DowntimeEvent
{
    public long Id { get; set; }
    public int AssetId { get; set; }
    public int? OrderId { get; set; }
    public DateTime StartedAt { get; set; }
    public DateTime? EndedAt { get; set; }
    public string ReasonCode { get; set; } = "";
    public bool Planned { get; set; }
}

Thêm thực thể cho bảng mã lý do, ánh xạ vào mes.DowntimeReasons:

public class DowntimeReason
{
    public string Code { get; set; } = "";   // khoá chính
    public string Name { get; set; } = "";
    public bool Planned { get; set; }
}

Đăng ký DbSet (ProductionOrders, ProductionLogs, DowntimeEvents, DowntimeReasons) và ánh xạ trong FactoryDbContext tương tự bài 9 (ToTable("ProductionOrders","mes"), HasPrecision(18,3) cho số lượng, datetime2(0) cho thời điểm).

3. Bộ tính OEE: một hàm thuần, có kiểm thử

Tách công thức khỏi cơ sở dữ liệu và HTTP để kiểm thử được. Đây là phần phải đúng nhất của MES.

Services/OeeCalculator.cs:

namespace Factory.Api.Services;

public record DowntimeSpan(DateTime Start, DateTime? End, bool Planned);

public record OeeResult(
    double PlannedProductionMin, double RunMin,
    double Availability, double Performance, double Quality, double Oee);

public static class OeeCalculator
{
    public static OeeResult Compute(
        DateTime from, DateTime to,
        IEnumerable<DowntimeSpan> downtimes,
        decimal good, decimal reject, decimal idealCycleSec)
    {
        double plannedWindow = (to - from).TotalMinutes;
        double planned = 0, unplanned = 0;

        foreach (var d in downtimes)
        {
            var s = d.Start < from ? from : d.Start;
            var e = (d.End ?? to) > to ? to : (d.End ?? to);      // cắt theo khung, sự kiện đang mở tính đến hết khung
            if (e <= s) continue;
            var minutes = (e - s).TotalMinutes;
            if (d.Planned) planned += minutes; else unplanned += minutes;
        }

        double plannedProd = Math.Max(plannedWindow - planned, 0);
        double run = Math.Max(plannedProd - unplanned, 0);
        double total = (double)(good + reject);

        double a = plannedProd > 0 ? run / plannedProd : 0;
        double p = run > 0 ? Math.Min((double)idealCycleSec * total / (run * 60), 1.0) : 0;
        double q = total > 0 ? (double)good / total : 0;

        return new OeeResult(plannedProd, run, a, p, q, a * p * q);
    }
}

Hai quyết định: chặn P ở 100% (vì chu kỳ chuẩn sai hoặc số đếm nhiễu có thể cho P lớn hơn 1), và sự kiện dừng đang mở được tính tới hết khung.

Kiểm thử bằng xUnit, dùng đúng dữ liệu của bài 5 (kết quả kỳ vọng ≈ 0,769):

dotnet new xunit -n Factory.Tests
dotnet add Factory.Tests reference Factory.Api
using Factory.Api.Services;
using Xunit;

public class OeeCalculatorTests
{
    [Fact]
    public void Matches_lesson5_example()
    {
        var from = new DateTime(2026, 12, 2, 0, 0, 0, DateTimeKind.Utc);
        var to = from.AddHours(8);
        var downtimes = new[]
        {
            new DowntimeSpan(from.AddHours(3), from.AddHours(3).AddMinutes(40), false),
            new DowntimeSpan(from.AddHours(5), from.AddHours(5).AddMinutes(20), false),
            new DowntimeSpan(from.AddHours(6.5), from.AddHours(6.75), true),
        };

        var r = OeeCalculator.Compute(from, to, downtimes, 16500, 570, 1.3m);

        Assert.Equal(465, r.PlannedProductionMin, 3);
        Assert.Equal(405, r.RunMin, 3);
        Assert.Equal(0.769, r.Oee, 3);
    }

    [Fact]
    public void Open_downtime_counts_until_end_of_window()
    {
        var from = new DateTime(2026, 12, 2, 0, 0, 0, DateTimeKind.Utc);
        var r = OeeCalculator.Compute(from, from.AddHours(1),
            new[] { new DowntimeSpan(from.AddMinutes(30), null, false) }, 0, 0, 1m);
        Assert.Equal(30, r.RunMin, 3);
    }
}

Chạy dotnet test. Nếu một ngày bạn đổi quy ước tính OEE, bộ kiểm thử này sẽ cho bạn biết ngay con số nào đã đổi.

4. API

Lệnh sản xuất

[ApiController]
[Route("api/production-orders")]
public class ProductionOrdersController(FactoryDbContext db) : ControllerBase
{
    public class CreateRequest
    {
        [Range(1, int.MaxValue)] public int ProductId { get; set; }
        [Required, StringLength(30)] public string Line { get; set; } = "";
        [Range(0.001, 100_000_000)] public decimal PlannedQty { get; set; }
    }

    [HttpGet]
    public async Task<IActionResult> List(string? status) { /* lọc theo Status, kèm tổng đạt, loại */ }

    [HttpPost, Authorize(Policy = "CanPlan")]
    public async Task<IActionResult> Create(CreateRequest r) { /* sinh OrderNo bằng SEQUENCE như bài 9 */ }

    [HttpPost("{id:int}/start"), Authorize(Policy = "CanOperate")]
    public async Task<IActionResult> Start(int id)
    {
        var now = DateTime.UtcNow;
        try
        {
            var n = await db.ProductionOrders
                .Where(o => o.Id == id && o.Status == "Planned")
                .ExecuteUpdateAsync(s => s.SetProperty(o => o.Status, "Running")
                                           .SetProperty(o => o.ActualStart, now));
            return n == 0 ? Conflict(new { message = "Lệnh không ở trạng thái Planned." }) : NoContent();
        }
        catch (DbUpdateException ex) when (ex.InnerException is Microsoft.Data.SqlClient.SqlException { Number: 2601 or 2627 })
        {
            return Conflict(new { message = "Dây chuyền này đang chạy một lệnh khác." });
        }
    }
}

Quy tắc "một lệnh Running mỗi dây chuyền" do chỉ mục thực thi; mã C# chỉ chuyển lỗi vi phạm thành câu thông báo dễ hiểu. (Khi dùng ExecuteUpdateAsync, lỗi ném ra có thể là SqlException trực tiếp thay vì DbUpdateException; hãy bắt cả hai trong mã thật và kiểm tra bằng kiểm thử.)

Ghi sản lượng

[ApiController, Route("api/production-logs")]
public class ProductionLogsController(FactoryDbContext db, IHubContext<FloorHub> hub) : ControllerBase
{
    public class LogRequest
    {
        [Range(1, int.MaxValue)] public int OrderId { get; set; }
        [Range(1, int.MaxValue)] public int AssetId { get; set; }
        [Range(0, 10_000_000)] public decimal GoodQty { get; set; }
        [Range(0, 10_000_000)] public decimal RejectQty { get; set; }
    }

    [HttpPost, Authorize(Policy = "CanOperate")]
    public async Task<IActionResult> Create(LogRequest r)
    {
        var running = await db.ProductionOrders.AnyAsync(o => o.Id == r.OrderId && o.Status == "Running");
        if (!running) return Conflict(new { message = "Lệnh không ở trạng thái Running." });

        var log = new ProductionLog
        {
            OrderId = r.OrderId, AssetId = r.AssetId, LoggedAt = DateTime.UtcNow,
            GoodQty = r.GoodQty, RejectQty = r.RejectQty,
        };
        db.ProductionLogs.Add(log);
        await db.SaveChangesAsync();

        await hub.Clients.All.SendAsync("production", new { r.OrderId, r.AssetId, r.GoodQty, r.RejectQty, log.LoggedAt });
        return Ok(new { log.Id });
    }
}

Dừng máy

[ApiController, Route("api/downtime")]
public class DowntimeController(FactoryDbContext db, IHubContext<FloorHub> hub) : ControllerBase
{
    public class StartRequest
    {
        [Range(1, int.MaxValue)] public int AssetId { get; set; }
        [Required] public string ReasonCode { get; set; } = "";
    }

    [HttpPost("start"), Authorize(Policy = "CanOperate")]
    public async Task<IActionResult> Start(StartRequest r)
    {
        var reason = await db.DowntimeReasons.FindAsync(r.ReasonCode);
        if (reason is null) return BadRequest(new { message = "Mã lý do không hợp lệ." });

        var runningOrderId = await db.ProductionOrders
            .Join(db.Assets, o => o.Line, a => a.Line, (o, a) => new { o, a })
            .Where(x => x.a.Id == r.AssetId && x.o.Status == "Running")
            .Select(x => (int?)x.o.Id).FirstOrDefaultAsync();

        var ev = new DowntimeEvent
        {
            AssetId = r.AssetId, OrderId = runningOrderId, StartedAt = DateTime.UtcNow,
            ReasonCode = r.ReasonCode, Planned = reason.Planned,
        };
        db.DowntimeEvents.Add(ev);
        try { await db.SaveChangesAsync(); }
        catch (DbUpdateException) { return Conflict(new { message = "Thiết bị đang có một sự kiện dừng chưa đóng." }); }

        await db.Assets.Where(a => a.Id == r.AssetId)
            .ExecuteUpdateAsync(s => s.SetProperty(a => a.Status, (byte)(reason.Planned ? 0 : 2)));
        await hub.Clients.All.SendAsync("machine", new { r.AssetId, status = reason.Planned ? 0 : 2, r.ReasonCode });
        return Ok(new { ev.Id });
    }

    [HttpPost("end/{assetId:int}"), Authorize(Policy = "CanOperate")]
    public async Task<IActionResult> End(int assetId)
    {
        var now = DateTime.UtcNow;
        var n = await db.DowntimeEvents
            .Where(e => e.AssetId == assetId && e.EndedAt == null)
            .ExecuteUpdateAsync(s => s.SetProperty(e => e.EndedAt, now));
        if (n == 0) return Conflict(new { message = "Thiết bị không có sự kiện dừng đang mở." });

        await db.Assets.Where(a => a.Id == assetId).ExecuteUpdateAsync(s => s.SetProperty(a => a.Status, (byte)1));
        await hub.Clients.All.SendAsync("machine", new { assetId, status = 1 });
        return NoContent();
    }
}

OEE và Pareto

[ApiController, Route("api/oee")]
public class OeeController(FactoryDbContext db) : ControllerBase
{
    // GET /api/oee?assetId=2&from=2026-12-02T00:00:00Z&to=2026-12-02T08:00:00Z
    [HttpGet]
    public async Task<IActionResult> Get(int assetId, DateTime from, DateTime to)
    {
        if (to <= from || (to - from).TotalDays > 31) return BadRequest(new { message = "Khoảng thời gian không hợp lệ." });
        from = from.ToUniversalTime(); to = to.ToUniversalTime();

        var asset = await db.Assets.AsNoTracking().FirstOrDefaultAsync(a => a.Id == assetId);
        if (asset?.IdealCycleSec is null) return BadRequest(new { message = "Thiết bị chưa có chu kỳ chuẩn." });

        var downs = await db.DowntimeEvents.AsNoTracking()
            .Where(d => d.AssetId == assetId && d.StartedAt < to && (d.EndedAt == null || d.EndedAt > from))
            .Select(d => new DowntimeSpan(d.StartedAt, d.EndedAt, d.Planned)).ToListAsync();

        var logs = await db.ProductionLogs.AsNoTracking()
            .Where(l => l.AssetId == assetId && l.LoggedAt > from && l.LoggedAt <= to).ToListAsync();

        var r = OeeCalculator.Compute(from, to, downs, logs.Sum(l => l.GoodQty), logs.Sum(l => l.RejectQty), asset.IdealCycleSec.Value);
        return Ok(r);
    }

    [HttpGet("downtime-pareto")]
    public async Task<IActionResult> Pareto(DateTime from, DateTime to)
    {
        from = from.ToUniversalTime(); to = to.ToUniversalTime();
        var rows = await db.DowntimeEvents.AsNoTracking()
            .Where(d => !d.Planned && d.EndedAt != null && d.StartedAt >= from && d.StartedAt < to)
            .GroupBy(d => d.ReasonCode)
            .Select(g => new { reason = g.Key, minutes = g.Sum(d => EF.Functions.DateDiffMinute(d.StartedAt, d.EndedAt!.Value)) })
            .OrderByDescending(x => x.minutes).ToListAsync();
        return Ok(rows);
    }
}

Với khoảng thời gian dài, cân nhắc tính trước theo giờ hoặc theo ca vào một bảng tổng hợp (mes.OeeHourly) để biểu đồ tải nhanh; bài 12 nhắc lại.

5. Thời gian thực với SignalR

Thay vì giao diện hỏi máy chủ mỗi vài giây (polling), SignalR cho máy chủ đẩy sự kiện xuống trình duyệt qua WebSocket.

Hubs/FloorHub.cs:

using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.SignalR;

namespace Factory.Api.Hubs;

[Authorize]
public class FloorHub : Hub { }

Program.cs (thêm):

builder.Services.AddSignalR();

// JWT cho WebSocket: trình duyệt không gắn được header, nên token đi qua query string.
// Trong AddJwtBearer(o => { ... }) thêm:
o.Events = new JwtBearerEvents
{
    OnMessageReceived = ctx =>
    {
        var token = ctx.Request.Query["access_token"];
        if (!string.IsNullOrEmpty(token) && ctx.HttpContext.Request.Path.StartsWithSegments("/hubs"))
            ctx.Token = token;
        return Task.CompletedTask;
    }
};

app.MapHub<FloorHub>("/hubs/floor");

Token trong query string có thể lọt vào nhật ký máy chủ proxy. Chỉ chấp nhận đường dẫn /hubs như trên, dùng HTTPS và thời hạn token ngắn.

Proxy WebSocket trong vite.config.js:

server: { proxy: {
  "/api":  "http://localhost:5080",
  "/hubs": { target: "http://localhost:5080", ws: true },
} },

Hook phía React

npm install @microsoft/signalr recharts
// hooks/useFloorHub.js
import { HubConnectionBuilder, LogLevel } from "@microsoft/signalr";
import { useQueryClient } from "@tanstack/react-query";
import { useEffect } from "react";
import { useAuth } from "../auth/AuthContext.jsx";

export function useFloorHub() {
  const qc = useQueryClient();
  const { token } = useAuth();

  useEffect(() => {
    if (!token) return;
    const conn = new HubConnectionBuilder()
      .withUrl("/hubs/floor", { accessTokenFactory: () => token })
      .withAutomaticReconnect()
      .configureLogging(LogLevel.Warning)
      .build();

    conn.on("machine", () => qc.invalidateQueries({ queryKey: ["assets"] }));
    conn.on("production", () => {
      qc.invalidateQueries({ queryKey: ["oee"] });
      qc.invalidateQueries({ queryKey: ["production-orders"] });
    });

    conn.start().catch((e) => console.warn("SignalR:", e.message));
    return () => { conn.stop(); };
  }, [token, qc]);
}

Mỗi sự kiện chỉ báo là dữ liệu đã đổi, còn dữ liệu chính vẫn được tải qua API có phân quyền; cách này đơn giản và an toàn. Gọi useFloorHub() một lần trong component gốc sau khi đăng nhập.

6. Dashboard

import { useQuery } from "@tanstack/react-query";
import { Bar, BarChart, CartesianGrid, ResponsiveContainer, Tooltip, XAxis, YAxis } from "recharts";
import { api } from "../../api.js";

const pct = (v) => `${(v * 100).toFixed(1)}%`;

function Kpi({ label, value }) {
  return <div className="kpi"><span>{label}</span><strong>{value}</strong></div>;
}

export default function MesDashboard({ assetId, from, to }) {
  const qs = new URLSearchParams({ assetId, from, to });
  const oee = useQuery({ queryKey: ["oee", assetId, from, to], queryFn: () => api(`/oee?${qs}`) });
  const pareto = useQuery({
    queryKey: ["oee", "pareto", from, to],
    queryFn: () => api(`/oee/downtime-pareto?${new URLSearchParams({ from, to })}`),
  });

  return (
    <section>
      {oee.data && (
        <div className="kpis">
          <Kpi label="OEE" value={pct(oee.data.oee)} />
          <Kpi label="Availability" value={pct(oee.data.availability)} />
          <Kpi label="Performance" value={pct(oee.data.performance)} />
          <Kpi label="Quality" value={pct(oee.data.quality)} />
        </div>
      )}
      <h3>Thời gian dừng theo lý do (phút)</h3>
      <div style={{ height: 280 }}>
        <ResponsiveContainer>
          <BarChart data={pareto.data ?? []}>
            <CartesianGrid strokeDasharray="3 3" />
            <XAxis dataKey="reason" />
            <YAxis />
            <Tooltip />
            <Bar dataKey="minutes" fill="#22c55e" />
          </BarChart>
        </ResponsiveContainer>
      </div>
    </section>
  );
}

Nguyên tắc dashboard nhà máy: một con số lớn, màu có nghĩa (đỏ khi dưới ngưỡng), không rối, thấy được ở xa. Đừng hiển thị 20 biểu đồ; trưởng ca chỉ cần biết "ca này ổn hay không, vì sao không".

Bài tập

  1. Thêm điểm cuối GET /api/oee/by-shift?assetId=&date= trả về OEE của ba ca trong ngày, gọi OeeCalculator ba lần.
  2. Thêm cảnh báo trên màn hình: nếu một sự kiện dừng không kế hoạch kéo dài quá 15 phút, hiện banner đỏ và đẩy sự kiện alarm qua SignalR.
  3. Viết kiểm thử cho OeeCalculator với sự kiện dừng bắt đầu trước khung thời gian, và với P > 1 (xác nhận được chặn ở 1).
  4. Thêm biểu đồ đường "sản lượng luỹ kế theo giờ so với kế hoạch" từ mes.ProductionLogs.

Tóm tắt

  • Quy tắc "một lệnh Running mỗi dây chuyền", "một sự kiện dừng mở mỗi máy" được thực thi bằng chỉ mục duy nhất có lọc.
  • OeeCalculator là hàm thuần có kiểm thử; cắt theo khung thời gian, tách dừng có kế hoạch và không kế hoạch.
  • SignalR đẩy thông báo đổi dữ liệu; dữ liệu thật vẫn lấy qua API có phân quyền.
  • Dashboard tốt = ít con số, rõ ý nghĩa.
  • Bài 11 nối MES với ERP: vật tư, định mức, tồn kho và trừ kho khi sản xuất xong.