Example #1
0
 void handlePlaystateChanged(object sender, DeviceController.DevicePlaystateEventArgs e)
 {
     if (e.Playstate == DeviceController.DevicePlaystateEventArgs.DevicePlaystate.ReachedEnd)
     {
         PlayNext();
     }
 }
Example #2
0
	void Start () 
	{
		instance = this;
		anim = GetComponent<Animator> ();
		initialPosition = transform.position;
		movement = initialPosition;
	}
Example #3
0
        /*
         * Methods
         */
        public Interface(DeviceController.IController controller,
                          ContentProvider.Providers providers)
        {
            Controller = controller;
            Providers = providers;
            Clients = new Dictionary<IWebClient, IDevice>();
            KnownDevices = new Dictionary<string, IDevice>();

            WebSocketManager = new WebSocket.Manger(WEBSOCKET_PORT);
            WebSocketManager.ClientConnect += HandleClientConnect;
            WebSocketManager.ClientDisconnect += HandleClientDisconnect;
            WebSocketManager.ClientMessage += HandleClientMessage;

            Controller.DeviceDiscovery += HandleDeviceDiscovery;
        }
Example #4
0
  void FireRay() {
    Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
    RaycastHit hit;

    if (Physics.Raycast(ray, out hit)) {
      GameObject collidedDevice = hit.collider.gameObject;

      if (collidedDevice.CompareTag("Device")) {

        Instantiate(particle, collidedDevice.transform.position, collidedDevice.transform.rotation);

        currentDevice.SetModel(true);
        currentDevice = collidedDevice.GetComponent<DeviceController>();
        if (currentDevice.IsFunctioning()) {
          GetComponent<AudioSource>().PlayOneShot(jumpFx);
          currentDevice.CyberJump(this);
        }
      }
    }
  }
        public void Launch(string ignored)
        {
            var result = DeviceController.Start(CurrentApplicationDefinition);

            Console.WriteLine("launch:" + result);
        }
        public void Stop(string ignored)
        {
            var result = DeviceController.Stop(CurrentApplicationDefinition);

            Console.WriteLine("stop:" + result);
        }
Example #7
0
        private string setDeviceCommand(ref string result, ref string device, ref string cmd, ref DeviceController deviceCtrl)
        {
            try
            {
                if (getAtlCmd(ref result, ref device, ref cmd, ref deviceCtrl))
                {
                    DeviceController tempdeviceCtrl = null;
                    tempdeviceCtrl = deviceCtrl;

                    SpinWait.SpinUntil(() => (tempdeviceCtrl.processState == DeviceController.PROCESS_STATE_IDLE) ||
                                       (tempdeviceCtrl.processState == DeviceController.PROCESS_STATE_ERROR), 10000);


                    deviceCtrl.errorCode    = "";
                    deviceCtrl.processState = DeviceController.PROCESS_STATE_PROCESS;
                    deviceCtrl.sendCommand(cmd);

                    result = deviceCtrl.errorCode;
                    //if (deviceCtrl.processState == DeviceController.PROCESS_STATE_IDLE)
                    //{
                    //    deviceCtrl.errorCode = "";
                    //    deviceCtrl.processState = DeviceController.PROCESS_STATE_PROCESS;
                    //    deviceCtrl.sendCommand(cmd);

                    //    ////等待600秒
                    //    //SpinWait.SpinUntil(() => (tempdeviceCtrl.processState == DeviceController.PROCESS_STATE_IDLE)
                    //    //                            || (tempdeviceCtrl.processState == DeviceController.PROCESS_STATE_ERROR),
                    //    //                            600000);
                    //    //result = deviceCtrl.errorCode;
                    //}
                    //else
                    //{
                    //    result = device + " is " + deviceCtrl.processState + ".";
                    //}
                }
            }
            catch (Exception e)
            {
                logger.Error(e.StackTrace);
                result = e.StackTrace;
            }

            return(result);
        }
Example #8
0
 void HandleDeviceDiscovery(object sender, DeviceController.DeviceEventArgs e)
 {
     e.Device.PlaystateChanged += handlePlaystateChanged;
 }
 public void Initialize()
 {
     controller          = new DeviceController();
     databaseAdapterMock = new Mock <IDatabaseAdapter>();
 }
