Notification after user becomes idle on OS X? - objective-c

What's the best way of detecting when a user has been idle for X amount of time, and then detect when the user becomes immediately active?
I know there's NSWorkspace which provides will/did sleep/wake notifications, but I can't rely on that because the sleep setting is usually about ~15 minutes to never. I need to be able to detect if the user's been idle for ~1-2 minutes.
This answer provides a way to get the idle time. I'd like to avoid polling if possible.

Polling is your only option, to my knowledge. As user1118321 points out, polling every O(minutes) is unlikely to cause any problems, performance or otherwise.
If your app has a GUI and receives UI events anyway, you could install a handler via +[NSEvent addLocalMonitorForEventsMatchingMask:handler:] that resets your timer on each event. That'll help reduce if not eliminate polls when the user is consistently active, in your own app at least.
Once you've determined that the user has been idle long enough, you could then install a global event tap to watch for the next event. See for example -[NSEvent addGlobalMonitorForEventsMatchingMask:handler:].
Note: you should use CGEventSourceSecondsSinceLastEventType if at all possible rather than poking into the IO registry. It's a formal, supported API and may be more efficient. Not to mention it's way simpler. There's also UKIdleTimer though it relies on Carbon, so may not be applicable.

Related

How to program factory reset switch in a small embedded device

