-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathblockly_helper.js
313 lines (283 loc) · 8.98 KB
/
blockly_helper.js
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
/**
* Backup code blocks to localStorage.
*/
function backup_blocks() {
if ('localStorage' in window) {
var xml = Blockly.Xml.workspaceToDom(Blockly.mainWorkspace);
window.localStorage.setItem('arduino', Blockly.Xml.domToText(xml));
}
}
/**
* Restore code blocks from localStorage.
*/
function restore_blocks() {
if ('localStorage' in window && window.localStorage.arduino) {
var xml = Blockly.Xml.textToDom(window.localStorage.arduino);
Blockly.Xml.domToWorkspace(Blockly.mainWorkspace, xml);
}
}
/*
* auto save and restore blocks
*/
function auto_save_and_restore_blocks() {
// Restore saved blocks in a separate thread so that subsequent
// initialization is not affected from a failed load.
window.setTimeout(restore_blocks, 0);
// Hook a save function onto unload.
bindEvent(window, 'unload', backup_blocks);
tabClick(selected);
// Init load event.
var loadInput = document.getElementById('load');
loadInput.addEventListener('change', load, false);
document.getElementById('fakeload').onclick = function() {
loadInput.click();
};
}
/**
* Save Arduino generated code to server
*/
function saveCodeServer() {
var fileName = 'ESP_CODE';
//doesn't save if the user quits the save prompt
if(fileName){
// Create blob with arduino code from workspace
var blob = new Blob([Blockly.Arduino.workspaceToCode()], {type: 'text/plain;charset=utf-8'});
// Create formdata object and add blob with name and filename
var formData = new FormData();
formData.append('inoCode', blob, "user_code.ino");
// Generate AJAX call to upload2.php
$.ajax('upload.php', {
method: "POST",
data: formData,
processData: false,
contentType: false,
success: [
// Upon success, log and alert user
function (data) {
console.log(data);
console.log("Uploaded successfully!");
alert("Uploaded!");
}
],
error: [
// Upon error, show error message given by server, log data and alert user
function(jqXHR, status, err_thrown) {
console.log("Uploading failed. Data received in error is: ");
console.log(jqXHR);
console.log(status);
console.log(err_thrown);
console.log("Done showing errors!")
},
function (data) {
console.log("Error uploading");
console.log(data);
alert("Failed!");
}
]
});
}
}
/**
* Save Arduino generated code to local file.
*/
function saveCode() {
var fileName = window.prompt('What would you like to name your file?', 'BlocklyDuino');
//doesn't save if the user quits the save prompt
if(fileName){
var blob = new Blob([Blockly.Arduino.workspaceToCode()], {type: 'text/plain;charset=utf-8'});
saveAs(blob, fileName + '.ino');
}
}
/**
* Save blocks to local file.
* better include Blob and FileSaver for browser compatibility
*/
function save() {
var xml = Blockly.Xml.workspaceToDom(Blockly.mainWorkspace);
var data = Blockly.Xml.domToText(xml);
var fileName = window.prompt('What would you like to name your file?', 'BlocklyDuino');
// Store data in blob.
// var builder = new BlobBuilder();
// builder.append(data);
// saveAs(builder.getBlob('text/plain;charset=utf-8'), 'blockduino.xml');
if(fileName){
var blob = new Blob([data], {type: 'text/xml'});
saveAs(blob, fileName + ".xml");
}
}
/**
* Load blocks from local file.
*/
function load(event) {
var files = event.target.files;
// Only allow uploading one file.
if (files.length != 1) {
return;
}
// FileReader
var reader = new FileReader();
reader.onloadend = function(event) {
var target = event.target;
// 2 == FileReader.DONE
if (target.readyState == 2) {
try {
var xml = Blockly.Xml.textToDom(target.result);
} catch (e) {
alert('Error parsing XML:\n' + e);
return;
}
var count = Blockly.mainWorkspace.getAllBlocks().length;
if (count && confirm('Replace existing blocks?\n"Cancel" will merge.')) {
Blockly.mainWorkspace.clear();
}
Blockly.Xml.domToWorkspace(Blockly.mainWorkspace, xml);
}
// Reset value of input after loading because Chrome will not fire
// a 'change' event if the same file is loaded again.
document.getElementById('load').value = '';
};
reader.readAsText(files[0]);
}
/**
* Discard all blocks from the workspace.
*/
function discard() {
var count = Blockly.mainWorkspace.getAllBlocks().length;
if (count < 2 || window.confirm('Delete all ' + count + ' blocks?')) {
Blockly.mainWorkspace.clear();
renderContent();
}
}
/**
* Bind an event to a function call.
* @param {!Element} element Element upon which to listen.
* @param {string} name Event name to listen to (e.g. 'mousedown').
* @param {!Function} func Function to call when event is triggered.
* W3 browsers will call the function with the event object as a parameter,
* MSIE will not.
*/
function bindEvent(element, name, func) {
if (element.addEventListener) { // W3C
element.addEventListener(name, func, false);
} else if (element.attachEvent) { // IE
element.attachEvent('on' + name, func);
}
}
//loading examples via ajax
var ajax;
function createAJAX() {
if (window.ActiveXObject) { //IE
try {
return new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try {
return new ActiveXObject("Microsoft.XMLHTTP");
} catch (e2) {
return null;
}
}
} else if (window.XMLHttpRequest) {
return new XMLHttpRequest();
} else {
return null;
}
}
function onSuccess() {
if (ajax.readyState == 4) {
if (ajax.status == 200) {
try {
var xml = Blockly.Xml.textToDom(ajax.responseText);
} catch (e) {
alert('Error parsing XML:\n' + e);
return;
}
var count = Blockly.mainWorkspace.getAllBlocks().length;
if (count && confirm('Replace existing blocks?\n"Cancel" will merge.')) {
Blockly.mainWorkspace.clear();
}
Blockly.Xml.domToWorkspace(Blockly.mainWorkspace, xml);
} else {
alert("Server error");
}
}
}
function load_by_url(uri) {
ajax = createAJAX();
if (!ajax) {
alert ('Not compatible with XMLHttpRequest');
return 0;
}
if (ajax.overrideMimeType) {
ajax.overrideMimeType('text/xml');
}
ajax.onreadystatechange = onSuccess;
ajax.open ("GET", uri, true);
ajax.send ("");
}
function uploadCode(code, callback) {
var target = document.getElementById('content_arduino');
var spinner = new Spinner().spin(target);
var url = "http://127.0.0.1:8080/";
var method = "POST";
// You REALLY want async = true.
// Otherwise, it'll block ALL execution waiting for server response.
var async = true;
var request = new XMLHttpRequest();
request.onreadystatechange = function() {
if (request.readyState != 4) {
return;
}
spinner.stop();
var status = parseInt(request.status); // HTTP response status, e.g., 200 for "200 OK"
var errorInfo = null;
switch (status) {
case 200:
break;
case 0:
errorInfo = "code 0\n\nCould not connect to server at " + url + ". Is the local web server running?";
break;
case 400:
errorInfo = "code 400\n\nBuild failed - probably due to invalid source code. Make sure that there are no missing connections in the blocks.";
break;
case 500:
errorInfo = "code 500\n\nUpload failed. Is the Arduino connected to USB port?";
break;
case 501:
errorInfo = "code 501\n\nUpload failed. Is 'ino' installed and in your path? This only works on Mac OS X and Linux at this time.";
break;
default:
errorInfo = "code " + status + "\n\nUnknown error.";
break;
}
callback(status, errorInfo);
};
request.open(method, url, async);
request.setRequestHeader("Content-Type", "text/plain;charset=UTF-8");
request.send(code);
}
function uploadClick() {
var code = Blockly.Arduino.workspaceToCode();
alert("Ready to upload to Arduino.");
uploadCode(code, function(status, errorInfo) {
if (status == 200) {
alert("Program uploaded ok");
} else {
alert("Error uploading program: " + errorInfo);
}
});
}
/***
* Reset will empty the window of blocks
*/
function resetClick() {
var code = "void setup() {} void loop() {}";
// var code = "";
$.get('template.txt', function(data) {
if (data) {
alert("Obtained data!");
code = data;
} else {
alert("Error reading code template!")
}
});
}