Why is WinUsb_WritePipe returning error 997 With asynchronous winusb io? - winusb

If I use WinUsb_WritePipe with a LPOVERLAPPED entry, and use WinUsb_GetOverlappedResult to wait on the results, I have an error where WinUsb_WritePipe always returns false, and GetLastError returns error 997.
OVERLAPPED ovr = { 0 };
ovr.hEvent = CreateEvent(NULL, TRUE, FALSE, "USBWrite");
...
while( ... )
{
// If waiting...
WinUsb_GetOverlappedResult( winusbhandle, &ovr, &NumberOfBytesTransferred, 1);
// Always,
WinUsb_WritePipe(winusbhandle, 0x01, usb_out_buffer, sizeof(usb_out_buffer), &bytesWritten, &ovr);
// This returns as a failure and GetLastError() == 997
}
}

There is no issue. The error code should be checked, but, error 997 just means that "Yes, we have queued your data, it is now in progress. Nothing is wrong."
So, you should detect this error, and ignore it. Other errors are real.

Related

"Error: 13 INTERNAL: An internal error occurred" happened in firebase-function's trigger sometimes

This trigger is used for detecting sequence in schedule has been updated, and help to update the schedule's overview status and finished time.
But it didn't always work when an internal error was occurred as below:
Error: 13 INTERNAL: An internal error occurred. at Object.exports.createStatusError
(/srv/node_modules/grpc/src/common.js:91:15) at Object.onReceiveStatus
(/srv/node_modules/grpc/src/client_interceptors.js:1204:28) at InterceptingListener._callNext
(/srv/node_modules/grpc/src/client_interceptors.js:568:42) at InterceptingListener.onReceiveStatus
(/srv/node_modules/grpc/src/client_interceptors.js:618:8) at callback
(/srv/node_modules/grpc/src/client_interceptors.js:845:24)
Here is my code:
export const calc_status = function.firestore.document("users/{userid}/schedule/{scheduledid}").onUpdate(async (change, context) => {
// before error occurred ...
const data = change.after.data();
let curStatus = data.status;
...
...
// after getting occurred ...
if(data.status !== curStatus ) {
data.status = curStatus;
if(curStatus === 'finished') {
data.finish_time = new Date().toISOString();
}
if(curStatus !== 'expired'){
data.update_time = data.expired_time;
data.finish_time = data.expired_time;
} else {
data.update_time = new Date().toISOString();
}
await change.after.ref.update(data);
return Status.SUCCEEDED;
}
return Status.SUCCEEDED;
}
I'm very confused why the error occurred because this function works fine at most time.
Does anyone met the same problem as mine?
Why the error happened? And what's your solution?
Thank you.
This appears to be long standing framework bug github.com/firebase/firebase-functions/issues/536 with no resolution as of yet.
Though you can't get around the error which anecdotally and very intermittently happens on a cold start you can work around it by enabling retries for the function via the full console see Retry Cloud Functions for Firebase until it succeeds for instructions.
This assumes you handle internal errors in your code very well as it will retry for any failure but in my case the functions onCreate handler was just queuing up some later processing via PubSub so any failure meant it should retry.
Oct 2020 Update
Since v3.11 of firebase-functions you can now set the retry mode in your function code by setting failurePolicy to true
module.exports = functions.runWith({ failurePolicy: true }).firestore.document('collection/doc').onWrite(async (change, context) => {
//do function stuff
});

Meteor: long latency when returning from server metod call

I do a Meteor.call. I see the server execute its code and finish in less than one second. Then, every once in a while, the client waits a very long time to receive the response. This happens locally, so it isn't related to any internet connectivity issue. The response consists of a quite small object, so I don't think it's a JSON parsing issue, either.
The point here is that the server is finished and has returned its response... but the client does not receive it for up to several minutes.
server code:
findComments : function(ne, sw, filter, timezoneOffset) {
// ... do some Mongo queries and updates ... etc. nothing too weird.
console.log("returning now...");
return result;
}
client code:
Meteor.call("findComments", ne, sw, filter, timezoneOffset, function(err, comments) {
console.log("comments = " + comments);
// ... and we're back
}
I can put a breakpoint in this "Meteor.call" line in the client code, and in the callback. I see "returning now..." on the server, and then.... nothing. I wait a couple minutes, and then I see the good result coming back to the client in the callback.
This behavior can be seen in Chrome, as well as on the installed app on Android and iOS. It happens rarely, but is extremely disruptive, and we are not able to isolate any particular conditions leading to this.
What to do??
EDIT:
The client does eventually go into the callback, after about 2 minutes. During this time, the CPU is idle. I also tested this with a simple server call that takes no arguments and does nothing at all on the server... same effect.
So, if I stop execution on the client to see what he's up to during this time, it stops in this function, in lib/trans-websocket.js:
var WebSocketTransport = SockJS.websocket = function(ri, trans_url) { // 1263
var that = this; // 1264
var url = trans_url + '/websocket'; // 1265
if (url.slice(0, 5) === 'https') { // 1266
url = 'wss' + url.slice(5); // 1267
} else { // 1268
url = 'ws' + url.slice(4); // 1269
} // 1270
that.ri = ri; // 1271
that.url = url; // 1272
var Constructor = _window.WebSocket || _window.MozWebSocket; // 1273
// 1274
that.ws = new Constructor(that.url); // 1275
that.ws.onmessage = function(e) { <-- RIGHT HERE IS WHERE IT STOPS // 1276
that.ri._didMessage(e.data); // 1277
}; // 1278
// Firefox has an interesting bug. If a websocket connection is // 1279
// created after onunload, it stays alive even when user // 1280
// navigates away from the page. In such situation let's lie - // 1281
// let's not open the ws connection at all. See: // 1282
// https://github.com/sockjs/sockjs-client/issues/28 // 1283
// https://bugzilla.mozilla.org/show_bug.cgi?id=696085 // 1284
that.unload_ref = utils.unload_add(function(){that.ws.close()}); // 1285
that.ws.onclose = function() { // 1286
that.ri._didMessage(utils.closeFrame(1006, "WebSocket connection broken")); // 1287
}; // 1288
}; // 1289
Oddly, any breakpoints I put in this code will be ignored. But I can examine the value of the MessageEvent e:
bubbles : false
cancelBubble : false
cancelable : false
composed : false
currentTarget : WebSocket
data : "a["{\"msg\":\"updated\",\"methods\":[\"64\"]}"]"
defaultPrevented : false
eventPhase : 2
isTrusted : true
lastEventId : ""
origin : "ws://localhost:3000"
path : Array[0]
ports : null
returnValue : true
source : null
srcElement : WebSocket
target : WebSocket
timeStamp : 17400.095
type : "message"
__proto__ : MessageEvent
Try to put your function inside try/catch like this:
myFunction() {
try {
...
} catch(e) {
throw new Meteor.Error(e.code,e);
}
}
Then in Meteor.call catch the error. Maybe error happend on server.
This is for anyone who is still looking for solution to this problem.
As it it mentioned in Meteor docs.
Once the Method has finished running on the server, it sends a result message to the client with the Method ID generated in step 2, and the return value itself. The client stores this for later use, but doesn’t call the Method callback yet. If you pass the onResultReceived option to Meteor.apply, that callback is fired.
Ref: https://guide.meteor.com/methods.html#advanced-boilerplate
So if you want your call back to be triggered once the server method return the value then you can use Metor.apply method with the option onResultReceived.
Meteor.apply(
"findComments",
[ne, sw, filter, timezoneOffset],
{
onResultReceived: function(err, comments) {
console.log("comments = " + comments);
// ... and we're back
}
}
Even I was struggling with the latency time but after doing above its instant.

Error in http syntax error in arduino code

The function below describes a set of values from adruino shield and uno board using gps module.
I receive some errors perhaps it is in the syntax. Please ignore the line in which the error has been pointed out. I don't want people to get scared seeing a large coding.
void send_HTTP(){
uint8_t answer=0;
// Initializes HTTP service
answer = sendATcommand("AT+HTTPINIT", "OK", 10000);
if (answer == 1)
{
// Sets CID parameter
answer = sendATcommand("AT+HTTPPARA=\"CID\",1", "OK", 5000);
if (answer == 1)
{
// Sets url
sprintf(aux_str, "AT+HTTPPARA=\"URL\",\"http://%s/demo_sim908.php?", url);// line number :459
Serial.print(aux_str);
sprintf(frame, "visor=false&latitude=%s&longitude=%s&altitude=%s&time=%s&satellites=%s&speedOTG=%s&course=%s",
latitude, longitude, altitude, date, satellites, speedOTG, course); // line number : 460
Serial.print(frame);
answer = sendATcommand("\"", "OK", 5000);
if (answer == 1)
{
// Starts GET action
answer = sendATcommand("AT+HTTPACTION=0", "+HTTPACTION:0,200", 30000);
if (answer == 1)
{
Serial.println(F("Done!"));
}
else
{
Serial.println(F("Error getting url"));
}
}
else
{
Serial.println(F("Error setting the url"));
}
}
else
{
Serial.println(F("Error setting the CID"));
}
}
else
{
Serial.println(F("Error initializating"));
}
sendATcommand("AT+HTTPTERM", "OK", 5000);
}
And I get the following errors.
Arduino: 1.7.5 (Windows 8.1), Board: "Arduino Uno"
sketch_aug22e.ino:459:13: error: missing terminating " character
sketch_aug22e.ino: In function 'void send_HTTP()':
sketch_aug22e.ino:460:34: error: expected ')' before ';' token
Error compiling.
This report would have more information with
"Show verbose output during compilation"
enabled in File > Preferences.
You have an uneven number of quotation marks in line 459:
sprintf(aux_str, "AT+HTTPPARA=\"URL\",\"http://%s/demo_sim908.php?", url);
which is confusing the compiler.
It's hard to say without knowing exactly what you want to do but if you are printing 3 separate strings then it may be that you do not want to 'ESC' the third string - e.g.:
sprintf(aux_str, "AT+HTTPPARA=\"URL\"", "http://%s/demo_sim908.php?", url);
or alternatively if you are just trying to print two strings and the 'comma' before http is just part of the string then you might just have needed to close that 'ESCed' URL:
sprintf(aux_str, "AT+HTTPPARA=\"URL\",http://%s/demo_sim908.php?\", url);

Bacon.js stream with some okay errors

The result of a PUT operation against a database, is sometimes ok even if it doesn't come back as a HTTP code 200.
In this specific case I want to treat 400 as another okay error, but struggle to come up with an elegant way of doing it.
# stream from a promise any non 200 is fail
putter = Bacon.fromPromise #_exec 'PUT', '/some/resource', {}
errors = putter.errors().mapError(errBody) # now errors are normal values
badErrors = errors.filter(statusIsnt(400)).flatMap (body) ->
return new Bacon.Error body # and now they are errors again
okErrors = errors.filter(statusIs(400)).flatMap (body) -> {}
noError = putter.mapError().filter (v) -> v? # attempt to get rid of errors
Bacon.mergeAll noError, okErrors, badErrors # combine to get result stream
I come from a promises background, and I find the above somewhat clumsy, which leads me to conclude I'm missing something. Compare:
#_exec 'PUT', '/some/resource', {}
.fail (err) ->
if err.body.status == 400 # ok
return {}
else
throw err
You can use withHandler with Bacon.Error for throw and (implicit) Bacon.Next for result. But the code will look very similar to your handling already in promise. Actually promise version has less boilerplate.
Compare your promise version
promise = #_exec('PUT', '/some/resource', {})
recovered = promise.fail (err) ->
# 400 is ok. make it ok already in promise
if err?.body?.status == 400 then {} else throw err.body
result = Bacon.fromPromise recovered
and withHandler Bacon "only" version
promise = #_exec('PUT', '/some/resource', {})
stream = Bacon.fromPromise promise
result = stream.withHandler (event) ->
if (event.hasValue())
#push(event)
else
# error
if event.error?.body?.status == 400 then
#push({})
else
#push(event)
One possible solution for this specific scenario is to amend the result already in the promise, but I can easily envisage cases where you can't do that.
Bacon.fromPromise #_exec('PUT', '/some/resource', {}).fail (err) ->
# 400 is ok. make it ok already in promise
if err?.body?.status == 400 then {} else throw err.body
Surely there must be a better functional approach to this problem?
withHandler is an underlying method that lets you operate on Events of all types. Within it you can call #push, which will send errors to the error stream and values to the value streeam. Perhaps the following:
Bacon.fromPromise(#_exec('PUT', '/some/resource', {}))
.withHandler((event) ->
if event.isError && event.error.body?.status? == 400
#push(new Bacon.Next({}))
else
#push(event)
)

httpconnection.getResponseCode() giving EOF exception

I am using Httconnection for connecting to webserver , somtimes request fails causing
EOFException when calling httpconnection.getResponseCode().
I am setting the following headers while making the connection
HttpConnection httpconnection = (HttpConnection) Connector.open(url.concat(";interface=wifi"));
httpconnection.setRequestProperty("User-Agent","Profile/MIDP-2.0 Configuration/CLDC-1.0");
httpconnection.setRequestProperty("Content-Language", "en-US");
I am closing all the connections after processing the request properly.Is this exception is due to exceeding max connections.
It's an internal server error, which return status code 500 in response.
This may be caused by incorrect request, but as well server code or overload may be the reason.
If you have access to server, check event logs.
See also
500 EOF when chunk header expected
Why might LWP::UserAgent be failing with '500 EOF'?
500 EOF instead of reponse status line in perl script
Apache 1.3 error - Unexpected EOF reading HTTP status - connectionreset
Error 500!
UPDATE On the other hand, if it's not response message, but a real exception, then it may be simply a bug, just like in old java
And workaround may be putting getResponseCode() inside of try/catch and call second time on exception:
int responseCode = -1;
try {
responseCode = con.getResponseCode();
} catch (IOException ex1) {
//check if it's eof, if yes retrieve code again
if (-1 != ex1.getMessage().indexOf("EOF")) {
try {
responseCode = con.getResponseCode();
} catch (IOException ex2) {
System.out.println(ex2.getMessage());
// handle exception
}
} else {
System.out.println(ex1.getMessage());
// handle exception
}
}
Talking by connections number limit, read
What Is - Maximum number of simultaneous connections
How To - Close connections
Using HTTPTransportSE, write this before invoke the method "call"
ArrayList<HeaderProperty> headerPropertyArrayList = new ArrayList<HeaderProperty>();
headerPropertyArrayList.add(new HeaderProperty("Connection", "close"));
transport.call(SOAP_ACTION, envelope, headerPropertyArrayList);

Resources