QR Code Reader for Sony SmartEyeglass - qr-code

$ Hello, I am using an app I found on Github https://github.com/simsor/SmartEyeglassQRCode/blob/master/AndroidApp/app/src/main/java/com/example/sony/smarteyeglass/extension/helloworld/HelloWorldControl.java, which is a qr code reader for Sony's SmartEyeglass. But for some reason it is not working. When I scan a QRcode, it either says "QR code not found" or "please wait" for a very long time, without ever showing the result. I tried a few things, but nothing changed. Does any of you maybe know what's going on ?
public void processPicture(CameraEvent event) {
updateLayout("Please wait...");
if (event.getIndex() == 0) {
if (event.getData() != null && event.getData().length > 0) {
byte[] data = event.getData();
Bitmap bitmap = BitmapFactory.decodeByteArray(data, 0, data.length);
int[] intArray = new int[bitmap.getWidth() * bitmap.getHeight()];
//copy pixel data from the Bitmap into the 'intArray' array
bitmap.getPixels(intArray, 0, bitmap.getWidth(), 0, 0, bitmap.getWidth(), bitmap.getHeight());
LuminanceSource source = new RGBLuminanceSource(bitmap.getWidth(), bitmap.getHeight(), intArray);
BinaryBitmap bbmap = new BinaryBitmap(new HybridBinarizer(source));
Reader reader = new QRCodeReader();
int DelayTime = 5000;
boolean error = false;
try {
Result result = reader.decode(bbmap);
Log.d(Constants.LOG_TAG, result.getText());
doWebsiteCommunication(result.getText());
} catch (NotFoundException e) {
updateLayout("QR Code Not Found");
error = true;
e.printStackTrace();
} catch (ChecksumException e) {
e.printStackTrace();
updateLayout(new String[] {
"QR Code looks corrupted",
"Maybe try again?"
});
error = true;
} catch (FormatException e) {
e.printStackTrace();
updateLayout("That's not a QR Code");
error = true;
}
if (error) {
try {
Thread.sleep(DelayTime);
} catch (InterruptedException e) {
e.printStackTrace();
}
currentlyTakingPicture = false;
updateLayout(DEFAULT_TEXT);
}
}
}
}

The problem is the
doWebsiteCommunication(result.getText());
Just replace it with
updateLayout(result.getText());
This should work fine
PS: the doWebsiteCommunication was meant to update an external Website with the scandata, but since you just wanna read the qr code you dont need it

Related

why zxing can not decode this qrcode image?

