/*public static bool GetDeviceByClass(String DeviceInterfaceGUID) { IntPtr IntPtrBuffer = Marshal.AllocHGlobal(BUFFER_SIZE); Win32Wrapper.WinErrors LastError; bool Status = false; Guid DeviceGUID = new Guid(DeviceInterfaceGUID); try { //Get a handle to a device information set that contains all installed devices that support the Device Infomation Interface (GUID) IntPtr h = Win32Wrapper.SetupDiGetClassDevs(ref DeviceGUID, IntPtr.Zero, IntPtr.Zero, (uint)(Win32Wrapper.DIGCF.DIGCF_PRESENT | Win32Wrapper.DIGCF.DIGCF_DEVICEINTERFACE)); if (h.ToInt32() != INVALID_HANDLE_VALUE) { bool Success = true; uint i = 0; UInt32 RequiredSize = 0; while (Success) { //Create a Device Interface Data structure Win32Wrapper.SP_DEVICE_INTERFACE_DATA DeviceInterfaceData = new Win32Wrapper.SP_DEVICE_INTERFACE_DATA(); DeviceInterfaceData.cbSize = (uint)Marshal.SizeOf(DeviceInterfaceData); //Start the enumeration Success = Win32Wrapper.SetupDiEnumDeviceInterfaces(h, IntPtr.Zero, ref DeviceGUID, i, ref DeviceInterfaceData); if (!Success) { LastError = (Win32Wrapper.WinErrors)Marshal.GetLastWin32Error(); if (LastError == Win32Wrapper.WinErrors.ERROR_NO_MORE_ITEMS) { Status = false; break; } else { throw new Exception("Error enumerating devices!"); } } //Create a Device Info Data structure Win32Wrapper.SP_DEVINFO_DATA DeviceInfoData = new Win32Wrapper.SP_DEVINFO_DATA(); DeviceInfoData.cbSize = (uint)Marshal.SizeOf(DeviceInfoData); //Success = Win32Wrapper.SetupDiGetDeviceInterfaceDetail(h, ref DeviceInterfaceData, ref IntPtr.Zero, 0, out RequiredSize, ref IntPtr.Zero); //Create a Device Interface Detail Data structure Win32Wrapper.SP_DEVICE_INTERFACE_DETAIL_DATA DeviceInterfaceDetailData = new Win32Wrapper.SP_DEVICE_INTERFACE_DETAIL_DATA(); if (IntPtr.Size == 8) //For 64 bit operating systems DeviceInterfaceDetailData.cbSize = 8; else DeviceInterfaceDetailData.cbSize = (uint)(4 + Marshal.SystemDefaultCharSize); //For 32 bit systems Success = Win32Wrapper.SetupDiGetDeviceInterfaceDetail(h, ref DeviceInterfaceData, ref DeviceInterfaceDetailData, BUFFER_SIZE, out RequiredSize, ref DeviceInfoData); if (!Success) { throw new Exception("Error enumerating devices!"); } //Is this Port a USB Port? Ask the parent, then it's parent and so on UInt32 StartingDevice = DeviceInfoData.DevInst; Win32Wrapper.CRErrorCodes CRResult; bool IsRemainDevices = true; while(IsRemainDevices) { UInt32 hParentDevice = 0; CRResult = (Win32Wrapper.CRErrorCodes)Win32Wrapper.CM_Get_Parent(out hParentDevice, StartingDevice, 0); if (CRResult == Win32Wrapper.CRErrorCodes.CR_NO_SUCH_DEVNODE) { IsRemainDevices = true;//We hit the top of the PNP tree break; } if (CRResult != Win32Wrapper.CRErrorCodes.CR_SUCCESS) { throw new Exception("Error calling CM_Get_Parent: " + CRResult.ToString()); } if (IsRemainDevices) { CRResult = (Win32Wrapper.CRErrorCodes)Win32Wrapper.CM_Get_Device_ID(hParentDevice, IntPtrBuffer, BUFFER_SIZE, 0); if (CRResult != Win32Wrapper.CRErrorCodes.CR_SUCCESS) { throw new Exception("Error calling CM_Get_Device_ID: " + CRResult.ToString()); } String DeviceID = Marshal.PtrToStringAuto(IntPtrBuffer); if (DeviceID.StartsWith("USB\\")) { Status = true; } } //Do the next parent StartingDevice = hParentDevice; } //End of while(IsRemainDevices) i++; } //End of while (Success) } //End of if (h.ToInt32() != INVALID_HANDLE_VALUE) Win32Wrapper.SetupDiDestroyDeviceInfoList(h); //Clean up the old structure we no longer need. return Status; } catch (Exception ex) { throw ex; } finally { Marshal.FreeHGlobal(IntPtrBuffer); } }*/ /// <summary> /// Enumerate all USB devices and look for the device whose VID and PID are provided. /// </summary> /// <param name="VID">The Vendor ID of the USB Device.</param> /// <param name="PID">The Product ID of the USB Device.</param> /// <param name="DP">A Device Properties structure.</param> /// <param name="GetCOMPort">Set to True to retrieve the COM Port number if the Device is emulating a Serial Port.</param> /// <returns>True the Device is found.</returns> public static bool GetUSBDevice(UInt32 VID, UInt32 PID, ref DeviceProperties DP, bool GetCOMPort) { IntPtr IntPtrBuffer = Marshal.AllocHGlobal(BUFFER_SIZE); IntPtr h = IntPtr.Zero; Win32Wrapper.WinErrors LastError; bool Status = false; try { string DevEnum = "USB"; string ExpectedDeviceID = "VID_" + VID.ToString("X4") + "&" + "PID_" + PID.ToString("X4"); ExpectedDeviceID = ExpectedDeviceID.ToLowerInvariant(); h = Win32Wrapper.SetupDiGetClassDevs(IntPtr.Zero, DevEnum, IntPtr.Zero, (int)(Win32Wrapper.DIGCF.DIGCF_PRESENT | Win32Wrapper.DIGCF.DIGCF_ALLCLASSES)); if (h.ToInt32() != INVALID_HANDLE_VALUE) { bool Success = true; uint i = 0; while (Success) { if (Success) { UInt32 RequiredSize = 0; UInt32 RegType = 0; IntPtr Ptr = IntPtr.Zero; //Create a Device Info Data structure Win32Wrapper.SP_DEVINFO_DATA DevInfoData = new Win32Wrapper.SP_DEVINFO_DATA(); DevInfoData.cbSize = (uint)Marshal.SizeOf(DevInfoData); Success = Win32Wrapper.SetupDiEnumDeviceInfo(h, i, ref DevInfoData); if (Success) { //Get the required buffer size //First query for the size of the hardware ID, so we can know how big a buffer to allocate for the data. Win32Wrapper.SetupDiGetDeviceRegistryProperty(h, ref DevInfoData, (UInt32)Win32Wrapper.SPDRP.SPDRP_HARDWAREID, ref RegType, IntPtr.Zero, 0, ref RequiredSize); LastError = (Win32Wrapper.WinErrors)Marshal.GetLastWin32Error(); if (LastError == Win32Wrapper.WinErrors.ERROR_INSUFFICIENT_BUFFER) { if (RequiredSize > BUFFER_SIZE) { Status = false; } else { if (Win32Wrapper.SetupDiGetDeviceRegistryProperty(h, ref DevInfoData, (UInt32)Win32Wrapper.SPDRP.SPDRP_HARDWAREID, ref RegType, IntPtrBuffer, BUFFER_SIZE, ref RequiredSize)) { string HardwareID = Marshal.PtrToStringAuto(IntPtrBuffer); HardwareID = HardwareID.ToLowerInvariant(); if (HardwareID.Contains(ExpectedDeviceID)) { Status = true; //Found device if (Win32Wrapper.SetupDiGetDeviceRegistryProperty(h, ref DevInfoData, (UInt32)Win32Wrapper.SPDRP.SPDRP_FRIENDLYNAME, ref RegType, IntPtrBuffer, BUFFER_SIZE, ref RequiredSize)) { DP.FriendlyName = Marshal.PtrToStringAuto(IntPtrBuffer); } if (Win32Wrapper.SetupDiGetDeviceRegistryProperty(h, ref DevInfoData, (UInt32)Win32Wrapper.SPDRP.SPDRP_DEVTYPE, ref RegType, IntPtrBuffer, BUFFER_SIZE, ref RequiredSize)) { DP.DeviceType = Marshal.PtrToStringAuto(IntPtrBuffer); } if (Win32Wrapper.SetupDiGetDeviceRegistryProperty(h, ref DevInfoData, (UInt32)Win32Wrapper.SPDRP.SPDRP_CLASS, ref RegType, IntPtrBuffer, BUFFER_SIZE, ref RequiredSize)) { DP.DeviceClass = Marshal.PtrToStringAuto(IntPtrBuffer); } if (Win32Wrapper.SetupDiGetDeviceRegistryProperty(h, ref DevInfoData, (UInt32)Win32Wrapper.SPDRP.SPDRP_MFG, ref RegType, IntPtrBuffer, BUFFER_SIZE, ref RequiredSize)) { DP.DeviceManufacturer = Marshal.PtrToStringAuto(IntPtrBuffer); } if (Win32Wrapper.SetupDiGetDeviceRegistryProperty(h, ref DevInfoData, (UInt32)Win32Wrapper.SPDRP.SPDRP_LOCATION_INFORMATION, ref RegType, IntPtrBuffer, BUFFER_SIZE, ref RequiredSize)) { DP.DeviceLocation = Marshal.PtrToStringAuto(IntPtrBuffer); } if (Win32Wrapper.SetupDiGetDeviceRegistryProperty(h, ref DevInfoData, (UInt32)Win32Wrapper.SPDRP.SPDRP_LOCATION_PATHS, ref RegType, IntPtrBuffer, BUFFER_SIZE, ref RequiredSize)) { DP.DevicePath = Marshal.PtrToStringAuto(IntPtrBuffer); } if (Win32Wrapper.SetupDiGetDeviceRegistryProperty(h, ref DevInfoData, (UInt32)Win32Wrapper.SPDRP.SPDRP_PHYSICAL_DEVICE_OBJECT_NAME, ref RegType, IntPtrBuffer, BUFFER_SIZE, ref RequiredSize)) { DP.DevicePhysicalObjectName = Marshal.PtrToStringAuto(IntPtrBuffer); } if (Win32Wrapper.SetupDiGetDeviceRegistryProperty(h, ref DevInfoData, (UInt32)Win32Wrapper.SPDRP.SPDRP_DEVICEDESC, ref RegType, IntPtrBuffer, BUFFER_SIZE, ref RequiredSize)) { DP.DeviceDescription = Marshal.PtrToStringAuto(IntPtrBuffer); } if (GetCOMPort) { //Open the Device Parameters Key of the device IntPtr hDeviceRegistryKey; hDeviceRegistryKey = Win32Wrapper.SetupDiOpenDevRegKey(h, ref DevInfoData, (UInt32)Win32Wrapper.DICS_FLAG.DICS_FLAG_GLOBAL, 0, (UInt32)Win32Wrapper.DIREG.DIREG_DEV, (UInt32)Win32Wrapper.REGKEYSECURITY.KEY_READ); if (hDeviceRegistryKey.ToInt32() == INVALID_HANDLE_VALUE) { LastError = (Win32Wrapper.WinErrors)Marshal.GetLastWin32Error(); break; //throw new Exception("Error opening the Registry: " + LastError.ToString()); } else { UInt32 Type = 0; System.Text.StringBuilder Data = new System.Text.StringBuilder(BUFFER_SIZE); UInt32 Size = (UInt32)Data.Capacity; int Result; Result = Win32Wrapper.RegQueryValueEx(hDeviceRegistryKey, "PortName", 0, out Type, Data, ref Size); if (Result == (int)Win32Wrapper.WinErrors.ERROR_SUCCESS) { DP.COMPort = Data.ToString(); } //Close Registry Win32Wrapper.RegCloseKey(hDeviceRegistryKey); } } break; } else { Status = false; } //End of if (HardwareID.Contains(ExpectedDeviceID)) } } //End of if (RequiredSize > BUFFER_SIZE) } //End of if (LastError == Win32Wrapper.WinErrors.ERROR_INSUFFICIENT_BUFFER) } // End of if (Success) } // End of if (Success) else { LastError = (Win32Wrapper.WinErrors)Marshal.GetLastWin32Error(); Status = false; } i++; } // End of while (Success) } //End of if (h.ToInt32() != INVALID_HANDLE_VALUE) return Status; } catch (Exception ex) { throw ex; } finally { Win32Wrapper.SetupDiDestroyDeviceInfoList(h); //Clean up the old structure we no longer need. Marshal.FreeHGlobal(IntPtrBuffer); } }
/// <summary> /// Gets the profile settings. /// </summary> /// <param name="deviceProperties">The device properties.</param> /// <returns>The TranscodeSettings for the device</returns> public static TranscodeSettings[] GetProfileSettings(DeviceProperties deviceProperties) { foreach (var profile in PlayToConfiguration.Profiles) { if (!string.IsNullOrEmpty(profile.FriendlyName)) { if (!string.Equals(deviceProperties.Name, profile.FriendlyName, StringComparison.OrdinalIgnoreCase)) continue; } if (!string.IsNullOrEmpty(profile.ModelNumber)) { if (!string.Equals(deviceProperties.ModelNumber, profile.ModelNumber, StringComparison.OrdinalIgnoreCase)) continue; } if (!string.IsNullOrEmpty(profile.ModelName)) { if (!string.Equals(deviceProperties.ModelName, profile.ModelName, StringComparison.OrdinalIgnoreCase)) continue; } deviceProperties.DisplayName = profile.Name; deviceProperties.ClientType = profile.ClientType; return profile.TranscodeSettings; } // Since we don't have alot of info about different devices we go down the safe // route abd use the default transcoding settings if no profile exist return GetDefaultTranscodingSettings(); }
public DeviceProperties GetExistingDeviceProperties(Guid deviceUID) { var existingDeviceProp = GetExistingDevice(deviceUID); if (existingDeviceProp == null) { logger.LogInformation($"Device {deviceUID.ToString()} Doesn't Exist"); return(null); } var device = new DeviceProperties { DeviceSerialNumber = existingDeviceProp.SerialNumber, DeviceState = ((DeviceStateEnum)Enum.Parse(typeof(DeviceStateEnum), existingDeviceProp.fk_DeviceStatusID.ToString())).ToString(), DeviceType = deviceTypesCache.Where(x => x.Value.DeviceTypeID == existingDeviceProp.fk_DeviceTypeID).First().Key, CellModemIMEI = existingDeviceProp.CellModemIMEI, CellularFirmwarePartnumber = existingDeviceProp.CellularFirmwarePartnumber, DataLinkType = existingDeviceProp.DataLinkType, DeregisteredUTC = existingDeviceProp.DeregisteredUTC, DevicePartNumber = existingDeviceProp.DevicePartNumber, DeviceUID = existingDeviceProp.DeviceUID.ToString(), FirmwarePartNumber = existingDeviceProp.FirmwarePartNumber, GatewayFirmwarePartNumber = existingDeviceProp.GatewayFirmwarePartNumber, MainboardSoftwareVersion = existingDeviceProp.MainboardSoftwareVersion, ModuleType = existingDeviceProp.ModuleType, NetworkFirmwarePartnumber = existingDeviceProp.NetworkFirmwarePartnumber, SatelliteFirmwarePartnumber = existingDeviceProp.SatelliteFirmwarePartnumber }; return(device); }
internal static string GetSourceType(this DeviceProperties props) { switch (props.Type) { case 1: return("Line Power"); case 2: return("Battery"); case 3: return("UPS"); case 4: return("Monitor"); case 5: return("Mouse"); case 8: return("Phone"); default: return("Unknown"); } }
public IActionResult GetDeviceDetailsByDeviceUID(Guid deviceUID) { var deviceData = new DeviceProperties(); try { logger.LogInformation($"Get DeviceDetails called for {deviceUID}"); var userGuid = Utils.GetUserContext(Request); if (userGuid == null || deviceService.ValidateAuthorizedCustomerByDevice(userGuid.Value, deviceUID)) { logger.LogInformation(string.Format("Unauthorized User Access-Get DeviceDetails called for {0}", deviceUID)); return(BadRequest("Unauthorized User Access")); } deviceData = deviceService.GetExistingDeviceProperties(deviceUID); if (deviceData != null) { if (PLDeviceTypes.Contains(deviceData.DeviceType.ToLower(), StringComparer.InvariantCultureIgnoreCase)) { deviceData.RadioFirmwarePartNumber = deviceData.FirmwarePartNumber; deviceData.FirmwarePartNumber = null; } return(Ok(deviceData)); } else { return(BadRequest("Device Doesn't Exist")); } } catch (Exception ex) { logger.LogError("Get DeviceDetails threw an exception", ex); return(StatusCode((int)HttpStatusCode.InternalServerError, ex.Message)); } }
private static void ApplyPropertyValueModels( DeviceProperties deviceProperties, IEnumerable <DevicePropertyValueModel> devicePropertyValueModels) { object[] args; TypeConverter converter; Type devicePropertiesType; Dictionary <string, DevicePropertyMetadata> devicePropertyIndex; Dictionary <string, PropertyInfo> propIndex; PropertyInfo propInfo; DevicePropertyMetadata propMetadata; MethodInfo setter; devicePropertyIndex = GetDevicePropertyConfiguration().ToDictionary(t => t.Name); devicePropertiesType = deviceProperties.GetType(); propIndex = devicePropertiesType.GetProperties().ToDictionary(t => t.Name); args = new object[1]; foreach (DevicePropertyValueModel propVal in devicePropertyValueModels) { if ((propVal == null) || string.IsNullOrEmpty(propVal.Name)) { continue; } // Pass through properties that don't have a specified // configuration. if (devicePropertyIndex.TryGetValue(propVal.Name, out propMetadata) && !propMetadata.IsEditable) { continue; } if (!propIndex.TryGetValue(propVal.Name, out propInfo) || ((setter = propInfo.GetSetMethod()) == null) || ((converter = TypeDescriptor.GetConverter(propInfo.PropertyType)) == null)) { continue; } try { args[0] = converter.ConvertFromString(propVal.Value); } catch (NotSupportedException ex) { throw new InvalidOperationException( string.Format( CultureInfo.InvariantCulture, "Unable to assign value, \"{0},\" to Device property, {1}.", propVal.Value, propInfo.Name), ex); } setter.Invoke(deviceProperties, args); } }
public async Task UpdateListAsyncTest() { var mockStorageAdapterClient = new Mock <IStorageAdapterClient>(); var mockDevices = new Mock <IDevices>(); var cache = new DeviceProperties( mockStorageAdapterClient.Object, new ServicesConfig(), new Logger("UnitTest", LogLevel.Debug), mockDevices.Object); var oldCacheValue = new DevicePropertyServiceModel { Rebuilding = false, Tags = new HashSet <string> { "c", "a", "y", "z" }, Reported = new HashSet <string> { "1", "9", "2", "3" } }; var cachePatch = new DevicePropertyServiceModel { Tags = new HashSet <string> { "a", "y", "z", "@", "#" }, Reported = new HashSet <string> { "9", "2", "3", "11", "12" } }; var newCacheValue = new DevicePropertyServiceModel { Tags = new HashSet <string> { "c", "a", "y", "z", "@", "#" }, Reported = new HashSet <string> { "1", "9", "2", "3", "12", "11" } }; mockStorageAdapterClient .Setup(m => m.GetAsync(It.IsAny <string>(), It.IsAny <string>())) .Returns(() => Task.FromResult(new ValueApiModel { Data = JsonConvert.SerializeObject(oldCacheValue) })); mockStorageAdapterClient .Setup(m => m.UpdateAsync(It.IsAny <string>(), It.IsAny <string>(), It.IsAny <string>(), It.IsAny <string>())) .Returns(() => Task.FromResult(new ValueApiModel { Data = JsonConvert.SerializeObject(newCacheValue) })); var result = await cache.UpdateListAsync(cachePatch); Assert.True(result.Tags.SetEquals(newCacheValue.Tags)); Assert.True(result.Reported.SetEquals(newCacheValue.Reported)); }
/// <summary> /// 上报读属性响应 /// </summary> /// <param name="requestId">请求id,响应的请求id必须和请求的一致</param> /// <param name="services">服务属性</param> public void RespondPropsGet(string requestId, List <ServiceProperty> services) { DeviceProperties deviceProperties = new DeviceProperties(); deviceProperties.services = services; Report(new PubMessage(CommonTopic.TOPIC_SYS_PROPERTIES_GET_RESPONSE + "=" + requestId, deviceProperties)); }
private async void sendDeviceMetaData() { DeviceProperties device = new DeviceProperties(); Thermostat thermostat = new Thermostat(); thermostat.ObjectType = "DeviceInfo"; thermostat.IsSimulatedDevice = false; thermostat.Version = "1.0"; device.HubEnabledState = true; device.DeviceID = deviceId; device.Manufacturer = "Raspberry"; device.ModelNumber = "Pi2"; device.SerialNumber = "5849735293875"; device.FirmwareVersion = "10"; device.Platform = "Windows 10"; device.Processor = "RaspBerry"; device.InstalledRAM = "976 MB"; device.DeviceState = "normal"; string pos = await GetGeoLocFromWeb(); var nloc = pos.IndexOf("loc"); var sub01 = pos.Substring(nloc + 7); string location = sub01.Substring(0, sub01.IndexOf('"')); var x = location.Split(','); device.Latitude = System.Convert.ToDouble(x[0]); device.Longitude = System.Convert.ToDouble(x[1]); thermostat.DeviceProperties = device; Command TriggerAlarm = new Command(); TriggerAlarm.Name = "TriggerAlarm"; CommandParameter param = new CommandParameter(); param.Name = "Message"; param.Type = "String"; TriggerAlarm.Parameters = new CommandParameter[] { param }; thermostat.Commands = new Command[] { TriggerAlarm }; try { var msg = new Message(Serialize(thermostat)); if (deviceClient != null) { await deviceClient.SendEventAsync(msg); } } catch (System.Exception e) { Debug.Write("Exception while sending device meta data :\n" + e.Message.ToString()); } Debug.Write("Sent meta data to IoT Suite\n" + hostName); }
public Guid GetGUIDPropertyValue(Guid formatId, uint positionId) { _tagpropertykey property = CreateProperty(formatId, positionId); Guid propertyValue; DeviceProperties.GetGuidValue(ref property, out propertyValue); return(propertyValue); }
public string GetStringPropertyValue(Guid formatId, uint positionId) { _tagpropertykey property = CreateProperty(formatId, positionId); string propertyValue; DeviceProperties.GetStringValue(ref property, out propertyValue); return(propertyValue); }
public uint GetUIntPropertyValue(Guid formatId, uint positionId) { _tagpropertykey property = CreateProperty(formatId, positionId); uint propertyValue; DeviceProperties.GetUnsignedIntegerValue(ref property, out propertyValue); return(propertyValue); }
private void EditDeviceButton_Tapped(object sender, TappedRoutedEventArgs e) { var selectedDevice = (Model.Device)DevicesView.SelectedItem; SetSelectionEnabled(false); DeviceProperties.Operation = Controls.FormOperation.Edit; DeviceProperties.Device = selectedDevice ?? throw new Exception("Edit device button should not be active when no device is selected"); DeviceProperties.Visibility = Visibility.Visible; DeviceProperties.SetInitialFocus(); }
private async void sendDeviceMetaData() { DeviceProperties device = new DeviceProperties(); Thermostat thermostat = new Thermostat(); thermostat.ObjectType = "DeviceInfo"; thermostat.IsSimulatedDevice = false; thermostat.Version = "1.0"; device.HubEnabledState = true; device.DeviceID = deviceId; device.Manufacturer = "Microsoft"; device.ModelNumber = "Lumia950"; device.SerialNumber = "5849735293875"; device.FirmwareVersion = "10"; device.Platform = "Windows 10"; device.Processor = "SnapDragon"; device.InstalledRAM = "3GB"; device.DeviceState = "normal"; Geolocator geolocator = new Geolocator(); Geoposition pos = await geolocator.GetGeopositionAsync(); device.Latitude = (float)pos.Coordinate.Point.Position.Latitude; device.Longitude = (float)pos.Coordinate.Point.Position.Longitude; thermostat.DeviceProperties = device; Command TriggerAlarm = new Command(); TriggerAlarm.Name = "TriggerAlarm"; CommandParameter param = new CommandParameter(); param.Name = "Message"; param.Type = "String"; TriggerAlarm.Parameters = new CommandParameter[] { param }; thermostat.Commands = new Command[] { TriggerAlarm }; try { var msg = new Message(Serialize(thermostat)); if (deviceClient != null) { await deviceClient.SendEventAsync(msg); } } catch (System.Exception e) { Debug.Write("Exception while sending device meta data :\n" + e.Message.ToString()); } Debug.Write("Sent meta data to IoT Suite\n" + hostName); }
/// <summary> /// Initialize the device properties for a new device. /// </summary> /// <param name="device"></param> /// <param name="deviceId"></param> /// <param name="isSimulated"></param> /// <returns></returns> private static void InitializeDeviceProperties(DeviceModel device, string deviceId, bool isSimulated) { DeviceProperties deviceProps = new DeviceProperties(); deviceProps.DeviceID = deviceId; deviceProps.HubEnabledState = null; deviceProps.CreatedTime = DateTime.UtcNow; deviceProps.DeviceState = "normal"; deviceProps.UpdatedTime = null; device.DeviceProperties = deviceProps; }
public async Task TryRecreateListAsyncSkipByTimeTest() { var mockStorageAdapterClient = new Mock <IStorageAdapterClient>(); var mockDevices = new Mock <IDevices>(); var cache = new DeviceProperties( mockStorageAdapterClient.Object, new AppConfig { Global = new GlobalConfig(), IotHubManagerService = new IotHubManagerServiceConfig { DevicePropertiesCache = new DevicePropertiesCacheConfig { Ttl = 60, }, }, }, new Mock <ILogger <DeviceProperties> >().Object, mockDevices.Object); mockStorageAdapterClient .Setup(x => x.GetAsync( It.Is <string>(s => s == DeviceProperties.CacheCollectioId), It.Is <string>(s => s == DeviceProperties.CacheKey))) .ReturnsAsync(new ValueApiModel { ETag = this.rand.NextString(), Data = JsonConvert.SerializeObject(new DevicePropertyServiceModel { Rebuilding = false, Tags = new HashSet <string> { "tags.IsSimulated" }, }), Metadata = new Dictionary <string, string> { { "$modified", DateTimeOffset.UtcNow.ToString(CultureInfo.InvariantCulture) }, }, }); var result = await cache.TryRecreateListAsync(); Assert.False(result); mockStorageAdapterClient .Verify( x => x.GetAsync( It.Is <string>(s => s == DeviceProperties.CacheCollectioId), It.Is <string>(s => s == DeviceProperties.CacheKey)), Times.Once); }
public void ItDoesntRegisterWhenTheFeatureIsDisabled() { // Arrange this.servicesConfig.SetupGet(x => x.DeviceTwinEnabled).Returns(false); var target2 = new DeviceProperties(this.servicesConfig.Object, this.logger.Object); // Act target2.RegisterChangeUpdateAsync(this.sdkClient.Object, DEVICE_ID, null).CompleteOrTimeout(); // Assert this.sdkClient.Verify(x => x.SetDesiredPropertyUpdateCallbackAsync( It.IsAny <DesiredPropertyUpdateCallback>(), It.IsAny <object>()), Times.Never); }
/// <summary> /// Initialize the device properties for a new device. /// </summary> /// <param name="device"></param> /// <param name="deviceId"></param> /// <param name="isSimulated"></param> /// <returns></returns> private static void InitializeDeviceProperties(DeviceModel device, string deviceId, bool isSimulated) { var deviceProps = new DeviceProperties { DeviceID = deviceId, HubEnabledState = null, CreatedTime = DateTime.UtcNow, DeviceState = "normal", UpdatedTime = null }; device.DeviceProperties = deviceProps; }
internal VpnSiteData(string id, string name, string type, string location, IDictionary <string, string> tags, string etag, WritableSubResource virtualWan, DeviceProperties deviceProperties, string ipAddress, string siteKey, AddressSpace addressSpace, BgpSettings bgpProperties, ProvisioningState?provisioningState, bool?isSecuritySite, IList <VpnSiteLinkData> vpnSiteLinks, O365PolicyProperties o365Policy) : base(id, name, type, location, tags) { Etag = etag; VirtualWan = virtualWan; DeviceProperties = deviceProperties; IPAddress = ipAddress; SiteKey = siteKey; AddressSpace = addressSpace; BgpProperties = bgpProperties; ProvisioningState = provisioningState; IsSecuritySite = isSecuritySite; VpnSiteLinks = vpnSiteLinks; O365Policy = o365Policy; }
/// <summary> /// Executes the SetLEDState action. /// </summary> /// <param name="desiredLedState">In value for the DesiredLEDState action parameter.</param> public async Task SetLedState(LedStateEnum desiredLedState) { var loIn = new object[1]; loIn[0] = DeviceProperties.ToStringLedState(desiredLedState); var action = new SoapAction { ArgNames = new[] { "DesiredLEDState" }, Name = CsActionSetLedState, ExpectedReplyCount = 0 }; await InvokeActionAsync(action, loIn); }
public override List <Error> Validate(List <Error> errors) { RequireString(this, x => x.DeviceId, 14, errors, "A"); ValidateString(this, x => x.DeviceDesignator, 32, errors, "B"); ValidateString(this, x => x.DeviceSoftwareVersion, 32, errors, "C"); RequireString(this, x => x.ClientNAME, 16, errors, "D"); //Hex validation could be improved upon ValidateString(this, x => x.DeviceSerialNumber, 32, errors, "E"); RequireString(this, x => x.DeviceStructureLabel, 32, errors, "F"); //Hex validation could be improved upon RequireString(this, x => x.DeviceLocalizationLabel, 32, errors, "G"); //Hex validation could be improved upon DeviceElements.ForEach(i => i.Validate(errors)); DeviceProcessDatas.ForEach(i => i.Validate(errors)); DeviceProperties.ForEach(i => i.Validate(errors)); DeviceValuePresentations.ForEach(i => i.Validate(errors)); return(errors); }
private void AddDeviceButton_Tapped(object sender, TappedRoutedEventArgs e) { var selectedSite = SitesView.SelectedItem as Model.Site; if (selectedSite == null) { throw new Exception("It should not be possible to select add device if no site is selected"); } SetSelectionEnabled(false); DeviceProperties.Operation = Controls.FormOperation.Add; DeviceProperties.Device = null; DeviceProperties.ClearForm(); DeviceProperties.SiteId = selectedSite.Id; DeviceProperties.Visibility = Visibility.Visible; DeviceProperties.SetInitialFocus(); }
public async Task TryRecreateListAsyncSkipByTimeTest() { var mockStorageAdapterClient = new Mock <IStorageAdapterClient>(); var mockDevices = new Mock <IDevices>(); var cache = new DeviceProperties( mockStorageAdapterClient.Object, new ServicesConfig { DevicePropertiesTTL = 60 }, new Logger("UnitTest", LogLevel.Debug), mockDevices.Object); mockStorageAdapterClient .Setup(x => x.GetAsync( It.Is <string>(s => s == DeviceProperties.CACHE_COLLECTION_ID), It.Is <string>(s => s == DeviceProperties.CACHE_KEY))) .ReturnsAsync(new ValueApiModel { ETag = this.rand.NextString(), Data = JsonConvert.SerializeObject(new DevicePropertyServiceModel { Rebuilding = false, Tags = new HashSet <string> { "tags.IsSimulated" } }), Metadata = new Dictionary <string, string> { { "$modified", DateTimeOffset.UtcNow.ToString(CultureInfo.InvariantCulture) } } }); var result = await cache.TryRecreateListAsync(); Assert.False(result); mockStorageAdapterClient .Verify(x => x.GetAsync( It.Is <string>(s => s == DeviceProperties.CACHE_COLLECTION_ID), It.Is <string>(s => s == DeviceProperties.CACHE_KEY)), Times.Once); }
public async Task <DeviceModel> UpdateDeviceFromDeviceInfoPacketAsync(DeviceModel device) { if (device == null) { throw new ArgumentNullException("device"); } // Get original device document DeviceModel existingDevice = await this.GetDeviceAsync(device.IoTHub.ConnectionDeviceId); SupportedMethodsHelper.AddSupportedMethodsFromReportedProperty(device, existingDevice.Twin); // Save the command history, original created date, and system properties (if any) of the existing device if (existingDevice.DeviceProperties != null) { DeviceProperties deviceProperties = device.DeviceProperties; deviceProperties.CreatedTime = existingDevice.DeviceProperties.CreatedTime; existingDevice.DeviceProperties = deviceProperties; } device.CommandHistory = existingDevice.CommandHistory; // Copy the existing system properties, or initialize them if they do not exist if (existingDevice.SystemProperties != null) { device.SystemProperties = existingDevice.SystemProperties; } else { device.SystemProperties = null; } // If there is Telemetry or Command objects from device, replace instead of merge if (device.Telemetry != null) { existingDevice.Telemetry = device.Telemetry; } if (device.Commands != null) { existingDevice.Commands = device.Commands; } return(await _deviceRegistryCrudRepository.UpdateDeviceAsync(existingDevice)); }
public async Task <DeviceProperties> GetDeviceInfoAsync(string deviceName) { ConsoleHelper.WriteStep("Fetching device..."); var client = new HttpClient(); var result = new DeviceProperties(); try { client.MaxResponseContentBufferSize = 999999; client.DefaultRequestHeaders.Add("Authorization", string.Format("Bearer {0}", bearerToken.access_token)); var uri = $"{Constants.VisionApiUri}/api/device-management/get-device-info/{deviceName.Trim()}"; ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12; HttpResponseMessage response = await client.GetAsync(uri); if (response.IsSuccessStatusCode) { var content = await response.Content.ReadAsStringAsync(); result = JsonConvert.DeserializeObject <DeviceProperties>(content); ConsoleHelper.WriteStepResult("Received device information"); } else { var content = await response.Content.ReadAsStringAsync(); ConsoleHelper.WriteError(string.Format("Fetch failed {0}", content)); } } catch (Exception ex) { ConsoleHelper.WriteException(ex); return(null); } finally { client.Dispose(); } return(result); }
/// <summary> /// Cross synchonize DeviceProperties and ReportedProperties /// </summary> /// <returns></returns> protected void CrossSyncProperties(TwinCollection patch, TwinCollection reported, bool regenerate) { var devicePropertiesType = DeviceProperties.GetType(); var reportedPairs = reported.AsEnumerableFlatten().ToDictionary(pair => pair.Key, pair => pair.Value); if (!regenerate) { // Overwrite regenerated DeviceProperties by current ReportedProperties foreach (var pair in reportedPairs) { string devicePropertyName = _propertyMapping.SingleOrDefault(p => p.Value == pair.Key).Key; if (string.IsNullOrWhiteSpace(devicePropertyName)) { continue; } try { DeviceProperties.SetProperty(devicePropertyName, pair.Value.Value); } catch { // Ignore any failure while overwriting the DeviceProperties } } } // Add missing DeviceProperties to ReportedProperties foreach (var property in devicePropertiesType.GetProperties()) { string reportedName; if (!_propertyMapping.TryGetValue(property.Name, out reportedName)) { continue; } var value = property.GetValue(DeviceProperties); if (regenerate || value != null && !reportedPairs.ContainsKey(reportedName)) { patch.Set(reportedName, value); } } }
public async Task GetListAsyncTest() { var mockStorageAdapterClient = new Mock <IStorageAdapterClient>(); var mockDevices = new Mock <IDevices>(); var cache = new DeviceProperties( mockStorageAdapterClient.Object, new Mock <AppConfig> { DefaultValue = DefaultValue.Mock }.Object, new Mock <ILogger <DeviceProperties> >().Object, mockDevices.Object); var cacheValue = new DevicePropertyServiceModel { Rebuilding = false, Tags = new HashSet <string> { "ccc", "aaaa", "yyyy", "zzzz" }, Reported = new HashSet <string> { "1111", "9999", "2222", "3333" }, }; mockStorageAdapterClient .Setup(m => m.GetAsync(It.IsAny <string>(), It.IsAny <string>())) .Returns(() => Task.FromResult(new ValueApiModel { Data = JsonConvert.SerializeObject(cacheValue) })); var result = await cache.GetListAsync(); Assert.Equal(result.Count, cacheValue.Tags.Count + cacheValue.Reported.Count); foreach (string tag in cacheValue.Tags) { Assert.Contains(result, s => s.Contains(tag)); } foreach (string reported in cacheValue.Reported) { Assert.Contains(result, s => s.Contains(reported)); } }
private void Identify_Click(object sender, RoutedEventArgs e) { // Setup our user properties: UserProperties userProps = new UserProperties(); userProps.UserId = "testuser_2"; userProps.ExtraProperties.Add("email", "*****@*****.**"); // Note that userProps.AppVersion has been automatically inferred from // the version of the calling assembly, but can be overriden here, e.g: // userProps.AppVersion = Assembly.GetExecutingAssembly().GetName().Version.ToString(); // Setup our device properties: DeviceProperties devProps = new DeviceProperties(); // It's a good idea to set a device ID, that way you can tell how many devices // a give user uses. Best way is to generate a device ID on first start and stash it // in the settings of the app devProps.DeviceId = "9818C32E-00E3-493D-837C-AD0C0D77748C"; AmplitudeService.Instance.Identify(userProps, devProps); }
internal static string GetDeviceState(this DeviceProperties props) { switch (props.State) { case 1: return("Charging"); case 2: return("Discharging"); case 3: return("Empty"); case 4: return("Fully Charged"); default: return("Unknown"); } }
/// <summary> /// Serializes this instance of <see cref="VmDisk" /> into a <see cref="Carbon.Json.JsonNode" />. /// </summary> /// <param name="container">The <see cref="Carbon.Json.JsonObject"/> container to serialize this object into. If the caller /// passes in <c>null</c>, a new instance will be created and returned to the caller.</param> /// <param name="serializationMode">Allows the caller to choose the depth of the serialization. See <see cref="Microsoft.Rest.ClientRuntime.SerializationMode"/>.</param> /// <returns> /// a serialized instance of <see cref="VmDisk" /> as a <see cref="Carbon.Json.JsonNode" />. /// </returns> public Carbon.Json.JsonNode ToJson(Carbon.Json.JsonObject container, Microsoft.Rest.ClientRuntime.SerializationMode serializationMode) { container = container ?? new Carbon.Json.JsonObject(); bool returnNow = false; BeforeToJson(ref container, ref returnNow); if (returnNow) { return(container); } AddIf(null != DataSourceReference ? (Carbon.Json.JsonNode)DataSourceReference.ToJson(null) : null, "data_source_reference", container.Add); AddIf(null != DeviceProperties ? (Carbon.Json.JsonNode)DeviceProperties.ToJson(null) : null, "device_properties", container.Add); AddIf(null != DiskSizeBytes ? (Carbon.Json.JsonNode) new Carbon.Json.JsonNumber((long)DiskSizeBytes) : null, "disk_size_bytes", container.Add); AddIf(null != DiskSizeMib ? (Carbon.Json.JsonNode) new Carbon.Json.JsonNumber((int)DiskSizeMib) : null, "disk_size_mib", container.Add); AddIf(null != Uuid ? (Carbon.Json.JsonNode) new Carbon.Json.JsonString(Uuid) : null, "uuid", container.Add); AddIf(null != VolumeGroupReference ? (Carbon.Json.JsonNode)VolumeGroupReference.ToJson(null) : null, "volume_group_reference", container.Add); AfterToJson(ref container); return(container); }
/// <summary> /// Gets the profile settings. /// </summary> /// <param name="deviceProperties">The device properties.</param> /// <returns>The TranscodeSettings for the device</returns> public static TranscodeSettings[] GetProfileSettings(DeviceProperties deviceProperties) { foreach (var profile in PlayToConfiguration.Profiles) { if (!string.IsNullOrEmpty(profile.FriendlyName)) { if (!string.Equals(deviceProperties.Name, profile.FriendlyName, StringComparison.OrdinalIgnoreCase)) { continue; } } if (!string.IsNullOrEmpty(profile.ModelNumber)) { if (!string.Equals(deviceProperties.ModelNumber, profile.ModelNumber, StringComparison.OrdinalIgnoreCase)) { continue; } } if (!string.IsNullOrEmpty(profile.ModelName)) { if (!string.Equals(deviceProperties.ModelName, profile.ModelName, StringComparison.OrdinalIgnoreCase)) { continue; } } deviceProperties.DisplayName = profile.Name; deviceProperties.ClientType = profile.ClientType; return(profile.TranscodeSettings); } // Since we don't have alot of info about different devices we go down the safe // route abd use the default transcoding settings if no profile exist return(GetDefaultTranscodingSettings()); }
private async void sendDeviceMetaData() { DeviceProperties device = new DeviceProperties(); Thermostat thermostat = new Thermostat(); thermostat.ObjectType = "DeviceInfo"; thermostat.IsSimulatedDevice = false; thermostat.Version = "1.0"; device.HubEnabledState = true; device.DeviceID = deviceId; device.Manufacturer = "Microsoft"; device.ModelNumber = "Lumia950"; device.SerialNumber = "5849735293875"; device.FirmwareVersion = "10"; device.Platform = "Windows 10"; device.Processor = "SnapDragon"; device.InstalledRAM = "3GB"; device.DeviceState = "normal"; Geolocator geolocator = new Geolocator(); Geoposition pos = await geolocator.GetGeopositionAsync(); device.Latitude = (float)pos.Coordinate.Point.Position.Latitude; device.Longitude = (float)pos.Coordinate.Point.Position.Longitude; thermostat.DeviceProperties = device; Command TriggerAlarm = new Command(); TriggerAlarm.Name = "TriggerAlarm"; CommandParameter param = new CommandParameter(); param.Name = "Message"; param.Type = "String"; TriggerAlarm.Parameters = new CommandParameter[] { param }; thermostat.Commands = new Command[] { TriggerAlarm }; try { var msg = new Message(Serialize(thermostat)); if (deviceClient != null) { await deviceClient.SendEventAsync(msg); } } catch (System.Exception e) { Debug.Write("Exception while sending device meta data :\n" + e.Message.ToString()); } Debug.Write("Sent meta data to IoT Suite\n" + hostName); }
public async Task TryRecreateListAsyncTest() { var mockStorageAdapterClient = new Mock <IStorageAdapterClient>(); var mockDevices = new Mock <IDevices>(); var cache = new DeviceProperties( mockStorageAdapterClient.Object, new AppConfig { Global = new GlobalConfig(), IotHubManagerService = new IotHubManagerServiceConfig { DevicePropertiesCache = new DevicePropertiesCacheConfig { Whitelist = "tags.*, reported.Type, reported.Config.*", Ttl = 3600, }, }, }, new Mock <ILogger <DeviceProperties> >().Object, mockDevices.Object); var etagOld = this.rand.NextString(); var etagLock = this.rand.NextString(); var etagNew = this.rand.NextString(); mockStorageAdapterClient .Setup(x => x.GetAsync( It.Is <string>(s => s == DeviceProperties.CacheCollectioId), It.Is <string>(s => s == DeviceProperties.CacheKey))) .ReturnsAsync(new ValueApiModel { ETag = etagOld, Data = JsonConvert.SerializeObject(new DevicePropertyServiceModel { Rebuilding = false, }), Metadata = new Dictionary <string, string> { { "$modified", (DateTimeOffset.UtcNow - TimeSpan.FromDays(1)).ToString(CultureInfo.InvariantCulture) }, }, }); mockDevices.Setup(x => x.GetDeviceTwinNamesAsync()) .ReturnsAsync(new DeviceTwinName { Tags = new HashSet <string> { "Building", "Group" }, ReportedProperties = new HashSet <string> { "Config.Interval", "otherProperty" }, }); mockStorageAdapterClient .Setup(x => x.UpdateAsync( It.Is <string>(s => s == DeviceProperties.CacheCollectioId), It.Is <string>(s => s == DeviceProperties.CacheKey), It.Is <string>(s => Rebuilding(s)), It.Is <string>(s => s == etagOld))) .ReturnsAsync(new ValueApiModel { ETag = etagLock, }); mockStorageAdapterClient .Setup(x => x.UpdateAsync( It.Is <string>(s => s == DeviceProperties.CacheCollectioId), It.Is <string>(s => s == DeviceProperties.CacheKey), It.Is <string>(s => !Rebuilding(s)), It.Is <string>(s => s == etagLock))) .ReturnsAsync(new ValueApiModel { ETag = etagNew, }); var expiredNames = new DeviceTwinName { Tags = new HashSet <string> { "Building", "Group", }, ReportedProperties = new HashSet <string> { "Type", "Config.Interval", "MethodStatus", "UpdateStatus", }, }; var result = await cache.TryRecreateListAsync(); Assert.True(result); mockStorageAdapterClient .Verify( x => x.GetAsync( It.Is <string>(s => s == DeviceProperties.CacheCollectioId), It.Is <string>(s => s == DeviceProperties.CacheKey)), Times.Once); mockDevices .Verify(x => x.GetDeviceTwinNamesAsync(), Times.Once); mockStorageAdapterClient .Verify( x => x.UpdateAsync( It.Is <string>(s => s == DeviceProperties.CacheCollectioId), It.Is <string>(s => s == DeviceProperties.CacheKey), It.Is <string>(s => Rebuilding(s)), It.Is <string>(s => s == etagOld)), Times.Once); }