public void addDevice(int deviceID, DeviceInfo deviceInfo, DeviceType deviceType)
 {
     Debug.Log("addDevice("+deviceID+", "+deviceInfo+", "+deviceType+")");
     bool alreadyEquiped = (!_equipedDevices.Exists(device => device.getID() == deviceID));
     bool alreadyInventory = (!_inventoryDevices.Exists(device => device.getID() == deviceID));
     if(alreadyEquiped || alreadyInventory) {
         Vector3 localPosition;
         UnityEngine.Transform parent;
         List<DisplayedDevice> devices;
         int newDeviceId = deviceID;
         if(deviceType == DeviceType.Equiped) {
             parent = equipPanel.transform;
             devices = _equipedDevices;
             if(deviceID == 0) {
                 newDeviceId = devices.Count;
             }
             Debug.Log("addDevice("+newDeviceId+") in equipment");
         } else {
             parent = inventoryPanel.transform;
             devices = _inventoryDevices;
             Debug.Log("addDevice("+newDeviceId+") in inventory");
         }
         localPosition = getNewPosition(deviceType);
         DisplayedDevice newDevice = DisplayedDevice.Create (parent, localPosition, newDeviceId, deviceType, deviceInfo, this);
         devices.Add(newDevice);
         //let's add reaction to reaction engine
         //for each module of deviceInfo, add to reaction engine
         //deviceInfo._modules.ForEach( module => module.addToReactionEngine(celliaMediumID, reactionEngine));
     } else {
         Debug.Log("addDevice failed: alreadyEquiped="+alreadyEquiped+", alreadyInventory="+alreadyInventory);
     }
 }
Beispiel #2
0
		public extern static int clGetDeviceIDs (
			IntPtr platform,
			DeviceType device_type,
			uint num_entries,
			IntPtr[] devices,
			out uint num_devices
		);
 public HttpWiflyImpl(HttpImplementationClient.RequestReceivedDelegate requestReceived, int localPort, DeviceType deviceType, SPI.SPI_module spiModule, Cpu.Pin chipSelect)
 {
     m_requestReceived = requestReceived;
     LocalPort = localPort;
     this.m_spiModule = spiModule;
     this.m_chipSelect = chipSelect;
 }
Beispiel #4
0
 /// <summary>
 /// 定位模块或通道的命令
 /// </summary>
 /// <param name="deviceType">设备类型</param>
 /// <returns></returns>
 public Byte[] ControlModuleOrChannelLocateCommand(DeviceType deviceType = DeviceType.Module)
 {
     return GetDatagram(MessageId.ControlModuleOrChannelLocate,
         deviceType == DeviceType.Channel ?
         new Parameter(ParameterType.ChannelNo, ChannelNo) :
         new Parameter(ParameterType.None, 0X00));
 }
 public GraphicsDeviceInformation()
 {
     deviceType = DeviceType.Hardware;
     adapter = GraphicsAdapter.DefaultAdapter;
     presentationParameters = new PresentationParameters();
     presentationParameters.Clear();
 }
 internal DeviceAnnouncement(UpnpClient client, DeviceType type, string udn, IEnumerable<string> locations)
 {
     this.client = client;
     this.type = type;
     this.udn = udn;
     this.locations = locations;
 }
 public OutputRequirements(DeviceType devType, bool hardwareTnL, Version ps, Version vs)
 {
     this.devType = devType;
     this.hardwareTnL = hardwareTnL;
     this.ps = ps;
     this.vs = vs;
 }
Beispiel #8
0
        /// <summary>
        /// Write to Chassis Fru - (Important) note that this function enables write to any offset 
        /// Offset checks ensures that we are within permissible limits, but cannot enforce semantics within those limits
        /// Length checks validity of packet, however empty fields in packet are responsibility of writing function
        /// User level priority since this is not an internal call
        /// </summary>
        /// <param name="offset"></param>
        /// <param name="length"></param>
        /// <param name="packet"></param>
        /// <returns></returns>
        public CompletionCode WriteChassisFru(ushort offset, ushort length, 
            byte[] packet, DeviceType deviceType)
        {
            ChassisFruWriteResponse response = new ChassisFruWriteResponse();
            response.CompletionCode = (byte)CompletionCode.UnspecifiedError;

            try
            {
                response = (ChassisFruWriteResponse)this.SendReceive(deviceType,
                    this.DeviceId, new ChassisFruWriteRequest(offset, length, packet),
                 typeof(ChassisFruWriteResponse), (byte)PriorityLevel.User);
            }
            catch (Exception ex)
            {
                Tracer.WriteError(string.Format("ChassisFru.WriteChassisFru() Write had an exception with paramaters: Offset: {0} Length: {1} Packet: {2} DeviceType: {3} Exception: {4}",
                    offset, length, (packet == null ? "Null packet" : Ipmi.IpmiSharedFunc.ByteArrayToHexString(packet)), deviceType.ToString(), ex));
            }

            if (response.CompletionCode != (byte)CompletionCode.Success)
            {
                Tracer.WriteError("ChassisFru.WriteChassisFru() write failed with completion code {0:X}", response.CompletionCode);
            }

            return (CompletionCode)response.CompletionCode;
        }
 public static int CtlCode(DeviceType type, int function, DeviceControlMethod method, DeviceControlAccess access)
 {
     return ((int)type << 16) |
         ((int)access << 14) |
         (function << 2) |
         (int)method;
 }
Beispiel #10
0
        /// <summary>
        /// Initializes a new instance of the <see cref="Trame"/> class.
        /// </summary>
        /// <param name="dt">Dt.</param>
        public Trame(DeviceType dt)
        {
            last = Creator.GetNewInvalidSkeleton();
            currentType = dt;

            resetTimer = new Timer(1000);
            resetTimer.AutoReset = true;
            lastUpdate = DateTime.Now;

            resetTimer.Elapsed += (sender, args) =>
            {
                if ((dt == DeviceType.KINECT || dt == DeviceType.LEAP_MOTION_AND_KINECT) && !resetInProgress && (DateTime.Now - lastUpdate).TotalMilliseconds > 2000)
                {
                    resetInProgress = true;
                    // reset trame
                    UpdatedType();
                    currentDevice.Start();

                    resetInProgress = false;
                    lastUpdate = DateTime.Now;
                }
            };

            UpdatedType();
        }
Beispiel #11
0
        public HDPApp(DeviceType deviceType, IBlobCache cache)
        {
            RxApp.DefaultExceptionHandler = Observer.Create ((Exception e) => {
                System.Diagnostics.Debug.WriteLine(e.Message); 
                System.Diagnostics.Debug.WriteLine(e.StackTrace);
            });

            BlobCache.ApplicationName = "HDP";
            _cache = BlobCache.LocalMachine;

            JsonConvert.DefaultSettings = 
                () => new JsonSerializerSettings() { 
                ContractResolver = new CamelCasePropertyNamesContractResolver(),
                Converters = {new MediaTypeConverter(), new StringEnumConverter()}
            };

            _apiService = new ApiService (deviceType: deviceType);
            _newsService = new NewsService (_apiService);
            _eventsService = new EventsService (_apiService);
            _electionArticlesService = new ElectionArticlesService (_apiService);

            Locator.CurrentMutable.RegisterConstant (this, typeof(HDPApp));

            State = new AppState ();

            UserCity.Subscribe (city => {
                System.Diagnostics.Debug.WriteLine("Current city is: {0}", city); 
            });

            _repository = new ContentRepository (_newsService, _electionArticlesService, _eventsService, cache);

            ImplementCommands ();
        }
        public string RegisterDevice(int tenantID, string userID, string token, DeviceType type)
        {
            if (string.IsNullOrEmpty(token))
                throw new FaultException("empty device token");

            if (string.IsNullOrEmpty(userID))
                throw new FaultException("empty user id");

            var device = GetDeviceDao().GetAll(tenantID, userID).FirstOrDefault(x => x.Token == token);

            if (device == null)
            {
                _log.DebugFormat("register device ({0}, {1}, {2}, {3})", tenantID, userID, token, type);
                device = new Device
                    {
                        TenantID = tenantID,
                        UserID = userID,
                        Token = token,
                        Type = type
                    };

                GetDeviceDao().Save(device);
            }

            return device.RegistrationID;
        }
        // Using device type decideds which device object to initilise, this allows for dynamic object creation.
        public static DeviceBase GetDeviceObject(DeviceInformation deviceInfo, DeviceType type)
        {
            DeviceBase device = null;
            // Main switch statement to handle the creation of the device objects.
            switch (type)
            {
                case DeviceType.GenericAccess:
                    device = new GenericAccessDevice();
                    break;
                case DeviceType.HeartRate:
                    device = new HeartRateMonitorDevice();
                    break;
            }

            if (device == null)
            {
                // Display error if device does not have a value and return null.
                MessageHelper.DisplayBasicMessage(StringResources.InitialisationError);
                return device;
            }

            device.Initialise(deviceInfo.Id);

            return device;
        }
