/ Repetier / gcode.cpp
gcode.cpp
   1  /*
   2      This file is part of Repetier-Firmware.
   3  
   4      Repetier-Firmware is free software: you can redistribute it and/or modify
   5      it under the terms of the GNU General Public License as published by
   6      the Free Software Foundation, either version 3 of the License, or
   7      (at your option) any later version.
   8  
   9      Repetier-Firmware is distributed in the hope that it will be useful,
  10      but WITHOUT ANY WARRANTY; without even the implied warranty of
  11      MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  12      GNU General Public License for more details.
  13  
  14      You should have received a copy of the GNU General Public License
  15      along with Repetier-Firmware.  If not, see <http://www.gnu.org/licenses/>.
  16  
  17      This firmware is a nearly complete rewrite of the sprinter firmware
  18      by kliment (https://github.com/kliment/Sprinter)
  19      which based on Tonokip RepRap firmware rewrite based off of Hydra-mmm firmware.
  20  
  21    Functions in this file are used to communicate using ascii or repetier protocol.
  22  */
  23  
  24  #include "Reptier.h"
  25  
  26  #define bit_clear(x,y) x&= ~(1<<y) //cbi(x,y) 
  27  #define bit_set(x,y)   x|= (1<<y)//sbi(x,y) 
  28  
  29  #define MAX_CMD_SIZE 96
  30  GCode gcode_buffer[GCODE_BUFFER_SIZE]; ///< Buffer for received commands.
  31  byte gcode_rindex=0; ///< Read position in gcode_buffer.
  32  byte gcode_windex=0; ///< Write position in gcode_buffer.
  33  byte gcode_transbuffer[MAX_CMD_SIZE]; ///< Current received command. 
  34  byte gcode_wpos=0; ///< Writing position in gcode_transbuffer.
  35  byte gcode_binary; ///< Flags the command as binary input.
  36  byte gcode_last_binary=0; ///< Was the last successful command in binary mode?
  37  byte gcode_comment=false; ///< Flags true if we are reading the comment part of a command.
  38  byte gcode_binary_size; ///< Expected size of the incoming binary command.
  39  bool gcode_wait_all_parsed=false; ///< Don't read until all commands are parsed. Needed if gcode_buffer is misused as storage for strings.
  40  long gcode_lastN=0; ///< Last line number received.
  41  long gcode_actN; ///< Line number of current command.
  42  char gcode_wait_resend=-1; ///< Waiting for line to be resend. -1 = no wait.
  43  volatile byte gcode_buflen=0; ///< Number of commands stored in gcode_buffer
  44  unsigned long gcode_lastdata=0; ///< Time, when we got the last data packet. Used to detect missing bytes.
  45  SerialOutput out; ///< Instance used for serail write operations.
  46  
  47  #ifndef EXTERNALSERIAL
  48  // Implement serial communication for one stream only!
  49  /*
  50    HardwareSerial.h - Hardware serial library for Wiring
  51    Copyright (c) 2006 Nicholas Zambetti.  All right reserved.
  52  
  53    This library is free software; you can redistribute it and/or
  54    modify it under the terms of the GNU Lesser General Public
  55    License as published by the Free Software Foundation; either
  56    version 2.1 of the License, or (at your option) any later version.
  57  
  58    This library is distributed in the hope that it will be useful,
  59    but WITHOUT ANY WARRANTY; without even the implied warranty of
  60    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  61    Lesser General Public License for more details.
  62  
  63    You should have received a copy of the GNU Lesser General Public
  64    License along with this library; if not, write to the Free Software
  65    Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
  66  
  67    Modified 28 September 2010 by Mark Sproul
  68    
  69    Modified to use only 1 queue with fixed length by Repetier
  70  */
  71  
  72  ring_buffer rx_buffer = { { 0 }, 0, 0};
  73  ring_buffer tx_buffer = { { 0 }, 0, 0};
  74  
  75  inline void rf_store_char(unsigned char c, ring_buffer *buffer)
  76  {
  77    int i = (unsigned int)(buffer->head + 1) & SERIAL_BUFFER_MASK;
  78  
  79    // if we should be storing the received character into the location
  80    // just before the tail (meaning that the head would advance to the
  81    // current location of the tail), we're about to overflow the buffer
  82    // and so we don't write the character or advance the head.
  83    if (i != buffer->tail) {
  84      buffer->buffer[buffer->head] = c;
  85      buffer->head = i;
  86    }
  87  }
  88  #if !defined(USART0_RX_vect) && defined(USART1_RX_vect)
  89  // do nothing - on the 32u4 the first USART is USART1
  90  #else
  91  #if !defined(USART_RX_vect) && \
  92      !defined(SIG_UART0_RECV) && !defined(USART0_RX_vect) && \
  93  	!defined(SIG_UART_RECV)
  94    #error "Don't know what the Data Received vector is called for the first UART"
  95  #else
  96    void rfSerialEvent() __attribute__((weak));
  97    void rfSerialEvent() {}
  98    #define serialEvent_implemented
  99  #if defined(USART_RX_vect)
 100    SIGNAL(USART_RX_vect)
 101  #elif defined(SIG_UART0_RECV)
 102    SIGNAL(SIG_UART0_RECV)
 103  #elif defined(USART0_RX_vect)
 104    SIGNAL(USART0_RX_vect)
 105  #elif defined(SIG_UART_RECV)
 106    SIGNAL(SIG_UART_RECV)
 107  #endif
 108    {
 109    #if defined(UDR0)
 110      unsigned char c  =  UDR0;
 111    #elif defined(UDR)
 112      unsigned char c  =  UDR;
 113    #else
 114      #error UDR not defined
 115    #endif
 116      rf_store_char(c, &rx_buffer);
 117    }
 118  #endif
 119  #endif
 120  
 121  #if !defined(USART0_UDRE_vect) && defined(USART1_UDRE_vect)
 122  // do nothing - on the 32u4 the first USART is USART1
 123  #else
 124  #if !defined(UART0_UDRE_vect) && !defined(UART_UDRE_vect) && !defined(USART0_UDRE_vect) && !defined(USART_UDRE_vect)
 125    #error "Don't know what the Data Register Empty vector is called for the first UART"
 126  #else
 127  #if defined(UART0_UDRE_vect)
 128  ISR(UART0_UDRE_vect)
 129  #elif defined(UART_UDRE_vect)
 130  ISR(UART_UDRE_vect)
 131  #elif defined(USART0_UDRE_vect)
 132  ISR(USART0_UDRE_vect)
 133  #elif defined(USART_UDRE_vect)
 134  ISR(USART_UDRE_vect)
 135  #endif
 136  {
 137    if (tx_buffer.head == tx_buffer.tail) {
 138  	// Buffer empty, so disable interrupts
 139  #if defined(UCSR0B)
 140      bit_clear(UCSR0B, UDRIE0);
 141  #else
 142      bit_clear(UCSRB, UDRIE);
 143  #endif
 144    }
 145    else {
 146      // There is more data in the output buffer. Send the next byte
 147      unsigned char c = tx_buffer.buffer[tx_buffer.tail];
 148      tx_buffer.tail = (tx_buffer.tail + 1) & SERIAL_BUFFER_MASK;
 149  	
 150    #if defined(UDR0)
 151      UDR0 = c;
 152    #elif defined(UDR)
 153      UDR = c;
 154    #else
 155      #error UDR not defined
 156    #endif
 157    }
 158  }
 159  #endif
 160  #endif
 161  
 162  
 163  // Constructors ////////////////////////////////////////////////////////////////
 164  
 165  RFHardwareSerial::RFHardwareSerial(ring_buffer *rx_buffer, ring_buffer *tx_buffer,
 166    volatile uint8_t *ubrrh, volatile uint8_t *ubrrl,
 167    volatile uint8_t *ucsra, volatile uint8_t *ucsrb,
 168    volatile uint8_t *udr,
 169    uint8_t rxen, uint8_t txen, uint8_t rxcie, uint8_t udrie, uint8_t u2x)
 170  {
 171    _rx_buffer = rx_buffer;
 172    _tx_buffer = tx_buffer;
 173    _ubrrh = ubrrh;
 174    _ubrrl = ubrrl;
 175    _ucsra = ucsra;
 176    _ucsrb = ucsrb;
 177    _udr = udr;
 178    _rxen = rxen;
 179    _txen = txen;
 180    _rxcie = rxcie;
 181    _udrie = udrie;
 182    _u2x = u2x;
 183  }
 184  
 185  // Public Methods //////////////////////////////////////////////////////////////
 186  
 187  void RFHardwareSerial::begin(unsigned long baud)
 188  {
 189    uint16_t baud_setting;
 190    bool use_u2x = true;
 191  
 192  #if F_CPU == 16000000UL
 193    // hardcoded exception for compatibility with the bootloader shipped
 194    // with the Duemilanove and previous boards and the firmware on the 8U2
 195    // on the Uno and Mega 2560.
 196    if (baud == 57600) {
 197      use_u2x = false;
 198    }
 199  #endif
 200  
 201  try_again:
 202    
 203    if (use_u2x) {
 204      *_ucsra = 1 << _u2x;
 205      baud_setting = (F_CPU / 4 / baud - 1) / 2;
 206    } else {
 207      *_ucsra = 0;
 208      baud_setting = (F_CPU / 8 / baud - 1) / 2;
 209    }
 210    
 211    if ((baud_setting > 4095) && use_u2x)
 212    {
 213      use_u2x = false;
 214      goto try_again;
 215    }
 216  
 217    // assign the baud_setting, a.k.a. ubbr (USART Baud Rate Register)
 218    *_ubrrh = baud_setting >> 8;
 219    *_ubrrl = baud_setting;
 220  
 221    bit_set(*_ucsrb, _rxen);
 222    bit_set(*_ucsrb, _txen);
 223    bit_set(*_ucsrb, _rxcie);
 224    bit_clear(*_ucsrb, _udrie);
 225  }
 226  
 227  void RFHardwareSerial::end()
 228  {
 229    // wait for transmission of outgoing data
 230    while (_tx_buffer->head != _tx_buffer->tail)
 231      ;
 232  
 233    bit_clear(*_ucsrb, _rxen);
 234    bit_clear(*_ucsrb, _txen);
 235    bit_clear(*_ucsrb, _rxcie);  
 236    bit_clear(*_ucsrb, _udrie);
 237    
 238    // clear any received data
 239    _rx_buffer->head = _rx_buffer->tail;
 240  }
 241  
 242  int RFHardwareSerial::available(void)
 243  {
 244    return (unsigned int)(SERIAL_BUFFER_SIZE + _rx_buffer->head - _rx_buffer->tail) & SERIAL_BUFFER_MASK;
 245  }
 246  
 247  int RFHardwareSerial::peek(void)
 248  {
 249    if (_rx_buffer->head == _rx_buffer->tail) {
 250      return -1;
 251    } else {
 252      return _rx_buffer->buffer[_rx_buffer->tail];
 253    }
 254  }
 255  
 256  int RFHardwareSerial::read(void)
 257  {
 258    // if the head isn't ahead of the tail, we don't have any characters
 259    if (_rx_buffer->head == _rx_buffer->tail) {
 260      return -1;
 261    } else {
 262      unsigned char c = _rx_buffer->buffer[_rx_buffer->tail];
 263      _rx_buffer->tail = (unsigned int)(_rx_buffer->tail + 1) & SERIAL_BUFFER_MASK;
 264      return c;
 265    }
 266  }
 267  
 268  void RFHardwareSerial::flush()
 269  {
 270    while (_tx_buffer->head != _tx_buffer->tail)
 271      ;
 272  }
 273  #ifdef COMPAT_PRE1
 274    void 
 275  #else
 276    size_t 
 277  #endif
 278  RFHardwareSerial::write(uint8_t c)
 279  {
 280    int i = (_tx_buffer->head + 1) & SERIAL_BUFFER_MASK;
 281  	
 282    // If the output buffer is full, there's nothing for it other than to 
 283    // wait for the interrupt handler to empty it a bit
 284    // ???: return 0 here instead?
 285    while (i == _tx_buffer->tail)
 286      ;
 287  	
 288    _tx_buffer->buffer[_tx_buffer->head] = c;
 289    _tx_buffer->head = i;
 290  	
 291    bit_set(*_ucsrb, _udrie);
 292  #ifndef COMPAT_PRE1 
 293    return 1;
 294  #endif
 295  }
 296  
 297  // Preinstantiate Objects //////////////////////////////////////////////////////
 298  
 299  #if defined(UBRRH) && defined(UBRRL)
 300    RFHardwareSerial RFSerial(&rx_buffer, &tx_buffer, &UBRRH, &UBRRL, &UCSRA, &UCSRB, &UDR, RXEN, TXEN, RXCIE, UDRIE, U2X);
 301  #elif defined(UBRR0H) && defined(UBRR0L)
 302    RFHardwareSerial RFSerial(&rx_buffer, &tx_buffer, &UBRR0H, &UBRR0L, &UCSR0A, &UCSR0B, &UDR0, RXEN0, TXEN0, RXCIE0, UDRIE0, U2X0);
 303  #elif defined(USBCON)
 304    // do nothing - Serial object and buffers are initialized in CDC code
 305  #else
 306    #error no serial port defined  (port 0)
 307  #endif
 308  
 309  #endif
 310  
 311  /** \page Repetier-protocol
 312  
 313  \section Introduction
 314  
 315  The repetier-protocol was developed, to overcome some shortcommings in the standard
 316  RepRap communication method, while remaining backward compatible. To use the improved
 317  features of this protocal, you need a host which speaks it. On Windows the recommended
 318  host software is Repetier-Host. It is developed in parallel to this firmware and supports
 319  all implemented features.
 320  
 321  \subsection Improvements
 322  
 323  - With higher speeds, the serial connection is more likely to produce communication failures.
 324    The standard method is to transfer a checksum at the end of the line. This checksum is the
 325    XORd value of all characters send. The value is limited to a range between 0 and 127. It can 
 326    not detect two identical missing characters or a wrong order. Therefore the new protocol
 327    uses Fletchers checksum, which overcomes these shortcommings.
 328  - The new protocol send data in binary format. This reduces the data size to less then 50% and
 329    it speeds up decoding the command. No slow conversion from string to floats are needed.
 330    
 331  */
 332  
 333  /** \brief Computes size of binary data from bitfield.
 334  
 335  In the repetier-protocol in binary mode, the first 2 bytes define the
 336  data. From this bitfield, this function computes the size of the command
 337  including the 2 bytes of the bitfield and the 2 bytes for the checksum.
 338  
 339  Gcode Letter to Bit and Datatype:
 340  
 341  - N : Bit 0 : 16-Bit Integer
 342  - M : Bit 1 :  8-Bit unsigned byte
 343  - G : Bit 2 :  8-Bit unsigned byte
 344  - X : Bit 3 :  32-Bit Float
 345  - Y : Bit 4 :  32-Bit Float
 346  - Z : Bit 5 :  32-Bit Float
 347  - E : Bit 6 :  32-Bit Float
 348  -  : Bit 7 :  always set to distinguish binary from ASCII line.
 349  - F : Bit 8 :  32-Bit Float
 350  - T : Bit 9 :  8 Bit Integer
 351  - S : Bit 10 : 32 Bit Value
 352  - P : Bit 11 : 32 Bit Integer
 353  - V2 : Bit 12 : Version 2 command for additional commands/sizes
 354  - Ext : Bit 13 : There are 2 more bytes following with Bits, only for future versions
 355  - Int :Bit 14 : Marks it as internal command, 
 356  - Text : Bit 15 : 16 Byte ASCII String terminated with 0
 357  Second word if V2:
 358  - I : Bit 0 : 32-Bit float
 359  - J : Bit 1 : 32-Bit float
 360  - R : Bit 2 : 32-Bit float
 361  */
 362  byte gcode_comp_binary_size(char *ptr) {// unsigned int bitfield) {
 363     byte s = 4; // include checksum and bitfield
 364     unsigned int bitfield = *(int*)ptr;
 365     if(bitfield & 1) s+=2;
 366     if(bitfield & 8) s+=4;
 367     if(bitfield & 16) s+=4;
 368     if(bitfield & 32) s+=4;
 369     if(bitfield & 64) s+=4;
 370     if(bitfield & 256) s+=4;
 371     if(bitfield & 512) s+=1;
 372     if(bitfield & 1024) s+=4;
 373     if(bitfield & 2048) s+=4;
 374     if(bitfield & 4096) { // Version 2 or later
 375       s+=2; // for bitfield 2
 376       unsigned int bitfield2 = *(int*)(ptr+2);
 377       if(bitfield & 2) s+=2;
 378       if(bitfield & 4) s+=2;
 379       if(bitfield2 & 1) s+= 4;
 380       if(bitfield2 & 2) s+= 4;
 381       if(bitfield2 & 4) s+= 4;
 382       if(bitfield & 32768) s+=(byte)ptr[4]+1;
 383       //OUT_P_I_LN("LenStr:",(int)ptr[4]);
 384       //OUT_P_I_LN("LenBinV2:",s);
 385     } else {
 386       if(bitfield & 2) s+=1;
 387       if(bitfield & 4) s+=1;
 388       if(bitfield & 32768) s+=16;
 389     }
 390     return s;
 391  }
 392  
 393  extern "C" void __cxa_pure_virtual() { }
 394  
 395  SerialOutput::SerialOutput() {
 396  }
 397  #ifdef COMPAT_PRE1
 398  void 
 399  #else
 400  size_t
 401  #endif
 402  SerialOutput::write(uint8_t value) {
 403    RFSERIAL.write(value);
 404  #ifndef COMPAT_PRE1
 405    return 1;
 406  #endif
 407  }
 408  void SerialOutput::printFloat(double number, uint8_t digits) 
 409  { 
 410    if (isnan(number)) {
 411  	print_P(PSTR("NAN"));
 412      return;
 413    }
 414  
 415    if (isinf(number)) {
 416  	print_P(PSTR("INF"));
 417      return;
 418    }
 419    
 420    // Handle negative numbers
 421    if (number < 0.0)
 422    {
 423       write('-');
 424       number = -number;
 425    }
 426  
 427    // Round correctly so that print(1.999, 2) prints as "2.00"
 428    double rounding = 0.5;
 429    for (uint8_t i=0; i<digits; ++i)
 430      rounding /= 10.0;
 431    
 432    number += rounding;
 433  
 434    // Extract the integer part of the number and print it
 435    unsigned long int_part = (unsigned long)number;
 436    double remainder = number - (double)int_part;
 437    print(int_part);
 438  
 439    // Print the decimal point, but only if there are digits beyond
 440    if (digits > 0)
 441      write('.'); 
 442  
 443    // Extract digits from the remainder one at a time
 444    while (digits-- > 0)
 445    {
 446      remainder *= 10.0;
 447      int toPrint = int(remainder);
 448      print(toPrint);
 449      remainder -= toPrint; 
 450    } 
 451  }
 452  
 453  /**
 454    Print a string stored in program memory on serial console.
 455    
 456    Example: serial_print_pgm(PSTR("Dummy string"));
 457  */
 458  void SerialOutput::print_P(PGM_P ptr) {
 459    char c;
 460    while ((c=pgm_read_byte(ptr++)) != 0x00) 
 461       write(c);
 462  }
 463  
 464  /**
 465    Print a string stored in program memory on serial console.
 466    
 467    Example: out.println_P(PSTR("Dummy string"));
 468  */
 469  void SerialOutput::println_P(PGM_P ptr) {
 470    print_P(ptr);
 471    println();
 472  }
 473  void SerialOutput::print_long_P(PGM_P ptr,long value) {
 474    print_P(ptr);
 475    print(value);
 476  }
 477  void SerialOutput::print_int_P(PGM_P ptr,int value) {
 478    print_P(ptr);
 479    print(value);
 480  }
 481  
 482  void SerialOutput::print_float_P(PGM_P ptr,float value,uint8_t digits) {
 483    print_P(ptr);
 484    out.printFloat(value,digits);
 485  }
 486  void SerialOutput::println_long_P(PGM_P ptr,long value) {
 487    print_P(ptr);
 488    println(value);
 489  }
 490  void SerialOutput::println_int_P(PGM_P ptr,int value) {
 491    print_P(ptr);
 492    println(value);
 493  }
 494  
 495  void SerialOutput::println_float_P(PGM_P ptr,float value,uint8_t digits) {
 496    print_P(ptr);
 497    printFloat(value,digits);
 498    println();
 499  }
 500  void SerialOutput::print_error_P(PGM_P ptr,bool newline) {
 501    OUT_P("error:");
 502    print_P(ptr);
 503    if(newline)
 504      println();
 505  }
 506  /** \brief request resend of the expected line.
 507  */
 508  void gcode_resend() {
 509    RFSERIAL.flush();
 510    gcode_wpos=0;
 511    if(gcode_binary)
 512      gcode_wait_resend = 30;
 513    else
 514      gcode_wait_resend = 14;
 515    OUT_LN;
 516    OUT_P_L_LN("Resend:",gcode_lastN+1);
 517    OUT_P_LN("ok");
 518  }
 519  void emergencyStop() {
 520  #if defined(KILL_METHOD) && KILL_METHOD==1
 521    resetFunc();
 522  #else
 523       cli(); // Don't allow interrupts to do their work
 524       kill(false);
 525       manage_temperatures();
 526       pwm_pos[0] = pwm_pos[1] = pwm_pos[2] = pwm_pos[3]=0;
 527  #if EXT0_HEATER_PIN>-1
 528      WRITE(EXT0_HEATER_PIN,0);
 529  #endif
 530  #if defined(EXT1_HEATER_PIN) && EXT1_HEATER_PIN>-1
 531      WRITE(EXT1_HEATER_PIN,0);
 532  #endif
 533  #if defined(EXT2_HEATER_PIN) && EXT2_HEATER_PIN>-1
 534      WRITE(EXT2_HEATER_PIN,0);
 535  #endif
 536  #if FAN_PIN>-1
 537      WRITE(FAN_PIN,0);
 538  #endif
 539       while(1) {}
 540  #endif
 541  }
 542  /**
 543    Check if result is plausible. If it is, an ok is send and the command is stored in queue.
 544    If not, a resend and ok is send.
 545  */
 546  void gcode_checkinsert(GCode *act) {
 547    if(GCODE_HAS_M(act)) {
 548     if(act->M==110) { // Reset line number
 549       gcode_lastN = gcode_actN;
 550       OUT_P_LN("ok");
 551       return;
 552     }
 553     if(act->M==112) { // Emergency kill - freeze printer
 554       emergencyStop();
 555     }
 556    }
 557    if(GCODE_HAS_N(act)) {
 558      if((((gcode_lastN+1) & 0xffff)!=(gcode_actN&0xffff))) {
 559        if(gcode_wait_resend<0) { // after a resend, we have to skip the garbage in buffers, no message for this
 560          if(DEBUG_ERRORS) {
 561             OUT_P_L("Error: expected line ",gcode_lastN+1); 
 562             OUT_P_L_LN(" got ",gcode_actN);
 563          }
 564          gcode_resend(); // Line missing, force resend
 565        } else {
 566          --gcode_wait_resend;
 567          gcode_wpos = 0;
 568          OUT_P_L_LN("skip ",gcode_actN);
 569          OUT_P_LN("ok");
 570        }
 571        return;
 572      }
 573      gcode_lastN = gcode_actN;
 574    }
 575    gcode_windex = (gcode_windex+1) % GCODE_BUFFER_SIZE;
 576    gcode_buflen++;
 577  #ifdef ACK_WITH_LINENUMBER  
 578    OUT_P_L_LN("ok ",gcode_actN);
 579  #else
 580    OUT_P_LN("ok");
 581  #endif
 582    gcode_last_binary = gcode_binary;
 583    gcode_wait_resend = -1; // everything is ok.
 584  #ifndef ECHO_ON_EXECUTE
 585    if(DEBUG_ECHO) {
 586        OUT_P("Echo:");
 587        gcode_print_command(act);
 588        out.println();
 589    }
 590  #endif
 591  }
 592  void gcode_silent_insert() {
 593    gcode_windex = (gcode_windex+1) % GCODE_BUFFER_SIZE;
 594    gcode_buflen++;
 595  #ifndef ECHO_ON_EXECUTE
 596    if(DEBUG_ECHO) {
 597        out.print_P(PSTR("Echo:"));
 598        gcode_print_command(act);
 599        out.println();
 600    }
 601  #endif
 602  }
 603  /**
 604    Get the next buffered command. Returns 0 if no more commands are buffered. For each
 605    returned command, the gcode_command_finished() function must be called.
 606  */
 607  GCode *gcode_next_command() {
 608    if(gcode_buflen==0) return 0; // No more data
 609    byte idx = gcode_rindex;
 610    gcode_rindex = (idx+1) % GCODE_BUFFER_SIZE;
 611    return &gcode_buffer[idx];
 612  }
 613  /** \brief Removes the last returned command from cache.
 614  
 615  */
 616  void gcode_command_finished(GCode *code) {
 617    if(!gcode_buflen) return; // Should not happen, but safety first
 618  #ifdef ECHO_ON_EXECUTE
 619    if(DEBUG_ECHO) {
 620        OUT_P("Echo:");
 621        gcode_print_command(code);
 622        out.println();
 623    }
 624  #endif
 625    gcode_buflen--;
 626  }
 627  
 628  /** \brief Execute commands in progmem stored string. Multiple commands are seperated by \n */
 629  void gcode_execute_PString(PGM_P cmd) {
 630    char buf[80];
 631    byte buflen;
 632    char c;
 633    GCode code;
 634    do {
 635      // Wait for a free place in command buffer
 636      // Scan next command from string
 637      byte comment=0; 
 638      buflen = 0;   
 639      do {
 640        c = pgm_read_byte(cmd++);
 641        if(c == 0 || c == '\n') break;
 642        if(c == ';') comment = 1;
 643        if(comment) continue;
 644        buf[buflen++] = c;
 645      } while(buflen<79);
 646      if(buflen==0) { // empty line ignore
 647        continue;
 648      }
 649      buf[buflen]=0;
 650      // Send command into command buffer
 651      if(gcode_parse_ascii(&code,(char *)buf) && (code.params & 518)) { // Success
 652        process_command(&code,false);
 653        defaultLoopActions();
 654      }
 655    } while(c);
 656  }
 657  /** \brief Read from serial console or sdcard.
 658  
 659  This function is the main function to read the commands from serial console or from sdcard.
 660  It must be called frequently to empty the incoming buffer.
 661  */
 662  void gcode_read_serial() {
 663    if(gcode_wait_all_parsed && gcode_buflen) return;
 664    gcode_wait_all_parsed=false;
 665    GCode *act;
 666    unsigned long time = millis();
 667    if(gcode_buflen>=GCODE_BUFFER_SIZE) return; // all buffers full
 668    if(RFSERIAL.available()==0) {
 669      if((gcode_wait_resend>=0 || gcode_wpos>0) && time-gcode_lastdata>200) {
 670        gcode_resend(); // Something is wrong, a started line was not continued in the last second 
 671        gcode_lastdata = time;
 672      }
 673  #ifdef WAITING_IDENTIFIER
 674      else if(gcode_buflen == 0 && time-gcode_lastdata>1000) { // Don't do it if buffer is not empty. It may be a slow executing command.
 675        OUT_P_LN(WAITING_IDENTIFIER); // Unblock communication in case the last ok was not received correct.
 676        gcode_lastdata = time;
 677      }   
 678  #endif
 679    }
 680    while(RFSERIAL.available() > 0 && gcode_wpos < MAX_CMD_SIZE) {  // consume data until no data or buffer full
 681      gcode_lastdata = millis();
 682      gcode_transbuffer[gcode_wpos++] = RFSERIAL.read();
 683      // first lets detect, if we got an old type ascii command
 684      if(gcode_wpos==1) {
 685        if(gcode_wait_resend>=0 && gcode_last_binary) {
 686           if(!gcode_transbuffer[0]) {gcode_wait_resend--;} // Skip 30 zeros to get in sync
 687           else gcode_wait_resend = 30;
 688           gcode_wpos = 0;
 689           continue;
 690        }
 691        if(!gcode_transbuffer[0]) {gcode_wpos = 0;continue;}
 692        gcode_binary = (gcode_transbuffer[0] & 128)!=0;
 693      }
 694      if(gcode_binary) {
 695        if(gcode_wpos < 2 ) continue;
 696        if(gcode_wpos == 5) gcode_binary_size = gcode_comp_binary_size((char*)gcode_transbuffer);
 697        if(gcode_wpos==gcode_binary_size) {
 698          act = &gcode_buffer[gcode_windex];
 699          if(gcode_parse_binary(act,gcode_transbuffer)) { // Success
 700            gcode_checkinsert(act);
 701          } else {
 702            gcode_resend();
 703          }
 704          gcode_wpos = 0;
 705          return;
 706        }
 707      } else { // Ascii command
 708        char ch = gcode_transbuffer[gcode_wpos-1];
 709        if(ch == '\n' || ch == '\r' || ch == ':' || gcode_wpos >= (MAX_CMD_SIZE - 1) ) {// complete line read
 710          gcode_transbuffer[gcode_wpos]=0;
 711          gcode_comment = false;
 712          if(gcode_wpos==1) { // empty line ignore
 713            gcode_wpos = 0;
 714            continue;
 715          }
 716          act = &gcode_buffer[gcode_windex];
 717          if(gcode_parse_ascii(act,(char *)gcode_transbuffer)) { // Success
 718            gcode_checkinsert(act);
 719          } else {
 720            gcode_resend();
 721          }
 722          gcode_wpos = 0;
 723          return;
 724        } else {
 725          if(ch == ';') gcode_comment = true; // ignore new data until lineend
 726          if(gcode_comment) gcode_wpos--;
 727        }           
 728      }
 729    }
 730    #if SDSUPPORT
 731    if(!sd.sdmode || gcode_wpos!=0) { // not reading or incoming serial command
 732      return;
 733    }
 734    while( sd.filesize > sd.sdpos && gcode_wpos < MAX_CMD_SIZE) {  // consume data until no data or buffer full
 735      gcode_lastdata = millis();
 736      int n = sd.file.read();
 737      if(n==-1) {
 738        OUT_P_LN("SD read error");
 739        break;
 740      }
 741      sd.sdpos++; // = file.curPosition();
 742      gcode_transbuffer[gcode_wpos++] = (byte)n;
 743    
 744      // first lets detect, if we got an old type ascii command
 745      if(gcode_wpos==1) {
 746        gcode_binary = (gcode_transbuffer[0] & 128)!=0;
 747      }
 748      if(gcode_binary) {
 749        if(gcode_wpos < 2 ) continue;
 750        if(gcode_wpos == 5) gcode_binary_size = gcode_comp_binary_size((char*)gcode_transbuffer);
 751        if(gcode_wpos==gcode_binary_size) {
 752          act = &gcode_buffer[gcode_windex];
 753          if(gcode_parse_binary(act,gcode_transbuffer)) { // Success
 754            gcode_silent_insert();
 755          } 
 756          gcode_wpos = 0;
 757          return;
 758        }
 759      } else {
 760        char ch = gcode_transbuffer[gcode_wpos-1];
 761        if(ch == '\n' || ch == '\r' || ch == ':' || gcode_wpos >= (MAX_CMD_SIZE - 1) ) {// complete line read
 762          gcode_transbuffer[gcode_wpos]=0;
 763          gcode_comment = false;
 764          if(gcode_wpos==1) { // empty line ignore
 765            gcode_wpos = 0;
 766            continue;
 767          }
 768          act = &gcode_buffer[gcode_windex];
 769          if(gcode_parse_ascii(act,(char *)gcode_transbuffer)) { // Success
 770            gcode_silent_insert();
 771          }
 772          gcode_wpos = 0;
 773          return;
 774        } else {
 775          if(ch == ';') gcode_comment = true; // ignore new data until lineend
 776          if(gcode_comment) gcode_wpos--;
 777        }
 778      }
 779    }
 780    sd.sdmode = false;
 781    OUT_P_LN("Done printing file");
 782    /*OUT_P_L("Printed bytes:",sd.sdpos);
 783    OUT_P_L_LN(" of ",sd.filesize);
 784    OUT_P_I_LN("WPOS:",gcode_wpos);*/
 785    gcode_wpos = 0;
 786  #endif
 787  }
 788  
 789  /**
 790    Converts a binary bytefield containing one GCode line into a GCode structure.
 791    Returns true if checksum was correct.
 792  */
 793  bool gcode_parse_binary(GCode *code,byte *buffer) {
 794     unsigned int sum1=0,sum2=0; // for fletcher-16 checksum
 795     // first do fletcher-16 checksum tests see
 796     // http://en.wikipedia.org/wiki/Fletcher's_checksum
 797     byte i=0;
 798     byte *p = buffer;
 799     byte len = gcode_binary_size-2;
 800     while (len) {
 801       byte tlen = len > 21 ? 21 : len;
 802       len -= tlen;
 803       do {
 804          sum1 += *p++;
 805          if(sum1>=255) sum1-=255;
 806          sum2 += sum1;
 807          if(sum2>=255) sum2-=255;
 808       } while (--tlen);
 809     }
 810     sum1 -= *p++;
 811     sum2 -= *p;
 812     if(sum1 | sum2) {
 813        if(DEBUG_ERRORS) {
 814          OUT_P_LN("Error:Binary cmd wrong checksum.");
 815        }
 816       return false;
 817     }
 818     p = buffer;
 819     code->params = *(unsigned int *)p;p+=2;
 820     byte textlen=16;
 821     if(GCODE_IS_V2(code)) {
 822       code->params2 = *(unsigned int *)p;p+=2;
 823       if(GCODE_HAS_STRING(code)) 
 824         textlen = *p++;
 825     } else code->params2 = 0;
 826     if(code->params & 1) {gcode_actN=code->N=*(unsigned int *)p;p+=2;}
 827     if(GCODE_IS_V2(code)) { // Read G,M as 16 bit value
 828       if(code->params & 2) {code->M=*(unsigned int *)p;p+=2;}
 829       if(code->params & 4) {code->G=*(unsigned int *)p;p+=2;}
 830     } else {
 831       if(code->params & 2) {code->M=*p++;}
 832       if(code->params & 4) {code->G=*p++;}
 833     }
 834     //if(code->params & 8) {memcpy(&code->X,p,4);p+=4;}
 835     if(code->params & 8) {code->X=*(float *)p;p+=4;}
 836     if(code->params & 16) {code->Y=*(float *)p;p+=4;}
 837     if(code->params & 32) {code->Z =*(float *)p;p+=4;}
 838     if(code->params & 64) {code->E=*(float *)p;p+=4;}
 839     if(code->params & 256) {code->F=*(float *)p;p+=4;}
 840     if(code->params & 512) {code->T=*p++;}
 841     if(code->params & 1024) {code->S=*(long int*)p;p+=4;}
 842     if(code->params & 2048) {code->P=*(long int*)p;p+=4;}
 843     if(GCODE_HAS_I(code)) {code->I=*(float *)p;p+=4;}
 844     if(GCODE_HAS_J(code)) {code->J=*(float *)p;p+=4;}
 845     if(GCODE_HAS_R(code)) {code->R=*(float *)p;p+=4;}
 846     if(GCODE_HAS_STRING(code)) { // set text pointer to string
 847       code->text = (char*)p;
 848       code->text[textlen] = 0; // Terminate string overwriting checksum
 849       gcode_wait_all_parsed=true; // Don't destroy string until executed
 850     }
 851     return true; 
 852  }
 853  inline float gcode_value(char *s) { return (strtod(s, NULL)); }
 854  inline long gcode_value_long(char *s) { return (strtol(s, NULL, 10)); }
 855  
 856  /**
 857    Converts a ascii GCode line into a GCode structure.
 858  */
 859  bool gcode_parse_ascii(GCode *code,char *line) {
 860    bool has_checksum = false;
 861    char *pos;
 862    code->params = 0;
 863    code->params2 = 0;
 864    if((pos = strchr(line,'N'))!=0) { // Line number detected
 865       gcode_actN = gcode_value_long(++pos);
 866       code->params |=1;
 867       code->N = gcode_actN & 0xffff;
 868    }
 869    if((pos = strchr(line,'M'))!=0) { // M command
 870       code->M = gcode_value_long(++pos) & 0xffff;
 871       code->params |= 2;
 872       if(code->M>255) code->params |= 4096;
 873    }
 874    if(GCODE_HAS_M(code) && (code->M == 23 || code->M == 28 || code->M == 29 || code->M == 30 || code->M == 32 || code->M == 117)) {
 875       // after M command we got a filename for sd card management
 876       char *sp = line;
 877       while(*sp!='M') sp++; // Search M command
 878       while(*sp!=' ') sp++; // search next whitespace
 879       while(*sp==' ') sp++; // skip leading whitespaces
 880       //char *wp = code->text;
 881       code->text = sp;
 882       while(*sp) {
 883          if(code->M != 117 && (*sp==' ' || *sp=='*')) break; // end of filename reached
 884          sp++;
 885          //*wp++ = *sp++;
 886       }
 887       //*wp = 0; // ensure ending 0 
 888       *sp = 0; // Removes checksum, but we don't care. Could also be part of the string.
 889       gcode_wait_all_parsed = true; // don't risk string be deleted
 890       code->params |= 32768;
 891    } else {
 892      if((pos = strchr(line,'G'))!=0) { // G command
 893         code->G = gcode_value_long(++pos) & 0xffff;
 894         code->params |= 4;
 895         if(code->G>255) code->params |= 4096;
 896      }
 897      if((pos = strchr(line,'X'))!=0) { 
 898         code->X = gcode_value(++pos);
 899         code->params |= 8;
 900      }
 901      if((pos = strchr(line,'Y'))!=0) { 
 902         code->Y = gcode_value(++pos);
 903         code->params |= 16;
 904      }
 905      if((pos = strchr(line,'Z'))!=0) { 
 906         code->Z = gcode_value(++pos);
 907         code->params |= 32;
 908      }
 909      if((pos = strchr(line,'E'))!=0) { 
 910         code->E = gcode_value(++pos);
 911         code->params |= 64;
 912      }
 913      if((pos = strchr(line,'F'))!=0) { 
 914         code->F = gcode_value(++pos);
 915         code->params |= 256;
 916      }
 917      if((pos = strchr(line,'T'))!=0) { // M command
 918         code->T = gcode_value_long(++pos) & 0xff;
 919         code->params |= 512;
 920      }
 921      if((pos = strchr(line,'S'))!=0) { // M command
 922         code->S = gcode_value_long(++pos);
 923         code->params |= 1024;
 924      }
 925      if((pos = strchr(line,'P'))!=0) { // M command
 926         code->P = gcode_value_long(++pos);
 927         code->params |= 2048;
 928      }
 929      if((pos = strchr(line,'I'))!=0) { 
 930         code->I = gcode_value(++pos);
 931         code->params2 |= 1;
 932         code->params |= 4096; // Needs V2 for saving
 933      }
 934      if((pos = strchr(line,'J'))!=0) { 
 935         code->J = gcode_value(++pos);
 936         code->params2 |= 2;
 937         code->params |= 4096; // Needs V2 for saving
 938      }
 939      if((pos = strchr(line,'R'))!=0) { 
 940         code->R = gcode_value(++pos);
 941         code->params2 |= 4;
 942         code->params |= 4096; // Needs V2 for saving
 943      }
 944    }
 945    if((pos = strchr(line,'*'))!=0) { // checksum
 946      byte checksum_given = gcode_value_long(pos+1);
 947      byte checksum = 0;
 948      while(line!=pos) checksum ^= *line++;
 949      if(checksum!=checksum_given) {
 950        if(DEBUG_ERRORS) {
 951          out.println_int_P(PSTR("Error: Wrong checksum "),(int)checksum);
 952        }
 953        return false; // mismatch
 954      }
 955    }
 956    return true;
 957  }
 958  
 959  /** \brief Print command on serial console */
 960  void gcode_print_command(GCode *code) {
 961    if(GCODE_HAS_M(code)) {
 962      out.print('M');
 963      out.print((int)code->M);
 964      out.print(' ');
 965    }
 966    if(GCODE_HAS_G(code)) {
 967      out.print('G');
 968      out.print((int)code->G);
 969      out.print(' ');
 970    }
 971    if(GCODE_HAS_T(code)) {
 972      out.print('T');
 973      out.print((int)code->T);
 974      out.print(' ');
 975    }
 976    if(GCODE_HAS_X(code)) {
 977      out.print_float_P(PSTR(" X"),code->X);
 978    }
 979    if(GCODE_HAS_Y(code)) {
 980      out.print_float_P(PSTR(" Y"),code->Y);
 981    }
 982    if(GCODE_HAS_Z(code)) {
 983      out.print_float_P(PSTR(" Z"),code->Z);
 984    }
 985    if(GCODE_HAS_E(code)) {
 986      out.print_float_P(PSTR(" E"),code->E,4);
 987    }
 988    if(GCODE_HAS_F(code)) {
 989      out.print_float_P(PSTR(" F"),code->F);
 990    }
 991    if(GCODE_HAS_S(code)) {
 992      out.print_long_P(PSTR(" S"),code->S);
 993    }
 994    if(GCODE_HAS_P(code)) {
 995      out.print_long_P(PSTR(" P"),code->P);
 996    }
 997    if(GCODE_HAS_I(code)) {
 998      out.print_float_P(PSTR(" I"),code->I);
 999    }
1000    if(GCODE_HAS_J(code)) {
1001      out.print_float_P(PSTR(" J"),code->J);
1002    }
1003    if(GCODE_HAS_R(code)) {
1004      out.print_float_P(PSTR(" R"),code->R);
1005    }
1006    if(GCODE_HAS_STRING(code)) {
1007      out.print(' ');
1008      out.print(code->text);
1009    }  
1010  }