Automatic (bluetooth Pairing) with windows 7 and Mobile phone - c#

Currently i am programming USB Bluetooth Dongle in C# 2010. I want to program in such a way that it automatically pairs with the Bluetooth device found. I don't want the user to manually accept the pairing request in both Mobile phone as well as in Windows 7. I am using my phone (X Peria S) to test this. Is this method of programming possible? I tried to code this using 32feet.net library for the Bluetooth, here is my code
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using InTheHand.Net;
using InTheHand.Net.Bluetooth;
using InTheHand.Net.Sockets;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
private Guid service = BluetoothService.BluetoothBase;
private BluetoothClient bluetoothClient;
public Form1()
{
InitializeComponent();
}
private void Search_Bluetooth(object sender, EventArgs e)
{
BluetoothRadio.PrimaryRadio.Mode = RadioMode.Discoverable;
bluetoothClient = new BluetoothClient();
Cursor.Current = Cursors.WaitCursor;
BluetoothDeviceInfo [] bluetoothDeviceInfo = bluetoothClient.DiscoverDevices(10);
comboBox1.DataSource = bluetoothDeviceInfo;
comboBox1.DisplayMember = "DeviceName";
comboBox1.ValueMember = "DeviceAddress";
comboBox1.Focus();
Cursor.Current = Cursors.Default;
}
private void Pair(object sender, EventArgs e)
{
if (comboBox1.SelectedValue != null)
{
try
{
bluetoothClient.Connect(new BluetoothEndPoint((BluetoothAddress)comboBox1.SelectedValue, service));
MessageBox.Show("Connected");
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
}
}
}
When i run this project i see the list of Bluetooth device in the surrounding but when ever i want to pair with it gives me an error saying "A connection attempt failed because the connected party did not properly respond a period of time"
I think the problem is private Guid service = BluetoothService.BluetoothBase but i am not sure, am i using the right service .BluetoothBase to pair with my phone?
Is there any existing solution for this? Any help and suggestion is highly appreciated.
Thanks.

You have to know the PIN for your dongle that will be requested during authentication.
If you want to connect to e.g. a mobile bluetooth RS-232 dongle, you have to know the PIN, but you don't have to accept the connection on the remote device (RS-232 dongle) because of the lack of a user interface. But on a mobile phone you have to.
I wrote the following interface:
interface IStackAdapter
{
IList<IRemoteBTDevice> DiscoveredDevices { get; }
void LoadStack();
void DoInquiry();
void DoConnection(IRemoteBTDevice rd);
void ReleaseLink();
}
Next, I implemented that interface for each different bluetooth stack. Here is the connection for a Widcomm stack:
/// <summary>
/// Connects to a remote device.
/// </summary>
/// <param name="rd">Remote device that the adapter is supposed to connect to.</param>
public void DoConnection(IRemoteBTDevice rd)
{
BluetoothAddress remoteAddress = new BluetoothAddress(Convert.ToInt64(rd.Id, 16));
BluetoothDeviceInfo bdi = new BluetoothDeviceInfo(remoteAddress);
try
{
if (!bdi.Authenticated)
{
string pair = rd.Pin; /* PIN for your dongle */
bool paired = BluetoothSecurity.PairRequest(bdi.DeviceAddress, pair);
}
}
catch (Exception ex)
{
//Log and rethrow
}
}

If you use a Windows Phone you can use the PeerFinder in Windows Phone to connect:
PeerFinder.AlternateIdentities["Bluetooth:PAIRED"] = "";
var available_devices = await PeerFinder.FindAllPeersAsync();
HostName hostName = null;
for (int i = 0; i < available_devices.Count; i++)
{
PeerInformation dispositivo = available_devices[i];
if (dispositivo.DisplayName.ToUpper() == /*Name of you device */)
{
hostName = dispositivo.HostName;
break;
}
}
if (hostName != null)
{
var socket = new StreamSocket();
await socket.ConnectAsync(hostName, "1");
}

Related

c# - Omron PLC read DM table via UDP

