diff --git a/Modbus.Net/Modbus.Net.FBox/AddressCombinerFBox.cs b/Modbus.Net/Modbus.Net.FBox/AddressCombinerFBox.cs deleted file mode 100644 index 2a1ec4d..0000000 --- a/Modbus.Net/Modbus.Net.FBox/AddressCombinerFBox.cs +++ /dev/null @@ -1,24 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; - -namespace Modbus.Net.FBox -{ - public class AddressCombinerFBox : AddressCombiner - { - public override IEnumerable Combine(IEnumerable addresses) - { - return (from address in addresses - select - new CommunicationUnit() - { - Area = address.Area, - Address = address.Address, - GetCount = 1, - DataType = address.DataType - }); - } - } -} diff --git a/Modbus.Net/Modbus.Net.FBox/AddressFormaterFBox.cs b/Modbus.Net/Modbus.Net.FBox/AddressFormaterFBox.cs deleted file mode 100644 index c4d2038..0000000 --- a/Modbus.Net/Modbus.Net.FBox/AddressFormaterFBox.cs +++ /dev/null @@ -1,16 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; - -namespace Modbus.Net.FBox -{ - public class AddressFormaterFBox : AddressFormater - { - public override string FormatAddress(string area, int address) - { - return area + " " + address; - } - } -} diff --git a/Modbus.Net/Modbus.Net.FBox/AddressTranslatorFBox.cs b/Modbus.Net/Modbus.Net.FBox/AddressTranslatorFBox.cs deleted file mode 100644 index 7dc48a2..0000000 --- a/Modbus.Net/Modbus.Net.FBox/AddressTranslatorFBox.cs +++ /dev/null @@ -1,80 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; - -namespace Modbus.Net.FBox -{ - public class AddressTranslatorFBox : AddressTranslator - { - protected Dictionary AreaCodeDictionary; - - public AddressTranslatorFBox() - { - AreaCodeDictionary = new Dictionary - { - {"LW", 0}, - {"V", 1}, - {"VW", 2}, - {"VD", 3}, - {"V.B", 4}, - {"I", 5}, - {"IW", 6}, - {"ID", 7}, - {"I.B", 8}, - {"Q", 9}, - {"QW", 10}, - {"QD", 11}, - {"Q.B", 12}, - {"M", 13}, - {"MW", 14}, - {"MD", 15}, - {"M.B", 16}, - {"0X", 20}, - {"1X", 21}, - {"2X", 22}, - {"3X", 23}, - {"4X", 24}, - {"SD", 30}, - {"D", 31}, - {"T_word", 32}, - {"C_word", 33}, - {"DB", 10000}, - }; - } - - public override AddressDef AddressTranslate(string address, bool isRead) - { - var tmpAddress = address.Trim().ToUpper(); - if (tmpAddress.Substring(0, 2) == "DB") - { - var addressSplit = tmpAddress.Split(' '); - if (addressSplit.Length != 2) throw new FormatException(); - addressSplit[0] = addressSplit[0].Substring(2); - return new AddressDef() - { - Area = int.Parse(addressSplit[0]) + AreaCodeDictionary["DB"], - Address = int.Parse(addressSplit[1]) - }; - } - var tmpAddressArray = (tmpAddress.Split(' ')); - string head = tmpAddressArray[0]; - string tail = tmpAddressArray[1]; - return - new AddressDef() - { - Area = AreaCodeDictionary[head], - Address = int.Parse(tail) - }; - } - - public string GetAreaName(int code) - { - if (code < 10000) - return AreaCodeDictionary.FirstOrDefault(p => p.Value == code).Key; - else - return AreaCodeDictionary.FirstOrDefault(p => p.Value == code - code%10000).Key + code%10000; - } - } -} diff --git a/Modbus.Net/Modbus.Net.FBox/Constants.cs b/Modbus.Net/Modbus.Net.FBox/Constants.cs deleted file mode 100644 index 9955fb2..0000000 --- a/Modbus.Net/Modbus.Net.FBox/Constants.cs +++ /dev/null @@ -1,76 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; - -namespace Modbus.Net.FBox -{ - public enum SignalRServer - { - FBoxServer = 0, - DelianServer = 1 - } - - public class Constants - { - public SignalRServer SignalRServer = SignalRServer.FBoxServer; - - public string BaseAddress - { - get - { - switch (SignalRServer) - { - case SignalRServer.FBoxServer: - { - return "https://account.flexem.com/core"; - } - case SignalRServer.DelianServer: - { - return "https://id.data.hzdelian.com/core"; - } - default: - { - return "https://account.flexem.com/core"; - } - } - } - } - - public string AuthorizeEndpoint => BaseAddress + "/connect/authorize"; - - public string LogoutEndpoint => BaseAddress + "/connect/endsession"; - - public string TokenEndpoint => BaseAddress + "/connect/token"; - - public string UserInfoEndpoint => BaseAddress + "/connect/userinfo"; - - public string IdentityTokenValidationEndpoint => BaseAddress + "/connect/identitytokenvalidation"; - - public string TokenRevocationEndpoint => BaseAddress + "/connect/revocation"; - - public string AspNetWebApiSampleApi - { - get - { - switch (SignalRServer) - { - case SignalRServer.FBoxServer: - { - return "http://fbox360.com/api/client/"; - } - case SignalRServer.DelianServer: - { - return "http://wl.data.hzdelian.com/api/client/"; - } - default: - { - return "http://fbox360.com/api/client/"; - } - } - } - } - - } -} diff --git a/Modbus.Net/Modbus.Net.FBox/Entity.cs b/Modbus.Net/Modbus.Net.FBox/Entity.cs deleted file mode 100644 index 7e82f00..0000000 --- a/Modbus.Net/Modbus.Net.FBox/Entity.cs +++ /dev/null @@ -1,286 +0,0 @@ -using System; -using System.Collections.Generic; -using Newtonsoft.Json; - -namespace Modbus.Net.FBox -{ - public class BoxGroup - { - [JsonProperty("boxRegs")] - public List BoxRegs { get; set; } - [JsonProperty("children")] - public List Children { get; set; } - [JsonProperty("id")] - public int Id { get; set; } - [JsonProperty("name")] - public string Name { get; set; } - } - - public class BoxReg - { - [JsonProperty("box")] - public Box Box { get; set; } - [JsonProperty("id")] - public int Id { get; set; } - [JsonProperty("alias")] - public string Alias { get; set; } - [JsonProperty("registrationDate")] - public DateTime RegistrationDate { get; set; } - [JsonProperty("Favorite")] - public bool Favorite { get; set; } - } - - public class Box - { - [JsonProperty("commServer")] - public CommServer CommServer { get; set; } - [JsonProperty("id")] - public int Id { get; set; } - [JsonProperty("uid")] - public string Uid { get; set; } - [JsonProperty("boxNo")] - public string BoxNo { get; set; } - [JsonProperty("connectionState")] - public int ConnectionState { get; set; } - [JsonProperty("allowedCommServerIds")] - public List AllowedCommserverIds { get; set; } - [JsonProperty("currentSessionID")] - public int CurrentSessionId { get; set; } - } - - public class CommServer - { - [JsonProperty("id")] - public int Id { get; set; } - [JsonProperty("serverId")] - public int ServerId { get; set; } - [JsonProperty("apiBaseUrl")] - public string ApiBaseUrl { get; set; } - [JsonProperty("signalrUrl")] - public string SignalRUrl { get; set; } - [JsonProperty("state")] - public int State { get; set; } - [JsonProperty("disabled")] - public bool Disabled { get; set; } - } - - public class GetValue - { - [JsonProperty("id")] - public string Id { get; set; } - [JsonProperty("status")] - public int Status { get; set; } - [JsonProperty("value")] - public double? Value { get; set; } - } - - public class DMonGroup - { - [JsonProperty("id")] - public int Id { get; set; } - [JsonProperty("name")] - public string Name { get; set; } - [JsonProperty("dMonEntries")] - public List DMonEntries { get; set; } - [JsonProperty("uid")] - public string Uid { get; set; } - } - - public class DMonEntry - { - [JsonProperty("src")] - public DMonSource Source { get; set; } - [JsonProperty("id")] - public int Id { get; set; } - [JsonProperty("uid")] - public string Uid { get; set; } - [JsonProperty("fracDigits")] - public int FracDigits { get; set; } - [JsonProperty("intDigits")] - public int IntDigits { get; set; } - [JsonProperty("padLeft")] - public bool PadLeft { get; set; } - [JsonProperty("padRight")] - public bool PadRight { get; set; } - [JsonProperty("updateInterval")] - public int UpdateInterval { get; set; } - [JsonProperty("privilege")] - public int Privilege { get; set; } - [JsonProperty("name")] - public string Name { get; set; } - [JsonProperty("desc")] - public string Desc { get; set; } - [JsonProperty("dataType")] - public int DataType { get; set; } - } - - public class DMonSource - { - [JsonProperty("id")] - public int Id { get; set; } - [JsonProperty("uid")] - public string Uid { get; set; } - [JsonProperty("UpdateInterval")] - public int UpdateInterval { get; set; } - [JsonProperty("isDMon")] - public bool IsDMon { get; set; } - [JsonProperty("isAlarm")] - public bool IsAlarm { get; set; } - [JsonProperty("flag")] - public int Flag { get; set; } - [JsonProperty("regWidth")] - public int RegWidth { get; set; } - [JsonProperty("regId")] - public int RegId { get; set; } - [JsonProperty("mainAddr")] - public int MainAddr { get; set; } - [JsonProperty("subAddr")] - public int SubAddr { get; set; } - [JsonProperty("subIndex")] - public int SubIndex { get; set; } - [JsonProperty("serverId")] - public int ServerId { get; set; } - [JsonProperty("portNo")] - public int PortNo { get; set; } - [JsonProperty("stationNo")] - public int StationNo { get; set; } - [JsonProperty("deviceId")] - public int DeviceId { get; set; } - [JsonProperty("ip")] - public string Ip { get; set; } - [JsonProperty("port")] - public int Port { get; set; } - } - - public class DeviceSpecSource - { - [JsonProperty("id")] - public int Id { get; set; } - [JsonProperty("name")] - public string Name { get; set; } - [JsonProperty("defaultStationNo")] - public int DefaultStationNo { get; set; } - [JsonProperty("minStationNo")] - public int MinStationNo { get; set; } - [JsonProperty("maxStationNo")] - public int MaxStationNo { get; set; } - [JsonProperty("class")] - public int Class { get; set; } - [JsonProperty("comPortParams")] - public ComPortParam ComPortParams { get; set; } - [JsonProperty("ethParams")] - public EthParam EthParams { get; set; } - [JsonProperty("byteOrders")] - public ByteOrder ByteOrders { get; set; } - [JsonProperty("supportedPlcs")] - public List SupportedPlcs { get; set; } - [JsonProperty("regs")] - public List Regs { get; set; } - [JsonProperty("boardcastNo")] - public int BoardcastNo { get; set; } - [JsonProperty("mfr")] - public string Mfr { get; set; } - [JsonProperty("connType")] - public int ConnType { get; set; } - [JsonProperty("driverFileMd5")] - public string DriverFileMd5 { get; set; } - } - - public class ComPortParam - { - [JsonProperty("baudRate")] - public int BaudRate { get; set; } - [JsonProperty("dataBits")] - public int DataBits { get; set; } - [JsonProperty("stopBits")] - public int StopBits { get; set; } - [JsonProperty("parity")] - public int Parity { get; set; } - [JsonProperty("workingMode")] - public int WorkingMode { get; set; } - [JsonProperty("plcResponseTimeout")] - public int PlcResponseTimeout { get; set; } - [JsonProperty("protocalTimeout1")] - public int ProtocalTimeout1 { get; set; } - [JsonProperty("protocalTimeout2")] - public int ProtocalTimeout2 { get; set; } - [JsonProperty("maxPacketsWordReg")] - public int MaxPacketsWordReg { get; set; } - [JsonProperty("maxPacketsBitReg")] - public int MaxPacketsBitReg { get; set; } - [JsonProperty("assembleIntervalBitReg")] - public int AssembleIntervalBitReg { get; set; } - [JsonProperty("listRead")] - public bool ListRead { get; set; } - [JsonProperty("maxList")] - public int MaxList { get; set; } - [JsonProperty("protocalInterval")] - public int ProtocalInterval { get; set; } - } - - public class EthParam - { - [JsonProperty("ip")] - public string Ip { get; set; } - [JsonProperty("port")] - public int Port { get; set; } - [JsonProperty("plcResponseTimeout")] - public int PlcResponseTimeout { get; set; } - [JsonProperty("protocalTimeout1")] - public int ProtocalTimeout1 { get; set; } - [JsonProperty("protocalTimeout2")] - public int ProtocalTimeout2 { get; set; } - [JsonProperty("maxPacketsWordReg")] - public int MaxPacketsWordReg { get; set; } - [JsonProperty("maxPacketsBitReg")] - public int MaxPacketsBitReg { get; set; } - [JsonProperty("assembleIntervalBitReg")] - public int AssembleIntervalBitReg { get; set; } - [JsonProperty("listRead")] - public bool ListRead { get; set; } - [JsonProperty("maxList")] - public int MaxList { get; set; } - [JsonProperty("protocalInterval")] - public int ProtocalInterval { get; set; } - } - - public class ByteOrder - { - [JsonProperty("u16")] - public int U16 { get; set; } - [JsonProperty("u32")] - public int U32 { get; set; } - [JsonProperty("float")] - public int Float { get; set; } - } - - public class AddressTypeReg - { - [JsonProperty("id")] - public int Id { get; set; } - [JsonProperty("name")] - public string Name { get; set; } - [JsonProperty("ioWidth")] - public int IoWidth { get; set; } - [JsonProperty("minMainAddr")] - public int MinMainAddr { get; set; } - [JsonProperty("maxMainAddr")] - public int MaxMainAddr { get; set; } - [JsonProperty("mainAddrType")] - public int MainAddrType { get; set; } - [JsonProperty("subAddrType")] - public int SubAddrType { get; set; } - [JsonProperty("isBigEndian")] - public bool IsBigEndian { get; set; } - [JsonProperty("subAddrLen")] - public int SubAddrLen { get; set; } - [JsonProperty("subIndexType")] - public int SubIndexType { get; set; } - [JsonProperty("minSubIndex")] - public int MinSubIndex { get; set; } - [JsonProperty("maxSubIndex")] - public int MaxSubIndex { get; set; } - [JsonProperty("hasSubIndex")] - public bool HasSubIndex { get; set; } - } -} diff --git a/Modbus.Net/Modbus.Net.FBox/FBoxConnector.cs b/Modbus.Net/Modbus.Net.FBox/FBoxConnector.cs deleted file mode 100644 index bdb21da..0000000 --- a/Modbus.Net/Modbus.Net.FBox/FBoxConnector.cs +++ /dev/null @@ -1,677 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Net; -using System.Net.Http; -using System.Text; -using System.Threading; -using System.Threading.Tasks; -using Microsoft.AspNet.SignalR.Client; -using Newtonsoft.Json; -using IdentityModel.Client; - -namespace Modbus.Net.FBox -{ - public struct SignalRSigninMsg - { - public string ClientId { get; set; } - public string ClientSecret { get; set; } - public string UserId { get; set; } - public string Password { get; set; } - public string SigninAdditionalValues { get; set; } - public SignalRServer SignalRServer { get; set; } - } - - public class FBoxConnector : BaseConnector - { - private TokenClient _oauth2; - private string _refreshToken; - - private HttpClient _httpClient { get; set; } - private HttpClient _httpClient2 { get; set; } - private HubConnection _hubConnection { get; set; } - protected SignalRSigninMsg Msg { get; } - private DMonGroup _dataGroup { get; set; } - private string _groupUid { get; set; } - private string _boxUid { get; set; } - private string _boxNo { get; set; } - private int _boxSessionId { get; set; } - private int _connectionState { get; set; } - private Dictionary _data { get; set; } - private Dictionary _dataType { get; set; } - - private DateTime _timeStamp { get; set; } = DateTime.MinValue; - - public override string ConnectionToken { get; } - - //private AsyncLock _lock = new AsyncLock(); - - private Timer _timer; - - private string MachineId => ConnectionToken.Split(',')[0]; - - private string LocalSequence => ConnectionToken.Split(',')[1]; - - private bool _connected; - public override bool IsConnected => _connected; - - private Constants _constants; - private Constants Constants => _constants ?? (_constants = new Constants()); - - public FBoxConnector(string machineId, string localSequence, SignalRSigninMsg msg) - { - Constants.SignalRServer = msg.SignalRServer; - //System.Net.ServicePointManager.ServerCertificateValidationCallback = delegate { return true; }; - ConnectionToken = machineId + "," + localSequence; - Msg = msg; - _data = new Dictionary(); - _dataType = new Dictionary(); - } - - private async void ChangeToken(object sender) - { - try - { - var tokenResponse = await _oauth2.RequestRefreshTokenAsync(_refreshToken); - _refreshToken = tokenResponse.RefreshToken; - _httpClient.SetBearerToken(tokenResponse.AccessToken); - - _httpClient2.SetBearerToken(tokenResponse.AccessToken); - - _hubConnection.Headers["Authorization"] = "Bearer " + tokenResponse.AccessToken; - await _hubConnection.Start(); - await - _httpClient2.PostAsync( - "dmon/group/" + _dataGroup.Uid + "/start", null); - - } - catch (Exception e) - { - Console.WriteLine("Retoken failed." + e.Message); - } - Console.WriteLine("Retoken success."); - } - - public override bool Connect() - { - return AsyncHelper.RunSync(ConnectAsync); - } - - public override async Task ConnectAsync() - { - try - { - - _oauth2 = new TokenClient( - Constants.TokenEndpoint, - Msg.ClientId, - Msg.ClientSecret - ); - var tokenResponse = await _oauth2.RequestResourceOwnerPasswordAsync - ( - Msg.UserId, - Msg.Password, - Msg.SigninAdditionalValues - ); - if (tokenResponse != null) - { - _refreshToken = tokenResponse.RefreshToken; - if (await CallService(Msg, tokenResponse.AccessToken)) - { - await - _httpClient2.PostAsync( - "dmon/group/" + _dataGroup.Uid + "/start", null); - _connected = true; - _timer = new Timer(ChangeToken, null, 3600*1000*4, 3600*1000*4); - Console.WriteLine("SignalR Connected success"); - _connectionState = 1; - return true; - } - } - _connectionState = 0; - return false; - } - catch (Exception e) - { - _oauth2 = null; - Console.WriteLine("SignalR Connected failed " + e.Message); - Clear(); - _connectionState = 0; - return false; - } - } - - private async Task CallService(SignalRSigninMsg msg, string token) - { - try - { - var guid = Guid.NewGuid().ToString(); - - var baseAddress = Constants.AspNetWebApiSampleApi; - - _httpClient = new HttpClient - { - BaseAddress = new Uri(baseAddress) - }; - - _httpClient.SetBearerToken(token); - - //var response = await _httpClient.GetStringAsync("device/spec"); - - //List deviceSpecs = JsonConvert.DeserializeObject>(response); - //deviceSpecs = deviceSpecs.OrderBy(p => p.Id).ToList(); - - - var response = await _httpClient.GetStringAsync("boxgroup"); - - List boxGroups = JsonConvert.DeserializeObject>(response); - if (boxGroups == null) return false; - - foreach (var boxGroup in boxGroups) - { - var boxes = boxGroup.BoxRegs; - if (boxes == null) continue; - foreach (var box in boxes) - { - var sessionId = box.Box.CurrentSessionId; - var baseUrl = box.Box.CommServer.ApiBaseUrl; - var signalrUrl = box.Box.CommServer.SignalRUrl; - var boxUid = box.Box.Uid; - var boxNo = box.Box.BoxNo; - - if (boxNo != MachineId) continue; - - _httpClient2 = new HttpClient - { - BaseAddress = new Uri(baseUrl) - }; - _httpClient2.SetBearerToken(token); - _httpClient2.DefaultRequestHeaders.Add("X-FBox-ClientId", guid); - - response = await _httpClient2.GetStringAsync("box/" + box.Box.Uid + "/dmon/def/grouped"); - - - List dataGroups = JsonConvert.DeserializeObject>(response); - foreach (var dataGroup in dataGroups) - { - if (dataGroup.Name == LocalSequence) - { - _dataGroup = dataGroup; - break; - } - } - - _boxSessionId = sessionId; - _boxNo = boxNo; - - _hubConnection = new HubConnection(signalrUrl); - _hubConnection.Headers.Add("Authorization", "Bearer " + token); - _hubConnection.Headers.Add("X-FBox-ClientId", guid); - _hubConnection.Headers.Add("X-FBox-Session", sessionId.ToString()); - - IHubProxy dataHubProxy = _hubConnection.CreateHubProxy("clientHub"); - dataHubProxy.On>("dMonUpdateValue", - (boxSessionId, values) => - { - -//#if DEBUG - //Console.WriteLine($"Box session {boxSessionId} return at {DateTime.Now}"); -//#endif - - _timeStamp = DateTime.Now; - - foreach (var value in values) - { - if (value.Status != 0) - { - lock (_data) - { - var dMonEntry = - _dataGroup.DMonEntries.FirstOrDefault( - p => p.Uid == value.Id); - if (dMonEntry != null) - { - if (_data.ContainsKey(dMonEntry.Desc)) - { - _data.Remove(dMonEntry.Desc); - } - } - - } - return; - } - lock (_data) - { - if (_dataGroup.DMonEntries.Any(p => p.Uid == value.Id)) - { - if (_data == null) - { - _data = new Dictionary(); - } - - var dMonEntry = _dataGroup.DMonEntries.FirstOrDefault( - p => p.Uid == value.Id); - - if (value.Value.HasValue && dMonEntry != null) - { - if (_data.ContainsKey(dMonEntry.Desc)) - { - _data[dMonEntry.Desc] = value.Value.Value; - } - else - { - _data.Add(dMonEntry.Desc, value.Value.Value); - } - } - } - } - } - }); - - dataHubProxy.On("boxConnectionStateChanged", - async (newConnectionToken, getBoxUid, oldStatus, newStatus) => - { -#if DEBUG - Console.WriteLine( - $"Box uid {getBoxUid} change state at {DateTime.Now} new connectionToken {newConnectionToken} newStatus {newStatus}"); -#endif - sessionId = newConnectionToken; - _boxSessionId = sessionId; - - //_connectionState = newStatus; - - if (!IsConnected || _httpClient2 == null || _hubConnection == null) - { - Clear(); - return; - } - try - { - while ( - !_httpClient2.DefaultRequestHeaders.TryAddWithoutValidation("X-FBox-Session", - sessionId.ToString())) - { - _httpClient2.DefaultRequestHeaders.Remove("X-FBox-Session"); - } - _httpClient2.DefaultRequestHeaders.Add("X-FBox-Session", sessionId.ToString()); - - - _hubConnection.Headers["X-FBox-Session"] = sessionId.ToString(); - await _hubConnection.Start(); - _data.Clear(); - //if (newStatus == 1) - //{ - //if (IsConnected) - //{ - await - _httpClient2.PostAsync( - "dmon/group/" + _dataGroup.Uid + "/start", null); - //} - //} - - //else - //{ - //lock (_data) - //{ - //_data.Clear(); - //} - //await DisconnectAsync(); - //_connected = false; - //} - } - catch (Exception ex) - { - Console.WriteLine("SignalR boxSessionId change error: " + ex.Message); - await DisconnectAsync(); - _connected = false; - } - }); - - _hubConnection.Error += async ex => - { - Console.WriteLine(@"SignalR error: {0}", ex.Message); - await DisconnectAsync(); - _connected = false; - }; - - _hubConnection.Closed += () => - { - _hubConnection.Dispose(); - _connected = false; - }; - - ServicePointManager.DefaultConnectionLimit = 10; - - if (_dataGroup == null) return false; - - var groupUid = _dataGroup.Uid; - var groupName = _dataGroup.Name; - - if (groupName != "(Default)" && groupName != "默认组") - { - _groupUid = groupUid; - } - if (groupName != "(Default)" && groupName != "默认组") - { - _boxUid = boxUid; - } - - _dataType = new Dictionary(); - if (_dataGroup.DMonEntries != null) - { - foreach (var dMonEntry in _dataGroup.DMonEntries) - { - Type type; - switch (dMonEntry.DataType) - { - //位 - case 0: - { - type = typeof (bool); - break; - } - //16位无符号 - case 1: - { - type = typeof (ushort); - break; - } - //16位有符号 - case 2: - { - type = typeof (short); - break; - } - //32位无符号 - case 11: - { - type = typeof (uint); - break; - } - //32位有符号 - case 12: - { - type = typeof (int); - break; - } - //16位BCD - case 3: - { - type = typeof (short); - break; - } - //32位BCD - case 13: - { - type = typeof (int); - break; - } - //浮点数 - case 16: - { - type = typeof (float); - break; - } - //16位16进制 - case 4: - { - type = typeof (short); - break; - } - //32位16进制 - case 14: - { - type = typeof (int); - break; - } - //16位2进制 - case 5: - { - type = typeof (short); - break; - } - //32位2进制 - case 15: - { - type = typeof (int); - break; - } - default: - { - type = typeof (short); - break; - } - } - - if (!_dataType.ContainsKey(dMonEntry.Desc)) - { - _dataType.Add(dMonEntry.Desc, type); - } - else - { - _dataType[dMonEntry.Desc] = type; - } - } - } - - await _hubConnection.Start(); - await dataHubProxy.Invoke("updateClientId", guid); - - return true; - } - } - return false; - } - catch - { - Clear(); - return false; - } - } - - public override bool Disconnect() - { - return AsyncHelper.RunSync(DisconnectAsync); - } - - public async Task DisconnectAsync() - { - try - { - if (_httpClient2 != null) - { - await - _httpClient2.PostAsync( - "dmon/group/" + _groupUid + "/stop", - null); - } - Clear(); - Console.WriteLine("SignalR Disconnect success"); - _connectionState = 0; - return true; - - } - catch (Exception e) - { - Console.WriteLine("SignalR Disconnect failed " + e.Message); - Clear(); - _connectionState = 0; - return false; - } - } - - private async void Clear() - { - try - { - if (_hubConnection != null) - { - await Task.Run(() => _hubConnection.Stop(TimeSpan.FromSeconds(10))); - _hubConnection = null; - } - } - catch (Exception) - { - _hubConnection = null; - // ignored - } - try - { - if (_httpClient != null) - { - _httpClient.Dispose(); - _httpClient = null; - } - } - catch (Exception) - { - //ignore - } - try - { - if (_httpClient2 != null) - { - _httpClient2.Dispose(); - _httpClient2 = null; - } - } - catch (Exception) - { - //ignore - } - if (_data != null) - { - lock (_data) - { - _data.Clear(); - _dataType.Clear(); - } - } - _timeStamp = DateTime.MinValue; - _connected = false; - try - { - if (_timer != null) - { - _timer.Dispose(); - _timer = null; - } - } - catch (Exception) - { - //ignore - } - } - - public override bool SendMsgWithoutReturn(byte[] message) - { - throw new NotImplementedException(); - } - - public override Task SendMsgWithoutReturnAsync(byte[] message) - { - throw new NotImplementedException(); - } - - public override byte[] SendMsg(byte[] message) - { - return AsyncHelper.RunSync(() => SendMsgAsync(message)); - } - - public override async Task SendMsgAsync(byte[] message) - { - if (_httpClient == null) - { - await DisconnectAsync(); - _connected = false; - return null; - } - - if (_hubConnection.State == ConnectionState.Disconnected) - { - await _hubConnection.Start(); - } - - var formater = new AddressFormaterFBox(); - var translator = new AddressTranslatorFBox(); - - byte[] ans; - - //if (_connectionState != 1) - //{ - //await DisconnectAsync(); - //_connected = false; - //Console.WriteLine($"Return Value Rejected with connectionToken {ConnectionToken}"); - //return null; - //} - - if (_timeStamp == DateTime.MinValue) - { - return Encoding.ASCII.GetBytes("NoData"); - } - - if (DateTime.Now - _timeStamp > TimeSpan.FromMinutes(2)) - { - Console.WriteLine("SignalR Timeout: {0} {1} {2}", _timeStamp, DateTime.Now, ConnectionToken); - if (_connectionState != 1) - { - await DisconnectAsync(); - _connected = false; - return null; - } - } - - Dictionary machineDataValue; - lock (_data) - { - machineDataValue = _data.ToDictionary(pair => pair.Key, pair => pair.Value); - } - var machineDataType = _dataType; - if (machineDataType == null || machineDataType.Count == 0) - { - await DisconnectAsync(); - _connected = false; - Console.WriteLine($"Return Value Rejected with connectionToken {ConnectionToken}"); - return null; - } - - if (machineDataValue == null || machineDataValue.Count == 0) - { - return Encoding.ASCII.GetBytes("NoData"); - } - - int pos = 0; - int area = BigEndianValueHelper.Instance.GetInt(message, ref pos); - int address = BigEndianValueHelper.Instance.GetInt(message, ref pos); - //short count = BigEndianValueHelper.Instance.GetShort(message, ref pos); - object[] dataAns = new object[1]; - try - { - dataAns[0] = - Convert.ChangeType( - machineDataValue[formater.FormatAddress(translator.GetAreaName(area), address)], - machineDataType[formater.FormatAddress(translator.GetAreaName(area), address)]); - } - catch (Exception) - { - if (machineDataValue.Count != machineDataType.Count) - { - await - _httpClient2.PostAsync( - "dmon/group/" + _dataGroup.Uid + "/start", null); - } - return Encoding.ASCII.GetBytes("NoData"); - //dataAns[0] = - //Convert.ChangeType( - //0, - //machineDataType[formater.FormatAddress(translator.GetAreaName(area), address)]); - } - finally - { - ans = BigEndianValueHelper.Instance.ObjectArrayToByteArray(dataAns); - } - - return ans; - } - } -} diff --git a/Modbus.Net/Modbus.Net.FBox/FBoxMachine.cs b/Modbus.Net/Modbus.Net.FBox/FBoxMachine.cs deleted file mode 100644 index 1440914..0000000 --- a/Modbus.Net/Modbus.Net.FBox/FBoxMachine.cs +++ /dev/null @@ -1,16 +0,0 @@ -using System; -using System.Collections.Generic; - -namespace Modbus.Net.FBox -{ - public class FBoxMachine : BaseMachine - { - public FBoxMachine(FBoxType fBoxType, string connectionString, string localSequence, SignalRSigninMsg msg, - IEnumerable getAddresses, bool keepConnect) : base(getAddresses, keepConnect) - { - AddressFormater = new AddressFormaterFBox(); - AddressCombiner = new AddressCombinerFBox(); - BaseUtility = new FBoxUtility(fBoxType, connectionString, localSequence, CommunicateAddresses, msg); - } - } -} diff --git a/Modbus.Net/Modbus.Net.FBox/FBoxProtocal.cs b/Modbus.Net/Modbus.Net.FBox/FBoxProtocal.cs deleted file mode 100644 index 5bf0f95..0000000 --- a/Modbus.Net/Modbus.Net.FBox/FBoxProtocal.cs +++ /dev/null @@ -1,65 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -using Modbus.Net; -using Modbus.Net.FBox; - -namespace Modbus.Net.FBox -{ - public abstract class FBoxProtocal : BaseProtocal - { - public override bool Connect() - { - return ProtocalLinker.Connect(); - } - - public override async Task ConnectAsync() - { - return await ProtocalLinker.ConnectAsync(); - } - } - - public class ReadRequestFBoxInputStruct : InputStruct - { - public ReadRequestFBoxInputStruct(string startAddress, ushort getCount, AddressTranslator addressTranslator) - { - var address = addressTranslator.AddressTranslate(startAddress, true); - Address = address.Address; - Area = address.Area; - GetCount = getCount; - } - - public int Area { get; set; } - public int Address { get; set; } - public ushort GetCount { get; set; } - } - - - public class ReadRequestFBoxOutputStruct : OutputStruct - { - public ReadRequestFBoxOutputStruct(byte[] value) - { - GetValue = value; - } - - public byte[] GetValue { get; private set; } - } - - public class ReadRequestFBoxProtocal : SpecialProtocalUnit - { - public override byte[] Format(InputStruct message) - { - var r_message = (ReadRequestFBoxInputStruct) message; - return Format(r_message.Area, r_message.Address, r_message.GetCount); - } - - public override OutputStruct Unformat(byte[] messageBytes, ref int pos) - { - var values = new byte[messageBytes.Length]; - Array.Copy(messageBytes, pos, values, 0, messageBytes.Length); - return new ReadRequestFBoxOutputStruct(values); - } - } -} diff --git a/Modbus.Net/Modbus.Net.FBox/FBoxProtocalLinker.cs b/Modbus.Net/Modbus.Net.FBox/FBoxProtocalLinker.cs deleted file mode 100644 index d99c3cc..0000000 --- a/Modbus.Net/Modbus.Net.FBox/FBoxProtocalLinker.cs +++ /dev/null @@ -1,25 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; - -namespace Modbus.Net.FBox -{ - public class FBoxProtocalLinker : ProtocalLinker - { - protected FBoxProtocalLinker(string machineId, string localSequence, SignalRSigninMsg msg) - { - _baseConnector = new FBoxConnector(machineId, localSequence, msg); - } - - public override bool CheckRight(byte[] content) - { - if (content != null && content.Length == 6 && Encoding.ASCII.GetString(content) == "NoData") - { - return false; - } - return base.CheckRight(content); - } - } -} diff --git a/Modbus.Net/Modbus.Net.FBox/FBoxSignalRProtocal.cs b/Modbus.Net/Modbus.Net.FBox/FBoxSignalRProtocal.cs deleted file mode 100644 index 35c3f63..0000000 --- a/Modbus.Net/Modbus.Net.FBox/FBoxSignalRProtocal.cs +++ /dev/null @@ -1,16 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; - -namespace Modbus.Net.FBox -{ - public class FBoxSignalRProtocal : FBoxProtocal - { - public FBoxSignalRProtocal(string machineId, string localSequence, SignalRSigninMsg msg) - { - ProtocalLinker = new FBoxSignalRProtocalLinker(machineId, localSequence, msg); - } - } -} diff --git a/Modbus.Net/Modbus.Net.FBox/FBoxSignalRProtocalLinker.cs b/Modbus.Net/Modbus.Net.FBox/FBoxSignalRProtocalLinker.cs deleted file mode 100644 index 1c9ade4..0000000 --- a/Modbus.Net/Modbus.Net.FBox/FBoxSignalRProtocalLinker.cs +++ /dev/null @@ -1,15 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; - -namespace Modbus.Net.FBox -{ - public class FBoxSignalRProtocalLinker : FBoxProtocalLinker - { - public FBoxSignalRProtocalLinker(string machineId, string localSequence, SignalRSigninMsg msg) : base(machineId, localSequence, msg) - { - } - } -} diff --git a/Modbus.Net/Modbus.Net.FBox/FBoxUtility.cs b/Modbus.Net/Modbus.Net.FBox/FBoxUtility.cs deleted file mode 100644 index ebaa7f7..0000000 --- a/Modbus.Net/Modbus.Net.FBox/FBoxUtility.cs +++ /dev/null @@ -1,88 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; - -namespace Modbus.Net.FBox -{ - public enum FBoxType - { - AddressSync = 0, - CommunicationTagSync = 1 - } - - public class FBoxUtility :BaseUtility - { - private FBoxType _fboxType; - private SignalRSigninMsg SigninMsg { get; set; } - - public string LocalSequence { get; set; } - - protected IEnumerable CommunicationUnits { get; set; } - public FBoxType ConnectionType - { - get - { - return _fboxType; - } - set - { - _fboxType = value; - switch (_fboxType) - { - case FBoxType.AddressSync: - { - throw new NotImplementedException(); - } - case FBoxType.CommunicationTagSync: - { - Wrapper = new FBoxSignalRProtocal(ConnectionString, LocalSequence, SigninMsg); - break; - } - } - } - } - - public FBoxUtility(FBoxType fBoxType, string connectionString, string localSequence, IEnumerable communicationUnits, SignalRSigninMsg msg) - { - ConnectionString = connectionString; - LocalSequence = localSequence; - CommunicationUnits = communicationUnits.AsEnumerable(); - SigninMsg = msg; - - ConnectionType = fBoxType; - AddressTranslator = new AddressTranslatorFBox(); - } - - public override void SetConnectionType(int connectionType) - { - ConnectionType = (FBoxType) connectionType; - } - - public override async Task GetDatasAsync(byte belongAddress, byte masterAddress, string startAddress, int getByteCount) - { - try - { - var readRequestFBoxInputStruct = new ReadRequestFBoxInputStruct(startAddress, (ushort)getByteCount, AddressTranslator); - var readRequestSiemensOutputStruct = - await - Wrapper.SendReceiveAsync(Wrapper[typeof(ReadRequestFBoxProtocal)], readRequestFBoxInputStruct) as ReadRequestFBoxOutputStruct; - return new GetDataReturnDef() - { - ReturnValue = readRequestSiemensOutputStruct?.GetValue, - IsLittleEndian = Wrapper[typeof (ReadRequestFBoxProtocal)].IsLittleEndian - }; - } - catch (Exception) - { - return null; - } - } - - public override Task SetDatasAsync(byte belongAddress, byte masterAddress, string startAddress, object[] setContents) - { - throw new NotImplementedException(); - } - } -} diff --git a/Modbus.Net/Modbus.Net.FBox/Modbus.Net.FBox.csproj b/Modbus.Net/Modbus.Net.FBox/Modbus.Net.FBox.csproj deleted file mode 100644 index 340b3b1..0000000 --- a/Modbus.Net/Modbus.Net.FBox/Modbus.Net.FBox.csproj +++ /dev/null @@ -1,92 +0,0 @@ - - - - - Debug - AnyCPU - {492A9231-4184-4CFF-8C01-72B8F73CDACA} - Library - Properties - Modbus.Net.FBox - Modbus.Net.FBox - v4.5 - 512 - - - - true - full - false - bin\Debug\ - DEBUG;TRACE - prompt - 4 - - - pdbonly - true - bin\Release\ - TRACE - prompt - 4 - - - - ..\packages\IdentityModel.1.10.0\lib\net45\IdentityModel.dll - True - - - ..\packages\Microsoft.AspNet.SignalR.Client.2.2.0\lib\net45\Microsoft.AspNet.SignalR.Client.dll - True - - - ..\packages\Newtonsoft.Json.8.0.3\lib\net45\Newtonsoft.Json.dll - True - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - Designer - - - - - - {124ebef2-8960-4447-84cf-1d683b1ef7cc} - Modbus.Net - - - - - \ No newline at end of file diff --git a/Modbus.Net/Modbus.Net.FBox/Modbus.Net.FBox.nuspec b/Modbus.Net/Modbus.Net.FBox/Modbus.Net.FBox.nuspec deleted file mode 100644 index 2eb08c3..0000000 --- a/Modbus.Net/Modbus.Net.FBox/Modbus.Net.FBox.nuspec +++ /dev/null @@ -1,24 +0,0 @@ - - - - Modbus.Net.FBox - 1.1.2 - Modbus.Net.FBox - Chris L.(Luo Sheng) - Hangzhou Delian Information and Science Technology Co., Ltd. - https://github.com/parallelbgls/Modbus.Net/blob/master/LICENSE.md - https://github.com/parallelbgls/Modbus.Net/tree/master/Modbus.Net/Modbus.Net.FBox - false - Modbus.Net FBox Implementation - Copyright 2015 Hangzhou Delian Science and Technology Co.,Ltd. - hardware communicate protocal fbox Delian - - - - - - - - - - \ No newline at end of file diff --git a/Modbus.Net/Modbus.Net.FBox/Properties/AssemblyInfo.cs b/Modbus.Net/Modbus.Net.FBox/Properties/AssemblyInfo.cs deleted file mode 100644 index 133deff..0000000 --- a/Modbus.Net/Modbus.Net.FBox/Properties/AssemblyInfo.cs +++ /dev/null @@ -1,36 +0,0 @@ -using System.Reflection; -using System.Runtime.CompilerServices; -using System.Runtime.InteropServices; - -// 有关程序集的一般信息由以下 -// 控制。更改这些特性值可修改 -// 与程序集关联的信息。 -[assembly: AssemblyTitle("Modbus.Net.FBox")] -[assembly: AssemblyDescription("")] -[assembly: AssemblyConfiguration("")] -[assembly: AssemblyCompany("")] -[assembly: AssemblyProduct("Modbus.Net.FBox")] -[assembly: AssemblyCopyright("Copyright © 2016")] -[assembly: AssemblyTrademark("")] -[assembly: AssemblyCulture("")] - -//将 ComVisible 设置为 false 将使此程序集中的类型 -//对 COM 组件不可见。 如果需要从 COM 访问此程序集中的类型, -//请将此类型的 ComVisible 特性设置为 true。 -[assembly: ComVisible(false)] - -// 如果此项目向 COM 公开,则下列 GUID 用于类型库的 ID -[assembly: Guid("492a9231-4184-4cff-8c01-72b8f73cdaca")] - -// 程序集的版本信息由下列四个值组成: -// -// 主版本 -// 次版本 -// 生成号 -// 修订号 -// -//可以指定所有这些值,也可以使用“生成号”和“修订号”的默认值, -// 方法是按如下所示使用“*”: : -// [assembly: AssemblyVersion("1.0.*")] -[assembly: AssemblyVersion("1.1.0")] -[assembly: AssemblyFileVersion("1.1.0")] diff --git a/Modbus.Net/Modbus.Net.FBox/app.config b/Modbus.Net/Modbus.Net.FBox/app.config deleted file mode 100644 index de5386a..0000000 --- a/Modbus.Net/Modbus.Net.FBox/app.config +++ /dev/null @@ -1,11 +0,0 @@ - - - - - - - - - - - \ No newline at end of file diff --git a/Modbus.Net/Modbus.Net.FBox/packages.config b/Modbus.Net/Modbus.Net.FBox/packages.config deleted file mode 100644 index 92a6a37..0000000 --- a/Modbus.Net/Modbus.Net.FBox/packages.config +++ /dev/null @@ -1,6 +0,0 @@ - - - - - - \ No newline at end of file diff --git a/Modbus.Net/Modbus.Net.OPC.1.1.1.nupkg b/Modbus.Net/Modbus.Net.OPC.1.1.1.nupkg new file mode 100644 index 0000000..7b3e4a7 Binary files /dev/null and b/Modbus.Net/Modbus.Net.OPC.1.1.1.nupkg differ diff --git a/Modbus.Net/Modbus.Net.OPC/DaClientExtend.cs b/Modbus.Net/Modbus.Net.OPC/DaClientExtend.cs index 15acda7..793e36c 100644 --- a/Modbus.Net/Modbus.Net.OPC/DaClientExtend.cs +++ b/Modbus.Net/Modbus.Net.OPC/DaClientExtend.cs @@ -1,8 +1,11 @@ using System; using System.Threading.Tasks; +using Hylasoft.Opc.Common; +using Hylasoft.Opc.Da; +using Opc; using Opc.Da; -namespace Hylasoft.Opc.Da +namespace Modbus.Net.OPC { /// @@ -25,7 +28,7 @@ namespace Hylasoft.Opc.Da public OpcValueResult Read(string tag) { var item = new Item { ItemName = tag }; - var result = _server.Read(new[] { item })[0]; + var result = Server.Read(new[] { item })[0]; CheckResult(result, tag); return new OpcValueResult() { @@ -46,5 +49,13 @@ namespace Hylasoft.Opc.Da public MyDaClient(Uri serverUrl) : base(serverUrl) { } + + private static void CheckResult(IResult result, string tag) + { + if (result == null) + throw new OpcException("The server replied with an empty response"); + if (result.ResultID.ToString() != "S_OK") + throw new OpcException(string.Format("Invalid response from the server. (Response Status: {0}, Opc Tag: {1})", result.ResultID, tag)); + } } } diff --git a/Modbus.Net/Modbus.Net.OPC/Modbus.Net.OPC.csproj b/Modbus.Net/Modbus.Net.OPC/Modbus.Net.OPC.csproj index f67ea1f..04b806d 100644 --- a/Modbus.Net/Modbus.Net.OPC/Modbus.Net.OPC.csproj +++ b/Modbus.Net/Modbus.Net.OPC/Modbus.Net.OPC.csproj @@ -31,23 +31,33 @@ 4 - - ..\packages_local\Opc.Ua.Client.dll + + ..\packages\H.Opc.0.7.0\lib\h-opc.dll + True - - ..\packages_local\Opc.Ua.Configuration.dll + + ..\packages\H.Opc.0.7.0\lib\Opc.Ua.Client.dll + True - - ..\packages_local\Opc.Ua.Core.dll + + ..\packages\H.Opc.0.7.0\lib\Opc.Ua.Configuration.dll + True - - ..\packages_local\OpcComRcw.dll + + ..\packages\H.Opc.0.7.0\lib\Opc.Ua.Core.dll + True - - ..\packages_local\OpcNetApi.dll + + ..\packages\H.Opc.0.7.0\lib\OpcComRcw.dll + True - - ..\packages_local\OpcNetApi.Com.dll + + ..\packages\H.Opc.0.7.0\lib\OpcNetApi.dll + True + + + ..\packages\H.Opc.0.7.0\lib\OpcNetApi.Com.dll + True @@ -71,10 +81,6 @@ - - {4f43b6f0-0c32-4c34-978e-9b8b5b0b6e80} - h-opc - {124ebef2-8960-4447-84cf-1d683b1ef7cc} Modbus.Net @@ -82,6 +88,7 @@ + - \ No newline at end of file diff --git a/Modbus.Net/h-opc/packages.config b/Modbus.Net/h-opc/packages.config deleted file mode 100644 index 34147bc..0000000 --- a/Modbus.Net/h-opc/packages.config +++ /dev/null @@ -1,5 +0,0 @@ - - - - - \ No newline at end of file diff --git a/Modbus.Net/packages_local/Opc.Ua.Client.dll b/Modbus.Net/packages_local/Opc.Ua.Client.dll deleted file mode 100644 index 905d23b..0000000 Binary files a/Modbus.Net/packages_local/Opc.Ua.Client.dll and /dev/null differ diff --git a/Modbus.Net/packages_local/Opc.Ua.Configuration.dll b/Modbus.Net/packages_local/Opc.Ua.Configuration.dll deleted file mode 100644 index a328bb0..0000000 Binary files a/Modbus.Net/packages_local/Opc.Ua.Configuration.dll and /dev/null differ diff --git a/Modbus.Net/packages_local/Opc.Ua.Core.dll b/Modbus.Net/packages_local/Opc.Ua.Core.dll deleted file mode 100644 index 189e309..0000000 Binary files a/Modbus.Net/packages_local/Opc.Ua.Core.dll and /dev/null differ diff --git a/Modbus.Net/packages_local/OpcComRcw.dll b/Modbus.Net/packages_local/OpcComRcw.dll deleted file mode 100644 index 4bdd8b0..0000000 Binary files a/Modbus.Net/packages_local/OpcComRcw.dll and /dev/null differ diff --git a/Modbus.Net/packages_local/OpcNetApi.Com.dll b/Modbus.Net/packages_local/OpcNetApi.Com.dll deleted file mode 100644 index 4a46625..0000000 Binary files a/Modbus.Net/packages_local/OpcNetApi.Com.dll and /dev/null differ diff --git a/Modbus.Net/packages_local/OpcNetApi.dll b/Modbus.Net/packages_local/OpcNetApi.dll deleted file mode 100644 index dcec3dd..0000000 Binary files a/Modbus.Net/packages_local/OpcNetApi.dll and /dev/null differ diff --git a/Modbus.Net/packages_local/README.md b/Modbus.Net/packages_local/README.md deleted file mode 100644 index 32224bc..0000000 --- a/Modbus.Net/packages_local/README.md +++ /dev/null @@ -1,3 +0,0 @@ -## External Packages - -this folder contains all the dependency assemblies which are not handled by NuGet