I am trying to transfer a file to my iphone using 32feet bluetooth, but cannot seem to get past the ObexWebResponse.
I have read many post on this but none of the solutions seem to work for me.
The Error i get is
// Connect failed
// The requested address is not valid in its context "address:Guid"
private BluetoothClient _bluetoothClient;
private BluetoothComponent _bluetoothComponent;
private List<BluetoothDeviceInfo> _inRangeBluetoothDevices;
private BluetoothDeviceInfo _hlkBoardDevice;
private EventHandler<BluetoothWin32AuthenticationEventArgs> _bluetoothAuthenticatorHandler;
private BluetoothWin32Authentication _bluetoothAuthenticator;
public BTooth() {
_bluetoothClient = new BluetoothClient();
_bluetoothComponent = new BluetoothComponent(_bluetoothClient);
_inRangeBluetoothDevices = new List<BluetoothDeviceInfo>();
_bluetoothAuthenticatorHandler = new EventHandler<BluetoothWin32AuthenticationEventArgs>(_bluetoothAutenticator_handlePairingRequest);
_bluetoothAuthenticator = new BluetoothWin32Authentication(_bluetoothAuthenticatorHandler);
_bluetoothComponent.DiscoverDevicesProgress += _bluetoothComponent_DiscoverDevicesProgress;
_bluetoothComponent.DiscoverDevicesComplete += _bluetoothComponent_DiscoverDevicesComplete;
ConnectAsync();
}
public void ConnectAsync() {
_inRangeBluetoothDevices.Clear();
_hlkBoardDevice = null;
_bluetoothComponent.DiscoverDevicesAsync(255, true, true, true, false, null);
}
private void PairWithBoard() {
Console.WriteLine("Pairing...");
bool pairResult = BluetoothSecurity.PairRequest(_hlkBoardDevice.DeviceAddress, null);
if (pairResult) {
Console.WriteLine("Success");
Console.WriteLine($"Authenticated equals {_hlkBoardDevice.Authenticated}");
} else {
Console.WriteLine("Fail"); // Instantly fails
}
}
private void _bluetoothComponent_DiscoverDevicesProgress(object sender, DiscoverDevicesEventArgs e) { _inRangeBluetoothDevices.AddRange(e.Devices); }
private void _bluetoothComponent_DiscoverDevicesComplete(object sender, DiscoverDevicesEventArgs e) {
for (int i = 0; i < _inRangeBluetoothDevices.Count; ++i) {
if (_inRangeBluetoothDevices[i].DeviceName == "Uranus") {
_hlkBoardDevice = _inRangeBluetoothDevices[i];
PairWithBoard();
TransferFile();
return;
}
}
// no devices found
}
private void _bluetoothAutenticator_handlePairingRequest(object sender, BluetoothWin32AuthenticationEventArgs e) {
e.Confirm = true; // Never reach this line
}
// not working
// transfers a file to the phone
public void TransferFile() {
string file = "E:\\test.txt",
filename = System.IO.Path.GetFileName(file);
string deviceAddr = _hlkBoardDevice.DeviceAddress.ToString();
BluetoothAddress addr = BluetoothAddress.Parse(deviceAddr);
_bluetoothClient.Connect(BluetoothAddress.Parse(deviceAddr), BluetoothService.SerialPort);
Uri u = new Uri($"obex://{deviceAddr}/{file}");
ObexWebRequest owr = new ObexWebRequest(u);
owr.ReadFile(file);
// error:
// Connect failed
// The requested address is not valid in its context ...
var response = (ObexWebResponse)owr.GetResponse();
Console.WriteLine("Response Code: {0} (0x{0:X})", response.StatusCode);
response.Close();
}
The pairing and authentication works just fine, and I can get the BluetoothService.Handsfree to make a call for me but the transferring of the file fails. Not knowing what the actual error is, I tried almost every service available with no luck.
Can you help me figure out what is going on? This is my first attempt working with Bluetooth services so I still have a ton to learn.
Is it possible to transfer a file from iPhone to Windows desktop via Bluetooth?
However, in case you need to transfer media files (images, videos, etc) from Android device, you can use ObexListener class provided by 32Feet library for this purpose, and then you can simply call _obexListener.GetContext() method that will block and wait for incoming connections.
Once a new connection is received, you can save the received file to local storage, as shown in the below example:
ObexListener _listener = new ObexListener();
_listener.Start();
// This method will block and wait for incoming connections
ObexListenerContext _context = _listener.GetContext();
// Once new connection is received, you can save the file to local storage
_context.Request.WriteFile(#"c:\sample.jpg");
NOTE: When working with OBEX on Windows, make sure to disable the "Bluetooth OBEX Service" Windows service, in order not to let it handle the incoming OBEX requests instead of the desired application.
I walked away from this for a while. and started Trying to use xamiren but then had to create a virtual Mac so that I could have the apple store to just load software on my phone. From there xamerin 'should' work well but its another field and tons more to firgure out.
Related
I am trying to retrieve the rtsp stream from my server, and when I disconnect vlc (after sending a Teardown request), I want the vlc to reconnect.
When run from the console (vlc --repeat --rtsp-tcp rtsp://ip:port) everything works. But when running from wpf application, the --repeat command doesn't work.
var libDirectory = new DirectoryInfo(Path.Combine(currentDirectory, "libvlc", IntPtr.Size == 4 ? "win-x86" : "win-x64"));
this.VlcControl.SourceProvider.CreatePlayer(libDirectory, new string[] { "--rtsp-tcp", "--repeat" });
string liveLink = $"rtsp://{ip}:{port}/{kid}";
this.VlcControl.SourceProvider.MediaPlayer.Play(liveLink);
already tried using the command --loop and --insert-repeat=65535
Nothing works.
Can anyone suggest a solution to the issue?
// Declare a Delegate
delegate void delegate_vlc_play(Uri file, string[] pars);
// Make sure to link the Event
private void OnEndReached(object sender, Vlc.DotNet.Core.VlcMediaPlayerEndReachedEventArgs e)
{
if (_AutoLoop) // private field of externally visible Property "AutoLoop"
{
// Get a new instance of the delegate
delegate_vlc_play del_vlc = new delegate_vlc_play(myVLCControl.Play);
// Call asyncroneously (save _CurrentFile somewhere when you call the Play() in the first place)
del_vlc.BeginInvoke(new Uri(_CurrentFile), new string[] { }, null, null);
}
}
from https://github.com/ZeBobo5/Vlc.DotNet/issues/96
I'm developing an application for Windows 10 to send ZPL commands to a Zebra printer. For the life of me I cannot figure out how to send the raw commands. I can't use the printer dialog box before each print because the app needs to print documents as they come in from an external service. In short: no user intervention.
So far I'm successfully getting the DeviceInformation instance for the printer connected via USB. This is where I'm stuck. Here are the callbacks bound to XAML components for the device selection.
private async void selectPrinter_Click(object sender, RoutedEventArgs e)
{
picker = new DevicePicker();
picker.Filter.SupportedDeviceSelectors.Add("System.Devices.InterfaceClassGuid:=\"{0ecef634-6ef0-472a-8085-5ad023ecbccd}\"");
picker.DevicePickerDismissed += DevicePickerDismissed;
picker.DeviceSelected += DeviceSelected;
Rect rect = new Rect(100, 100, 200, 200);
picker.Show(rect);
}
private async void DeviceSelected(DevicePicker sender, DeviceSelectedEventArgs args)
{
settings.PrinterId = args.SelectedDevice.Id;
device = args.SelectedDevice;
await UpdatePrinterText();
picker.Hide();
}
private async Task UpdatePrinterText()
{
if (device == null)
{
var printerId = settings.PrinterId;
if (!string.IsNullOrWhiteSpace(printerId))
device = await DeviceInformation.CreateFromIdAsync(printerId);
}
await Dispatcher.RunAsync(CoreDispatcherPriority.High, () => printerName.Text = device?.Name ?? "(no printer selected)");
}
I've tried using UsbDevice to send raw commands, but the app errors out with System.IO.FileNotFoundException: 'The system cannot find the file specified. (Exception from HRESULT: 0x80070002)' on var usbDevice = await UsbDevice.FromIdAsync(device.Id); Full code:
private async void printTest_Click(object sender, RoutedEventArgs e)
{
if (device == null)
return;
var usbDevice = await UsbDevice.FromIdAsync(device.Id);
var outPipe = usbDevice.DefaultInterface.BulkOutPipes[0];
var stream = outPipe.OutputStream;
var writer = new DataWriter(stream);
var command = "^XA^FO10,10,^AO,30,20^FDFDTesting^FS^FO10,30^BY3^BCN,100,Y,N,N^FDTesting^FS^XZ";
var buffer = Encoding.ASCII.GetBytes(command);
writer.WriteBytes(buffer);
await writer.StoreAsync();
}
Update: the USB cord had come loose. So I plugged it in, and now UsbDevice.FromAsync is returning null. I guess MS REALLY doesn't want you mucking around with printers...
Sending raw ZPL to printers can be done with the Generic Text based driver.
This is small portion of window service code for fetching real-time attendance data from Biometric Device from cloud. Service is working but unable to get data from Device.This service is taking data from device and storing inside project folder making .log files.But when punched the card on device i get nothing.i am confusion on app.config files.There is local host(127.0.0.1:8080) as server in sdk of manufacturer which i got(but they are saying this is cloud based sdk).What should be server list in this case? Please help me.I am totally new in this WebSocketServer.
private void webSocketServer_NewMessageReceived(WebSocketSession session, string message) this method is used for registering new devices but this is not firing when i punched card to device.I am not pasting all codes here within this method.
using SuperWebSocket;
using SuperSocket.SocketBase;
public class WebSocketLoader
{
private static WebSocketServer webSocketServer;
public static Dictionary<string, string> _registeredDevices;
private WebSocketLoader(IWorkItem server)
{
var wsServer = server as WebSocketServer;
webSocketServer = wsServer;
}
public static WebSocketSession GetSessionByID(string sn)
{
if (_registeredDevices.ContainsKey(sn))
{
return webSocketServer.GetAppSessionByID(_registeredDevices[sn]);
}
else
return null;
}
public static void Setup(IWorkItem server)
{
var webSocketLoader = new WebSocketLoader(server);
webSocketLoader.AddNewMessageReceived();
webSocketLoader.AddNewSessionConnected();
webSocketLoader.AddSessionClosed();
_registeredDevices = new Dictionary<string, string>();
_registeredDevices.Clear();
}
public void AddNewMessageReceived()
{
webSocketServer.NewMessageReceived += new SessionHandler<WebSocketSession, string>(webSocketServer_NewMessageReceived);
}
public void AddNewSessionConnected()
{
webSocketServer.NewSessionConnected += new SessionHandler<WebSocketSession>(webSocketServer_NewSessionConnected);
}
private void webSocketServer_NewSessionConnected(WebSocketSession session)
{
Console.WriteLine(webSocketServer.GetAllSessions().Count());
LogHelper.Receive("NewConnected[" + session.RemoteEndPoint + "]");
}
private void webSocketServer_SessionClosed(WebSocketSession session, CloseReason reason)
{
LogHelper.Receive("Closed[" + session.RemoteEndPoint + "],Reason:" + reason);
}
private void webSocketServer_NewMessageReceived(WebSocketSession session, string message)
{
Console.WriteLine(webSocketServer.GetAllSessions().Count());
LogHelper.Receive("MessageReceived[" + session.RemoteEndPoint + "],Message:" + message);
}
}
App.config file contains following line
<RedisConfig WriteServerList="127.0.0.1:8080" ReadServerList="127.0.0.1:8080" MaxWritePoolSize="10000" MaxReadPoolSize="10000" DB="1" AutoStart="true" LocalCacheTime="180" RecordeLog="false">
127.0.0.1 meant for localhost. You need to update a valid IP and PORT in the biometric machine. Then if you use that IP & Port your code may work. Make sure the machine is connected in the same network.
In general, biometric machines can be not be associated with the public IP. Hence, TCP/IP communication with the machines installed in the remote location can not be done through cloud application.
For cloud communication from biometric machine, web api supported biometric machines can be used.
I am trying to record audio and play it directly (I want to hear my voice in the headphone without saving it) however the MediaElement and the MediaCapture seems non to work at the same time.
I initialized my MediaCapture so:
_mediaCaptureManager = new MediaCapture();
var settings = new MediaCaptureInitializationSettings();
settings.StreamingCaptureMode = StreamingCaptureMode.Audio;
settings.MediaCategory = MediaCategory.Other;
settings.AudioProcessing = AudioProcessing.Default;
await _mediaCaptureManager.InitializeAsync(settings);
However I don't really know how to proceed; I am wonderign if one of these ways could work (I tryied implement them without success, and I have not found examples):
Is there a way to use StartPreviewAsync() recording Audio, or it only works for Videos? I noticed that I get the following error:"The specified object or value does not exist" while setting my CaptureElement Source; it only happens if I write "settings.StreamingCaptureMode = StreamingCaptureMode.Audio;" while everyting works for .Video.
How can I record to a stream using StartRecordToStreamAsync(); I mean, how have I to initialize the IRandomAccessStream and read from it? Can I write on a stream while I keep reading for it?
I read that changing AudioCathegory of the MediaElement and the MediaCathegory of the MediaCapture to Communication there is a possibility it could work. However, while my code works (it just have to record and save in a file) with the previous setting, it don't works if I wrote "settings.MediaCategory = MediaCategory.Communication;" instead of "settings.MediaCategory = MediaCategory.Other;". Can you tell me why?
Here is my current program that just record, save and play:
private async void CaptureAudio()
{
try
{
_recordStorageFile = await KnownFolders.VideosLibrary.CreateFileAsync(fileName, CreationCollisionOption.GenerateUniqueName);
MediaEncodingProfile recordProfile = MediaEncodingProfile.CreateWav(AudioEncodingQuality.Auto);
await _mediaCaptureManager.StartRecordToStorageFileAsync(recordProfile, this._recordStorageFile);
_recording = true;
}
catch (Exception e)
{
Debug.WriteLine("Failed to capture audio:"+e.Message);
}
}
private async void StopCapture()
{
if (_recording)
{
await _mediaCaptureManager.StopRecordAsync();
_recording = false;
}
}
private async void PlayRecordedCapture()
{
if (!_recording)
{
var stream = await _recordStorageFile.OpenAsync(FileAccessMode.Read);
playbackElement1.AutoPlay = true;
playbackElement1.SetSource(stream, _recordStorageFile.FileType);
playbackElement1.Play();
}
}
If you have any suggestion I'll be gratefull.
Have a good day.
Would you consider targeting Windows 10 instead? The new AudioGraph API allows you to do just this, and the Scenario 2 (Device Capture) in the SDK sample demonstrates it well.
First, the sample populates all output devices into a list:
private async Task PopulateDeviceList()
{
outputDevicesListBox.Items.Clear();
outputDevices = await DeviceInformation.FindAllAsync(MediaDevice.GetAudioRenderSelector());
outputDevicesListBox.Items.Add("-- Pick output device --");
foreach (var device in outputDevices)
{
outputDevicesListBox.Items.Add(device.Name);
}
}
Then it gets to building the AudioGraph:
AudioGraphSettings settings = new AudioGraphSettings(AudioRenderCategory.Media);
settings.QuantumSizeSelectionMode = QuantumSizeSelectionMode.LowestLatency;
// Use the selected device from the outputDevicesListBox to preview the recording
settings.PrimaryRenderDevice = outputDevices[outputDevicesListBox.SelectedIndex - 1];
CreateAudioGraphResult result = await AudioGraph.CreateAsync(settings);
if (result.Status != AudioGraphCreationStatus.Success)
{
// TODO: Cannot create graph, propagate error message
return;
}
AudioGraph graph = result.Graph;
// Create a device output node
CreateAudioDeviceOutputNodeResult deviceOutputNodeResult = await graph.CreateDeviceOutputNodeAsync();
if (deviceOutputNodeResult.Status != AudioDeviceNodeCreationStatus.Success)
{
// TODO: Cannot create device output node, propagate error message
return;
}
deviceOutputNode = deviceOutputNodeResult.DeviceOutputNode;
// Create a device input node using the default audio input device
CreateAudioDeviceInputNodeResult deviceInputNodeResult = await graph.CreateDeviceInputNodeAsync(MediaCategory.Other);
if (deviceInputNodeResult.Status != AudioDeviceNodeCreationStatus.Success)
{
// TODO: Cannot create device input node, propagate error message
return;
}
deviceInputNode = deviceInputNodeResult.DeviceInputNode;
// Because we are using lowest latency setting, we need to handle device disconnection errors
graph.UnrecoverableErrorOccurred += Graph_UnrecoverableErrorOccurred;
// Start setting up the output file
FileSavePicker saveFilePicker = new FileSavePicker();
saveFilePicker.FileTypeChoices.Add("Pulse Code Modulation", new List<string>() { ".wav" });
saveFilePicker.FileTypeChoices.Add("Windows Media Audio", new List<string>() { ".wma" });
saveFilePicker.FileTypeChoices.Add("MPEG Audio Layer-3", new List<string>() { ".mp3" });
saveFilePicker.SuggestedFileName = "New Audio Track";
StorageFile file = await saveFilePicker.PickSaveFileAsync();
// File can be null if cancel is hit in the file picker
if (file == null)
{
return;
}
MediaEncodingProfile fileProfile = CreateMediaEncodingProfile(file);
// Operate node at the graph format, but save file at the specified format
CreateAudioFileOutputNodeResult fileOutputNodeResult = await graph.CreateFileOutputNodeAsync(file, fileProfile);
if (fileOutputNodeResult.Status != AudioFileNodeCreationStatus.Success)
{
// TODO: FileOutputNode creation failed, propagate error message
return;
}
fileOutputNode = fileOutputNodeResult.FileOutputNode;
// Connect the input node to both output nodes
deviceInputNode.AddOutgoingConnection(fileOutputNode);
deviceInputNode.AddOutgoingConnection(deviceOutputNode);
Once all of that is done, you can record to a file while at the same time playing the recorded audio like so:
private async Task ToggleRecordStop()
{
if (recordStopButton.Content.Equals("Record"))
{
graph.Start();
recordStopButton.Content = "Stop";
}
else if (recordStopButton.Content.Equals("Stop"))
{
// Good idea to stop the graph to avoid data loss
graph.Stop();
TranscodeFailureReason finalizeResult = await fileOutputNode.FinalizeAsync();
if (finalizeResult != TranscodeFailureReason.None)
{
// TODO: Finalization of file failed. Check result code to see why, propagate error message
return;
}
recordStopButton.Content = "Record";
}
}
I'm attempting to write a C# library which looks at all available USB serial ports on a Raspberry Pi so that I can enumerate, identify and communicate with a set of Arduinos connected to the Pi via a USB hub.
I am able to make this work on my windows machine (several Arduinos connected to my desktop computer) and have even been able to make it work on my Pi however, I am struggling to understand how to generalize the fix.
If I attempt to run the program by itself on the Pi, I am able to open the serial port and send data however, I cannot receive anything from the Arduinos: I get timeout exceptions. I understand that Mono's implementation of SerialPort is limited and I must use SerialPort.ReadByte() instead of Readline() and the data received events (my solution is based on code from HowToSystemIOPorts). My Serial port enumeration is using a method outlined in another stack exchange response here.
My timeout is currently set to 4 seconds, which is several orders of magnitude longer than I expect to receive the message.
After a lot of googling, I came across mention of using minicom to initialize the serial port here, which to my surprise allowed me to receive data from the Arduino. The biggest drawback is that I need to initialize the port using minicom and leave the process opening each time I boot the Pi. I also can't seem to figure out how to make this work with multiple Arduinos.
Here is what I have tried so far:
Updated the Pi firmware and software to their latest versions
Attempted to use both an Arduino MEGA 2560 R3 and Arduino UNO
Changed the owner of the tty* ports (ttyACM0 and ttyUSB0 in this case) to both my user and group
Successfully configured the port via minicom, left the process running and start the program and read/wrote data. A manual process which only seems to work for one Arduino at a time
Successfully run the program in Windows without fault
Verified the Arduinos are recognized by the Pi running "dmesg | grep tty"
Here is what I hope to solve:
Automatic setup/initialization of the Arduino serial ports. Whether through a shell script run before the main program or within Mono code so that the code below can run as intended.
Here is my connection code:
public bool StartArduinoComms()
{
string[] ports = GetPortNames();
foreach (string port in ports)
{
mLogger.LogMessage(ProsthesisCore.Utility.Logger.LoggerChannels.Arduino, string.Format("Found serial port {0}", port));
}
bool foundCorrectArduino = false;
var idPacket = new ArduinoMessageBase();
idPacket.ID = ArduinoMessageValues.kIdentifyValue;
string jsonOutput = Newtonsoft.Json.JsonConvert.SerializeObject(idPacket);
foreach (string port in ports)
{
SerialPort serialPort = new SerialPort(port, kArduinoCommsBaudRate);
serialPort.Parity = Parity.None;
serialPort.DataBits = 8;
serialPort.StopBits = StopBits.One;
//Only check unopened ports
if (!serialPort.IsOpen)
{
serialPort.Open();
//Disable telemtry just incase
var toggle = new { ID = ArduinoMessageValues.kTelemetryEnableValue, EN = false };
string disableTelem = Newtonsoft.Json.JsonConvert.SerializeObject(toggle);
serialPort.Write(disableTelem);
//Discard any built up data
serialPort.DiscardInBuffer();
serialPort.Write(jsonOutput);
serialPort.ReadTimeout = kIDTimeoutMilliseconds;
string response = string.Empty;
for (int i = 0; i < kNumRetries; ++i)
{
try
{
//This is guaranteed to timeout if not configured through minicom
response = ReadLine(serialPort);
break;
}
//Catch case where the serial port is unavailable. MOve to next port
catch (TimeoutException)
{
continue;
}
}
if (!string.IsNullOrEmpty(response))
{
//Perform response validation
}
else
{
//Got no response
}
if (!foundCorrectArduino)
{
serialPort.Close();
}
}
}
return foundCorrectArduino;
}
/// <summary>
/// From https://stackoverflow.com/questions/434494/serial-port-rs232-in-mono-for-multiple-platforms
/// </summary>
/// <returns></returns>
private static string[] GetPortNames()
{
int p = (int)Environment.OSVersion.Platform;
List<string> serial_ports = new List<string>();
// Are we on Unix?
if (p == 4 || p == 128 || p == 6)
{
string[] ttys = System.IO.Directory.GetFiles("/dev/", "tty*");
foreach (string dev in ttys)
{
//Arduino MEGAs show up as ttyACM due to their different USB<->RS232 chips
if (dev.StartsWith("/dev/ttyS") || dev.StartsWith("/dev/ttyUSB") || dev.StartsWith("/dev/ttyACM"))
{
serial_ports.Add(dev);
}
}
}
else
{
serial_ports.AddRange(SerialPort.GetPortNames());
}
return serial_ports.ToArray();
}
Have a look at stty command. It will let you set/read teminal settings
http://linux.about.com/od/lna_guide/a/gdelna38t01.htm will give a rundown on it's use.
It would be easier to call out to than minicom, and the settings stay on the device.
I have done something like the same as you before.
I had to read and write data through USB Serial adapter, and didnt use minicom.
It may not be god code but i found that inorder to read the data I could create a new thread and have that check for data, my code include a lot of stuff but basicly i did this:
System.Threading.Thread newThread;
newThread = new System.Threading.Thread(this.check_get_data);
and the check_get_data method
public void check_get_data ()
{
byte tmpByte = 0;
while (m_objSerialPort.BytesToRead != 0) {
tmpByte = (byte)m_objSerialPort.ReadByte ();
DoSomethingWithByte(tmpByte);
Thread.Sleep(20);
}
}
this is currently running with two usbserials. dont know if it helps but hope you find your solution