2016-01-18 update 1 ValueHelper Change, Status machine to two ValueHelpers.

This commit is contained in:
parallelbgls@outlook.com
2016-01-18 15:54:10 +08:00
parent 21635b0ad9
commit 97584e359c
14 changed files with 319 additions and 204 deletions

View File

@@ -27,7 +27,7 @@ namespace CrossLampControl.WebApi.Controllers
Lamp light = new Lamp(); Lamp light = new Lamp();
object[] lampsbyte = _utility.GetDatas(2, 0, "Q 0", new KeyValuePair<Type, int>(typeof(bool), 7)); object[] lampsbyte = _utility.GetDatas(2, 0, "Q 0", new KeyValuePair<Type, int>(typeof(bool), 7));
bool[] lamps = bool[] lamps =
ValueHelper.Instance.ObjectArrayToDestinationArray<bool>( BigEndianValueHelper.Instance.ObjectArrayToDestinationArray<bool>(
lampsbyte); lampsbyte);
if (lamps[0]) if (lamps[0])
{ {

View File

@@ -30,19 +30,19 @@ namespace ModBus.Net
if (initNum < 0) if (initNum < 0)
{ {
initNum = address.Address; initNum = address.Address;
getCount = (int)ValueHelper.Instance.ByteLength[address.DataType.FullName]; getCount = (int)BigEndianValueHelper.Instance.ByteLength[address.DataType.FullName];
} }
else else
{ {
if (address.Address > preNum + ValueHelper.Instance.ByteLength[preType.FullName]) if (address.Address > preNum + BigEndianValueHelper.Instance.ByteLength[preType.FullName])
{ {
ans.Add(new CommunicationUnit(){Area = area, Address = initNum, GetCount = getCount, DataType = typeof(byte)}); ans.Add(new CommunicationUnit(){Area = area, Address = initNum, GetCount = getCount, DataType = typeof(byte)});
initNum = address.Address; initNum = address.Address;
getCount = (int)ValueHelper.Instance.ByteLength[address.DataType.FullName]; getCount = (int)BigEndianValueHelper.Instance.ByteLength[address.DataType.FullName];
} }
else else
{ {
getCount += (int)ValueHelper.Instance.ByteLength[address.DataType.FullName]; getCount += (int)BigEndianValueHelper.Instance.ByteLength[address.DataType.FullName];
} }
} }
preNum = address.Address; preNum = address.Address;

View File

@@ -61,38 +61,61 @@ namespace ModBus.Net
public async Task<Dictionary<string,ReturnUnit>> GetDatasAsync() public async Task<Dictionary<string,ReturnUnit>> GetDatasAsync()
{ {
Dictionary<string, ReturnUnit> ans = new Dictionary<string, ReturnUnit>(); try
if (!BaseUtility.IsConnected)
{ {
await BaseUtility.ConnectAsync(); Dictionary<string, ReturnUnit> ans = new Dictionary<string, ReturnUnit>();
} if (!BaseUtility.IsConnected)
if (!BaseUtility.IsConnected) return null;
foreach (var communicateAddress in CommunicateAddresses)
{
var datas = await BaseUtility.GetDatasAsync<byte>(2, 0, AddressFormater.FormatAddress(communicateAddress.Area,communicateAddress.Address), (int)Math.Ceiling(communicateAddress.GetCount * ValueHelper.Instance.ByteLength[communicateAddress.DataType.FullName]));
if (datas == null || datas.Length == 0) return null;
int pos = 0;
while (pos < communicateAddress.GetCount)
{ {
var address = await BaseUtility.ConnectAsync();
GetAddresses.SingleOrDefault( }
p => p.Area == communicateAddress.Area && p.Address == pos + communicateAddress.Address); if (!BaseUtility.IsConnected) return null;
if (address != null) foreach (var communicateAddress in CommunicateAddresses)
{
var datas =
await
BaseUtility.GetDatasAsync<byte>(2, 0,
AddressFormater.FormatAddress(communicateAddress.Area, communicateAddress.Address),
(int)
Math.Ceiling(communicateAddress.GetCount*
BigEndianValueHelper.Instance.ByteLength[
communicateAddress.DataType.FullName]));
if (datas == null || datas.Length == 0) return null;
int pos = 0;
while (pos < communicateAddress.GetCount)
{ {
ans.Add(address.CommunicationTag, new ReturnUnit{PlcValue = Double.Parse(ValueHelper.Instance.GetValue(datas, ref pos, address.DataType).ToString()) * address.Zoom,UnitExtend = address.UnitExtend}); var address =
} GetAddresses.SingleOrDefault(
else p => p.Area == communicateAddress.Area && p.Address == pos + communicateAddress.Address);
{ if (address != null)
pos++; {
ans.Add(address.CommunicationTag,
new ReturnUnit
{
PlcValue =
Double.Parse(
BigEndianValueHelper.Instance.GetValue(datas, ref pos, address.DataType)
.ToString())*address.Zoom,
UnitExtend = address.UnitExtend
});
}
else
{
pos++;
}
} }
} }
if (!KeepConnect)
{
BaseUtility.Disconnect();
}
if (ans.Count == 0) ans = null;
return ans;
} }
if (!KeepConnect) catch (Exception e)
{ {
BaseUtility.Disconnect(); Console.WriteLine(ConnectionToken + " " + e.Message);
return null;
} }
if (ans.Count == 0) ans = null;
return ans;
} }
public bool Connect() public bool Connect()

View File

@@ -67,10 +67,10 @@ namespace ModBus.Net
try try
{ {
string typeName = getTypeAndCount.Key.FullName; string typeName = getTypeAndCount.Key.FullName;
double bCount = ValueHelper.Instance.ByteLength[typeName]; double bCount = BigEndianValueHelper.Instance.ByteLength[typeName];
byte[] getBytes = GetDatas(belongAddress, masterAddress, startAddress, byte[] getBytes = GetDatas(belongAddress, masterAddress, startAddress,
(int) Math.Ceiling(bCount*getTypeAndCount.Value)); (int) Math.Ceiling(bCount*getTypeAndCount.Value));
return ValueHelper.Instance.ByteArrayToObjectArray(getBytes, getTypeAndCount); return BigEndianValueHelper.Instance.ByteArrayToObjectArray(getBytes, getTypeAndCount);
} }
catch (Exception) catch (Exception)
{ {
@@ -84,10 +84,10 @@ namespace ModBus.Net
try try
{ {
string typeName = getTypeAndCount.Key.FullName; string typeName = getTypeAndCount.Key.FullName;
double bCount = ValueHelper.Instance.ByteLength[typeName]; double bCount = BigEndianValueHelper.Instance.ByteLength[typeName];
byte[] getBytes = await GetDatasAsync(belongAddress, masterAddress, startAddress, byte[] getBytes = await GetDatasAsync(belongAddress, masterAddress, startAddress,
(int) Math.Ceiling(bCount*getTypeAndCount.Value)); (int) Math.Ceiling(bCount*getTypeAndCount.Value));
return ValueHelper.Instance.ByteArrayToObjectArray(getBytes, getTypeAndCount); return BigEndianValueHelper.Instance.ByteArrayToObjectArray(getBytes, getTypeAndCount);
} }
catch (Exception) catch (Exception)
{ {
@@ -102,7 +102,7 @@ namespace ModBus.Net
{ {
var getBytes = GetDatas(belongAddress, masterAddress, startAddress, var getBytes = GetDatas(belongAddress, masterAddress, startAddress,
new KeyValuePair<Type, int>(typeof (T), getByteCount)); new KeyValuePair<Type, int>(typeof (T), getByteCount));
return ValueHelper.Instance.ObjectArrayToDestinationArray<T>(getBytes); return BigEndianValueHelper.Instance.ObjectArrayToDestinationArray<T>(getBytes);
} }
catch (Exception) catch (Exception)
{ {
@@ -117,7 +117,7 @@ namespace ModBus.Net
{ {
var getBytes = await GetDatasAsync(belongAddress, masterAddress, startAddress, var getBytes = await GetDatasAsync(belongAddress, masterAddress, startAddress,
new KeyValuePair<Type, int>(typeof(T), getByteCount)); new KeyValuePair<Type, int>(typeof(T), getByteCount));
return ValueHelper.Instance.ObjectArrayToDestinationArray<T>(getBytes); return BigEndianValueHelper.Instance.ObjectArrayToDestinationArray<T>(getBytes);
} }
catch (Exception) catch (Exception)
{ {
@@ -134,11 +134,11 @@ namespace ModBus.Net
foreach (var getTypeAndCount in getTypeAndCountList) foreach (var getTypeAndCount in getTypeAndCountList)
{ {
string typeName = getTypeAndCount.Key.FullName; string typeName = getTypeAndCount.Key.FullName;
double bCount = ValueHelper.Instance.ByteLength[typeName]; double bCount = BigEndianValueHelper.Instance.ByteLength[typeName];
bAllCount += (int)Math.Ceiling(bCount * getTypeAndCount.Value); bAllCount += (int)Math.Ceiling(bCount * getTypeAndCount.Value);
} }
byte[] getBytes = GetDatas(belongAddress, masterAddress, startAddress, bAllCount); byte[] getBytes = GetDatas(belongAddress, masterAddress, startAddress, bAllCount);
return ValueHelper.Instance.ByteArrayToObjectArray(getBytes, getTypeAndCountList); return BigEndianValueHelper.Instance.ByteArrayToObjectArray(getBytes, getTypeAndCountList);
} }
catch (Exception) catch (Exception)
{ {
@@ -155,11 +155,11 @@ namespace ModBus.Net
foreach (var getTypeAndCount in getTypeAndCountList) foreach (var getTypeAndCount in getTypeAndCountList)
{ {
string typeName = getTypeAndCount.Key.FullName; string typeName = getTypeAndCount.Key.FullName;
double bCount = ValueHelper.Instance.ByteLength[typeName]; double bCount = BigEndianValueHelper.Instance.ByteLength[typeName];
bAllCount += (int)Math.Ceiling(bCount * getTypeAndCount.Value); bAllCount += (int)Math.Ceiling(bCount * getTypeAndCount.Value);
} }
byte[] getBytes = await GetDatasAsync(belongAddress, masterAddress, startAddress, bAllCount); byte[] getBytes = await GetDatasAsync(belongAddress, masterAddress, startAddress, bAllCount);
return ValueHelper.Instance.ByteArrayToObjectArray(getBytes, getTypeAndCountList); return BigEndianValueHelper.Instance.ByteArrayToObjectArray(getBytes, getTypeAndCountList);
} }
catch (Exception) catch (Exception)
{ {

View File

@@ -39,6 +39,7 @@ namespace ModBus.Net.FBox
private static Dictionary<string, Dictionary<string, double>> _machineData; private static Dictionary<string, Dictionary<string, double>> _machineData;
private static Dictionary<string, Dictionary<string, Type>> _machineDataType; private static Dictionary<string, Dictionary<string, Type>> _machineDataType;
private static Dictionary<string, string> _boxUidBoxNo; private static Dictionary<string, string> _boxUidBoxNo;
private static HashSet<string> _connectedDataGroupUid;
public override string ConnectionToken { get; } public override string ConnectionToken { get; }
@@ -59,7 +60,7 @@ namespace ModBus.Net.FBox
} }
} }
private static AsyncLock _lock = new AsyncLock(); private static readonly AsyncLock _lock = new AsyncLock();
private bool _connected; private bool _connected;
public override bool IsConnected { get { return _connected; } } public override bool IsConnected { get { return _connected; } }
@@ -96,6 +97,7 @@ namespace ModBus.Net.FBox
_groupNameBoxUid = new Dictionary<string, string>(); _groupNameBoxUid = new Dictionary<string, string>();
_boxUidDataGroups = new Dictionary<string, List<DMonGroup>>(); _boxUidDataGroups = new Dictionary<string, List<DMonGroup>>();
_boxUidBoxNo = new Dictionary<string, string>(); _boxUidBoxNo = new Dictionary<string, string>();
_connectedDataGroupUid = new HashSet<string>();
_timer = new Timer(ChangeToken, null, 3600 * 1000 * 4, 3600 * 1000 * 4); _timer = new Timer(ChangeToken, null, 3600 * 1000 * 4, 3600 * 1000 * 4);
} }
Msg = msg; Msg = msg;
@@ -105,24 +107,32 @@ namespace ModBus.Net.FBox
{ {
try try
{ {
var tokenResponse = await _oauth2[Msg].RequestRefreshTokenAsync(_refreshToken[Msg]); using (await _lock.LockAsync())
_refreshToken[Msg] = tokenResponse.RefreshToken;
_httpClient[Msg].SetBearerToken(tokenResponse.AccessToken);
foreach (var boxUidMsg in _boxUidMsg)
{ {
if (boxUidMsg.Value.Equals(Msg)) var tokenResponse = await _oauth2[Msg].RequestRefreshTokenAsync(_refreshToken[Msg]);
_refreshToken[Msg] = tokenResponse.RefreshToken;
_httpClient[Msg].SetBearerToken(tokenResponse.AccessToken);
foreach (var boxUidMsg in _boxUidMsg)
{ {
if (_httpClient2.ContainsKey(boxUidMsg.Key) && _hubConnections.ContainsKey(boxUidMsg.Key)) if (boxUidMsg.Value.Equals(Msg))
_httpClient2[boxUidMsg.Key].SetBearerToken(tokenResponse.AccessToken);
_hubConnections[boxUidMsg.Key].Stop();
_hubConnections[boxUidMsg.Key].Headers["Authorization"] = "Bearer " + tokenResponse.AccessToken;
await _hubConnections[boxUidMsg.Key].Start();
var localDataGroups = _boxUidDataGroups[boxUidMsg.Key];
foreach (var localDataGroup in localDataGroups)
{ {
await if (_httpClient2.ContainsKey(boxUidMsg.Key) && _hubConnections.ContainsKey(boxUidMsg.Key))
_httpClient2[boxUidMsg.Key].PostAsync( _httpClient2[boxUidMsg.Key].SetBearerToken(tokenResponse.AccessToken);
"dmon/group/" + localDataGroup.Uid + "/start", null); _hubConnections[boxUidMsg.Key].Stop();
_hubConnections[boxUidMsg.Key].Headers["Authorization"] = "Bearer " +
tokenResponse.AccessToken;
await _hubConnections[boxUidMsg.Key].Start();
var localDataGroups = _boxUidDataGroups[boxUidMsg.Key];
foreach (var localDataGroup in localDataGroups)
{
if (_connectedDataGroupUid.Contains(localDataGroup.Uid))
{
await
_httpClient2[boxUidMsg.Key].PostAsync(
"dmon/group/" + localDataGroup.Uid + "/start", null);
}
}
} }
} }
} }
@@ -174,6 +184,7 @@ namespace ModBus.Net.FBox
_httpClient2[_groupNameBoxUid[ConnectionToken]].PostAsync( _httpClient2[_groupNameBoxUid[ConnectionToken]].PostAsync(
"dmon/group/" + _groupNameUid[ConnectionToken] + "/start", "dmon/group/" + _groupNameUid[ConnectionToken] + "/start",
null); null);
_connectedDataGroupUid.Add(_groupNameUid[ConnectionToken]);
_connected = true; _connected = true;
Console.WriteLine("SignalR Connected success"); Console.WriteLine("SignalR Connected success");
return true; return true;
@@ -199,6 +210,7 @@ namespace ModBus.Net.FBox
private async Task CallService(SignalRSigninMsg msg, string token) private async Task CallService(SignalRSigninMsg msg, string token)
{ {
var guid = Guid.NewGuid().ToString(); var guid = Guid.NewGuid().ToString();
var baseAddress = Constants.AspNetWebApiSampleApi; var baseAddress = Constants.AspNetWebApiSampleApi;
@@ -213,11 +225,11 @@ namespace ModBus.Net.FBox
_httpClient[msg].SetBearerToken(token); _httpClient[msg].SetBearerToken(token);
/*var response = await _httpClient.GetStringAsync("device/spec"); //var response = await _httpClient.GetStringAsync("device/spec");
//List<DeviceSpecSource> deviceSpecs = JsonConvert.DeserializeObject<List<DeviceSpecSource>>(response);
//deviceSpecs = deviceSpecs.OrderBy(p => p.Id).ToList();
List<DeviceSpecSource> deviceSpecs = JsonConvert.DeserializeObject<List<DeviceSpecSource>>(response);
deviceSpecs = deviceSpecs.OrderBy(p => p.Id).ToList();
*/
var response = await _httpClient[msg].GetStringAsync("boxgroup"); var response = await _httpClient[msg].GetStringAsync("boxgroup");
@@ -252,7 +264,10 @@ namespace ModBus.Net.FBox
List<DMonGroup> dataGroups = JsonConvert.DeserializeObject<List<DMonGroup>>(response); List<DMonGroup> dataGroups = JsonConvert.DeserializeObject<List<DMonGroup>>(response);
_boxUidDataGroups.Add(boxUid, dataGroups); _boxUidDataGroups.Add(boxUid, dataGroups);
_boxUidSessionId.Add(boxUid, sessionId); lock (_boxUidSessionId)
{
_boxUidSessionId.Add(boxUid, sessionId);
}
_boxUidBoxNo.Add(boxUid, boxNo); _boxUidBoxNo.Add(boxUid, boxNo);
_boxUidMsg.Add(boxUid, Msg); _boxUidMsg.Add(boxUid, Msg);
@@ -271,7 +286,8 @@ namespace ModBus.Net.FBox
if (_boxUidSessionId.ContainsValue(boxSessionId)) if (_boxUidSessionId.ContainsValue(boxSessionId))
{ {
Console.WriteLine($"Box session {boxSessionId} return at {DateTime.Now}"); Console.WriteLine($"Box session {boxSessionId} return at {DateTime.Now}");
var localBoxUid = _boxUidSessionId.FirstOrDefault(p => p.Value == boxSessionId).Key; var localBoxUid =
_boxUidSessionId.FirstOrDefault(p => p.Value == boxSessionId).Key;
var localBoxNo = _boxUidBoxNo[localBoxUid]; var localBoxNo = _boxUidBoxNo[localBoxUid];
foreach (var value in values) foreach (var value in values)
@@ -287,10 +303,12 @@ namespace ModBus.Net.FBox
var dMonEntry = var dMonEntry =
dataGroupInner.DMonEntries.FirstOrDefault( dataGroupInner.DMonEntries.FirstOrDefault(
p => p.Uid == value.Id); p => p.Uid == value.Id);
if (dMonEntry != null && _machineData.ContainsKey(localBoxNo + "," + dataGroupInner.Name)) if (dMonEntry != null &&
_machineData.ContainsKey(localBoxNo + "," +
dataGroupInner.Name))
{ {
if (_machineData[localBoxNo + "," + dataGroupInner.Name] if (_machineData[localBoxNo + "," + dataGroupInner.Name]
.ContainsKey(dMonEntry.Desc)) .ContainsKey(dMonEntry.Desc))
{ {
_machineData[localBoxNo + "," + dataGroupInner.Name] _machineData[localBoxNo + "," + dataGroupInner.Name]
.Remove(dMonEntry.Desc); .Remove(dMonEntry.Desc);
@@ -309,12 +327,15 @@ namespace ModBus.Net.FBox
{ {
if (dataGroupInner.DMonEntries.Any(p => p.Uid == value.Id)) if (dataGroupInner.DMonEntries.Any(p => p.Uid == value.Id))
{ {
if (!_machineData.ContainsKey(localBoxNo + "," + dataGroupInner.Name)) if (
!_machineData.ContainsKey(localBoxNo + "," +
dataGroupInner.Name))
{ {
_machineData.Add(localBoxNo + "," + dataGroupInner.Name, _machineData.Add(localBoxNo + "," + dataGroupInner.Name,
new Dictionary<string, double>()); new Dictionary<string, double>());
} }
if (_machineData[localBoxNo + "," + dataGroupInner.Name] == null) if (_machineData[localBoxNo + "," + dataGroupInner.Name] ==
null)
{ {
_machineData[localBoxNo + "," + dataGroupInner.Name] = _machineData[localBoxNo + "," + dataGroupInner.Name] =
new Dictionary<string, double>(); new Dictionary<string, double>();
@@ -327,16 +348,19 @@ namespace ModBus.Net.FBox
if (value.Value.HasValue && dMonEntry != null) if (value.Value.HasValue && dMonEntry != null)
{ {
if ( if (
_machineData[localBoxNo + "," + dataGroupInner.Name].ContainsKey( _machineData[localBoxNo + "," + dataGroupInner.Name]
dMonEntry.Desc)) .ContainsKey(
dMonEntry.Desc))
{ {
_machineData[localBoxNo + "," + dataGroupInner.Name][dMonEntry.Desc] = _machineData[localBoxNo + "," + dataGroupInner.Name]
[dMonEntry.Desc] =
value.Value.Value; value.Value.Value;
} }
else else
{ {
_machineData[localBoxNo + "," + dataGroupInner.Name].Add(dMonEntry.Desc, _machineData[localBoxNo + "," + dataGroupInner.Name]
value.Value.Value); .Add(dMonEntry.Desc,
value.Value.Value);
} }
} }
break; break;
@@ -370,13 +394,17 @@ namespace ModBus.Net.FBox
{ {
foreach (var localDataGroup in localDataGroups) foreach (var localDataGroup in localDataGroups)
{ {
if (!_connectionTokenState.ContainsKey(localBoxNo + "," + localDataGroup.Name)) if (
!_connectionTokenState.ContainsKey(localBoxNo + "," +
localDataGroup.Name))
{ {
_connectionTokenState.Add(localBoxNo + "," + localDataGroup.Name, newStatus); _connectionTokenState.Add(localBoxNo + "," + localDataGroup.Name,
newStatus);
} }
else else
{ {
_connectionTokenState[localBoxNo + "," + localDataGroup.Name] = newStatus; _connectionTokenState[localBoxNo + "," + localDataGroup.Name] =
newStatus;
} }
} }
} }
@@ -390,13 +418,16 @@ namespace ModBus.Net.FBox
await _hubConnections[getBoxUid].Start(); await _hubConnections[getBoxUid].Start();
} }
if (newStatus == 1 && IsConnected) if (newStatus == 1)
{ {
foreach (var localDataGroup in localDataGroups) foreach (var localDataGroup in localDataGroups)
{ {
await if (_connectedDataGroupUid.Contains(localDataGroup.Uid))
_httpClient2[getBoxUid].PostAsync( {
"dmon/group/" + localDataGroup.Uid + "/start", null); await
_httpClient2[getBoxUid].PostAsync(
"dmon/group/" + localDataGroup.Uid + "/start", null);
}
} }
} }
} }
@@ -423,15 +454,18 @@ namespace ModBus.Net.FBox
var groupUid = dataGroup.Uid; var groupUid = dataGroup.Uid;
var groupName = dataGroup.Name; var groupName = dataGroup.Name;
if (groupName != "(Default)" && groupName != "默认组" && !_connectionTokenState.ContainsKey(boxNo + "," + groupName)) if (groupName != "(Default)" && groupName != "默认组" &&
!_connectionTokenState.ContainsKey(boxNo + "," + groupName))
{ {
_connectionTokenState.Add(boxNo + "," + groupName, 1); _connectionTokenState.Add(boxNo + "," + groupName, 1);
} }
if (groupName != "(Default)" && groupName != "默认组" && !_groupNameUid.ContainsKey(boxNo + "," + groupName)) if (groupName != "(Default)" && groupName != "默认组" &&
!_groupNameUid.ContainsKey(boxNo + "," + groupName))
{ {
_groupNameUid.Add(boxNo + "," + groupName, groupUid); _groupNameUid.Add(boxNo + "," + groupName, groupUid);
} }
if (groupName != "(Default)" && groupName != "默认组" && !_groupNameBoxUid.ContainsKey(boxNo + "," + groupName)) if (groupName != "(Default)" && groupName != "默认组" &&
!_groupNameBoxUid.ContainsKey(boxNo + "," + groupName))
{ {
_groupNameBoxUid.Add(boxNo + "," + groupName, boxUid); _groupNameBoxUid.Add(boxNo + "," + groupName, boxUid);
} }
@@ -542,61 +576,70 @@ namespace ModBus.Net.FBox
await hubConnection.Start(); await hubConnection.Start();
await dataHubProxy.Invoke("updateClientId", guid); await dataHubProxy.Invoke("updateClientId", guid);
} }
} }
} }
private async Task ConnectRecovery(HubConnection hubConnection) private async Task ConnectRecovery(HubConnection hubConnection)
{ {
string getBoxUid; using (await _lock.LockAsync())
lock (_boxUidSessionId)
{ {
getBoxUid = string getBoxUid;
_boxUidSessionId.FirstOrDefault( lock (_boxUidSessionId)
p => p.Value == int.Parse(hubConnection.Headers["X-FBox-Session"])).Key;
}
try
{
if (hubConnection.State != ConnectionState.Connected)
{ {
try getBoxUid =
_boxUidSessionId.FirstOrDefault(
p => p.Value == int.Parse(hubConnection.Headers["X-FBox-Session"])).Key;
}
try
{
if (hubConnection.State != ConnectionState.Connected)
{ {
hubConnection.Stop(); try
} {
catch hubConnection.Stop();
{ }
// ignored catch
} {
// ignored
}
await hubConnection.Start(); await hubConnection.Start();
if (IsConnected)
{
var localDataGroups = _boxUidDataGroups[getBoxUid]; var localDataGroups = _boxUidDataGroups[getBoxUid];
foreach (var localDataGroup in localDataGroups) foreach (var localDataGroup in localDataGroups)
{ {
await if (_connectedDataGroupUid.Contains(localDataGroup.Uid))
_httpClient2[getBoxUid].PostAsync(
"dmon/group/" + localDataGroup.Uid + "/start", null);
}
}
}
}
catch
{
if (_boxUidBoxNo.ContainsKey(getBoxUid))
{
var localBoxNo = _boxUidBoxNo[getBoxUid];
lock (_machineData)
{
foreach (var machineDataUnit in _machineData)
{
if (machineDataUnit.Key.Contains(localBoxNo))
{ {
_machineData.Remove(machineDataUnit.Key); await
_httpClient2[getBoxUid].PostAsync(
"dmon/group/" + localDataGroup.Uid + "/start", null);
} }
} }
} }
} }
_connected = false; catch
{
if (_boxUidBoxNo.ContainsKey(getBoxUid))
{
var localBoxNo = _boxUidBoxNo[getBoxUid];
lock (_machineData)
{
foreach (var machineDataUnit in _machineData)
{
if (machineDataUnit.Key.Contains(localBoxNo))
{
_machineData.Remove(machineDataUnit.Key);
}
}
}
}
var localDataGroups = _boxUidDataGroups[getBoxUid];
foreach (var localDataGroup in localDataGroups)
{
_connectedDataGroupUid.RemoveWhere(p => p == localDataGroup.Uid);
}
_connected = false;
}
} }
} }
@@ -619,6 +662,7 @@ namespace ModBus.Net.FBox
_httpClient2[_groupNameBoxUid[ConnectionToken]].PostAsync( _httpClient2[_groupNameBoxUid[ConnectionToken]].PostAsync(
"dmon/group/" + _groupNameUid[ConnectionToken] + "/stop", "dmon/group/" + _groupNameUid[ConnectionToken] + "/stop",
null); null);
_connectedDataGroupUid.RemoveWhere(p => p == _groupNameUid[ConnectionToken]);
_connected = false; _connected = false;
Console.WriteLine("SignalR Disconnect success"); Console.WriteLine("SignalR Disconnect success");
return true; return true;
@@ -687,9 +731,9 @@ namespace ModBus.Net.FBox
return null; return null;
} }
int pos = 0; int pos = 0;
int area = ValueHelper.Instance.GetInt(message, ref pos); int area = BigEndianValueHelper.Instance.GetInt(message, ref pos);
int address = ValueHelper.Instance.GetInt(message, ref pos); int address = BigEndianValueHelper.Instance.GetInt(message, ref pos);
//short count = ValueHelper.Instance.GetShort(message, ref pos); //short count = BigEndianValueHelper.Instance.GetShort(message, ref pos);
object[] dataAns = new object[1]; object[] dataAns = new object[1];
try try
{ {
@@ -707,7 +751,7 @@ namespace ModBus.Net.FBox
} }
finally finally
{ {
ans = ValueHelper.Instance.ObjectArrayToByteArray(dataAns); ans = BigEndianValueHelper.Instance.ObjectArrayToByteArray(dataAns);
} }
} }

View File

@@ -104,9 +104,9 @@ namespace ModBus.Net.Modbus
public override OutputStruct Unformat(byte[] messageBytes, ref int pos) public override OutputStruct Unformat(byte[] messageBytes, ref int pos)
{ {
byte belongAddress = ValueHelper.Instance.GetByte(messageBytes, ref pos); byte belongAddress = BigEndianValueHelper.Instance.GetByte(messageBytes, ref pos);
byte functionCode = ValueHelper.Instance.GetByte(messageBytes, ref pos); byte functionCode = BigEndianValueHelper.Instance.GetByte(messageBytes, ref pos);
byte dataCount = ValueHelper.Instance.GetByte(messageBytes, ref pos); byte dataCount = BigEndianValueHelper.Instance.GetByte(messageBytes, ref pos);
byte[] dataValue = new byte[dataCount]; byte[] dataValue = new byte[dataCount];
Array.Copy(messageBytes, 3, dataValue, 0, dataCount); Array.Copy(messageBytes, 3, dataValue, 0, dataCount);
return new ReadDataModbusOutputStruct(belongAddress, functionCode, dataCount, dataValue); return new ReadDataModbusOutputStruct(belongAddress, functionCode, dataCount, dataValue);
@@ -178,10 +178,10 @@ namespace ModBus.Net.Modbus
public override OutputStruct Unformat(byte[] messageBytes, ref int flag) public override OutputStruct Unformat(byte[] messageBytes, ref int flag)
{ {
byte belongAddress = ValueHelper.Instance.GetByte(messageBytes, ref flag); byte belongAddress = BigEndianValueHelper.Instance.GetByte(messageBytes, ref flag);
byte functionCode = ValueHelper.Instance.GetByte(messageBytes, ref flag); byte functionCode = BigEndianValueHelper.Instance.GetByte(messageBytes, ref flag);
ushort startAddress = ValueHelper.Instance.GetUShort(messageBytes, ref flag); ushort startAddress = BigEndianValueHelper.Instance.GetUShort(messageBytes, ref flag);
ushort writeCount = ValueHelper.Instance.GetUShort(messageBytes, ref flag); ushort writeCount = BigEndianValueHelper.Instance.GetUShort(messageBytes, ref flag);
return new WriteDataModbusOutputStruct(belongAddress, functionCode, startAddress, return new WriteDataModbusOutputStruct(belongAddress, functionCode, startAddress,
writeCount); writeCount);
} }
@@ -244,16 +244,16 @@ namespace ModBus.Net.Modbus
public override OutputStruct Unformat(byte[] messageBytes, ref int flag) public override OutputStruct Unformat(byte[] messageBytes, ref int flag)
{ {
byte belongAddress = ValueHelper.Instance.GetByte(messageBytes, ref flag); byte belongAddress = BigEndianValueHelper.Instance.GetByte(messageBytes, ref flag);
byte functionCode = ValueHelper.Instance.GetByte(messageBytes, ref flag); byte functionCode = BigEndianValueHelper.Instance.GetByte(messageBytes, ref flag);
byte writeByteCount = ValueHelper.Instance.GetByte(messageBytes, ref flag); byte writeByteCount = BigEndianValueHelper.Instance.GetByte(messageBytes, ref flag);
ushort year = ValueHelper.Instance.GetUShort(messageBytes, ref flag); ushort year = BigEndianValueHelper.Instance.GetUShort(messageBytes, ref flag);
byte day = ValueHelper.Instance.GetByte(messageBytes, ref flag); byte day = BigEndianValueHelper.Instance.GetByte(messageBytes, ref flag);
byte month = ValueHelper.Instance.GetByte(messageBytes, ref flag); byte month = BigEndianValueHelper.Instance.GetByte(messageBytes, ref flag);
ushort hour = ValueHelper.Instance.GetUShort(messageBytes, ref flag); ushort hour = BigEndianValueHelper.Instance.GetUShort(messageBytes, ref flag);
byte second = ValueHelper.Instance.GetByte(messageBytes, ref flag); byte second = BigEndianValueHelper.Instance.GetByte(messageBytes, ref flag);
byte minute = ValueHelper.Instance.GetByte(messageBytes, ref flag); byte minute = BigEndianValueHelper.Instance.GetByte(messageBytes, ref flag);
ushort millisecond = ValueHelper.Instance.GetUShort(messageBytes, ref flag); ushort millisecond = BigEndianValueHelper.Instance.GetUShort(messageBytes, ref flag);
return new GetSystemTimeModbusOutputStruct(belongAddress, functionCode, writeByteCount, year, day, return new GetSystemTimeModbusOutputStruct(belongAddress, functionCode, writeByteCount, year, day,
month, hour, second, minute, millisecond); month, hour, second, minute, millisecond);
} }
@@ -341,10 +341,10 @@ namespace ModBus.Net.Modbus
public override OutputStruct Unformat(byte[] messageBytes, ref int flag) public override OutputStruct Unformat(byte[] messageBytes, ref int flag)
{ {
byte belongAddress = ValueHelper.Instance.GetByte(messageBytes, ref flag); byte belongAddress = BigEndianValueHelper.Instance.GetByte(messageBytes, ref flag);
byte functionCode = ValueHelper.Instance.GetByte(messageBytes, ref flag); byte functionCode = BigEndianValueHelper.Instance.GetByte(messageBytes, ref flag);
ushort startAddress = ValueHelper.Instance.GetUShort(messageBytes, ref flag); ushort startAddress = BigEndianValueHelper.Instance.GetUShort(messageBytes, ref flag);
ushort writeCount = ValueHelper.Instance.GetUShort(messageBytes, ref flag); ushort writeCount = BigEndianValueHelper.Instance.GetUShort(messageBytes, ref flag);
return new SetSystemTimeModbusOutputStruct(belongAddress, functionCode, startAddress, writeCount); return new SetSystemTimeModbusOutputStruct(belongAddress, functionCode, startAddress, writeCount);
} }
} }

View File

@@ -13,8 +13,8 @@ namespace ModBus.Net.Modbus
byte[] newFormat = new byte[6 + content.Length]; byte[] newFormat = new byte[6 + content.Length];
int tag = 0; int tag = 0;
ushort leng = (ushort)content.Length; ushort leng = (ushort)content.Length;
Array.Copy(ValueHelper.Instance.GetBytes(tag), 0, newFormat, 0, 4); Array.Copy(BigEndianValueHelper.Instance.GetBytes(tag), 0, newFormat, 0, 4);
Array.Copy(ValueHelper.Instance.GetBytes(leng), 0, newFormat, 4, 2); Array.Copy(BigEndianValueHelper.Instance.GetBytes(leng), 0, newFormat, 4, 2);
Array.Copy(content, 0, newFormat, 6, content.Length); Array.Copy(content, 0, newFormat, 6, content.Length);
return newFormat; return newFormat;
} }

View File

@@ -36,7 +36,7 @@ namespace ModBus.Net
/// <returns></returns> /// <returns></returns>
public static byte[] TranslateContent(params object[] contents) public static byte[] TranslateContent(params object[] contents)
{ {
return ValueHelper.Instance.ObjectArrayToByteArray(contents); return BigEndianValueHelper.Instance.ObjectArrayToByteArray(contents);
} }
} }

View File

@@ -99,19 +99,19 @@ namespace ModBus.Net.Siemens
case 0xc0: case 0xc0:
{ {
pos += 2; pos += 2;
tdpuSize = ValueHelper.Instance.GetByte(messageBytes, ref pos); tdpuSize = BigEndianValueHelper.Instance.GetByte(messageBytes, ref pos);
break; break;
} }
case 0xc1: case 0xc1:
{ {
pos += 2; pos += 2;
srcTsap = ValueHelper.Instance.GetUShort(messageBytes, ref pos); srcTsap = BigEndianValueHelper.Instance.GetUShort(messageBytes, ref pos);
break; break;
} }
case 0xc2: case 0xc2:
{ {
pos += 2; pos += 2;
dstTsap = ValueHelper.Instance.GetUShort(messageBytes, ref pos); dstTsap = BigEndianValueHelper.Instance.GetUShort(messageBytes, ref pos);
break; break;
} }
} }
@@ -174,11 +174,11 @@ namespace ModBus.Net.Siemens
public override OutputStruct Unformat(byte[] messageBytes, ref int pos) public override OutputStruct Unformat(byte[] messageBytes, ref int pos)
{ {
pos = 4; pos = 4;
ushort pduRef = ValueHelper.Instance.GetUShort(messageBytes, ref pos); ushort pduRef = BigEndianValueHelper.Instance.GetUShort(messageBytes, ref pos);
pos = 14; pos = 14;
ushort maxCalling = ValueHelper.Instance.GetUShort(messageBytes, ref pos); ushort maxCalling = BigEndianValueHelper.Instance.GetUShort(messageBytes, ref pos);
ushort maxCalled = ValueHelper.Instance.GetUShort(messageBytes, ref pos); ushort maxCalled = BigEndianValueHelper.Instance.GetUShort(messageBytes, ref pos);
ushort maxPdu = ValueHelper.Instance.GetUShort(messageBytes, ref pos); ushort maxPdu = BigEndianValueHelper.Instance.GetUShort(messageBytes, ref pos);
return new EstablishAssociationSiemensOutputStruct(pduRef,maxCalling,maxCalled,maxPdu); return new EstablishAssociationSiemensOutputStruct(pduRef,maxCalling,maxCalled,maxPdu);
} }
} }
@@ -244,7 +244,7 @@ namespace ModBus.Net.Siemens
ushort dbBlock = r_message.DbBlock; ushort dbBlock = r_message.DbBlock;
byte area = r_message.Area; byte area = r_message.Area;
int offsetBit = r_message.Offset*8; int offsetBit = r_message.Offset*8;
byte[] offsetBitBytes = ValueHelper.Instance.GetBytes(offsetBit); byte[] offsetBitBytes = BigEndianValueHelper.Instance.GetBytes(offsetBit);
return Format(new byte[7], protoId, rosctr, redId, pduRef, parLg, datLg, serviceId, numberOfVariables return Format(new byte[7], protoId, rosctr, redId, pduRef, parLg, datLg, serviceId, numberOfVariables
, variableSpec, vAddrLg, syntaxId, type, numberOfElements, dbBlock, area, , variableSpec, vAddrLg, syntaxId, type, numberOfElements, dbBlock, area,
offsetBitBytes.Skip(1).ToArray()); offsetBitBytes.Skip(1).ToArray());
@@ -253,11 +253,11 @@ namespace ModBus.Net.Siemens
public override OutputStruct Unformat(byte[] messageBytes, ref int pos) public override OutputStruct Unformat(byte[] messageBytes, ref int pos)
{ {
pos = 4; pos = 4;
ushort pduRef = ValueHelper.Instance.GetUShort(messageBytes, ref pos); ushort pduRef = BigEndianValueHelper.Instance.GetUShort(messageBytes, ref pos);
pos = 14; pos = 14;
byte accessResult = ValueHelper.Instance.GetByte(messageBytes, ref pos); byte accessResult = BigEndianValueHelper.Instance.GetByte(messageBytes, ref pos);
byte dataType = ValueHelper.Instance.GetByte(messageBytes, ref pos); byte dataType = BigEndianValueHelper.Instance.GetByte(messageBytes, ref pos);
ushort length = ValueHelper.Instance.GetUShort(messageBytes, ref pos); ushort length = BigEndianValueHelper.Instance.GetUShort(messageBytes, ref pos);
int byteLength = length/8; int byteLength = length/8;
var values = new Byte[byteLength]; var values = new Byte[byteLength];
Array.Copy(messageBytes, pos, values, 0, byteLength); Array.Copy(messageBytes, pos, values, 0, byteLength);
@@ -304,7 +304,7 @@ namespace ModBus.Net.Siemens
public override byte[] Format(InputStruct message) public override byte[] Format(InputStruct message)
{ {
var r_message = (WriteRequestSiemensInputStruct) message; var r_message = (WriteRequestSiemensInputStruct) message;
byte[] valueBytes = ValueHelper.Instance.ObjectArrayToByteArray(r_message.WriteValue); byte[] valueBytes = BigEndianValueHelper.Instance.ObjectArrayToByteArray(r_message.WriteValue);
const byte protoId = 0x32; const byte protoId = 0x32;
const byte rosctr = 0x01; const byte rosctr = 0x01;
const ushort redId = 0x0000; const ushort redId = 0x0000;
@@ -321,7 +321,7 @@ namespace ModBus.Net.Siemens
ushort dbBlock = r_message.DbBlock; ushort dbBlock = r_message.DbBlock;
byte area = r_message.Area; byte area = r_message.Area;
int offsetBit = r_message.Offset * 8; int offsetBit = r_message.Offset * 8;
byte[] offsetBitBytes = ValueHelper.Instance.GetBytes(offsetBit); byte[] offsetBitBytes = BigEndianValueHelper.Instance.GetBytes(offsetBit);
const byte reserved = 0x00; const byte reserved = 0x00;
const byte type = (byte)SiemensDataType.OtherAccess; const byte type = (byte)SiemensDataType.OtherAccess;
ushort numberOfWriteBits = (ushort)(valueBytes.Length*8); ushort numberOfWriteBits = (ushort)(valueBytes.Length*8);
@@ -333,9 +333,9 @@ namespace ModBus.Net.Siemens
public override OutputStruct Unformat(byte[] messageBytes, ref int pos) public override OutputStruct Unformat(byte[] messageBytes, ref int pos)
{ {
pos = 4; pos = 4;
ushort pduRef = ValueHelper.Instance.GetUShort(messageBytes, ref pos); ushort pduRef = BigEndianValueHelper.Instance.GetUShort(messageBytes, ref pos);
pos = 14; pos = 14;
byte accessResult = ValueHelper.Instance.GetByte(messageBytes, ref pos); byte accessResult = BigEndianValueHelper.Instance.GetByte(messageBytes, ref pos);
return new WriteRequestSiemensOutputStruct(pduRef, (SiemensAccessResult)accessResult); return new WriteRequestSiemensOutputStruct(pduRef, (SiemensAccessResult)accessResult);
} }
} }

View File

@@ -7,7 +7,7 @@ namespace ModBus.Net.Siemens
public override byte[] BytesExtend(byte[] content) public override byte[] BytesExtend(byte[] content)
{ {
Array.Copy(new byte[]{0x03,0x00,0x00,0x00,0x02,0xf0,0x80}, 0, content, 0, 7); Array.Copy(new byte[]{0x03,0x00,0x00,0x00,0x02,0xf0,0x80}, 0, content, 0, 7);
Array.Copy(ValueHelper.Instance.GetBytes((ushort)content.Length), 0, content, 2, 2); Array.Copy(BigEndianValueHelper.Instance.GetBytes((ushort)content.Length), 0, content, 2, 2);
return content; return content;
} }

View File

@@ -7,9 +7,9 @@
get get
{ {
var pos = 15; var pos = 15;
return ValueHelper.Instance.GetBit(ValueHelper.Instance.GetBytes(TodValue), ref pos); return BigEndianValueHelper.Instance.GetBit(BigEndianValueHelper.Instance.GetBytes(TodValue), ref pos);
} }
set { TodValue = ValueHelper.Instance.SetBit(ValueHelper.Instance.GetBytes(TodValue), 15, value); } set { TodValue = BigEndianValueHelper.Instance.SetBit(BigEndianValueHelper.Instance.GetBytes(TodValue), 15, value); }
} }
public byte K0_4 public byte K0_4
@@ -17,13 +17,13 @@
get get
{ {
var pos = 0; var pos = 0;
var byteValue = ValueHelper.Instance.GetByte(ValueHelper.Instance.GetBytes(TodValue), ref pos); var byteValue = BigEndianValueHelper.Instance.GetByte(BigEndianValueHelper.Instance.GetBytes(TodValue), ref pos);
return (byte)(byteValue%64/4); return (byte)(byteValue%64/4);
} }
set set
{ {
var pos = 0; var pos = 0;
var byteValue = ValueHelper.Instance.GetByte(ValueHelper.Instance.GetBytes(TodValue), ref pos); var byteValue = BigEndianValueHelper.Instance.GetByte(BigEndianValueHelper.Instance.GetBytes(TodValue), ref pos);
byteValue = (byte)(byteValue - (byteValue%128/4) + value); byteValue = (byte)(byteValue - (byteValue%128/4) + value);
TodValue = (ushort)(TodValue%128 + byteValue*128); TodValue = (ushort)(TodValue%128 + byteValue*128);
} }
@@ -34,9 +34,9 @@
get get
{ {
var pos = 5; var pos = 5;
return ValueHelper.Instance.GetBit(ValueHelper.Instance.GetBytes(TodValue), ref pos); return BigEndianValueHelper.Instance.GetBit(BigEndianValueHelper.Instance.GetBytes(TodValue), ref pos);
} }
set { TodValue = ValueHelper.Instance.SetBit(ValueHelper.Instance.GetBytes(TodValue), 5, value); } set { TodValue = BigEndianValueHelper.Instance.SetBit(BigEndianValueHelper.Instance.GetBytes(TodValue), 5, value); }
} }
public byte UA public byte UA
@@ -44,15 +44,15 @@
get get
{ {
var pos = 3; var pos = 3;
var low = ValueHelper.Instance.GetBit(ValueHelper.Instance.GetBytes(TodValue), ref pos) ? 1 : 0; var low = BigEndianValueHelper.Instance.GetBit(BigEndianValueHelper.Instance.GetBytes(TodValue), ref pos) ? 1 : 0;
var high = ValueHelper.Instance.GetBit(ValueHelper.Instance.GetBytes(TodValue), ref pos) ? 1 : 0; var high = BigEndianValueHelper.Instance.GetBit(BigEndianValueHelper.Instance.GetBytes(TodValue), ref pos) ? 1 : 0;
high *= 2; high *= 2;
return (byte) (high + low); return (byte) (high + low);
} }
set set
{ {
TodValue = ValueHelper.Instance.SetBit(ValueHelper.Instance.GetBytes(TodValue), 3, value % 2 >= 1); TodValue = BigEndianValueHelper.Instance.SetBit(BigEndianValueHelper.Instance.GetBytes(TodValue), 3, value % 2 >= 1);
TodValue = ValueHelper.Instance.SetBit(ValueHelper.Instance.GetBytes(TodValue), 4, value / 2 >= 1); TodValue = BigEndianValueHelper.Instance.SetBit(BigEndianValueHelper.Instance.GetBytes(TodValue), 4, value / 2 >= 1);
} }
} }
public bool UZS public bool UZS
@@ -60,9 +60,9 @@
get get
{ {
var pos = 2; var pos = 2;
return ValueHelper.Instance.GetBit(ValueHelper.Instance.GetBytes(TodValue), ref pos); return BigEndianValueHelper.Instance.GetBit(BigEndianValueHelper.Instance.GetBytes(TodValue), ref pos);
} }
set { TodValue = ValueHelper.Instance.SetBit(ValueHelper.Instance.GetBytes(TodValue), 2, value); } set { TodValue = BigEndianValueHelper.Instance.SetBit(BigEndianValueHelper.Instance.GetBytes(TodValue), 2, value); }
} }
public bool ESY public bool ESY
@@ -70,9 +70,9 @@
get get
{ {
var pos = 1; var pos = 1;
return ValueHelper.Instance.GetBit(ValueHelper.Instance.GetBytes(TodValue), ref pos); return BigEndianValueHelper.Instance.GetBit(BigEndianValueHelper.Instance.GetBytes(TodValue), ref pos);
} }
set { TodValue = ValueHelper.Instance.SetBit(ValueHelper.Instance.GetBytes(TodValue), 1, value); } set { TodValue = BigEndianValueHelper.Instance.SetBit(BigEndianValueHelper.Instance.GetBytes(TodValue), 1, value); }
} }
public bool SYA public bool SYA
@@ -80,9 +80,9 @@
get get
{ {
var pos = 0; var pos = 0;
return ValueHelper.Instance.GetBit(ValueHelper.Instance.GetBytes(TodValue), ref pos); return BigEndianValueHelper.Instance.GetBit(BigEndianValueHelper.Instance.GetBytes(TodValue), ref pos);
} }
set { TodValue = ValueHelper.Instance.SetBit(ValueHelper.Instance.GetBytes(TodValue), 0, value); } set { TodValue = BigEndianValueHelper.Instance.SetBit(BigEndianValueHelper.Instance.GetBytes(TodValue), 0, value); }
} }
public ushort TodValue { get; set; } public ushort TodValue { get; set; }

