I am trying to access DJI Mavic 2 Pro data through DJI WSDK.
I was able to setup the code as per DJI tutorial
When I print appActivationState, I get the status as ACTIVATED.
When I print aircraftBindindState, I get the status as NOT_REQUIRED
When I print SDKRegistrationResultCode, I get the status as NO_ERROR
When I print ProductIndex, I get the status as 0
When I print ComponentIndex, I get the status as 0
However, when I print other drone data such as temperature, battery, ...etc, I always get the same output.
My code for Mavic 2 Pro on Windows SDK is as shown below:
using DJI.WindowsSDK;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices.WindowsRuntime;
using Windows.Foundation;
using Windows.Foundation.Collections;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Controls.Primitives;
using Windows.UI.Xaml.Data;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Navigation;
using DJI.WindowsSDK.Components;
using DJI.WindowsSDK.FlySafe;
// The Blank Page item template is documented at https://go.microsoft.com/fwlink/?LinkId=402352&clcid=0x409
namespace DJIWSDKDemo
{
public sealed partial class MainPage : Page
{
public MainPage()
{
this.InitializeComponent();
DJISDKManager.Instance.SDKRegistrationStateChanged += Instance_SDKRegistrationEvent;
//Replace with your registered App Key. Make sure your App Key matched your application's package name on DJI developer center.
DJISDKManager.Instance.RegisterApp("c086d1c2xxxxxxxxxxxxxxxx");
}
private async void Instance_SDKRegistrationEvent(SDKRegistrationState state, SDKError resultCode)
{
if (resultCode == SDKError.NO_ERROR)
{
System.Diagnostics.Debug.WriteLine("Register app successfully.");
//The product connection state will be updated when it changes here.
DJISDKManager.Instance.ComponentManager.GetProductHandler(0).ProductTypeChanged += async delegate (object sender, ProductTypeMsg? value)
{
await Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, async () =>
{
if (value != null && value?.value != ProductType.UNRECOGNIZED)
{
System.Diagnostics.Debug.WriteLine("The Aircraft is connected now.");
while (true) {
System.Threading.Thread.Sleep(3000);
System.Diagnostics.Debug.WriteLine("The App Acitvation State is: " + DJISDKManager.Instance.appActivationState);
System.Diagnostics.Debug.WriteLine("The Aircraft Binding State: " + DJISDKManager.Instance.aircraftBindindState);
System.Diagnostics.Debug.WriteLine("SDK Registeration Result Code: " + DJISDKManager.Instance.SDKRegistrationResultCode);
System.Diagnostics.Debug.WriteLine("Product Index: " + DJISDKManager.Instance.ComponentManager.GetBatteryHandler(0, 0).ProductIndex);
System.Diagnostics.Debug.WriteLine("Component Index: " + DJISDKManager.Instance.ComponentManager.GetBatteryHandler(0, 0).ComponentIndex);
System.Diagnostics.Debug.WriteLine("Remaining Battery: " + DJISDKManager.Instance.ComponentManager.GetBatteryHandler(0, 0).GetChargeRemainingAsync());
System.Diagnostics.Debug.WriteLine("Battery Temperature: " + DJISDKManager.Instance.ComponentManager.GetBatteryHandler(0, 0).GetBatteryTemperatureAsync());
}
}
else
{
System.Diagnostics.Debug.WriteLine("The Aircraft is disconnected now.");
//You can hide your pages according to the aircraft connection state here, or show the connection tips to the users.
}
});
};
}
else
{
System.Diagnostics.Debug.WriteLine("Register SDK failed, the error is: ");
System.Diagnostics.Debug.WriteLine(resultCode.ToString());
}
}
}
}
When I run the code, I get the following output:
The output of temperature (System.Runtime.CompilerServices.AsyncTaskMethodBuilder1+AsyncStateMachineBox1[DJI.WindowsSDK.ResultValue1[System.Nullable1[DJI.WindowsSDK.DoubleMsg]],DJI.WindowsSDK.Components.BatteryHandler+d__58]) and battery (System.Runtime.CompilerServices.AsyncTaskMethodBuilder1+AsyncStateMachineBox1[DJI.WindowsSDK.ResultValue1[System.Nullable1[DJI.WindowsSDK.IntMsg]],DJI.WindowsSDK.Components.BatteryHandler+d__22]) are never changing.
I'm expecting the output to be integer value that changes as the drone battery is being consumed
Could you tell me what is the problem and how to fix it?
Related
I have a problem with connecting to our LDAP server, using the NuGet package “Novell.Directory.Ldap.NETStandard2_0”.
My application is a Xamarin.Forms, with the Andoid & UWP part, based on NetStandard 2.0, using Visual Studio 2019, updated.
I could not find any built-in functionality in Netcore2.0 for using LDAP,
That is why I used the Nuget Package (Novell.Directory.Ldap.NETStandard2_0 by Novell, dsbenghe, mkostreba).
I have also used an LDAP query tool for Windows to test the connection, and that works.
But when I try to establish a connection in my app, I get an error with error code 91.
I have tried it with the full hostname, and with the direct ip address of the domain server, but I get the same error result. I have tried this with debugging UWP, not android.
I haven't started on making a correct credentials query yet, because the connection itself should first be ok.
This is my code: (under a simple button clicked)
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Novell.Directory.Ldap;
using Xamarin.Forms;
using Xamarin.Forms.Xaml;
using System.ComponentModel;
namespace App1.view
{
[XamlCompilation(XamlCompilationOptions.Compile)]
public partial class Page2 : ContentPage
{
public Page2()
{
InitializeComponent();
}
private void button2_Clicked(object sender, EventArgs e)
{
try
{
LdapConnection conn = new LdapConnection();
conn.Connect("ldapserverhostname", 389);
conn.Bind("username query", "some password");
DisplayAlert("Error", "succesvol", "ok");
conn.Disconnect();
}
catch (LdapException f)
{
DisplayAlert("Error", f.ResultCode.ToString(), "ok");
return;
}
catch (Exception f)
{
DisplayAlert("Error", f.Message, "ok");
return;
}
}
}
}
Who could help me with this?
update 16 apr 2020:
I have established a connection + successful bind with our LDAP server using WPF NetCore console application, and also with a WPF NetCore desktop application, using the same serverinfo and user query info.
But I cannot get this working under Xamarin.Forms UWP or with a dedicated UWP app. Firewall of the computer is out of the question (I believe), because I am able to communicate with the LDAP server in multiple ways.
I have tried it with sideloading my Xamarin.Forms UWP app, but no result. >> Jumps to the first catch, every time.
Besides using the Novell Ldap Nuget, I have also tried the Windows Compatibility Pack for NetCore app in my UWP and Xamarin.Forms UWP app, but that will result in an "not supported platform" error.
here is my working code from the WPF NetCore desktop app:
using System;
using System.Collections.Generic;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using Novell.Directory.Ldap;
using Novell.Directory;
namespace WpfApp3
{
/// <summary>
/// Interaction logic for Window1.xaml
/// </summary>
public partial class Window1 : Window
{
public Window1()
{
InitializeComponent();
}
private void Button_Click(object sender, RoutedEventArgs e)
{
string ldapHost = "fullyhostname.com";
String loginDN = "CN=MyUserName,OU=HK,something=Users,DC=ourdomainname,DC=com";
String password = "mypassword";
LdapConnection conn = new LdapConnection();
try
{
conn.Connect(ldapHost, 389);
if (conn.Connected)
{
MessageBoxResult r = MessageBox.Show("connection succeeded");
}
conn.Bind(loginDN, password);
MessageBoxResult t = MessageBox.Show("bind succeeded");
}
catch (LdapException f)
{
Console.WriteLine("Error1:" + "code= " + f.ResultCode.ToString());
Console.WriteLine("Error1:" + "code= " + f.LdapErrorMessage);
return;
}
catch (Exception f)
{
Console.WriteLine("Error:" + f.Message);
return;
}
conn.Disconnect();
}
}
}
Using Visual Studios RC 2017, using their template for a .NET Windows Form Application
Trying to get a list of usb devices from my computer, and stick it crudely into a rTextbox for a school project, using a function in System.Management called "GetUSBDevices()".
Attempting to do this using a function I know System.Management has, and that works while using in a Visual Studios C# Console Application Template,and for some reason It won't recognize the reference...
I've tried:
Adding System.Management as a reference through the solution explorer
reinstalling the System.Management Reference
calling the function directly from the library [ System.Management.GetUSBDevices(); ]
And nothing has worked so far...
Code That Doesn't Work:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.Management; //ISSUE HERE!
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace Manager
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
public void DisplayProcess()
{
richTextBox1.Clear();
Process[] plist = Process.GetProcesses();
foreach (Process p in plist)
{
richTextBox1.Text += "Process " + p.Id.ToString() + " : " + p.ProcessName.ToString() + "\n";
}
}
//-----------------------------------ISSUE HERE-----------------------------
//-----------------------------------ISSUE HERE-----------------------------
//-----------------------------------ISSUE HERE-----------------------------
private void DisplayUSB()
{
richTextBox1.Clear();
var usbDevices = GetUSBDevices();
foreach (var usb in usbDevices)
{
richTextBox1.Text += "USB Device " + usb.DeviceID;
}
}
private void button1_Click(object sender, EventArgs e)
{
switch (button1.Text)
{
case "Start":
button1.Text = "USB";
DisplayProcess();
break;
case "USB":
button1.Text = "Manager";
// DisplayUSB();
break;
case "Manager":
DisplayProcess();
button1.Text = "USB";
break;
}
}
private void button2_Click(object sender, EventArgs e)
{
switch(button1.Text)
{
case "Start":
MessageBox.Show("Please Start The Manager!","REFRESH ERROR");
break;
case "USB":
DisplayProcess();
break;
//case "Manager":
// DisplayUSB();
// break;
}
}
}
}
Errors given are:
Error CS0103 The name 'GetUSBDevices' does not exist in the current context Manager c:\users\*****\documents\visual studio 2017\Projects\Manager\Manager\Form1.cs 38
Error CS1579 foreach statement cannot operate on variables of type '?' because '?' does not contain a public definition for 'GetEnumerator' Manager c:\users*****\documents\visual studio 2017\Projects\Manager\Manager\Form1.cs 40
Code That Does Work (taken from Get List of connected USB Devices and tested personally, works on my PC fine)
namespace ConsoleApplication1
{
using System;
using System.Collections.Generic;
using System.Management;
class Program
{
static void Main(string[] args)
{
var usbDevices = GetUSBDevices();
foreach (var usbDevice in usbDevices)
{
Console.WriteLine("Device ID: {0}, PNP Device ID: {1}, Description: {2}",
usbDevice.DeviceID, usbDevice.PnpDeviceID, usbDevice.Description);
}
Console.Read();
}
}
}
Will very much appreciate any help i can get in the matter, so it will work!
Function GetUSBDevices() is not in System.Management but in the code you copied from the other SO question. So my guess is that you forgot to copy that piece of code ;-).
I want to run the Skeinforge slicer program written in Python inside my Windows Phone 8 C# application. I have determined that I should probably use IronPython to do this, I have already determined that I can run Skeinforge inside the ipy.exe terminal I got when I installed IronPython. My problem though is that I am struggling to figure out how to host and run a Python script with IronPython inside Windows Phone 8. I have also already managed to get a simple hello world script running inside a Desktop Windows Forms application that transfers the applications console output to the Debug console with the following code:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Diagnostics;
using System.IO;
using IronPython.Hosting;
using Microsoft.Scripting.Hosting;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
DebugWriter debugW = new DebugWriter();
Console.SetOut(debugW);
}
private void button1_Click(object sender, EventArgs e)
{
TextWriter tw = new StreamWriter("Test.py");
tw.Write(scriptBox.Text);
tw.Close();
try
{
var ipy = Python.CreateRuntime();
dynamic test = ipy.UseFile("Test.py");
}
catch (Exception ex)
{
Debug.WriteLine("Error: " + ex.Message);
}
}
}
}
And this is the DebugWriter:
class DebugWriter : TextWriter
{
private StringBuilder content = new StringBuilder();
public DebugWriter()
{
Debug.WriteLine("Writing console to debug");
}
public override void Write(char value)
{
base.Write(value);
if (value == '\n')
{
Debug.WriteLine(content.ToString());
content = new StringBuilder();
}
else
{
content.Append(value);
}
}
public override Encoding Encoding
{
get { return System.Text.Encoding.UTF8; }
}
}
I have no idea how to even add the IronPython libraries to my Windows Phone 8 application though as the standard libraries won't import. I have though tried compiling the apparently now defunct Windows Phone 7 libraries with the master source code and I can import these libraries, but I get absolutely no response on the debug terminal when I try to run my hello world script.
Do any of you have any idea how to get this woring in Windows Phone 8, if you know how to do this in Windows 8/Metro/RT then that would also probably work for WP8.
UPDATE:
I have looked at the debug output again and I seem to get this error when trying to use the WP7 libraries to run a hello world script:
A first chance exception of type 'System.NotImplementedException' occurred in Microsoft.Scripting.DLL
Error: The method or operation is not implemented.
I managed to get Skeinforge running on a modified version of IPY. You can get the source for my application here: http://skeinforgewp8.codeplex.com/
Im trying to get my notefunction to post the current city you are in by using your gps coordinates when saving a note. Right now it's only showing "unknown location". Im kinda lost right now and i have worked so long with this code to try and get it to work so please could anyone tell me what i have done wrong?
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;
using System.Device.Location;
using System.Text;
using System.IO.IsolatedStorage;
using System.IO;
using Secret.myTerraService;
namespace Secret
{
public partial class AddNotePage : PhoneApplicationPage
{
private IsolatedStorageSettings settings = IsolatedStorageSettings.ApplicationSettings;
private string location = "";
#region Hämtar din geografiska position
public AddNotePage()
{
InitializeComponent();
GeoCoordinateWatcher watcher;
watcher = new GeoCoordinateWatcher(GeoPositionAccuracy.Default)
{
MovementThreshold = 20
};
watcher.PositionChanged += this.watcher_PositionChanged;
watcher.StatusChanged += this.watcher_StatusChanged;
watcher.Start();
}
private void watcher_StatusChanged(object sender, GeoPositionStatusChangedEventArgs e)
{
switch (e.Status)
{
case GeoPositionStatus.Disabled:
// location is unsupported on this device
break;
case GeoPositionStatus.NoData:
// data unavailable
break;
}
}
private void watcher_PositionChanged(object sender, GeoPositionChangedEventArgs<GeoCoordinate> e)
{
var epl = e.Position.Location;
// Access the position information thusly:
epl.Latitude.ToString("0.000");
epl.Longitude.ToString("0.000");
epl.Altitude.ToString();
epl.HorizontalAccuracy.ToString();
epl.VerticalAccuracy.ToString();
epl.Course.ToString();
epl.Speed.ToString();
e.Position.Timestamp.LocalDateTime.ToString();
}
void client_ConvertLonLatPtToNearestPlaceCompleted(object sender, myTerraService.ConvertLonLatPtToNearestPlaceCompletedEventArgs e)
{
location = e.Result;
//throw new NotImplementedException();
}
#endregion
#region Knappfunktioner
private void AppBar_Cancel_Click(object sender, EventArgs e)
{
navigateBack();
}
private void AppBar_Save_Click(object sender, EventArgs e)
{ // spara en ny anteckning
if (location.Trim().Length == 0)
{
location = "Okänd Plats";
}
// skapa namnet på filen
StringBuilder sb = new StringBuilder();
sb.Append(DateTime.Now.Year);
sb.Append("_");
sb.Append(String.Format("{0:00}", DateTime.Now.Month));
sb.Append("_");
sb.Append(String.Format("{0:00}", DateTime.Now.Day));
sb.Append("_");
sb.Append(String.Format("{0:00}", DateTime.Now.Hour));
sb.Append("_");
sb.Append(String.Format("{0:00}", DateTime.Now.Minute));
sb.Append("_");
sb.Append(String.Format("{0:00}", DateTime.Now.Second));
sb.Append("_");
location = location.Replace(" ", "-");
location = location.Replace(", ", "_");
sb.Append(location);
sb.Append(".txt");
//spara filen i Isolated Storage
var appStorage = IsolatedStorageFile.GetUserStoreForApplication();
try
{
using (var fileStream = appStorage.OpenFile(sb.ToString(), System.IO.FileMode.Create))
{
using (StreamWriter sw = new StreamWriter(fileStream))
{
sw.WriteLine(editTextBox.Text);
}
}
}
catch
{
// åtgärda vid senare tillfälle..
}
//Klart Navigera tillbaka till NoteMainPage
navigateBack();
}
When testing this, I can see a few points where your code could break. You should debug with breakpoints to actually confirm that your app is getting GPS location data. If not, use the Windows Phone emulator and run a GPS simulation (and then confirm again).
Next, once you know that your GPS data is coming in and formatted correctly for your Terra Web Service, confirm that the data is actually being sent to the Terra Web Service and that data is being returned from the web service call. If your Terra Web Service is returning "Unknown Location" still, try again but this time plot the GPS location near a major city to increase the odds of the web service knowing what city you are close to. If you are still returning "Unknown Location" then you can be fairly certain that the issue resides with the web service provider.
In my experience with the Windows Phone location services (I've only used dev phones with WiFi access (i.e. no sim)), location data sometimes takes a few seconds or minutes to pickup. If you're testing this on a physical dev phone in a basement or an area with limited access for the GPS to find you, odds are the data isn't being generated. Also, because the Windows Phone location data isn't necessarily instant, you can't always call it on the fly and expect it to have location data ready. In my experience I have had the user opt in to location services (per the Windows Phone Marketplace submission requirements) and then have a background agent pull location data while the user is using the app. That way location data is likely to be ready by the time user would need it (like your example when the user saves the note).
Here's a working example I made for you in C# that will work for your Windows Phone app. The sample is a console app for the sake of simplicity and time. If you can't figure it out still, I'll code it up for Windows Phone. With this though you really have everything you need to make it work, just plug in the lat and long variables. Download Working Source Code (Visual Studio 2010)
C# Source code snippet
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using TerraServiceExample.com.msrmaps; // add the service using statement
// http://msrmaps.com/terraservice2.asmx
namespace TerraServiceExample
{
class Program
{
/// <summary> The main entry point for the application. </summary>
static void Main(string[] args)
{
// Create the GPS point from your location services data
LonLatPt location = new LonLatPt();
// Modify Lat and Lon based on your needs
// This example uses the GPS Coordinates for "Eau Claire, Wisconsin, United States"
location.Lat = 44.811349;
location.Lon = -91.498494;
// Create a new TerraService object
TerraService ts = new TerraService();
// Output the nearest location from the TerraService
Console.WriteLine(ts.ConvertLonLatPtToNearestPlace(location));
// For console app to stay open/close easily
Console.WriteLine("Press any key to close window...");
Console.ReadKey();
// Lastly, appreciate the Microsoft folks that made this available for free
// They are all interesting individuals but you should read about Jim Gray via Wikipedia to
// understand some history behind this cool web service.
}
}
}
I am a total beginner at C#, but I have used Java a lot. I am trying to use the following code in my app to get location data. I am making a Windows 8 desktop app to use the GPS sensor in my device:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Windows.Devices.Sensors;
using Windows.Devices.Geolocation;
using Windows.Devices.Geolocation.Geoposition;
using Windows.Foundation;
namespace Hello_Location
{
public partial class Form1 :
{
public Form1()
{
InitializeComponent();
}
async private void Form1_Load(object sender, EventArgs e)
{
Geolocator loc = new Geolocator();
try
{
loc.DesiredAccuracy = PositionAccuracy.High;
Geoposition pos = await loc.GetGeopositionAsync();
var lat = pos.Coordinate.Latitude;
var lang = pos.Coordinate.Longitude;
Console.WriteLine(lat+ " " +lang);
}
catch (System.UnauthorizedAccessException)
{
// handle error
}
}
private void button1_Click(object sender, EventArgs e)
{
}
}
}
I get this error:
'await' requires that the type
'Windows.Foundation.IAsyncOperation'
have a suitable GetAwaiter method. Are you missing a using directive
for 'System'? C:\Users\clidy\documents\visual studio
2012\Projects\Hello-Location\Hello-Location\Form1.cs
How can I fix this?
Also it will be very useful if you can point me to some resources for C# location and the sensor API for windows desktop apps. Upon googling, I am only getting Windows RT APIs.
To fix your error you have to reference to the link that Bart gave in one of the question's comments.
You might need to add a reference to System.Runtime.WindowsRuntime.dll
as well if you are using mapped types like Windows Runtime event
handlers:
...
That assembly resides in C:\Program Files (x86)\Reference
Assemblies\Microsoft\Framework.NETCore\v4.5
I recently found a "solution" for a similar question: C# desktop application doesn't share my physical location. Maybe you might be interested by my approach: https://stackoverflow.com/a/14645837/674700.
It's more like a workaround and it's not targeting Windows 8, but it works in the end.
alex's solution works!
add that reference and geolocation api starts working like a charm! so do async methods for other sensors!
here is a function i just got working using it.
async public void UseGeoLocation()
{
Geolocator _GeoLocator = new Geolocator();
Geoposition _GeoPosition =
await _GeoLocator.GetGeopositionAsync();
Clipboard.Clear();
Clipboard.SetText("latitude," +
_GeoPosition.Coordinate.Latitude.ToString() +
"," + "longitude," + _GeoPosition.Coordinate.Longitude.ToString() +
"," + "heading," + _GeoPosition.Coordinate.Heading.ToString() +
"," + "speed," + _GeoPosition.Coordinate.Speed.ToString());
Application.Exit();
}