2015-10-23 update 1 fix a bug and add FBox Connection

This commit is contained in:
parallelbgls@outlook.com
2015-10-23 16:19:26 +08:00
parent ca479803a2
commit 118a5919ae
17 changed files with 1078 additions and 8 deletions

View File

@@ -1,4 +1,4 @@
<?xml version="1.0" encoding="utf-8"?> <?xml version="1.0" encoding="utf-8"?>
<!-- <!--
For more information on how to configure your ASP.NET application, please visit For more information on how to configure your ASP.NET application, please visit
http://go.microsoft.com/fwlink/?LinkId=301879 http://go.microsoft.com/fwlink/?LinkId=301879
@@ -9,8 +9,7 @@
<section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" /> <section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
</configSections> </configSections>
<connectionStrings> <connectionStrings>
<add name="DefaultConnection" connectionString="Data Source=(LocalDb)\v11.0;AttachDbFilename=|DataDirectory|\aspnet-CrossLampControl.WebApi-20140912112502.mdf;Initial Catalog=aspnet-CrossLampControl.WebApi-20140912112502;Integrated Security=True" <add name="DefaultConnection" connectionString="Data Source=(LocalDb)\v11.0;AttachDbFilename=|DataDirectory|\aspnet-CrossLampControl.WebApi-20140912112502.mdf;Initial Catalog=aspnet-CrossLampControl.WebApi-20140912112502;Integrated Security=True" providerName="System.Data.SqlClient" />
providerName="System.Data.SqlClient" />
</connectionStrings> </connectionStrings>
<appSettings></appSettings> <appSettings></appSettings>
<system.web> <system.web>
@@ -33,7 +32,7 @@
<assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1"> <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
<dependentAssembly> <dependentAssembly>
<assemblyIdentity name="Microsoft.Owin" publicKeyToken="31bf3856ad364e35" /> <assemblyIdentity name="Microsoft.Owin" publicKeyToken="31bf3856ad364e35" />
<bindingRedirect oldVersion="1.0.0.0-2.1.0.0" newVersion="2.1.0.0" /> <bindingRedirect oldVersion="0.0.0.0-2.1.0.0" newVersion="2.1.0.0" />
</dependentAssembly> </dependentAssembly>
<dependentAssembly> <dependentAssembly>
<assemblyIdentity name="Newtonsoft.Json" culture="neutral" publicKeyToken="30ad4fe6b2a6aeed" /> <assemblyIdentity name="Newtonsoft.Json" culture="neutral" publicKeyToken="30ad4fe6b2a6aeed" />
@@ -57,7 +56,7 @@
</dependentAssembly> </dependentAssembly>
<dependentAssembly> <dependentAssembly>
<assemblyIdentity name="WebGrease" publicKeyToken="31bf3856ad364e35" /> <assemblyIdentity name="WebGrease" publicKeyToken="31bf3856ad364e35" />
<bindingRedirect oldVersion="1.0.0.0-1.5.2.14234" newVersion="1.5.2.14234" /> <bindingRedirect oldVersion="0.0.0.0-1.5.2.14234" newVersion="1.5.2.14234" />
</dependentAssembly> </dependentAssembly>
</assemblyBinding> </assemblyBinding>
</runtime> </runtime>

View File

@@ -69,7 +69,7 @@ namespace ModBus.Net
if (!BaseUtility.IsConnected) return null; if (!BaseUtility.IsConnected) return null;
foreach (var communicateAddress in CommunicateAddresses) foreach (var communicateAddress in CommunicateAddresses)
{ {
var datas = await BaseUtility.GetDatasAsync<byte>(2, 0, AddressFormater.FormatAddress(communicateAddress.Area,communicateAddress.Address), communicateAddress.GetCount); 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; if (datas == null || datas.Length == 0) return null;
int pos = 0; int pos = 0;
while (pos < communicateAddress.GetCount) while (pos < communicateAddress.GetCount)

View File

@@ -0,0 +1,24 @@
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<CommunicationUnit> Combine(IEnumerable<AddressUnit> addresses)
{
return (from address in addresses
select
new CommunicationUnit()
{
Area = address.Area,
Address = address.Address,
GetCount = 1,
DataType = address.DataType
});
}
}
}

View File

@@ -0,0 +1,16 @@
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;
}
}
}

View File

