Added unfinished version of Arduino code generator.

parent bcf088cf
/**
* @license
* Visual Blocks Language
*
* Copyright 2012 Google Inc.
* https://blockly.googlecode.com/
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* @fileoverview Helper functions for generating Arduino for blocks.
* @author gasolin@gmail.com (Fred Lin)
*/
'use strict';
goog.provide('Blockly.Arduino');
goog.require('Blockly.Generator');
Blockly.Arduino = new Blockly.Generator('Arduino');
/**
* List of illegal variable names.
* This is not intended to be a security feature. Blockly is 100% client-side,
* so bypassing this list is trivial. This is intended to prevent users from
* accidentally clobbering a built-in object or function.
* @private
*/
if (!Blockly.Arduino.RESERVED_WORDS_) {
Blockly.Arduino.RESERVED_WORDS_ = '';
}
Blockly.Arduino.RESERVED_WORDS_ +=
// http://arduino.cc/en/Reference/HomePage
'setup,loop,if,else,for,switch,case,while,do,break,continue,return,goto,define,include,HIGH,LOW,INPUT,OUTPUT,INPUT_PULLUP,true,false,interger, constants,floating,point,void,bookean,char,unsigned,byte,int,word,long,float,double,string,String,array,static, volatile,const,sizeof,pinMode,digitalWrite,digitalRead,analogReference,analogRead,analogWrite,tone,noTone,shiftOut,shitIn,pulseIn,millis,micros,delay,delayMicroseconds,min,max,abs,constrain,map,pow,sqrt,sin,cos,tan,randomSeed,random,lowByte,highByte,bitRead,bitWrite,bitSet,bitClear,bit,attachInterrupt,detachInterrupt,interrupts,noInterrupts'
;
/**
* Order of operation ENUMs.
*
*/
Blockly.Arduino.ORDER_ATOMIC = 0; // 0 "" ...
Blockly.Arduino.ORDER_UNARY_POSTFIX = 1; // expr++ expr-- () [] .
Blockly.Arduino.ORDER_UNARY_PREFIX = 2; // -expr !expr ~expr ++expr --expr
Blockly.Arduino.ORDER_MULTIPLICATIVE = 3; // * / % ~/
Blockly.Arduino.ORDER_ADDITIVE = 4; // + -
Blockly.Arduino.ORDER_SHIFT = 5; // << >>
Blockly.Arduino.ORDER_RELATIONAL = 6; // is is! >= > <= <
Blockly.Arduino.ORDER_EQUALITY = 7; // == != === !==
Blockly.Arduino.ORDER_BITWISE_AND = 8; // &
Blockly.Arduino.ORDER_BITWISE_XOR = 9; // ^
Blockly.Arduino.ORDER_BITWISE_OR = 10; // |
Blockly.Arduino.ORDER_LOGICAL_AND = 11; // &&
Blockly.Arduino.ORDER_LOGICAL_OR = 12; // ||
Blockly.Arduino.ORDER_CONDITIONAL = 13; // expr ? expr : expr
Blockly.Arduino.ORDER_ASSIGNMENT = 14; // = *= /= ~/= %= += -= <<= >>= &= ^= |=
Blockly.Arduino.ORDER_NONE = 99; // (...)
/*
* Arduino Board profiles
*
*/
var profile = {
arduino: {
description: "Arduino standard-compatible board",
digital : [["1", "1"], ["2", "2"], ["3", "3"], ["4", "4"], ["5", "5"], ["6", "6"], ["7", "7"], ["8", "8"], ["9", "9"], ["10", "10"], ["11", "11"], ["12", "12"], ["13", "13"], ["A0", "A0"], ["A1", "A1"], ["A2", "A2"], ["A3", "A3"], ["A4", "A4"], ["A5", "A5"]],
analog : [["A0", "A0"], ["A1", "A1"], ["A2", "A2"], ["A3", "A3"], ["A4", "A4"], ["A5", "A5"]],
serial : 9600
},
arduino_mega:{
description: "Arduino Mega-compatible board"
//53 digital
//15 analog
},
//Behind the Wire Arduino profile
arduino_btw: {
description: "Arduino Behind The Wire",
digital : [["RedLight","RedLight"],["GreenLight","GreenLight"],["WhiteLight","WhiteLight"],["UpButton","UpButton"],["DownButton","DownButton"],["OnButton","OnButton"],["OffButton","OffButton"],["LeftButton","LeftButton"],["RightButton","RightButton"]],
analog : [["EngineLeft","EngineLeft"],["EngineRight","EngineRight"],["Throttle","Throttle"]],
nav_lights : [["Red (Left Wing)","RedLight"],["Green (Right Wing)","GreenLight"],["White (Tail)","WhiteLight"]],
buttons : [["Left","LeftButton"],["Right","RightButton"]],
rudder_angle: [["-45","-45"],["-30","-30"],["-15","-15"],["0","0"],["15","15"],["30","30"],["45","45"]],
engines : [["Engine Left","EngineLeft"],["Engine Right","EngineRight"]]
}
}
//set default profile to arduino standard-compatible board
profile["default"] = profile["arduino_btw"];
//alert(profile.default.digital[0]);
/**
* Initialise the database of variable names.
*/
Blockly.Arduino.init = function() {
// Create a dictionary of definitions to be printed before setups.
Blockly.Arduino.definitions_ = Object.create(null);
// Create a dictionary of setups to be printed before the code.
Blockly.Arduino.setups_ = Object.create(null);
if (Blockly.Variables) {
if (!Blockly.Arduino.variableDB_) {
Blockly.Arduino.variableDB_ =
new Blockly.Names(Blockly.Arduino.RESERVED_WORDS_);
} else {
Blockly.Arduino.variableDB_.reset();
}
var defvars = [];
var variables = Blockly.Variables.allVariables();
for (var x = 0; x < variables.length; x++) {
defvars[x] = 'int ' +
Blockly.Arduino.variableDB_.getDistinctName(variables[x],
Blockly.Variables.NAME_TYPE) + ';\n';
}
Blockly.Arduino.definitions_['variables'] = defvars.join('\n');
}
};
/**
* Prepend the generated code with the variable definitions.
* @param {string} code Generated code.
* @return {string} Completed code.
*/
Blockly.Arduino.finish = function(code) {
// Indent every line.
code = ' ' + code.replace(/\n/g, '\n ');
code = code.replace(/\n\s+$/, '\n');
code = 'void loop() \n{\n' + code + '\n}';
// Convert the definitions dictionary into a list.
var imports = ["#include <BehindTheWire.h>\n"];
var definitions = [];
for (var name in Blockly.Arduino.definitions_) {
var def = Blockly.Arduino.definitions_[name];
if (def.match(/^#include/)) {
imports.push(def);
} else {
definitions.push(def);
}
}
// Convert the setups dictionary into a list.
var setups = [];
for (var name in Blockly.Arduino.setups_) {
setups.push(Blockly.Arduino.setups_[name]);
}
var allDefs = imports.join('\n') + '\n\n' + definitions.join('\n') + '\nvoid setup() \n{\n '+setups.join('\n ') + '\n}'+ '\n\n';
return allDefs.replace(/\n\n+/g, '\n\n').replace(/\n*$/, '\n\n\n') + code;
};
/**
* Naked values are top-level blocks with outputs that aren't plugged into
* anything. A trailing semicolon is needed to make this legal.
* @param {string} line Line of generated code.
* @return {string} Legal line of code.
*/
Blockly.Arduino.scrubNakedValue = function(line) {
return line + ';\n';
};
/**
* Encode a string as a properly escaped Arduino string, complete with quotes.
* @param {string} string Text to encode.
* @return {string} Arduino string.
* @private
*/
Blockly.Arduino.quote_ = function(string) {
// TODO: This is a quick hack. Replace with goog.string.quote
string = string.replace(/\\/g, '\\\\')
.replace(/\n/g, '\\\n')
.replace(/\$/g, '\\$')
.replace(/'/g, '\\\'');
return '\"' + string + '\"';
};
/**
* Common tasks for generating Arduino from blocks.
* Handles comments for the specified block and any connected value blocks.
* Calls any statements following this block.
* @param {!Blockly.Block} block The current block.
* @param {string} code The Arduino code created for this block.
* @return {string} Arduino code with comments and subsequent blocks added.
* @this {Blockly.CodeGenerator}
* @private
*/
Blockly.Arduino.scrub_ = function(block, code) {
if (code === null) {
// Block has handled code generation itself.
return '';
}
var commentCode = '';
// Only collect comments for blocks that aren't inline.
if (!block.outputConnection || !block.outputConnection.targetConnection) {
// Collect comment for this block.
var comment = block.getCommentText();
if (comment) {
commentCode += Blockly.Generator.prefixLines(comment, '// ') + '\n';
}
// Collect comments for all value arguments.
// Don't collect comments for nested statements.
for (var x = 0; x < block.inputList.length; x++) {
if (block.inputList[x].type == Blockly.INPUT_VALUE) {
var childBlock = block.inputList[x].connection.targetBlock();
if (childBlock) {
var comment = Blockly.Generator.allNestedComments(childBlock);
if (comment) {
commentCode += Blockly.Generator.prefixLines(comment, '// ');
}
}
}
}
}
var nextBlock = block.nextConnection && block.nextConnection.targetBlock();
var nextCode = this.blockToCode(nextBlock);
return commentCode + code + nextCode;
};
This diff is collapsed.
/**
* @fileoverview Behind The Wire Landing Gear Servo Blocks
* @author danse@jarofdoom.co.uk Richard Fontaine
*/
'use strict';
//define blocks
if (!Blockly.Language) Blockly.Language = {};
/////////////////////////////
// Landing Gear //
/////////////////////////////
//Define Landing Gear UP block
Blockly.Language.landing_gear_up = {
category:'Landing Gear',
helpUrl:'',
init: function(){
this.setColour(0);
this.appendDummyInput("")
.appendTitle("Move landing gear up");
this.setPreviousStatement(true);
this.setNextStatement(true);
}
};
//Define Landing Gear UP code
Blockly.Arduino.landing_gear_up = function() {
Blockly.Arduino.definitions_['define_servo'] = '#include <Servo.h>\n';
Blockly.Arduino.setups_['prepare_servo_lg'] = 'functions.landingGearPrepare();\n';
var code = 'functions.landingGearUp();\n';
return code;
}
//Define Landing Gear down block
Blockly.Language.landing_gear_down = {
category:'Landing Gear',
helpUrl:'',
init: function(){
this.setColour(0);
this.appendDummyInput("")
.appendTitle("Move landing gear down");
this.setPreviousStatement(true);
this.setNextStatement(true);
}
};
//Define Landing Gear down code
Blockly.Arduino.landing_gear_down = function() {
Blockly.Arduino.definitions_['define_servo'] = '#include <Servo.h>\n';
Blockly.Arduino.setups_['prepare_servo_lg'] = 'functions.landingGearPrepare();\n';
var code = 'functions.landingGearDown();\n';
return code;
}
/////////////////////////////
// Rudder //
/////////////////////////////
//Define Rudder Left block
Blockly.Language.rudder_left = {
category:'Rudder',
helpUrl:'',
init: function(){
this.setColour(0);
this.appendDummyInput("")
.appendTitle("Move rudder Left");
this.setPreviousStatement(true);
this.setNextStatement(true);
}
};
//Define Rudder Left code
Blockly.Arduino.rudder_left = function() {
Blockly.Arduino.definitions_['define_servo'] = '#include <Servo.h>\n';
Blockly.Arduino.definitions_['define_btw_global'] = 'BehindTheWire functions;\n';
Blockly.Arduino.setups_['prepare_servo_r'] = 'functions.rudderPrepare();\n';
var code = 'functions.rudderLeft();\n';
return code;
}
//Define Rudder Right block
Blockly.Language.rudder_right = {
category:'Rudder',
helpUrl:'',
init: function(){
this.setColour(0);
this.appendDummyInput("")
.appendTitle("Move rudder Right");
this.setPreviousStatement(true);
this.setNextStatement(true);
}
};
//Define Rudder Right code
Blockly.Arduino.rudder_right = function() {
Blockly.Arduino.definitions_['define_servo'] = '#include <Servo.h>\n';
Blockly.Arduino.definitions_['define_btw_global'] = 'BehindTheWire functions;\n';
Blockly.Arduino.setups_['prepare_servo_r'] = 'functions.rudderPrepare();\n';
var code = 'functions.rudderRight();\n';
return code;
}
//Define Rudder Set Position block
Blockly.Language.rudder_set_position = {
category:'Rudder',
helpUrl:'',
init: function(){
this.setColour(0);
this.appendDummyInput("")
.appendTitle("Move Rudder to a")
.appendTitle(new Blockly.FieldDropdown(profile.arduino_btw.rudder_angle), "ANGLE")
.appendTitle("degrees angle");
this.setPreviousStatement(true);
this.setNextStatement(true);
this.setTooltip('Set the rudder position to 0-180');
}
};
//Define Rudder Set Position code
Blockly.Arduino.rudder_set_position = function() {
var servo_position = this.getTitleValue('ANGLE');
Blockly.Arduino.definitions_['define_servo'] = '#include <Servo.h>\n';
Blockly.Arduino.definitions_['define_btw_global'] = 'BehindTheWire functions;\n';
Blockly.Arduino.setups_['prepare_servo_r'] = 'functions.rudderPrepare();\n';
//var servo_position =
// Blockly.Arduino.valueToCode(this, 'RUDDER_POSITION', Blockly.Arduino.ORDER_ATOMIC) ||
// '90';
var code = 'functions.rudderSetPosition(' + servo_position + ');\n';
return code;
}
/////////////////////////////
// LEDs //
/////////////////////////////
Blockly.Language.navigation_lights = {
category: 'Navigation Lights',
helpUrl: '',
init: function() {
this.setColour(230);
this.appendDummyInput("")
.appendTitle("Set ")
.appendTitle(new Blockly.FieldDropdown(profile.arduino_btw.nav_lights), "LED")
.appendTitle("Light ")
.appendTitle(new Blockly.FieldDropdown([["ON", "ON"], ["OFF", "OFF"]]), "STATE");
this.setPreviousStatement(true);
this.setNextStatement(true);
}
};
Blockly.Arduino.navigation_lights = function() {
var dropdown_light = this.getTitleValue('LED');
var dropdown_state = this.getTitleValue('STATE');
Blockly.Arduino.setups_['setup_output_'+dropdown_light] = 'pinMode('+dropdown_light+', OUTPUT);';
var code = 'digitalWrite('+dropdown_light+','+dropdown_state+');\n'
return code;
}
/////////////////////////////
// Buttons //
/////////////////////////////
Blockly.Language.read_button = {
category: 'Buttons',
helpUrl: '',
init: function() {
this.setColour(230);
this.appendDummyInput("")
.appendTitle(new Blockly.FieldDropdown(profile.arduino_btw.buttons), "Button")
.appendTitle(" button is ON?");
this.setOutput(true, Boolean);
this.setTooltip('');
}
};
Blockly.Arduino.read_button = function() {
var dropdown_button = this.getTitleValue('Button');
Blockly.Arduino.setups_['setup_input_'+dropdown_button] = 'pinMode('+dropdown_button+', INPUT);';
var code = 'digitalRead('+dropdown_button+')';
return [code, Blockly.Arduino.ORDER_ATOMIC];
};
Blockly.Language.pot = {
category: 'Buttons',
helpUrl: '',
init: function() {
this.setColour(230);
this.appendDummyInput("")
.appendTitle("Read Knob")
this.setOutput(true, Number);
this.setTooltip('Return value between 0 and 1024');
}
};
Blockly.Arduino.pot = function() {
//var dropdown_analogue = this.getTitleValue('THROTTLE');
//Blockly.Arduino.setups_['setup_input_'+dropdown_analogue] = 'pinMode('+dropdown_analogue+', INPUT);';
//var code = 'analogRead('+dropdown_analogue+')';
var code = 'analogRead(Throttle)';
return [code, Blockly.Arduino.ORDER_ATOMIC];
};
/////////////////////////////
// ENGINES //
/////////////////////////////
Blockly.Language.set_engine_speed = {
category: 'Engines',
helpUrl: '',
init: function() {
this.setColour(190);
this.appendValueInput("ENGINE_SPEED", Number)
.appendTitle("Set ")
.appendTitle(new Blockly.FieldDropdown(profile.arduino_btw.engines), "ENGINE")
.appendTitle("speed to")
.setCheck(Number);
this.setInputsInline(true);
this.setPreviousStatement(true);
this.setNextStatement(true);
}
};
Blockly.Arduino.set_engine_speed = function() {
var dropdown_engine = this.getTitleValue('ENGINE');
var engine_speed = Blockly.Arduino.valueToCode(this, 'ENGINE_SPEED', Blockly.Arduino.ORDER_ATOMIC) || '90';
Blockly.Arduino.setups_['setup_output_'+dropdown_engine] = 'pinMode('+dropdown_engine+', OUTPUT);';
var code = 'analogWrite('+dropdown_engine+', '+engine_speed+');\n'
return code;
}
Blockly.Language.throttle = {
category: 'Engines',
helpUrl: '',
init: function() {
this.setColour(230);
this.appendDummyInput("")
.appendTitle("Throttle Value")
this.setOutput(true, Number);
this.setTooltip('Return value between 0 and 1024');
}
};
Blockly.Arduino.throttle = function() {
var code = 'map(analogRead(Throttle),0,1024,0,255)';
return [code, Blockly.Arduino.ORDER_ATOMIC];
};
/////////////////////////////
// WAIT //
/////////////////////////////
Blockly.Language.wait = {
category : 'Wait',
helpUrl: '',
init: function() {
this.setColour(120);
this.appendDummyInput("")
.appendTitle("Wait ")
.appendTitle(new Blockly.FieldDropdown([["1","1000"],["0.1","100"],["0.5","500"],["1.5","1500"],["2","2000"],["5","5000"],["10","10000"]]),"WAIT")
.appendTitle(" seconds");
this.setPreviousStatement(true);
this.setNextStatement(true);
}
}
Blockly.Arduino.wait = function(){
var dropdown_wait = this.getTitleValue("WAIT");
var code = "delay("+dropdown_wait+");\n";
return code;
}
/**
* Visual Blocks Language
*
* Copyright 2012 Google Inc.
* http://blockly.googlecode.com/
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* @fileoverview Generating Dart for colour blocks.
* @author fraser@google.com (Neil Fraser)
*/
'use strict';
Blockly.Dart = Blockly.Generator.get('Dart');
Blockly.Dart.addReservedWords('Math');
Blockly.Dart.colour_picker = function() {
// Colour picker.
var code = '\'' + this.getTitleValue('COLOUR') + '\'';
return [code, Blockly.Dart.ORDER_ATOMIC];
};
Blockly.Dart.colour_rgb = function() {
// Compose a colour from RGB components.
var red = Blockly.Dart.valueToCode(this, 'RED',
Blockly.Dart.ORDER_NONE) || 0;
var green = Blockly.Dart.valueToCode(this, 'GREEN',
Blockly.Dart.ORDER_NONE) || 0;
var blue = Blockly.Dart.valueToCode(this, 'BLUE',
Blockly.Dart.ORDER_NONE) || 0;
if (!Blockly.Dart.definitions_['colour_rgb']) {
Blockly.Dart.definitions_['import_dart_math'] =
'import \'dart:math\' as Math;';
var functionName = Blockly.Dart.variableDB_.getDistinctName(
'colour_rgb', Blockly.Generator.NAME_TYPE);
Blockly.Dart.colour_rgb.functionName = functionName;
var func = [];
func.push('String ' + functionName + '(r, g, b) {');
func.push(' String rs = (Math.max(Math.min(r, 1), 0) * 255).round()' +
'.toRadixString(16);');
func.push(' String gs = (Math.max(Math.min(g, 1), 0) * 255).round()' +
'.toRadixString(16);');
func.push(' String bs = (Math.max(Math.min(b, 1), 0) * 255).round()' +
'.toRadixString(16);');
func.push(' rs = \'0$rs\';');
func.push(' rs = rs.substring(rs.length - 2);');
func.push(' gs = \'0$gs\';');
func.push(' gs = gs.substring(gs.length - 2);');
func.push(' bs = \'0$bs\';');
func.push(' bs = bs.substring(bs.length - 2);');
func.push(' return \'#$rs$gs$bs\';');
func.push('}');
Blockly.Dart.definitions_['colour_rgb'] = func.join('\n');
}
var code = Blockly.Dart.colour_rgb.functionName +
'(' + red + ', ' + green + ', ' + blue + ')';
return [code, Blockly.Dart.ORDER_UNARY_POSTFIX];
};
Blockly.Dart.colour_blend = function() {
// Blend two colours together.
var c1 = Blockly.Dart.valueToCode(this, 'COLOUR1',
Blockly.Dart.ORDER_NONE) || '\'#000000\'';
var c2 = Blockly.Dart.valueToCode(this, 'COLOUR2',
Blockly.Dart.ORDER_NONE) || '\'#000000\'';
var ratio = Blockly.Dart.valueToCode(this, 'RATIO',
Blockly.Dart.ORDER_NONE) || 0.5;
if (!Blockly.Dart.definitions_['colour_blend']) {
Blockly.Dart.definitions_['import_dart_math'] =
'import \'dart:math\' as Math;';
var functionName = Blockly.Dart.variableDB_.getDistinctName(
'colour_blend', Blockly.Generator.NAME_TYPE);
Blockly.Dart.colour_blend.functionName = functionName;
var func = [];
func.push('String ' + functionName + '(c1, c2, ratio) {');
func.push(' ratio = Math.max(Math.min(ratio, 1), 0);');
func.push(' int r1 = int.parse(\'0x${c1.substring(1, 3)}\');');
func.push(' int g1 = int.parse(\'0x${c1.substring(3, 5)}\');');
func.push(' int b1 = int.parse(\'0x${c1.substring(5, 7)}\');');
func.push(' int r2 = int.parse(\'0x${c2.substring(1, 3)}\');');
func.push(' int g2 = int.parse(\'0x${c2.substring(3, 5)}\');');
func.push(' int b2 = int.parse(\'0x${c2.substring(5, 7)}\');');
func.push(' String rs = (r1 * (1 - ratio) + r2 * ratio).round()' +
'.toRadixString(16);');
func.push(' String gs = (g1 * (1 - ratio) + g2 * ratio).round()' +
'.toRadixString(16);');
func.push(' String bs = (b1 * (1 - ratio) + b2 * ratio).round()' +
'.toRadixString(16);');
func.push(' rs = \'0$rs\';');
func.push(' rs = rs.substring(rs.length - 2);');
func.push(' gs = \'0$gs\';');
func.push(' gs = gs.substring(gs.length - 2);');
func.push(' bs = \'0$bs\';');
func.push(' bs = bs.substring(bs.length - 2);');
func.push(' return \'#$rs$gs$bs\';');
func.push('}');
Blockly.Dart.definitions_['colour_blend'] = func.join('\n');
}
var code = Blockly.Dart.colour_blend.functionName +
'(' + c1 + ', ' + c2 + ', ' + ratio + ')';
return [code, Blockly.Dart.ORDER_UNARY_POSTFIX];
};
/**
* Visual Blocks Language
*
* Copyright 2012 Google Inc.
* http://blockly.googlecode.com/
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* @fileoverview Generating Arduino for control blocks.
* @author gasolin@gmail.com (Fred Lin)
*/
'use strict';
Blockly.Arduino = Blockly.Generator.get('Arduino');
Blockly.Arduino.controls_if = function() {
// If/elseif/else condition.
var n = 0;
var argument = Blockly.Arduino.valueToCode(this, 'IF' + n,
Blockly.Arduino.ORDER_NONE) || 'false';
var branch = Blockly.Arduino.statementToCode(this, 'DO' + n);
var code = 'if (' + argument + ') {\n' + branch + '\n}';
for (n = 1; n <= this.elseifCount_; n++) {
argument = Blockly.Arduino.valueToCode(this, 'IF' + n,
Blockly.Arduino.ORDER_NONE) || 'false';
branch = Blockly.Arduino.statementToCode(this, 'DO' + n);
code += ' else if (' + argument + ') {\n' + branch + '}';
}
if (this.elseCount_) {
branch = Blockly.Arduino.statementToCode(this, 'ELSE');
code += ' else {\n' + branch + '\n}';
}
return code + '\n';
};
Blockly.Arduino.controls_repeat = function() {
// Repeat n times.
var repeats = Number(this.getTitleValue('TIMES'));
var branch = Blockly.Arduino.statementToCode(this, 'DO');
if (Blockly.Arduino.INFINITE_LOOP_TRAP) {
branch = Blockly.Arduino.INFINITE_LOOP_TRAP.replace(/%1/g,
'\'' + this.id + '\'') + branch;
}
var loopVar = Blockly.Arduino.variableDB_.getDistinctName(
'count', Blockly.Variables.NAME_TYPE);
var code = 'for (' + loopVar + ' = 0; ' +
loopVar + ' < ' + repeats + '; ' +
loopVar + '++) {\n' +
branch + '}\n';
return code;
};
Blockly.Arduino.controls_whileUntil = function() {
// Do while/until loop.
var argument0 = Blockly.Arduino.valueToCode(this, 'BOOL',
Blockly.Arduino.ORDER_NONE) || 'false';
var branch = Blockly.Arduino.statementToCode(this, 'DO');
if (Blockly.Arduino.INFINITE_LOOP_TRAP) {
branch = Blockly.Arduino.INFINITE_LOOP_TRAP.replace(/%1/g,
'\'' + this.id + '\'') + branch;
}
if (this.getTitleValue('MODE') == 'UNTIL') {
if (!argument0.match(/^\w+$/)) {
argument0 = '(' + argument0 + ')';
}
argument0 = '!' + argument0;
}
return 'while (' + argument0 + ') {\n' + branch + '}\n';
};
Blockly.Arduino.controls_for = function() {
// For loop.
var variable0 = Blockly.Arduino.variableDB_.getName(
this.getTitleValue('VAR'), Blockly.Variables.NAME_TYPE);
var argument0 = Blockly.Arduino.valueToCode(this, 'FROM',
Blockly.Arduino.ORDER_ASSIGNMENT) || '0';
var argument1 = Blockly.Arduino.valueToCode(this, 'TO',
Blockly.Arduino.ORDER_ASSIGNMENT) || '0';
var branch = Blockly.Arduino.statementToCode(this, 'DO');
if (Blockly.Arduino.INFINITE_LOOP_TRAP) {
branch = Blockly.Arduino.INFINITE_LOOP_TRAP.replace(/%1/g,
'\'' + this.id + '\'') + branch;
}
var code;
if (argument0.match(/^-?\d+(\.\d+)?$/) &&
argument1.match(/^-?\d+(\.\d+)?$/)) {
// Both arguments are simple numbers.
var up = parseFloat(argument0) <= parseFloat(argument1);
code = 'for (' + variable0 + ' = ' + argument0 + '; ' +
variable0 + (up ? ' <= ' : ' >= ') + argument1 + '; ' +
variable0 + (up ? '++' : '--') + ') {\n' +
branch + '}\n';
} else {
code = '';
// Cache non-trivial values to variables to prevent repeated look-ups.
var startVar = argument0;
if (!argument0.match(/^\w+$/) && !argument0.match(/^-?\d+(\.\d+)?$/)) {
var startVar = Blockly.Arduino.variableDB_.getDistinctName(
variable0 + '_start', Blockly.Variables.NAME_TYPE);
code += 'int ' + startVar + ' = ' + argument0 + ';\n';
}
var endVar = argument1;
if (!argument1.match(/^\w+$/) && !argument1.match(/^-?\d+(\.\d+)?$/)) {
var endVar = Blockly.Arduino.variableDB_.getDistinctName(
variable0 + '_end', Blockly.Variables.NAME_TYPE);
code += 'int ' + endVar + ' = ' + argument1 + ';\n';
}
code += 'for (' + variable0 + ' = ' + startVar + ';\n' +
' (' + startVar + ' <= ' + endVar + ') ? ' +
variable0 + ' <= ' + endVar + ' : ' +
variable0 + ' >= ' + endVar + ';\n' +
' ' + variable0 + ' += (' + startVar + ' <= ' + endVar +
') ? 1 : -1) {\n' +
branch0 + '}\n';
}
return code;
};
Blockly.Arduino.controls_forEach = function() {
// For each loop.
var variable0 = Blockly.Arduino.variableDB_.getName(
this.getTitleValue('VAR'), Blockly.Variables.NAME_TYPE);
var argument0 = Blockly.Arduino.valueToCode(this, 'LIST',
Blockly.Arduino.ORDER_ASSIGNMENT) || '[]';
var branch = Blockly.Arduino.statementToCode(this, 'DO');
if (Blockly.Arduino.INFINITE_LOOP_TRAP) {
branch = Blockly.Arduino.INFINITE_LOOP_TRAP.replace(/%1/g,
'\'' + this.id + '\'') + branch;
}
var code = 'for (var ' + variable0 + ' in ' + argument0 + ') {\n' +
branch + '}\n';
return code;
};
Blockly.Arduino.controls_flow_statements = function() {
// Flow statements: continue, break.
switch (this.getTitleValue('FLOW')) {
case 'BREAK':
return 'break;\n';
case 'CONTINUE':
return 'continue;\n';
}
throw 'Unknown flow statement.';
};
/**
* @fileoverview Helper functions for generating Arduino blocks.
* @author author@email.com (Name)
*/
'use strict';
//define blocks
if (!Blockly.Language) Blockly.Language = {};
//define read block
Blockly.Language.custom_read = {
category: 'Custom',
helpUrl: '',
init: function() {
this.setColour(230);
this.appendDummyInput("")
.appendTitle("CustomRead PIN#")
.appendTitle(new Blockly.FieldDropdown(profile.default.digital), "PIN");
this.setOutput(true, Boolean);
this.setTooltip('input block');
}
};
//define write block
Blockly.Language.custom_write = {
category: 'Custom',
helpUrl: '',
init: function() {
this.setColour(230);
this.appendDummyInput("")
.appendTitle("CustomWrite PIN#")
.appendTitle(new Blockly.FieldImage("http://www.seeedstudio.com/wiki/images/thumb/e/e0/LED1.jpg/400px-LED1.jpg", 64, 64))
.appendTitle(new Blockly.FieldDropdown(profile.default.analog), "PIN")
.appendTitle("value");
this.appendValueInput("NUM", Number);
this.setInputsInline(true);
this.setPreviousStatement(true, null);
this.setNextStatement(true, null);
this.setTooltip('Output block');
}
};
// define generators
Blockly.Arduino.custom_write = function() {
var dropdown_pin = this.getTitleValue('PIN');
var value_num = Blockly.Arduino.valueToCode(this, 'NUM', Blockly.Arduino.ORDER_ATOMIC);
var code = 'analogWrite('+dropdown_pin+','+value_num+');\n';
return code;
};
Blockly.Arduino.custom_read = function() {
var dropdown_pin = this.getTitleValue('PIN');
// Blockly.Arduino.definitions_['define_custom_read'] = '#include &lt;Servo.h&gt;\n';
// Blockly.Arduino.definitions_['var_custom_read'+dropdown_pin] = 'Servo servo_'+dropdown_pin+';\n';
// Blockly.Arduino.setups_['setup_custom_read_'+dropdown_pin] = 'servo_'+dropdown_pin+'.attach('+dropdown_pin+');\n';
var code = 'analogRead('+dropdown_pin+')';
return [code, Blockly.Arduino.ORDER_ATOMIC];
};
/**
* Visual Blocks Language
*
* Copyright 2012 Google Inc.
* http://blockly.googlecode.com/
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* @fileoverview Generating Arduino for list blocks.
* @author gasolin@gmail.com (Fred Lin)
*/
'use strict';
Blockly.Arduino = Blockly.Generator.get('Arduino');
Blockly.Arduino.lists_create_empty = function() {
// Create an empty list.
return ['[]', Blockly.Arduino.ORDER_ATOMIC];
};
Blockly.Arduino.lists_create_with = function() {
// Create a list with any number of elements of any type.
var code = new Array(this.itemCount_);
for (var n = 0; n < this.itemCount_; n++) {
code[n] = Blockly.Arduino.valueToCode(this, 'ADD' + n,
Blockly.Arduino.ORDER_NONE) || 'null';
}
var code = '[' + code.join(', ') + ']';
return [code, Blockly.Arduino.ORDER_ATOMIC];
};
Blockly.Arduino.lists_repeat = function() {
// Create a list with one element repeated.
if (!Blockly.Arduino.definitions_['lists_repeat']) {
// Function adapted from Closure's goog.array.repeat.
var functionName = Blockly.Arduino.variableDB_.getDistinctName('lists_repeat',
Blockly.Generator.NAME_TYPE);
Blockly.Arduino.lists_repeat.repeat = functionName;
var func = [];
func.push('List ' + functionName + '(value, n) {');
func.push(' var array = new List(n);');
func.push(' for (int i = 0; i < n; i++) {');
func.push(' array[i] = value;');
func.push(' }');
func.push(' return array;');
func.push('}');
Blockly.Arduino.definitions_['lists_repeat'] = func.join('\n');
}
var argument0 = Blockly.Arduino.valueToCode(this, 'ITEM', true) || 'null';
var argument1 = Blockly.Arduino.valueToCode(this, 'NUM') || '0';
var code = Blockly.Arduino.lists_repeat.repeat +
'(' + argument0 + ', ' + argument1 + ')';
return [code, Blockly.Arduino.ORDER_UNARY_POSTFIX];
};
Blockly.Arduino.lists_length = function() {
// Testing the length of a list is the same as for a string.
return Blockly.Arduino.text_length.call(this);
};
Blockly.Arduino.lists_isEmpty = function() {
// Testing a list for being empty is the same as for a string.
return Blockly.Arduino.text_isEmpty.call(this);
};
Blockly.Arduino.lists_indexOf = function() {
// Searching a list for a value is the same as search for a substring.
return Blockly.Arduino.text_indexOf.call(this);
};
Blockly.Arduino.lists_getIndex = function() {
// Indexing into a list is the same as indexing into a string.
return Blockly.Arduino.text_charAt.call(this);
};
Blockly.Arduino.lists_setIndex = function() {
// Set element at index.
var argument0 = Blockly.Arduino.valueToCode(this, 'AT',
Blockly.Arduino.ORDER_ADDITIVE) || '1';
var argument1 = Blockly.Arduino.valueToCode(this, 'LIST',
Blockly.Arduino.ORDER_UNARY_POSTFIX) || '[]';
var argument2 = Blockly.Arduino.valueToCode(this, 'TO',
Blockly.Arduino.ORDER_ASSIGNMENT) || 'null';
// Blockly uses one-based indicies.
if (argument0.match(/^\d+$/)) {
// If the index is a naked number, decrement it right now.
argument0 = parseInt(argument0, 10) - 1;
} else {
// If the index is dynamic, decrement it in code.
argument0 += ' - 1';
}
return argument1 + '[' + argument0 + '] = ' + argument2 + ';\n';
};
/**
* Visual Blocks Language
*
* Copyright 2012 Google Inc.
* http://blockly.googlecode.com/
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* @fileoverview Generating Arduino for logic blocks.
* @author gasolin@gmail.com (Fred Lin)
*/
'use strict';
Blockly.Arduino = Blockly.Generator.get('Arduino');
Blockly.Arduino.logic_compare = function() {
// Comparison operator.
var mode = this.getTitleValue('OP');
var operator = Blockly.Arduino.logic_compare.OPERATORS[mode];
var order = (operator == '==' || operator == '!=') ?
Blockly.Arduino.ORDER_EQUALITY : Blockly.Arduino.ORDER_RELATIONAL;
var argument0 = Blockly.Arduino.valueToCode(this, 'A', order) || '0';
var argument1 = Blockly.Arduino.valueToCode(this, 'B', order) || '0';
var code = argument0 + ' ' + operator + ' ' + argument1;
return [code, order];
};
Blockly.Arduino.logic_compare.OPERATORS = {
EQ: '==',
NEQ: '!=',
LT: '<',
LTE: '<=',
GT: '>',
GTE: '>='
};
Blockly.Arduino.logic_operation = function() {
// Operations 'and', 'or'.
var operator = (this.getTitleValue('OP') == 'AND') ? '&&' : '||';
var order = (operator == '&&') ? Blockly.Arduino.ORDER_LOGICAL_AND :
Blockly.Arduino.ORDER_LOGICAL_OR;
var argument0 = Blockly.Arduino.valueToCode(this, 'A', order) || 'false';
var argument1 = Blockly.Arduino.valueToCode(this, 'B', order) || 'false';
var code = argument0 + ' ' + operator + ' ' + argument1;
return [code, order];
};
Blockly.Arduino.logic_negate = function() {
// Negation.
var order = Blockly.Arduino.ORDER_UNARY_PREFIX;
var argument0 = Blockly.Arduino.valueToCode(this, 'BOOL', order) || 'false';
var code = '!' + argument0;
return [code, order];
};
Blockly.Arduino.logic_boolean = function() {
// Boolean values true and false.
var code = (this.getTitleValue('BOOL') == 'TRUE') ? 'true' : 'false';
return [code, Blockly.Arduino.ORDER_ATOMIC];
};
Blockly.Arduino.logic_null = function() {
var code = 'NULL';
return [code ,Blockly.Arduino.ORDER_ATOMIC];
};
This diff is collapsed.
/**
* Visual Blocks Language
*
* Copyright 2012 Google Inc.
* http://blockly.googlecode.com/
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* @fileoverview Generating Arduino for variable blocks.
* @author gasolin@gmail.com (Fred Lin)
*/
'use strict';
Blockly.Arduino = Blockly.Generator.get('Arduino');
Blockly.Arduino.procedures_defreturn = function() {
// Define a procedure with a return value.
var funcName = Blockly.Arduino.variableDB_.getName(this.getTitleValue('NAME'),
Blockly.Procedures.NAME_TYPE);
var branch = Blockly.Arduino.statementToCode(this, 'STACK');
if (Blockly.Arduino.INFINITE_LOOP_TRAP) {
branch = Blockly.Arduino.INFINITE_LOOP_TRAP.replace(/%1/g,
'\'' + this.id + '\'') + branch;
}
var returnValue = Blockly.Arduino.valueToCode(this, 'RETURN',
Blockly.Arduino.ORDER_NONE) || '';
if (returnValue) {
returnValue = ' return ' + returnValue + ';\n';
}
var returnType = returnValue ? 'Dynamic' : 'void';
var args = [];
for (var x = 0; x < this.arguments_.length; x++) {
args[x] = Blockly.Arduino.variableDB_.getName(this.arguments_[x],
Blockly.Variables.NAME_TYPE);
}
var code = returnType + ' ' + funcName + '(' + args.join(', ') + ') {\n' +
branch + returnValue + '}\n';
code = Blockly.Arduino.scrub_(this, code);
Blockly.Arduino.definitions_[funcName] = code;
return null;
};
// Defining a procedure without a return value uses the same generator as
// a procedure with a return value.
Blockly.Arduino.procedures_defnoreturn = Blockly.Arduino.procedures_defreturn;
Blockly.Arduino.procedures_callreturn = function() {
// Call a procedure with a return value.
var funcName = Blockly.Arduino.variableDB_.getName(this.getTitleValue('NAME'),
Blockly.Procedures.NAME_TYPE);
var args = [];
for (var x = 0; x < this.arguments_.length; x++) {
args[x] = Blockly.Arduino.valueToCode(this, 'ARG' + x,
Blockly.Arduino.ORDER_NONE) || 'null';
}
var code = funcName + '(' + args.join(', ') + ')';
return [code, Blockly.Arduino.ORDER_UNARY_POSTFIX];
};
Blockly.Arduino.procedures_callnoreturn = function() {
// Call a procedure with no return value.
var funcName = Blockly.Arduino.variableDB_.getName(this.getTitleValue('NAME'),
Blockly.Procedures.NAME_TYPE);
var args = [];
for (var x = 0; x < this.arguments_.length; x++) {
args[x] = Blockly.Arduino.valueToCode(this, 'ARG' + x,
Blockly.Arduino.ORDER_NONE) || 'null';
}
var code = funcName + '(' + args.join(', ') + ');\n';
return code;
};
Blockly.Arduino.procedures_ifreturn = function() {
// Conditionally return value from a procedure.
var condition = Blockly.Arduino.valueToCode(this, 'CONDITION',
Blockly.Arduino.ORDER_NONE) || 'false';
var code = 'if (' + condition + ') {\n';
if (this.hasReturnValue_) {
var value = Blockly.Arduino.valueToCode(this, 'VALUE',
Blockly.Arduino.ORDER_NONE) || 'null';
code += ' return ' + value + ';\n';
} else {
code += ' return;\n';
}
code += '}\n';
return code;
};
/**
* Visual Blocks Language
*
* Copyright 2012 Google Inc.
* http://blockly.googlecode.com/
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* @fileoverview Generating Arduino for text blocks.
*/
'use strict';
goog.provide('Blockly.Arduino.text');
goog.require('Blockly.Arduino');
Blockly.Arduino['text'] = function(block) {
// Text value.
var code = Blockly.Arduino.quote_(block.getFieldValue('TEXT'));
return [code, Blockly.Arduino.ORDER_ATOMIC];
};
Blockly.Arduino['text_join'] = function(block) {
// Create a string made up of any number of elements of any type.
var code;
if (block.itemCount_ == 0) {
return ['\'\'', Blockly.Arduino.ORDER_ATOMIC];
} else if (block.itemCount_ == 1) {
var argument0 = Blockly.Arduino.valueToCode(block, 'ADD0',
Blockly.Arduino.ORDER_UNARY_POSTFIX) || '\'\'';
code = 'String(' + argument0 + ')';
return [code, Blockly.Arduino.ORDER_UNARY_POSTFIX];
} else {
code = [];
code[0] = (Blockly.Arduino.valueToCode(block, 'ADD0',
Blockly.Arduino.ORDER_NONE) || '\'\'');
for (var n = 1; n < block.itemCount_; n++) {
code[n] = '+' + (Blockly.Arduino.valueToCode(block, 'ADD' + n,
Blockly.Arduino.ORDER_NONE) || '\'\'');
}
code = code.join('');
return [code, Blockly.Arduino.ORDER_UNARY_POSTFIX];
}
};
Blockly.Arduino['text_append'] = function(block) {
// Append to a variable in place.
var varName = Blockly.Arduino.variableDB_.getName(
block.getFieldValue('VAR'), Blockly.Variables.NAME_TYPE);
var argument0 = Blockly.Arduino.valueToCode(block, 'TEXT',
Blockly.Arduino.ORDER_UNARY_POSTFIX) || '\'\'';
return varName + ' = new StringBuffer(' + varName +
').add(' + argument0 + ').toString();\n';
};
Blockly.Arduino.text_length = function() {
// String length.
var argument0 = Blockly.Arduino.valueToCode(this, 'VALUE',
Blockly.Arduino.ORDER_UNARY_POSTFIX) || '\'\'';
return [argument0 + '.length', Blockly.Arduino.ORDER_UNARY_POSTFIX];
};
Blockly.Arduino.text_isEmpty = function() {
// Is the string null?
var argument0 = Blockly.Arduino.valueToCode(this, 'VALUE',
Blockly.Arduino.ORDER_UNARY_POSTFIX) || '\'\'';
return [argument0 + '.isEmpty()', Blockly.Arduino.ORDER_UNARY_POSTFIX];
};
Blockly.Arduino.text_endString = function() {
// Return a leading or trailing substring.
var first = this.getTitleValue('END') == 'FIRST';
var code;
if (first) {
var argument0 = Blockly.Arduino.valueToCode(this, 'NUM',
Blockly.Arduino.ORDER_NONE) || '1';
var argument1 = Blockly.Arduino.valueToCode(this, 'TEXT',
Blockly.Arduino.ORDER_UNARY_POSTFIX) || '\'\'';
code = argument1 + '.substring(0, ' + argument0 + ')';
} else {
if (!Blockly.Arduino.definitions_['text_tailString']) {
var functionName = Blockly.Arduino.variableDB_.getDistinctName(
'text_tailString', Blockly.Generator.NAME_TYPE);
Blockly.Arduino.text_endString.text_tailString = functionName;
var func = [];
func.push('String ' + functionName + '(n, myString) {');
func.push(' // Return a trailing substring of n characters.');
func.push(' return myString.substring(myString.length - n);');
func.push('}');
Blockly.Arduino.definitions_['text_tailString'] = func.join('\n');
}
var argument0 = Blockly.Arduino.valueToCode(this, 'NUM',
Blockly.Arduino.ORDER_NONE) || '1';
var argument1 = Blockly.Arduino.valueToCode(this, 'TEXT',
Blockly.Arduino.ORDER_NONE) || '\'\'';
code = Blockly.Arduino.text_endString.text_tailString +
'(' + argument0 + ', ' + argument1 + ')';
}
return [code, Blockly.Arduino.ORDER_UNARY_POSTFIX];
};
Blockly.Arduino.text_indexOf = function() {
// Search the text for a substring.
var operator = this.getTitleValue('END') == 'FIRST' ?
'indexOf' : 'lastIndexOf';
var argument0 = Blockly.Arduino.valueToCode(this, 'FIND',
Blockly.Arduino.ORDER_NONE) || '\'\'';
var argument1 = Blockly.Arduino.valueToCode(this, 'VALUE',
Blockly.Arduino.ORDER_UNARY_POSTFIX) || '\'\'';
var code = argument1 + '.' + operator + '(' + argument0 + ') + 1';
return [code, Blockly.Arduino.ORDER_UNARY_POSTFIX];
};
Blockly.Arduino.text_charAt = function() {
// Get letter at index.
var argument0 = Blockly.Arduino.valueToCode(this, 'AT',
Blockly.Arduino.ORDER_NONE) || '1';
var argument1 = Blockly.Arduino.valueToCode(this, 'VALUE',
Blockly.Arduino.ORDER_UNARY_POSTFIX) || '\'\'';
// Blockly uses one-based arrays.
if (argument0.match(/^-?\d+$/)) {
// If the index is a naked number, decrement it right now.
argument0 = parseInt(argument0, 10) - 1;
} else {
// If the index is dynamic, decrement it in code.
argument0 += ' - 1';
}
var code = argument1 + '[' + argument0 + ']';
return [code, Blockly.Arduino.ORDER_UNARY_POSTFIX];
};
Blockly.Arduino.text_changeCase = function() {
// Change capitalization.
var mode = this.getTitleValue('CASE');
var operator = Blockly.Arduino.text_changeCase.OPERATORS[mode];
var code;
if (operator) {
// Upper and lower case are functions built into Dart.
var argument0 = Blockly.Arduino.valueToCode(this, 'TEXT',
Blockly.Arduino.ORDER_UNARY_POSTFIX) || '\'\'';
code = argument0 + operator;
} else {
if (!Blockly.Arduino.definitions_['toTitleCase']) {
// Title case is not a native Dart function. Define one.
var functionName = Blockly.Arduino.variableDB_.getDistinctName(
'text_toTitleCase', Blockly.Generator.NAME_TYPE);
Blockly.Arduino.text_changeCase.toTitleCase = functionName;
var func = [];
func.push('String ' + functionName + '(str) {');
func.push(' RegExp exp = const RegExp(r\'\\b\');');
func.push(' List<String> list = str.split(exp);');
func.push(' String title = \'\';');
func.push(' for (String part in list) {');
func.push(' if (part.length > 0) {');
func.push(' title.add(part[0].toUpperCase());');
func.push(' if (part.length > 0) {');
func.push(' title.add(part.substring(1).toLowerCase());');
func.push(' }');
func.push(' }');
func.push(' }');
func.push(' return title.toString();');
func.push('}');
Blockly.Arduino.definitions_['toTitleCase'] = func.join('\n');
}
var argument0 = Blockly.Arduino.valueToCode(this, 'TEXT',
Blockly.Arduino.ORDER_NONE) || '\'\'';
code = Blockly.Arduino.text_changeCase.toTitleCase + '(' + argument0 + ')';
}
return [code, Blockly.Arduino.ORDER_UNARY_POSTFIX];
};
Blockly.Arduino.text_changeCase.OPERATORS = {
UPPERCASE: '.toUpperCase()',
LOWERCASE: '.toLowerCase()',
TITLECASE: null
};
Blockly.Arduino.text_trim = function() {
// Trim spaces.
var mode = this.getTitleValue('MODE');
var operator = Blockly.Arduino.text_trim.OPERATORS[mode];
var argument0 = Blockly.Arduino.valueToCode(this, 'TEXT',
Blockly.Arduino.ORDER_UNARY_POSTFIX) || '\'\'';
return [argument0 + operator, Blockly.Arduino.ORDER_UNARY_POSTFIX];
};
Blockly.Arduino.text_trim.OPERATORS = {
LEFT: '.replaceFirst(new RegExp(r\'^\\s+\'), \'\')',
RIGHT: '.replaceFirst(new RegExp(r\'\\s+$\'), \'\')',
BOTH: '.trim()'
};
Blockly.Arduino.text_print = function() {
// Print statement.
var argument0 = Blockly.Arduino.valueToCode(this, 'TEXT',
Blockly.Arduino.ORDER_NONE) || '\'\'';
return 'print(' + argument0 + ');\n';
};
Blockly.Arduino.text_prompt = function() {
// Prompt function.
Blockly.Arduino.definitions_['import_dart_html'] = '#import(\'dart:html\');';
var msg = Blockly.Arduino.quote_(this.getTitleValue('TEXT'));
var code = 'window.prompt(' + msg + ', \'\')';
var toNumber = this.getTitleValue('TYPE') == 'NUMBER';
if (toNumber) {
code = 'Math.parseDouble(' + code + ')';
}
return [code, Blockly.Arduino.ORDER_UNARY_POSTFIX];
};
/**
* Visual Blocks Language
*
* Copyright 2012 Google Inc.
* http://blockly.googlecode.com/
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* @fileoverview Generating Arduino code for variables blocks.
*/
'use strict';
goog.provide('Blockly.Arduino.variables');
goog.require('Blockly.Arduino');
//if (!Blockly.Language) Blockly.Language = {};
//Blockly.Language.variables_get = {
// // Variable getter.
// category: null, // Variables are handled specially.
// helpUrl: Blockly.LANG_VARIABLES_GET_HELPURL,
// init: function() {
// this.setColour(330);
// this.appendDummyInput("")
// .appendTitle(Blockly.LANG_VARIABLES_GET_TITLE_1)
// .appendTitle(new Blockly.FieldVariable(
// Blockly.LANG_VARIABLES_GET_ITEM), 'VAR');
// this.setOutput(true, null);
// this.setTooltip(Blockly.LANG_VARIABLES_GET_TOOLTIP_1);
// },
// getVars: function() {
// return [this.getTitleValue('VAR')];
// },
// renameVar: function(oldName, newName) {
// if (Blockly.Names.equals(oldName, this.getTitleValue('VAR'))) {
// this.setTitleValue(newName, 'VAR');
// }
// }
//};
//Blockly.Language.variables_declare = {
// // Variable setter.
// category: null, // Variables are handled specially.
// helpUrl: Blockly.LANG_VARIABLES_SET_HELPURL,
// init: function() {
// this.setColour(330);
// this.appendValueInput('VALUE', null)
// .appendTitle('Declare')
// .appendTitle(new Blockly.FieldVariable(
// Blockly.LANG_VARIABLES_SET_ITEM), 'VAR')
// .appendTitle("as")
// .appendTitle(new Blockly.FieldDropdown([["Number", "int"]]), "TYPE")
// .appendTitle("value");
// this.setPreviousStatement(true);
// this.setNextStatement(true);
// this.setTooltip(Blockly.LANG_VARIABLES_SET_TOOLTIP_1);
// },
// getVars: function() {
// return [this.getTitleValue('VAR')];
// },
// renameVar: function(oldName, newName) {
// if (Blockly.Names.equals(oldName, this.getTitleValue('VAR'))) {
// this.setTitleValue(newName, 'VAR');
// }
// }
//};
//Blockly.Language.variables_set = {
// // Variable setter.
// category: null, // Variables are handled specially.
// helpUrl: Blockly.LANG_VARIABLES_SET_HELPURL,
// init: function() {
// this.setColour(330);
// this.appendValueInput('VALUE')
// .appendTitle(Blockly.LANG_VARIABLES_SET_TITLE_1)
// .appendTitle(new Blockly.FieldVariable(
// Blockly.LANG_VARIABLES_SET_ITEM), 'VAR');
// this.setPreviousStatement(true);
// this.setNextStatement(true);
// this.setTooltip(Blockly.LANG_VARIABLES_SET_TOOLTIP_1);
// },
// getVars: function() {
// return [this.getTitleValue('VAR')];
// },
// renameVar: function(oldName, newName) {
// if (Blockly.Names.equals(oldName, this.getTitleValue('VAR'))) {
// this.setTitleValue(newName, 'VAR');
// }
// }
//};
/**
* @fileoverview Variable blocks for Arduino.
* @author gasolin@gmail.com (Fred Lin)
*/
//Blockly.Arduino = Blockly.Generator.get('Arduino');
Blockly.Arduino['variables_get'] = function(block) {
// Variable getter.
var code = Blockly.Arduino.variableDB_.getName(block.getFieldValue('VAR'),
Blockly.Variables.NAME_TYPE);
return [code, Blockly.Arduino.ORDER_ATOMIC];
};
//Blockly.Arduino.variables_declare = function() {
// // Variable setter.
// var dropdown_type = this.getTitleValue('TYPE');
// //TODO: settype to variable
// var argument0 = Blockly.Arduino.valueToCode(this, 'VALUE',
// Blockly.Arduino.ORDER_ASSIGNMENT) || '0';
// var varName = Blockly.Arduino.variableDB_.getName(this.getTitleValue('VAR'),
// Blockly.Variables.NAME_TYPE);
// Blockly.Arduino.setups_['setup_var'+varName] = varName + ' = ' + argument0 + ';\n';
// return '';
//};
Blockly.Arduino['variables_set'] = function(block) {
// Variable setter.
var argument0 = Blockly.Arduino.valueToCode(block, 'VALUE',
Blockly.Arduino.ORDER_ASSIGNMENT) || '0';
var varName = Blockly.Arduino.variableDB_.getName(
block.getFieldValue('VAR'), Blockly.Variables.NAME_TYPE);
return varName + ' = ' + argument0 + ';\n';
};
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment