Unity LocationServices not working on iOS - c#

I have a Unity 5.5.1f1 project that I am attempting to use the LocaitonServices to get the users current GPS Location. I am testing this script on physical android and iOS devices. LocationServices is returning a location when running the project on Android, but on iOS 10.2.1 it never returns a location. Is there anything specific that needs to enabled to use the device location on iOS? I am using the TestLocationService script from Location Service Docs:
using UnityEngine;
using System.Collections;
public class TestLocationService : MonoBehaviour
{
IEnumerator Start()
{
// First, check if user has location service enabled
if (!Input.location.isEnabledByUser)
yield break;
// Start service before querying location
Input.location.Start();
// Wait until service initializes
int maxWait = 20;
while (Input.location.status == LocationServiceStatus.Initializing && maxWait > 0)
{
yield return new WaitForSeconds(1);
maxWait--;
}
// Service didn't initialize in 20 seconds
if (maxWait < 1)
{
print("Timed out");
yield break;
}
// Connection has failed
if (Input.location.status == LocationServiceStatus.Failed)
{
print("Unable to determine device location");
yield break;
}
else
{
// Access granted and location value could be retrieved
print("Location: " + Input.location.lastData.latitude + " " + Input.location.lastData.longitude + " " + Input.location.lastData.altitude + " " + Input.location.lastData.horizontalAccuracy + " " + Input.location.lastData.timestamp);
}
// Stop service if there is no need to query location updates continuously
Input.location.Stop();
}
}
It is saying that Input.location.isEnabledByUser == false but Location services are enabled on my device. Note that when opening the app I was never prompted on my iOS device to allow location use, but I was on android.

Related

Access System Information Like CPU/GPU Temp/Usage/Freq C#

I want to know how to access to system information like CPU-GPU-RAM usage-temp-frequency and...
is there an easy way to do this? if not, can I use other softwares like HWiNFO to extract this informations ? Like An CMD App That Can Run from CMD And Return CPU Temp or Else.
News :
OK . I Found This But its throwing an exception that I don't Know What it is ! Here is Code From performancepsu.com :
using OpenHardwareMonitor.Hardware;
namespace Monitor
{
class Program
{
// CPU Temp
static float cpuTemp;
// CPU Usage
static float cpuUsage;
// CPU Power Draw (Package)
static float cpuPowerDrawPackage;
// CPU Frequency
static float cpuFrequency;
// GPU Temperature
static float gpuTemp;
// GPU Usage
static float gpuUsage;
// GPU Core Frequency
static float gpuCoreFrequency;
// GPU Memory Frequency
static float gpuMemoryFrequency;
/**
* Init OpenHardwareMonitor.dll Computer Object
**/
static Computer c = new Computer()
{
GPUEnabled = true,
CPUEnabled = true,
//RAMEnabled = true, // uncomment for RAM reports
//MainboardEnabled = true, // uncomment for Motherboard reports
//FanControllerEnabled = true, // uncomment for FAN Reports
//HDDEnabled = true, // uncomment for HDD Report
};
/**
* Pulls data from OHM
**/
static void ReportSystemInfo()
{
foreach (var hardware in c.Hardware)
{
if (hardware.HardwareType == HardwareType.CPU)
{
// only fire the update when found
hardware.Update();
// loop through the data
foreach (var sensor in hardware.Sensors)
if (sensor.SensorType == SensorType.Temperature && sensor.Name.Contains("CPU Package"))
{
// store
cpuTemp = sensor.Value.GetValueOrDefault();
// print to console
System.Diagnostics.Debug.WriteLine("cpuTemp: " + sensor.Value.GetValueOrDefault());
}
else if (sensor.SensorType == SensorType.Load && sensor.Name.Contains("CPU Total"))
{
// store
cpuUsage = sensor.Value.GetValueOrDefault();
// print to console
System.Diagnostics.Debug.WriteLine("cpuUsage: " + sensor.Value.GetValueOrDefault());
}
else if (sensor.SensorType == SensorType.Power && sensor.Name.Contains("CPU Package"))
{
// store
cpuPowerDrawPackage = sensor.Value.GetValueOrDefault();
// print to console
System.Diagnostics.Debug.WriteLine("CPU Power Draw - Package: " + sensor.Value.GetValueOrDefault());
}
else if (sensor.SensorType == SensorType.Clock && sensor.Name.Contains("CPU Core #1"))
{
// store
cpuFrequency = sensor.Value.GetValueOrDefault();
// print to console
System.Diagnostics.Debug.WriteLine("cpuFrequency: " + sensor.Value.GetValueOrDefault());
}
}
// Targets AMD & Nvidia GPUS
if (hardware.HardwareType == HardwareType.GpuAti || hardware.HardwareType == HardwareType.GpuNvidia)
{
// only fire the update when found
hardware.Update();
// loop through the data
foreach (var sensor in hardware.Sensors)
if (sensor.SensorType == SensorType.Temperature && sensor.Name.Contains("GPU Core"))
{
// store
gpuTemp = sensor.Value.GetValueOrDefault();
// print to console
System.Diagnostics.Debug.WriteLine("gpuTemp: " + sensor.Value.GetValueOrDefault());
}
else if (sensor.SensorType == SensorType.Load && sensor.Name.Contains("GPU Core"))
{
// store
gpuUsage = sensor.Value.GetValueOrDefault();
// print to console
System.Diagnostics.Debug.WriteLine("gpuUsage: " + sensor.Value.GetValueOrDefault());
}
else if (sensor.SensorType == SensorType.Clock && sensor.Name.Contains("GPU Core"))
{
// store
gpuCoreFrequency = sensor.Value.GetValueOrDefault();
// print to console
System.Diagnostics.Debug.WriteLine("gpuCoreFrequency: " + sensor.Value.GetValueOrDefault());
}
else if (sensor.SensorType == SensorType.Clock && sensor.Name.Contains("GPU Memory"))
{
// store
gpuMemoryFrequency = sensor.Value.GetValueOrDefault();
// print to console
System.Diagnostics.Debug.WriteLine("gpuMemoryFrequency: " + sensor.Value.GetValueOrDefault());
}
}
// ... you can access any other system information you want here
}
}
static void Main(string[] args)
{
c.Open();
// loop
while (true)
{
ReportSystemInfo();
}
}
}
}
And the Error is :
Unhandled exception. System.MissingMethodException: Method not found: 'System.Threading.Mutex System.Threading.Mutex.OpenExisting(System.String, System.Security.AccessControl.MutexRights)'.
at OpenHardwareMonitor.Hardware.Ring0.Open()
at OpenHardwareMonitor.Hardware.Computer.Open()
at Monitor.Program.Main(String[] args) in D:\VisualStudio\Monitor_Test\Monitor_Test\Program.cs:line 136
What Should I do ?
Use System.Management DLL to Query WMI.
look at this article :
https://ourcodeworld.com/articles/read/335/how-to-retrieve-the-cpu-s-temperature-with-c-in-winforms
OK . After a Long Time I Found the Solution. First Download .NET Framework SDK (I used 4.8) . Then Install it. Set Target Framework of Project to 4.8 in .csproj file :
<TargetFramework>net48</TargetFramework>
and Remove This Tags :
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
then add a manifest file to project and replace first tag with second :
<requestedExecutionLevel level="asInvoker" uiAccess="false" />
<requestedExecutionLevel level="requireAdministrator" uiAccess="false" />
THE END !
Output is :
CPU Usage : 2 %
CPU Temp : 46 °C
CPU Clock : 3520 MHz
GPU Usage : 0 %
GPU Temp : 36 °C
GPU Clock : 405 MHz
RAM Usage : 84 %

How do I find a map route with Azure IoT?