@@ -0,0 +1,73 @@
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<string, int> AreaCodeDictionary;
public AddressTranslatorFBox()
{
AreaCodeDictionary = new Dictionary<string, int>
{
{"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},
{"DB", 10000},
};
}
public override KeyValuePair<int, int> AddressTranslate(string address, bool isRead)
{
var tmpAddress = address.Replace(" ", "");
tmpAddress = tmpAddress.ToUpper();
if (tmpAddress.Substring(0, 2) == "DB")
{
var addressSplit = tmpAddress.Split('.');
if (addressSplit.Length != 2) throw new FormatException();
addressSplit[0] = addressSplit[0].Substring(2);
if (addressSplit[1].Substring(0, 2) == "DB")
addressSplit[1] = addressSplit[1].Substring(2);
return new KeyValuePair<int, int>(int.Parse(addressSplit[1]),
int.Parse(addressSplit[0]) + AreaCodeDictionary["DB"]);
}
int i = 0;
int t;
while (!int.TryParse(tmpAddress[i].ToString(), out t) && i < tmpAddress.Length)
{
i++;
}
if (i == 0 || i >= tmpAddress.Length) throw new FormatException();
string head = tmpAddress.Substring(0, i);
string tail = tmpAddress.Substring(i);
return
new KeyValuePair<int, int>(int.Parse(tail),
AreaCodeDictionary[head]);
}
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;
}
}
}

View File

@@ -0,0 +1,22 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ModBus.Net.FBox
{
public static class Constants
{
public const string BaseAddress = "https://account.flexem.com/core";
public const string AuthorizeEndpoint = BaseAddress + "/connect/authorize";
public const string LogoutEndpoint = BaseAddress + "/connect/endsession";
public const string TokenEndpoint = BaseAddress + "/connect/token";
public const string UserInfoEndpoint = BaseAddress + "/connect/userinfo";
public const string IdentityTokenValidationEndpoint = BaseAddress + "/connect/identitytokenvalidation";
public const string TokenRevocationEndpoint = BaseAddress + "/connect/revocation";
public const string AspNetWebApiSampleApi = "http://fbox360.com/api/client/";
}
}

View File

@@ -0,0 +1,286 @@
using System;
using System.Collections.Generic;
using Newtonsoft.Json;
namespace DelinRemoteControlBoxTest
{
public class BoxGroup
{
[JsonProperty("boxRegs")]
public List<BoxReg> BoxRegs { get; set; }
[JsonProperty("children")]
public List<BoxGroup> 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<int> 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<DMonEntry> 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<string> SupportedPlcs { get; set; }
[JsonProperty("regs")]
public List<AddressTypeReg> 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; }
}
}

View File

@@ -0,0 +1,15 @@
using System;
using System.Collections.Generic;
namespace ModBus.Net.FBox
{
public class FBoxMachine : BaseMachine
{
public FBoxMachine(FBoxType fBoxType, string connectionString, SignalRSigninMsg msg, IEnumerable<AddressUnit> getAddresses, bool keepConnect) : base(getAddresses, keepConnect)
{
AddressFormater = new AddressFormaterFBox();
AddressCombiner = new AddressCombinerFBox();
BaseUtility = new FBoxUtility(fBoxType, connectionString, CommunicateAddresses, msg);
}
}
}

View File

@@ -0,0 +1,65 @@
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<bool> 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.Key;
Area = address.Value;
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);
}
}
}

View File

@@ -0,0 +1,16 @@
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, SignalRSigninMsg msg)
{
ProtocalLinker = new FBoxSignalRProtocalLinker(machineId, msg);
}
}
}

View File

@@ -0,0 +1,20 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ModBus.Net.FBox
{
public class FBoxSignalRProtocalLinker : SignalRProtocalLinker
{
public FBoxSignalRProtocalLinker(string machineId, SignalRSigninMsg msg) : base(machineId, msg)
{
}
public override bool CheckRight(byte[] content)
{
return true;
}
}
}

View File