JavaSE: Exception is "com.google.zxing.NotFoundException"
Can any one help me?
The version is 3.4.1
<dependency>
<groupId>com.google.zxing</groupId>
<artifactId>javase</artifactId>
<version>3.3.1</version>
</dependency>
and the java code is there.
BufferedImageLuminanceSource source = new BufferedImageLuminanceSource(image);
BinaryBitmap bitmap = new BinaryBitmap(new HybridBinarizer(source));
Result result;
Map<DecodeHintType,Object> hints = new LinkedHashMap<>();
hints.put(DecodeHintType.CHARACTER_SET, "utf-8");
hints.put(DecodeHintType.TRY_HARDER, Boolean.TRUE);
result = new MultiFormatReader().decode(bitmap, hints);
return result.getText();
The Exception info is :
com.google.zxing.NotFoundException
There is not anything other displayed...
But the following code can not be decoded out,It's really weird
Almost identical QR codes, one can be decoded but the other cannot be coded`
Use GenericMultipleBarcodeReader to read the QR code.
public void decodefile(String filename) {
// Read an image to BufferedImage
BufferedImage image = null;
try {
image = ImageIO.read(new File(filename));
} catch (IOException e) {
System.out.println(e);
return;
}
// ZXing
BinaryBitmap bitmap = null;
int[] pixels = image.getRGB(0, 0, image.getWidth(), image.getHeight(), null, 0, image.getWidth());
RGBLuminanceSource source = new RGBLuminanceSource(image.getWidth(), image.getHeight(), pixels);
bitmap = new BinaryBitmap(new HybridBinarizer(source));
MultiFormatReader reader = new MultiFormatReader();
GenericMultipleBarcodeReader multiReader = new GenericMultipleBarcodeReader(reader);
try {
Result[] zxingResults = multiReader.decodeMultiple(bitmap);
System.out.println("ZXing result count: " + zxingResults.length);
if (zxingResults != null) {
for (Result zxingResult : zxingResults) {
System.out.println("Format: " + zxingResult.getBarcodeFormat());
System.out.println("Text: " + zxingResult.getText());
System.out.println();
}
}
} catch (NotFoundException e) {
e.printStackTrace();
}
pixels = null;
bitmap = null;
if (image != null) {
image.flush();
image = null;
}
}
Here is my results:
ZXing result count: 1
Format: QR_CODE
Text: https://mp-daily.bookln.cn/q?c=1201M9XUEDE

If there is data, how is the stream returning zero bytes?

I have a RXTX project that I'm working on. I have it set ups as follows:
public void doConnect(ActionEvent event)
{
String selectedPort = (String)connectTabController.portList.getValue();
System.out.println("Connecting to: " + selectedPort);
selectedPortIdentifier = (CommPortIdentifier)portMap.get(selectedPort);
CommPort commPort = null;
try
{
commPort = selectedPortIdentifier.open("AT QC ReponseTime", TIMEOUT);
serialPort = (SerialPort)commPort;
setConnected(true);
if (isConnected)
{
if (initIOStream() == true)
{
initListener();
System.out.println("Initializing listener");
connectTabController.gui_changeStatusLabel("Device Connected!");
}
}
}
catch (PortInUseException e)
{
System.out.println("Port In use! " + e.toString());
}
catch (Exception e)
{
System.out.println("Failed to open! " + e.toString());
}
}
public boolean initIOStream()
{
//return value for whether opening the streams is successful or not
boolean successful = false;
try {
//
input = serialPort.getInputStream();
output = serialPort.getOutputStream();
writeData(RESETTPOD);
System.out.println("Writing Reset command");
successful = true;
System.out.println("IO Stream opened successfully!");
return successful;
}
catch (IOException e) {
System.out.println("I/O Streams failed to open. (" + e.toString() + ")");
return successful;
}
}
public void initListener()
{
try
{
serialPort.addEventListener(this);
serialPort.notifyOnDataAvailable(true);
}
catch (TooManyListenersException e)
{
System.out.println("Too many listeners. (" + e.toString() + ")");
}
}
That's how the connection is made, and it has a listener that's supposed to notify when data is available, which triggers the following:
#Override
public void serialEvent(SerialPortEvent evt) {
BufferedReader reader = null;
if (evt.getEventType() == SerialPortEvent.DATA_AVAILABLE)
{
try
{
reader = new BufferedReader(new InputStreamReader(input));
if (reader.ready())
{
fullLine = reader.readLine();
System.out.println(fullLine + "\n");
}
}
catch (Exception e)
{
System.out.println("#SerialEvent Failed to read data. (" + e.toString() + ")");
}
}
}
However, I keep getting "UNDERLYING INPUT STREAM RETURNED ZERO BYTES"
This makes no sense, since if there is nothing to read then the listener shouldnt be triggered int he first place. I tried running the app and I keep getting this error message around every 1/3 second, which corresponds to the burst-output of the device that's sending data. (which works fine in programs like PuttY)
If you are going to use the BufferedReader, take a look at the refence API document for javax.comm, CommPort and getInputStream. Then try using different settings for threshold and receive timeout.
eg).
serialPort.enableReceiveThreshold(3);
serialPort.enableReceiveTimeout(1);
https://docs.oracle.com/cd/E17802_01/products/products/javacomm/reference/api/

wait() in asp.net (showing uploaded image)

I want to force my program to wait some moments after doing something, and then do somwthing else, in asp.net and silverlight.
(In Detail, I want to upload an image by silverlight program, and then show it in my page by an Image control. But when I upload images which their size is about 6KB or upper, the image doesn't show, however it has been uplaoded successfully. I think that waiting some moments may solve the problem)
May anyone guide me?
thank you
I use the code in this page
This is the code in MyPage.Xaml:
private void UploadBtn_Click(object sender, RoutedEventArgs e)
{
OpenFileDialog dlg = new OpenFileDialog();
dlg.Multiselect = false;
dlg.Filter = UPLOAD_DIALOG_FILTER;
if ((bool)dlg.ShowDialog())
{
progressBar.Visibility = Visibility.Visible;
progressBar.Value = 0;
_fileName = dlg.File.Name;
UploadFile(_fileName, dlg.File.OpenRead());
}
else
{
//user clicked cancel
}
}
private void UploadFile(string fileName, Stream data)
{
// Just kept here
progressBar.Maximum = data.Length;
UriBuilder ub = new UriBuilder("http://mysite.com/receiver.ashx");
ub.Query = string.Format("fileName={0}", fileName);
WebClient c = new WebClient();
c.OpenWriteCompleted += (sender, e) =>
{
PushData(data, e.Result);
e.Result.Close();
data.Close();
};
try
{
c.OpenWriteAsync(ub.Uri);
}
catch (Exception e)
{
MessageBox.Show(e.ToString());
}
}
private void PushData(Stream input, Stream output)
{
byte[] buffer = new byte[input.Length];
int bytesRead;
while ((bytesRead = input.Read(buffer, 0, buffer.Length)) != 0)
{
output.Write(buffer, 0, buffer.Length);
}
progressBar.Value += input.Length;
if (progressBar.Value >= progressBar.Maximum)
{
progressBar.Visibility = System.Windows.Visibility.Collapsed;
loadImage();
}
}
private void loadImage()
{
Uri ur = new Uri("http://mysite.com/upload/" + _fileName);
img1.Source = new BitmapImage(ur);
}
And this is receiver.ashx:
public void ProcessRequest(HttpContext context)
{
string filename = context.Request.QueryString["filename"].ToString(); using (FileStream fs = File.Create(context.Server.MapPath("~/upload/" + filename)))
{
SaveFile(context.Request.InputStream, fs);
}
}
private void SaveFile(Stream stream, FileStream fs)
{
byte[] buffer = new byte[stream.Length];
int bytesRead;
while ((bytesRead = stream.Read(buffer, 0, buffer.Length)) != 0)
{
fs.Write(buffer, 0, bytesRead);
}
}

ThreadPool and Memory (BTStackServer) exception - .NET

In continuation with my problem here, I created a test app that uses ThreadPool threads to send emails. Here's the code I am using.
protected void btnSend_Click(object sender, EventArgs e)
{
EmailInfo em = new EmailInfo { Body = "Test", FromEmail = "test#test.com", Subject = "Test Email", To = "test#test.com" };
//txtNumEmails is a textbox where I can enter number of emails to send
for (int i = 0; i < Convert.ToInt32(this.txtNumEmails.Text); i++)
{
bool bResult = ThreadPool.QueueUserWorkItem(new WaitCallback(EmailNow), em);
}
}
public void EmailNow(object emailInfo) // Email Info object
{
EmailInfo em = emailInfo as EmailInfo;
SmtpClient client = new SmtpClient("localhost");
client.UseDefaultCredentials = true;
client.DeliveryMethod = SmtpDeliveryMethod.SpecifiedPickupDirectory;
client.PickupDirectoryLocation = #"C:\temp\testemails\";
MailMessage m = new MailMessage();
m.To.Add(new MailAddress(em.To));
m.Body = em.Body;
m.IsBodyHtml = false;
m.From = new MailAddress(em.FromEmail);
m.Subject = em.Subject;
client.Send(m);
}
For smaller numbers (10k, 50k) they work great, but once I increase the number to 200k (which is my target), I got this exception:
It created about 186k emails before it threw this exception.
I am assuming this is not the exception caused due to lack of disk space (since i am storing all the emails locally in C:\temp\testemails but because it was low in RAM(?). As suggested by a this user, I used semaphores to limit them to 10k, but still ran in to the same issue. Here's the code for the one with semaphores.
protected void Button1_Click(object sender, EventArgs e)
{
EmailInfo em = new EmailInfo { Body = "Test", FromEmail = "test#test.com", Subject = "Test Email", To = "test#test.com" };
var semaphore = new SemaphoreSlim(10000, 10000);
for (int i = 0; i < Convert.ToInt32(this.txtNumEmails.Text); i++)
{
semaphore.Wait();
bool bResult = ThreadPool.QueueUserWorkItem( (state) => {
try
{
EmailNow(em);
}
catch (Exception)
{
throw;
}
finally
{
semaphore.Release();
}
}, null);
}
}
This one threw an exception as well but I see all 200k emails in the folder. I can definitely use try catch and gracefully exit if this exception occurs, but how would I prevent this from happening in the first place.
Try disposing SmtpClient object by either wrapping inside using block or calling dispose() explicitly.
Try reducing the 10000 to 1000 for the SemaphoreSlim constructor.

blackberry HttpConnection.GET

URL: http://monSite/GET.asp
we must authenticate before getting the result.
I want to send the login and password with HttpConn.setRequestMethod (HttpConnection.POST) and retrieve the XML file with HttpConn.setRequestMethod (HttpConnection.GET) with the same HTTP Client.
conn = (HttpConnection) new ConnectionFactory().getConnection(_url).getConnection();
URLEncodedPostData postData = null;
postData = new URLEncodedPostData("UTF-8", false);
postData.append("userName",_username);
postData.append("passWord", _password);
conn.setRequestProperty(HttpProtocolConstants.HEADER_CONTENT_LANGUAGE, "en-US");
conn.setRequestProperty(HttpProtocolConstants.HEADER_CACHE_CONTROL,"no-cache, no-store, no-transform");
// Specify the content type.
conn.setRequestMethod(HttpConnection.POST);
conn.setRequestProperty(HttpProtocolConstants.HEADER_CONTENT_TYPE, postData.getContentType());
byte [] postBytes = postData.getBytes();
conn.setRequestProperty(HttpProtocolConstants.HEADER_CONTENT_LENGTH, Integer.toString(postBytes.length));
os = conn.openOutputStream();
os.write(postBytes);
os.flush();
os.close();
//GET XML file
conn.setRequestMethod(HttpConnection.GET);
conn.setRequestProperty("User-Agent",
"Profile/MIDP-1.0 Confirguration/CLDC-1.0");
if (conn.getResponseCode() == HttpConnection.HTTP_OK) {
int total = 0;
int size = 1024;
char[] buffer = new char[size];
int len;
InputStreamReader isr = new InputStreamReader(conn.openInputStream(), "UTF-8");
while ((len = isr.read(buffer, 0, size)) > 0)
{
buff.append(buffer, 0, len);
total += len;
}
result = buff.toString();
} else {
result = "Error in connection" + conn.getResponseCode();
}
} catch (Exception ex) {
ex.printStackTrace();
} finally {
try {
if (in != null) {
in.close();
}
conn.close();
} catch (IOException e) {
e.printStackTrace();
}
}
the HttpConnection.POST works very well but GET no (login failed: the authentication parameter does not saved)
In HttpConnection.GET request you need to append attribute in your url like:
String url="http://www.xyz?userName="+_username+"&password="+_password+"";
and then get the InputStream
below link may be helpful for you
http://supportforums.blackberry.com/t5/Java-Development/Make-an-HTTP-Connection-to-get-a-Content-of-URL/td-p/95075

Resources