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?
Related
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))
// {
I've got a device to my computer and I want to read its data from port 2005
I use the following code to read from the 2005 port.
public MainWindow()
{
try
{
IPAddress localAddr = IPAddress.Parse("0.0.0.0");
var host = Dns.GetHostEntry(Dns.GetHostName());
foreach (var ip in host.AddressList)
{
if (ip.AddressFamily == AddressFamily.InterNetwork)
{
localAddr = IPAddress.Parse(ip.ToString());
}
}
TcpClient client = null;
try
{
client = new TcpClient(localAddr.ToString(), 2005);
}
catch (SocketException se)
{
}
Byte[] bytes = new Byte[256];
String data = null;
while (true)
{
data = null;
NetworkStream stream = client.GetStream();
int i;
while ((i = stream.Read(bytes, 0, bytes.Length)) != 0)
{
data = System.Text.Encoding.ASCII.GetString(bytes, 0, i);
DecodeReceivedMsg(data);
}
client.Close();
}
}
catch (SocketException e)
{
}
finally
{
}
}
My problem is that I do not always read the port, and many times, the while(true) does not run.
please guide me
I have to send push notifications for pkPasses on iOS devices.
I have found a code on git hub.
Using SendEmptyPushNotification method for sending push notification. I am sending PushToken for deviceIdentifier
But its not working. Sometimes this code is taking too much time and sometimes it takes no time. But in both the cases i am not able to get any push notification on my iOS device. I really stuck here. Can anyone help??
public class IPhonePushNotificationService
{
public void SendEmptyPushNotification(string deviceIdentifier, string thumbprint)
{
string server = "gateway.push.apple.com";
using (TcpClient tcpClient = new TcpClient(server, 2195))
{
Trace.TraceInformation("Opening SSL Connection...");
using (SslStream sslStream = new SslStream(tcpClient.GetStream()))
{
try
{
X509Certificate2Collection certs = new X509Certificate2Collection();
Trace.TraceInformation("Adding certificate to connection...");
X509Certificate cert = GetAppleServerCert(thumbprint);
certs.Add(cert);
Trace.TraceInformation("Authenticating against the SSL stream...");
sslStream.AuthenticateAsClient(server, certs, SslProtocols.Default, false);
}
catch (AuthenticationException exp)
{
Trace.TraceError("Failed to authenticate to APNS - {0}", exp.Message);
return;
}
catch (IOException exp)
{
Trace.TraceError("Failed to connect to APNS - {0}", exp.Message);
return;
}
byte[] buf = new byte[256];
MemoryStream ms = new MemoryStream();
BinaryWriter bw = new BinaryWriter(ms);
bw.Write(new byte[] { 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 32 });
byte[] deviceToken = HexToData(deviceIdentifier);
bw.Write(deviceToken);
string msg = "{}";
bw.Write(new byte[] { 0, 2 });
bw.Write(msg.ToCharArray());
bw.Flush();
Trace.TraceInformation("Message sent. Closing stream...");
if (sslStream != null)
{
sslStream.Write(ms.ToArray());
}
byte[] response = new byte[6];
sslStream.Read(response, 0, 6);
sslStream.Flush();
}
}
}
private static X509Certificate GetAppleServerCert(string thumbprint)
{
X509Store store;
store = new X509Store(StoreLocation.CurrentUser);
if (store != null)
{
store.Open(OpenFlags.ReadOnly);
X509Certificate2Collection certs = store.Certificates;
if (certs.Count > 0)
{
for (int i = 0; i < certs.Count; i++)
{
X509Certificate2 cert = certs[i];
if (cert.Thumbprint.Equals(thumbprint, StringComparison.InvariantCultureIgnoreCase))
{
return certs[i];
}
}
}
}
Trace.TraceError("Could not find the certification containing: {0} ", "R5QS56362W:R5QS56362W");
throw new InvalidDataException("Could not find the Apple Push Notification certificate");
}
private static byte[] HexToData(string hexString)
{
if (hexString == null)
{
return null;
}
if (hexString.Length % 2 == 1)
{
hexString = '0' + hexString; // Up to you whether to pad the first or last byte
}
byte[] data = new byte[hexString.Length / 2];
for (int i = 0; i < data.Length; i++)
{
data[i] = Convert.ToByte(hexString.Substring(i * 2, 2), 16);
}
return data;
}
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
Here is my code where i am getting profile image bytes from twitter api,
new Thread() {
public void run() {
byte dbata[] = getBitmap(profle_pic_str);
if (dbata != null) {
EncodedImage bitmap_img = EncodedImage.createEncodedImage(dbata, 0, -1);
Bitmap image =bitmap_img.getBitmap();
final Bitmap profle_pic_bmp = image;
final Bitmap scld_bmp = new Bitmap(90, 100);
Application.getApplication().invokeLater(new Runnable() {
public void run() {
if (profle_pic_bmp != null) {
profle_pic_bmp.scaleInto(scld_bmp, Bitmap.FILTER_LANCZOS);
phot_profle.setBitmap(scld_bmp);
} else {
Dialog.alert("null");
}
}
});
// } else {
// Dialog.alert("bytes are null");
}
}
}.start();
Here i have method getBitmap(profle_pic_str); which returning bytes array of image,
public byte[] getBitmap(String url) {
Bitmap bitmap = null;
String strg = HttpConnector.getConnectionString();
byte b[] = null;
try {
b = getXML(url + strg);
} catch (IOException ie) {
ie.printStackTrace();
}
return b;
}
the url which i used is this one
http://api.twitter.com/1/users/profile_image?screen_name=screen_nameof_user&size=bigger
public byte[] getXML(String url) throws IOException {
ContentConnection connection =
(ContentConnection) javax.microedition.io.Connector.open(url);
java.io.DataInputStream iStrm = connection.openDataInputStream();
java.io.ByteArrayOutputStream bStrm = null;
byte xmlData[] = null;
try {
// ContentConnection includes a length method
int length = (int) connection.getLength();
if (length != -1) {
xmlData = new byte[length];
// Read the png into an array
// iStrm.read(imageData);
iStrm.readFully(xmlData);
} else // Length not available...
{
bStrm = new java.io.ByteArrayOutputStream();
int ch;
while ((ch = iStrm.read()) != -1) bStrm.write(ch);
xmlData = bStrm.toByteArray();
bStrm.close();
}
} catch (Exception e) {
e.printStackTrace();
} finally {
// Clean up
if (iStrm != null) iStrm.close();
if (connection != null) connection.close();
if (bStrm != null) bStrm.close();
}
return xmlData;
}
When i am trying to convert byte array to EncodedImage
EncodedImage bitmap_img = EncodedImage.createEncodedImage(dbata, 0, -1);
in this line of code i am getting illegal argument exception.
same code is working for Facebook profile image. I dont know why this code giving error when i am doing for twitter. Please help me friends.
try this -
EncodedImage _encoded_img = EncodedImage.createEncodedImage(dbata, 0, dbata.length);
On your code,
EncodedImage bitmap_img = EncodedImage.createEncodedImage(dbata, 0,-1);
-1 is the length of the array. Its not static. Change -1 to dbata.length.