I try to read OMRON plc's DM table with a C# WPF application beacuse I have to visualize live datas from the machine.
I can read messages via UDP, but I dont know how to read the DM table from the PLC. (PLC's settings are okay, that is ready to the FINS communication)
Here is my code for reading messages via UDP:
using System;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Windows.Forms;
namespace OMRON_FINS
{
public partial class Form2 : Form
{
UdpClient Client = new UdpClient(9600); // PORT number
string data = "";
public Form2()
{
InitializeComponent();
textBox1.Text = GetLocalIPAddress();
}
public static string GetLocalIPAddress()
{
var host = Dns.GetHostEntry(Dns.GetHostName());
foreach (var ip in host.AddressList)
{
if (ip.AddressFamily == AddressFamily.InterNetwork)
{
return ip.ToString();
}
}
throw new Exception("No network adapters with an IPv4 address in the system!");
}
private void button1_Click(object sender, EventArgs e)
{
try
{
Client.BeginReceive(new AsyncCallback(recv), null);
label5.Text = "Reading....";
}
catch (Exception ex)
{
richTextBox1.Text += ex.Message.ToString();
}
}
public void recv(IAsyncResult res)
{
IPEndPoint RemoteIP = new IPEndPoint(IPAddress.Any, 60240);
byte[] received = Client.EndReceive(res, ref RemoteIP);
data = Encoding.UTF8.GetString(received);
this.Invoke(new MethodInvoker(delegate
{
richTextBox1.Text += "\nReceived data: " + data;
}));
Client.BeginReceive(new AsyncCallback(recv), null);
}
}
}
Is there any example or guide to read the DM table?
Thanks!

How to connect a gsm modem AUTOMATICALLY to available COM ports (without combobox)

THIS QUESTION MAY SEAM A DUPLICATE, BUT NOT. after a long period of search on internet and no, result, then had to seek for assistance.
All solutions apply to loading available ports in a combo box and the user checks one at a go. But the automation feature then dies.
thus, im looking for assistance on how the modem can connect automatically from the available ports without user interaction (USER FRIENDLINESS)
FOR THE COMBO BOX, IT IS WORKING FINE AS BELOW,
using GsmComm.GsmCommunication;
using GsmComm.PduConverter;
using GsmComm.Server;
using MySql.Data.MySqlClient;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Configuration;
using System.Data;
using System.Drawing;
using System.IO.Ports;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace COMM_All
{
public partial class Comm_F : Form
{
public Comm_F()
{
InitializeComponent();
}
private void COM_PORTS()
{
string[] ports = SerialPort.GetPortNames();
txtGPort1.Items.AddRange(ports);
txtGPort2.Items.AddRange(ports);
}
private void Form1_Load(object sender, EventArgs e)
{
COM_PORTS();
}
private void Modem1_Click(object sender, EventArgs e)
{
if (txtGPort1.Text == "") { MessageBox.Show("Invalid Port Name"); return; }
comm = new GsmCommMain(txtGPort1.Text, 9600, 8);
Cursor.Current = Cursors.Default;
bool retry;
do
{
retry = false;
try
{
Cursor.Current = Cursors.WaitCursor; comm.Open(); Cursor.Current = Cursors.Default;
//MessageBox.Show("Modem Connected Sucessfully");
txtGStatus1.Text = "Connected Sucessfully";
comm.EnableMessageNotifications();
MessageBox.Show("Message notifications activated.");
}
catch (Exception)
{
Cursor.Current = Cursors.Default;
if (MessageBox.Show(this, "GSM Modem is not available", "Check",
MessageBoxButtons.RetryCancel, MessageBoxIcon.Warning) == DialogResult.Retry)
retry = true;
else { return; }
}
} while (retry);
}
}
}
Note: Computer has multiple usb devices;

AudioSwitcher API change output device

I made a small gadget with an Arduino that sends 2 values via serial to my c# program (potentiometer value for volume and switch button to change output device). The volume part is already complete but I'm not being able to change between the two output devices (monitor audio and Headphones).
My code at the moment:
using AudioSwitcher.AudioApi.CoreAudio;
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;
namespace Volume
{
public partial class Form1 : Form
{
//msg recieved by serial
String msg;
string[] tokens;
//active device
CoreAudioDevice defaultPlaybackDevice = new CoreAudioController().DefaultPlaybackDevice;
String PHONES = "Headphones (Razer Kraken USB)";
String COLUNA = "ASUS VP228-4 (NVIDIA High Definition Audio)";
public Form1()
{
//open port for serial msg and start timmer
InitializeComponent();
serialPort1.Open();
timer1.Enabled = true;
}
private void serialPort1_DataReceived(object sender, System.IO.Ports.SerialDataReceivedEventArgs e)
{
//handling of the msg
msg = serialPort1.ReadLine();
tokens = msg.Split('%');
}
private void timer1_Tick(object sender, EventArgs e)
{
label1.Text = tokens[0];
label2.Text = tokens[1];
label6.Text = defaultPlaybackDevice.FullName;
//change volume
defaultPlaybackDevice.Volume = Int32.Parse(tokens[0]);
//change output device
if (tokens[1] == "ON")
{
if (defaultPlaybackDevice.FullName == PHONES)
{
//do nothing
}
else
{
//change to monitor output
}
}
else
{
if (defaultPlaybackDevice.FullName == COLUNA)
{
//do nothing
}
else
{
//change to headphones
}
}
}
}
}
I am using an API called AudioSwitcher.AudioApi.CoreAudio which should allow me to do what I want but I am not being able to find how.
First you need to get all the PlaybackDevices
IEnumerable<CoreAudioDevice> devices = new CoreAudioController().GetPlaybackDevices();
and then you can make a function to change your Default playbackdevice with the fullname like this
private void ChangeOutput(string op)
{
foreach (CoreAudioDevice d in devices)
{
if (d.FullName == op)
d.SetAsDefault();
}
}

How to connect to instrument through USB using c#

I am trying to use the Ivi.Visa.Interop .dll to communicate to a Voltech PM1000+ power meter using USB. I'm relatively new to C# and do not know really where to start. I am using Visual Studio 2015 Community. I have already talked to a different instrument using GPIB and here is the code for that:
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 Ivi.Visa.Interop;
namespace commOverIP
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void InitiateIOBtn_Click(object sender, EventArgs e)
{
///testing out excel
InitiateIOBtn.Text = "Initializing";
try
{
// resource manager and message-based session manager
Ivi.Visa.Interop.ResourceManager mngr = new Ivi.Visa.Interop.ResourceManager();
// GPIB address
string srcAddress = "GPIB::27::INSTR"; // GPIB address of data acquisition
//setting up communication
Ivi.Visa.Interop.FormattedIO488 instrument = new Ivi.Visa.Interop.FormattedIO488();
Ivi.Visa.Interop.IMessage Imsg = (mngr.Open(srcAddress, Ivi.Visa.Interop.AccessMode.NO_LOCK, 1000, "") as IMessage);
instrument.IO = Imsg;
instrument.IO.Clear();//clear io buffer
instrument.WriteString("*RST", true);//send RST? command to instrument
instrument.WriteString("*IDN?", true);//send IDN? command to instrument
returnOfCommand.Text = instrument.ReadString();//read IDN? result
//close communication
instrument.IO.Close();
System.Runtime.InteropServices.Marshal.ReleaseComObject(instrument);
System.Runtime.InteropServices.Marshal.ReleaseComObject(mngr);
InitiateIOBtn.Text = "Initialize I/O";
//*/
}
catch(Exception exp)
{
MessageBox.Show(exp.Message);
}
InitiateIOBtn.Text = "Initialize I/O";
}
}
}
This works fine but USB seems to be a different beast. The only real lead I found was in the .dll with the:
IUsb.Init(string, Ivi.Visa.Interop.AccessMode, int, string)
I tried implementing this but I don't really know where to start.
If anyone could give me an example of how to query a "*IDN?" command that would be great. Or, even if there is a better way of doing this than through the Ivi.Visa.Interop dll.
Thanks in advance
Restart your device once. Clearing the IO also helps. Afterwards following code should work fine:
string resourceString= "USB0::xxx::xxx::xxx::0::INSTR";
ResourceManager manager = new ResourceManager();
FormattedIO488 connection = new FormattedIO488();
connection.IO = (IMessage)manager.Open(resourceString, AccessMode.NO_LOCK, 0, "");
connection.IO.Clear();
connection.WriteString("*IDN?", true);
string result = connection.ReadString();
I do what you are asking all of the time and I completely understand how frustrating it can be. I remember doing Google searches to come up with this code. The code actually came from some Keysight documentation when I bought the Agilent 82357B USB/GPIB Controller.
This can be adapted for any GPIB instrument, the only difference being the strings that you send to the instrument. These can be obtained by getting the programming manual for the instrument in which you're interested.
I installed the Keysight (formerly Agilent) I/O Library Suites that is used with the Agilent 82357B. One thing that is not obvious is that you should disable the 'Auto Discovery' option, as this feature will occasionally put your device in Local mode.
using System.Threading;
using System.Runtime.InteropServices;
// Add reference for VISA-COM 5.9 Type Library
using Ivi.Visa.Interop;
namespace USBCommunications
{
class Program
{
static void Main(string[] args)
{
Gpib.Write(address: 5, command: "*IDN?");
bool success = Gpib.Read(address: 5, valueRead: out string valueRead);
System.Console.WriteLine($"The ID is {valueRead}");
System.Console.ReadLine();
}
}
public class Gpib
{
static ResourceManager resourceManager;
static FormattedIO488 ioObject;
public static bool Write(byte address, string command)
{
resourceManager = new ResourceManager();
ioObject = new FormattedIO488();
string addr = $"GPIB::{address.ToString()}::INSTR";
try
{
ioObject.IO = (IMessage)resourceManager.Open(addr, AccessMode.NO_LOCK, 0, "");
Thread.Sleep(20);
ioObject.WriteString(data: command, flushAndEND: true);
return true;
}
catch
{
return false;
}
finally
{
try { ioObject.IO.Close(); }
catch { }
try { Marshal.ReleaseComObject(ioObject); }
catch { }
try { Marshal.ReleaseComObject(resourceManager); }
catch { }
}
}
public static bool Read(byte address, out string valueRead)
{
resourceManager = new ResourceManager();
ioObject = new FormattedIO488();
string addr = $"GPIB::{address.ToString()}::INSTR";
try
{
ioObject.IO = (IMessage)resourceManager.Open(addr, AccessMode.NO_LOCK, 0, "");
Thread.Sleep(20);
valueRead = ioObject.ReadString();
return true;
}
catch
{
valueRead = "";
return false;
}
finally
{
try { ioObject.IO.Close(); }
catch { }
try { Marshal.ReleaseComObject(ioObject); }
catch { }
try { Marshal.ReleaseComObject(resourceManager); }
catch { }
}
}
}
}
Happy programming!!