I am attempting to complete the first tutorial in the Azure IoT learning path but every time I try to make the device find a customer it says "Failed to find map route." in the console. I've followed all the steps, looked over the code and there's no troubleshooting answers for this particular error. The device is connected to my program it just cannot find the map route.
static void GetRoute(StateEnum newState)
{
// Set the state to ready, until the new route arrives.
state = StateEnum.ready;
var req = new RouteRequestDirections
{
Query = FormattableString.Invariant($"{currentLat},{currentLon}:{destinationLat},{destinationLon}")
};
var directions = azureMapsServices.GetRouteDirections(req).Result;
if (directions.Error != null || directions.Result == null)
{
// Handle any error.
redMessage("Failed to find map route");
}
else
{
int nPoints = directions.Result.Routes[0].Legs[0].Points.Length;
greenMessage($"Route found. Number of points = {nPoints}");
// Clear the path. Add two points for the start point and destination.
path = new double[nPoints + 2, 2];
int c = 0;
// Start with the current location.
path[c, 0] = currentLat;
path[c, 1] = currentLon;
++c;
// Retrieve the route and push the points onto the array.
for (var n = 0; n < nPoints; n++)
{
var x = directions.Result.Routes[0].Legs[0].Points[n].Latitude;
var y = directions.Result.Routes[0].Legs[0].Points[n].Longitude;
path[c, 0] = x;
path[c, 1] = y;
++c;
}
// Finish with the destination.
path[c, 0] = destinationLat;
path[c, 1] = destinationLon;
// Store the path length and time taken, to calculate the average speed.
var meters = directions.Result.Routes[0].Summary.LengthInMeters;
var seconds = directions.Result.Routes[0].Summary.TravelTimeInSeconds;
var pathSpeed = meters / seconds;
double distanceApartInMeters;
double timeForOneSection;
// Clear the time on the path array. The path array is 1 less than the points array.
timeOnPath = new double[nPoints + 1];
// Calculate how much time is required for each section of the path.
for (var t = 0; t < nPoints + 1; t++)
{
// Calculate distance between the two path points, in meters.
distanceApartInMeters = DistanceInMeters(path[t, 0], path[t, 1], path[t + 1, 0], path[t + 1, 1]);
// Calculate the time for each section of the path.
timeForOneSection = distanceApartInMeters / pathSpeed;
timeOnPath[t] = timeForOneSection;
}
truckOnSection = 0;
truckSectionsCompletedTime = 0;
timeOnCurrentTask = 0;
// Update the state now the route has arrived. Either: enroute or returning.
state = newState;
}
}
For the error make sure that:
The key call within the code above is var directions = azureMapsServices.GetRouteDirections(req).Result;. The directions
structure is complex. Consider setting a breakpoint in this method,
and examining the contents of directions.
You can use the below example code to add the direct method to deliver to a customer :
static Task<MethodResponse> CmdGoToCustomer(MethodRequest methodRequest, object userContext)
{
try
{
// Pick up variables from the request payload, with the name specified in IoT Central.
var payloadString = Encoding.UTF8.GetString(methodRequest.Data);
int customerNumber = Int32.Parse(payloadString);
// Check for a valid key and customer ID.
if (customerNumber >= 0 && customerNumber < customer.Length)
{
switch (state)
{
case StateEnum.dumping:
case StateEnum.loading:
case StateEnum.delivering:
eventText = "Unable to act - " + state;
break;
case StateEnum.ready:
case StateEnum.enroute:
case StateEnum.returning:
if (contents == ContentsEnum.empty)
{
eventText = "Unable to act - empty";
}
else
{
// Set event only when all is good.
eventText = "New customer: " + customerNumber.ToString();
destinationLat = customer[customerNumber, 0];
destinationLon = customer[customerNumber, 1];
// Find route from current position to destination, storing route.
GetRoute(StateEnum.enroute);
}
break;
}
// Acknowledge the direct method call with a 200 success message.
string result = "{\"result\":\"Executed direct method: " + methodRequest.Name + "\"}";
return Task.FromResult(new MethodResponse(Encoding.UTF8.GetBytes(result), 200));
}
else
{
eventText = $"Invalid customer: {customerNumber}";
// Acknowledge the direct method call with a 400 error message.
string result = "{\"result\":\"Invalid customer\"}";
return Task.FromResult(new MethodResponse(Encoding.UTF8.GetBytes(result), 400));
}
}
catch
{
// Acknowledge the direct method call with a 400 error message.
string result = "{\"result\":\"Invalid call\"}";
return Task.FromResult(new MethodResponse(Encoding.UTF8.GetBytes(result), 400));
}
}
For more information please refer this MS TUTORIAL : Create your first Azure IoT Central App & Create a programming project for a real device
MS Q&A: Error - Create your first Azure IoT Central app

C# uwp record two webcams at 60 frames per second

