forked from Duet3D/RepRapFirmware
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathWebserver.cpp
More file actions
1446 lines (1328 loc) · 39.3 KB
/
Copy pathWebserver.cpp
File metadata and controls
1446 lines (1328 loc) · 39.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/****************************************************************************************************
RepRapFirmware - Webserver
This class serves a single-page web applications to the attached network. This page forms the user's
interface with the RepRap machine. This software interprests returned values from the page and uses it
to Generate G Codes, which it sends to the RepRap. It also collects values from the RepRap like
temperature and uses those to construct the web page.
The page itself - reprap.htm - uses Knockout.js and Jquery.js. See:
http://knockoutjs.com/
http://jquery.com/
-----------------------------------------------------------------------------------------------------
Version 0.2
10 May 2013
Adrian Bowyer
RepRap Professional Ltd
http://reprappro.com
Licence: GPL
-----------------------------------------------------------------------------------------------------
The supported requests are GET requests for files (for which the root is the www directory on the
SD card), and the following. These all start with "/rr_". Ordinary files used for the web interface
must not have names starting "/rr_" or they will not be found.
rr_connect Sent by the web interface software to establish an initial connection, indicating that
any state variables relating to the web interface (e.g. file upload in progress) should
be reset. Returns the same response as rr_status.
rr_poll Returns the old-style status response. Not recommended because all the position,
extruder position and temperature variables are returned in a single array, which means
that the web interface has to know in advance how many heaters and extruders there are.
Provided only for backwards compatibility with older web interface software. Likely to
be removed in a future version.
rr_status New-style status response, in which temperatures, axis positions and extruder positions
are returned in separate variables. Another difference is that extruder positions are
returned as absolute positions instead of relative to the previous gcode.
rr_files?dir=xxx
Returns a listing of the filenames in the /gcode directory of the SD card. 'dir' is a
directory path relative to the root of the SD card. If the 'dir' variable is not present,
it defaults to the /gcode directory.
rr_axes Returns the axis lengths.
rr_name Returns the machine name in variable myname.
rr_password?password=xxx
Returns variable "password" having value "right" if xxx is the correct password and
"wrong" otherwise.
rr_upload_begin?name=xxx
Indicates that we wish to upload the specified file. xxx is the filename relative
to the root of the SD card. The directory component of the filename must already
exist. Returns variables ubuff (= max upload data we can accept in the next message)
and err (= 0 if the file was created successfully, nonzero if there was an error).
rr_upload_data?data=xxx
Provides a data block for the file upload. Returns the samwe variables as rr_upload_begin,
except that err is only zero if the file was successfully created and there has not been
a file write error yet. This response is returned before attempting to write this data block.
rr_upload_end
Indicates that we have finished sending upload data. The server closes the file and reports
the overall status in err. It may also return ubuff again.
rr_upload_cancel
Indicates that the user wishes to cancel the current upload. Returns err and ubuff.
rr_delete?name=xxx
Delete file xxx. Returns err (zero if successful).
****************************************************************************************************/
#include "RepRapFirmware.h"
//***************************************************************************************************
static const char* overflowResponse = "overflow";
static const char* badEscapeResponse = "bad escape";
// Feeding G Codes to the GCodes class
bool Webserver::GCodeAvailable()
{
return gcodeReadIndex != gcodeWriteIndex;
}
char Webserver::ReadGCode()
{
char c;
if (gcodeReadIndex == gcodeWriteIndex)
{
c = 0;
}
else
{
c = gcodeBuffer[gcodeReadIndex];
gcodeReadIndex = (gcodeReadIndex + 1u) % gcodeBufLength;
}
return c;
}
// Process a received string of gcodes
void Webserver::LoadGcodeBuffer(const char* gc)
{
char gcodeTempBuf[GCODE_LENGTH];
uint16_t gtp = 0;
bool inComment = false;
for (;;)
{
char c = *gc++;
if (c == 0)
{
gcodeTempBuf[gtp] = 0;
ProcessGcode(gcodeTempBuf);
return;
}
if (c == '\n')
{
gcodeTempBuf[gtp] = 0;
ProcessGcode(gcodeTempBuf);
gtp = 0;
inComment = false;
}
else
{
if (c == ';')
{
inComment = true;
}
if (gtp == ARRAY_UPB(gcodeTempBuf))
{
// gcode is too long, we haven't room for another character and a null
if (c != ' ' && !inComment)
{
platform->Message(HOST_MESSAGE, "Webserver: GCode local buffer overflow.\n");
HandleReply("Webserver: GCode local buffer overflow", true);
return;
}
// else we're either in a comment or the current character is a space.
// If we're in a comment, we'll silently truncate it.
// If the current character is a space, we'll wait until we see a non-comment character before reporting an error,
// in case the next character is end-of-line or the start of a comment.
}
else
{
gcodeTempBuf[gtp++] = c;
}
}
}
}
// Process a received string of gcodes
void Webserver::StoreGcodeData(const char* data, size_t len)
{
if (len > GetGcodeBufferSpace())
{
platform->Message(HOST_MESSAGE, "Webserver: GCode buffer overflow.\n");
HandleReply("Webserver: GCode buffer overflow", true);
}
else
{
size_t remaining = gcodeBufLength - gcodeWriteIndex;
if (len <= remaining)
{
memcpy(gcodeBuffer + gcodeWriteIndex, data, len);
}
else
{
memcpy(gcodeBuffer + gcodeWriteIndex, data, remaining);
memcpy(gcodeBuffer, data + remaining, len - remaining);
}
gcodeWriteIndex = (gcodeWriteIndex + len) % gcodeBufLength;
}
}
// Process a null-terminated gcode
// We intercept four G/M Codes so we can deal with file manipulation and emergencies. That
// way things don't get out of sync, and - as a file name can contain
// a valid G code (!) - confusion is avoided.
void Webserver::ProcessGcode(const char* gc)
{
if (StringStartsWith(gc, "M30 ")) // delete SD card file
{
reprap.GetGCodes()->DeleteFile(&gc[4]);
}
else if (StringStartsWith(gc, "M23 ")) // select SD card file to print next
{
reprap.GetGCodes()->QueueFileToPrint(&gc[4]);
}
else if (StringStartsWith(gc, "M112") && !isdigit(gc[4])) // emergency stop
{
reprap.EmergencyStop();
gcodeReadIndex = gcodeWriteIndex; // clear the buffer
reprap.GetGCodes()->Reset();
}
else if (StringStartsWith(gc, "M503") && !isdigit(gc[4])) // echo config.g file
{
FileStore *configFile = platform->GetFileStore(platform->GetSysDir(), platform->GetConfigFile(), false);
if (configFile == NULL)
{
HandleReply("Configuration file not found", true);
}
else
{
char c;
size_t i = 0;
while (i < ARRAY_UPB(gcodeReply) && configFile->Read(c))
{
gcodeReply[i++] = c;
}
configFile->Close();
gcodeReply[i] = 0;
++seq;
}
}
else if (StringStartsWith(gc, "M25") && !isDigit(gc[3])) // pause SD card print
{
reprap.GetGCodes()->PauseSDPrint();
}
else
{
StoreGcodeData(gc, strlen(gc) + 1);
}
}
//********************************************************************************************
// Communications with the client
//--------------------------------------------------------------------------------------------
// Output to the client
// Start sending a file or a JSON response.
void Webserver::SendFile(const char* nameOfFileToSend)
{
if (StringEquals(nameOfFileToSend, "/"))
{
nameOfFileToSend = INDEX_PAGE;
}
FileStore *fileToSend = platform->GetFileStore(platform->GetWebDir(), nameOfFileToSend, false);
if (fileToSend == NULL)
{
nameOfFileToSend = FOUR04_FILE;
fileToSend = platform->GetFileStore(platform->GetWebDir(), nameOfFileToSend, false);
if (fileToSend == NULL)
{
RejectMessage("not found", 404);
return;
}
}
Network *net = reprap.GetNetwork();
RequestState *req = net->GetRequest(NULL);
req->Write("HTTP/1.1 200 OK\n");
const char* contentType;
bool zip = false;
if (StringEndsWith(nameOfFileToSend, ".png"))
{
contentType = "image/png";
}
else if (StringEndsWith(nameOfFileToSend, ".ico"))
{
contentType = "image/x-icon";
}
else if (StringEndsWith(nameOfFileToSend, ".js"))
{
contentType = "application/javascript";
}
else if (StringEndsWith(nameOfFileToSend, ".css"))
{
contentType = "text/css";
}
else if (StringEndsWith(nameOfFileToSend, ".htm") || StringEndsWith(nameOfFileToSend, ".html"))
{
contentType = "text/html";
}
else if (StringEndsWith(nameOfFileToSend, ".zip"))
{
contentType = "application/zip";
zip = true;
}
else
{
contentType = "application/octet-stream";
}
req->Printf("Content-Type: %s\n", contentType);
if (zip && fileToSend != NULL)
{
req->Write("Content-Encoding: gzip\n");
req->Printf("Content-Length: %lu", fileToSend->Length());
}
req->Write("Connection: close\n\n");
net->SendAndClose(fileToSend);
}
void Webserver::SendJsonResponse(const char* command)
{
Network *net = reprap.GetNetwork();
RequestState *req = net->GetRequest(NULL);
bool keepOpen = false;
bool mayKeepOpen;
if (numQualKeys == 0)
{
mayKeepOpen = GetJsonResponse(command, "", "", 0);
}
else
{
mayKeepOpen = GetJsonResponse(command, qualifiers[0].key, qualifiers[0].value, qualifiers[1].key - qualifiers[0].value - 1);
}
if (mayKeepOpen)
{
// Check that the browser wants to persist the connection too
for (size_t i = 0; i < numHeaderKeys; ++i)
{
if (StringEquals(headers[i].key, "Connection"))
{
// Comment out the following line to disable persistent connections
keepOpen = StringEquals(headers[i].value, "keep-alive");
break;
}
}
}
req->Write("HTTP/1.1 200 OK\n");
req->Write("Content-Type: application/json\n");
req->Printf("Content-Length: %u\n", strlen(jsonResponse));
req->Printf("Connection: %s\n\n", keepOpen ? "keep-alive" : "close");
req->Write(jsonResponse);
net->SendAndClose(NULL, keepOpen);
}
//----------------------------------------------------------------------------------------------------
// Input from the client
void Webserver::CheckPassword(const char *pw)
{
gotPassword = StringEquals(pw, password);
}
void Webserver::JsonReport(bool ok, const char* request)
{
if (ok)
{
jsonResponse[ARRAY_UPB(jsonResponse)] = 0;
if (reprap.Debug())
{
platform->Message(HOST_MESSAGE, "JSON response: ");
platform->Message(HOST_MESSAGE, jsonResponse);
platform->Message(HOST_MESSAGE, " queued\n");
}
}
else
{
jsonResponse[0] = 0;
platform->Message(HOST_MESSAGE, "KnockOut request: ");
platform->Message(HOST_MESSAGE, request);
platform->Message(HOST_MESSAGE, " not recognised\n");
}
}
// Get the Json response for this command.
// 'value' is null-terminated, but we also pass its length in case it contains embedded nulls, which matter when uploading files.
bool Webserver::GetJsonResponse(const char* request, const char* key, const char* value, size_t valueLength)
{
bool found = true; // assume success
bool keepOpen = false; // assume we don't want to persist the connection
if (StringEquals(request, "status")) // new style status request
{
GetStatusResponse(1);
}
else if (StringEquals(request, "poll")) // old style status request
{
GetStatusResponse(0);
}
else if (StringEquals(request, "gcode") && StringEquals(key, "gcode"))
{
LoadGcodeBuffer(value);
snprintf(jsonResponse, ARRAY_UPB(jsonResponse), "{\"buff\":%u}", GetReportedGcodeBufferSpace());
}
else if (StringEquals(request, "upload_begin") && StringEquals(key, "name"))
{
CancelUpload();
FileStore *f = platform->GetFileStore("0:/", value, true);
if (f != NULL)
{
fileBeingUploaded.Set(f);
uploadState = uploadOK;
}
else
{
uploadState = uploadError;
}
GetJsonUploadResponse();
}
else if (StringEquals(request, "upload_data") && StringEquals(key, "data"))
{
if (uploadState == uploadOK)
{
uploadPointer = value;
uploadLength = valueLength;
}
GetJsonUploadResponse();
keepOpen = true;
}
else if (StringEquals(request, "upload_end") && StringEquals(key, "size"))
{
// Write the remaining data
if (uploadLength != 0)
{
if (!fileBeingUploaded.Write(uploadPointer, uploadLength))
{
uploadState = uploadError;
}
}
uploadPointer = NULL;
uploadLength = 0;
if (uploadState == uploadOK && !fileBeingUploaded.Flush())
{
uploadState = uploadError;
}
// Check the file length is as expected
if (uploadState == uploadOK && fileBeingUploaded.Length() != strtoul(value, NULL, 10))
{
uploadState = uploadError;
}
// Close the file
if (!fileBeingUploaded.Close())
{
uploadState = uploadError;
}
GetJsonUploadResponse();
if (uploadState != uploadOK && strlen(filenameBeingUploaded) != 0)
{
platform->GetMassStorage()->Delete("0:/", filenameBeingUploaded);
}
filenameBeingUploaded[0] = 0;
}
else if (StringEquals(request, "upload_cancel"))
{
CancelUpload();
snprintf(jsonResponse, ARRAY_UPB(jsonResponse), "{\"err\":%d}", 0);
}
else if (StringEquals(request, "delete") && StringEquals(key, "name"))
{
bool ok = platform->GetMassStorage()->Delete("0:/", value);
snprintf(jsonResponse, ARRAY_UPB(jsonResponse), "{\"err\":%d}", (ok) ? 0 : 1);
}
else if (StringEquals(request, "files"))
{
const char* dir = (StringEquals(key, "dir")) ? value : platform->GetGCodeDir();
const char* fileList = platform->GetMassStorage()->FileList(dir, false);
snprintf(jsonResponse, ARRAY_UPB(jsonResponse), "{\"files\":[%s]}", fileList);
}
else if (StringEquals(request, "fileinfo") && StringEquals(key, "name"))
{
unsigned long length;
float height, filament, layerHeight;
char generatedBy[50];
bool found = GetFileInfo(value, length, height, filament, layerHeight, generatedBy, ARRAY_SIZE(generatedBy));
if (found)
{
snprintf(jsonResponse, ARRAY_UPB(jsonResponse),
"{\"err\":0,\"size\":%lu,\"height\":%.2f,\"filament\":%.1f,\"layerHeight\":%.2f,\"generatedBy\":\"%s\"}",
length, height, filament, layerHeight, generatedBy);
}
else
{
snprintf(jsonResponse, ARRAY_UPB(jsonResponse), "{\"err\":1}");
}
}
else if (StringEquals(request, "name"))
{
snprintf(jsonResponse, ARRAY_UPB(jsonResponse), "{\"myName\":\"");
size_t j = strlen(jsonResponse);
for (size_t i = 0; i < ARRAY_SIZE(myName) - 1; ++i)
{
char c = myName[i];
if (c < ' ') // if null terminator or bad character
break;
if (c == '"' || c == '\\')
{
// Need to escape the quote-mark or backslash for JSON
jsonResponse[j++] = '\\';
}
jsonResponse[j++] = c;
}
jsonResponse[j++] = '"';
jsonResponse[j++] = '}';
jsonResponse[j] = 0;
}
else if (StringEquals(request, "password") && StringEquals(key, "password"))
{
CheckPassword(value);
snprintf(jsonResponse, ARRAY_UPB(jsonResponse), "{\"password\":\"%s\"}", (gotPassword) ? "right" : "wrong");
}
else if (StringEquals(request, "axes"))
{
strncpy(jsonResponse, "{\"axes\":", ARRAY_UPB(jsonResponse));
char ch = '[';
for (int8_t drive = 0; drive < AXES; drive++)
{
sncatf(jsonResponse, ARRAY_UPB(jsonResponse), "%c%.1f", ch, platform->AxisTotalLength(drive));
ch = ',';
}
strncat(jsonResponse, "]}", ARRAY_UPB(jsonResponse));
}
else if (StringEquals(request, "connect"))
{
CancelUpload();
GetStatusResponse(1);
}
else
{
found = false;
}
JsonReport(found, request);
return keepOpen;
}
void Webserver::GetJsonUploadResponse()
{
snprintf(jsonResponse, ARRAY_UPB(jsonResponse), "{\"ubuff\":%u,\"err\":%d}", GetReportedUploadBufferSpace(), (uploadState == uploadOK) ? 0 : 1);
}
void Webserver::GetStatusResponse(uint8_t type)
{
GCodes *gc = reprap.GetGCodes();
if (type == 1)
{
// New-style status request
// Send the printing/idle status
char ch = (reprap.IsStopped()) ? 'S' : (gc->PrintingAFile()) ? 'P' : 'I';
snprintf(jsonResponse, ARRAY_UPB(jsonResponse), "{\"status\":\"%c\",\"heaters\":", ch);
// Send the heater temperatures
ch = '[';
for (int8_t heater = 0; heater < HEATERS; heater++)
{
sncatf(jsonResponse, ARRAY_UPB(jsonResponse), "%c\%.1f", ch, reprap.GetHeat()->GetTemperature(heater));
ch = ',';
}
// Send XYZ and extruder positions
float liveCoordinates[DRIVES + 1];
reprap.GetMove()->LiveCoordinates(liveCoordinates);
strncat(jsonResponse, "],\"pos\":", ARRAY_UPB(jsonResponse)); // announce the XYZ position
ch = '[';
for (int8_t drive = 0; drive < AXES; drive++)
{
sncatf(jsonResponse, ARRAY_UPB(jsonResponse), "%c%.2f", ch, liveCoordinates[drive]);
ch = ',';
}
sncatf(jsonResponse, ARRAY_UPB(jsonResponse), "],\"extr\":"); // announce the extruder positions
ch = '[';
for (int8_t drive = AXES; drive < DRIVES; drive++) // loop through extruders
{
sncatf(jsonResponse, ARRAY_UPB(jsonResponse), "%c%.3f", ch, gc->GetExtruderPosition(drive - AXES));
ch = ',';
}
strncat(jsonResponse, "]", ARRAY_UPB(jsonResponse));
// Send the speed and extruder override factors
sncatf(jsonResponse, ARRAY_UPB(jsonResponse), ",\"sfactor\":%.2f,\"efactor:\":", gc->GetSpeedFactor() * 100.0);
const float *extrusionFactors = gc->GetExtrusionFactors();
for (unsigned int i = 0; i < DRIVES - AXES; ++i)
{
sncatf(jsonResponse, ARRAY_UPB(jsonResponse), "%c%.2f", (i == 0) ? '[' : ',', extrusionFactors[i] * 100.0);
}
strncat(jsonResponse, "]", ARRAY_UPB(jsonResponse));
}
else
{
// The old (deprecated) poll response lists the status, then all the heater temperatures, then the XYZ positions, then all the extruder positions.
// These are all returned in a single vector called "poll".
// This is a poor choice of format because we can't easily tell which is which unless we already know the number of heaters and extruders.
char c = (gc->PrintingAFile()) ? 'P' : 'I';
snprintf(jsonResponse, ARRAY_UPB(jsonResponse), "{\"poll\":[\"%c\",", c); // Printing
for (int8_t heater = 0; heater < HEATERS; heater++)
{
sncatf(jsonResponse, ARRAY_UPB(jsonResponse), "\"%.1f\",", reprap.GetHeat()->GetTemperature(heater));
}
// Send XYZ and extruder positions
float liveCoordinates[DRIVES + 1];
reprap.GetMove()->LiveCoordinates(liveCoordinates);
for (int8_t drive = 0; drive < DRIVES; drive++) // loop through extruders
{
char ch = (drive == DRIVES - 1) ? ']' : ','; // append ] to the last one but , to the others
sncatf(jsonResponse, ARRAY_UPB(jsonResponse), "\"%.2f\"%c", liveCoordinates[drive], ch);
}
}
// Send the Z probe value
int v0 = platform->ZProbe();
int v1, v2;
switch (platform->GetZProbeSecondaryValues(v1, v2))
{
case 1:
sncatf(jsonResponse, ARRAY_UPB(jsonResponse), ",\"probe\":\"%d (%d)\"", v0, v1);
break;
case 2:
sncatf(jsonResponse, ARRAY_UPB(jsonResponse), ",\"probe\":\"%d (%d, %d)\"", v0, v1, v2);
break;
default:
sncatf(jsonResponse, ARRAY_UPB(jsonResponse), ",\"probe\":\"%d\"", v0);
break;
}
// Send the amount of buffer space available for gcodes
sncatf(jsonResponse, ARRAY_UPB(jsonResponse), ",\"buff\":%u", GetReportedGcodeBufferSpace());
// Send the home state. To keep the messages short, we send 1 for homed and 0 for not homed, instead of true and false.
if (type != 0)
{
sncatf(jsonResponse, ARRAY_UPB(jsonResponse), ",\"homed\":[%d,%d,%d]",
(gc->GetAxisIsHomed(0)) ? 1 : 0,
(gc->GetAxisIsHomed(1)) ? 1 : 0,
(gc->GetAxisIsHomed(2)) ? 1 : 0);
}
else
{
sncatf(jsonResponse, ARRAY_UPB(jsonResponse), ",\"hx\":%d,\"hy\":%d,\"hz\":%d",
(gc->GetAxisIsHomed(0)) ? 1 : 0,
(gc->GetAxisIsHomed(1)) ? 1 : 0,
(gc->GetAxisIsHomed(2)) ? 1 : 0);
}
// Send the response sequence number
sncatf(jsonResponse, ARRAY_UPB(jsonResponse), ",\"seq\":%u", (unsigned int) seq);
// Send the response to the last command. Do this last because it is long and may need to be truncated.
strncat(jsonResponse, ",\"resp\":\"", ARRAY_UPB(jsonResponse));
size_t jp = strnlen(jsonResponse, ARRAY_UPB(jsonResponse));
const char *p = gcodeReply;
while (*p != 0 && jp < ARRAY_SIZE(jsonResponse) - 3) // leave room for the final '"}\0'
{
char c = *p++;
char esc;
switch (c)
{
case '\r':
esc = 'r';
break;
case '\n':
esc = 'n';
break;
case '\t':
esc = 't';
break;
case '"':
esc = '"';
break;
case '\\':
esc = '\\';
break;
default:
esc = 0;
break;
}
if (esc)
{
if (jp == ARRAY_SIZE(jsonResponse) - 4)
{
break;
}
jsonResponse[jp++] = '\\';
jsonResponse[jp++] = esc;
}
else
{
jsonResponse[jp++] = c;
}
}
jsonResponse[jp] = 0;
strncat(jsonResponse, "\"}", ARRAY_UPB(jsonResponse));
}
// Process a character from the client
// Rewritten as a state machine by dc42 to increase capability and speed, and reduce RAM requirement.
// On entry:
// There is space for at least 1 character in clientMessage.
// On return:
// If we return false:
// We want more characters. There is space for at least 1 character in clientMessage.
// If we return true:
// We have processed the message and sent the reply. No more characters may be read from this message.
// Whenever this calls ProcessMessage:
// The first line has been split up into words. Variables numCommandWords and commandWords give the number of words we found
// and the pointers to each word. The second word is treated specially. It is assumed to be a filename followed by an optional
// qualifier comprising key/value pairs. Both may include %xx escapes, and the qualifier may include + to mean space. We store
// a pointer to the filename without qualifier in commandWords[1]. We store the qualifier key/value pointers in array 'qualifiers'
// and the number of them in numQualKeys.
// The remaining lines have been parsed as header name/value pairs. Pointers to them are stored in array 'headers' and the number
// of them in numHeaders.
// If one of our arrays is about to overflow, or the message is not in a format we expect, then we call RejectMessage with an
// appropriate error code and string.
bool Webserver::CharFromClient(char c)
{
switch(state)
{
case doingCommandWord:
switch(c)
{
case '\n':
clientMessage[clientPointer++] = 0;
++numCommandWords;
numHeaderKeys = 0;
headers[0].key = clientMessage + clientPointer;
state = doingHeaderKey;
break;
case '\r':
break;
case ' ':
case '\t':
clientMessage[clientPointer++] = 0;
if (numCommandWords < maxCommandWords)
{
++numCommandWords;
commandWords[numCommandWords] = clientMessage + clientPointer;
if (numCommandWords == 1)
{
state = doingFilename;
}
}
else
{
return RejectMessage("too many command words");
}
break;
default:
clientMessage[clientPointer++] = c;
break;
}
break;
case doingFilename:
switch(c)
{
case '\n':
clientMessage[clientPointer++] = 0;
++numCommandWords;
numQualKeys = 0;
numHeaderKeys = 0;
headers[0].key = clientMessage + clientPointer;
state = doingHeaderKey;
break;
case '?':
clientMessage[clientPointer++] = 0;
++numCommandWords;
numQualKeys = 0;
qualifiers[0].key = clientMessage + clientPointer;
state = doingQualifierKey;
break;
case '%':
state = doingFilenameEsc1;
break;
case '\r':
break;
case ' ':
case '\t':
clientMessage[clientPointer++] = 0;
if (numCommandWords < maxCommandWords)
{
++numCommandWords;
commandWords[numCommandWords] = clientMessage + clientPointer;
state = doingCommandWord;
}
else
{
return RejectMessage("too many command words");
}
break;
default:
clientMessage[clientPointer++] = c;
break;
}
break;
case doingQualifierKey:
switch(c)
{
case '=':
clientMessage[clientPointer++] = 0;
qualifiers[numQualKeys].value = clientMessage + clientPointer;
++numQualKeys;
state = doingQualifierValue;
break;
case '\n': // key with no value
case ' ':
case '\t':
case '\r':
case '%': // none of our keys needs escaping, so treat an escape within a key as an error
case '&': // key with no value
return RejectMessage("bad qualifier key");
default:
clientMessage[clientPointer++] = c;
break;
}
break;
case doingQualifierValue:
switch(c)
{
case '\n':
clientMessage[clientPointer++] = 0;
qualifiers[numQualKeys].key = clientMessage + clientPointer; // so that we can read the whole value even if it contains a null
numHeaderKeys = 0;
headers[0].key = clientMessage + clientPointer;
state = doingHeaderKey;
break;
case ' ':
case '\t':
clientMessage[clientPointer++] = 0;
qualifiers[numQualKeys].key = clientMessage + clientPointer; // so that we can read the whole value even if it contains a null
++numCommandWords;
commandWords[numCommandWords] = clientMessage + clientPointer;
state = doingCommandWord;
break;
case '\r':
break;
case '%':
state = doingQualifierValueEsc1;
break;
case '&':
// Another variable is coming
clientMessage[clientPointer++] = 0;
qualifiers[numQualKeys].key = clientMessage + clientPointer; // so that we can read the whole value even if it contains a null
if (numQualKeys < maxQualKeys)
{
state = doingQualifierKey;
}
else
{
return RejectMessage("too many keys in qualifier");
}
break;
case '+':
clientMessage[clientPointer++] = ' ';
break;
default:
clientMessage[clientPointer++] = c;
break;
}
break;
case doingFilenameEsc1:
case doingQualifierValueEsc1:
if (c >= '0' && c <= '9')
{
decodeChar = (c - '0') << 4;
state = (ServerState)(state + 1);
}
else if (c >= 'A' && c <= 'F')
{
decodeChar = (c - ('A' - 10)) << 4;
state = (ServerState)(state + 1);
}
else
{
return RejectMessage(badEscapeResponse);
}
break;
case doingFilenameEsc2:
case doingQualifierValueEsc2:
if (c >= '0' && c <= '9')
{
clientMessage[clientPointer++] = decodeChar | (c - '0');
state = (ServerState)(state - 2);
}
else if (c >= 'A' && c <= 'F')
{
clientMessage[clientPointer++] = decodeChar | c - ('A' - 10);
state = (ServerState)(state - 2);
}
else
{
return RejectMessage(badEscapeResponse);
}
break;
case doingHeaderKey:
switch(c)
{
case '\n':
if (clientMessage + clientPointer == headers[numHeaderKeys].key) // if the key hasn't started yet, then this is the blank line at the end
{
return ProcessMessage();
}
else
{
return RejectMessage("unexpected newline");
}
break;
case '\r':
break;
case ':':
clientMessage[clientPointer++] = 0;
headers[numHeaderKeys].value = clientMessage + clientPointer;
++numHeaderKeys;
state = expectingHeaderValue;
break;
default:
clientMessage[clientPointer++] = c;
break;
}
break;
case expectingHeaderValue:
if (c == ' ' || c == '\t')
{
break; // ignore spaces between header key and value
}
state = doingHeaderValue;
// no break
case doingHeaderValue:
if (c == '\n')
{
state = doingHeaderContinuation;
}
else if (c != '\r')
{
clientMessage[clientPointer++] = c;
}
break;
case doingHeaderContinuation:
switch(c)
{
case ' ':
case '\t':
// It's a continuation of the previous value
clientMessage[clientPointer++] = c;
state = doingHeaderValue;
break;
case '\n':
// It's the blank line
clientMessage[clientPointer] = 0;
return ProcessMessage();
case '\r':
break;
default:
// It's a new key
if (clientPointer + 3 <= ARRAY_SIZE(clientMessage))
{
clientMessage[clientPointer++] = 0;
headers[numHeaderKeys].key = clientMessage + clientPointer;
clientMessage[clientPointer++] = c;
state = doingHeaderKey;
}
else
{
return RejectMessage(overflowResponse);
}
break;
}
break;
case doingPost:
break;
default:
break;
}
if (clientPointer == ARRAY_SIZE(clientMessage))
{
return RejectMessage(overflowResponse);
}
return false;
}
// Process the message received so far. We have reached the end of the headers.