I am building a small embedded device. I am using a reset switch, and when this is pressed for more than 5 seconds, the whole device should reset and clear all the data and go to factory reset state.
I know what to clear when this event happens. What I want to know is how do I raise this event? I mean when switch is pressed, how do I design the system to know that 5 seconds have elapsed and I have to reset now. I need high level design with any timers and interrupts. Can some one please help me?
Depends on the device. But few rough ideas:
Possibly the device manual may say about the number of interrupts per second that is produced by "holding down the switch" (switch down). If you have this value, you can easily calculate the 5 seconds.
If not, you would need to use timer too. Start the timer when you get the first interrupt of "switch down" and count up to 5 seconds.
Note that, You should also monitor for "switch up", that is, "release of switch". I hope there will be an interrupt for that too. (Possibly with different status value).
So you should break the above loop (you shouldn't do the reset) when you see this interrupt.
Hope this helps.
Interrupt-driven means low level, close to the hardware. An interrupt-driven solution, with for example a bare metal microcontroller, would look like this:
Like when reading any other switch, sample the switch n number of times and filter out the signal bounce (and potential EMI).
Start a hardware timer. Usually the on-chip timers are far too fast to count a whole 5 seconds, even when you set it to run as slow as possible. So you need to set the timer with a pre-scale value, picked so that one whole timer cycle equals a known time unit (like for example 10 milliseconds).
Upon timer overflow, trigger an interrupt. Inside the interrupt, check that the switch is still pressed, then increase a counter. When the counter reaches a given value, execute the reset code. For example, if you get a timer overflow every 10 milliseconds, your counter should count up to 5000ms/10ms = 500.
If the switch is released before the time is elapsed, reset the counter and stop the timer interrupt.
How to reset the system is highly system-specific. You should put the system in a safe system, then overwrite your current settings by overwriting the NVM where settings is stored with some default factory settings stored elsewhere in NVM. Once that is done, you should force the processor to reset itself and reboot with the new settings in place.
This means that you must have a system with electronically-erasable NVM. Depending on the size of the data, this NVM could either be data flash on-chip in a microcontroller, or some external memory circuit.
Detecting a 5S or 30S timeout can be done using a GPIO on an interrupt.
If using an rtos,
. Interrupt would wake a thread from sleep and disables itself,
. All the thread does is count the time the switch is pressed for (you scan the switch at regular intervals)
. If the switch is pressed for desired time set a global variable/setting in eeprom which will trigger the factory reset function
. Else enable the interrupt again and put the thread to sleep
. Also, use a de-bounce circuit to avoid issues.
Also define what do you mean by factory reset?
There are two kinds in general, both cases I will help using eeprom
Revert all configurations (Low cost, easier)
In this case, you partition the eeprom, have a working configuration and factory configuration. You copy over the factory configurations to the working partition and perform a software reset
Restore complete firmware (Costly, needs more testing)
This is more tricky, but can be done with help of bootloaders that allow for flashing from eeprom/or sd card.
In this case the binary firmware blob will also be stored with the factory configuration, in the safe partition and will be used to flash controller flash and configurations.
All depends on the size/memory and cost. can be designed in many more ways, i am just laying out simplest examples.
I created some products with a combined switch to. I did so by using a capacitator to initiate a reset pulse on the reset pin of the device (current and levels limit by some resistors and/or diodes). At start-up I monitor the state of the input pin connected to the switch. I simply wait until this pin goes height with a time-out of 5 seconds. In case of a time-out I reset my configuration to default.

Is boost::asio asyn_read with timer a good idea?

My server app needs to keep thousands of TCP connections. One time, I used one timer for each connection. Once a timer is expired, my code will check database to see if there is a message is ready for sending or not, if found then send it to remote client. This design works but the performance is very very slow, because there are thousands of timers in my app. My friend asked me to remove all timers and use one thread to check the database and send them to all remote clients in for(...) loop.
But I see a lot of articles that introcuce how to use dead_line_timer with async_read, see below link
http://www.boost.org/doc/libs/1_40_0/doc/html/boost_asio/example/timeouts/stream_receive_timeout.cpp
My question is, does this work well when server has thousands of connections? I guess not, how do you think?
I think the timers are not your main performance problem. They have of course some penalty, but by far not in the dimensions that the IO itself has.
I could imagine that your main problem is that you have a a large delay betweeen change-in-db -> timer-expired -> send happens. Another problem could be that you check your whole DB when a timer expires? If yes then you could only set a flag when an update happens, check for that in the timer and reset in when you sent the update.
Can you directly send the changes after they happen so that you avoid the timers at all? You could use io_service->post() to trigger an update function which sends the update to all connected clients. You should also use the async_write methods to avoid that a single client blocks your whole application.
If you don't want to send all updates but only in given intervals then your friends suggestion to use a single timer for checking for changes and sending the updates sounds also good.

Network activity indicator and asynchronous sockets

I have an app which continuously reads status updates from a server connection.
All is working well with a stream delegate to handle all the reading and writing asynchronously.
There's no part of the app that is "waiting" for a specific response from the server, it is just continuously handling status updates as they sporadically arrive from the socket. There are no requests on the client side that are waiting for responses.
I'm wondering what the best practice would be for the network activity indicator in this case.
I could turn it on in the stream event handler, and off before we leave the handler, but that would be a very short time (just enough for an non-blocking read or write to occur). Trying this, I only see the faintest flicker of the indicator; it needs to be on longer than just during the event handler.
What about turning it on in the stream delegate, and setting a timer to turn it off a short time later? (This would ensure it's on long enough to be seen, rather than the short time spent in the stream delegate.)
Note: I've tried this last idea: turning on the network activity indicator whenever there's stream activity, and note the NSDate; then in a timer (that I have fired every 1 second), if the time passsed is >.5 second, I turn off the indicator. This seems to give a reasonable indication of network activity.
Any better recommendations?
If the network activity is continuous then it sounds like it might be somewhat annoying to the user, especially if it's turning on and off all the time.
Perhaps better would be to test for lack-of-response up to a certain timeout value and then display an alert view to the user if you aren't getting any response from the server. Even that could be optional if you can provide feedback (like "Last update: 5 mins ago") to the user instead.

UIApplication Idle Timer

This is a simple question and I can not seem to find any information on it, but I just want to know if the following code will get my app rejected or not. Basically, is this a private API
[application setIdleTimerDisabled:YES];
I want to add this to my AppDelegate under didFinishLaunchingWithOptions. I just do not want to use something so simple and get my app rejected. Thanks for any information!
It's public, though apple advises:
Important You should set this property only if necessary and should be
sure to reset it to NO when the need no longer exists. Most
applications should let the system turn off the screen when the idle
timer elapses. This includes audio applications. With appropriate use
of Audio Session Services, playback and recording proceed
uninterrupted when the screen turns off. The only applications that
should disable the idle timer are mapping applications, games, or
similar programs with sporadic user interaction.
So you should be okay if your app is as they describe, or if you use it sparingly.

Cocoa Distributed Objects, Long Polling, launchd and "Not Responding" in Activity Monitor

Scenario:
I have a Distributed-objects-based IPC between a mac application and a launchd daemon (written with Foundation classes). Since I had issues before regarding asynchronous messaging (e.g. I have a registerClient: on the server's root object and whenever there's an event the server's root object notifies / calls a method in the client's proxy object), I did long-polling which meant that the client "harvests" lists of events / notifications from the daemon. This "harvest" is done through a server object method call, which then returns an NSArray instance.
It works pretty well, until for a few seconds, the server object's process (launched thru launchd) starts being labeled red with the "(Not responding)" tag beside it (inside Activity Monitor). Like I said, functionally, it works well, but we just want to get rid of this "Not responding" label.
How can I prevent this "Not responding" tag?
FYI, I already did launchd-based processes before and this is the first time I did long-polling. Also, I tried NSSocketPortNameServer-based connections and also NSSocketPort-based ones. They didn't have this problem. Locking wasn't also an issue 'coz the locks used were only NSCondition's and we logged and debugged the program and it seems like the only locking "issue" is on the harvesting part, which actually, functionally works. Also, client-process is written in PyObjC while server process was written using ObjC.
Thanks in advance.
Sample the process to find out what it's doing or waiting on.
Peter's correct in the approach, though you may be able to figure it out through simple inspection. "Not responding" means that you're not processing events on your event queue for at least 5 seconds (used to be 2 seconds, but they upped it in 10.4). For a UI process, this would create a spinning wait cursor, but for a non-UI process, you're not seeing the effects as easily.
If this is a runloop-based program, it means you're probably doing something with a blocking (synchronous) operation that should be done with the run loop and a callback (async). Alternately, you need a second thread to process your blocking operations so your mainthread can continue to respond to events.
My problem was actually the call for getting a process's PID using the signature FNDR... that part caused the "Not responding" error and it never was the locks or the long-polling part. Sorry about this guys. But thank God I already found the answer.