What I need to do is record 2 usb webcams at 60 fps 1280x720 format in UWP c#.
The camera's are currently previewed in a CaptureElement
This is how it start previewing:
public async Task StartPreviewSideAsync(DeviceInformation deviceInformation)
{
if (deviceInformation != null)
{
var settings = new MediaCaptureInitializationSettings {VideoDeviceId = deviceInformation.Id};
try
{
_mediaCaptureSide = new MediaCapture();
var profiles = MediaCapture.FindAllVideoProfiles(deviceInformation.Id);
Debug.WriteLine(MediaCapture.IsVideoProfileSupported(deviceInformation.Id) + " count: " + profiles.Count);
var match = (from profile in profiles
from desc in profile.SupportedRecordMediaDescription
where desc.Width == 1280 && desc.Height == 720 && Math.Abs(Math.Round(desc.FrameRate) - 60) < 1
select new {profile, desc}).FirstOrDefault();
if (match != null)
{
settings.VideoProfile = match.profile;
settings.RecordMediaDescription = match.desc;
}
await _mediaCaptureSide.InitializeAsync(settings);
SideCam.Source = _mediaCaptureSide;
await _mediaCaptureSide.StartPreviewAsync();
_displayRequestSide = new DisplayRequest();
_displayRequestSide.RequestActive();
DisplayInformation.AutoRotationPreferences = DisplayOrientations.Landscape;
CameraManager.GetCameraManager.CurrentSideCamera = deviceInformation;
IsPreviewingSide = true;
}
catch (UnauthorizedAccessException)
{
Debug.WriteLine("The app was denied access to the camera");
IsPreviewingSide = false;
}
catch (Exception ex)
{
Debug.WriteLine("MediaCapture initialization failed. {0}", ex.Message);
IsPreviewingSide = false;
}
}
}
And this is the method that starts the recording:
public IAsyncOperation<LowLagMediaRecording> RecBackCam(StorageFile fileBack)
{
var mp4File = MediaEncodingProfile.CreateMp4(VideoEncodingQuality.HD720p);
if (mp4File.Video != null)
mp4File.Video.Bitrate = 3000000;
return _mediaCaptureBack.PrepareLowLagRecordToStorageFileAsync(mp4File, fileBack);
}
but it does not record 60fps because it cannot find a profile for it (in the preview method).
and when I use this (in the recoding method):
mp4File.Video.FrameRate.Numerator = 3600;
mp4File.Video.FrameRate.Denominator = 60;
it records 60 frames per second but frame 1 and 2 are the same 3 and 4 and so on. But I need actual 60 frames per second.
all the basics of the code comes from the mdsn website
link to code on msdn.
To set the frame rate for MediaCapture, we can use VideoDeviceController.SetMediaStreamPropertiesAsync method like the following:
await _mediaCapture.VideoDeviceController.SetMediaStreamPropertiesAsync(MediaStreamType.VideoRecord, encodingProperties);
For the encodingProperties, we can get it from VideoDeviceController.GetAvailableMediaStreamProperties method, this method returns a list of the supported encoding properties for the video device. If your camera supports 60 fps, 1280x720 resolution then you should be able to find the corresponding VideoEncodingProperties in this list.
For more info, please see the article Set format, resolution, and frame rate for MediaCapture and also Camera resolution sample on GitHub.

Copying Files Across Network Locations Fast in Debug but Slow With Built Windows Form Application

