public void GrantLocalUARTCredits()
{
if (this.PendingLocalUARTCreditsCount != 0) return;
this.PendingLocalUARTCreditsCount = this.MaxLocalUARTCreditsCount -
this.LocalUARTCreditsCount;
Byte[] byteData = new Byte[1];
byteData[0] = (Byte)((this.PendingLocalUARTCreditsCount & 0xFF));
NSData valueData = (NSData.FromArray(byteData));
Characteristic UartRxCreditsCharacteristic = "00000003-0000-1000-
8000-008025000000";(error here)
this.CbPeripheral.WriteValue(valueData, this.UartRxCreditsCharacteristic, CBCharacteristicWriteType.WithoutResponse);
}
I'm using CoreBluetools in a xamarin C# project and
get null reference exception with the last line as the CBCharacteristic I think is not defined. At the top of the file I define CBCharacteristic with
public CBCharacteristic UartRxCreditsCharacteristic {get ; set;}
and in this file below this I set the uuid with
public static string UART_RX_CREDITS_UUID = " 00000003-0000-1000-8000-008025000000"
I can discover,connect and disconnect with the app as it worked with our original device but with this device it requires RX/TX credits to communicate (1 credit for each 20 byte packet max 255 credits). This bit of code is from the original translated Objective C (to C#) manufacturers code and the error is the WriteValue code line says 'Null reference Exception'((object reference not set to an instance of an object) as I think the Characteristic can't be found when I run the code. enter code here
Not sure how to solve this. Nick
This code does the trick
internal void Connect(CBPeripheral peripheral)
{
peripheral.DiscoveredService += (sender, e) =>
{
if (peripheral.Services == null) { return; }
foreach (var s in peripheral.Services)
// var s in peripheral.Services
{
//if (s.UUID.ToString().Contains("0000f100"))
if (s.UUID.ToString().Contains("fefb"))
//s = s.UUID.ToString();
{
service = s;
peripheral.DiscoverCharacteristics(service);
};
}
};
peripheral.DiscoveredCharacteristic += (sender, e) =>
{
foreach (var c in service.Characteristics)
{
if (c.UUID.ToString() == (TIO_UART_RX_UUID))
{
UartRxCharacteristic = c;
}
}
foreach (var c in service.Characteristics)
{
if (c.UUID.ToString() == (TIO_UART_RX_CREDITS_UUID))
{
UartRxCreditsCharacteristic = c;
}
}
foreach (var c in service.Characteristics)
{
if (c.UUID.ToString() == (TIO_UART_TX_CREDITS_UUID))
{
UartTxCreditsCharacteristic = c;
peripheral.SetNotifyValue(true, c);
}
}
foreach (var c in service.Characteristics)
{
if (c.UUID.ToString() == (TIO_UART_TX_UUID))
// {
Related
I used libUsbDotNet library (C#) to read data from USB device.
The program sees the device and turns to it, but gives a response IoTimedOut.
The program code is shown below.
public static UsbDeviceFinder MyUsbFinder = new UsbDeviceFinder(0x10C4, 0xEA61);
public static UsbDevice MyUsbDevice;
public static void Main()
{
MyUsbDevice = UsbDevice.OpenUsbDevice(MyUsbFinder);
if (MyUsbDevice == null) throw new Exception("Device Not Found.");
IUsbDevice wholeUsbDevice = MyUsbDevice as IUsbDevice;
if (!ReferenceEquals(wholeUsbDevice, null))
{
wholeUsbDevice.SetConfiguration(1);
wholeUsbDevice.ClaimInterface(0);
}
UsbEndpointReader reader = MyUsbDevice.OpenEndpointReader(ReadEndpointID.Ep01);
ErrorCode ec = ErrorCode.None;
int bytesRead = 0;
byte[] readBuffer = new byte[32];
while (true) {
Thread.Sleep(100);
ec = reader.Read(readBuffer, 1500, out bytesRead);
if (bytesRead > 0)
{
Console.WriteLine("Data Received");
// Console.Write(Encoding.Default.GetString(readBuffer, 0, bytesRead));
}
else {
Console.Write("Error type: ");
Console.WriteLine(ec);
Console.ReadKey();
MyUsbDevice.Close();
break;
}
}
}
I tried to change the reading parameters but it doesn't help. Can you please tell me what it may be related to, it is not clear to me from the libUsbDotNet documentation?
I recently received a BLE device for Bluetooth to Serial. It uses TruConnect and I'm trying to get it to communicate with my serial device. The serial device receives communication over a serial cable and echoes back anything that is sent to it as well as any results from a command that is sent.
Right now I'm simply trying to send TruConnect commands to the BLE device to check the current baud rate that the BLE device is set for.
I wrote some code based on this TruConnect guide that I found:
https://truconnect.ack.me/1.5/apps/communicating_via_ble#reading_from_a_truconnect_device_serial_interface.
The problem seems to be that whenever I try to read anything from the tx characteristic when there should be data, the data is not right.
Setting up CBPeripheral events:
private void setupPerif(CBPeripheral perf)
{
selectedPeripheral = perf;
selectedPeripheral.UpdatedCharacterteristicValue += (sender, e) =>
{
var c = e.Characteristic;
if (c != null)
{
var uuid = c.UUID.ToString(true).ToLower();
if (uuid == UUID_RX)
{
//
}
else if (uuid == UUID_TX)
{
// expecting bytes to contain valid response data
// it almost always contains twenty 0s.
byte[] bytes = c.Value.Where(i => i != 13).ToArray();
var invalidBytes = c.Value.Where(i => i > 127).ToArray();
var nonZeros = c.Value.Where(i => i != 0).ToArray();
if (nonZeros.Length < 1)
{
return;
}
else
{
foreach (byte b in bytes)
handler.handleByteReceived((char)b);
}
}
else if (uuid == UUID_MODE)
{
//
}
}
};
selectedPeripheral.DiscoveredService += (sender, e) =>
{
var services = selectedPeripheral.Services;
if (services != null)
{
foreach (CBService service in services)
{
if (service.UUID.ToString(true).ToLower() == UUID_TRUCONNECT)
{
truConnect = service;
selectedPeripheral.DiscoverCharacteristics(truConnect);
}
}
}
};
selectedPeripheral.DiscoveredCharacteristic += (sender, e) =>
{
if (truConnect != null && truConnect.Characteristics != null)
{
foreach (CBCharacteristic c in truConnect.Characteristics)
{
var uuidString = c.UUID.ToString(true).ToLower();
if (uuidString == UUID_RX)
{
rx = c;
}
else if (uuidString == UUID_TX)
{
tx = c;
}
else if (uuidString == UUID_MODE)
{
mode = c;
// set to stream mode
selectedPeripheral.WriteValue(NSData.FromArray(new byte[] { MODE_COMMAND }), mode, CBCharacteristicWriteType.WithResponse);
}
}
}
};
selectedPeripheral.WroteCharacteristicValue += (sender, e) =>
{
// if UUID is for RX, we just wrote to RX. Drill down to
// TX characteristic and read it. This will trigger
// the UpdatedCharacteristicValue event.
string uuid = e.Characteristic.UUID.ToString(true).ToLower();
if (uuid == UUID_RX)
{
var services = selectedPeripheral.Services;
if (services != null)
{
foreach (CBService s in services)
{
if (s.UUID.ToString(true).ToLower() == UUID_TRUCONNECT)
{
var charachteristics = s.Characteristics;
if (charachteristics != null && charachteristics.Length > 0)
{
foreach (CBCharacteristic c in charachteristics)
{
if (c.UUID.ToString(true).ToLower() == UUID_TX)
{
Timer t = new Timer(new TimerCallback(delegate(object o)
{
selectedPeripheral.ReadValue(c);
}), null, TimeSpan.FromMilliseconds(100), TimeSpan.FromMilliseconds(-1));
}
}
}
}
}
}
}
};
manager.ConnectPeripheral(selectedPeripheral);
}
Writes to rx. This is what should be used to actually send commands.
public void sendCommand(string command)
{
command += endString + "\n";
if (rx != null)
{
NSData d = NSData.FromString(command);
foreach (CBService s in selectedPeripheral.Services)
{
if (s.UUID.ToString(true).ToLower() == UUID_TRUCONNECT)
foreach (CBCharacteristic c in s.Characteristics)
{
if (c.UUID.ToString(true).ToLower() == UUID_RX)
selectedPeripheral.WriteValue(NSData.FromString(command), c, CBCharacteristicWriteType.WithResponse);
}
}
}
}
So my question is, why am I not getting the expected data when the CBPeripheral.UpdatedCharacteristicValue event is called? Occasionally I will get the expected data, but it is quite rare, and I can't seem to find any logical reason or pattern that would explain why this is happening.
AHA! I figured it out!
The problem was that I need to set the notify value for the appropriate characteristics. After doing that, I didn't need to call CBPeripheral.ReadValue(CBCharacteristic).
selectedPeripheral.DiscoveredCharacteristic += (sender, e) =>
{
if (truConnect != null && truConnect.Characteristics != null)
{
foreach (CBCharacteristic c in truConnect.Characteristics)
{
var uuidString = c.UUID.ToString(true).ToLower();
if (uuidString == UUID_RX)
{
rx = c;
}
else if (uuidString == UUID_TX)
{
tx = c;
// set the notify value to true and poof!
// now CBPeripheral.UpdatedCharacteristicValue
// event will be triggered at the appropriate time.
selectedPeripheral.SetNotifyValue(true, tx);
}
else if (uuidString == UUID_MODE)
{
mode = c;
// set to remote command mode
selectedPeripheral.WriteValue(NSData.FromArray(new byte[] { MODE_COMMAND }), mode, CBCharacteristicWriteType.WithResponse);
}
}
}
};
I am using following code for getting contents of a web page
String url = "http://abc.com/qrticket.asp?qrcode="
+ "2554";
try {
url += ";deviceside=true;interface=wifi;ConnectionTimeout=" + 50000;
HttpConnection connection = (HttpConnection) Connector.open(url,
Connector.READ_WRITE);
connection.setRequestMethod(HttpConnection.GET);
// connection.openDataOutputStream();
InputStream is = connection.openDataInputStream();
String res = "";
int chr;
while ((chr = is.read()) != -1) {
res += (char) chr;
}
is.close();
connection.close();
showDialog(parseData(res));
} catch (IOException ex) {
ex.printStackTrace();
showDialog("http: " + ex.getMessage());
} catch (Exception ex) {
ex.printStackTrace();
showDialog("unknown: " + ex.getMessage());
}
public void showDialog(final String text) {
UiApplication.getUiApplication().invokeLater(new Runnable() {
public void run() {
Dialog.alert(text);
}
});
}
public String parseData(String str) {
String[] data = split(str, "//");
StringBuffer builder = new StringBuffer();
for (int i = 0; i < data.length; i++) {
System.out.println("data:" + data[i]);
String[] vals = split(data[i], ">>");
if (vals.length > 1) {
System.out.println(vals[0]);
builder.append(vals[0].trim()).append(": ")
.append(vals[1].trim()).append("\n");
} else {
builder.delete(0, builder.toString().length()).append(
vals[0].trim());
break;
}
}
return builder.toString();
}
public String[] split(String splitStr, String delimiter) {
// some input validation
if (delimiter == null || delimiter.length() == 0) {
return new String[] { splitStr };
} else if (splitStr == null) {
return new String[0];
}
StringBuffer token = new StringBuffer();
Vector tokens = new Vector();
int delimLength = delimiter.length();
int index = 0;
for (int i = 0; i < splitStr.length();) {
String temp = "";
if (splitStr.length() > index + delimLength) {
temp = splitStr.substring(index, index + delimLength);
} else {
temp = splitStr.substring(index);
}
if (temp.equals(delimiter)) {
index += delimLength;
i += delimLength;
if (token.length() > 0) {
tokens.addElement(token.toString());
}
token.setLength(0);
continue;
} else {
token.append(splitStr.charAt(i));
}
i++;
index++;
}
// don't forget the "tail"...
if (token.length() > 0) {
tokens.addElement(token.toString());
}
// convert the vector into an array
String[] splitArray = new String[tokens.size()];
for (int i = 0; i > splitArray.length; i++) {
splitArray[i] = (String) tokens.elementAt(i);
}
return splitArray;
}
This is working absolutely fine in simulator but giving 'http:null' (IOException) on device, I dont know why??
How to solve this problem?
Thanks in advance
I think the problem might be the extra connection suffixes you're trying to add to your URL.
http://abc.com/qrticket.asp?qrcode=2554;deviceside=true;interface=wifi;ConnectionTimeout=50000
According to this BlackBerry document, the ConnectionTimeout parameter isn't available for Wifi connections.
Also, I think that if you're using Wifi, your suffix should simply be ";interface=wifi".
Take a look at this blog post on making connections on BlackBerry Java, pre OS 5.0. If you only have to support OS 5.0+, I would recommend using the ConnectionFactory class.
So, I would try this with the url:
http://abc.com/qrticket.asp?qrcode=2554;interface=wifi
Note: it's not clear to me whether your extra connection parameters are just ignored, or are actually a problem. But, since you did get an IOException on that line, I would try removing them.
The problem was that no activation of blackberry internet service. After subscription problem is solved.
Thanks alto all of you especially #Nate
Hi am trying to run my app on blackberry device using Edge gprs connection but its not rendering the pages.i have tried lot to get the connection,also i tried the various links to solve, one of the simple code i have attached here, kindly guide me to solve this
public static String getConnectionString() {
String value="" ;
if(WLANInfo.getWLANState() == WLANInfo.WLAN_STATE_CONNECTED)
{
value=";interface=wifi";
}else{
value=";deviceside=true";
}
return value;
}
Append the connection string to your url. Then try
public static String getConnectionString() {
// This code is based on the connection code developed by Mike Nelson of
// AccelGolf.
// http://blog.accelgolf.com/2009/05/22/blackberry-cross-carrier-and-cross-network-http-connection
String connectionString = null;
// Simulator behavior is controlled by the USE_MDS_IN_SIMULATOR
// variable.
if (DeviceInfo.isSimulator()) {
connectionString = ";deviceSide=true";
}
// Wifi is the preferred transmission method
else if (WLANInfo.getWLANState() == WLANInfo.WLAN_STATE_CONNECTED) {
// System.out.println("Device is connected via Wifi.");
connectionString = ";interface=wifi";
}
// Is the carrier network the only way to connect?
else if ((CoverageInfo.getCoverageStatus() & CoverageInfo.COVERAGE_DIRECT) == CoverageInfo.COVERAGE_DIRECT) {
// System.out.println("Carrier coverage.---->>" + CoverageInfo.getCoverageStatus());
String carrierUid = getCarrierBIBSUid();
// DebugScreen.Log(" carrierUid is: " + carrierUid);
if (carrierUid == null) {
// Has carrier coverage, but not BIBS. So use the carrier's TCP
// network
// System.out.println("No Uid");
String wapString = getAvailableConnectionsString();
// DebugScreen.Log("from wap2 connection--->" + wapString);
if(wapString == null){
connectionString = ";deviceside=true";
}else{
connectionString = wapString;
}
} else {
// otherwise, use the Uid to construct a valid carrier BIBS
// request
connectionString = ";deviceside=true;connectionUID=" + carrierUid + ";ConnectionType=mds-public";
}
}
// Check for an MDS connection instead (BlackBerry Enterprise Server)
else if ((CoverageInfo.getCoverageStatus() & CoverageInfo.COVERAGE_MDS) == CoverageInfo.COVERAGE_MDS) {
// System.out.println("MDS coverage found");
connectionString = ";deviceside=false";
}
// If there is no connection available abort to avoid bugging the user
// unnecssarily.
else if (CoverageInfo.getCoverageStatus() == CoverageInfo.COVERAGE_NONE) {
// System.out.println("There is no available connection.");
}
// In theory, all bases are covered so this shouldn't be reachable.
else {
// System.out.println("no other options found, assuming device.");
connectionString = ";deviceside=true";
}
return connectionString;
}
Add this method and append connection String to url.
private static String getCarrierBIBSUid() {
ServiceRecord[] records = ServiceBook.getSB().getRecords();
int currentRecord;
for (currentRecord = 0; currentRecord < records.length; currentRecord++) {
// DebugScreen.Log("Util.getCarrierBIBSUid() for ippp--------->>" + records[currentRecord].getCid().toLowerCase());
if (records[currentRecord].getCid().toLowerCase().equals("ippp")) {
// DebugScreen.Log("Util.getCarrierBIBSUid() for bibs..........'''''" + records[currentRecord].getName().toLowerCase().indexOf("bibs") );
if (records[currentRecord].getName().toLowerCase().indexOf("bibs") >= 0) {
return records[currentRecord].getUid();
}
}
}
return null;
}
public static String getAvailableConnectionsString() {
String conns = null;
ServiceBook sb = ServiceBook.getSB();
ServiceRecord[] records = sb.getRecords();
String cid;
String uid;
for (int i = 0; i < records.length; i++) {
ServiceRecord myRecord = records[i];
// System.out.println("record name:"+myRecord.getName()+" cid:"+myRecord.getCid().toLowerCase()+" "+myRecord.getUid().toLowerCase());
if (myRecord.isValid() && !myRecord.isDisabled()) {
cid = myRecord.getCid().toLowerCase();
uid = myRecord.getUid().toLowerCase();
//Wap2.0
if (cid.indexOf("wptcp") != -1 && uid.indexOf("wifi") == -1 && uid.indexOf("mms") == -1 ) {
conns = ";deviceside=true" + ";ConnectionUID="+ myRecord.getUid();
if(myRecord.getUid().equalsIgnoreCase("GTCP BIBS")){
return conns;
}
}
}
}
return conns;
}
This code is work for me..
below is the current codes i have.
what it does is basically loop thru project solution project file and detect if it is a C# file. however it can't detect files that are put in a folder , how can i modify it to read a C# file in a solution folder.
Regards , Andy
foreach (var projectItem in
_applicationObject.Solution.Projects.Cast<Project>().SelectMany(project => project.ProjectItems.Cast<ProjectItem>()))
{
//for (var i = 0; i < projectItem.FileCount; i++)
//{
if (projectItem.FileCount > 0 && projectItem.Name.EndsWith(".cs")) // check if project is .Cs files
{
string fileName;
try
{
fileName = projectItem.FileNames[0];
}
catch (Exception)
{
continue;
}
//end of find filename
}
}
This will print all items in the solution, I believe.
It works with C++ solution in VS 2012.
// XXX Test
IEnumerator enumerator = m_applicationObject.Solution.GetEnumerator();
string indent = " ";
while (enumerator.MoveNext())
{
Project p = enumerator.Current as Project;
if (p != null)
{
Debug.WriteLine(p.Name);
ProcessProjectItems(p.ProjectItems, indent);
}
}
// XXX Test
void ProcessProjectItems(ProjectItems pis, string indent)
{
if (pis == null)
return;
IEnumerator items = pis.GetEnumerator();
while (items.MoveNext())
{
ProjectItem pi = items.Current as ProjectItem;
if (pi != null)
{
Debug.WriteLine(indent + pi.Name);
if (pi.ProjectItems != null)
{
ProcessProjectItems(pi.ProjectItems, indent + " ");
}
else
{
Project p = pi.Object as Project;
if (p != null && p.ProjectItems != null)
ProcessProjectItems(p.ProjectItems, indent + " ");
}
}
}
}