@@ -0,0 +1,81 @@
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; }
protected IEnumerable<CommunicationUnit> 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, SigninMsg);
break;
}
}
}
}
public FBoxUtility(FBoxType fBoxType, string connectionString, IEnumerable<CommunicationUnit> communicationUnits, SignalRSigninMsg msg)
{
ConnectionString = connectionString;
CommunicationUnits = communicationUnits.AsEnumerable();
SigninMsg = msg;
ConnectionType = fBoxType;
AddressTranslator = new AddressTranslatorFBox();
}
public override void SetConnectionType(int connectionType)
{
ConnectionType = (FBoxType) connectionType;
}
protected override async Task<byte[]> GetDatasAsync(byte belongAddress, byte masterAddress, string startAddress, int getByteCount)
{
try
{
var readRequestFBoxInputStruct = new ReadRequestFBoxInputStruct(startAddress, (ushort)getByteCount, AddressTranslator);
var readRequestSimenseOutputStruct =
(ReadRequestFBoxOutputStruct)await
Wrapper.SendReceiveAsync(Wrapper[typeof(ReadRequestFBoxProtocal)], readRequestFBoxInputStruct);
return readRequestSimenseOutputStruct.GetValue;
}
catch (Exception)
{
return null;
}
}
public override Task<bool> SetDatasAsync(byte belongAddress, byte masterAddress, string startAddress, object[] setContents)
{
throw new NotImplementedException();
}
}
}

View File

