i want to implement a code to keep a watch on suppose some event ...at the meantime i don have any inbuilt eventwatcher so i hv to implement one of mine..which consumes least cpu & memory.
can u suggest me one..
for example a pseudocode is given:
while(true)
{
if(process.isrunning)
process.kill();
}
If you don't have any event to hook into, then your code has to be "active" to run the checks. And that costs CPU cycles.
What you can to do ease waste is to add a call to sleep (Thread.Sleep in .NET, sleep in some implementations of C++).
while (true) {
if(process.isrunning)
process.kill();
sleep(100); // Wait 100 millisecond before trying again
}
But that will make you code a little less responsive.
you can try using timer queue : http://msdn.microsoft.com/en-us/library/ms687003%28VS.85%29.aspx its basically using kernel scheduler to call your function callback at specified interval, the caller is from different thread so it won't interrupt the main thread and make your application responsive, the thread is managed by Windows so you don't have to manage your own pooling thread, and its relative accurate.
implementation example:
`
//a singleton class that hold timer queue
class TimerQueue {
protected:
HANDLE timerQueue;
TimerQueue() {
this->timerQueue = ::CreateTimerQueue();
}
~TimerQueue() {
if(this->timerQueue) {
::DeleteTimerQueueEx(this->timerQueue,NULL);
this->timerQueue = NULL;
}
}
public:
static HANDLE getHandle() {
static TimerQueue timerQueueSingleton;
return timerQueueSingleton.timerQueue;
}
}
//timer base class
class Timer
{
protected:
HANDLE timer;
virtual void timerProc() = 0;
static void CALLBACK timerCallback(PVOID param,BOOLEAN timerOrWait) {
Timer* self = (Timer*)param;
self->timerProc();
}
public:
Timer(DWORD startTimeMs,DWORD periodTimeMs) {
if(!::CreateTimerQueueTimer( &this->timer, TimerQueue::getHandle(),
(WAITORTIMERCALLBACK)&this->timerCallback,
this, startTimeMs, periodTimeMs,
WT_EXECUTEDEFAULT) ) {
this->timer = NULL;
}
}
virtual ~Timer() {
if(this->timer) {
::DeleteTimerQueueTimer(TimerQueue::getHandle(),&this->timer,NULL);
this->timer = NULL;
}
}
}
//derive and implement timerProc
class MyTimer : public Timer
{
protected:
virtual void timerProc() {
if(process.isRunning()) {
process.kill();
}
}
public:
MyTimer(DWORD startTimeMs,DWORD periodTimeMs)
: Timer(startTimeMs,periodTimeMs) {}
}
//usage:
int main(int argc,char* argv[]) {
MyTimer timer(0,100); //start immediately, at 10 Hz interval
}
`
disclaimer : i don't test or compile those codes, you should recheck it
Although you've tagged this as language-agnostic, any good implementation is going to vary widely not just from one language to another, but across operating systems. There are plenty of circumstances where programs or operating system functions need to do just this sort of thing, and mechanisms will have been implemented to do this in as sensible, non-intrusive a way as possible.
If you have a particular language and/or operating system in mind, please tell us, and give us a better idea of what you're trying to achieve. That way we can point you towards the most appropriate of the many possible solutions to this problem.
Related
Because of I had problems with Bluetooth on Android Lollipop, I have tried to change the scanner method.
So I have tried to use the new package.
In the previous version, I called startScan(mLeScanCallback) and everything works but now, when I call startScan(mScanCallback) I have the error: "D/BluetoothLeScanner: could not find callback wrapper".
No devices are found and the ListAdapter, I use to show the devices, is empty.
The comment lines are the previous code (and it worked!).
This my code:
public class Selection extends ListActivity implements ServiceConnection {
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mHandler = new Handler();
// Initializes a Bluetooth adapter through BluetoothManager.
final BluetoothManager bluetoothManager = (BluetoothManager) getSystemService(Context.BLUETOOTH_SERVICE);
mBluetoothAdapter = bluetoothManager.getAdapter();
getApplicationContext().bindService(new Intent(this, MetaWearBleService.class), this, Context.BIND_AUTO_CREATE);
}
private void scanLeDevice(final boolean enable) {
final BluetoothLeScanner bluetoothLeScanner = mBluetoothAdapter.getBluetoothLeScanner();
if (enable) {
mHandler.postDelayed(new Runnable() {
#Override
public void run() {
//mBluetoothAdapter.stopLeScan(mLeScanCallback);
bluetoothLeScanner.stopScan(mScanCallback);
setListAdapter(listAdapter);
}
}, SCAN_PERIOD);
//mBluetoothAdapter.startLeScan(mLeScanCallback);
bluetoothLeScanner.startScan(mScanCallback);
} else {
//mBluetoothAdapter.stopLeScan(mLeScanCallback);
bluetoothLeScanner.stopScan(mScanCallback);
setListAdapter(listAdapter);
}
}
private ScanCallback mScanCallback =
new ScanCallback() {
public void onLeScan(final BluetoothDevice device, int rssi, byte[] scanRecord) {
runOnUiThread(new Runnable() {
#Override
public void run() {
listAdapter.addDevice(device);
}
});
}
};
Instead the ListAdapter extends BaseAdapter and use a ViewHolder. If it necessary, I post it.
So what does it mean "D/BluetoothLeScanner: could not find callback wrapper"? What is it wrong?
Otherwise how I can't resolve the problem of scanning with the Android Lollipop?
In Lollipop I have often errors about BluetoothGatt. I don't know to minized it (or solve it).
Thanks
The log message D/BluetoothLeScanner: could not find callback wrapper appears whenever Android's bluetooth scanning APIs are told top stop scanning for an app when they think scanning has not started. You can see this by looking at the source code of Android's BluetoothLeScanner here.
This is usually safe to ignore as there are lot of reasons that scanning my not have actually started (it was already stopped, bluetooth is off, permissions have not been granted, etc.) Client software that does scanning often stops scanning on a timer regardless of whether it has been successfully started, or whether it was manually stopped before the timer goes off. Android's example code (and the code shown above) does exactly this, often causing these log messages to show up.
If you really want to minimize these messages, you need to keep track of whether scanning actually started and only stop scanning if it actually did. Unfortunately, you don't get a return code if scanning starts successfully, and you only get an asynchronous callback to onScanFailed(errorCode) if you cannot start successfully. So one approach would be to set scanStartCount++; when you call start scan, and set scanStartCount--; when you get a callback to onScanFailed(errorCode). Then when your timer goes off to stop the scan, only actually stop it if the scanStartCount > 0.
Keep in mind that you can only minimize these messages coming from your application. Other applications on the phone doing bluetooth scanning may be causing these messages to be emitted as well.
for the same problem
I had just add permissions :
Manifest.permission.ACCESS_FINE_LOCATION,
Manifest.permission.
Manifest.permission.
Manifest.permission.BLUETOOTH_PRIVILEGED,
in your activity call this methods :
checkPermissions(MainActivity.this, this);
public static void checkPermissions(Activity activity, Context context){
int PERMISSION_ALL = 1;
String[] PERMISSIONS = {
Manifest.permission.ACCESS_FINE_LOCATION,
Manifest.permission.BLUETOOTH,
Manifest.permission.BLUETOOTH_ADMIN,
Manifest.permission.BLUETOOTH_PRIVILEGED,
};
if(!hasPermissions(context, PERMISSIONS)){
ActivityCompat.requestPermissions( activity, PERMISSIONS, PERMISSION_ALL);
}
}
public static boolean hasPermissions(Context context, String... permissions) {
if (context != null && permissions != null) {
for (String permission : permissions) {
if (ActivityCompat.checkSelfPermission(context, permission) != PackageManager.PERMISSION_GRANTED) {
return false;
}
}
}
return true;
}
hope it's help
I had the same problem with android m.It was due to lack of permissions.Make sure you go to settings and grant location permission to your app
for location permission, only ACCESS_FINE_LOCATION worked. ACCESS_COARSE_LOCATION had the same problem.
We're providing a library that needs to run code on its own custom threads. Once done, I want these threads to call callbacks (event handlers) through a Dispatcher (System.Windows.Threading.Dispatcher). The library user shall use the Dispatcher to dispatch event handling to.
We could simply always dispatch on CoreApplication.MainView.CoreWindow.Dispatcher but not all programs (e.g. Windows 10 IoT Core apps) provide an UI and thus they lack a main window.
Can the user simply refer to System.Windows.Threading.Dispatcher.CurrentDispatcher to get his thread's Dispatcher? Or can't all threads have a Dispatcher?
Edit: Here's more context for this question. Hopefully it makes the question easier to grasp: https://github.com/getsenic/nuimo-windows/issues/2
For first, I'm not sure, that you should execute event handlers on UI thread, because only client knows if he needed access UI elements.
For second, before invoking CoreApplication.MainView property you can check CoreApplication.Views.Count > 0 (I'm not absolutely sure that it will work because currently I don't have device to test it).
And also you can solve this issue in another way: in constructor of you object save the SynchronizationContext of executing thread and then use it to raise events. It will work if your object instantiates from UI thread (in most cases it's true). That way you can completely refuse from Dispatcher.
public class NotifierExample
{
private readonly SynchronizationContext _synchronizationContext;
public event EventHandler SomethingHappened;
public NotifierExample()
{
_synchronizationContext = SynchronizationContext.Current;
}
public void Do()
{
Task.Factory.StartNew(() =>
{
//do something
OnSomethingHappened();
});
}
private void OnSomethingHappened()
{
if (_synchronizationContext != null)
{
_synchronizationContext.Post(o => RaiseSomethingHappened(), null);
}
else
{
RaiseSomethingHappened();
}
}
private void RaiseSomethingHappened()
{
var somethingHappened = SomethingHappened;
somethingHappened?.Invoke(this, EventArgs.Empty);
}
}
Or can't all threads have a Dispatcher?
Dispatcher threads are always tied to UI threads. IoT headless mode app does not have an UI so it does not have a Dispatcher thread.
Can the user simply refer to System.Windows.Threading.Dispatcher.CurrentDispatcher to get his thread's Dispatcher
System.Windows.Threading.Dispatcher.CurrentDispatcher is only supported in legacy .NET platform. The UWP alternative is CoreApplication.MainView.CoreWindow.Dispatcher as you pointed out.
If you want to to do async callbacks in Headless(without GUI) mode, you can probably refer to Task Parallel Library(TPL), the ContinueWhenAll ContinueWhenAny etc API... might well suits your needs. Refer to https://msdn.microsoft.com/en-us/library/system.threading.tasks.taskfactory.aspx.
just thought I would share something I have found to help delivering data across an application I am wondering what others think about this I wanted to have a way to capture event bubbling up back down to other components but in a way that it would make it easy to use anywhere in may app so this is what i came up with.
I Extend the Application class and wrap in an abstract function registering a function of any component anywhere and capture it at the top most level and pass to where ever i chose to.
public class AxApplication extends Application
{
public var ___registeredEvents:Array = new Array();
public var ___registeredFunctions:Array = new Array();
function AxApplication()
{
super();
}
public function localRegisterForEvent(e:Event,func:*,caller:*):void
{
caller.addEventListener(e.type,localCallerEventHandler,true,3);
caller.addEventListener(e.type,localCallerEventHandler,false,3);
___registeredEvents.push(e);
___registeredFunctions.push(func);
}
public function localCallerEventHandler(e:*):void
{
if(e!=null)
{
for(var i:int = 0 ; i< ___registeredEvents.length; i++)
{
if(e.type == ___registeredEvents[i].type)
{
___registeredFunctions[i](e);
//the registered function gets called
//there no garbage collection implemented!
}
}
}
}
}
I think that is not a very useful solution. Why? Because you scatter AxApplication references around the application. Views and Model instance don't need any references to the application at all. It would be better to to implement a controller layer which uses a simple eventBus property, which could look like:
private static const _EVENT_BUS:IEventDispatcher = FlexGlobals.topLevelApplication;
protected final function eventBus():IEventDispatcher {
return _EVENT_BUS;
}
If you implement a base view controller/mediator (depending from which framework you're coming), you don't have any reference to non-framework classes at all, which makes it highly reusable. It is just a simple reuse of the Application singleton which you use to dispatch system wide events. You register listeners in the view controller/mediator and update the views or models accordingly. RobotLegs for example uses a system wide event dispatcher as well.
Why not just using the parentApplication approach? Because you can't implement tests (the generated test-runner of IDEs won't extend your AxApplication) or just yank the components/models in a different application - that is basically not possible.
So I have many objects with materials that each possess different properties (brick, glass, etc.) and are each affected differently by elemental effects. A brick material for example will be affected differently by fire or acid than a cement material. A brick that's Burning or Melting will be affected differently when another Burning/Melting effect is applied.
At this point in my game, I have an FSM but it's very simple. If I drop a fire element on a brick, it would go to the Burning state. However if I then dropped a water element on the brick, I might want the fire to go out, take/add health and change textures (or not depending on the current combination).
The point is, I have many combinations with no commonality between them so I can't create something uniform. Sometimes I need to change the texture and other times I don't. Sometimes take damage while other times add health. Sometimes I need to just do nothing in a function. At this point, the only thing I can thing of is creating a global mapping such as:
FunctionMap[ObjectMaterial][CurrentObjectState][ElementBeingApplied]
(i.e.
FunctionMap[Brick][Burning][Acid]
FunctionMap[Brick][Melting][Acid]
)
The problem is, is that this is obviously a ton of functions due to the amount of combinations available with materials and effect types. Can anyone recommend a route to take or pattern to look at?
Although not entirely relevant to the discussion, this is being made in AS3 and Away3D.
Here are some of my classes for one example:
public class Brick extends AbstractBlock implements IFireable
{
public function Brick()
{
super(this);
this.material = new BitmapMaterial(_spriteManager.GetBlockMaterial(BlockUtilities.GetMaterialMap["brick_new"]));
_type = "Brick";
/*
RulesManager.StateMap["Brick"]["OnFire"]["Water"] = some function;
RulesManager.StateMap["Brick"]["OnFire"]["Fire"] = some function;
RulesManager.StateMap["Brick"]["OnFire"]["Acid"] = some function;
RulesManager.StateMap["Brick"]["OnFire"]["Ice"] = some function;
RulesManager.StateMap["Brick"]["OnWater"]["Water"] = some function;
//and so on...there are nine different materials so I'm not liking this way
*/
}
public override function render():void
{
super.render();
}
}
public class OnFire extends AbstractDamage
{
protected var _timeStart:Number = 0;
private var _damageAccumulated:Number = 0;
public function OnFire(block:AbstractBlock,bombType:String)
{
super(block,bombType);
}
public override function enter():void
{
super.enter();
}
public override function exit():void
{
super.exit();
}
public override function update(time:Number):void
{
super.update(time);
if(_timeStart == 0)
_timeStart = time;
var time_delta:Number = (time - _timeStart)/_waitTime;
var damageToSubtract:Number = (time_delta * _damageDone);
_damageAccumulated += damageToSubtract;
_self.Integrity = _self.Integrity - _damageAccumulated;
}
}
}
Thus, a fire element could be applied to a bunch of applies. One those blocks, currently frozen, is now hit and is now changing to the OnFire state. Each block has its own state machine and the states are themselves objects as you can see.
block.FSM.changeState(new OnFire(block));
So your problem is that you have 9 * 5 * 4 combinations of effects, right? Having separate functions for each of those would not be fun to manage. But, even if it's a lot of data, you need it. I would make that data as simple as possible, then parse it. Something like:
var materialProperties = {
brick: {
fire: {
normal: {damage: 10, image: 'brick_fire.jpg'},
}
water: {
fire: {damage: 0, image: 'brick_smoking.jpg'}
}
},
//... a lot more of this ...
}
class Material
{
public var damage:int = 0;
public var image:String = '';
private var properties:Object;
private var state:String;
public function Material(properties)
{
this.properties = properties;
}
public function apply(effect:String):void
{
if(properties[effect])
{
if(properties[effect][state])
{
update(properties[effect][state]);
}
else if(properties[effect]['normal'])
{
update(properties[effect]['normal']);
}
}
state = effect;
}
private function update(properties):void
{
damage += properties.damage;
image = properties.image;
}
}
var brick = new Material(materialProperties.brick);
brick.apply('fire');
brick.apply('water');
Do you have custom classes setup? To me, this sounds like an ideal solution.
Once you map out each classes properties and abilities, object management should be trivial.
ie a Brick class which has certain states [burning, melting] and reacts differently [function calls] when it interacts [collides] with another class [Water Class].
I hope I'm not barking up the wrong tree.... If you can provide a bit more on what your looking for, im sure someone smarter than me will jump in ;)
Short answer because I believe Mr Linquist does a great job of explaining it - but it sounds to me like a job for the visitor pattern. In a nutshell, your elements (brick, concrete, etc) all allow visitors (fire, ice, acid, etc) to come and 'visit' them and apply their effects.
Hope this helps!
I am making a game, and I have finally finished the gameplay aspect of it, but now it's time for me to create a menu and a high scores screen. I'm not entirely sure how to do it, the game will be in a different state (MENU_STATE, GAMEPLAY_STATE, SCORESCREEN_STATE) and in each state I want to draw different things to the screen, is it okay for me to do something like this then?
draw function()
{
if MENU_STATE
draw menu
if GAMEPLAY_STATE
draw game
if SCORESCREEN_STATE
draw scores
}
I've been following a strictly no logic in the draw function and it's been good so far, but I really can't figure out a different way to do this.
You could use separate classes for the three states, implementing a common interface, and rather than setting a constant for state, set an instance of one of the classes:
interface IState {
void draw();
}
class Menu implements IState {
void draw() {
// Draw menu
}
}
class Game implements IState {
void draw() {
// Draw game
}
}
void draw() {
state.draw();
}
This still isn't ideal (you don't really want drawing code in your state, you want something a bit more separate), but the abstraction is a common one and could be relevant (and it's hard to advise further without knowing more of your architecture).
You are calling some drawing functions in that routine but that doesn't mean
you have to name it draw.
Perhaps this is more appropriate in your case:
// pseudocode
on_game_state function(state)
{
select (state):
MENU_STATE:
draw menu
GAMEPLAY_STATE:
draw game
SCORESCREEN_STATE:
draw scores
}
Using a statemachine would make this simpler. Each state will have its own set of update and draw functions that are called when it is on top of the state stack. Instead of having one draw function with internal state switches you would have Game_Draw(), Menu_Draw(), HighScoreScreen_Draw() etc. Similarly your update functions could be separated out.
static void StateMachine_DrawTopState()
{
switch(stateMachine_topState)
{
case STATE_GAMEPLAY:
{
Gameplay_Draw();
}
break;
case STATE_MENU:
{
Menu_Draw();
}
break;
}
}
Similar to Andrew Aylett's answer and assuming an object-oriented language, perhaps you could do something like:
Interface IState {
void init();
void update();
void draw();
}
class GameplayScene implements IState {
void init() {
// initialize gameplay
}
void update() {
// update game logic
}
void draw() {
// draw game
}
}
class MenuScene implements IState {
void init() {
// initialize menu
}
void update() {
// update menu logic
}
void draw() {
// draw menu
}
}
class ScoresScene etc...
class TitleScene etc...
// Somewhere else, probably in the Game class
void Main() {
// Init game
Scene currentScene = new TitleScene;
while (Scene != null) {
Scene.init();
Scene.update();
Scene.draw();
}
// Exit game
}
You would also need to think about how to handle transition between scenes. You could have each scene class have a member variable called something like nextScene and the main function queries it at the start of the loop to switch to the proper scene.
If you don't have the luxury of using an object-oriented programming language (like C++, Java, C#, Python, etc.), both Colin's and Nick D's answers might help, although I'd try to have the switch statement in one place (say one big game_update function) to allow adding new states by making a change in one place. Alternatively, you could build on the Colin's state machine design to make something more generic and that doesn't explicitly require a hard-coded switch statement. (although to be honest I can't think of a good way to do it at the moment)
It is absolutely not ok to put game logic in a draw function.
However, if it makes your life easier in this specific case, it's ok anyway.
You can always change it later if it becomes a mess.
Yes it's fine, game programmers are allowed to bend the rules for performance gains. The view and the model of a game world are quite often one and the same thing to avoid latency created by decoupling the view and the model.
There's no reason why you can't make the menu and highscores objects part of your game world, it's been done before in quite a few games.