Example #10
0
        public void AddUser(User user, DeviceController device)
        {
            if (user == null || device == null)
            {
                return;
            }
            if (user.UserAuthentications == null || user.UserAuthentications.Count == 0)
            {
                return;
            }
            if (user.GetUserAccessableDeviceIds().Contains(device.DeviceID) == false)
            {
                return;
            }

            var deviceID   = device.DeviceID;
            var deviceCode = device.Code.ToInt32();

            Log.Info("Getting user authentication infos...");
            var userAuthenticationsOfDevice = user.UserAuthentications.Where(a => a.DeviceID == deviceID);
            var authenticationsOfDevice     = userAuthenticationsOfDevice as IList <UserAuthentication> ?? userAuthenticationsOfDevice.ToList();

            Log.Info("Getting user permission infos...");
            var deviceRoles = _deviceRole.Query(new Hashtable {
                { "Status", (int)GeneralStatus.Enabled }
            }).ToList();
            var userDevicePermission = user.GetUserDeviceRoleAuthorizedPermissionByDeviceId(deviceID, deviceRoles);

            Log.Info("Building device user...");
            var deviceUser = new UserInfo();

            deviceUser.UserId           = user.UserCode.ToInt32();
            deviceUser.ExternalUserCode = user.UserID.ToString();
            // user info
            deviceUser.UserName     = user.Name;
            deviceUser.UserStatus   = user.Status == GeneralStatus.Enabled;
            deviceUser.DepartmentId = user.DepartmentID;
            deviceUser.Comment      = user.Remark;
            // user role
            deviceUser.Role             = (Rld.DeviceSystem.Contract.Model.UserRole)userDevicePermission.PermissionAction.GetHashCode();
            deviceUser.AccessTimeZoneId = userDevicePermission.AllowedAccessTimeZoneID;

            //user authentication
            foreach (var userAuthentication in authenticationsOfDevice)
            {
                switch (userAuthentication.AuthenticationType)
                {
                case AuthenticationType.FingerPrint1:
                case AuthenticationType.FingerPrint2:
                case AuthenticationType.FingerPrint3:
                case AuthenticationType.FingerPrint4:
                case AuthenticationType.FingerPrint5:
                case AuthenticationType.FingerPrint6:
                case AuthenticationType.FingerPrint7:
                case AuthenticationType.FingerPrint8:
                case AuthenticationType.FingerPrint9:
                case AuthenticationType.FingerPrint10:
                {
                    var service = new FingerPrintService()
                    {
                        Index = (int)userAuthentication.AuthenticationType, Enabled = true
                    };
                    service.FingerPrintData = userAuthentication.AuthenticationData;
                    service.UseForDuress    = userAuthentication.IsDuress;
                    deviceUser.CredentialServices.Add(service);
                }
                break;

                case AuthenticationType.Password:
                {
                    var service = new PasswordService()
                    {
                        Enabled = true
                    };
                    service.Password     = SimpleEncryption.Decode(userAuthentication.AuthenticationData);
                    service.UseForDuress = userAuthentication.IsDuress;
                    deviceUser.CredentialServices.Add(service);
                }
                break;

                case AuthenticationType.IcCard:
                {
                    var service = new CredentialCardService()
                    {
                        Enabled = true
                    };
                    service.CardNumber   = userAuthentication.AuthenticationData;
                    service.UseForDuress = userAuthentication.IsDuress;
                    deviceUser.CredentialServices.Add(service);
                }
                break;

                default:
                    break;
                }
            }

            Log.Info("Invoke WebSocketOperation...");
            var operation             = new WebSocketOperation(deviceCode);
            var createUserInfoRequest = new CreateUserInfoRequest()
            {
                Token = operation.Token, UserInfo = deviceUser
            };
            string rawRequest  = DataContractSerializationHelper.Serialize(createUserInfoRequest);
            var    rawResponse = operation.Execute(rawRequest);

            if (string.IsNullOrWhiteSpace(rawResponse))
            {
                throw new Exception(string.Format("Create user id:[{0}], device user id:[{1}] to device id:[{2}] fails. Response is empty, maybe the device is not register to device system.",
                                                  user.UserID, deviceUser.UserId, deviceID));
            }

            var response = DataContractSerializationHelper.Deserialize <CreateUserInfoResponse>(rawResponse);

            Log.InfoFormat("Create user id:[{0}], device user id:[{1}] to device id:[{2}], result:[{3}]", user.UserID, deviceUser.UserId, deviceID, response.ResultType);

            if (response.ResultType != ResultType.OK)
            {
                throw new Exception(string.Format("Create user id:[{0}], device user id:[{1}] to device id:[{2}] fails.", user.UserID, deviceUser.UserId, deviceID));
            }
        }
 public DeviceControllerTest()
 {
     _rabbitMock = new Mock <IRabbitMqAbstraction>();
     _mongoMock  = new Mock <IMongoDbDataAccess>();
     _controller = new DeviceController(_rabbitMock.Object, _mongoMock.Object);
 }
Example #12
0
 protected CharacteristicCommandBase(CharacteristicInfo characteristicInfo)
 {
     CharacteristicInfo = characteristicInfo;
     _deviceController  = IoC.Get <DeviceController>();
 }
Example #13
0
        protected override async Task <int> InvokeAsync(InvocationContext context, IStandardStreamWriter console, DeviceController device)
        {
            var kitNumber = context.ParseResult.ValueForOption <int>("kit");
            var file      = context.ParseResult.ValueForOption <string>("file");

            try
            {
                Stopwatch sw = Stopwatch.StartNew();
                // Allow up to 30 seconds in total.
                var token = new CancellationTokenSource(TimeSpan.FromSeconds(30)).Token;
                var kit   = await device.LoadKitAsync(kitNumber, null, token);

                console.WriteLine($"Finished loading in {(int) sw.Elapsed.TotalSeconds} seconds");
                using (var stream = File.Create(file))
                {
                    kit.Save(stream);
                }
                console.WriteLine($"Saved kit to {file}");
            }
            catch (OperationCanceledException)
            {
                console.WriteLine("Data loading from device was cancelled");
                return(1);
            }
            catch (Exception ex)
            {
                console.WriteLine($"Error loading data from device: {ex}");
                return(1);
            }
            return(0);
        }