Beispiel #14
0
        internal void Deploy(DeviceType device)
        {
            if (m_xap == null)
            {
                throw new InvalidOperationException("Target application is not selected.");
            }

            var hookProvider = new HookProvider(
                m_view.GetLogMethodNames(),
                m_view.GetLogParameterValues(),
                m_view.GetLogReturnValues(),
                m_view.GetHooks()
                );

            PatchTask patchTask = new PatchTask(
                m_xap,
                hookProvider,
                device,
                AddOutputText,
                ResetButton
                );

            var context = TaskScheduler.FromCurrentSynchronizationContext();

            Task.Factory.StartNew(patchTask.Run)
                .ContinueWith(t =>
                {
                    if (t.IsFaulted)
                    {
                        HandleError(t.Exception.InnerException);
                    }
                },
                context
                );
        }
        //-------------------------------------------------------------------------------------
        /// <summary>
        /// Constructor
        /// </summary>
        /// <param name="device">ref NodeController</param>
        /// <param name="deviceType">type of device</param>
        public DeviceView(DeviceController device, DeviceType deviceType)
        {
            InitializeComponent();
            this.deviceController = device;

            BitmapImage bi3 = new BitmapImage();

            if (deviceType == DeviceType.dPc)
            {
                bi3.BeginInit();
                bi3.UriSource = new Uri("/GEditor;component/Resources/screen_zoom_in_ch.png", UriKind.Relative);
                bi3.EndInit();
            }
            else
            {
                if (deviceType == DeviceType.dSwitch)
                {
                    bi3.BeginInit();
                    bi3.UriSource = new Uri("/GEditor;component/Resources/switch_ch.png", UriKind.Relative);
                    bi3.EndInit();
                }
                else
                {
                    bi3.BeginInit();
                    bi3.UriSource = new Uri("/GEditor;component/Resources/password_ch.png", UriKind.Relative);
                    bi3.EndInit();
                }
            }
            this.point.Source = bi3;
            Canvas.SetZIndex(this, 2);
            this.point.Width = this.point.Height = radiusView;
        }
Beispiel #16
0
        public static Miner CreateMiner(DeviceType deviceType, string minerPath)
        {
            if (minerPath == MinerPaths.eqm && DeviceType.AMD != deviceType) {
                return new eqm();
            } else if (minerPath == MinerPaths.nheqminer) {
                return new nheqminer();
            } else if (
                ConfigManager.GeneralConfig.Use3rdPartyMiners == Use3rdPartyMiners.YES
                && minerPath == MinerPaths.ClaymoreZcashMiner && DeviceType.AMD == deviceType) {
                return new ClaymoreZcashMiner();
            } else if (minerPath == MinerPaths.ethminer && DeviceType.CPU != deviceType) {
                if (DeviceType.AMD == deviceType) {
                    return new MinerEtherumOCL();
                } else {
                    return new MinerEtherumCUDA();
                }
            } else if (minerPath.Contains("cpuminer") && DeviceType.CPU == deviceType) {
                return new cpuminer();
            } else if (minerPath.Contains("sgminer") && DeviceType.AMD == deviceType) {
                return new sgminer();
            } else if(minerPath.Contains("ccminer") && DeviceType.NVIDIA == deviceType) {
                return new ccminer();
            }

            return null;
        }
Beispiel #17
0
 public DeviceBase(AudioBase audio, VideoBase video)
 {
     _audio = audio;
     _video = video;
     _deviceType = DeviceType.NO_DEVICE;
     _name = "Plug in your Kinect";
 }
		public void CreateZonesFile(string inputFilename, string outputFilename, string guid, string userName, long userId, string completitionCode, DeviceType device, EngineVersion version)
		{
            FileStream inputStream = null;
            Cartridge cartridge;

            try
            {
                // Open Lua file
                inputStream = new FileStream(inputFilename, FileMode.Open);

                // Create input object for plain folders
                IInput input = new Folder(inputStream, inputFilename);

                // Check Lua file
                input.Check();

                // Load Lua code and extract all required data
                cartridge = input.Load();

                // Close input
                input = null;
            }
            finally
            {
                if (inputStream != null)
                {
                    inputStream.Close();
                    inputStream = null;
                }
            }

			// Create selected engine
			IEngine engine = Compiler.CreateEngine(device);

			// Convert Lua code and insert special code for this player
			cartridge = engine.ConvertCartridge(cartridge);
			userName = engine.ConvertString(userName);

			// ---------- Compile Lua code into binary chunk ----------

			// Compile Lua code
			cartridge.Chunk = LUA.Compile(cartridge.LuaCode, cartridge.LuaFileName);

			// ---------- Save cartridge as GWC file ----------

			// Create object for output format (could be also WFC or any other IOutput)
			var outputFormat = new GWC();

			// Write output file
			// Create output in correct format
			var ms = outputFormat.Create(cartridge, userName, userId, completitionCode);
			// Save output to file
			using(FileStream ofs = new FileStream(outputFilename, FileMode.Create)) {
				ms.CopyTo(ofs);
				// Close output
				ofs.Flush();
				ofs.Close();
			}
		}
Beispiel #19
0
 public Device(string name, string hostname, DeviceType type, TimeSpan refreshInterval, int portNumber)
 {
     _name = name;
     _hostname = hostname;
     _type = type;
     _refreshInterval = refreshInterval;
     _portNumber = portNumber;
 }
 public static ContextHandle CreateContextFromType(ContextProperty[] properties,
                                             DeviceType deviceType,
                                             ContextNotify pfnNotify,
                                             IntPtr userData,
                                             out OpenCLErrorCode errcodeRet)
 {
     return new ContextHandle(clCreateContextFromType(properties, deviceType, pfnNotify, userData, out errcodeRet));
 }
Beispiel #21
0
 public DeviceBase(AudioBase audio, VideoBase video, KinectSensor sensor_xbox360)
 {
     _audio = audio;
     _video = video;
     sensor = sensor_xbox360;
     _deviceType = DeviceType.KINECT_1;
     _name = "K360-" + sensor.UniqueKinectId;
 }
Beispiel #22
0
        public Fan(byte deviceId)
        {
            // set the type as Fan
            this.deviceType = DeviceType.Fan;

            // set the device Id
            this.deviceId = deviceId;
        }
Beispiel #23
0
 public Icon(DeviceType deviceType, float width, float height, int scale, string xcodefile)
 {
     this.deviceType = deviceType;
     this.width = width;
     this.height = height;
     this.scale = scale;
     this.xcodefile = xcodefile;
 }
Beispiel #24
0
 public Device(DeviceType type, string id, USB2LCD.VersionInfo version)
 {
     this.type = type;
     this.id = id;
     this.serialnum = version.serialnumber;
     this.module = version.module;
     this.version = version.version;
 }
 public MinerEtherum(DeviceType deviceType, string minerDeviceName, string blockString)
     : base(deviceType, minerDeviceName)
 {
     Path = Ethereum.EtherMinerPath;
     _isEthMinerExit = true;
     CurrentBlockString = blockString;
     DagGenerationType = ConfigManager.Instance.GeneralConfig.EthminerDagGenerationType;
 }
 public AntiAliasCaps(int adapter, DeviceType devType, Format format)
 {
     availableTypes = new List<MultiSampleType>();
     for (int i = 0; i <= 16; i++)
     {
         CheckMultiSampleType(adapter, (MultiSampleType)i, devType, format);
     }
 }
 public Device(Room room, int devicenum, string deviceName, DeviceType deviceType, State state)
 {
     this.room = room;
     this.devicenum = devicenum;
     this.deviceName = deviceName;
     this.deviceType = deviceType;
     this.state = state;
 }
 /// <summary>
 /// Get ID's of the Devices
 /// </summary>
 /// <returns></returns>
 public static OpenCLErrorCode GetDeviceIDs(PlatformHandle platform,
                                      DeviceType deviceType,
                                      uint numEntries,
                                      DeviceHandle[] devices,
                                      out uint numDevices)
 {
     return clGetDeviceIDs((platform as IHandleData).Handle, deviceType, numEntries, devices, out numDevices);
 }
		protected void DetermineCurrentDevice ()
		{
			// figure out the current device type
			if (UIScreen.MainScreen.Bounds.Height == 1024 || UIScreen.MainScreen.Bounds.Width == 1024) {
				CurrentDevice = DeviceType.iPad;
			} else {
				CurrentDevice = DeviceType.iPhone;
			}
		}
		protected void DetermineCurrentDevice ()
		{
			// figure out the current device type
			if (UIDevice.CurrentDevice.UserInterfaceIdiom == UIUserInterfaceIdiom.Pad) {
				CurrentDevice = DeviceType.iPad;
			} else {
				CurrentDevice = DeviceType.iPhone;
			}
		}