public partial class ImageCopier : Form {
private BackgroundWorker backgroundWorker = new BackgroundWorker();
public ImageCopier() {
InitializeComponent();
//backgroundWorker.DoWork += Copier_DoWork;
}
private void Form1_Load(object sender, EventArgs e) {
string[] accounts = Directory.GetDirectories("photolocation", "???").Select(d => new DirectoryInfo(d).Name).ToArray();
accountBox.Items.AddRange(accounts);
}
private void copyButton_Click(object sender, EventArgs e) {
if (accountBox.SelectedItems.Count == 0) {
MessageBox.Show("You must select an account.");
}
else {
for (int i = 0; i < accountBox.SelectedItems.Count; i++) {
MessageBox.Show("Starting on account " + accountBox.SelectedItems[i]);
for (int a = 0; a <= 9; a++) {
directoryLabel.Text = "In Folder " + a.ToString();
directoryLabel.Refresh();
string[] files = Directory.GetFiles("photolocation" + accountBox.SelectedItems[i] + "\\photos\\" + a + "\\");
files = files.Where(f => f.Contains('$') != true).ToArray();
if (files.Count() != 0) {
for (int b = 0; b < files.Count(); b++) {
fileLabel.Text = "File " + (b + 1) + " of " + files.Count().ToString();
fileLabel.Refresh();
File.Copy(files[b], files[b].Replace("photolocation", "altlocation"), true);
}
}
else {
MessageBox.Show("Computer does not have read access to image server or there are no photos.");
}
}
MessageBox.Show("Finished account " + accountBox.SelectedItems[i]);
}
//backgroundWorker.RunWorkerAsync();
}
}
private void Copier_DoWork(object sender, DoWorkEventArgs e) {
for (int i = 0; i < accountBox.SelectedItems.Count; i++) {
MessageBox.Show("Starting on account " + accountBox.SelectedItems[i]);
for (int a = 0; a <= 9; a++) {
directoryLabel.Text = "In Folder " + a.ToString();
directoryLabel.Refresh();
string[] files = Directory.GetFiles("photolocation" + accountBox.SelectedItems[i] + "\\photos\\" + a + "\\");
files = files.Where(f => f.Contains('$') != true).ToArray();
if (files.Count() != 0) {
for (int b = 0; b < files.Count(); b++) {
//fileLabel.Text = "File " + (b + 1) + " of " + files.Count().ToString();
//fileLabel.Refresh();
File.Copy(files[b], files[b].Replace("photolocation", "altlocation"), true);
}
}
else {
MessageBox.Show("Computer does not have read access to image server or there are no photos.");
}
}
MessageBox.Show("Finished account " + accountBox.SelectedItems[i]);
}
}
}
The code above is how I'm using it when debugging. I use the backgroundWorker and the Copier_DoWork when it's built, since it just goes Not Responding otherwise. The issue is that when I run it this way Debugging it flies through the files and copies them all within a matter of a few hours. Considering how many images it's copying, that's pretty quick. However, with the background worker it just drags and I estimate it would probably take 35 hours to copy the same amount of files.
I changed the folder location names for this piece of code, but "photolocation" and "altlocation" are two different network computers and locations where the photos need to be duplicated. Most of the images are relatively small, 120kb at the most usually. With a random larger one every now and then.
This is not a huge deal as I just threw this together to take care of an issue that will be fixed after this week by other code, but I'm still curious as to what's causing it to be so much slower. Any help would be appreciated.
The above code does not make much sense... For example, Copier_DoWork directly access UI thread to update controls and you even do some explicit refresh. The whole approach is wrong so don't expect good results!
Also, if your processing is so long, you should report your progress and display a progress bar. And you can use the extra argument to send data to the UI thread like the text you want to update on the UI.
If you would turn on all exceptions including MDA while debugging, you would probably have a better idea of where the problem occurs. It is very unusual that the Release version is slower than the Debug version.
Either, you have somehow done undesirable modifications to the configuration or are in a really weird case.
Also, it does not make any sense to show message boxes while doing background processing. If that is for debugging purpose, then delete it before posting question if you don't even talk about displayed messages in your question. If that is your actual UI, then you should seriously reconsider it.
I ended up fixing it by using FileStreams for the starting location and the ending location and CopyTo from the first stream to the second in the backgroundWorker instead of File.Copy and it works much faster, just as fast as File.Copy was working in Debug.

C#, Counting iterations for a complaint process

i have to create a programme that will handle complaints i have to track how many times i complete the process, this means i will need a count that increases when i return to the first form in the process however the number always resets when the first form is opened
runNum is set to a public int this is the code i have for entering data ito the form automatically then increaseing the runmber before opening the next form so far:
private void autoFill()
{
TitlePage titlepage = new TitlePage();
if (titlepage.getRun() == true)
{
int priority = runNum % 4;
if (priority == 0)
priority = 2;
txtDate.Text = DateTime.Today.ToString("dd/MM/yyyy");
txtRef.Text = (100 + runNum).ToString();
txtPriority.Text = priority.ToString();
txtCustName.Text = firstNames[runNum] + " " + secondNames[runNum];
txtCustAddress.Text = (runNum + 5).ToString() + " " + Address1[runNum] + " " + Address2[(runNum % 7)];
txtCustEmail.Text = firstNames[runNum] + secondNames[runNum] + "#" + ISP[(runNum % 10)] + "." + Suff[(runNum % 10)];
txtCustTel.Text = TelNo[runNum];
//TBD- fill this in with actual data
rtbComplaint.Text = "Complaint type, Sevarity, soultion exsiting, employee who dealt with complaint, Date";
rtbComplaint.Enabled = false;
txtPriority.Enabled = false;
txtDate.Enabled = false;
txtRef.Enabled = false;
txtCustName.Enabled = false;
txtCustName.Enabled = false;
txtCustEmail.Enabled = false;
txtCustAddress.Enabled = false;
txtCustTel.Enabled = false;
if (runNum % 2 == 0)
{
rdoNo.Checked = true;
enter code here }
else
{
rdoYes.Checked = true;
}
getTimer();
runNum++;
}
}
A public int will always be reset in this case. You should declare a static int on your parent page if you want global access to the variable. But global variables are to be avoided. Rather try to save your iterations in a central point such as a database or file which you can retrieve the value from or even use a server cached object which you can update and get the value from again.
i would go with a static variable but be aware that even static variables can be reset if the appdomain is restarted or the webpage class gets recompiled.
see
Lifetime of ASP.NET Static Variable
edited: sorry i assumed this question was a for an asp.net application. is this not the case?
if its a normal windows form then you will need to store it in some server side, whether DB, shared file on a server or something similar

Categories

Resources