Merge remote-tracking branch 'upstream/edge' into upstreamedge
[clinton/Smoothieware.git] / src / libs / utils.cpp
index de174c6..b3e60fa 100644 (file)
 #include <string>
 #include <cstring>
 #include <stdio.h>
-using std::string;
+#include <cstdlib>
+
+#include "mbed.h"
 
-volatile bool _isr_context = false;
+using std::string;
 
 uint16_t get_checksum(const string &to_check)
 {
@@ -131,7 +133,7 @@ string shift_parameter( string &parameters )
 }
 
 // Separate command from arguments
-string get_arguments( string possible_command )
+string get_arguments( const string& possible_command )
 {
     size_t beginning = possible_command.find_first_of(" ");
     if( beginning == string::npos ) {
@@ -198,3 +200,78 @@ string absolute_from_relative( string path )
 
     return cwd + '/' + path;
 }
+
+// FIXME this does not handle empty strings correctly
+//split a string on a delimiter, return a vector of the split tokens
+vector<string> split(const char *str, char c)
+{
+    vector<string> result;
+
+    do {
+        const char *begin = str;
+
+        while(*str != c && *str)
+            str++;
+
+        result.push_back(string(begin, str));
+    } while (0 != *str++);
+
+    return result;
+}
+
+// FIXME this does not handle empty strings correctly
+// parse a number list "1.1,2.2,3.3" and return the numbers in a vector of floats
+vector<float> parse_number_list(const char *str)
+{
+    vector<string> l= split(str, ',');
+    vector<float> r;
+    for(auto& s : l){
+        float x = strtof(s.c_str(), nullptr);
+        r.push_back(x);
+    }
+    return r;
+}
+
+vector<uint32_t> parse_number_list(const char *str, uint8_t radix)
+{
+    vector<string> l= split(str, ',');
+    vector<uint32_t> r;
+    for(auto& s : l){
+        uint32_t x = strtol(s.c_str(), nullptr, radix);
+        r.push_back(x);
+    }
+    return r;
+}
+
+int append_parameters(char *buf, std::vector<std::pair<char,float>> params, size_t bufsize)
+{
+    size_t n= 0;
+    for(auto &i : params) {
+        if(n >= bufsize) break;
+        buf[n++]= i.first;
+        n += snprintf(&buf[n], bufsize-n, "%1.4f ", i.second);
+    }
+    return n;
+}
+
+string wcs2gcode(int wcs) {
+    string str= "G5";
+    str.append(1, std::min(wcs, 5) + '4');
+    if(wcs >= 6) {
+        str.append(".").append(1, '1' + (wcs - 6));
+    }
+    return str;
+}
+
+void safe_delay_ms(uint32_t delay)
+{
+    safe_delay_us(delay*1000);
+}
+
+void safe_delay_us(uint32_t dus)
+{
+    uint32_t start = us_ticker_read();
+    while ((us_ticker_read() - start) < dus) {
+        THEKERNEL->call_event(ON_IDLE);
+    }
+}