Example #14
0
        public void UpdateUser(User systemUserInfo, UserInfo deviceUserInfo, DeviceController device)
        {
            if (systemUserInfo == null || device == null)
            {
                return;
            }

            systemUserInfo.Name   = GetDeviceUserName(deviceUserInfo);
            systemUserInfo.Remark = deviceUserInfo.Comment;
            UpdateUserDepartment(systemUserInfo, deviceUserInfo.DepartmentId);

            Log.Info("Getting user authentication infos...");
            var deviceID = device.DeviceID;
            var userAuthenticationsOfDevice = systemUserInfo.UserAuthentications.Where(a => a.DeviceID == deviceID);
            var authenticationsOfDevice     = userAuthenticationsOfDevice as IList <UserAuthentication> ?? userAuthenticationsOfDevice.ToList();
            var deviceUserId = systemUserInfo.UserCode.ToInt32();

            var userAuthenticationFromDevice = new List <UserAuthentication>();

            foreach (var service in deviceUserInfo.CredentialServices)
            {
                var userAuthentication = new UserAuthentication()
                {
                    UserID       = systemUserInfo.UserID,
                    DeviceID     = deviceID,
                    DeviceUserID = deviceUserId,
                    Status       = GeneralStatus.Enabled,
                    CreateDate   = DateTime.Now,
                    CreateUserID = GlobalSetting.DeviceSystemId,
                };

                if (service is PasswordService)
                {
                    var passwordService            = service as PasswordService;
                    var originalUserAuthentication = authenticationsOfDevice.FirstOrDefault(a => a.AuthenticationType == AuthenticationType.Password);
                    userAuthentication.UserAuthenticationID = originalUserAuthentication != null ? originalUserAuthentication.UserAuthenticationID : 0;
                    userAuthentication.AuthenticationType   = AuthenticationType.Password;
                    userAuthentication.AuthenticationData   = SimpleEncryption.Encode(passwordService.Password);
                    userAuthentication.IsDuress             = passwordService.UseForDuress;
                }
                else if (service is CredentialCardService)
                {
                    var credentialCardService      = service as CredentialCardService;
                    var originalUserAuthentication = authenticationsOfDevice.FirstOrDefault(a => a.AuthenticationType == AuthenticationType.IcCard);
                    userAuthentication.UserAuthenticationID = originalUserAuthentication != null ? originalUserAuthentication.UserAuthenticationID : 0;
                    userAuthentication.AuthenticationType   = AuthenticationType.IcCard;
                    userAuthentication.AuthenticationData   = credentialCardService.CardNumber;
                    userAuthentication.IsDuress             = credentialCardService.UseForDuress;
                }
                else if (service is FingerPrintService)
                {
                    var fpService = service as FingerPrintService;
                    var originalUserAuthentication = authenticationsOfDevice.FirstOrDefault(a => a.AuthenticationType.GetHashCode() == fpService.Index);
                    userAuthentication.UserAuthenticationID = originalUserAuthentication != null ? originalUserAuthentication.UserAuthenticationID : 0;
                    userAuthentication.AuthenticationType   = (AuthenticationType)fpService.Index;
                    userAuthentication.AuthenticationData   = fpService.FingerPrintData;
                    userAuthentication.IsDuress             = fpService.UseForDuress;
                }

                userAuthenticationFromDevice.Add(userAuthentication);
            }

            Log.Info("Sync user to database...");
            var addedAuthentications     = new List <UserAuthentication>();
            var deletedAuthenticationIds = new List <int>();

            if (userAuthenticationFromDevice.Any())
            {
                var originalUserAuthenticationIDs = systemUserInfo.UserAuthentications.Select(d => d.UserAuthenticationID);
                var UserAuthenticationIDs         = userAuthenticationFromDevice.Select(d => d.UserAuthenticationID);
                deletedAuthenticationIds = originalUserAuthenticationIDs.Except(UserAuthenticationIDs).ToList();

                addedAuthentications = userAuthenticationFromDevice.FindAll(d => d.UserAuthenticationID == 0);
            }
            else
            {
                deletedAuthenticationIds = systemUserInfo.UserAuthentications.Select(d => d.UserAuthenticationID).ToList();
            }

            userAuthenticationFromDevice.FindAll(d => d.UserAuthenticationID != 0).ForEach(d =>
            {
                var auth = systemUserInfo.UserAuthentications.First(x => x.UserAuthenticationID == d.UserAuthenticationID);
                auth.AuthenticationData = d.AuthenticationData;

                _userAuthenticationRepo.Update(auth);
                Log.InfoFormat("User authentication id={0} updated", d.UserAuthenticationID);
            });
            deletedAuthenticationIds.ForEach(d =>
            {
                _userAuthenticationRepo.Delete(d);
                Log.InfoFormat("User authentication id={0} deleted", d);
            });
            addedAuthentications.ForEach(d =>
            {
                var auth = _userAuthenticationRepo.Insert(d);
                Log.InfoFormat("User authentication id={0} inserted", auth.UserAuthenticationID);
            });

            _userRepo.Update(systemUserInfo);

            _userEventRepo.Insert(new UserEvent()
            {
                EventType    = UserEventType.Modify,
                UserID       = systemUserInfo.UserID,
                CreateDate   = DateTime.Now,
                CreateUserID = GlobalSetting.DeviceSystemId,
                IsFinished   = true,
                EventData    = "Sync system user operation",
            });
        }
