Imagine a device full of sensors. Now, in case a sensor x detects something, something should happen. Meanwhile, in case something else is detected, like two sensors detects two different things, then, this device must behave differently.
From webdesign (so javascript) I learned about Events, for example (using jquery) $(".x").on("click", function(){})
or from angularjs $scope.watch("name_of_var", function())
.
Is there any possibility to replicate this behaviour in C, without using complex libraries?
I would assume you're owning an embedded system with access to interrupts or a major event loop in a separate thread, otherwise this isn't possible..
A basic model for event handling is here:
#define NOEVENT 0
typedef void *(*EventHandler)(void *);
void *doNothing(void *p){/*do nothing absolutely*/ return NULL; }
typedef struct _event{
EventHandler handler;
}Event, *PEvent;
Event AllEvents[1000];
unsigned short counter = 0;
void InitEvents()
{
LOCK(AllEvents);
for(int i = 0; i < 1000; i++){
AllEvents[i].handler = doNothing;
}
UNLOCK(AllEvents);
}
void AddEvent(int EventType, EventHandler ev_handler)
{
LOCK(AllEvents);
AllEvents[EventType].handler = ev_handler;
UNLOCK(AllEvents);
}
void RemoveEvent(int EventType, EventHandler ev_handler)
{
LOCK(AllEvents);
AllEvents[EventType] = doNothing;
UNLOCK(AllEvents); /*to safeguard the event loop*/
}
/*to be run in separate thread*/
void EventLoop()
{
int event = NOEVENT;
EventHandler handler;
while(1){
while(event == NOEVENT)event=GetEvents();
handler = AllEvents[event].handler;
handler();/*perform on an event*/
}
}