-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathblockly_helper.js
284 lines (251 loc) · 7.99 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
/**
* Execute the user's code.
* Just a quick and dirty eval. No checks for infinite loops, etc.
*/
function runJS() {
var code = Blockly.Generator.workspaceToCode('JavaScript');
try {
eval(code);
} catch (e) {
alert('Program error:\n' + e);
}
}
/**
* 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) {
Blockly.mainWorkspace.clear(); // clear the workspace
var xml = Blockly.Xml.textToDom(window.localStorage.arduino);
Blockly.Xml.domToWorkspace(Blockly.mainWorkspace, xml);
Blockly.mainWorkspace.setScale(0.7); // default scale
Blockly.mainWorkspace.scrollCenter(); // set scroll bars to center
}
}
/**
* Save generated code to local file.
*/
function saveCode() {
var fileName = window.prompt('What would you like to name your file?', 'Cube')
//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?', 'Cube');
// 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 blocks.')) {
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();
var xml = '<xml><block type="exp_start" deletable="true" movable="true"></block></xml>'; // add default block back
Blockly.Xml.domToWorkspace(Blockly.Xml.textToDom(xml), workspace);
Blockly.mainWorkspace.zoomToFit();
Blockly.mainWorkspace.setScale(0.7);
Blockly.mainWorkspace.scrollCenter(workspace); // set scroll bars to center
}
}
/*
* 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();
};
}
/**
* 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 blocks.')) {
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);
}
});
}
function resetClick() {
var code = "void setup() {} void loop() {}";
uploadCode(code, function(status, errorInfo) {
if (status != 200) {
alert("Error resetting program: " + errorInfo);
}
});
}