Exemplo n.º 1
0
        public FBoxUtility(FBoxType fBoxType, string connectionString, IEnumerable<CommunicationUnit> communicationUnits, SignalRSigninMsg msg)
        {
            ConnectionString = connectionString;
            CommunicationUnits = communicationUnits.AsEnumerable();
            SigninMsg = msg;

            ConnectionType = fBoxType;           
            AddressTranslator = new AddressTranslatorFBox();
        }
Exemplo n.º 2
0
        public SignalRConnector(string machineId, SignalRSigninMsg msg)
        {
            Constants.SignalRServer = msg.SignalRServer;
            System.Net.ServicePointManager.ServerCertificateValidationCallback = delegate { return true; };
            ConnectionToken = machineId;
            if (_oauth2 == null)
            {
                _httpClient = new Dictionary<SignalRSigninMsg, HttpClient>();
                _oauth2 = new Dictionary<SignalRSigninMsg, OAuth2Client>();
                _hubConnections = new Dictionary<string, HubConnection>();
                _httpClient2 = new Dictionary<string, HttpClient>();
                _machineData = new Dictionary<string, Dictionary<string, double>>();
                _machineDataType = new Dictionary<string, Dictionary<string, Type>>();
                _boxUidSessionId = new Dictionary<string, int>();
                _connectionTokenState = new Dictionary<string, int>();
                _groupNameUid = new Dictionary<string, string>();  
                _groupNameBoxUid = new Dictionary<string, string>();
                _boxUidDataGroups = new Dictionary<string, List<DMonGroup>>();                       
            }

            if (!_oauth2.ContainsKey(msg))
            {
                _oauth2.Add(msg, new OAuth2Client(
                    new Uri(Constants.TokenEndpoint),
                    msg.ClientId,
                    msg.ClientSecret
                    ));
                var tokenResponse = _oauth2[msg].RequestResourceOwnerPasswordAsync
                    (
                        msg.UserId,
                        msg.Password,
                        msg.SigninAdditionalValues
                    ).Result;
                if (tokenResponse != null)
                    AsyncHelper.RunSync(() => CallService(msg, tokenResponse.AccessToken));
            }
        }
Exemplo n.º 3
0
 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);      
 }