Example #15
0
        public void AddUser(User systemUserInfo, UserInfo deviceUserInfo, DeviceController device)
        {
            var deviceID     = device.DeviceID;
            var deviceUserId = systemUserInfo.UserCode.ToInt32();

            systemUserInfo.Photo     = "avator.jpg";
            systemUserInfo.Type      = UserType.Employee;
            systemUserInfo.UserCode  = systemUserInfo.UserCode;
            systemUserInfo.Gender    = GenderType.Male;
            systemUserInfo.Phone     = "";
            systemUserInfo.Status    = GeneralStatus.Enabled;
            systemUserInfo.StartDate = DateTime.Now;
            systemUserInfo.EndDate   = null;

            systemUserInfo.UserPropertyInfo.LastName        = null;
            systemUserInfo.UserPropertyInfo.FirstName       = null;
            systemUserInfo.UserPropertyInfo.Nationality     = 0;
            systemUserInfo.UserPropertyInfo.NativePlace     = null;
            systemUserInfo.UserPropertyInfo.Birthday        = new DateTime(2000, 1, 1);
            systemUserInfo.UserPropertyInfo.Marriage        = Marriage.Single;
            systemUserInfo.UserPropertyInfo.PoliticalStatus = null;
            systemUserInfo.UserPropertyInfo.Degree          = null;
            systemUserInfo.UserPropertyInfo.HomeNumber      = "";
            systemUserInfo.UserPropertyInfo.EnglishName     = "";
            systemUserInfo.UserPropertyInfo.Company         = "";
            systemUserInfo.UserPropertyInfo.TechnicalTitle  = "";
            systemUserInfo.UserPropertyInfo.TechnicalLevel  = "";
            systemUserInfo.UserPropertyInfo.IDType          = (int)IDType.ID;
            systemUserInfo.UserPropertyInfo.IDNumber        = "";
            systemUserInfo.UserPropertyInfo.SocialNumber    = "";
            systemUserInfo.UserPropertyInfo.Email           = "";
            systemUserInfo.UserPropertyInfo.Address         = "";
            systemUserInfo.UserPropertyInfo.Postcode        = "";
            systemUserInfo.UserPropertyInfo.Remark          = "";

            systemUserInfo.Name   = GetDeviceUserName(deviceUserInfo);
            systemUserInfo.Remark = deviceUserInfo.Comment;
            UpdateUserDepartment(systemUserInfo, deviceUserInfo.DepartmentId);

            foreach (var service in deviceUserInfo.CredentialServices)
            {
                var userAuthentication = new UserAuthentication()
                {
                    UserID       = systemUserInfo.UserID,
                    DeviceID     = deviceID,
                    DeviceUserID = deviceUserId,
                    Status       = GeneralStatus.Enabled,
                    CreateDate   = DateTime.Now,
                    CreateUserID = GlobalSetting.DeviceSystemId,
                };

                if (service is PasswordService)
                {
                    var passwordService = service as PasswordService;
                    userAuthentication.AuthenticationType = AuthenticationType.Password;
                    userAuthentication.AuthenticationData = SimpleEncryption.Encode(passwordService.Password);
                    userAuthentication.IsDuress           = passwordService.UseForDuress;
                }
                else if (service is CredentialCardService)
                {
                    var credentialCardService = service as CredentialCardService;
                    userAuthentication.AuthenticationType = AuthenticationType.IcCard;
                    userAuthentication.AuthenticationData = credentialCardService.CardNumber;
                    userAuthentication.IsDuress           = credentialCardService.UseForDuress;
                }
                else if (service is FingerPrintService)
                {
                    var fpService = service as FingerPrintService;
                    userAuthentication.AuthenticationType = (AuthenticationType)fpService.Index;
                    userAuthentication.AuthenticationData = fpService.FingerPrintData;
                    userAuthentication.IsDuress           = fpService.UseForDuress;
                }

                systemUserInfo.UserAuthentications.Add(userAuthentication);
            }

            var userAuthenticationRepo = RepositoryManager.GetRepository <IUserAuthenticationRepository>();
            var userPropertyRepo       = RepositoryManager.GetRepository <IUserPropertyRepository>();
            var userRepo      = RepositoryManager.GetRepository <IUserRepository>();
            var userEventRepo = RepositoryManager.GetRepository <IUserEventRepository>();

            Log.Info("Sync user to database...");
            userPropertyRepo.Insert(systemUserInfo.UserPropertyInfo);
            userRepo.Insert(systemUserInfo);

            EncodePassword(systemUserInfo);
            systemUserInfo.UserAuthentications.ForEach(a => a.UserID = systemUserInfo.UserID);
            systemUserInfo.UserAuthentications.ForEach(a => userAuthenticationRepo.Insert(a));

            userEventRepo.Insert(new UserEvent()
            {
                EventType    = UserEventType.Add,
                UserID       = systemUserInfo.UserID,
                CreateDate   = DateTime.Now,
                CreateUserID = GlobalSetting.DeviceSystemId,
                IsFinished   = true,
                EventData    = "Add user by sync system user operation",
            });
        }