Beispiel #31
0
        public ClientRT(int discussionId, string dbSrvAddr, string UsrName, int usrDbId, DeviceType devType)
        {
            this.discussionId     = discussionId;
            this.dbSrvAddr        = dbSrvAddr;
            this.localUsr.Name    = UsrName;
            this.localUsr.usrDbId = usrDbId;
            this.devType          = devType;

            peer = new LiteLobbyPeer(this);

            Connect();
        }
 public CArrayGenerator(DeviceSession session, DeviceType device)
 {
     this.session = session;
     this.device  = device;
 }
Beispiel #33
0
 private static uint DeviceTypeToUInt(DeviceType deviceType)
 {
     return((uint)deviceType);
 }
Beispiel #34
0
        public override async Task OnDeviceTypesCreating(DeviceTypeBuilder deviceTypeBuilder)
        {
            //Dimmer Type Devices
            var dimmerDt = new DeviceType
            {
                UniqueIdentifier = MiLightDeviceTypes.Color.ToString(),
                Name             = "MiLight Color Light",
                ShowInList       = true
            };

            dimmerDt.Commands.Add(new DeviceTypeCommand
            {
                UniqueIdentifier = "Z1TURNON",
                Name             = "Zone 1, Turn On",
                ArgumentType     = DataType.NONE,
                CustomData1      = "On",
                CustomData2      = "One",
                Description      = "Turns Zone 1 On."
            });
            dimmerDt.Commands.Add(new DeviceTypeCommand
            {
                UniqueIdentifier = "Z1TURNOFF",
                Name             = "Zone 1, Turn Off",
                CustomData1      = "Off",
                CustomData2      = "One",
                ArgumentType     = DataType.NONE,
                Description      = "Turns Zone 1 Off."
            });
            dimmerDt.Commands.Add(new DeviceTypeCommand
            {
                UniqueIdentifier = "Z2TURNON",
                Name             = "Zone 2, Turn On",
                ArgumentType     = DataType.NONE,
                CustomData1      = "On",
                CustomData2      = "Two",
                Description      = "Turns Zone 2 On."
            });
            dimmerDt.Commands.Add(new DeviceTypeCommand
            {
                UniqueIdentifier = "Z2TURNOFF",
                Name             = "Zone 2, Turn Off",
                CustomData1      = "Off",
                CustomData2      = "Two",
                ArgumentType     = DataType.NONE,
                Description      = "Turns Zone 2 Off."
            });

            dimmerDt.Commands.Add(new DeviceTypeCommand
            {
                UniqueIdentifier = "Z3TURNON",
                Name             = "Zone 3, Turn On",
                ArgumentType     = DataType.NONE,
                CustomData1      = "On",
                CustomData2      = "Three",
                Description      = "Turns Zone 3 On."
            });

            dimmerDt.Commands.Add(new DeviceTypeCommand
            {
                UniqueIdentifier = "Z3TURNOFF",
                Name             = "Zone 3, Turn Off",
                CustomData1      = "Off",
                CustomData2      = "Three",
                ArgumentType     = DataType.NONE,
                Description      = "Turns Zone 3 Off."
            });

            dimmerDt.Commands.Add(new DeviceTypeCommand
            {
                UniqueIdentifier = "Z4TURNON",
                Name             = "Zone 4, Turn On",
                ArgumentType     = DataType.NONE,
                CustomData1      = "On",
                CustomData2      = "Four",
                Description      = "Turns Zone 4 On."
            });

            dimmerDt.Commands.Add(new DeviceTypeCommand
            {
                UniqueIdentifier = "Z4TURNOFF",
                Name             = "Zone 4, Turn Off",
                CustomData1      = "Off",
                CustomData2      = "Four",
                ArgumentType     = DataType.NONE,
                Description      = "Turns Zone 4 Off."
            });

            dimmerDt.Commands.Add(new DeviceTypeCommand
            {
                UniqueIdentifier = "ALLOFF",
                Name             = "All Off",
                CustomData1      = "AllOff",
                CustomData2      = "",
                ArgumentType     = DataType.NONE,
                Description      = "Turns All Zones Off."
            });

            dimmerDt.Commands.Add(new DeviceTypeCommand
            {
                UniqueIdentifier = "ALLON",
                Name             = "All On",
                CustomData1      = "AllOn",
                CustomData2      = "",
                ArgumentType     = DataType.NONE,
                Description      = "Turns All Zones On."
            });

            dimmerDt.Commands.Add(new DeviceTypeCommand
            {
                UniqueIdentifier = "HUE",
                Name             = "Hue",
                CustomData1      = "Hue",
                CustomData2      = "",
                ArgumentType     = DataType.DECIMAL,
                Description      = "Changes the current zone the specified hue."
            });

            dimmerDt.Commands.Add(new DeviceTypeCommand
            {
                UniqueIdentifier = "SETBRIGHTNESS",
                Name             = "SetBrightness",
                CustomData1      = "SetBrightness",
                CustomData2      = "",
                ArgumentType     = DataType.INTEGER,
                Description      = "Changes the current zone the specified brightness."
            });

            dimmerDt.Commands.Add(new DeviceTypeCommand
            {
                UniqueIdentifier = "EFFECTDOWN",
                Name             = "Previous effect",
                ArgumentType     = DataType.NONE,
                CustomData1      = "EffectDown",
                CustomData2      = "",
                Description      = "Changes the current zone to the previous effect."
            });

            dimmerDt.Commands.Add(new DeviceTypeCommand
            {
                UniqueIdentifier = "EFFECTUP",
                Name             = "Next Effect",
                CustomData1      = "EffectUp",
                CustomData2      = "",
                ArgumentType     = DataType.NONE,
                Description      = "Changes the current zone to the next effect."
            });

            dimmerDt.Commands.Add(new DeviceTypeCommand
            {
                UniqueIdentifier = "SPEEDDOWN",
                Name             = "Slower speed",
                ArgumentType     = DataType.NONE,
                CustomData1      = "SpeedDown",
                CustomData2      = "",
                Description      = "Changes the current effect to a slower speed."
            });
            dimmerDt.Commands.Add(new DeviceTypeCommand
            {
                UniqueIdentifier = "SPEEDUP",
                Name             = "Faster Speed",
                CustomData1      = "SpeedUp",
                CustomData2      = "",
                ArgumentType     = DataType.NONE,
                Description      = "Changes the current effect to a faster speed."
            });

            var dimmerSaveResult = await deviceTypeBuilder.RegisterAsync(AdapterGuid, dimmerDt, CancellationToken);

            if (dimmerSaveResult.HasError)
            {
                await
                Log.ReportErrorFormatAsync(CancellationToken,
                                           "An error occured when registering the OpenZWave dimmer device type. {0}",
                                           dimmerSaveResult.Message);
            }

            using (var context = new ZvsContext(EntityContextConnection))
            {
                DimmerTypeId =
                    await
                    context.DeviceTypes.Where(o => o.UniqueIdentifier == MiLightDeviceTypes.Color.ToString())
                    .Select(o => o.Id)
                    .FirstOrDefaultAsync();
            }

            await base.OnDeviceTypesCreating(deviceTypeBuilder);
        }
 public void OnRegistered(string token, DeviceType deviceType)
 {
     App.Impronta = token;
 }
 public void OnUnregistered(DeviceType deviceType)
 {
     Debug.WriteLine("Push Notification - Device Unnregistered");
 }
 public override void OnDeviceArrival(DeviceType deviceType)
 {
     Debug.WriteLine("Device arrived " + deviceType);
 }
        public void OnMessage(JObject values, DeviceType deviceType)
        {
            if (values == null)
            {
                return;
            }

            _showNotification = false;
            Debug.WriteLine("Message Arrived: {0}", JsonConvert.SerializeObject(values));

            if (!_authService.IsAuthenticated)
            {
                return;
            }

            JToken token;

            if (!values.TryGetValue("type", StringComparison.OrdinalIgnoreCase, out token) || token == null)
            {
                return;
            }

            var type = (Enums.PushType)token.ToObject <short>();

            switch (type)
            {
            case Enums.PushType.SyncCipherUpdate:
            case Enums.PushType.SyncCipherCreate:
                var cipherCreateUpdateMessage = values.ToObject <SyncCipherPushNotification>();
                if (cipherCreateUpdateMessage.OrganizationId == null &&
                    cipherCreateUpdateMessage.UserId != _authService.UserId)
                {
                    break;
                }
                else if (cipherCreateUpdateMessage.OrganizationId != null &&
                         !_authService.BelongsToOrganization(cipherCreateUpdateMessage.OrganizationId))
                {
                    break;
                }
                _syncService.SyncCipherAsync(cipherCreateUpdateMessage.Id);
                break;

            case Enums.PushType.SyncFolderUpdate:
            case Enums.PushType.SyncFolderCreate:
                var folderCreateUpdateMessage = values.ToObject <SyncFolderPushNotification>();
                if (folderCreateUpdateMessage.UserId != _authService.UserId)
                {
                    break;
                }
                _syncService.SyncFolderAsync(folderCreateUpdateMessage.Id);
                break;

            case Enums.PushType.SyncFolderDelete:
                var folderDeleteMessage = values.ToObject <SyncFolderPushNotification>();
                if (folderDeleteMessage.UserId != _authService.UserId)
                {
                    break;
                }
                _syncService.SyncDeleteFolderAsync(folderDeleteMessage.Id, folderDeleteMessage.RevisionDate);
                break;

            case Enums.PushType.SyncLoginDelete:
                var loginDeleteMessage = values.ToObject <SyncCipherPushNotification>();
                if (loginDeleteMessage.OrganizationId == null &&
                    loginDeleteMessage.UserId != _authService.UserId)
                {
                    break;
                }
                else if (loginDeleteMessage.OrganizationId != null &&
                         !_authService.BelongsToOrganization(loginDeleteMessage.OrganizationId))
                {
                    break;
                }
                _syncService.SyncDeleteLoginAsync(loginDeleteMessage.Id);
                break;

            case Enums.PushType.SyncCiphers:
            case Enums.PushType.SyncVault:
                var cipherMessage = values.ToObject <SyncUserPushNotification>();
                if (cipherMessage.UserId != _authService.UserId)
                {
                    break;
                }
                _syncService.FullSyncAsync(true);
                break;

            case Enums.PushType.SyncSettings:
                var domainMessage = values.ToObject <SyncUserPushNotification>();
                if (domainMessage.UserId != _authService.UserId)
                {
                    break;
                }
                _syncService.SyncSettingsAsync();
                break;

            case Enums.PushType.SyncOrgKeys:
                var orgKeysMessage = values.ToObject <SyncUserPushNotification>();
                if (orgKeysMessage.UserId != _authService.UserId)
                {
                    break;
                }
                _syncService.SyncProfileAsync();
                break;

            default:
                break;
            }
        }
 public void OnError(string message, DeviceType deviceType)
 {
     Debug.WriteLine(string.Format("Push notification error - {0}", message));
 }
