wanshenmean
2026-03-17 737dec3c384f394fd6f9849b4480b697d1ba35d5
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
using System;
using WIDESEAWCS_S7Simulator.Core.Interfaces;
 
namespace WIDESEAWCS_S7Simulator.Core.Memory
{
    /// <summary>
    /// Q区(输出区/Output)实现
    /// 用于模拟西门子S7 PLC的输出过程映像区
    /// </summary>
    public class QRegion : MemoryRegion, IMemoryRegion
    {
        /// <summary>
        /// 区域类型
        /// </summary>
        public override string RegionType => "Q";
 
        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="size">区域大小(字节)</param>
        public QRegion(int size) : base(size)
        {
        }
 
        /// <summary>
        /// 读取位
        /// </summary>
        /// <param name="byteOffset">字节偏移量</param>
        /// <param name="bitOffset">位偏移量(0-7)</param>
        /// <returns>位状态(true/false)</returns>
        public bool ReadBit(ushort byteOffset, byte bitOffset)
        {
            if (bitOffset > 7)
                throw new ArgumentOutOfRangeException(nameof(bitOffset), "位偏移必须在0-7之间");
 
            _lock.EnterReadLock();
            try
            {
                if (byteOffset >= Size)
                    throw new ArgumentOutOfRangeException(nameof(byteOffset), "字节偏移超出Q区范围");
 
                return (_memory[byteOffset] & (1 << bitOffset)) != 0;
            }
            finally
            {
                _lock.ExitReadLock();
            }
        }
 
        /// <summary>
        /// 写入位
        /// </summary>
        /// <param name="byteOffset">字节偏移量</param>
        /// <param name="bitOffset">位偏移量(0-7)</param>
        /// <param name="value">位值(true/false)</param>
        public void WriteBit(ushort byteOffset, byte bitOffset, bool value)
        {
            if (bitOffset > 7)
                throw new ArgumentOutOfRangeException(nameof(bitOffset), "位偏移必须在0-7之间");
 
            _lock.EnterWriteLock();
            try
            {
                if (byteOffset >= Size)
                    throw new ArgumentOutOfRangeException(nameof(byteOffset), "字节偏移超出Q区范围");
 
                if (value)
                    _memory[byteOffset] |= (byte)(1 << bitOffset);
                else
                    _memory[byteOffset] &= (byte)~(1 << bitOffset);
            }
            finally
            {
                _lock.ExitWriteLock();
            }
        }
    }
}