Example #16
0
 void Device_VolumeChanged(object sender, DeviceController.DeviceVolumeEventArgs e)
 {
     DeviceState _playState = new DeviceState();
     _playState.volumeMaster = e.Volume.ToString();
     SendMessageAll(new Protocol.DeviceStateNotification(_playState));
 }
        public IEnumerable <Models.Resulter> GetResponse(string request)
        {
            ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;

            Models.Resulter resulter = new Models.Resulter();

            stringRequest = request;


            Devider devider = new Devider();

            string request_type = devider.RequestDevider(request);



            if (request_type.Equals("wiki"))
            {
                //StringAnalysis stringanalysis = new StringAnalysis();
                SearchInfo searchinfo = new SearchInfo();


                System.Diagnostics.Debug.WriteLine("Yes:");
                string keyworld = searchinfo.SimplifyStringForWiki(request);
                keyworld_wiki = keyworld;

                System.Diagnostics.Debug.WriteLine("|" + keyworld + "|");

                List <string> lstKeyworld = new List <string>();
                lstKeyworld = searchinfo.SeparateString(keyworld_wiki);

                string[] keyworld_cut = keyworld.Split(' ');
                if (keyworld_cut.Length == 2)
                {
                    SearchInfo searchInfo = new SearchInfo();

                    string str_contend = searchInfo.GetWikiInfomationsUrl("https://vi.m.wikipedia.org/w/api.php?action=opensearch&search=" + keyworld + "&limit=1&format=xml");
                    resulter.Contend = str_contend;
                    System.Diagnostics.Debug.WriteLine("Có Ket Qua 0: " + str_contend);
                    resulter.Type  = "Wiki";
                    resulter.Title = "None";
                    resulter.Timer = "None";
                }

                for (int i = 0; i < lstKeyworld.Count; i++)
                {
                    System.Diagnostics.Debug.WriteLine("List Key: " + lstKeyworld[i]);

                    //https://vi.m.wikipedia.org/w/api.php?action=opensearch&search=ngọc trinh&limit=1&format=xml
                    SearchInfo searchInfo = new SearchInfo();
                    System.Diagnostics.Debug.WriteLine("world: " + lstKeyworld[i]);
                    string str_contend = searchInfo.GetWikiInfomationsUrl("https://vi.m.wikipedia.org/w/api.php?action=opensearch&search=" + lstKeyworld[i] + "&limit=1&format=xml");
                    if (str_contend.Equals("không có kết quả"))
                    {
                        resulter.Contend = "không tìm thấy kết quả";
                        resulter.Type    = "None";
                        resulter.Title   = "None";
                        resulter.Timer   = "None";
                    }

                    if (!str_contend.Equals("không có kết quả"))
                    {
                        resulter.Contend = str_contend;
                        System.Diagnostics.Debug.WriteLine("Có Ket Qua: " + str_contend);
                        resulter.Type  = "Wiki";
                        resulter.Title = "None";
                        resulter.Timer = "None";
                        break;
                    }
                }
            }

            if (request_type.Equals("weather"))
            {
                Weather weather = new Weather();
                resulter.Contend = weather.getWeatherResponse(request);
                resulter.Timer   = "None";
                resulter.Title   = "None";
                resulter.Type    = "Weather";
            }


            if (request_type.Equals("media"))
            {
                MediaPlayer media = new MediaPlayer();


                string title = media.SimplifyStringForMedia(request);

                System.Diagnostics.Debug.WriteLine("Media:" + title);

                media.getLinkMedia(title);

                resulter.Contend = media.getLinkMedia(title);
                resulter.Timer   = "None";
                resulter.Title   = title;
                resulter.Type    = "Media";
            }

            if (request_type.Equals("reminder"))
            {
                Reminder reminder = new Reminder();

                // System.Diagnostics.Debug.WriteLine(reminder.getTimer("tôi muốn đặt lịch hẹn đi ăn nhậu vào thứ 5 tuần này lúc 6 giờ kém 20 tối"));

                //System.Diagnostics.Debug.WriteLine("API Contend: "+ reminder.getContend());


                resulter.Timer   = reminder.getTimer(request);
                resulter.Contend = reminder.getContend();
                resulter.Title   = "None";
                resulter.Type    = "Reminder";
            }


            if (request_type.Equals("controller"))
            {
                DeviceController device = new DeviceController();

                resulter.Contend = device.getDeviceName(request);
                resulter.Type    = "Controller";
                resulter.Title   = device.getCommandType(request);
                resulter.Timer   = "None";
            }

            if (request_type.Equals("none"))
            {
                resulter.Contend = "không thể thực hiện yêu cầu";
                resulter.Type    = "None";
                resulter.Title   = "None";
                resulter.Timer   = "None";
            }


            yield return(resulter);
        }