Interfacing Arduino with pc GUI using C#

I am just a beginner in c#. I am now trying to interface arduino with a GUI application. And i need a small function to automatically detect the port which I have connected Arduino. I tried using nested "try and catch" blocks but it failed. can anyone suggest a good way to automatic select the port in which arduino is connected and open that port such that we can move directly to coding other switches that do different functions in that arduino.
Recently i had the same situation and i wrote this method to check for our device, all you need to set your device to send specific Pattern on Specific input. In this example if you send 0x33 then your device have to send 0x8A to identify itself.
public enum SerialSignal
{
SendSync = 0x33,
ReceiveSync = 0x8A,
}
private static SerialPort _arduinoSerialPort ;
/// <summary>
/// Polls all serial port and check for our device connected or not
/// </summary>
/// <returns>True: if our device is connected</returns>
public static bool Initialize()
{
var serialPortNames = SerialPort.GetPortNames();
foreach (var serialPortName in serialPortNames)
{
try
{
_arduinoSerialPort = new SerialPort(serialPortName) { BaudRate = 9600 };
_arduinoSerialPort.Open();
_arduinoSerialPort.DiscardInBuffer();
_arduinoSerialPort.Write(new byte[] { (int)SerialSignal.SendSync }, 0, 1);
var readBuffer = new byte[1];
Thread.Sleep(500);
_arduinoSerialPort.ReadTimeout = 5000;
_arduinoSerialPort.WriteTimeout = 5000;
_arduinoSerialPort.Read(readBuffer, 0, 1);
// Check if it is our device or Not;
if (readBuffer[0] == (byte)SerialSignal.ReceiveSync){
return true;
}
}
catch (Exception ex)
{
Debug.WriteLine("Exception at Serial Port:" + serialPortName + Environment.NewLine +
"Additional Message: " + ex.Message);
}
// if the send Sync repply not received just release resourceses
if (_arduinoSerialPort != null) _arduinoSerialPort.Dispose();
}
return false;
}
public partial class Form1 : Form
{
SerialPort serial = new SerialPort();
static SerialPort cport;
public Form1()
{
InitializeComponent();
button1.Enabled = true;
button2.Enabled = false;
button3.Enabled = false;
}
private void button1_Click(object sender, EventArgs e)
{
int i;
try
{
string[] ports = SerialPort.GetPortNames();
foreach(string newport in ports)
{
cport = new SerialPort(newport, 9600);
cport.Open();
cport.WriteLine("A");
int intReturnASCII = serial.ReadByte();
char returnMessage = Convert.ToChar(intReturnASCII);
if (returnMessage == 'B')
{
button2.Enabled = true;
break;
}
else
{
cport.Close();
}
}
}
catch (Exception )
{
Console.WriteLine("No COM ports found");
}
}
I undertand that I'm a bit late, But I have created a simple and free C# NuGet library that allows for interaction between the host PC and an Arduino board!
Examples in the ReadMe.txt file.
ArduinoFace - NuGet

Categories

Resources