Beispiel #40
0
        public void Add(DeviceType device, DeviceData data)
        {
            var parts = _recordingDataParts[device];

            parts.Enqueue(data);
        }
Beispiel #41
0
 public static string ParseForMiningPair(MiningPair miningPair, AlgorithmType algorithmType, DeviceType deviceType, bool showLog = true)
 {
     return(ParseForMiningPairs(
                new List <MiningPair>()
     {
         miningPair
     },
                algorithmType, deviceType,
                MinerPaths.GetOptimizedMinerPath(miningPair), showLog));
 }
Beispiel #42
0
        private static string ParseForMiningPairs(List <MiningPair> MiningPairs, AlgorithmType algorithmType, DeviceType deviceType, string minerPath, bool showLog = true)
        {
            _showLog = showLog;

            // parse for nheqminer
            bool deviceCheckSkip = algorithmType == AlgorithmType.Equihash || algorithmType == AlgorithmType.DaggerHashimoto;

            if (algorithmType == AlgorithmType.Equihash)
            {
                // nheqminer
                if (minerPath == MinerPaths.nheqminer)
                {
                    if (deviceType == DeviceType.CPU)
                    {
                        CheckAndSetCPUPairs(MiningPairs);
                        return(Parse(MiningPairs, _nheqminer_CPU_Options));
                    }
                    if (deviceType == DeviceType.NVIDIA)
                    {
                        return(Parse(MiningPairs, _nheqminer_CUDA_Options));
                    }
                    if (deviceType == DeviceType.AMD)
                    {
                        return(Parse(MiningPairs, _nheqminer_AMD_Options));
                    }
                }
                else if (minerPath == MinerPaths.eqm)
                {
                    if (deviceType == DeviceType.CPU)
                    {
                        CheckAndSetCPUPairs(MiningPairs);
                        return(Parse(MiningPairs, _eqm_CPU_Options));
                    }
                    if (deviceType == DeviceType.NVIDIA)
                    {
                        return(Parse(MiningPairs, _eqm_CUDA_Options));
                    }
                }
                else if (minerPath == MinerPaths.ClaymoreZcashMiner)
                {
                    return(Parse(MiningPairs, _ClaymoreZcash_Options));
                }
            }
            else if (algorithmType == AlgorithmType.DaggerHashimoto)     // ethminer dagger
            // use if missing compute device for correct mapping
            // init fakes workaround
            {
                var cdevs_mappings = new List <MiningPair>();
                {
                    int id       = -1;
                    var fakeAlgo = new Algorithm(AlgorithmType.DaggerHashimoto, "daggerhashimoto");
                    foreach (var pair in MiningPairs)
                    {
                        while (++id != pair.Device.ID)
                        {
                            var fakeCdev = new ComputeDevice(id);
                            cdevs_mappings.Add(new MiningPair(fakeCdev, fakeAlgo));
                        }
                        cdevs_mappings.Add(pair);
                    }
                }
                if (deviceType == DeviceType.NVIDIA)
                {
                    return(Parse(cdevs_mappings, _cudaEthminerOptions));
                }
                else if (deviceType == DeviceType.AMD)
                {
                    return(Parse(cdevs_mappings, _oclEthminerOptions));
                }
            }
            else if (deviceCheckSkip == false)
            {
                // parse for device
                if (deviceType == DeviceType.CPU)
                {
                    CheckAndSetCPUPairs(MiningPairs);
                    return(Parse(MiningPairs, _cpuminerOptions));
                }
                else if (deviceType == DeviceType.NVIDIA)
                {
                    if (algorithmType != AlgorithmType.CryptoNight)
                    {
                        return(Parse(MiningPairs, _ccimerOptions));
                    }
                    else if (algorithmType == AlgorithmType.CryptoNight)
                    {
                        // check if any device is SM21 or SM3.x if yes return empty for stability reasons
                        foreach (var pair in MiningPairs)
                        {
                            var groupType = pair.Device.DeviceGroupType;
                            if (groupType == DeviceGroupType.NVIDIA_2_1 || groupType == DeviceGroupType.NVIDIA_3_x)
                            {
                                return("");
                            }
                        }
                        return(Parse(MiningPairs, _ccimerCryptoNightOptions, true));
                    }
                }
                else if (deviceType == DeviceType.AMD)
                {
                    // rawIntensity overrides xintensity, xintensity overrides intensity
                    var sgminer_intensities = new List <MinerOption>()
                    {
                        new MinerOption(MinerOptionType.Intensity, "-I", "--intensity", "d", MinerOptionFlagType.MultiParam, ","),      // default is "d" check if -1 works
                        new MinerOption(MinerOptionType.Xintensity, "-X", "--xintensity", "-1", MinerOptionFlagType.MultiParam, ","),   // default none
                        new MinerOption(MinerOptionType.Rawintensity, "", "--rawintensity", "-1", MinerOptionFlagType.MultiParam, ","), // default none
                    };
                    var contains_intensity = new Dictionary <MinerOptionType, bool>()
                    {
                        { MinerOptionType.Intensity, false },
                        { MinerOptionType.Xintensity, false },
                        { MinerOptionType.Rawintensity, false },
                    };
                    // check intensity and xintensity, the latter overrides so change accordingly
                    foreach (var cDev in MiningPairs)
                    {
                        foreach (var intensityOption in sgminer_intensities)
                        {
                            if (!string.IsNullOrEmpty(intensityOption.ShortName) && cDev.CurrentExtraLaunchParameters.Contains(intensityOption.ShortName))
                            {
                                cDev.CurrentExtraLaunchParameters        = cDev.CurrentExtraLaunchParameters.Replace(intensityOption.ShortName, intensityOption.LongName);
                                contains_intensity[intensityOption.Type] = true;
                            }
                            if (cDev.CurrentExtraLaunchParameters.Contains(intensityOption.LongName))
                            {
                                contains_intensity[intensityOption.Type] = true;
                            }
                        }
                    }
                    // replace
                    if (contains_intensity[MinerOptionType.Intensity] && contains_intensity[MinerOptionType.Xintensity])
                    {
                        LogParser("Sgminer replacing --intensity with --xintensity");
                        foreach (var cDev in MiningPairs)
                        {
                            cDev.CurrentExtraLaunchParameters = cDev.CurrentExtraLaunchParameters.Replace("--intensity", "--xintensity");
                        }
                    }
                    if (contains_intensity[MinerOptionType.Xintensity] && contains_intensity[MinerOptionType.Rawintensity])
                    {
                        LogParser("Sgminer replacing --xintensity with --rawintensity");
                        foreach (var cDev in MiningPairs)
                        {
                            cDev.CurrentExtraLaunchParameters = cDev.CurrentExtraLaunchParameters.Replace("--xintensity", "--rawintensity");
                        }
                    }

                    List <MinerOption> sgminerOptionsNew  = new List <MinerOption>();
                    string             temperatureControl = "";
                    // temp control and parse
                    if (ConfigManager.GeneralConfig.DisableAMDTempControl)
                    {
                        LogParser("DisableAMDTempControl is TRUE, temp control parameters will be ignored");
                    }
                    else
                    {
                        LogParser("Sgminer parsing temperature control parameters");
                        temperatureControl = Parse(MiningPairs, _sgminerTemperatureOptions, true, _sgminerOptions);
                    }
                    LogParser("Sgminer parsing default parameters");
                    string returnStr = String.Format("{0} {1}", Parse(MiningPairs, _sgminerOptions, false, _sgminerTemperatureOptions), temperatureControl);
                    LogParser("Sgminer extra launch parameters merged: " + returnStr);
                    return(returnStr);
                }
            }

            return("");
        }