Example #18
0
 public GetAlarmConfigurationQueryHandler(
     DeviceController deviceController)
 {
     _deviceController = deviceController;
 }
 //button grid
 private void btn_add_Click(object sender, EventArgs e)
 {
     DeviceController.NewDevice();
     EnableDeviceButtons();
 }
 private void btn_tools_Click(object sender, EventArgs e)
 {
     DeviceController.ShowConfigurationDevice();
 }
 public DisarmCommandHandler(
     DeviceController deviceController)
 {
     _deviceController = deviceController;
 }
 private void btn_save_Click(object sender, EventArgs e)
 {
     DeviceController.SaveDevice();
 }
        private void InitializeComponents()
        {
            DeviceController = new DeviceController();

            _view              = new QuickviewForm(this);
            _view.FormClosing += _view_FormClosing;

            SettingsForm = new SettingsForm(this);

            TrayIconMenuStrip        = new ContextMenuStrip();
            ContextMenuStripOpen     = new ToolStripMenuItem();
            ContextMenuStripSettings = new ToolStripMenuItem();
            ContextMenuStripClose    = new ToolStripMenuItem();
            TrayIcon         = new NotifyIcon();
            UpdateController = new UpdateController();
            UpdateController.UpdateAvailable   += UpdateController_UpdateAvailable;
            UpdateController.InstallAvailable  += _updateController_InstallAvailable;
            UpdateController.UpdateFailure     += _updateController_UpdateFailure;
            UpdateController.NoUpdateAvailable += _updateController_NoUpdateAvailable;

            //
            // ContextMenuStripOpen
            //
            ContextMenuStripOpen.Name   = "ContextMenuStripOpen";
            ContextMenuStripOpen.Text   = "Open";
            ContextMenuStripOpen.Click += ContextMenuStripOpen_Click;
            //
            // ContextMenuStripSettings
            //
            ContextMenuStripSettings.Name   = "ContextMenuStripSettings";
            ContextMenuStripSettings.Text   = "Settings";
            ContextMenuStripSettings.Click += ContextMenuStripSettings_Click;;
            //
            // ContextMenuStripClose
            //
            ContextMenuStripClose.Name   = "ToolStripMenuItemClose";
            ContextMenuStripClose.Text   = "Exit Playback Changer";
            ContextMenuStripClose.Click += ContextMenuStripClose_Click;
            //
            // TrayIconMenuStrip
            //
            TrayIconMenuStrip.Items.AddRange(new ToolStripItem[] {
                ContextMenuStripOpen,
                ContextMenuStripSettings,
                ContextMenuStripClose
            });
            TrayIconMenuStrip.Name = "TrayIconMenuStrip";
            //
            // TrayIcon
            //
            TrayIcon.Text        = "Playback Changer";
            TrayIcon.Icon        = Properties.Resources.icon;
            TrayIcon.MouseClick += _notifyIcon_MouseClick;

            TrayIcon.ContextMenuStrip = TrayIconMenuStrip;

            _keyboardHook                = new KeyboardHook();
            _keyboardHook.Activated     += _keyboardHook_Activated;
            _keyboardHook.HotkeyPressed += _keyboardHook_HotkeyPressed;

            this.ThreadExit += PlaybackChangerContext_ThreadExit;
        }
 private void btn_remove_Click(object sender, EventArgs e)
 {
     DeviceController.RemoveDevice();
     EnableDeviceButtons();
 }