@@ -0,0 +1,405 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Threading.Tasks;
using DelinRemoteControlBoxTest;
using Microsoft.AspNet.SignalR.Client;
using Newtonsoft.Json;
using Thinktecture.IdentityModel.Client;
namespace ModBus.Net.FBox
{
public class 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 class SignalRConnector : BaseConnector
{
private static OAuth2Client _oauth2;
private HttpClient _httpClient;
private readonly Dictionary<string, HttpClient> _httpClient2;
private readonly Dictionary<string, HubConnection> _hubConnections;
private Dictionary<string, string> GroupNameUid { get; }
private static Dictionary<string, Dictionary<string, double>> _machineData;
private static Dictionary<string, Dictionary<string, Type>> _machineDataType;
public override string ConnectionToken { get; }
private bool _connected;
public override bool IsConnected { get { return _connected; } }
public SignalRConnector(string machineId, SignalRSigninMsg msg)
{
ConnectionToken = machineId;
if (_oauth2 == null)
{
_oauth2 = new OAuth2Client(
new Uri(Constants.TokenEndpoint),
msg.ClientId,
msg.ClientSecret
);
_hubConnections = new Dictionary<string, HubConnection>();
_httpClient2 = new Dictionary<string, HttpClient>();
_machineData = new Dictionary<string, Dictionary<string, double>>();
_machineDataType = new Dictionary<string, Dictionary<string, Type>>();
GroupNameUid = new Dictionary<string, string>();
var tokenResponse = _oauth2.RequestResourceOwnerPasswordAsync
(
msg.UserId,
msg.Password,
msg.SigninAdditionalValues
).Result;
if (tokenResponse != null)
AsyncHelper.RunSync(()=>CallService(tokenResponse.AccessToken));
}
}
public override bool Connect()
{
return AsyncHelper.RunSync(ConnectAsync);
}
public override async Task<bool> ConnectAsync()
{
try
{
if (_hubConnections.ContainsKey(ConnectionToken) && _httpClient2.ContainsKey(ConnectionToken) && GroupNameUid.ContainsKey(ConnectionToken))
{
await _httpClient2[ConnectionToken].PostAsync("dmon/group/" + GroupNameUid[ConnectionToken] + "/start",
null);
_connected = true;
return true;
}
else
{
return false;
}
}
catch
{
return false;
}
}
private async Task CallService(string token)
{
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<DeviceSpecSource> deviceSpecs = JsonConvert.DeserializeObject<List<DeviceSpecSource>>(response);
deviceSpecs = deviceSpecs.OrderBy(p => p.Id).ToList();
*/
var response = await _httpClient.GetStringAsync("boxgroup");
List<BoxGroup> boxGroups = JsonConvert.DeserializeObject<List<BoxGroup>>(response);
foreach (var boxGroup in boxGroups)
{
var boxes = boxGroup.BoxRegs;
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 currentStat = box.Box.ConnectionState;
var client3 = new HttpClient
{
BaseAddress = new Uri(baseUrl)
};
client3.SetBearerToken(token);
client3.DefaultRequestHeaders.Add("X-FBox-ClientId", guid);
response = await client3.GetStringAsync("box/" + box.Box.Uid + "/dmon/def/grouped");
List<DMonGroup> dataGroups = JsonConvert.DeserializeObject<List<DMonGroup>>(response);
foreach (var dataGroup in dataGroups)
{
if (dataGroup == null) return;
var groupUid = dataGroup.Uid;
var groupName = dataGroup.Name;
if (groupName != "(Default)" && !GroupNameUid.ContainsKey(groupName))
{
GroupNameUid.Add(groupName, groupUid);
}
var client2 = new HttpClient
{
BaseAddress = new Uri(baseUrl)
};
if (groupName != "(Default)" && !_httpClient2.ContainsKey(groupName))
{
_httpClient2.Add(groupName, client2);
}
client2.SetBearerToken(token);
client2.DefaultRequestHeaders.Add("X-FBox-ClientId", guid);
var hubConnection = new HubConnection(signalrUrl);
if (groupName != "(Default)")
_hubConnections.Add(groupName, hubConnection);
if (!_machineDataType.ContainsKey(groupName))
{
_machineDataType.Add(groupName, new Dictionary<string, Type>());
}
foreach (var dMonEntry in dataGroup.DMonEntries)
{
switch (dMonEntry.DataType)
{
case 1:
{
Type type = typeof(ushort);
if (!_machineDataType[groupName].ContainsKey(dMonEntry.Desc))
{
_machineDataType[groupName].Add(dMonEntry.Desc, type);
}
else
{
_machineDataType[groupName][dMonEntry.Desc] = type;
}
break;
}
case 2:
{
Type type = typeof (short);
if (!_machineDataType[groupName].ContainsKey(dMonEntry.Desc))
{
_machineDataType[groupName].Add(dMonEntry.Desc, type);
}
else
{
_machineDataType[groupName][dMonEntry.Desc] = type;
}
break;
}
case 3:
{
Type type = typeof (uint);
if (!_machineDataType[groupName].ContainsKey(dMonEntry.Desc))
{
_machineDataType[groupName].Add(dMonEntry.Desc, type);
}
else
{
_machineDataType[groupName][dMonEntry.Desc] = type;
}
break;
}
case 4:
{
Type type = typeof (int);
if (!_machineDataType[groupName].ContainsKey(dMonEntry.Desc))
{
_machineDataType[groupName].Add(dMonEntry.Desc, type);
}
else
{
_machineDataType[groupName][dMonEntry.Desc] = type;
}
break;
}
case 7:
{
Type type = typeof (float);
if (!_machineDataType[groupName].ContainsKey(dMonEntry.Desc))
{
_machineDataType[groupName].Add(dMonEntry.Desc, type);
}
else
{
_machineDataType[groupName][dMonEntry.Desc] = type;
}
break;
}
}
}
hubConnection.Headers.Add("Authorization", "Bearer " + token);
hubConnection.Headers.Add("X-FBox-ClientId", guid);
hubConnection.Headers.Add("X-FBox-Session", sessionId.ToString());
IHubProxy stockTickerHubProxy = hubConnection.CreateHubProxy("clientHub");
stockTickerHubProxy.On<int, List<GetValue>>("dMonUpdateValue",
(boxSessionId, values) =>
{
if (boxSessionId == sessionId)
{
foreach (var value in values)
{
lock(_machineData)
{
if (dataGroup.DMonEntries.Any(p => p.Uid == value.Id))
{
if (!_machineData.ContainsKey(groupName))
{
_machineData.Add(groupName, new Dictionary<string, double>());
}
if (_machineData[groupName] == null)
{
_machineData[groupName] = new Dictionary<string, double>();
}
var dMonEntry =
dataGroup.DMonEntries.FirstOrDefault(p => p.Uid == value.Id);
if (value.Value.HasValue && dMonEntry != null)
{
if (_machineData[groupName].ContainsKey(dMonEntry.Desc))
{
_machineData[groupName][dMonEntry.Desc] = value.Value.Value;
}
else
{
_machineData[groupName].Add(dMonEntry.Desc, value.Value.Value);
}
}
}
}
}
}
}
);
stockTickerHubProxy.On<int, string, int, int>("boxConnectionStateChanged",
async (newConnectionToken, getBoxUid, oldStatus, newStatus) =>
{
if (getBoxUid == boxUid)
{
sessionId = newConnectionToken;
client2.DefaultRequestHeaders.Remove("X-FBox-Session");
client2.DefaultRequestHeaders.Add("X-FBox-Session", sessionId.ToString());
if (newStatus == 1 && IsConnected)
{
await client2.PostAsync("dmon/group/" + groupUid + "/start", null);
}
else
{
if (_machineData.ContainsKey(groupName))
{
_machineData.Remove(groupName);
}
await client2.PostAsync("dmon/group/" + groupUid + "/stop", null);
}
}
}
);
hubConnection.Error += ex => Console.WriteLine(@"SignalR error: {0}", ex.Message);
ServicePointManager.DefaultConnectionLimit = 10;
await hubConnection.Start();
await stockTickerHubProxy.Invoke("updateClientId", guid);
client2.DefaultRequestHeaders.Add("X-FBox-Session", sessionId.ToString());
}
}
}
}
public override bool Disconnect()
{
return AsyncHelper.RunSync(DisconnectAsync);
}
public async Task<bool> DisconnectAsync()
{
try
{
if (_hubConnections.ContainsKey(ConnectionToken) && _httpClient2.ContainsKey(ConnectionToken) && GroupNameUid.ContainsKey(ConnectionToken))
{
await _httpClient2[ConnectionToken].PostAsync("dmon/group/" + GroupNameUid[ConnectionToken] + "/stop",
null);
_connected = false;
return true;
}
else
{
return false;
}
}
catch
{
return false;
}
}
public override bool SendMsgWithoutReturn(byte[] message)
{
throw new NotImplementedException();
}
public override Task<bool> SendMsgWithoutReturnAsync(byte[] message)
{
throw new NotImplementedException();
}
public override byte[] SendMsg(byte[] message)
{
var formater = new AddressFormaterFBox();
var translator = new AddressTranslatorFBox();
byte[] ans;
lock (_machineData)
{
if (!_machineData.ContainsKey(ConnectionToken) || !_machineDataType.ContainsKey(ConnectionToken))
{
return null;
}
var machineDataValue = _machineData[ConnectionToken];
var machineDataType = _machineDataType[ConnectionToken];
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);
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)
{
dataAns[0] =
Convert.ChangeType(
0,
machineDataType[formater.FormatAddress(translator.GetAreaName(area), address)]);
}
finally
{
ans = ValueHelper.Instance.ObjectArrayToByteArray(dataAns);
}
}
return ans;
}
public override Task<byte[]> SendMsgAsync(byte[] message)
{
return Task.Factory.StartNew(() => SendMsg(message));
}
}
}

