temperaturecontrol: allow setting background tool without activating
[clinton/Smoothieware.git] / src / libs / Network / uip / CallbackStream.cpp
1 #include "CallbackStream.h"
2 #include "Kernel.h"
3 #include <stdio.h>
4
5 #include "SerialConsole.h"
6 //#define DEBUG_PRINTF THEKERNEL->serial->printf
7 #define DEBUG_PRINTF(...)
8
9 CallbackStream::CallbackStream(cb_t cb, void *u)
10 {
11 DEBUG_PRINTF("Callbackstream ctor: %p\n", this);
12 callback= cb;
13 user= u;
14 closed= false;
15 use_count= 0;
16 }
17
18 CallbackStream::~CallbackStream()
19 {
20 DEBUG_PRINTF("Callbackstream dtor: %p\n", this);
21 }
22
23 int CallbackStream::puts(const char *s)
24 {
25 if(closed) return 0;
26
27 if(s == NULL) return (*callback)(NULL, user);
28
29 int len = strlen(s);
30 int n;
31 do {
32 // call this streams result callback
33 n= (*callback)(s, user);
34
35 // if closed just pretend we sent it
36 if(n == -1) {
37 closed= true;
38 return len;
39
40 }else if(n == 0) {
41 // if output queue is full
42 // call idle until we can output more
43 THEKERNEL->call_event(ON_IDLE);
44 }
45 } while(n == 0);
46
47 return len;
48 }
49
50 void CallbackStream::mark_closed()
51 {
52 closed= true;
53 if(use_count <= 0) delete this;
54 }
55 void CallbackStream::dec()
56 {
57 use_count--;
58 if(closed && use_count <= 0) delete this;
59 }
60
61 extern "C" void *new_callback_stream(cb_t cb, void *u)
62 {
63 return new CallbackStream(cb, u);
64 }
65
66 extern "C" void delete_callback_stream(void *p)
67 {
68 // we don't delete it in case it is still on the command queue
69 ((CallbackStream*)p)->mark_closed();
70 }