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();
object[] lampsbyte = _utility.GetDatas(2, 0, "Q 0", new KeyValuePair<Type, int>(typeof(bool), 7));
bool[] lamps =
ValueHelper.Instance.ObjectArrayToDestinationArray<bool>(
BigEndianValueHelper.Instance.ObjectArrayToDestinationArray<bool>(
lampsbyte);
if (lamps[0])
{

View File

@@ -30,19 +30,19 @@ namespace ModBus.Net
if (initNum < 0)
{
initNum = address.Address;
getCount = (int)ValueHelper.Instance.ByteLength[address.DataType.FullName];
getCount = (int)BigEndianValueHelper.Instance.ByteLength[address.DataType.FullName];
}
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)});
initNum = address.Address;
getCount = (int)ValueHelper.Instance.ByteLength[address.DataType.FullName];
getCount = (int)BigEndianValueHelper.Instance.ByteLength[address.DataType.FullName];
}
else
{
getCount += (int)ValueHelper.Instance.ByteLength[address.DataType.FullName];
getCount += (int)BigEndianValueHelper.Instance.ByteLength[address.DataType.FullName];
}
}
preNum = address.Address;

View File

@@ -61,38 +61,61 @@ namespace ModBus.Net
public async Task<Dictionary<string,ReturnUnit>> GetDatasAsync()
{
Dictionary<string, ReturnUnit> ans = new Dictionary<string, ReturnUnit>();
if (!BaseUtility.IsConnected)
try
{
await BaseUtility.ConnectAsync();
}
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)
Dictionary<string, ReturnUnit> ans = new Dictionary<string, ReturnUnit>();
if (!BaseUtility.IsConnected)
{
var address =
GetAddresses.SingleOrDefault(
p => p.Area == communicateAddress.Area && p.Address == pos + communicateAddress.Address);
if (address != null)
await BaseUtility.ConnectAsync();
}
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*
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});
}
else
{
pos++;
var address =
GetAddresses.SingleOrDefault(
p => p.Area == communicateAddress.Area && p.Address == pos + communicateAddress.Address);
if (address != null)
{
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()

View File

@@ -67,10 +67,10 @@ namespace ModBus.Net
try
{
string typeName = getTypeAndCount.Key.FullName;
double bCount = ValueHelper.Instance.ByteLength[typeName];
double bCount = BigEndianValueHelper.Instance.ByteLength[typeName];
byte[] getBytes = GetDatas(belongAddress, masterAddress, startAddress,
(int) Math.Ceiling(bCount*getTypeAndCount.Value));
return ValueHelper.Instance.ByteArrayToObjectArray(getBytes, getTypeAndCount);
return BigEndianValueHelper.Instance.ByteArrayToObjectArray(getBytes, getTypeAndCount);
}
catch (Exception)
{
@@ -84,10 +84,10 @@ namespace ModBus.Net
try
{
string typeName = getTypeAndCount.Key.FullName;
double bCount = ValueHelper.Instance.ByteLength[typeName];
double bCount = BigEndianValueHelper.Instance.ByteLength[typeName];
byte[] getBytes = await GetDatasAsync(belongAddress, masterAddress, startAddress,
(int) Math.Ceiling(bCount*getTypeAndCount.Value));
return ValueHelper.Instance.ByteArrayToObjectArray(getBytes, getTypeAndCount);
return BigEndianValueHelper.Instance.ByteArrayToObjectArray(getBytes, getTypeAndCount);
}
catch (Exception)
{
@@ -102,7 +102,7 @@ namespace ModBus.Net
{
var getBytes = GetDatas(belongAddress, masterAddress, startAddress,
new KeyValuePair<Type, int>(typeof (T), getByteCount));
return ValueHelper.Instance.ObjectArrayToDestinationArray<T>(getBytes);
return BigEndianValueHelper.Instance.ObjectArrayToDestinationArray<T>(getBytes);
}
catch (Exception)
{
@@ -117,7 +117,7 @@ namespace ModBus.Net
{
var getBytes = await GetDatasAsync(belongAddress, masterAddress, startAddress,
new KeyValuePair<Type, int>(typeof(T), getByteCount));
return ValueHelper.Instance.ObjectArrayToDestinationArray<T>(getBytes);
return BigEndianValueHelper.Instance.ObjectArrayToDestinationArray<T>(getBytes);
}
catch (Exception)
{
@@ -134,11 +134,11 @@ namespace ModBus.Net
foreach (var getTypeAndCount in getTypeAndCountList)
{
string typeName = getTypeAndCount.Key.FullName;
double bCount = ValueHelper.Instance.ByteLength[typeName];
double bCount = BigEndianValueHelper.Instance.ByteLength[typeName];
bAllCount += (int)Math.Ceiling(bCount * getTypeAndCount.Value);
}
byte[] getBytes = GetDatas(belongAddress, masterAddress, startAddress, bAllCount);
return ValueHelper.Instance.ByteArrayToObjectArray(getBytes, getTypeAndCountList);
return BigEndianValueHelper.Instance.ByteArrayToObjectArray(getBytes, getTypeAndCountList);
}
catch (Exception)
{
@@ -155,11 +155,11 @@ namespace ModBus.Net
foreach (var getTypeAndCount in getTypeAndCountList)
{
string typeName = getTypeAndCount.Key.FullName;
double bCount = ValueHelper.Instance.ByteLength[typeName];
double bCount = BigEndianValueHelper.Instance.ByteLength[typeName];
bAllCount += (int)Math.Ceiling(bCount * getTypeAndCount.Value);
}
byte[] getBytes = await GetDatasAsync(belongAddress, masterAddress, startAddress, bAllCount);
return ValueHelper.Instance.ByteArrayToObjectArray(getBytes, getTypeAndCountList);
return BigEndianValueHelper.Instance.ByteArrayToObjectArray(getBytes, getTypeAndCountList);
}
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, Type>> _machineDataType;
private static Dictionary<string, string> _boxUidBoxNo;
private static HashSet<string> _connectedDataGroupUid;
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;
public override bool IsConnected { get { return _connected; } }
@@ -96,6 +97,7 @@ namespace ModBus.Net.FBox
_groupNameBoxUid = new Dictionary<string, string>();
_boxUidDataGroups = new Dictionary<string, List<DMonGroup>>();
_boxUidBoxNo = new Dictionary<string, string>();
_connectedDataGroupUid = new HashSet<string>();
_timer = new Timer(ChangeToken, null, 3600 * 1000 * 4, 3600 * 1000 * 4);
}
Msg = msg;
@@ -105,24 +107,32 @@ namespace ModBus.Net.FBox
{
try
{
var tokenResponse = await _oauth2[Msg].RequestRefreshTokenAsync(_refreshToken[Msg]);
_refreshToken[Msg] = tokenResponse.RefreshToken;
_httpClient[Msg].SetBearerToken(tokenResponse.AccessToken);
foreach (var boxUidMsg in _boxUidMsg)
using (await _lock.LockAsync())
{
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))
_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)
if (boxUidMsg.Value.Equals(Msg))
{
await
_httpClient2[boxUidMsg.Key].PostAsync(
"dmon/group/" + localDataGroup.Uid + "/start", null);
if (_httpClient2.ContainsKey(boxUidMsg.Key) && _hubConnections.ContainsKey(boxUidMsg.Key))
_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)
{
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(
"dmon/group/" + _groupNameUid[ConnectionToken] + "/start",
null);
_connectedDataGroupUid.Add(_groupNameUid[ConnectionToken]);
_connected = true;
Console.WriteLine("SignalR Connected success");
return true;
@@ -199,6 +210,7 @@ namespace ModBus.Net.FBox
private async Task CallService(SignalRSigninMsg msg, string token)
{
var guid = Guid.NewGuid().ToString();
var baseAddress = Constants.AspNetWebApiSampleApi;
@@ -213,11 +225,11 @@ namespace ModBus.Net.FBox
_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");
@@ -252,7 +264,10 @@ namespace ModBus.Net.FBox
List<DMonGroup> dataGroups = JsonConvert.DeserializeObject<List<DMonGroup>>(response);
_boxUidDataGroups.Add(boxUid, dataGroups);
_boxUidSessionId.Add(boxUid, sessionId);
lock (_boxUidSessionId)
{
_boxUidSessionId.Add(boxUid, sessionId);
}
_boxUidBoxNo.Add(boxUid, boxNo);
_boxUidMsg.Add(boxUid, Msg);
@@ -271,7 +286,8 @@ namespace ModBus.Net.FBox
if (_boxUidSessionId.ContainsValue(boxSessionId))
{
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];
foreach (var value in values)
@@ -287,10 +303,12 @@ namespace ModBus.Net.FBox
var dMonEntry =
dataGroupInner.DMonEntries.FirstOrDefault(
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]
.ContainsKey(dMonEntry.Desc))
.ContainsKey(dMonEntry.Desc))
{
_machineData[localBoxNo + "," + dataGroupInner.Name]
.Remove(dMonEntry.Desc);
@@ -309,12 +327,15 @@ namespace ModBus.Net.FBox
{
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,
new Dictionary<string, double>());
}
if (_machineData[localBoxNo + "," + dataGroupInner.Name] == null)
if (_machineData[localBoxNo + "," + dataGroupInner.Name] ==
null)
{
_machineData[localBoxNo + "," + dataGroupInner.Name] =
new Dictionary<string, double>();
@@ -327,16 +348,19 @@ namespace ModBus.Net.FBox
if (value.Value.HasValue && dMonEntry != null)
{
if (
_machineData[localBoxNo + "," + dataGroupInner.Name].ContainsKey(
dMonEntry.Desc))
_machineData[localBoxNo + "," + dataGroupInner.Name]
.ContainsKey(
dMonEntry.Desc))
{
_machineData[localBoxNo + "," + dataGroupInner.Name][dMonEntry.Desc] =
_machineData[localBoxNo + "," + dataGroupInner.Name]
[dMonEntry.Desc] =
value.Value.Value;
}
else
{
_machineData[localBoxNo + "," + dataGroupInner.Name].Add(dMonEntry.Desc,
value.Value.Value);
_machineData[localBoxNo + "," + dataGroupInner.Name]
.Add(dMonEntry.Desc,
value.Value.Value);
}
}
break;
@@ -370,13 +394,17 @@ namespace ModBus.Net.FBox
{
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
{
_connectionTokenState[localBoxNo + "," + localDataGroup.Name] = newStatus;
_connectionTokenState[localBoxNo + "," + localDataGroup.Name] =
newStatus;
}
}
}
@@ -390,13 +418,16 @@ namespace ModBus.Net.FBox
await _hubConnections[getBoxUid].Start();
}
if (newStatus == 1 && IsConnected)
if (newStatus == 1)
{
foreach (var localDataGroup in localDataGroups)
{
await
_httpClient2[getBoxUid].PostAsync(
"dmon/group/" + localDataGroup.Uid + "/start", null);
if (_connectedDataGroupUid.Contains(localDataGroup.Uid))
{
await
_httpClient2[getBoxUid].PostAsync(
"dmon/group/" + localDataGroup.Uid + "/start", null);
}
}
}
}
@@ -423,15 +454,18 @@ namespace ModBus.Net.FBox
var groupUid = dataGroup.Uid;
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);
}
if (groupName != "(Default)" && groupName != "默认组" && !_groupNameUid.ContainsKey(boxNo + "," + groupName))
if (groupName != "(Default)" && groupName != "默认组" &&
!_groupNameUid.ContainsKey(boxNo + "," + groupName))
{
_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);
}
@@ -542,61 +576,70 @@ namespace ModBus.Net.FBox
await hubConnection.Start();
await dataHubProxy.Invoke("updateClientId", guid);
}
}
}
private async Task ConnectRecovery(HubConnection hubConnection)
{
string getBoxUid;
lock (_boxUidSessionId)
using (await _lock.LockAsync())
{
getBoxUid =
_boxUidSessionId.FirstOrDefault(
p => p.Value == int.Parse(hubConnection.Headers["X-FBox-Session"])).Key;
}
try
{
if (hubConnection.State != ConnectionState.Connected)
string getBoxUid;
lock (_boxUidSessionId)
{
try
getBoxUid =
_boxUidSessionId.FirstOrDefault(
p => p.Value == int.Parse(hubConnection.Headers["X-FBox-Session"])).Key;
}
try
{
if (hubConnection.State != ConnectionState.Connected)
{
hubConnection.Stop();
}
catch
{
// ignored
}
try
{
hubConnection.Stop();
}
catch
{
// ignored
}
await hubConnection.Start();
if (IsConnected)
{
await hubConnection.Start();
var localDataGroups = _boxUidDataGroups[getBoxUid];
foreach (var localDataGroup in localDataGroups)
{
await
_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))
if (_connectedDataGroupUid.Contains(localDataGroup.Uid))
{
_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(
"dmon/group/" + _groupNameUid[ConnectionToken] + "/stop",
null);
_connectedDataGroupUid.RemoveWhere(p => p == _groupNameUid[ConnectionToken]);
_connected = false;
Console.WriteLine("SignalR Disconnect success");
return true;
@@ -687,9 +731,9 @@ namespace ModBus.Net.FBox
return null;
}
int pos = 0;
int area = ValueHelper.Instance.GetInt(message, ref pos);
int address = ValueHelper.Instance.GetInt(message, ref pos);
//short count = ValueHelper.Instance.GetShort(message, ref pos);
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
{
@@ -707,7 +751,7 @@ namespace ModBus.Net.FBox
}
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)
{
byte belongAddress = ValueHelper.Instance.GetByte(messageBytes, ref pos);
byte functionCode = ValueHelper.Instance.GetByte(messageBytes, ref pos);
byte dataCount = ValueHelper.Instance.GetByte(messageBytes, ref pos);
byte belongAddress = BigEndianValueHelper.Instance.GetByte(messageBytes, ref pos);
byte functionCode = BigEndianValueHelper.Instance.GetByte(messageBytes, ref pos);
byte dataCount = BigEndianValueHelper.Instance.GetByte(messageBytes, ref pos);
byte[] dataValue = new byte[dataCount];
Array.Copy(messageBytes, 3, dataValue, 0, dataCount);
return new ReadDataModbusOutputStruct(belongAddress, functionCode, dataCount, dataValue);
@@ -178,10 +178,10 @@ namespace ModBus.Net.Modbus
public override OutputStruct Unformat(byte[] messageBytes, ref int flag)
{
byte belongAddress = ValueHelper.Instance.GetByte(messageBytes, ref flag);
byte functionCode = ValueHelper.Instance.GetByte(messageBytes, ref flag);
ushort startAddress = ValueHelper.Instance.GetUShort(messageBytes, ref flag);
ushort writeCount = ValueHelper.Instance.GetUShort(messageBytes, ref flag);
byte belongAddress = BigEndianValueHelper.Instance.GetByte(messageBytes, ref flag);
byte functionCode = BigEndianValueHelper.Instance.GetByte(messageBytes, ref flag);
ushort startAddress = BigEndianValueHelper.Instance.GetUShort(messageBytes, ref flag);
ushort writeCount = BigEndianValueHelper.Instance.GetUShort(messageBytes, ref flag);
return new WriteDataModbusOutputStruct(belongAddress, functionCode, startAddress,
writeCount);
}
@@ -244,16 +244,16 @@ namespace ModBus.Net.Modbus
public override OutputStruct Unformat(byte[] messageBytes, ref int flag)
{
byte belongAddress = ValueHelper.Instance.GetByte(messageBytes, ref flag);
byte functionCode = ValueHelper.Instance.GetByte(messageBytes, ref flag);
byte writeByteCount = ValueHelper.Instance.GetByte(messageBytes, ref flag);
ushort year = ValueHelper.Instance.GetUShort(messageBytes, ref flag);
byte day = ValueHelper.Instance.GetByte(messageBytes, ref flag);
byte month = ValueHelper.Instance.GetByte(messageBytes, ref flag);
ushort hour = ValueHelper.Instance.GetUShort(messageBytes, ref flag);
byte second = ValueHelper.Instance.GetByte(messageBytes, ref flag);
byte minute = ValueHelper.Instance.GetByte(messageBytes, ref flag);
ushort millisecond = ValueHelper.Instance.GetUShort(messageBytes, ref flag);
byte belongAddress = BigEndianValueHelper.Instance.GetByte(messageBytes, ref flag);
byte functionCode = BigEndianValueHelper.Instance.GetByte(messageBytes, ref flag);
byte writeByteCount = BigEndianValueHelper.Instance.GetByte(messageBytes, ref flag);
ushort year = BigEndianValueHelper.Instance.GetUShort(messageBytes, ref flag);
byte day = BigEndianValueHelper.Instance.GetByte(messageBytes, ref flag);
byte month = BigEndianValueHelper.Instance.GetByte(messageBytes, ref flag);
ushort hour = BigEndianValueHelper.Instance.GetUShort(messageBytes, ref flag);
byte second = BigEndianValueHelper.Instance.GetByte(messageBytes, ref flag);
byte minute = BigEndianValueHelper.Instance.GetByte(messageBytes, ref flag);
ushort millisecond = BigEndianValueHelper.Instance.GetUShort(messageBytes, ref flag);
return new GetSystemTimeModbusOutputStruct(belongAddress, functionCode, writeByteCount, year, day,
month, hour, second, minute, millisecond);
}
@@ -341,10 +341,10 @@ namespace ModBus.Net.Modbus
public override OutputStruct Unformat(byte[] messageBytes, ref int flag)
{
byte belongAddress = ValueHelper.Instance.GetByte(messageBytes, ref flag);
byte functionCode = ValueHelper.Instance.GetByte(messageBytes, ref flag);
ushort startAddress = ValueHelper.Instance.GetUShort(messageBytes, ref flag);
ushort writeCount = ValueHelper.Instance.GetUShort(messageBytes, ref flag);
byte belongAddress = BigEndianValueHelper.Instance.GetByte(messageBytes, ref flag);
byte functionCode = BigEndianValueHelper.Instance.GetByte(messageBytes, ref flag);
ushort startAddress = BigEndianValueHelper.Instance.GetUShort(messageBytes, ref flag);
ushort writeCount = BigEndianValueHelper.Instance.GetUShort(messageBytes, ref flag);
return new SetSystemTimeModbusOutputStruct(belongAddress, functionCode, startAddress, writeCount);
}
}

View File

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

View File

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

View File

@@ -7,7 +7,7 @@ namespace ModBus.Net.Siemens
public override byte[] BytesExtend(byte[] content)
{
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;
}

View File

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

View File

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

View File

@@ -64,8 +64,8 @@ namespace NA200H.UI.ConsoleApp
ReadDataModbusOutputStruct readCoilStatusOutputStruct = (ReadDataModbusOutputStruct)wrapper.SendReceive(wrapper[typeof(ReadDataModbusProtocal)], readCoilStatusInputStruct);
//第三步:读取这个输出结构体的信息。
bool[] array =
ValueHelper.Instance.ObjectArrayToDestinationArray<bool>(
ValueHelper.Instance.ByteArrayToObjectArray(readCoilStatusOutputStruct.DataValue,
BigEndianValueHelper.Instance.ObjectArrayToDestinationArray<bool>(
BigEndianValueHelper.Instance.ByteArrayToObjectArray(readCoilStatusOutputStruct.DataValue,
new KeyValuePair<Type, int>(typeof (bool), 0x0a)));
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);
ReadDataModbusOutputStruct readHoldRegisterOutputStruct = (ReadDataModbusOutputStruct)wrapper.SendReceive(wrapper[typeof(ReadDataModbusProtocal)], readHoldRegisterInputStruct);
ushort[] array2 =
ValueHelper.Instance.ObjectArrayToDestinationArray<ushort>(
ValueHelper.Instance.ByteArrayToObjectArray(readHoldRegisterOutputStruct.DataValue,
BigEndianValueHelper.Instance.ObjectArrayToDestinationArray<ushort>(
BigEndianValueHelper.Instance.ByteArrayToObjectArray(readHoldRegisterOutputStruct.DataValue,
new KeyValuePair<Type, int>(typeof (ushort), 8)));
for (int i = 0; i < array2.Length; i++)
{
@@ -128,8 +128,8 @@ namespace NA200H.UI.ConsoleApp
(ReadRequestSiemensOutputStruct)
wrapper.SendReceive(wrapper[typeof(ReadRequestSiemensProtocal)], readRequestSiemensInputStruct);
ushort[] array =
ValueHelper.Instance.ObjectArrayToDestinationArray<ushort>(
ValueHelper.Instance.ByteArrayToObjectArray(readRequestSiemensOutputStruct.GetValue,
BigEndianValueHelper.Instance.ObjectArrayToDestinationArray<ushort>(
BigEndianValueHelper.Instance.ByteArrayToObjectArray(readRequestSiemensOutputStruct.GetValue,
new KeyValuePair<Type, int>(typeof (ushort), 2)));
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.AddressTranslator = new AddressTranslatorSiemens();
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);
}
@@ -50,7 +50,7 @@ namespace NA200H.UI.WPF
Thread.Sleep(100);
//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));
ushort[] getNumUshorts = ValueHelper.Instance.ObjectArrayToDestinationArray<ushort>(getNum);
ushort[] getNumUshorts = BigEndianValueHelper.Instance.ObjectArrayToDestinationArray<ushort>(getNum);
SetValue(getNumUshorts);
}
}