Exemplo n.º 4
0
        private async Task CallService(SignalRSigninMsg msg, string token)
        {
            var guid = Guid.NewGuid().ToString();

            var baseAddress = Constants.AspNetWebApiSampleApi;

            if (!_httpClient.ContainsKey(msg))
            {
                _httpClient.Add(msg, new HttpClient
                {
                    BaseAddress = new Uri(baseAddress)
                });
            }

            _httpClient[msg].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[msg].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 client2 = new HttpClient
                    {
                        BaseAddress = new Uri(baseUrl)
                    };
                    client2.SetBearerToken(token);
                    client2.DefaultRequestHeaders.Add("X-FBox-ClientId", guid);

                    response = await client2.GetStringAsync("box/" + box.Box.Uid + "/dmon/def/grouped");

                    List<DMonGroup> dataGroups = JsonConvert.DeserializeObject<List<DMonGroup>>(response);
                    _boxUidDataGroups.Add(boxUid, dataGroups);
                    _boxUidSessionId.Add(boxUid, sessionId);

                    var hubConnection = new HubConnection(signalrUrl);
                    _hubConnections.Add(boxUid, hubConnection);
                    hubConnection.Headers.Add("Authorization", "Bearer " + token);
                    hubConnection.Headers.Add("X-FBox-ClientId", guid);
                    hubConnection.Headers.Add("X-FBox-Session", sessionId.ToString());

                    IHubProxy dataHubProxy = hubConnection.CreateHubProxy("clientHub");
                    dataHubProxy.On<int, List<GetValue>>("dMonUpdateValue",
                        (boxSessionId, values) =>
                        {
                            lock (_boxUidSessionId)
                            {
                                if (_boxUidSessionId.ContainsValue(boxSessionId))
                                {
                                    Console.WriteLine($"Box session {boxSessionId} return at {DateTime.Now}");
                                    var localBoxUid = _boxUidSessionId.FirstOrDefault(p => p.Value == boxSessionId).Key;
                                    foreach (var value in values)
                                    {
                                        if (value.Status != 0) return;
                                        lock (_machineData)
                                        {
                                            if (_boxUidDataGroups.ContainsKey(localBoxUid))
                                            {
                                                foreach (var dataGroupInner in _boxUidDataGroups[localBoxUid])
                                                {
                                                    if (dataGroupInner.DMonEntries.Any(p => p.Uid == value.Id))
                                                    {
                                                        if (!_machineData.ContainsKey(dataGroupInner.Name))
                                                        {
                                                            _machineData.Add(dataGroupInner.Name,
                                                                new Dictionary<string, double>());
                                                        }
                                                        if (_machineData[dataGroupInner.Name] == null)
                                                        {
                                                            _machineData[dataGroupInner.Name] =
                                                                new Dictionary<string, double>();
                                                        }

                                                        var dMonEntry =
                                                            dataGroupInner.DMonEntries.FirstOrDefault(
                                                                p => p.Uid == value.Id);

                                                        if (value.Value.HasValue && dMonEntry != null)
                                                        {
                                                            if (
                                                                _machineData[dataGroupInner.Name].ContainsKey(
                                                                    dMonEntry.Desc))
                                                            {
                                                                _machineData[dataGroupInner.Name][dMonEntry.Desc] =
                                                                    value.Value.Value;
                                                            }
                                                            else
                                                            {
                                                                _machineData[dataGroupInner.Name].Add(dMonEntry.Desc,
                                                                    value.Value.Value);
                                                            }
                                                        }
                                                        break;
                                                    }
                                                }
                                            }
                                        }
                                    }
                                }
                            }
                        });

                    dataHubProxy.On<int, string, int, int>("boxConnectionStateChanged",
                        async (newConnectionToken, getBoxUid, oldStatus, newStatus) =>
                        {
                            using (await _lock.LockAsync())
                            {
                                if (_httpClient2.ContainsKey(getBoxUid))
                                {
                                    Console.WriteLine(
                                        $"Box uid {getBoxUid} change state at {DateTime.Now} new connectionToken {newConnectionToken} newStatus {newStatus}");
                                    sessionId = newConnectionToken;
                                    lock (_boxUidSessionId)
                                    {
                                        _boxUidSessionId[getBoxUid] = sessionId;
                                    }

                                    var localDataGroups = _boxUidDataGroups[getBoxUid];
                                    lock (_connectionTokenState)
                                    {
                                        foreach (var localDataGroup in localDataGroups)
                                        {
                                            if (!_connectionTokenState.ContainsKey(localDataGroup.Name))
                                            {
                                                _connectionTokenState.Add(localDataGroup.Name, newStatus);
                                            }
                                            else
                                            {
                                                _connectionTokenState[localDataGroup.Name] = newStatus;
                                            }
                                        }
                                    }
                                    _httpClient2[getBoxUid].DefaultRequestHeaders.Remove("X-FBox-Session");
                                    _httpClient2[getBoxUid].DefaultRequestHeaders.Add("X-FBox-Session",
                                        sessionId.ToString());
                                    _hubConnections[getBoxUid].Headers["X-FBox-Session"] = sessionId.ToString();

                                    if (_hubConnections[getBoxUid].State == ConnectionState.Disconnected)
                                    {
                                        await _hubConnections[getBoxUid].Start();                                       
                                    }

                                    if (newStatus == 1 && IsConnected)
                                    {                                     
                                        foreach (var localDataGroup in localDataGroups)
                                        {
                                            await
                                                _httpClient2[getBoxUid].PostAsync(
                                                    "dmon/group/" + localDataGroup.Uid + "/start", null);
                                        }
                                    }
                                    else
                                    {
                                        //foreach (var localDataGroup in localDataGroups)
                                        //{
                                            //lock (_machineData)
                                            //{
                                                //if (_machineData.ContainsKey(localDataGroup.Name))
                                                //{
                                                    //_machineData.Remove(localDataGroup.Name);
                                                //}
                                                //await
                                                    //_httpClient2[getBoxUid].PostAsync(
                                                        //"dmon/group/" + localDataGroup.Uid + "/stop", null);
                                            //}
                                        //}
                                    }
                                }
                            }
                        });

                    hubConnection.Error += ex => Console.WriteLine(@"SignalR error: {0}", ex.Message);

                    hubConnection.Closed += async () =>
                    {
                        string getBoxUid;
                        lock (_boxUidSessionId)
                        {
                            getBoxUid =
                                _boxUidSessionId.FirstOrDefault(
                                    p => p.Value == int.Parse(hubConnection.Headers["X-FBox-Session"])).Key;
                        }
                        if (hubConnection.State != ConnectionState.Connected)
                        {
                            await hubConnection.Start();
                            if (IsConnected)
                            {
                                var localDataGroups = _boxUidDataGroups[getBoxUid];
                                foreach (var localDataGroup in localDataGroups)
                                {
                                await
                                    _httpClient2[getBoxUid].PostAsync(
                                        "dmon/group/" + localDataGroup.Uid + "/start", null);
                                }
                            }
                        }
                    };

                    ServicePointManager.DefaultConnectionLimit = 10;

                    foreach (var dataGroup in dataGroups)
                    {
                        if (dataGroup == null) return;

                        var groupUid = dataGroup.Uid;
                        var groupName = dataGroup.Name;

                        _connectionTokenState.Add(groupName, 1);
                        if (groupName != "(Default)" && !_groupNameUid.ContainsKey(groupName))
                        {
                            _groupNameUid.Add(groupName, groupUid);
                        }
                        if (groupName != "(Default)" && !_groupNameBoxUid.ContainsKey(groupName))
                        {
                            _groupNameBoxUid.Add(groupName, boxUid);
                        }
                        if (groupName != "(Default)" && !_httpClient2.ContainsKey(boxUid))
                        {
                            _httpClient2.Add(boxUid, client2);
                        }

                        if (!_machineDataType.ContainsKey(groupName))
                        {
                            _machineDataType.Add(groupName, new Dictionary<string, Type>());
                        }
                        foreach (var dMonEntry in dataGroup.DMonEntries)
                        {
                            Type type;
                            switch (dMonEntry.DataType)
                            {
                                //位
                                case 0:
                                {
                                    type = typeof (bool);
                                    break;
                                }
                                //16位无符号
                                case 1:
                                {
                                    type = typeof (ushort);
                                    break;
                                }
                                //16位有符号
                                case 2:
                                {
                                    type = typeof (short);
                                    break;
                                }
                                //32位无符号
                                case 11:
                                {
                                    type = typeof (uint);
                                    break;
                                }
                                //32位有符号
                                case 12:
                                {
                                    type = typeof (int);
                                    break;
                                }
                                //16位BCD
                                case 3:
                                {
                                    type = typeof (short);
                                    break;
                                }
                                //32位BCD
                                case 13:
                                {
                                    type = typeof (int);
                                    break;
                                }
                                //浮点数
                                case 16:
                                {
                                    type = typeof (float);
                                    break;
                                }
                                //16位16进制
                                case 4:
                                {
                                    type = typeof (short);
                                    break;
                                }
                                //32位16进制
                                case 14:
                                {
                                    type = typeof (int);
                                    break;
                                }
                                //16位2进制
                                case 5:
                                {
                                    type = typeof (short);
                                    break;
                                }
                                //32位2进制
                                case 15:
                                {
                                    type = typeof (int);
                                    break;
                                }
                                default:
                                {
                                    type = typeof (short);
                                    break;
                                }
                            }

                            if (!_machineDataType[groupName].ContainsKey(dMonEntry.Desc))
                            {
                                _machineDataType[groupName].Add(dMonEntry.Desc, type);
                            }
                            else
                            {
                                _machineDataType[groupName][dMonEntry.Desc] = type;
                            }
                        }
                    }

                    await hubConnection.Start();
                    await dataHubProxy.Invoke("updateClientId", guid);
                }            
            }
        }
Exemplo n.º 5
0
 public FBoxSignalRProtocal(string machineId, SignalRSigninMsg msg)
 {
     ProtocalLinker = new FBoxSignalRProtocalLinker(machineId, msg);
 }
 public FBoxSignalRProtocalLinker(string machineId, SignalRSigninMsg msg) : base(machineId, msg)
 {
 }
Exemplo n.º 7
0
 protected SignalRProtocalLinker(string machineId, SignalRSigninMsg msg)
 {
     _baseConnector = new SignalRConnector(machineId, msg);
 }