using System; using System.Collections.Generic; using System.Linq; using System.Text; using QMAPP.FJC.Entity.EnergyManage; namespace MeterReadingService.MeterReader { /// /// 智能电表读取类 /// public class ElectricMeterReader:IMeterReader { Dictionary meterDic = new Dictionary(); public double Read(Meter meter) { if (!meterDic.ContainsKey(meter.NET_ADDR)) { meterDic.Add(meter.NET_ADDR, new System.Net.Sockets.TcpClient()); } var mclient = meterDic[meter.NET_ADDR]; if (!mclient.Connected) { mclient.Connect(meter.NET_ADDR.Split(':')[0], int.Parse(meter.NET_ADDR.Split(':')[0])); } byte[] readcommand = new byte[] { 0x00, 0xAA, 0xEF, 0x09, 0x09 }; mclient.Client.Send(readcommand); byte[] response =new byte[100]; mclient.Client.Receive(response); int reading = BitConverter.ToInt32(response, 8); return reading / 10d; } public IAsyncResult BeginRead(Meter meter, AsyncCallback readCallback, object state) { if (!meterDic.ContainsKey(meter.NET_ADDR)) { meterDic.Add(meter.NET_ADDR, new System.Net.Sockets.TcpClient()); } var mclient = meterDic[meter.NET_ADDR]; if (!mclient.Connected) { mclient.Connect(meter.NET_ADDR.Split(':')[0], int.Parse(meter.NET_ADDR.Split(':')[0])); } Action act = new Action(() => { this.Read(meter); }); return act.BeginInvoke(readCallback, state); } public void EndRead(out int result, out double reading, out string error, IAsyncResult Asyncresult) { if (Asyncresult.IsCompleted) { byte[] readbuffer = (byte[])Asyncresult.AsyncState; result = 1; reading = BitConverter.ToInt32(readbuffer, 8) / 10d; error = ""; } else { result = -1; reading = -1; error = "读取超时!"; } } } }