private MBMessage AckReadCoil(MBMessage req) { MBMessage resp = new MBMessage(req); /** * req: * Byte 1-2:Reference number * Byte 3-4:Bit count (1-2000) * resp: * Response * Byte 1: Byte count of response (B=(bit count+7)/8) * Byte 2-(B+1):Bit values (least significant bit is first coil!)" */ ushort refNum = req.GetWord(0); ushort bitCount = req.GetWord(2); if (_cms.IsValidRegAddress((byte)refNum)) { byte[] byteValues = _cms.MB_ReadCoils(refNum, bitCount); // 写入. var bcnt = byteValues.Length; resp.SetBodySize((ushort)(bcnt + 1)); resp.SetByte(0, (byte)bcnt); for (byte i = 0; i < bcnt; i++) { resp.SetByte(i + 1, byteValues[i]); } } else { // Error Response. // Byte 0:FC = 81 (hex) // Byte 1:exception code = 01 or 02 resp.FC = 0x82; resp.SetBody(new byte[] { MBException.E02_ILLEGAL_DATA_ADDRESS }); } return resp; }
MBMessage NewWriteCoil(ushort addr, bool onOff) { MBMessage req = new MBMessage(); req.TID = 0xFF; req.UID = 0x01; req.PID = 0; req.FC = 0x05; req.SetBodySize(4); req.SetWord(0, addr); // 单樘门开门控制信号 - 读/写 0x11 req.SetByte(2, onOff ? (byte)0xFF : (byte)0x00); // 读取16*6个字节 req.SetByte(3, 0x00); return req; }
// 扫描 private void buttonScan_Click(object sender, EventArgs e) { if (_client == null) return; MBMessage req = new MBMessage(); req.TID = 0xFF; req.UID = 0x01; req.PID = 0; req.FC = 0x01; req.SetBodySize(4); req.SetWord(0, 0); // x: 0x0000 req.SetWord(2, 53 * 16); // 全部读取. MBMessage resp = SendRequest(req); int DOF = 1; if (resp == null) return; int zcnt = 6; int scnt = 7; //状态列: action,so,sc,err,lcb,green,red int regStart = 0x0B; int reg; int cs = ViewColumns.ACTION; for (int c = 0; c < scnt; c++) { // log.DebugFormat("state {0}", c); for (int z = 0; z < zcnt; z++) { reg = regStart + zcnt * c + z; // z=0: 11, 11+ 6*1, // log.DebugFormat("{0}", reg); byte b1 = resp.GetByte(reg * 2 + DOF); // Z0, 动作, 0-7 号门 byte b2 = resp.GetByte(reg * 2 + 1 + DOF); // Z0, 动作, 8-11号门 UpdateDoorState(z, c + cs, b1, 0, 8); UpdateDoorState(z, c + cs, b1, 8, 4); } } }