Merge branch 'upstreamedge' into test/encoder-direct-step
[clinton/Smoothieware.git] / src / libs / USBDevice / USBSerial / USBSerial.cpp
1 /* Copyright (c) 2010-2011 mbed.org, MIT License
2 *
3 * Permission is hereby granted, free of charge, to any person obtaining a copy of this software
4 * and associated documentation files (the "Software"), to deal in the Software without
5 * restriction, including without limitation the rights to use, copy, modify, merge, publish,
6 * distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the
7 * Software is furnished to do so, subject to the following conditions:
8 *
9 * The above copyright notice and this permission notice shall be included in all copies or
10 * substantial portions of the Software.
11 *
12 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING
13 * BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
14 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
15 * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
16 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
17 */
18
19 #include <cstdint>
20 #include <cstdio>
21
22 #include "USBSerial.h"
23
24 #include "libs/Kernel.h"
25 #include "libs/SerialMessage.h"
26 #include "StreamOutputPool.h"
27
28 // extern void setled(int, bool);
29 #define setled(a, b) do {} while (0)
30
31 #define iprintf(...) do { } while (0)
32
33 USBSerial::USBSerial(USB *u): USBCDC(u), rxbuf(256 + 8), txbuf(128 + 8)
34 {
35 usb = u;
36 nl_in_rx = 0;
37 attach = attached = false;
38 flush_to_nl = false;
39 halt_flag = false;
40 query_flag = false;
41 last_char_was_dollar = false;
42 }
43
44 void USBSerial::ensure_tx_space(int space)
45 {
46 while (txbuf.free() < space) {
47 usb->endpointSetInterrupt(CDC_BulkIn.bEndpointAddress, true);
48 usb->usbisr();
49 }
50 }
51
52 int USBSerial::_putc(int c)
53 {
54 if (!attached)
55 return 1;
56 ensure_tx_space(1);
57 txbuf.queue(c);
58
59 usb->endpointSetInterrupt(CDC_BulkIn.bEndpointAddress, true);
60 return 1;
61 }
62
63 int USBSerial::_getc()
64 {
65 if (!attached)
66 return 0;
67 uint8_t c = 0;
68 setled(4, 1); while (rxbuf.isEmpty()); setled(4, 0);
69 rxbuf.dequeue(&c);
70 if (rxbuf.free() == MAX_PACKET_SIZE_EPBULK) {
71 usb->endpointSetInterrupt(CDC_BulkOut.bEndpointAddress, true);
72 iprintf("rxbuf has room for another packet, interrupt enabled\n");
73 } else if ((rxbuf.free() < MAX_PACKET_SIZE_EPBULK) && (nl_in_rx == 0)) {
74 // handle potential deadlock where a short line, and the beginning of a very long line are bundled in one usb packet
75 rxbuf.flush();
76 flush_to_nl = true;
77
78 usb->endpointSetInterrupt(CDC_BulkOut.bEndpointAddress, true);
79 iprintf("rxbuf has room for another packet, interrupt enabled\n");
80 }
81 if (nl_in_rx > 0)
82 if (c == '\n' || c == '\r')
83 nl_in_rx--;
84
85 return c;
86 }
87
88 int USBSerial::puts(const char *str)
89 {
90 if (!attached)
91 return strlen(str);
92 int i = 0;
93 while (*str) {
94 ensure_tx_space(1);
95 txbuf.queue(*str);
96 if ((txbuf.available() % 64) == 0)
97 usb->endpointSetInterrupt(CDC_BulkIn.bEndpointAddress, true);
98 i++;
99 str++;
100 }
101 usb->endpointSetInterrupt(CDC_BulkIn.bEndpointAddress, true);
102 return i;
103 }
104
105 uint16_t USBSerial::writeBlock(const uint8_t * buf, uint16_t size)
106 {
107 if (!attached)
108 return size;
109 if (size > txbuf.free()) {
110 size = txbuf.free();
111 }
112 if (size > 0) {
113 for (uint8_t i = 0; i < size; i++) {
114 txbuf.queue(buf[i]);
115 }
116 usb->endpointSetInterrupt(CDC_BulkIn.bEndpointAddress, true);
117 }
118 return size;
119 }
120
121 bool USBSerial::USBEvent_EPIn(uint8_t bEP, uint8_t bEPStatus)
122 {
123 /*
124 * Called in ISR context
125 */
126
127 // static bool needToSendNull = false;
128
129 bool r = true;
130
131 if (bEP != CDC_BulkIn.bEndpointAddress)
132 return false;
133
134 iprintf("USBSerial:EpIn: 0x%02X\n", bEPStatus);
135
136 uint8_t b[MAX_PACKET_SIZE_EPBULK];
137
138 int l = txbuf.available();
139 iprintf("%d bytes queued\n", l);
140 if (l > 0) {
141 if (l > MAX_PACKET_SIZE_EPBULK)
142 l = MAX_PACKET_SIZE_EPBULK;
143 iprintf("Sending %d bytes:\n\t", l);
144 int i;
145 for (i = 0; i < l; i++) {
146 txbuf.dequeue(&b[i]);
147 if (b[i] >= 32 && b[i] < 128)
148 iprintf("%c", b[i]);
149 else {
150 iprintf("\\x%02X", b[i]);
151 }
152 }
153 iprintf("\nSending...\n");
154 send(b, l);
155 iprintf("Sent\n");
156 if (txbuf.available() == 0)
157 r = false;
158 } else {
159 r = false;
160 }
161 iprintf("USBSerial:EpIn Complete\n");
162 return r;
163 }
164
165 bool USBSerial::USBEvent_EPOut(uint8_t bEP, uint8_t bEPStatus)
166 {
167 /*
168 * Called in ISR context
169 */
170
171 bool r = true;
172
173 iprintf("USBSerial:EpOut\n");
174 if (bEP != CDC_BulkOut.bEndpointAddress)
175 return false;
176
177 if (rxbuf.free() < MAX_PACKET_SIZE_EPBULK) {
178 // usb->endpointSetInterrupt(bEP, false);
179 return false;
180 }
181
182 uint8_t c[MAX_PACKET_SIZE_EPBULK];
183 uint32_t size = 64;
184
185 //we read the packet received and put it on the circular buffer
186 readEP(c, &size);
187 iprintf("Read %ld bytes:\n\t", size);
188 for (uint8_t i = 0; i < size; i++) {
189 if(c[i] == 'X' - 'A' + 1) { // ^X
190 THEKERNEL->set_feed_hold(false); // required to free stuff up
191 halt_flag = true;
192 continue;
193 }
194
195 if(c[i] == '?') { // ?
196 query_flag = true;
197 continue;
198 }
199
200 if(THEKERNEL->is_grbl_mode()) {
201 if(c[i] == '!') { // safe pause
202 THEKERNEL->set_feed_hold(true);
203 continue;
204 }
205
206 if(c[i] == '~') { // safe resume
207 THEKERNEL->set_feed_hold(false);
208 continue;
209 }
210 if(last_char_was_dollar && (c[i] == 'X' || c[i] == 'H')) {
211 // we need to do this otherwise $X/$H won't work if there was a feed hold like when stop is clicked in bCNC
212 THEKERNEL->set_feed_hold(false);
213 }
214 }
215
216 last_char_was_dollar = (c[i] == '$');
217
218 if (flush_to_nl == false)
219 rxbuf.queue(c[i]);
220
221 // if (c[i] >= 32 && c[i] < 128)
222 // {
223 // iprintf("%c", c[i]);
224 // }
225 // else
226 // {
227 // iprintf("\\x%02X", c[i]);
228 // }
229
230 if (c[i] == '\n' || c[i] == '\r') {
231 if (flush_to_nl)
232 flush_to_nl = false;
233 else
234 nl_in_rx++;
235 } else if (rxbuf.isFull() && (nl_in_rx == 0)) {
236 // to avoid a deadlock with very long lines, we must dump the buffer
237 // and continue flushing to the next newline
238 rxbuf.flush();
239 flush_to_nl = true;
240 }
241 }
242 iprintf("\nQueued, %d empty\n", rxbuf.free());
243
244 if (rxbuf.free() < MAX_PACKET_SIZE_EPBULK) {
245 // if buffer is full, stall endpoint, do not accept more data
246 r = false;
247
248 if (nl_in_rx == 0) {
249 // we have to check for long line deadlock here too
250 flush_to_nl = true;
251 rxbuf.flush();
252
253 // and since our buffer is empty, we can accept more data
254 r = true;
255 }
256 }
257
258 usb->readStart(CDC_BulkOut.bEndpointAddress, MAX_PACKET_SIZE_EPBULK);
259 iprintf("USBSerial:EpOut Complete\n");
260 return r;
261 }
262
263 uint8_t USBSerial::available()
264 {
265 return rxbuf.available();
266 }
267
268 bool USBSerial::ready()
269 {
270 return rxbuf.available();
271 }
272
273 void USBSerial::on_module_loaded()
274 {
275 this->register_for_event(ON_MAIN_LOOP);
276 this->register_for_event(ON_IDLE);
277 }
278
279 void USBSerial::on_idle(void *argument)
280 {
281 if(halt_flag) {
282 halt_flag = false;
283 THEKERNEL->call_event(ON_HALT, nullptr);
284 if(THEKERNEL->is_grbl_mode()) {
285 puts("ALARM:Abort during cycle\r\n");
286 } else {
287 puts("HALTED, M999 or $X to exit HALT state\r\n");
288 }
289 rxbuf.flush(); // flush the recieve buffer, hopefully upstream has stopped sending
290 nl_in_rx = 0;
291 }
292
293 if(query_flag) {
294 query_flag = false;
295 puts(THEKERNEL->get_query_string().c_str());
296 }
297
298 }
299
300 void USBSerial::on_main_loop(void *argument)
301 {
302 // apparently some OSes don't assert DTR when a program opens the port
303 if (available() && !attach)
304 attach = true;
305
306 if (attach != attached) {
307 if (attach) {
308 attached = true;
309 THEKERNEL->streams->append_stream(this);
310 puts("Smoothie\r\nok\r\n");
311 } else {
312 attached = false;
313 THEKERNEL->streams->remove_stream(this);
314 txbuf.flush();
315 rxbuf.flush();
316 nl_in_rx = 0;
317 }
318 }
319
320 // if we are in feed hold we do not process anything
321 if(THEKERNEL->get_feed_hold()) return;
322
323 if (nl_in_rx) {
324 string received;
325 while (available()) {
326 char c = _getc();
327 if( c == '\n' || c == '\r') {
328 struct SerialMessage message;
329 message.message = received;
330 message.stream = this;
331 iprintf("USBSerial Received: %s\n", message.message.c_str());
332 THEKERNEL->call_event(ON_CONSOLE_LINE_RECEIVED, &message );
333 return;
334 } else {
335 received += c;
336 }
337 }
338 }
339 }
340
341 void USBSerial::on_attach()
342 {
343 attach = true;
344 }
345
346 void USBSerial::on_detach()
347 {
348 attach = false;
349 }