View File

@@ -0,0 +1,16 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ModBus.Net.FBox
{
public class SignalRProtocalLinker : ProtocalLinker
{
protected SignalRProtocalLinker(string machineId, SignalRSigninMsg msg)
{
_baseConnector = new SignalRConnector(machineId, msg);
}
}
}

View File

@@ -38,14 +38,27 @@
</AssemblyOriginatorKeyFile> </AssemblyOriginatorKeyFile>
</PropertyGroup> </PropertyGroup>
<ItemGroup> <ItemGroup>
<Reference Include="Microsoft.AspNet.SignalR.Client, Version=2.2.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35, processorArchitecture=MSIL">
<HintPath>..\packages\Microsoft.AspNet.SignalR.Client.2.2.0\lib\net45\Microsoft.AspNet.SignalR.Client.dll</HintPath>
<Private>True</Private>
</Reference>
<Reference Include="Newtonsoft.Json, Version=6.0.0.0, Culture=neutral, PublicKeyToken=30ad4fe6b2a6aeed, processorArchitecture=MSIL">
<HintPath>..\packages\Newtonsoft.Json.6.0.5\lib\net45\Newtonsoft.Json.dll</HintPath>
<Private>True</Private>
</Reference>
<Reference Include="System" /> <Reference Include="System" />
<Reference Include="System.Core" /> <Reference Include="System.Core" />
<Reference Include="System.Net.Http" />
<Reference Include="System.Windows.Forms" /> <Reference Include="System.Windows.Forms" />
<Reference Include="System.Xml.Linq" /> <Reference Include="System.Xml.Linq" />
<Reference Include="System.Data.DataSetExtensions" /> <Reference Include="System.Data.DataSetExtensions" />
<Reference Include="Microsoft.CSharp" /> <Reference Include="Microsoft.CSharp" />
<Reference Include="System.Data" /> <Reference Include="System.Data" />
<Reference Include="System.Xml" /> <Reference Include="System.Xml" />
<Reference Include="Thinktecture.IdentityModel.Client.Net45, Version=1.0.0.0, Culture=neutral, processorArchitecture=MSIL">
<HintPath>..\packages\Thinktecture.IdentityModel.Client.4.0.1\lib\net45\Thinktecture.IdentityModel.Client.Net45.dll</HintPath>
<Private>True</Private>
</Reference>
</ItemGroup> </ItemGroup>
<ItemGroup> <ItemGroup>
<Compile Include="AddressCombiner.cs" /> <Compile Include="AddressCombiner.cs" />
@@ -56,6 +69,16 @@
<Compile Include="BaseUtility.cs" /> <Compile Include="BaseUtility.cs" />
<Compile Include="BaseMachine.cs" /> <Compile Include="BaseMachine.cs" />
<Compile Include="ComConnector.cs" /> <Compile Include="ComConnector.cs" />
<Compile Include="FBox\AddressCombinerFBox.cs" />
<Compile Include="FBox\AddressFormaterFBox.cs" />
<Compile Include="FBox\AddressTranslatorFBox.cs" />
<Compile Include="FBox\Constants.cs" />
<Compile Include="FBox\Entity.cs" />
<Compile Include="FBox\FBoxMachine.cs" />
<Compile Include="FBox\FBoxProtocal.cs" />
<Compile Include="FBox\FBoxSignalRProtocal.cs" />
<Compile Include="FBox\FBoxSignalRProtocalLinker.cs" />
<Compile Include="FBox\FBoxUtility.cs" />
<Compile Include="Modbus\AddressFormaterModbus.cs" /> <Compile Include="Modbus\AddressFormaterModbus.cs" />
<Compile Include="Modbus\AddressTranslatorModbus.cs" /> <Compile Include="Modbus\AddressTranslatorModbus.cs" />
<Compile Include="Modbus\ModbusMachine.cs" /> <Compile Include="Modbus\ModbusMachine.cs" />
@@ -79,6 +102,8 @@
<Compile Include="Modbus\ModbusProtocal.cs" /> <Compile Include="Modbus\ModbusProtocal.cs" />
<Compile Include="Modbus\ModbusTcpProtocal.cs" /> <Compile Include="Modbus\ModbusTcpProtocal.cs" />
<Compile Include="Properties\AssemblyInfo.cs" /> <Compile Include="Properties\AssemblyInfo.cs" />
<Compile Include="FBox\SignalRConnector.cs" />
<Compile Include="FBox\SignalRProtocalLinker.cs" />
<Compile Include="Simense\AddressFormaterSimense.cs" /> <Compile Include="Simense\AddressFormaterSimense.cs" />
<Compile Include="Simense\AddressTranslatorSimense.cs" /> <Compile Include="Simense\AddressTranslatorSimense.cs" />
<Compile Include="Simense\SimenseMachine.cs" /> <Compile Include="Simense\SimenseMachine.cs" />
@@ -101,7 +126,9 @@
<LastGenOutput>ConfigurationManager.Designer.cs</LastGenOutput> <LastGenOutput>ConfigurationManager.Designer.cs</LastGenOutput>
</EmbeddedResource> </EmbeddedResource>
</ItemGroup> </ItemGroup>
<ItemGroup /> <ItemGroup>
<None Include="packages.config" />
</ItemGroup>
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" /> <Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
<!-- To modify your build process, add your task inside one of the targets below and uncomment it. <!-- To modify your build process, add your task inside one of the targets below and uncomment it.
Other similar extension points exist, see Microsoft.Common.targets. Other similar extension points exist, see Microsoft.Common.targets.

View File

@@ -426,7 +426,6 @@ namespace ModBus.Net
CancellationTokenSource cts = new CancellationTokenSource(); CancellationTokenSource cts = new CancellationTokenSource();
cts.CancelAfter(TimeSpan.FromSeconds(_getCycle)); cts.CancelAfter(TimeSpan.FromSeconds(_getCycle));
var ans = await machine.GetDatasAsync().WithCancellation(cts.Token); var ans = await machine.GetDatasAsync().WithCancellation(cts.Token);
//var ans = await machine.GetDatasAsync().WithCancellation(cts.Token);
if (!machine.IsConnected) if (!machine.IsConnected)
{ {
MoveMachineToUnlinked(machine.Id); MoveMachineToUnlinked(machine.Id);

View File

@@ -0,0 +1,6 @@
<?xml version="1.0" encoding="utf-8"?>
<packages>
<package id="Microsoft.AspNet.SignalR.Client" version="2.2.0" targetFramework="net45" />
<package id="Newtonsoft.Json" version="7.0.1" targetFramework="net45" />
<package id="Thinktecture.IdentityModel.Client" version="4.0.1" targetFramework="net45" />
</packages>