/// <summary> /// DT_DEVICEテーブルからDtDeviceを取得する /// </summary> /// <param name="sid">取得するデータのSID</param> /// <returns>取得したデータ</returns> public DtDevice ReadDtDevice(long sid) { DtDevice model = null; try { _logger.Enter($"{nameof(sid)}={sid}"); DBAccessor.Models.DtDevice entity = null; _dbPolly.Execute(() => { using (DBAccessor.Models.RmsDbContext db = new DBAccessor.Models.RmsDbContext(_appSettings)) { entity = db.DtDevice.FirstOrDefault(x => x.Sid == sid); } }); if (entity != null) { model = entity.ToModel(); } return(model); } catch (Exception e) { throw new RmsException("DT_DEVICEテーブルのSelectに失敗しました。", e); } finally { _logger.LeaveJson("{0}", model); } }
public static InstancesOnDb CreateDevices(InstancesOnDb list = null) { if (list == null) { list = new InstancesOnDb(); } var builder = new TestDiProviderBuilder(); builder.ServiceCollection.AddTransient <IMtDeliveryFileTypeRepository, MtDeliveryFileTypeRepository>(); using (var provider = builder.Build()) { // 端末データテーブル { var deviceNewData = new DtDevice() { EquipmentModelSid = list.GetMtEquipmentModel().Sid, InstallTypeSid = list.GetMtInstallType().Sid, ConnectStatusSid = list.GetMtConnectStatusSid(), EdgeId = Guid.NewGuid(), EquipmentUid = Guid.NewGuid().ToString().Substring(0, 29), RemoteConnectUid = Guid.NewGuid().ToString().Substring(0, 29) }; var deviceRepository = provider.GetRequiredService <IDtDeviceRepository>(); var deviceCreateResult = deviceRepository.CreateDtDevice(deviceNewData); Assert.IsNotNull(deviceCreateResult); // deviceSid = deviceCreateResult.Entity.Sid; list.Add(deviceCreateResult); } } return(list); }
public async Task RequestRemoteAsync_SendSuccess_ReturnsSucceed() { // 以下の確認をしたい。 // ・DBから取得したエッジIDに対して処理を行う。 // ・設定から取得したメッセージを送る。 // ・引数セッションコードをその中に含む // 期待する結果 Guid expectedEdgeId = Guid.NewGuid(); string expectedSessionCode = "525215"; string expectedRemoteParameter = "isl.exe --session-code {0}."; string expectedMessage = JsonConvert.SerializeObject( new RequestRemoteMessage( expectedRemoteParameter, new RequestRemote() { SessionCode = expectedSessionCode })); var GotDevice = new DtDevice() { EdgeId = expectedEdgeId }; // 渡された値 Guid actualEdgeId = Guid.Empty; string actualMessage = string.Empty; // Target Create TestDiProviderBuilder builder = new TestDiProviderBuilder() .AddConfigure("RemoteParameter", expectedRemoteParameter); // Mock : デバイス取得に成功 SetMock_ReadDevice_Returns(GotDevice, builder); // Mock : メッセージ送信に成功 var mockOfRequestDevice = new Mock <IRequestDeviceRepository>(); mockOfRequestDevice .Setup(x => x.SendMessageAsync(It.IsAny <DeviceConnectionInfo>(), It.IsAny <string>())) .Callback <DeviceConnectionInfo, string>((info, message) => { // 引数が想定された内容で渡されたことを確認する。 actualEdgeId = info.EdgeId; actualMessage = message; }); builder.ServiceCollection.AddTransient(_ => mockOfRequestDevice.Object); var service = builder.Build().GetService <IDeviceService>(); var request = new RequestRemote() { SessionCode = expectedSessionCode }; var result = await service.RequestRemoteAsync(request); Assert.AreEqual(ResultCode.Succeed, result.ResultCode); Assert.AreEqual(expectedEdgeId, actualEdgeId); Assert.AreEqual(expectedMessage, actualMessage); }
private static void SetMock_ReadDevice_Returns(DtDevice result, TestDiProviderBuilder builder) { var mock = new Mock <IDtDeviceRepository>(); mock.Setup(x => x.ReadDtDevice(It.IsAny <long>())) .Returns(result); builder.ServiceCollection.AddTransient <IDtDeviceRepository>(_ => mock.Object); }
/// <summary> /// 引数に指定したDtDeviceをDT_DEVICEテーブルへ登録する /// </summary> /// <param name="inData">登録するデータ</param> /// <returns>処理結果</returns> public DtDevice CreateDtDevice(DtDevice inData) { DtDevice model = null; try { _logger.EnterJson("{0}", inData); DBAccessor.Models.DtDevice entity = new DBAccessor.Models.DtDevice(inData); // 初期値GUIDはIDを割り振る if (entity.EdgeId == Guid.Empty) { entity.EdgeId = Guid.NewGuid(); } _dbPolly.Execute(() => { using (DBAccessor.Models.RmsDbContext db = new DBAccessor.Models.RmsDbContext(_appSettings)) { // 接続ステータスが「unconnected」のデータを取得する var unconnectedData = db.MtConnectStatus .Where(x => x.Code.Equals(Const.ConnectStatus.Unconnected)) .FirstOrDefault(); if (unconnectedData == null) { // データ設定せずに返却 return; } // 接続ステータス設定 entity.ConnectStatusSid = unconnectedData.Sid; var dbdata = db.DtDevice.Add(entity).Entity; db.SaveChanges(_timePrivder); model = dbdata.ToModel(); } }); return(model); } catch (ValidationException e) { throw new RmsParameterException(e.ValidationResult.ErrorMessage, e); } catch (Exception e) { throw new RmsException("DT_DEVICEテーブルへのInsertに失敗しました。", e); } finally { _logger.LeaveJson("{0}", model); } }
/// <summary> /// 引数に指定したDtDeviceでDT_DEVICEテーブルを更新する /// </summary> /// <param name="inData">更新するデータ</param> /// <returns>更新したデータ</returns> public DtDevice UpdateDtDevice(DtDevice inData) { DtDevice model = null; try { _logger.EnterJson("{0}", inData); DBAccessor.Models.DtDevice entity = new DBAccessor.Models.DtDevice(inData); _dbPolly.Execute(() => { using (DBAccessor.Models.RmsDbContext db = new DBAccessor.Models.RmsDbContext(_appSettings)) { // 指定SIDのデータがDBになければnullリターン if (db.DtDevice.AsNoTracking().FirstOrDefault(x => x.Sid == inData.Sid) == null) { return; } db.DtDevice.Attach(entity); // 全フィールドを更新する // 特定フィールドだけUpdateする場合は下記のように記述してください // db.Entry(entity).Property(x => x.UpdateDatetime).IsModified = true; db.Entry(entity).Property(x => x.InstallTypeSid).IsModified = true; db.Entry(entity).Property(x => x.EquipmentModelSid).IsModified = true; if (db.SaveChanges(_timePrivder) > 0) { // 呼び出し側に更新済みデータを返却する model = db.DtDevice.AsNoTracking().FirstOrDefault(x => x.Sid == inData.Sid)?.ToModel(); } } }); return(model); } catch (ValidationException e) { throw new RmsParameterException(e.ValidationResult.ErrorMessage, e); } catch (Exception e) { throw new RmsException("DT_DEVICEテーブルのUpdateに失敗しました。", e); } finally { _logger.LeaveJson("{0}", model); } }
/// <summary> /// メッセージを送信する /// </summary> /// <param name="gatewayDevice">ゲートウェイ機器</param> /// <param name="deliveryMessage">配信メッセージ</param> /// <returns>送信成功/失敗</returns> private async Task <bool> SendMessageAsync(DtDevice gatewayDevice, string deliveryMessage) { // Sq1.5: ゲートウェイ機器が接続中のIoT Hubに問い合わせる var deveiceConnectionInfo = await GetDeviceConnectionInfoAsyncWrapper(gatewayDevice); if (deveiceConnectionInfo == null) { return(false); } // Sq1.6:ゲートウェイ機器にメッセージを送信する var sendResult = await SendMessageAsyncWrapper(deveiceConnectionInfo, deliveryMessage, gatewayDevice); return(sendResult); }
/// <summary> /// デバイスツイン更新イベントを受信して端末テーブルの「リモート接続UID」と「RMSソフトバージョン」を更新する /// </summary> /// <param name="sid">端末SID</param> /// <param name="data">更新データ</param> /// <returns>更新したデータ。テーブルが更新されなかった場合にはnullを返す</returns> public DtDevice UpdateDeviceInfoByTwinChanged(long sid, DtTwinChanged data) { DtDevice model = null; try { _logger.EnterJson("{0}", sid); _dbPolly.Execute(() => { using (DBAccessor.Models.RmsDbContext db = new DBAccessor.Models.RmsDbContext(_appSettings)) { string remoteConnectionUid = data.RemoteConnectionUid; string rmsSoftVersion = data.SoftVersion; // リモート接続UIDとRMSソフトバージョンを更新する DtDevice inData = new DtDevice() { Sid = sid, RemoteConnectUid = remoteConnectionUid, RmsSoftVersion = rmsSoftVersion }; DBAccessor.Models.DtDevice entity = new DBAccessor.Models.DtDevice(inData); db.DtDevice.Attach(entity); // リモート接続UIDとRMSソフトバージョンを更新する db.Entry(entity).Property(x => x.RemoteConnectUid).IsModified = true; db.Entry(entity).Property(x => x.RmsSoftVersion).IsModified = true; if (db.SaveChanges(_timePrivder) > 0) { model = entity.ToModel(); } } }); return(model); } catch (ValidationException e) { throw new RmsParameterException(e.ValidationResult.ErrorMessage, e); } catch (Exception e) { throw new RmsException("DT_DEVICEテーブルのUpdateに失敗しました。", e); } finally { _logger.LeaveJson("{0}", model); } }
public async Task RequestRemoteAsync_NotExistDevice_ReturnsNotFound() { DtDevice NotFoundResult = null; // Target Create var builder = new TestDiProviderBuilder(); // Mock : デバイス取得失敗 SetMock_ReadDevice_Returns(NotFoundResult, builder); var service = builder.Build().GetService <IDeviceService>(); var result = await service.RequestRemoteAsync(new RequestRemote()); Assert.AreEqual(ResultCode.NotFound, result.ResultCode); }
/// <summary> /// UtilityモデルをレスポンスDTOに変換する /// </summary> /// <param name="utilParam">Utilityのパラメータ</param> /// <returns>レスポンス用Dto</returns> public static DeviceResponseDto ConvertUtilityToResponseDto(this DtDevice utilParam) { return(utilParam == null ? null : new DeviceResponseDto() { Sid = utilParam.Sid, EdgeId = utilParam.EdgeId, InstallType = ConvertUtilityInstallTypeMasterToDto(utilParam.InstallTypeSid, utilParam.MtInstallType?.Code), EquipmentUid = utilParam.EquipmentUid, Models = ConvertUtilityModelMasterToDto(utilParam.EquipmentModelSid, utilParam.MtEquipmentModel?.Code), CreateDatetime = utilParam.CreateDatetime, UpdateDatetime = utilParam.UpdateDatetime, RemoteConnectUid = utilParam.RemoteConnectUid }); }
/// <summary> /// アラーム生成対象データを作成する /// </summary> /// <param name="alarmJudgementTargets">アラーム判定対象データ</param> /// <param name="alarmCreationTargets">アラーム生成対象データ</param> /// <returns>成功した場合true、失敗した場合falseを返す</returns> public bool CreateAlarmCreationTarget(IReadOnlyCollection <Tuple <DtDevice, DtAlarmDefConnectionMonitor> > alarmJudgementTargets, out List <Tuple <DtDevice, DtAlarmDefConnectionMonitor> > alarmCreationTargets) { bool result = true; _logger.EnterJson("{0}", new { alarmJudgementTargets }); alarmCreationTargets = new List <Tuple <DtDevice, DtAlarmDefConnectionMonitor> >(); foreach (var judgementTarget in alarmJudgementTargets) { try { (var device, var alarmDef) = judgementTarget; if (device.ConnectStatusCode != Utility.Const.ConnectStatusConnected && device.ConnectStatusCode != Utility.Const.ConnectStatusUnconnected) { if (device.ConnectUpdateDatetime != null) { TimeSpan disconnectedTime = _timeProvider.UtcNow - (DateTime)device.ConnectUpdateDatetime; int disconnectionDays = disconnectedTime.Days; if (JudgeAlarm(disconnectionDays, alarmDef)) { var alarmTargetDevice = new DtDevice(); alarmTargetDevice = device; alarmTargetDevice.DisconnectionDays = disconnectionDays; alarmTargetDevice.LastConnectDateTime = device.ConnectUpdateDatetime; alarmTargetDevice.AlarmJudgementTime = _timeProvider.UtcNow.ToString(); var alarmTarget = new Tuple <DtDevice, DtAlarmDefConnectionMonitor>(alarmTargetDevice, alarmDef); alarmCreationTargets.Add(alarmTarget); } } } } catch (Exception e) { // アラーム生成エラー(基本設計書 5.2.1.1 エラー処理) _logger.Error(e, nameof(Resources.UT_DCM_DCM_005), new object[] { judgementTarget?.Item1?.Sid }); result = false; } } _logger.LeaveJson("{0}", new { alarmCreationTargets }); return(result); }
public async Task RequestRemoteAsync_NotExistRemoteParamAtAppSettings_ReturnsServerError() { var GotDevice = new DtDevice(); // Target Create TestDiProviderBuilder builder = new TestDiProviderBuilder(); //.AddConfigure("RemoteParameter", "isl.exe --session-code {0}."); // Mock : デバイス取得に成功 SetMock_ReadDevice_Returns(GotDevice, builder); var service = builder.Build().GetService <IDeviceService>(); var result = await service.RequestRemoteAsync(new RequestRemote()); Assert.AreEqual(ResultCode.ServerEerror, result.ResultCode); }
/// <summary> /// 配信メッセージを作成する /// </summary> /// <param name="messageObject">配信メッセージオブジェクト</param> /// <param name="gatewayDevice">ゲートウェイ機器</param> /// <returns>配信メッセージ</returns> private string CreateDeliveryMessageJson(RequestDelivery messageObject, DtDevice gatewayDevice) { string deliveryMessage = null; try { Assert.IfNull(messageObject); deliveryMessage = JsonConvert.SerializeObject(messageObject); _logger.Debug("message: {0}", new object[] { deliveryMessage }); } catch (Exception e) { // Sq1.4 _logger.Error(e, nameof(Resources.CO_DLV_DLV_012), new object[] { gatewayDevice.EdgeId, gatewayDevice.EquipmentUid, e.Message }); } return(deliveryMessage); }
/// <summary> /// DT_DEVICEテーブルからDtDeviceを取得する /// </summary> /// <param name="equipmentUidOrEdgeId">取得するデータの機器UIDまたはエッジID</param> /// <returns>取得したデータ</returns> public DtDevice ReadDtDevice(string equipmentUidOrEdgeId) { DtDevice model = null; try { _logger.Enter($"{nameof(equipmentUidOrEdgeId)}={equipmentUidOrEdgeId}"); DBAccessor.Models.DtDevice entity = null; _dbPolly.Execute(() => { using (DBAccessor.Models.RmsDbContext db = new DBAccessor.Models.RmsDbContext(_appSettings)) { entity = db.DtDevice.FirstOrDefault(x => x.EquipmentUid == equipmentUidOrEdgeId); if (entity == null && Guid.TryParse(equipmentUidOrEdgeId, out Guid edgeId)) { entity = db.DtDevice.FirstOrDefault(x => x.EdgeId == edgeId); } } }); if (entity != null) { model = entity.ToModel(); } return(model); } catch (ValidationException e) { throw new RmsParameterException(e.ValidationResult.ErrorMessage, e); } catch (Exception e) { throw new RmsException("DT_DEVICEテーブルのSelectに失敗しました。", e); } finally { _logger.LeaveJson("{0}", model); } }
public async Task RequestRemoteAsync_ThrowExceptionAtSendMessage_ThrownException() { var exception = new Exception(); var GotDevice = new DtDevice(); // Target Create TestDiProviderBuilder builder = new TestDiProviderBuilder() .AddConfigure("RemoteParameter", "isl.exe --session-code {0}."); // Mock : デバイス取得に成功 SetMock_ReadDevice_Returns(GotDevice, builder); // Mock : メッセージ送信時に例外 SetMock_SendMessage_Thrown(exception, builder); var service = builder.Build().GetService <IDeviceService>(); var request = new RequestRemote(); var result = await service.RequestRemoteAsync(request); Assert.Fail(); }
/// <summary> /// DT_DEVICEテーブルからDtDeviceを削除する /// </summary> /// <param name="sid">削除するデータのSID</param> /// <param name="equipmentUid">削除するデータのデバイスUID</param> /// <param name="remoteConnectUid">削除するデータのリモート接続UID</param> /// <returns>削除したデータ</returns> public DtDevice DeleteDtDevice(long sid, string equipmentUid, string remoteConnectUid) { DtDevice model = null; try { _logger.Enter($"{nameof(sid)}={sid} {nameof(equipmentUid)}={equipmentUid} {nameof(remoteConnectUid)}={remoteConnectUid}"); DBAccessor.Models.DtDevice entity = new DBAccessor.Models.DtDevice() { Sid = sid, EquipmentUid = equipmentUid, RemoteConnectUid = remoteConnectUid }; _dbPolly.Execute(() => { using (DBAccessor.Models.RmsDbContext db = new DBAccessor.Models.RmsDbContext(_appSettings)) { db.DtDevice.Attach(entity); db.DtDevice.Remove(entity); if (db.SaveChanges(_timePrivder) > 0) { model = entity.ToModel(); } } }); return(model); } catch (Exception e) { throw new RmsException("DT_DEVICEテーブルのDeleteに失敗しました。", e); } finally { _logger.LeaveJson("{0}", model); } }
/// <summary> /// 端末へリモート接続のリクエストを行う /// </summary> /// <remarks>sd 03-2.リモート接続(ワンタイム接続)</remarks> /// <param name="request">リクエスト</param> /// <returns>結果</returns> public async Task <Result> RequestRemoteAsync(RequestRemote request) { Result result = null; RequestRemoteAsyncStatus status = RequestRemoteAsyncStatus.ReadDtDevice; try { _logger.EnterJson("In Param: {0}", request); // 端末データからDeviceIDをDeviceEdgeIdを取得する。 DtDevice model = _dtDeviceRepository.ReadDtDevice(request.DeviceId); if (model == null) { _logger.Error(nameof(Resources.CO_API_DRC_003)); result = new Result(ResultCode.NotFound, Resources.CO_API_DRC_003); return(result); } // Sq3.1.1 接続先情報を取得する status = RequestRemoteAsyncStatus.GetDeviceConnectionInfoAsync; DeviceConnectionInfo deveiceConnectionInfo = await _requestDeviceRepository.GetDeviceConnectionInfoAsync(model.EdgeId); if (deveiceConnectionInfo == null) { _logger.Error(nameof(Resources.CO_API_DRC_004)); result = new Result(ResultCode.NotFound, Resources.CO_API_DRC_004); return(result); } // Sq3.1.2 メッセージを生成する string message = CreateMessage(request, out result); // Sq3.1.3 メッセージを送信する status = RequestRemoteAsyncStatus.SendMessageAsync; await _requestDeviceRepository.SendMessageAsync(deveiceConnectionInfo, message); _logger.Info(nameof(Resources.CO_API_DRC_007)); result = new Result(ResultCode.Succeed, Resources.CO_API_DRC_007); return(result); } catch (Exception ex) { switch (status) { // ReadDtDeviceでnullを返さずにExceptionが発生した場合 case RequestRemoteAsyncStatus.ReadDtDevice: _logger.Error(nameof(Resources.CO_API_DRC_003)); result = new Result(ResultCode.NotFound, Resources.CO_API_DRC_003); break; case RequestRemoteAsyncStatus.GetDeviceConnectionInfoAsync: _logger.Error(ex, nameof(Resources.CO_API_DRC_004)); result = new Result(ResultCode.ServerEerror, Resources.CO_API_DRC_004); break; case RequestRemoteAsyncStatus.SendMessageAsync: default: _logger.Error(ex, nameof(Resources.CO_API_DRC_006)); result = new Result(ResultCode.ServerEerror, Resources.CO_API_DRC_006); break; } return(result); } finally { _logger.LeaveJson("Result Param: {0}", result); } }
/// <summary> /// 機器情報を更新する /// </summary> /// <remarks>sd 04-01.機器登録</remarks> /// <param name="utilParam">>Utility型機器情報</param> /// <param name="baseConfig">設置設定情報</param> /// <returns>結果付きDB保存済み機器情報</returns> public Result <DtDevice> Update(DtDevice utilParam, InstallBaseConfig baseConfig) { Result <DtDevice> result = null; CreateAndUpdateStatus status = CreateAndUpdateStatus.Other; try { _logger.EnterJson("In Param: {0}", utilParam); // 一連の動きのためトランザクション処理開始 using (TransactionScope scope = new TransactionScope()) { // Sq3.2.1:機器情報を保存する status = CreateAndUpdateStatus.UpdateDtDevice; DtDevice updatedDeviceInfo = _dtDeviceRepository.UpdateDtDevice(utilParam); if (updatedDeviceInfo == null) { // 指定SIDのデータがないとnullが返る _logger.Error(nameof(Resources.CO_API_DVU_003), new object[] { "指定したSIDのデータがDBにありません" }); return(new Result <DtDevice>( ResultCode.NotFound, string.Format(Resources.CO_API_DVU_003, new object[] { "指定したSIDのデータがDBにありません" }), utilParam)); } // 設置設定インスタンスにエッジID・機器UIDを登録する string edgeId = updatedDeviceInfo.EdgeId.ToString(); baseConfig.OwnConfig.EdgeId = edgeId; baseConfig.OwnConfig.EquipmentUid = updatedDeviceInfo.EquipmentUid; string configMessage = string.Empty; // Sq3.2.2:設置設定ファイルを生成する(機器情報) status = CreateAndUpdateStatus.MakeArchiveFile; var archiveFile = MakeArchiveFile( baseConfig, updatedDeviceInfo.EquipmentUid, updatedDeviceInfo.UpdateDatetime, out configMessage); // Sq3.2.3:設置設定ファイルをアップロードする(設置設定ファイル) status = CreateAndUpdateStatus.Upload; _deliveringRepository.Upload(archiveFile, configMessage); // 正常終了 status = CreateAndUpdateStatus.Other; _logger.Info(nameof(Resources.CO_API_DVU_007), new object[] { edgeId }); result = new Result <DtDevice>( ResultCode.Succeed, string.Format(Resources.CO_API_DVU_007, new object[] { edgeId }), updatedDeviceInfo); scope.Complete(); } return(result); } catch (RmsParameterException e) { // Sq3.2.1 _logger.Error(e, nameof(Resources.CO_API_DVU_003), new object[] { e.Message }); return(new Result <DtDevice>( ResultCode.ParameterError, string.Format(Resources.CO_API_DVU_003, new object[] { e.Message }), utilParam)); } catch (Exception) when(status == CreateAndUpdateStatus.Other) { // 想定外のエラーは呼び出し側に返却する throw; } catch (Exception e) { string errorMessage = string.Empty; switch (status) { case CreateAndUpdateStatus.UpdateDtDevice: // Sq3.2.1 _logger.Error(e, nameof(Resources.CO_API_DVU_004), new object[] { e.Message }); errorMessage = string.Format(Resources.CO_API_DVU_004, new object[] { e.Message }); break; case CreateAndUpdateStatus.MakeArchiveFile: // Sq3.2.2 _logger.Error(e, nameof(Resources.CO_API_DVU_005), new object[] { e.Message }); errorMessage = string.Format(Resources.CO_API_DVU_005, new object[] { e.Message }); break; case CreateAndUpdateStatus.Upload: default: // Sq3.2.3 _logger.Error(e, nameof(Resources.CO_API_DVU_006), new object[] { e.Message }); errorMessage = string.Format(Resources.CO_API_DVU_006, new object[] { e.Message }); break; } return(new Result <DtDevice>(ResultCode.ServerEerror, errorMessage, utilParam)); } finally { _logger.LeaveJson("Out Param: {0}", result); } }
/// <summary> /// デバイス接続情報を取得する(ラッパー) /// </summary> /// <param name="gatewayDevice">ゲートウェイ機器</param> /// <returns>デバイス接続情報</returns> private async Task <DeviceConnectionInfo> GetDeviceConnectionInfoAsyncWrapper(DtDevice gatewayDevice) { DeviceConnectionInfo deveiceConnectionInfo = null; try { deveiceConnectionInfo = await _requestDeviceRepository.GetDeviceConnectionInfoAsync(gatewayDevice.EdgeId); if (deveiceConnectionInfo == null) { // Sq1.5(デバイスが見つからない場合) throw new RmsException("IoTHubの接続文字列が見つかりません"); } } catch (Exception e) { // Sq1.5 _logger.Error(e, nameof(Resources.CO_DLV_DLV_013), new object[] { gatewayDevice.EdgeId, gatewayDevice.EquipmentUid, e.Message }); } return(deveiceConnectionInfo); }
/// <summary> /// 機器情報を更新する /// </summary> /// <remarks>sd 04-01.機器登録</remarks> /// <param name="utilParam">>Utility型機器情報</param> /// <param name="baseConfig">設置設定情報</param> /// <returns>結果付きDB保存済み機器情報</returns> public Result <DtDevice> Update(DtDevice utilParam, InstallBaseConfig baseConfig) { throw new Exception(); }
/// <summary> /// ゲートウェイ機器にメッセージを送信する(ラッパー) /// </summary> /// <param name="deveiceConnectionInfo">デバイス接続情報</param> /// <param name="deliveryMessage">配信メッセージ</param> /// <param name="gatewayDevice">ゲートウェイ機器</param> /// <returns>送信依頼処理成功/失敗</returns> private async Task <bool> SendMessageAsyncWrapper(DeviceConnectionInfo deveiceConnectionInfo, string deliveryMessage, DtDevice gatewayDevice) { bool ret = false; try { await _requestDeviceRepository.SendMessageAsync(deveiceConnectionInfo, deliveryMessage); ret = true; } catch (Exception e) { // Sq1.6 _logger.Error(e, nameof(Resources.CO_DLV_DLV_015), new object[] { gatewayDevice.EdgeId, gatewayDevice.EquipmentUid, e.Message }); } return(ret); }
/// <summary> /// ゲートウェイ機器を持つ配信機器の配信結果ステータスを更新する(messagesent)(ラッパー) /// </summary> /// <param name="includedGroup">配信結果情報をもつ配信グループ</param> /// <param name="gatewayDevice">ゲートウェイ機器</param> /// <returns>更新した適用結果</returns> private IEnumerable <DtInstallResult> CreateDtInstallResultStatusSentWrapper(DtDeliveryGroup includedGroup, DtDevice gatewayDevice) { IEnumerable <DtInstallResult> models = new List <DtInstallResult>(); try { models = _installResultRepository.CreateDtInstallResultStatusSent(includedGroup, gatewayDevice.Sid); } catch (Exception e) { // Sq1.7 _logger.Error(e, nameof(Resources.CO_DLV_DLV_016), new object[] { gatewayDevice.EdgeId, gatewayDevice.EquipmentUid, e.Message }); } return(models); }
/// <summary> /// DT_DEVICEテーブルからDtDeviceを取得する /// </summary> /// <returns>取得したデータ</returns> public IEnumerable <DtDevice> ReadDtDevice() { IEnumerable <DtDevice> models = null; try { _logger.Enter(); _dbPolly.Execute(() => { using (DBAccessor.Models.RmsDbContext db = new DBAccessor.Models.RmsDbContext(_appSettings)) { if (!db.DtDevice.Any()) { // 端末データテーブルにデータがない場合は正常系 models = new List <DtDevice>(); } else { // インベントリデータテーブルは更新ではなく新規追加なので端末SID毎に最新のデータを取得して結合する var inventoryLatests = db.DtInventory.GroupBy(x => x.DeviceSid).Select(y => y.OrderByDescending(z => z.CreateDatetime).FirstOrDefault()); var joinEntities = db.DtDevice .Join( db.MtConnectStatus, x => x.ConnectStatusSid, y => y.Sid, (device, connectStatus) => new { Device = device, ConnectStatusCode = connectStatus.Code }) .Join( db.MtInstallType, x => x.Device.InstallTypeSid, y => y.Sid, (joinTable, installType) => new { joinTable.Device, joinTable.ConnectStatusCode, InstallTypeTableCode = installType.Code, }) .Join( inventoryLatests, x => x.Device.Sid, y => y.DeviceSid, (joinTable, inventory) => new { joinTable.Device, joinTable.ConnectStatusCode, joinTable.InstallTypeTableCode, InventoryDetailInfo = inventory.DetailInfo }).ToList(); if (!joinEntities.Any()) { throw new RmsException("JoinによりDT_DEVICEテーブルのデータ抽出数が0になりました。"); } else { models = new List <DtDevice>(); foreach (var entity in joinEntities) { var detailInfo = JsonConvert.DeserializeObject <JObject>(entity.InventoryDetailInfo); // アラーム判定・アラーム情報の生成に必要な属性のみ取得 var model = new DtDevice { EquipmentUid = entity.Device.EquipmentUid, ConnectStatusCode = entity.ConnectStatusCode, TypeCode = entity.InstallTypeTableCode, TemperatureSensor = (string)detailInfo[Utility.Const.InventoryAlSoftwareName][Utility.Const.InventorySettingInfoName][Utility.Const.InventoryOptionName][Utility.Const.InventoryTemperatureSensorName], Dxa = (string)detailInfo[Utility.Const.InventoryAlSoftwareName][Utility.Const.InventorySettingInfoName][Utility.Const.InventoryOptionName][Utility.Const.InventoryDxaName], ConnectUpdateDatetime = entity.Device.ConnectUpdateDatetime }; models.Append(model); } } } } }); return(models); } catch (Exception e) { throw new RmsException("DT_DEVICEテーブルのSelectに失敗しました。", e); } finally { _logger.LeaveJson("{0}", models); } }
public bool TSCheck(string accounts, EventHandler <StatArgs> handler) { #region variable DateTime mtime = DateTime.Now; this.evnt = handler; this.mailer = new Mailer(accounts); this.failr = new List <string>(); this.mail("TS Time Checker (version " + System.Reflection.Assembly.GetEntryAssembly().GetName().Version + ") started!"); #endregion #region attach a device DtDevice dv = new DtDevice(); if (dv.AttachToType(245) != DTAPI_RESULT.OK) { return(this.err("Failed to attach to type")); } #endregion #region set device byte[] buf = new byte[0]; int bsize = 4194304; //1048576, 2097152, 4194304, 8388608 try { buf = new byte[bsize]; } catch (Exception e) { return(this.err(e.Message)); } DtInpChannel inp = new DtInpChannel(); if (inp.AttachToPort(dv, 1) != DTAPI_RESULT.OK) { return(this.err("Failed to Inp Channel")); } if (inp.SetRxControl(DTAPI.RXCTRL_RCV) != DTAPI_RESULT.OK) { return(this.err("Failed to set receive FIFO")); } #endregion #region read #region prepare string msg = String.Empty, dm; int afc = 0, iip = 0, y = 0, m = 0, d = 0, hr = 0, mn = 0, sc = 0; bool timed = false, read = false, init = true, dated = false, recor = false; DateTime ct = DateTime.Now.ToUniversalTime(); DateTime pt = new DateTime(1900, 1, 1); while (!this.stat.abort) { pt = new DateTime(1900, 1, 1); ct = DateTime.Now.ToUniversalTime(); read = true; #region data this.log("to read"); try { inp.Read(buf, bsize); } catch (Exception) { read = this.err("Failed to read data at " + this.dsptime(ct)); this.ongoing("Failed to read data at " + this.dsptime(ct), ref mtime); #region to del this.failr.Add("Failed to read data at " + this.dsptime(ct)); if (this.failr.Count > 9) { if (DateTime.Now.Subtract(mtime).TotalMinutes > 10) { dm = this.failr.Count + " read errors." + Environment.NewLine; for (int i = 0; i < 5; i++) { dm += "(" + (i + 1) + ") " + this.failr[i] + Environment.NewLine; } for (int i = this.failr.Count - 5; i < this.failr.Count; i++) { dm += "(" + (i + 1) + ") " + this.failr[i] + Environment.NewLine; } this.mail(dm); this.failr = new List <string>(); mtime = DateTime.Now; } } else if (DateTime.Now.Subtract(mtime).TotalMinutes > 60) { dm = this.failr.Count + " read errors." + Environment.NewLine; foreach (string s in this.failr) { dm += s + Environment.NewLine; } this.mail(dm); this.failr = new List <string>(); mtime = DateTime.Now; } #endregion } if (!read) { continue; } //ct = DateTime.Now.ToUniversalTime(); //to TEST. todo if (init) { this.logd(buf, ct); init = false; } #endregion #region analysis timed = false; msg = String.Empty; #region loop this.log("to loop"); try { for (int i = 0; i < bsize; i += 188) { if (buf[i] == 0x47 && (this.b2(buf, i + 1) & 0x1fff) == 0x14) { afc = (buf[i + 3] >> 4) & 3; iip = (afc & 2) == 2 ? buf[i + 4] + 5 : 4; //adaptation_field if ((afc & 1) == 1) { iip += buf[i + iip] + 1; if (buf[i + iip] == 0x70) { this.byMJD((int)this.b2(buf, i + iip + 3), ref y, ref m, ref d); if ((hr = this.byBCD(buf[i + iip + 5], true)) < 0 || (mn = this.byBCD(buf[i + iip + 6])) < 0 || (sc = this.byBCD(buf[i + iip + 7])) < 0) { this.logd(buf, ct); } else { dated = true; try { pt = new DateTime(1900 + y, m, d, hr, mn, sc); } catch (Exception e) { this.log(e.Message); this.logd(buf, ct); dated = false; } #region compare if (dated) { msg = this.samet(ct, pt) ? "Same" : "Different"; if (msg == "Different") { this.mail(msg + ": PlayBack Time " + this.dsptime(pt) + ", Local Time " + this.dsptime(ct)); this.logd(buf, ct); recor = true; } else if (recor) { this.mail(msg + " (Corrected): PlayBack Time " + this.dsptime(pt) + ", Local Time " + this.dsptime(ct)); this.logd(buf, ct); recor = false; } timed = true; break; } #endregion } } } } } } catch (Exception e) { this.log("Failed to analyze data. " + e.Message); this.ongoing("Failed to analyze data. " + e.Message, ref mtime); } #endregion #endregion if (timed) { this.log(msg + ": Play " + this.dsptime(pt) + ", Local " + this.dsptime(ct)); this.upAll(ct, pt, 100, timed ? TSStat.Success : TSStat.Failure, msg); } } #endregion #region abort //System.Threading.Thread.Sleep(500); //this.upStat(TSStat.Waiting); //while(!this.stat.abort) { // System.Threading.Thread.Sleep(500); // this.upEvent(); //} #endregion return(true); #endregion }
/// <summary> /// 端末テーブルの接続ステータスを更新する /// </summary> /// <param name="sid">端末SID</param> /// <param name="connectionEventTimeInfo">接続/切断イベント時刻情報</param> /// <returns>更新したデータ。ステータスに変更がなかった場合にはnullを返す</returns> public DtDevice UpdateDeviceConnectionStatus(long sid, ConnectionEventTimeInfo connectionEventTimeInfo) { DtDevice model = null; try { _logger.EnterJson("{0}", sid); _dbPolly.Execute(() => { using (DBAccessor.Models.RmsDbContext db = new DBAccessor.Models.RmsDbContext(_appSettings)) { // 該当するステータスSIDをマスタテーブルから取得する var record = db.MtConnectStatus.FirstOrDefault(x => x.Code == connectionEventTimeInfo.Status); if (record == null || record.Sid == 0) { throw new RmsException("接続ステータスマスターテーブルに該当するステータスが存在しませんでした。"); } // ステータスSID, 接続開始日時, 接続更新日時 DtDevice inData = new DtDevice() { Sid = sid, ConnectStatusSid = record.Sid, ConnectStartDatetime = connectionEventTimeInfo.EventTime, ConnectUpdateDatetime = connectionEventTimeInfo.EventTime }; DBAccessor.Models.DtDevice entity = new DBAccessor.Models.DtDevice(inData); db.DtDevice.Attach(entity); // 接続ステータスが更新されるのでステータスSIDと接続更新日時は更新対象 db.Entry(entity).Property(x => x.ConnectStatusSid).IsModified = true; db.Entry(entity).Property(x => x.ConnectUpdateDatetime).IsModified = true; // 初回接続フラグがtrueのときは接続開始日時も更新対象 if (connectionEventTimeInfo.IsFirstConnection) { db.Entry(entity).Property(x => x.ConnectStartDatetime).IsModified = true; } if (db.SaveChanges(_timePrivder) > 0) { model = entity.ToModel(); } } }); return(model); } catch (ValidationException e) { throw new RmsParameterException(e.ValidationResult.ErrorMessage, e); } catch (Exception e) { throw new RmsException("DT_DEVICEテーブルのUpdateに失敗しました。", e); } finally { _logger.LeaveJson("{0}", model); } }