Beispiel #43
0
 public Type GetTypeFromDeviceType(DeviceType deviceType)
 => deviceType switch
 {
Beispiel #44
0
        public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
        {
            string code = reader.Value as string;

            return(DeviceType.GetOrCreate(code));
        }
 public override void OnDeviceRemoval(DeviceType deviceType)
 {
     Debug.WriteLine("Device removed " + deviceType);
 }
Beispiel #46
0
 public void SetDeviceType(DeviceType x)
 {
     WriteVar("set_device", Ev3Dev.DeviceType_To_String(x));
 }
Beispiel #47
0
 //kreira tip uredjaja
 public void CreateDeviceType(DeviceType deviceType)
 {
     _context.DeviceTypes.Add(deviceType);
 }
Beispiel #48
0
 /// <summary>
 /// Initializes a new instance of the DeviceInner class.
 /// </summary>
 /// <param name="friendlyName">The friendly name of the device.</param>
 /// <param name="activationTime">The UTC time at which the device was
 /// activated</param>
 /// <param name="culture">The language culture setting on the device.
 /// For eg: "en-US"</param>
 /// <param name="deviceDescription">The device description.</param>
 /// <param name="deviceSoftwareVersion">The version number of the
 /// software running on the device.</param>
 /// <param name="deviceConfigurationStatus">The current configuration
 /// status of the device. Possible values include: 'Complete',
 /// 'Pending'</param>
 /// <param name="targetIqn">The target IQN.</param>
 /// <param name="modelDescription">The device model.</param>
 /// <param name="status">The current status of the device. Possible
 /// values include: 'Unknown', 'Online', 'Offline', 'Deactivated',
 /// 'RequiresAttention', 'MaintenanceMode', 'Creating', 'Provisioning',
 /// 'Deactivating', 'Deleted', 'ReadyToSetup'</param>
 /// <param name="serialNumber">The serial number.</param>
 /// <param name="deviceType">The type of the device. Possible values
 /// include: 'Invalid', 'Series8000VirtualAppliance',
 /// 'Series8000PhysicalAppliance'</param>
 /// <param name="activeController">The identifier of the active
 /// controller of the device. Possible values include: 'Unknown',
 /// 'None', 'Controller0', 'Controller1'</param>
 /// <param name="friendlySoftwareVersion">The device friendly software
 /// version.</param>
 /// <param name="id">The path ID that uniquely identifies the
 /// object.</param>
 /// <param name="name">The name of the object.</param>
 /// <param name="type">The hierarchical type of the object.</param>
 /// <param name="kind">The Kind of the object. Currently only
 /// Series8000 is supported. Possible values include:
 /// 'Series8000'</param>
 /// <param name="friendlySoftwareName">The friendly name of the
 /// software running on the device.</param>
 /// <param name="availableLocalStorageInBytes">The storage in bytes
 /// that is available locally on the device.</param>
 /// <param name="availableTieredStorageInBytes">The storage in bytes
 /// that is available on the device for tiered volumes.</param>
 /// <param name="provisionedTieredStorageInBytes">The storage in bytes
 /// that has been provisioned on the device for tiered volumes.</param>
 /// <param name="provisionedLocalStorageInBytes">The storage in bytes
 /// used for locally pinned volumes on the device (including additional
 /// local reservation).</param>
 /// <param name="provisionedVolumeSizeInBytes">Total capacity in bytes
 /// of tiered and locally pinned volumes on the device</param>
 /// <param name="usingStorageInBytes">The storage in bytes that is
 /// currently being used on the device, including both local and
 /// cloud.</param>
 /// <param name="totalTieredStorageInBytes">The total tiered storage
 /// available on the device in bytes.</param>
 /// <param name="agentGroupVersion">The device agent group
 /// version.</param>
 /// <param name="networkInterfaceCardCount">The number of network
 /// interface cards</param>
 /// <param name="deviceLocation">The location of the virtual
 /// appliance.</param>
 /// <param name="virtualMachineApiType">The virtual machine API type.
 /// Possible values include: 'Classic', 'Arm'</param>
 /// <param name="details">The additional device details regarding the
 /// end point count and volume container count.</param>
 /// <param name="rolloverDetails">The additional device details for the
 /// service data encryption key rollover.</param>
 public DeviceInner(string friendlyName, System.DateTime activationTime, string culture, string deviceDescription, string deviceSoftwareVersion, DeviceConfigurationStatus deviceConfigurationStatus, string targetIqn, string modelDescription, DeviceStatus status, string serialNumber, DeviceType deviceType, ControllerId activeController, string friendlySoftwareVersion, string id = default(string), string name = default(string), string type = default(string), Kind?kind = default(Kind?), string friendlySoftwareName = default(string), long?availableLocalStorageInBytes = default(long?), long?availableTieredStorageInBytes = default(long?), long?provisionedTieredStorageInBytes = default(long?), long?provisionedLocalStorageInBytes = default(long?), long?provisionedVolumeSizeInBytes = default(long?), long?usingStorageInBytes = default(long?), long?totalTieredStorageInBytes = default(long?), int?agentGroupVersion = default(int?), int?networkInterfaceCardCount = default(int?), string deviceLocation = default(string), VirtualMachineApiType?virtualMachineApiType = default(VirtualMachineApiType?), DeviceDetails details = default(DeviceDetails), DeviceRolloverDetails rolloverDetails = default(DeviceRolloverDetails))
     : base(id, name, type, kind)
 {
     FriendlyName              = friendlyName;
     ActivationTime            = activationTime;
     Culture                   = culture;
     DeviceDescription         = deviceDescription;
     DeviceSoftwareVersion     = deviceSoftwareVersion;
     FriendlySoftwareName      = friendlySoftwareName;
     DeviceConfigurationStatus = deviceConfigurationStatus;
     TargetIqn                 = targetIqn;
     ModelDescription          = modelDescription;
     Status                          = status;
     SerialNumber                    = serialNumber;
     DeviceType                      = deviceType;
     ActiveController                = activeController;
     FriendlySoftwareVersion         = friendlySoftwareVersion;
     AvailableLocalStorageInBytes    = availableLocalStorageInBytes;
     AvailableTieredStorageInBytes   = availableTieredStorageInBytes;
     ProvisionedTieredStorageInBytes = provisionedTieredStorageInBytes;
     ProvisionedLocalStorageInBytes  = provisionedLocalStorageInBytes;
     ProvisionedVolumeSizeInBytes    = provisionedVolumeSizeInBytes;
     UsingStorageInBytes             = usingStorageInBytes;
     TotalTieredStorageInBytes       = totalTieredStorageInBytes;
     AgentGroupVersion               = agentGroupVersion;
     NetworkInterfaceCardCount       = networkInterfaceCardCount;
     DeviceLocation                  = deviceLocation;
     VirtualMachineApiType           = virtualMachineApiType;
     Details                         = details;
     RolloverDetails                 = rolloverDetails;
     CustomInit();
 }
 public void OnUnregistered(DeviceType deviceType)
 {
 }
Beispiel #50
0
 public string RegisterDevice(int tenantID, string userID, string token, DeviceType type)
 {
     return(Channel.RegisterDevice(tenantID, userID, token, type));
 }
 public void OnMessage(global::Newtonsoft.Json.Linq.JObject values, DeviceType deviceType)
 {
     App.OnNotification(values);
 }
Beispiel #52
0
        public async Task <InvokeResult <Solution> > CreateSimpleSolutionAsync(EntityHeader org, EntityHeader user, DateTime createTimeStamp)
        {
            /* Create unit/state sets */
            var stateSet = new StateSet()
            {
                Key         = "onoff",
                Name        = "On/Off",
                Description = "Provides two simple states, On and Off",
                States      = new List <State> {
                    new State()
                    {
                        Key = "on", Name = "On", IsInitialState = true
                    },
                    new State()
                    {
                        Key = "off", Name = "Off"
                    }
                }
            };

            AddId(stateSet);
            AddOwnedProperties(stateSet, org);
            AddAuditProperties(stateSet, createTimeStamp, org, user);
            await _deviceAdminMgr.AddStateSetAsync(stateSet, org, user);

            var unitSet = new UnitSet()
            {
                Key   = "Temperature",
                Name  = "temperature",
                Units = new List <Unit>()
                {
                    new Unit()
                    {
                        Key = "fahrenheit", Name = "Fahrenheit", IsDefault = true
                    },
                    new Unit()
                    {
                        Key = "celsius", Name = "Celsius", IsDefault = false
                    },
                }
            };

            AddId(unitSet);
            AddOwnedProperties(unitSet, org);
            AddAuditProperties(unitSet, createTimeStamp, org, user);
            await _deviceAdminMgr.AddUnitSetAsync(unitSet, org, user);

            /* Create Pipeline Modules */
            var restListener = new ListenerConfiguration()
            {
                Name           = "Sample Rest",
                Key            = "samplereset",
                ListenerType   = EntityHeader <ListenerTypes> .Create(ListenerTypes.Rest),
                RestServerType = EntityHeader <RESTServerTypes> .Create(RESTServerTypes.HTTP),
                ListenOnPort   = 80,
                ContentType    = EntityHeader <DeviceMessaging.Admin.Models.MessageContentTypes> .Create(DeviceMessaging.Admin.Models.MessageContentTypes.JSON),
                UserName       = "******",
                Password       = "******"
            };

            AddId(restListener);
            AddOwnedProperties(restListener, org);
            AddAuditProperties(restListener, createTimeStamp, org, user);
            await _pipelineMgr.AddListenerConfigurationAsync(restListener, org, user);

            var msgTempDefinition = new DeviceMessaging.Admin.Models.DeviceMessageDefinition()
            {
                Name           = "Sample Temperature Message",
                Key            = "sampletempmsg",
                SampleMessages = new List <DeviceMessaging.Admin.Models.SampleMessage>()
                {
                    new DeviceMessaging.Admin.Models.SampleMessage()
                    {
                        Id      = Guid.NewGuid().ToId(),
                        Name    = "Example Temperature Message",
                        Key     = "exmpl001",
                        Payload = "98.5,38",
                        Headers = new System.Collections.ObjectModel.ObservableCollection <DeviceMessaging.Admin.Models.Header>()
                        {
                            new DeviceMessaging.Admin.Models.Header()
                            {
                                Name = "x-deviceid", Value = "device001"
                            },
                            new DeviceMessaging.Admin.Models.Header()
                            {
                                Name = "x-messageid", Value = "tmpmsg001"
                            }
                        }
                    }
                },
                MessageId   = "smpltmp001",
                ContentType = EntityHeader <DeviceMessaging.Admin.Models.MessageContentTypes> .Create(DeviceMessaging.Admin.Models.MessageContentTypes.Delimited),
                Fields      = new List <DeviceMessaging.Admin.Models.DeviceMessageDefinitionField>()
                {
                    new DeviceMessaging.Admin.Models.DeviceMessageDefinitionField()
                    {
                        Id             = Guid.NewGuid().ToId(),
                        Name           = "Temperature",
                        Key            = "temp",
                        DelimitedIndex = 0,
                        UnitSet        = new EntityHeader <UnitSet>()
                        {
                            Id = unitSet.Id, Text = unitSet.Name, Value = unitSet
                        },
                        StorageType = EntityHeader <ParameterTypes> .Create(ParameterTypes.State),
                    },
                    new DeviceMessaging.Admin.Models.DeviceMessageDefinitionField()
                    {
                        Id             = Guid.NewGuid().ToId(),
                        Name           = "Humidity",
                        Key            = "humidity",
                        DelimitedIndex = 1,
                        StorageType    = EntityHeader <ParameterTypes> .Create(ParameterTypes.Integer),
                    }
                }
            };

            AddId(msgTempDefinition);
            AddOwnedProperties(msgTempDefinition, org);
            AddAuditProperties(msgTempDefinition, createTimeStamp, org, user);
            await _deviceMsgMgr.AddDeviceMessageDefinitionAsync(msgTempDefinition, org, user);

            var motionMsgDefinition = new DeviceMessaging.Admin.Models.DeviceMessageDefinition()
            {
                Name           = "Sample Motion Message",
                Key            = "samplemptionmsg",
                SampleMessages = new List <DeviceMessaging.Admin.Models.SampleMessage>()
                {
                    new DeviceMessaging.Admin.Models.SampleMessage()
                    {
                        Id                 = Guid.NewGuid().ToId(),
                        Name               = "Example Motion Message",
                        Key                = "exmpl001",
                        Payload            = "{'motion':'on','level':80}",
                        PathAndQueryString = "/motion/device001"
                    }
                },
                MessageId   = "smplmot001",
                ContentType = EntityHeader <DeviceMessaging.Admin.Models.MessageContentTypes> .Create(DeviceMessaging.Admin.Models.MessageContentTypes.JSON),
                Fields      = new List <DeviceMessaging.Admin.Models.DeviceMessageDefinitionField>()
                {
                    new DeviceMessaging.Admin.Models.DeviceMessageDefinitionField()
                    {
                        Id       = Guid.NewGuid().ToId(),
                        Name     = "Motion",
                        Key      = "motion",
                        JsonPath = "motion",
                        StateSet = new EntityHeader <StateSet>()
                        {
                            Id = stateSet.Id, Text = stateSet.Name, Value = stateSet
                        },
                        StorageType = EntityHeader <ParameterTypes> .Create(ParameterTypes.State),
                    },
                    new DeviceMessaging.Admin.Models.DeviceMessageDefinitionField()
                    {
                        Id          = Guid.NewGuid().ToId(),
                        Name        = "Level",
                        Key         = "level",
                        JsonPath    = "level",
                        StorageType = EntityHeader <ParameterTypes> .Create(ParameterTypes.Integer),
                    }
                }
            };

            AddId(motionMsgDefinition);
            AddOwnedProperties(motionMsgDefinition, org);
            AddAuditProperties(motionMsgDefinition, createTimeStamp, org, user);
            await _deviceMsgMgr.AddDeviceMessageDefinitionAsync(motionMsgDefinition, org, user);


            var deviceIdParser1 = new DeviceMessaging.Admin.Models.DeviceMessageDefinitionField()
            {
                SearchLocation = EntityHeader <DeviceMessaging.Admin.Models.SearchLocations> .Create(DeviceMessaging.Admin.Models.SearchLocations.Header),
                HeaderName     = "x-deviceid",
                Name           = "Device Id in Header",
                Key            = "xdeviceid"
            };

            var deviceIdParser2 = new DeviceMessaging.Admin.Models.DeviceMessageDefinitionField()
            {
                SearchLocation = EntityHeader <DeviceMessaging.Admin.Models.SearchLocations> .Create(DeviceMessaging.Admin.Models.SearchLocations.Path),
                PathLocator    = "/*/{deviceid}",
                Name           = "Device Id in Path",
                Key            = "pathdeviceid"
            };

            var messageIdParser1 = new DeviceMessaging.Admin.Models.DeviceMessageDefinitionField()
            {
                SearchLocation = EntityHeader <DeviceMessaging.Admin.Models.SearchLocations> .Create(DeviceMessaging.Admin.Models.SearchLocations.Header),
                HeaderName     = "x-messageid",
                Name           = "Message Id in Header",
                Key            = "xmessageid",
            };
            var messageIdParser2 = new DeviceMessaging.Admin.Models.DeviceMessageDefinitionField()
            {
                SearchLocation = EntityHeader <DeviceMessaging.Admin.Models.SearchLocations> .Create(DeviceMessaging.Admin.Models.SearchLocations.Path),
                PathLocator    = "/{messageid}/*",
                Name           = "Message Id in Path",
                Key            = "pathmessageid"
            };

            var verifier = new Verifier()
            {
                Component = new EntityHeader()
                {
                    Id   = motionMsgDefinition.Id,
                    Text = motionMsgDefinition.Name
                },
                ExpectedOutputs = new System.Collections.ObjectModel.ObservableCollection <ExpectedValue>()
                {
                    new ExpectedValue()
                    {
                        Key = "motion", Value = "on"
                    },
                    new ExpectedValue()
                    {
                        Key = "level", Value = "80"
                    }
                },
                InputType          = EntityHeader <InputTypes> .Create(InputTypes.Text),
                Name               = "Simple Message Verifier",
                Key                = "smplmsgver",
                Description        = "Validates that a Sample Motion Message has the proper field parsers",
                Input              = "{'motion':'on','level':80}",
                PathAndQueryString = "/smplmot001/device001",
                ShouldSucceed      = true,
                VerifierType       = EntityHeader <VerifierTypes> .Create(VerifierTypes.MessageParser)
            };

            AddId(verifier);
            AddOwnedProperties(verifier, org);
            AddAuditProperties(verifier, createTimeStamp, org, user);
            await _verifierMgr.AddVerifierAsync(verifier, org, user);

            var deviceIdParserVerifier1 = new Verifier()
            {
                Component = new EntityHeader()
                {
                    Id   = deviceIdParser1.Id,
                    Text = deviceIdParser1.Name
                },
                ExpectedOutput = "device001",
                InputType      = EntityHeader <InputTypes> .Create(InputTypes.Text),
                Name           = "Find Device Id in Header",
                Key            = "msgidheader",
                Description    = "Validates that the Device Id can be extracted from the header",
                Headers        = new System.Collections.ObjectModel.ObservableCollection <DeviceMessaging.Admin.Models.Header>()
                {
                    new DeviceMessaging.Admin.Models.Header()
                    {
                        Name = "x-messageid", Value = "device001"
                    }
                },
                ShouldSucceed = true,
                VerifierType  = EntityHeader <VerifierTypes> .Create(VerifierTypes.MessageFieldParser)
            };

            AddId(deviceIdParserVerifier1);
            AddOwnedProperties(deviceIdParserVerifier1, org);
            AddAuditProperties(deviceIdParserVerifier1, createTimeStamp, org, user);
            await _verifierMgr.AddVerifierAsync(deviceIdParserVerifier1, org, user);

            var deviceIdParserVerifier2 = new Verifier()
            {
                Component = new EntityHeader()
                {
                    Id   = deviceIdParser2.Id,
                    Text = deviceIdParser2.Name
                },
                ExpectedOutput     = "device002",
                InputType          = EntityHeader <InputTypes> .Create(InputTypes.Text),
                Name               = "Finds Device Id in Path",
                Key                = "msgidpath",
                Description        = "Validats the the device id can be extracted from thepath",
                PathAndQueryString = "/smplmot001/device002",
                ShouldSucceed      = true,
                VerifierType       = EntityHeader <VerifierTypes> .Create(VerifierTypes.MessageFieldParser)
            };

            AddId(deviceIdParserVerifier2);
            AddOwnedProperties(deviceIdParserVerifier2, org);
            AddAuditProperties(deviceIdParserVerifier2, createTimeStamp, org, user);
            await _verifierMgr.AddVerifierAsync(deviceIdParserVerifier2, org, user);

            var messageIdParserVerifier1 = new Verifier()
            {
                Component = new EntityHeader()
                {
                    Id   = messageIdParser1.Id,
                    Text = messageIdParser1.Name
                },
                ExpectedOutput = "smplmsg001",
                InputType      = EntityHeader <InputTypes> .Create(InputTypes.Text),
                Name           = "Finds Message id in Header",
                Key            = "msgidheader",
                Description    = "Validates that the message id can be extracted from the header",
                Headers        = new System.Collections.ObjectModel.ObservableCollection <DeviceMessaging.Admin.Models.Header>()
                {
                    new DeviceMessaging.Admin.Models.Header()
                    {
                        Name = "x-messageid", Value = "smplmsg001"
                    }
                },
                ShouldSucceed = true,
                VerifierType  = EntityHeader <VerifierTypes> .Create(VerifierTypes.MessageFieldParser)
            };

            AddId(messageIdParserVerifier1);
            AddOwnedProperties(messageIdParserVerifier1, org);
            AddAuditProperties(messageIdParserVerifier1, createTimeStamp, org, user);
            await _verifierMgr.AddVerifierAsync(messageIdParserVerifier1, org, user);

            var messageIdParserVerifier2 = new Verifier()
            {
                Component = new EntityHeader()
                {
                    Id   = messageIdParser2.Id,
                    Text = messageIdParser2.Name
                },
                ExpectedOutput     = "smplmot002",
                InputType          = EntityHeader <InputTypes> .Create(InputTypes.Text),
                Name               = "Finds Message id in Path",
                Key                = "msgidpath",
                Description        = "Validates that the message id can be extracted from path.",
                PathAndQueryString = "/smplmot002/device001",
                ShouldSucceed      = true,
                VerifierType       = EntityHeader <VerifierTypes> .Create(VerifierTypes.MessageFieldParser)
            };

            AddId(messageIdParserVerifier2);
            AddOwnedProperties(messageIdParserVerifier2, org);
            AddAuditProperties(messageIdParserVerifier2, createTimeStamp, org, user);
            await _verifierMgr.AddVerifierAsync(messageIdParserVerifier2, org, user);

            var planner = new PlannerConfiguration()
            {
                Name = "Sample Planner",
                Key  = "sampleplanner",
                MessageTypeIdParsers = new List <DeviceMessaging.Admin.Models.DeviceMessageDefinitionField>()
                {
                    messageIdParser1, messageIdParser2
                },
                DeviceIdParsers = new List <DeviceMessaging.Admin.Models.DeviceMessageDefinitionField>()
                {
                    deviceIdParser1, deviceIdParser2
                }
            };

            AddId(planner);
            AddOwnedProperties(planner, org);
            AddAuditProperties(planner, createTimeStamp, org, user);
            await _pipelineMgr.AddPlannerConfigurationAsync(planner, org, user);


            /* Create Pipeline Modules */
            var sentinelConfiguration = new SentinelConfiguration()
            {
                Name = "Sample Sentinel",
                Key  = "samplereset",
            };

            AddId(sentinelConfiguration);
            AddOwnedProperties(sentinelConfiguration, org);
            AddAuditProperties(sentinelConfiguration, createTimeStamp, org, user);
            await _pipelineMgr.AddSentinelConfigurationAsync(sentinelConfiguration, org, user);

            var inputTranslator = new InputTranslatorConfiguration()
            {
                Name = "Sample Input Translator",
                Key  = "sampleinputtranslator",
                InputTranslatorType = EntityHeader <InputTranslatorConfiguration.InputTranslatorTypes> .Create(InputTranslatorConfiguration.InputTranslatorTypes.MessageBased),
            };

            AddId(inputTranslator);
            AddOwnedProperties(inputTranslator, org);
            AddAuditProperties(inputTranslator, createTimeStamp, org, user);
            await _pipelineMgr.AddInputTranslatorConfigurationAsync(inputTranslator, org, user);

            var wf = new DeviceWorkflow()
            {
                Key         = "sampleworkflow",
                Name        = "Sample Workflow",
                Description = "Sample Workflow",
                Attributes  = new List <DeviceAdmin.Models.Attribute>()
                {
                },
                Inputs = new List <WorkflowInput>()
                {
                },
                InputCommands = new List <InputCommand>()
                {
                },
                StateMachines = new List <StateMachine>()
                {
                },
                OutputCommands = new List <OutputCommand>()
                {
                }
            };

            AddId(wf);
            AddOwnedProperties(wf, org);
            AddAuditProperties(wf, createTimeStamp, org, user);
            await _deviceAdminMgr.AddDeviceWorkflowAsync(wf, org, user);

            var outTranslator = new OutputTranslatorConfiguration()
            {
                Name = "Sample Output Translator",
                Key  = "sampleinputtranslator",
                OutputTranslatorType = EntityHeader <OutputTranslatorConfiguration.OutputTranslatorTypes> .Create(OutputTranslatorConfiguration.OutputTranslatorTypes.MessageBased),
            };

            AddId(outTranslator);
            AddOwnedProperties(outTranslator, org);
            AddAuditProperties(outTranslator, createTimeStamp, org, user);
            await _pipelineMgr.AddOutputTranslatorConfigurationAsync(outTranslator, org, user);

            var tmpOutTrn = new RouteModuleConfig()
            {
                Id     = Guid.NewGuid().ToId(),
                Name   = outTranslator.Name,
                Module = new EntityHeader <DeviceAdmin.Interfaces.IPipelineModuleConfiguration>()
                {
                    Id = outTranslator.Id, Text = outTranslator.Name, Value = outTranslator
                },
                ModuleType = EntityHeader <PipelineModuleType> .Create(PipelineModuleType.OutputTranslator)
            };
            var tmpWf = new RouteModuleConfig()
            {
                Id     = Guid.NewGuid().ToId(),
                Name   = wf.Name,
                Module = new EntityHeader <DeviceAdmin.Interfaces.IPipelineModuleConfiguration>()
                {
                    Id = wf.Id, Text = wf.Name, Value = wf
                },
                PrimaryOutput = new RouteConnection()
                {
                    Id = tmpOutTrn.Id, Name = outTranslator.Name, Mappings = new List <KeyValuePair <string, object> >()
                },
                ModuleType = EntityHeader <PipelineModuleType> .Create(PipelineModuleType.Workflow)
            };
            var tmpInputTrn = new RouteModuleConfig()
            {
                Id     = Guid.NewGuid().ToId(),
                Name   = inputTranslator.Name,
                Module = new EntityHeader <DeviceAdmin.Interfaces.IPipelineModuleConfiguration>()
                {
                    Id = inputTranslator.Id, Text = inputTranslator.Name, Value = inputTranslator
                },
                PrimaryOutput = new RouteConnection()
                {
                    Id = tmpWf.Id, Name = wf.Name, Mappings = new List <KeyValuePair <string, object> >()
                },
                ModuleType = EntityHeader <PipelineModuleType> .Create(PipelineModuleType.InputTranslator)
            };
            var tmpSent = new RouteModuleConfig()
            {
                Id     = Guid.NewGuid().ToId(),
                Name   = sentinelConfiguration.Name,
                Module = new EntityHeader <DeviceAdmin.Interfaces.IPipelineModuleConfiguration>()
                {
                    Id = sentinelConfiguration.Id, Text = sentinelConfiguration.Name, Value = sentinelConfiguration
                },
                PrimaryOutput = new RouteConnection()
                {
                    Id = tmpInputTrn.Id, Name = inputTranslator.Name, Mappings = new List <KeyValuePair <string, object> >()
                },
                ModuleType = EntityHeader <PipelineModuleType> .Create(PipelineModuleType.Sentinel)
            };


            /* Create Route */
            var temperatureRoute = new Route()
            {
                Name = "Sample Temperature Route",
                Key  = "sampletemproute",
                MessageDefinition = new EntityHeader <DeviceMessaging.Admin.Models.DeviceMessageDefinition>()
                {
                    Id = msgTempDefinition.Id, Text = msgTempDefinition.Name, Value = msgTempDefinition
                },
                PipelineModules = new List <RouteModuleConfig>()
            };

            var motOutTran = new RouteModuleConfig()
            {
                Id     = Guid.NewGuid().ToId(),
                Name   = outTranslator.Name,
                Module = new EntityHeader <DeviceAdmin.Interfaces.IPipelineModuleConfiguration>()
                {
                    Id = outTranslator.Id, Text = outTranslator.Name, Value = outTranslator
                },
                ModuleType = EntityHeader <PipelineModuleType> .Create(PipelineModuleType.OutputTranslator)
            };
            var motWf = new RouteModuleConfig()
            {
                Id     = Guid.NewGuid().ToId(),
                Name   = wf.Name,
                Module = new EntityHeader <DeviceAdmin.Interfaces.IPipelineModuleConfiguration>()
                {
                    Id = wf.Id, Text = wf.Name, Value = wf
                },
                PrimaryOutput = new RouteConnection()
                {
                    Id = motOutTran.Id, Name = outTranslator.Name, Mappings = new List <KeyValuePair <string, object> >()
                },
                ModuleType = EntityHeader <PipelineModuleType> .Create(PipelineModuleType.Workflow)
            };
            var motInputTrn = new RouteModuleConfig()
            {
                Id     = Guid.NewGuid().ToId(),
                Name   = inputTranslator.Name,
                Module = new EntityHeader <DeviceAdmin.Interfaces.IPipelineModuleConfiguration>()
                {
                    Id = inputTranslator.Id, Text = inputTranslator.Name, Value = inputTranslator
                },
                PrimaryOutput = new RouteConnection()
                {
                    Id = motWf.Id, Name = wf.Name, Mappings = new List <KeyValuePair <string, object> >()
                },
                ModuleType = EntityHeader <PipelineModuleType> .Create(PipelineModuleType.InputTranslator)
            };

            var motSent = new RouteModuleConfig()
            {
                Id     = Guid.NewGuid().ToId(),
                Name   = sentinelConfiguration.Name,
                Module = new EntityHeader <DeviceAdmin.Interfaces.IPipelineModuleConfiguration>()
                {
                    Id = sentinelConfiguration.Id, Text = sentinelConfiguration.Name, Value = sentinelConfiguration
                },
                PrimaryOutput = new RouteConnection()
                {
                    Id = motInputTrn.Id, Name = inputTranslator.Name, Mappings = new List <KeyValuePair <string, object> >()
                },
                ModuleType = EntityHeader <PipelineModuleType> .Create(PipelineModuleType.Sentinel)
            };

            /* Create Route */
            var motionRoute = new Route()
            {
                Name = "Sample Motion Route",
                Key  = "sampletemproute",
                MessageDefinition = new EntityHeader <DeviceMessaging.Admin.Models.DeviceMessageDefinition>()
                {
                    Id = motionMsgDefinition.Id, Text = motionMsgDefinition.Name, Value = motionMsgDefinition
                },
                PipelineModules = new List <RouteModuleConfig>()
                {
                    motSent, motInputTrn, motWf, motOutTran
                }
            };

            var deviceConfig = new DeviceConfiguration()
            {
                ConfigurationVersion = 1.0,
                Name       = "Sample Device Config",
                Key        = "sampledeviceconfig",
                Properties = new List <CustomField>()
                {
                    new CustomField()
                    {
                        Id           = Guid.NewGuid().ToId(),
                        DefaultValue = "90",
                        FieldType    = EntityHeader <ParameterTypes> .Create(ParameterTypes.Decimal),
                        Key          = "setpoint",
                        Name         = "Setpoint",
                        Label        = "Setpoint",
                        HelpText     = "Setpoint where temperature will trigger warning",
                        IsRequired   = true,
                        Order        = 1
                    }
                },
                Routes = new List <Route>()
                {
                    temperatureRoute,
                    motionRoute
                }
            };

            AddId(deviceConfig);
            AddOwnedProperties(deviceConfig, org);
            AddAuditProperties(deviceConfig, createTimeStamp, org, user);
            await _deviceCfgMgr.AddDeviceConfigurationAsync(deviceConfig, org, user);

            var deviceType = new DeviceType()
            {
                Name = "Sample Device Type",
                Key  = "sampledevicetype",
                DefaultDeviceConfiguration = new EntityHeader()
                {
                    Id = deviceConfig.Id, Text = deviceConfig.Name
                }
            };

            AddId(deviceType);
            AddOwnedProperties(deviceType, org);
            AddAuditProperties(deviceType, createTimeStamp, org, user);
            await _deviceTypeMgr.AddDeviceTypeAsync(deviceType, org, user);


            /* Create Solution */
            var solution = new Solution()
            {
                Id        = "Sample App",
                Name      = "sampleapp",
                Listeners = new List <EntityHeader <ListenerConfiguration> >()
                {
                    new EntityHeader <ListenerConfiguration>()
                    {
                        Id = restListener.Id, Text = restListener.Name, Value = restListener
                    }
                },
                Planner = new EntityHeader <PlannerConfiguration>()
                {
                    Id = planner.Id, Text = planner.Name, Value = planner
                },
                DeviceConfigurations = new List <EntityHeader <DeviceConfiguration> >()
                {
                    new EntityHeader <DeviceConfiguration>()
                    {
                        Id = deviceConfig.Id, Text = deviceConfig.Name, Value = deviceConfig
                    }
                },
            };

            AddId(solution);
            AddOwnedProperties(solution, org);
            AddAuditProperties(solution, createTimeStamp, org, user);

            return(InvokeResult <Solution> .Create(solution));
        }
 public void OnError(string message, DeviceType deviceType)
 {
 }
Beispiel #54
0
 public Task CreateOrUpdateRegistrationAsync(string pushToken, string deviceId, string userId,
                                             string identifier, DeviceType type)
 {
     return(Task.FromResult(0));
 }
 public static int GetCountForType(DeviceType type)
 {
     return(Devices.Count(device => device.DeviceType == type));
 }
Beispiel #56
0
 public InputValueMapping(DeviceType deviceType, InputMappingType mappingType, int keyCode, float scale) : base(deviceType, mappingType, keyCode, scale)
 {
 }
Beispiel #57
0
        public void SendStatsEvent(StEvent e, int userId, int discussionId, int topicId, DeviceType devType)
        {
            if (peer == null || peer.PeerState != PeerStateValue.Connected)
            {
                return;
            }

            if (e == StEvent.LocalIgnorableEvent)
            {
                return;
            }

            var par = Serializers.WriteStatEventParams(e, userId, discussionId, topicId, devType);

            peer.OpCustom((byte)DiscussionOpCode.StatsEvent, par, true);
        }
Beispiel #58
0
        private static void UMCommonSetAppkeyAndChannel(string appkey, string channelId, DeviceType deviceType = DeviceType.Phone, string pushSecret = null)
        {
#if UNITY_EDITOR
#elif UNITY_IPHONE && USE_UMENG
            UmSDKSetWrapperTypeAndVersion("Unity", Version);
            UmSDKUMCommonSetAppkeyAndChannel(appkey, channelId);
#elif UNITY_ANDROID
            UMConfigure.CallStatic("setWraperType", "Unity", Version);
            UMConfigure.CallStatic("init", Context, appkey, channelId, (int)deviceType, pushSecret);
#endif
        }
Beispiel #59
0
        public IPoweredUpDevice CreateConnected(DeviceType deviceType, ILegoWirelessProtocol protocol, byte hubId, byte portId)
        {
            var type = GetTypeFromDeviceType(deviceType);

            return((type == null) ? new DynamicDevice(protocol, hubId, portId) : (IPoweredUpDevice)ActivatorUtilities.CreateInstance(_serviceProvider, type, protocol, hubId, portId));
        }
 private static extern int SdkShellInitialSource(ref IntPtr hDevice, DeviceType dwDeviceType, ModalType dwModal, uint dwVersion);