How to write(send) command to USB Port?(UVC, Webcam) - c#

I am new in c#
I am trying to send command to USB port(usbport=========fx3(Cypress chip), to light on LED than with in the custom board))
I tried to scanport but it was failed because my computer(win10) recognized the usb as camera(fx3 is chip that image processing)
so i found this code in sysnet.pe.kr
using System;
using System.Threading.Tasks;
using Windows.Devices.Enumeration;
namespace ConsoleApp1
{
class Program
{
static void Main(string[] args)
{
ListDevices().GetAwaiter().GetResult();
}
private static async Task ListDevices()
{
var devices = await DeviceInformation.FindAllAsync(DeviceClass.VideoCapture);
foreach (var item in devices)
{
Console.WriteLine($"{item.Id}: {item.Name}");
devices.
}
}
}
}
it works!!! so I found port
but i don't have idea how to send command to the port!!!
please help me ㅠㅠ

First you must read your camera documentation (from producer website or .. , it may have programing sdk)
Otherwise you can use LibUsbDotNet

Related

Enumerate UWP MIDI API devices from C# console application?

I want to get a list of installed MIDI Devices in Windows 10, using the Windows 10 UWP MIDI API.
This article shows example code to get a list of MIDI devices and their IDs, using C#:
using Windows.Devices.Midi;
using Windows.Devices.Enumeration;
...
private async void ListMidiDevices()
{
// Enumerate Input devices
var deviceList = DeviceInformation.FindAllAsync(
MidiInPort.GetDeviceSelector());
foreach (var deviceInfo in deviceList)
{
Console.WriteLine(deviceInfo.Id);
Console.WriteLine(deviceInfo.Name);
Console.WriteLine("----------");
}
// Output devices are enumerated the same way, but
// using MidiOutPort.GetDeviceSelector()
}
I tried inserting the code for ListMidiDevices in the Visual Studio Community 2015 "Hello World" example program. I put the code block in place of Console.WriteLine("Hello World!");
in the "hello world" console example. I added the "using" statements above in the proper place.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Windows.Devices.Midi;
using Windows.Devices.Enumeration;
namespace ConsoleApplicationHelloWorld
{
class Program
{
static void Main(string[] args)
{
// Enumerate Input devices
var deviceList = await DeviceInformation.FindAllAsync(
MidiInPort.GetDeviceSelector());
foreach (var deviceInfo in deviceList)
{
System.Diagnostics.Debug.WriteLine(deviceInfo.Id);
System.Diagnostics.Debug.WriteLine(deviceInfo.Name);
System.Diagnostics.Debug.WriteLine("----------");
}
// Output devices are enumerated the same way, but
// using MidiOutPort.GetDeviceSelector() }
}
}
Edit - VS wasn't building the UWP type. I upgraded to VS Community 2019, and installed ConsoleAppUniversal.vsix. Then I could create a new project - Console App C# Universal:
using System;
using Windows.Devices.Midi;
using Windows.Devices.Enumeration;
// This example code shows how you could implement the required main function for a
// Console UWP Application. You can replace all the code inside Main with your own custom code.
// You should also change the Alias value in the AppExecutionAlias Extension in the
// Package.appxmanifest to a value that you define. To edit this file manually, right-click
// it in Solution Explorer and select View Code, or open it with the XML Editor.
namespace ConsoleAppCsharpUniversal
{
class Program
{
static void Main(string[] args)
{
if (args.Length == 0)
{
Console.WriteLine("starting - no args");
// Enumerate Input devices
var deviceList = DeviceInformation.FindAllAsync(
MidiInPort.GetDeviceSelector());
foreach (var deviceInfo in deviceList)
{
Console.WriteLine(deviceInfo.Id);
Console.WriteLine(deviceInfo.Name);
Console.WriteLine("----------");
}
Console.WriteLine("finish - no args");
}
else
{
for (int i = 0; i < args.Length; i++)
{
Console.WriteLine($"arg[{i}] = {args[i]}");
}
}
Console.WriteLine("Press a key to continue: ");
Console.ReadLine();
}
}
}
Now the only remaining error is "foreach statement cannot operate on variables of type IAsyncOperation<DeviceInformationCollection> because IAsyncOperation<DeviceInformationCollection> does not contain a public instance definition for GetEnumerator"
Is there another way to access the device information without using an async method?
You have to make sure your project is targeting at least C# 7.1 (I think the template does have this out-of-the-box in VS 2019) and use the async Main method feature:
Your method signature will change to:
public static async Task Main(string[] args)
{
...
}
And then you need to await the FindAllAsync method:
var deviceList = await DeviceInformation.FindAllAsync(
MidiInPort.GetDeviceSelector());
Note: You can change the C# version by opening the csproj file in a text editor and adding the following into a <PropertyGroup>:
<LangVersion>7.1</LangVersion>
or even (if you want the latest features):
<LangVersion>latest</LangVersion>

Azure IoT Hub: Can't call direct method using AMQP protocol

I've been trying to make a direct method call using the AMQP protocol. But can't make it work. I believe calling direct method is possible over AMQP if I'm not wrong. It works with MQTT though. Any clues would be much appreciated.
Here's the code:
using Microsoft.Azure.Devices.Client;
using Microsoft.Azure.Devices.Shared;
using Newtonsoft.Json;
using System;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace VirtualIoTDevice
{
internal class Program
{
private const string DeviceConnectionString = "device-connection-string";
private const string DEVICE_ID = "device01";
private static DeviceClient _device;
private static async Task Main(string[] args)
{
Console.WriteLine("Initializing virtual IoT device..");
using (_device = DeviceClient.CreateFromConnectionString(DeviceConnectionString, DEVICE_ID))
{
await _device.OpenAsync();
await _device.SetMethodHandlerAsync("showMessage", ShowMessage, null);
Console.ReadKey();
}
}
private static Task<MethodResponse> ShowMessage(MethodRequest methodRequest, object userContext)
{
Console.WriteLine("***Direct message received***");
Console.WriteLine(methodRequest.DataAsJson);
var responsePayload = Encoding.ASCII.GetBytes(JsonConvert.SerializeObject(new { response = "Message shown!" }));
return Task.FromResult(new MethodResponse(responsePayload, 200));
}
}
}
And here's the command to invoke the direct method:
az iot hub invoke-device-method -n "iothub-name" -d "device01" --method-name "showMessage"
Ok, I know what your issue is: In the latest version of the SDK there was some change in regards to blocking threads. I don't know if this was an intended change or a regression.
However, in your case the Console.ReadKey() is somehow blocking AMQP from connecting in the first place. MQTT is not affected by this - which could indicate it might be a regression.
So, if you change Console.ReadKey() to for example await Task.Delay(-1) it works again in my test.

Skype C# API Select Chat

So I know this API is quite old and very undocumented, exactly the reason that I'm making a SO question, so I wanted to know how I can select a chat in Skype using the C# Skype Desktop API, I've done some looking around but most people seem to be using WinForms to make their app, mine's just a simple console application, code:
Skype Skype = new Skype();
Skype.Attach(5, true);
Skype.Chat.SendMessage("Hello ??");
Parser.Pause();
On runtime, I of course get an exception telling me I need to select a chat, but I'm not sure as to how I can do that, I've looked here but that didn't help me much.
Is there a way to reference a chat easily using a specific code? etc... Thanks!
I have constructed this snippet which should help you...
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Remoting.Channels;
using System.Text;
using System.Threading.Tasks;
using SKYPE4COMLib;
namespace skypeExperiment
{
class Program
{
static void Main(string[] args)
{
Skype s = new Skype();
s.Attach();
if (!s.Client.IsRunning)
{
// start minimized with no splash screen
s.Client.Start(true, true);
}
// wait for the client to be connected and ready
//you have to click in skype on the "Allow application" button which has popped up there
//to allow this application to communicate with skype
s.Attach(6, true);
//this will print out all the chat names to the console
//it will enumerate all the chats you've been in
foreach (Chat ch in s.Chats)
{
Console.WriteLine(ch.Name);
}
//pick one chat name of the enumerated ones and get the chat object
string chatName = "#someskypeuser/someskypeuser;9693a13447736b9";
Chat chat = GetChatByName(s, chatName);
//send a message to the selected chat
if (chat != null)
{
chat.SendMessage("test");
}
else
{
Console.WriteLine("Chat with that name was not found.");
}
Console.WriteLine("Press any key to continue...");
Console.ReadKey();
}
private static Chat GetChatByName(Skype client, string chatName)
{
foreach (Chat chat in client.Chats)
{
if (chat.Name == chatName) return chat;
}
return null;
}
}
}
Instead of using an existing chat object, you can create new chat object with method
Chat chat = s.CreateChatWith("name of the user to chat with");
chat.SendMessage("test");
You can create a group chat with:
Group mygroup = s.CreateGroup("mygroup");
mygroup.AddUser("user1");
mygroup.AddUser("user2");
Chat myGroupChat = s.CreateChatMultiple(mygroup.Users);
myGroupChat.SendMessage("test");
or create method to retrieve group by display name
private static Group GetGroupByDisplayName(Skype client, string groupDisplayName)
{
foreach (Group g in client.Groups)
{
if (g.DisplayName == groupDisplayName)
{
return g;
}
}
return null;
}
and use it then like:
Group majesticSubwayGroup = GetGroupByDisplayName("majesticsubway");
Chat majesticSubwayGroupChat = s.CreateChatMultiple(majesticSubwayGroup.Users);
majesticSubwayGroupChat.SendMessage("test");

LibUsbDotNet open device -> Device not found

I have usbasp programmer for AVR microcontrollers. This programmer uses libusb library. I've managed to connect it to pc, system detected new device and I managed to install driver for this device. It works well since I'm able to program AVR chips with it. So hardware part is 100% OK.
Now software part:
Using simple iterating over my libusb-win32 devices using LibUsbDotNet I find 2 devices. Both of them are named the same (and have same VID and PID) so I think this is composite device. Second one has some data in it. This is well shown on screenshots bellow.
And the code (it is just copy pasted from the examples)
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using LibUsbDotNet;
using LibUsbDotNet.Info;
using LibUsbDotNet.Main;
namespace USB_Test_CLI_CS {
class Program {
public static readonly int VendorID = 0x16C0;
public static readonly int ProductID = 0x05DC;
public static void Main(string[] args) {
UsbDevice usbDevice = null;
UsbRegDeviceList allDevices = UsbDevice.AllDevices;
Console.WriteLine("Found {0} devices", allDevices.Count);
foreach (UsbRegistry usbRegistry in allDevices) {
Console.WriteLine("Got device: {0}\r\n", usbRegistry.FullName);
if (usbRegistry.Open(out usbDevice)) {
Console.WriteLine("Device Information\r\n------------------");
Console.WriteLine("{0}", usbDevice.Info.ToString());
Console.WriteLine("VID & PID: {0} {1}", usbDevice.Info.Descriptor.VendorID, usbDevice.Info.Descriptor.ProductID);
Console.WriteLine("\r\nDevice configuration\r\n--------------------");
foreach (UsbConfigInfo usbConfigInfo in usbDevice.Configs) {
Console.WriteLine("{0}", usbConfigInfo.ToString());
Console.WriteLine("\r\nDevice interface list\r\n---------------------");
IReadOnlyCollection<UsbInterfaceInfo> interfaceList = usbConfigInfo.InterfaceInfoList;
foreach (UsbInterfaceInfo usbInterfaceInfo in interfaceList) {
Console.WriteLine("{0}", usbInterfaceInfo.ToString());
Console.WriteLine("\r\nDevice endpoint list\r\n--------------------");
IReadOnlyCollection<UsbEndpointInfo> endpointList = usbInterfaceInfo.EndpointInfoList;
foreach (UsbEndpointInfo usbEndpointInfo in endpointList) {
Console.WriteLine("{0}", usbEndpointInfo.ToString());
}
}
}
usbDevice.Close();
}
Console.WriteLine("\r\n----- Device information finished -----\r\n");
}
Console.WriteLine("Trying to find our device: {0} {1}", VendorID, ProductID);
UsbDeviceFinder usbDeviceFinder = new UsbDeviceFinder(VendorID, ProductID);
// This does not work !!! WHY ?
usbDevice = UsbDevice.OpenUsbDevice(usbDeviceFinder);
if (usbDevice != null) {
Console.WriteLine("OK");
} else {
Console.WriteLine("FAIL");
}
UsbDevice.Exit();
Console.Write("Press anything to close");
Console.ReadKey();
}
}
}
Here's output of this program
Found 2 devices
Got device: Van Ooijen Technische Informatica - USBasp
----- Device information finished -----
Got device: Van Ooijen Technische Informatica - USBasp
Device Information
------------------
Length:18
DescriptorType:Device
BcdUsb:0x0110
Class:VendorSpec
SubClass:0x00
Protocol:0x00
MaxPacketSize0:8
VendorID:0x16C0
ProductID:0x05DC
BcdDevice:0x0103
ManufacturerStringIndex:1
ProductStringIndex:2
SerialStringIndex:0
ConfigurationCount:1
ManufacturerString:www.fischl.de
ProductString:USBasp
SerialString:
VID & PID: 5824 1500
Device configuration
--------------------
Length:9
DescriptorType:Configuration
TotalLength:18
InterfaceCount:1
ConfigID:1
StringIndex:0
Attributes:0x80
MaxPower:25
ConfigString:
Device interface list
---------------------
Length:9
DescriptorType:Interface
InterfaceID:0
AlternateID:0
EndpointCount:0
Class:PerInterface
SubClass:0x00
Protocol:0x00
StringIndex:0
InterfaceString:
Device endpoint list
--------------------
----- Device information finished -----
Trying to find our device: 5824 1500
FAIL
Press anything to close
What I'd like to get is this simple code to detect this device which IS present (since simple iteration over all devices finds it and other tool "USB Cfg Interrogator" find it too).
This has been asked before but there were no constructive answer.
I also could use libusb-win32 c++ library and create some C# wrappers for it but if it is not needed and I can use LibUsbDotNet library I'd like to use it instead of creating wrappers myself.
What I'd like to get is this simple code to detect this device which IS present
You almost have that already. There is only one for which usbRegistry.Open() actually works.
There should be no other device - check that your use latest libusb-win32 version (1.2.6.0 at this time).
UsbDeviceFinder seems to have a problem with this phantom device.
You may try filter wizard to install device filter.

C# Skype API Video Call

I was working on a security monitor application and the best approach i found was Skype.
when a possible intrusion occurs the application calls a specified Skype ID which is probably my android phone i am done with all the image processing stuff. But i am stuck with this Skype API i wrote this piece of code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using SKYPE4COMLib;
namespace SkypeCall
{
class Program
{
static void Main(string[] args)
{
Skype skype;
skype = new Skype("Skype4COM.Skype", "Skype_");
Call call = skype.PlaceCall(SkypeID);
call.StartVideoSend();
}
}
}
This initiates a voice call but in the call.StartVideoSend(); shows an error
An unhandled exception of type 'System.Runtime.InteropServices.COMException' occurred in SkypeCall.exe
Additional information: CALL: Action failed
i even tried this but i guess that's old API and couldn't get anything out of it.
And not even by sending commands .
if somebody would help me out i'll be grateful.
I think you need to wait until the call is connected.
easiest way would be to test the call.Status
class Program
{
static void Main(string[] args)
{
Skype skype;
skype = new SKYPE4COMLib.Skype();
string SkypeID = args[1];
Call call = skype.PlaceCall(SkypeID);
do
{
System.Threading.Thread.Sleep(1);
} while (call.Status != TCallStatus.clsInProgress);
call.StartVideoSend();
}
}
You could also add an event, however I think this will fire on every call so unless you are only using it for this project it might be too much.
class Program
{
static string SkypeID = "";
static void Main(string[] args)
{
Skype skype;
skype = new SKYPE4COMLib.Skype();
skype.CallStatus += new _ISkypeEvents_CallStatusEventHandler(skype_CallStatus);
Call call = skype.PlaceCall(SkypeID);
Console.ReadKey();
}
static void skype_CallStatus(Call pCall, TCallStatus Status)
{
if (Status == TCallStatus.clsInProgress && pCall.PartnerHandle == SkypeID) { pCall.StartVideoSend(); }
}
}

Categories