View File

@@ -1,6 +1,7 @@
using System; using System;
using System.Collections; using System.Collections;
using System.Collections.Generic; using System.Collections.Generic;
using System.ComponentModel;
using System.Linq; using System.Linq;
namespace ModBus.Net namespace ModBus.Net
@@ -25,8 +26,6 @@ namespace ModBus.Net
{"System.Double", 8} {"System.Double", 8}
}; };
protected static bool _littleEndian = false;
protected ValueHelper() protected ValueHelper()
{ {
} }
@@ -36,12 +35,7 @@ namespace ModBus.Net
/// </summary> /// </summary>
public static bool LittleEndian public static bool LittleEndian
{ {
get { return _littleEndian; } get { return true; }
set
{
_littleEndian = value;
_Instance = LittleEndian ? new ValueHelper() : new BigEndianValueHelper();
}
} }
#region Factory #region Factory
@@ -57,7 +51,7 @@ namespace ModBus.Net
{ {
if (_Instance == null) if (_Instance == null)
{ {
_Instance = LittleEndian ? new ValueHelper() : new BigEndianValueHelper(); _Instance = new ValueHelper();
} }
return _Instance; return _Instance;
} }
@@ -164,6 +158,16 @@ namespace ModBus.Net
/// <returns></returns> /// <returns></returns>
public virtual object GetValue(byte[] data, ref int pos, Type t) public virtual object GetValue(byte[] data, ref int pos, Type t)
{ {
ValueHelper Instance;
if (this is BigEndianValueHelper)
{
Instance = BigEndianValueHelper.Instance;
}
else
{
Instance = ValueHelper.Instance;
}
switch (t.FullName) switch (t.FullName)
{ {
case "System.Int16": case "System.Int16":
@@ -359,8 +363,18 @@ namespace ModBus.Net
/// </summary> /// </summary>
/// <param name="contents"></param> /// <param name="contents"></param>
/// <returns></returns> /// <returns></returns>
public byte[] ObjectArrayToByteArray(object[] contents) public virtual byte[] ObjectArrayToByteArray(object[] contents)
{ {
ValueHelper Instance;
if (this is BigEndianValueHelper)
{
Instance = BigEndianValueHelper.Instance;
}
else
{
Instance = ValueHelper.Instance;
}
bool b = false; bool b = false;
//先查找传入的结构中有没有数组,有的话将其打开 //先查找传入的结构中有没有数组,有的话将其打开
var newContentsList = new List<object>(); var newContentsList = new List<object>();
@@ -400,7 +414,7 @@ namespace ModBus.Net
boolToByteTemp = 0; boolToByteTemp = 0;
} }
lastIsBool = true; lastIsBool = true;
if (_littleEndian) if (LittleEndian)
{ {
boolToByteTemp = (byte)(boolToByteTemp * 2 + ((bool)content ? 1 : 0)); boolToByteTemp = (byte)(boolToByteTemp * 2 + ((bool)content ? 1 : 0));
} }
@@ -488,7 +502,7 @@ namespace ModBus.Net
/// <param name="contents">byte数组</param> /// <param name="contents">byte数组</param>
/// <param name="translateTypeAndCount">单一的类型和需要转换的个数的键值对</param> /// <param name="translateTypeAndCount">单一的类型和需要转换的个数的键值对</param>
/// <returns>object数组</returns> /// <returns>object数组</returns>
public object[] ByteArrayToObjectArray(byte[] contents, KeyValuePair<Type, int> translateTypeAndCount) public virtual object[] ByteArrayToObjectArray(byte[] contents, KeyValuePair<Type, int> translateTypeAndCount)
{ {
return ByteArrayToObjectArray(contents, new List<KeyValuePair<Type, int>>() {translateTypeAndCount}); return ByteArrayToObjectArray(contents, new List<KeyValuePair<Type, int>>() {translateTypeAndCount});
} }
@@ -499,9 +513,19 @@ namespace ModBus.Net
/// <param name="contents">byte数组</param> /// <param name="contents">byte数组</param>
/// <param name="translateTypeAndCount">一连串类型和需要转换的个数的键值对该方法会依次转换每一个需要转的目标数据类型。比如typeof(int),5; typeof(short),3 会转换出8个元素当然前提是byte数组足够长的时候5个int和3个short然后全部变为object类型返回。</param> /// <param name="translateTypeAndCount">一连串类型和需要转换的个数的键值对该方法会依次转换每一个需要转的目标数据类型。比如typeof(int),5; typeof(short),3 会转换出8个元素当然前提是byte数组足够长的时候5个int和3个short然后全部变为object类型返回。</param>
/// <returns>object数组</returns> /// <returns>object数组</returns>
public object[] ByteArrayToObjectArray(byte[] contents, public virtual object[] ByteArrayToObjectArray(byte[] contents,
IEnumerable<KeyValuePair<Type, int>> translateTypeAndCount) IEnumerable<KeyValuePair<Type, int>> translateTypeAndCount)
{ {
ValueHelper Instance;
if (this is BigEndianValueHelper)
{
Instance = BigEndianValueHelper.Instance;
}
else
{
Instance = ValueHelper.Instance;
}
List<object> translation = new List<object>(); List<object> translation = new List<object>();
int count = 0; int count = 0;
foreach (var translateUnit in translateTypeAndCount) foreach (var translateUnit in translateTypeAndCount)
@@ -672,8 +696,32 @@ namespace ModBus.Net
} }
} }
internal class BigEndianValueHelper : ValueHelper public class BigEndianValueHelper : ValueHelper
{ {
protected static BigEndianValueHelper _BigEndianInstance;
protected BigEndianValueHelper()
{
}
protected new bool LittleEndian
{
get { return false; }
}
public new static BigEndianValueHelper Instance
{
get
{
if (_BigEndianInstance == null)
{
_BigEndianInstance = new BigEndianValueHelper();
}
return _BigEndianInstance;
}
}
public override Byte[] GetBytes(short value) public override Byte[] GetBytes(short value)
{ {
return Reverse(BitConverter.GetBytes(value)); return Reverse(BitConverter.GetBytes(value));

View File

@@ -64,8 +64,8 @@ namespace NA200H.UI.ConsoleApp
ReadDataModbusOutputStruct readCoilStatusOutputStruct = (ReadDataModbusOutputStruct)wrapper.SendReceive(wrapper[typeof(ReadDataModbusProtocal)], readCoilStatusInputStruct); ReadDataModbusOutputStruct readCoilStatusOutputStruct = (ReadDataModbusOutputStruct)wrapper.SendReceive(wrapper[typeof(ReadDataModbusProtocal)], readCoilStatusInputStruct);
//第三步:读取这个输出结构体的信息。 //第三步:读取这个输出结构体的信息。
bool[] array = bool[] array =
ValueHelper.Instance.ObjectArrayToDestinationArray<bool>( BigEndianValueHelper.Instance.ObjectArrayToDestinationArray<bool>(
ValueHelper.Instance.ByteArrayToObjectArray(readCoilStatusOutputStruct.DataValue, BigEndianValueHelper.Instance.ByteArrayToObjectArray(readCoilStatusOutputStruct.DataValue,
new KeyValuePair<Type, int>(typeof (bool), 0x0a))); new KeyValuePair<Type, int>(typeof (bool), 0x0a)));
for (int i = 0; i < array.Length; i++) for (int i = 0; i < array.Length; i++)
{ {
@@ -78,8 +78,8 @@ namespace NA200H.UI.ConsoleApp
ReadDataModbusInputStruct readHoldRegisterInputStruct = new ReadDataModbusInputStruct(0x02, "NW 1", 4, addressTranslator); ReadDataModbusInputStruct readHoldRegisterInputStruct = new ReadDataModbusInputStruct(0x02, "NW 1", 4, addressTranslator);
ReadDataModbusOutputStruct readHoldRegisterOutputStruct = (ReadDataModbusOutputStruct)wrapper.SendReceive(wrapper[typeof(ReadDataModbusProtocal)], readHoldRegisterInputStruct); ReadDataModbusOutputStruct readHoldRegisterOutputStruct = (ReadDataModbusOutputStruct)wrapper.SendReceive(wrapper[typeof(ReadDataModbusProtocal)], readHoldRegisterInputStruct);
ushort[] array2 = ushort[] array2 =
ValueHelper.Instance.ObjectArrayToDestinationArray<ushort>( BigEndianValueHelper.Instance.ObjectArrayToDestinationArray<ushort>(
ValueHelper.Instance.ByteArrayToObjectArray(readHoldRegisterOutputStruct.DataValue, BigEndianValueHelper.Instance.ByteArrayToObjectArray(readHoldRegisterOutputStruct.DataValue,
new KeyValuePair<Type, int>(typeof (ushort), 8))); new KeyValuePair<Type, int>(typeof (ushort), 8)));
for (int i = 0; i < array2.Length; i++) for (int i = 0; i < array2.Length; i++)
{ {
@@ -128,8 +128,8 @@ namespace NA200H.UI.ConsoleApp
(ReadRequestSiemensOutputStruct) (ReadRequestSiemensOutputStruct)
wrapper.SendReceive(wrapper[typeof(ReadRequestSiemensProtocal)], readRequestSiemensInputStruct); wrapper.SendReceive(wrapper[typeof(ReadRequestSiemensProtocal)], readRequestSiemensInputStruct);
ushort[] array = ushort[] array =
ValueHelper.Instance.ObjectArrayToDestinationArray<ushort>( BigEndianValueHelper.Instance.ObjectArrayToDestinationArray<ushort>(
ValueHelper.Instance.ByteArrayToObjectArray(readRequestSiemensOutputStruct.GetValue, BigEndianValueHelper.Instance.ByteArrayToObjectArray(readRequestSiemensOutputStruct.GetValue,
new KeyValuePair<Type, int>(typeof (ushort), 2))); new KeyValuePair<Type, int>(typeof (ushort), 2)));
for (int i = 0; i < array.Length; i++) for (int i = 0; i < array.Length; i++)
{ {

View File

@@ -27,7 +27,7 @@ namespace NA200H.UI.WPF
utility = new SiemensUtility(SiemensType.Tcp, "192.168.3.191", SiemensMachineModel.S7_200); utility = new SiemensUtility(SiemensType.Tcp, "192.168.3.191", SiemensMachineModel.S7_200);
utility.AddressTranslator = new AddressTranslatorSiemens(); utility.AddressTranslator = new AddressTranslatorSiemens();
object[] getNum = utility.GetDatas(0x02, 0x00, "V 1", new KeyValuePair<Type, int>(typeof(ushort), 4)); object[] getNum = utility.GetDatas(0x02, 0x00, "V 1", new KeyValuePair<Type, int>(typeof(ushort), 4));
ushort[] getNumUshorts = ValueHelper.Instance.ObjectArrayToDestinationArray<ushort>(getNum); ushort[] getNumUshorts = BigEndianValueHelper.Instance.ObjectArrayToDestinationArray<ushort>(getNum);
SetValue(getNumUshorts); SetValue(getNumUshorts);
} }
@@ -50,7 +50,7 @@ namespace NA200H.UI.WPF
Thread.Sleep(100); Thread.Sleep(100);
//object[] getNum = utility.GetDatas(0x02, 0x00, "NW 1", new KeyValuePair<Type, int>(typeof(ushort), 4)); //object[] getNum = utility.GetDatas(0x02, 0x00, "NW 1", new KeyValuePair<Type, int>(typeof(ushort), 4));
object[] getNum = utility.GetDatas(0x02, 0x00, "V 1", new KeyValuePair<Type, int>(typeof(ushort), 4)); object[] getNum = utility.GetDatas(0x02, 0x00, "V 1", new KeyValuePair<Type, int>(typeof(ushort), 4));
ushort[] getNumUshorts = ValueHelper.Instance.ObjectArrayToDestinationArray<ushort>(getNum); ushort[] getNumUshorts = BigEndianValueHelper.Instance.ObjectArrayToDestinationArray<ushort>(getNum);
SetValue(getNumUshorts); SetValue(getNumUshorts);
} }
} }