Example #25
0
        protected override async Task <int> InvokeAsync(InvocationContext context, IStandardStreamWriter console, DeviceController device)
        {
            var schema = device.Schema;

            for (int i = 1; i <= schema.Kits; i++)
            {
                var name = await device.LoadKitNameAsync(i, CancellationToken.None);

                console.WriteLine($"Kit {i}: {name}");
            }
            return(0);
        }
 private void tool_strip_configure_Click(object sender, EventArgs e)
 {
     DeviceController.ShowConfigurationDevice();
 }
        public void ForceUninstall(string ignored)
        {
            var result = DeviceController.ForceUninstall(CurrentApplicationDefinition);

            Console.WriteLine("forceUninstall:" + result);
        }
 private void video_interval_Tick(object sender, EventArgs e)
 {
     DeviceController.DividerVideo();
 }
        protected override async Task <int> InvokeAsync(InvocationContext context, IStandardStreamWriter console, DeviceController device)
        {
            var  path      = context.ParseResult.ValueForOption <string>("path");
            bool interpret = context.ParseResult.ValueForOption <bool>("interpret");
            var  root      = device.Schema.LogicalRoot.ResolveNode(path);

            var container = (FieldContainer)root.Container;
            var segment   = await device.LoadSegment(container.Address, container.Size, default);

            foreach (var field in container.Fields)
            {
                var bytes = new byte[field.Size];
                segment.ReadBytes(field.Offset, bytes.AsSpan());
                if (field is OverlayField overlay)
                {
                    var sizePerNestedField = field.Size / overlay.NestedFieldCount;
                    for (int i = 0; i < overlay.NestedFieldCount; i++)
                    {
                        string description = $"{field.Description} {i + 1}";
                        var    nestedBytes = bytes[(i * sizePerNestedField)..((i + 1) * sizePerNestedField)];
Example #30
0
        private void cboDevices_SelectedIndexChanged(object sender, EventArgs e)
        {
            try
            {
                int selectedDeviceID = (int)cboDevices.SelectedValue;
                if (selectedDeviceID == 0)
                {
                    btnOff.Enabled = false;
                    btnOn.Enabled  = false;
                }
                else
                {
                    btnOff.Enabled = true;
                    btnOn.Enabled  = true;
                }

                List <GetDeviceByRoomIdAndDeviceID_Result> lstDeviceByRoomIdAndDeviceId = DeviceController.GetDeviceByRoomIdAndDeviceId(roomId, selectedDeviceID);
                List <DevicesDTO> retVal = new List <DevicesDTO>();
                foreach (GetDeviceByRoomIdAndDeviceID_Result reg in lstDeviceByRoomIdAndDeviceId)
                {
                    retVal.Add(new DevicesDTO(reg));
                }

                if (selectedDeviceID == 3)
                {
                    btnOff.Enabled   = false;
                    btnOn.Enabled    = false;
                    lblTemp.Text     = retVal[0].Value.ToString();
                    lblUnitTemp.Text = retVal[0].Unit.ToString();
                }
                else
                {
                    lblTemp.Text     = retVal[0].Value.ToString();
                    lblUnitTemp.Text = retVal[0].Unit.ToString();
                }


                pctDeviceStateOff.Visible = true;
                pctDeviceStateOn.Visible  = false;
                btnOff.Visible            = false;
                btnOn.Visible             = true;

                if (retVal[0].State == false)
                {
                    pctDeviceStateOff.Visible = true;
                    pctDeviceStateOn.Visible  = false;
                    btnOff.Visible            = false;
                    btnOn.Visible             = true;
                }
                else
                {
                    pctDeviceStateOff.Visible = false;
                    pctDeviceStateOn.Visible  = true;
                    btnOff.Visible            = true;
                    btnOn.Visible             = false;
                }
            }
            catch (Exception ex)
            {
            }
        }
Example #31
0
 void Device_MuteChanged(object sender, DeviceController.DeviceMuteEventArgs e)
 {
     DeviceState _playState = new DeviceState();
     _playState.muteActive = (e.MuteState == DeviceController.DeviceMuteEventArgs.MuteStates.Muted) ? "true" : "false";
     SendMessageAll(new Protocol.DeviceStateNotification(_playState));
 }
        protected override async Task <int> InvokeAsync(InvocationContext context, IStandardStreamWriter console, DeviceController device)
        {
            var kit                   = context.ParseResult.ValueForOption <int>("kit");
            var file                  = context.ParseResult.ValueForOption <string>("file");
            var triggerRoot           = device.Schema.GetTriggerRoot(kit, trigger: 1);
            var deviceData            = ModuleData.FromLogicalRootNode(triggerRoot);
            var modelData             = ModuleData.FromLogicalRootNode(triggerRoot);
            var defaultValuesSnapshot = modelData.CreateSnapshot();

            var deviceDataRoot = new DataTreeNode(deviceData, triggerRoot);
            await device.LoadDescendants(deviceDataRoot, targetAddress : null, progressHandler : null, CancellationToken.None);

            var originalSnapshot = deviceData.CreateSnapshot();

            var(ifContainer, instrumentField) = device.Schema.GetMainInstrumentField(kit, trigger: 1);
            var modelInstrumentField = (InstrumentDataField)modelData.GetDataField(ifContainer, instrumentField);

            var instrumentContainers = triggerRoot.DescendantFieldContainers();

            var differences = new List <Difference>();

            try
            {
                // Reset the device to an empty snapshot
                deviceData.LoadSnapshot(defaultValuesSnapshot);
                await device.SaveDescendants(deviceDataRoot, targetAddress : null, progressHandler : null, CancellationToken.None);

                foreach (var instrument in device.Schema.PresetInstruments)
                {
                    // Make the change on the real module and load the data.
                    // Assumption: the segment containing the instrument itself (e.g. KitPadInst) doesn't
                    // have any implicit model changes to worry about.
                    await device.SetInstrumentAsync(kit, trigger : 1, instrument, CancellationToken.None);

                    await device.LoadDescendants(deviceDataRoot, targetAddress : null, progressHandler : null, CancellationToken.None);

                    // Make the change in the model.
                    modelData.LoadSnapshot(defaultValuesSnapshot);
                    modelInstrumentField.Instrument = instrument;

                    // Compare the two.
                    bool anyDifferences = false;
                    foreach (var container in instrumentContainers)
                    {
                        // We won't compare InstrumentDataField, TempoDataField or StringDataField this way, but that's okay.
                        var realFields  = deviceData.GetDataFields(container).SelectMany(ExpandOverlays).OfType <NumericDataFieldBase>().ToList();
                        var modelFields = modelData.GetDataFields(container).SelectMany(ExpandOverlays).OfType <NumericDataFieldBase>().ToList();
                        if (realFields.Count != modelFields.Count)
                        {
                            console.WriteLine($"Major failure: for instrument {instrument.Id} ({instrument.Group} / {instrument.Name}), found {realFields.Count} real fields and {modelFields.Count} model fields in container {container.Path}");
                            return(1);
                        }

                        foreach (var pair in realFields.Zip(modelFields))
                        {
                            var real  = pair.First;
                            var model = pair.Second;
                            if (real.SchemaField != model.SchemaField)
                            {
                                console.WriteLine($"Major failure: for instrument {instrument.Id} ({instrument.Group} / {instrument.Name}), mismatched schema field for {container.Path}: {real.SchemaField.Name} != {model.SchemaField.Name}");
                                return(1);
                            }
                            var realValue      = real.RawValue;
                            var predictedValue = model.RawValue;
                            if (realValue != predictedValue)
                            {
                                anyDifferences = true;
                                differences.Add(new Difference(instrument, container, real.SchemaField, realValue, predictedValue));
                            }
                        }
                    }
                    console.Write(anyDifferences ? "!" : ".");
                }
            }
            finally
            {
                // Restore the original data
                deviceData.LoadSnapshot(originalSnapshot);
                await device.SaveDescendants(deviceDataRoot, targetAddress : null, progressHandler : null, CancellationToken.None);
            }
            console.WriteLine();
            foreach (var difference in differences)
            {
                console.WriteLine(difference.ToString());
            }
            console.WriteLine($"Total differences: {differences.Count}");
            return(0);

            IEnumerable <IDataField> ExpandOverlays(IDataField field) =>
            field is OverlayDataField odf ? odf.CurrentFieldList.Fields : Enumerable.Repeat(field, 1);
        }
Example #33
0
 public void Dispose()
 {
     DeviceController.Dispose();
 }
 public GetAlarmStateQueryHandler(
     DeviceController deviceController)
 {
     _deviceController = deviceController;
 }
Example #35
0
 public bool IsCurrentDevice(DeviceController otherController)
 {
     return(currentDevice == otherController);
 }
Example #36
0
 public ReadTagCommandHandler(DeviceController deviceController)
 {
     _deviceController = deviceController;
 }
Example #37
0
        protected DeviceController ConnectTo(IReceivesColor device, params Tuple<DataElements, object>[] additionalData)
        {
            lock (this.lockObject)
            {
                IData data = null;
                if (additionalData.Any())
                {
                    data = new Data();
                    foreach (var kvp in additionalData)
                        data[kvp.Item1] = kvp.Item2;
                }

                var deviceController = new DeviceController(device, data);
                this.devices.Add(deviceController);

                return deviceController;
            }
        }
Example #38
0
        /// <summary>
        /// Glowne okno zaladowane
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void MainWindow_OnLoaded(object sender, RoutedEventArgs e)
        {
            // [1] - Check License
            if (!isLicenseFilePresent)
            {
                TextBox_StatusBar_Bottom.Text = "No license present";
            }
            else
            {
                try
                {
                    lcm.LoadLicenseDetails();
                    TextBox_StatusBar_Bottom.Text = String.Format("Registered to {0} {1}", lcm.GetByKeyName("FirstName"),
                                                                  lcm.GetByKeyName("LastName"));
                }
                catch
                {
                    // ignored
                }
            }


            // [3] - Load profile
            ApplicationProfile = AppProfileManager.Load_ApplicationProfile();      // Try to load the profile if does not exists
            // [3a] - See if we should be minimized
            if (ApplicationProfile.Autostart)
            {
                this.WindowState = WindowState.Minimized;                               // This starts minimized app if we choosed to AutoStart application
            }
            // [3b] - Assign proper value to brightness slider
            Slider_Brightness.Value = ApplicationProfile.ChannelSettings.Brightness;
            // [4] - Configure COM communications
            serialDeviceController = ApplicationProfile.LastCOMconnected == "" ? new DeviceController(ApplicationProfile.BaudRate) : new DeviceController(ApplicationProfile.BaudRate, ApplicationProfile.LastCOMconnected);
            // [4a] - Subscribe to event
            serialDeviceController.OnCOMdisconnected += (o, args) =>
            {
                Application.Current.Dispatcher.BeginInvoke(DispatcherPriority.Normal, new Action(() =>
                {
                    ToggleButton_Start.Content = "Start";                      // Zmieniamy napis na guziku
                    isRGBdataAqquireRunning    = false;                        // Zmieniamy status naszej flagi
                    Stop_Data_Aqquire          = true;                         // Zmieniamy flage aby Ambi nie wysylalo danych

                    TextBlock_StatusBar_1.Text = " Disconnected";
                }));
            };

            // [5] - Ustaw podstawowe ustawienia
            channelsManagement = new ChannelsManagement(ApplicationProfile.ChannelSettings, (int)SystemParameters.PrimaryScreenHeight, (int)SystemParameters.PrimaryScreenWidth);    // Ustawienia
            // [6] - Konfiguracja TASKa dla chwytania danych z ekranu
            #region Task - lapanie danych
            tsk_RGBdata = new Task(() =>
            {
                while (true)
                {
                    if (!(Stop_Data_Aqquire))
                    {
                        if (serialDeviceController.DeviceConnected)
                        {
                            // Funkcje sluzace do zlapania ekranu
                            Surface s = rgbManagement.CaptureScreen(
                                (int)SystemParameters.PrimaryScreenWidth,
                                (int)SystemParameters.PrimaryScreenHeight
                                );
                            DataRectangle dr = s.LockRectangle(LockFlags.None);
                            DataStream gs    = dr.Data;

                            foreach (LightChannel channel in channelsManagement.LightChannels)
                            {
                                //TODO: Sprawdzamy brightness
                                //rgbManagement.AverageScreenRGBfromChannel(gs, channel, channelsManagement.Pixel_Min_Treshold);

                                try
                                {
                                    rgbManagement.AverageScreen(gs, channel, channelsManagement.Pixel_Min_Treshold,
                                                                ApplicationProfile.ChannelSettings.Brightness);
                                }
                                catch
                                {
                                }
                                //TODO : Ta funkcja zostanie "fade out"

                                //if (channelsManagement.Average_Strong_Colors)
                                //{

                                //    //RgBcapture.AdjustAverageRGB(channel, channelsManagement.Average_Strong_Colors_Adjustment);
                                //}
                            }

                            serialDeviceController.Send_Data_To_Serial(new byte[1] {
                                0x01
                            });                                                                                                            // wypychamy dane na pasek

                            serialDeviceController.Send_Data_To_Serial(rgbManagement.CalculateRGBarray(channelsManagement.LightChannels)); // wypychamy dane na pasek

                            serialDeviceController.Send_Data_To_Serial(new byte[1] {
                                0x02
                            });                  // wypychamy dane na pasek

                            s.UnlockRectangle(); // <---------------------  UNLOCK !!!
                            s.Dispose();
                        }
                    }
                }
            });
            #endregion
            // [4b] - See if we must AutoRun our process :D
            if (ApplicationProfile.AutoRun)
            {
                ToggleButton_Start.IsEnabled = !ToggleButton_Start.IsEnabled;   // Toggle button state
                Action_Start();                                                 // Start Ambi
            }
            // [7] Tray configs
        }
Example #39
0
 public bool IsCurrentDevice(DeviceController otherController) {
   return currentDevice == otherController;
 }
Example #40
0
 internal void AddDeviceController(DeviceController.IController DeviceController)
 {
     DeviceController.DeviceDiscovery += HandleDeviceDiscovery;
 }