"use strict";

/* additional math */
Blockly.Blocks['math_degrad'] = {
  init: function init() {
    this.appendValueInput("convert").setCheck(null).appendField(new Blockly.FieldDropdown([[Blockly.Msg.math_degrad_rad, "radians"], [Blockly.Msg.math_degrad_deg, "degrees"]]), "rad_deg");
    this.setOutput(true, null);
    this.setColour("#5472ea");
    // this.setTooltip("");
    this.setHelpUrl("");
    var thisBlock = this;
    this.setTooltip(function () {
      var mode = thisBlock.getFieldValue('rad_deg');
      var TOOLTIPS = {
        'radians': Blockly.Msg.Math_Degrad_RAD_TOOLTIP,
        'degrees': Blockly.Msg.Math_Degrad_DEG_TOOLTIP
      };
      return TOOLTIPS[mode];
    });
  }
};

Blockly.Python['math_degrad'] = function (block) {
  var dropdown_rad_deg = block.getFieldValue('rad_deg');
  var value_convert = Blockly.Python.valueToCode(block, 'convert', Blockly.Python.ORDER_ATOMIC); // TODO: Assemble Python into code variable.

  Blockly.Python.definitions_['import_math'] = 'import math\n';
  var code = 'math.' + dropdown_rad_deg + '(' + value_convert + ')'; // TODO: Change ORDER_NONE to the correct strength.

  return [code, Blockly.Python.ORDER_NONE];
};
/* Serial Comm. */


Blockly.Blocks['serial_comm_print'] = {
  init: function init() {
    this.appendValueInput("serial_comm_input").setCheck("String").appendField(Blockly.Msg.serialcomm_print);
    this.setInputsInline(false);
    this.setPreviousStatement(true, null);
    this.setNextStatement(true, null);
    this.setColour("#22b845");
    this.setTooltip(Blockly.Msg.serial_Comm_Print_TOOLTIP);
    this.setHelpUrl("");
  }
};

Blockly.Python['serial_comm_print'] = function (block) {
  var value_name = Blockly.Python.valueToCode(block, 'serial_comm_input', Blockly.Python.ORDER_ATOMIC); // TODO: Assemble Python into code variable.

  var code = 'print(' + value_name + ')\n';
  return code;
};
/*
INPUT & OUTPUT
*/


var ESP32_IO_COLOR = "#ff8027";
Blockly.Blocks['esp32_main_controller_text_print'] = {
  init: function init() {
    this.jsonInit({
      "message0": Blockly.Msg.TEXT_PRINT_TITLE,
      "args0": [{
        "type": "input_value",
        "name": "TEXT"
      }],
      "previousStatement": null,
      "nextStatement": null,
      "colour": "#33cc99",
      "tooltip": Blockly.Msg.TEXT_PRINT_TOOLTIP,
      "helpUrl": Blockly.Msg.TEXT_PRINT_HELPURL
    });
  }
};

Blockly.Python['esp32_main_controller_text_print'] = function (block) {
  // Print statement.
  var msg = Blockly.Python.valueToCode(block, 'TEXT', Blockly.Python.ORDER_NONE) || '___';
  return 'print(' + msg + ')\n';
};

Blockly.Blocks['esp32_main_controller_text'] = {
  init: function init() {
    this.setHelpUrl(Blockly.Msg.TEXT_TEXT_HELPURL);
    this.setColour("#33cc99");
    this.appendDummyInput().appendField(this.newQuote_(true)).appendField(new Blockly.FieldTextInput(''), 'TEXT').appendField(this.newQuote_(false));
    this.setOutput(true, 'String'); // Assign 'this' to a variable for use in the tooltip closure below.

    var thisBlock = this; // Text block is trivial.  Use tooltip of parent block if it exists.

    this.setTooltip(function () {
      var parent = thisBlock.getParent();
      return parent && parent.getInputsInline() && parent.tooltip || Blockly.Msg.TEXT_TEXT_TOOLTIP;
    });
  },
  newQuote_: function newQuote_(open) {
    if (open == this.RTL) {
      var file = 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAwAAAAKCAQAAAAqJXdxAAAAqUlEQVQI1z3KvUpCcRiA8ef9E4JNHhI0aFEacm1o0BsI0Slx8wa8gLauoDnoBhq7DcfWhggONDmJJgqCPA7neJ7p934EOOKOnM8Q7PDElo/4x4lFb2DmuUjcUzS3URnGib9qaPNbuXvBO3sGPHJDRG6fGVdMSeWDP2q99FQdFrz26Gu5Tq7dFMzUvbXy8KXeAj57cOklgA+u1B5AoslLtGIHQMaCVnwDnADZIFIrXsoXrgAAAABJRU5ErkJggg==';
    } else {
      var file = 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAwAAAAKCAQAAAAqJXdxAAAAn0lEQVQI1z3OMa5BURSF4f/cQhAKjUQhuQmFNwGJEUi0RKN5rU7FHKhpjEH3TEMtkdBSCY1EIv8r7nFX9e29V7EBAOvu7RPjwmWGH/VuF8CyN9/OAdvqIXYLvtRaNjx9mMTDyo+NjAN1HNcl9ZQ5oQMM3dgDUqDo1l8DzvwmtZN7mnD+PkmLa+4mhrxVA9fRowBWmVBhFy5gYEjKMfz9AylsaRRgGzvZAAAAAElFTkSuQmCC';
    }

    return new Blockly.FieldImage(file, 12, 12, '"');
  }
};

Blockly.Python['esp32_main_controller_text'] = function (block) {
  // Text value.
  var code = Blockly.Python.quote_(block.getFieldValue('TEXT'));
  return [code, Blockly.Python.ORDER_ATOMIC];
};

Blockly.Blocks['esp32_main_controller_io_from_digital_pin'] = {
  init: function init() {
    this.appendDummyInput().appendField("").appendField(new Blockly.FieldDropdown([[Blockly.Msg.time_iot_module, "1"], [Blockly.Msg.time_ai_module, "2"]]), "digital_get_type").appendField(Blockly.Msg.digital_get);
    this.appendValueInput("digital_pin_input").setCheck(null);
    this.appendDummyInput().appendField(Blockly.Msg.digital_get_value);
    this.setInputsInline(true);
    this.setOutput(true, null);
    this.setColour(ESP32_IO_COLOR);
    var thisBlock = this;
    this.setTooltip(function () {
      var mode = thisBlock.getFieldValue('digital_get_type');
      var TOOLTIPS = {
        '1': Blockly.Msg.Esp32_Main_Controller_Io_From_Digital_Pin_TOOLTIP.replace('%1', Blockly.Msg.time_iot_module),
        '2': Blockly.Msg.Esp32_Main_Controller_Io_From_Digital_Pin_TOOLTIP.replace('%1', Blockly.Msg.time_ai_module)
      };
      return TOOLTIPS[mode];
    });
    this.setHelpUrl("");
  }
};

Blockly.Python['esp32_main_controller_io_from_digital_pin'] = function (block) {
  var value_name = Blockly.Python.valueToCode(block, 'digital_pin_input', Blockly.Python.ORDER_ATOMIC);
  var timer_type = block.getFieldValue('digital_get_type'); // TODO: Assemble Python into code variable.
  // TODO: Assemble Python into code variable.

  var code = '';

  if (timer_type == 2) {
    Blockly.Python.definitions_['import_setup'] = '' + 'from fpioa_manager import *\n' + 'from Maix import FPIOA,GPIO\n' + '';
    var aa = 'FPIOA().set_function(' + value_name + ',fm.fpioa.GPIOHS' + value_name + ')\n' + '_read_ai_ext_pin' + value_name + ' = GPIO(GPIO.GPIOHS' + value_name + ', GPIO.IN,GPIO.PULL_UP)\n';
    Blockly.Python.addVariable('_read_ai_ext_pin' + value_name, aa, true);
    code = '_read_ai_ext_pin' + value_name + '.value()';
  } else if (timer_type == 1) {
    Blockly.Python.definitions_['import_setup'] = '' + 'from machine import Pin\n' + '';

    var _aa = '_PIN_IN_' + value_name + ' = Pin(' + value_name + ', Pin.IN)\n';

    Blockly.Python.addVariable('_PIN_IN_' + value_name, _aa, true);
    code = '_PIN_IN_' + value_name + '.value()';
  } // TODO: Change ORDER_NONE to the correct strength.


  return [code, Blockly.Python.ORDER_CONDITIONAL];
};

Blockly.Blocks['esp32_main_controller_io_high_low'] = {
  init: function init() {
    this.appendDummyInput().appendField(new Blockly.FieldDropdown([[Blockly.Msg.io_high, "1"], [Blockly.Msg.io_low, "0"]]), "high_low");
    this.setInputsInline(true);
    this.setOutput(true, null);
    this.setColour(ESP32_IO_COLOR);
    this.setHelpUrl("");
    var thisBlock = this;
    this.setTooltip(function () {
      var mode = thisBlock.getFieldValue('high_low');
      var TOOLTIPS = {
        '1': Blockly.Msg.Esp32_Main_Controller_Io_High_Low_TOOLTIP.replace('%1', Blockly.Msg.io_high),
        '0': Blockly.Msg.Esp32_Main_Controller_Io_High_Low_TOOLTIP.replace('%1', Blockly.Msg.io_low)
      };
      return TOOLTIPS[mode];
    });
  }
};

Blockly.Python['esp32_main_controller_io_high_low'] = function (block) {
  var dropdown_name = block.getFieldValue('high_low'); // TODO: Assemble Python into code variable.

  var code = dropdown_name; // TODO: Change ORDER_NONE to the correct strength.

  return [code, Blockly.Python.ORDER_NONE];
};

Blockly.Blocks['esp32_main_controller_io_set_digital_pin'] = {
  init: function init() {
    this.appendDummyInput().appendField("").appendField(new Blockly.FieldDropdown([[Blockly.Msg.time_iot_module, "1"], [Blockly.Msg.time_ai_module, "2"]]), "digital_set_type").appendField(Blockly.Msg.digital_set);
    this.appendValueInput("digital_pin_input").setCheck(null);
    this.appendDummyInput().appendField(Blockly.Msg.digital_set_as);
    this.appendValueInput("high_low").setCheck(null);
    this.setInputsInline(true);
    this.setPreviousStatement(true, null);
    this.setNextStatement(true, null);
    this.setColour(ESP32_IO_COLOR);
    this.setHelpUrl("");
    var thisBlock = this;
    this.setTooltip(function () {
      var mode = thisBlock.getFieldValue('digital_set_type');
      var TOOLTIPS = {
        '1': Blockly.Msg.Esp32_Main_Controller_Io_Set_Digital_Pin_TOOLTIP.replace('%1', Blockly.Msg.time_iot_module),
        '2': Blockly.Msg.Esp32_Main_Controller_Io_Set_Digital_Pin_TOOLTIP.replace('%1', Blockly.Msg.time_ai_module)
      };
      return TOOLTIPS[mode];
    });
  }
};

Blockly.Python['esp32_main_controller_io_set_digital_pin'] = function (block) {
  var value_name1 = Blockly.Python.valueToCode(block, 'digital_pin_input', Blockly.Python.ORDER_ATOMIC);
  var value_name2 = Blockly.Python.valueToCode(block, 'high_low', Blockly.Python.ORDER_ATOMIC);
  var timer_type = block.getFieldValue('digital_set_type');
  var code = "";

  if (timer_type == 1) {
    // TODO: Assemble Python into code variable.
    Blockly.Python.definitions_['import_setup'] = '' + 'from machine import Pin\n' + '';
    var variable = '_PIN_OUT_' + value_name1 + ' = Pin(' + value_name1 + ', Pin.OUT)\n';
    Blockly.Python.addVariable('_PIN_OUT_' + value_name1, variable, true);
    code = '_PIN_OUT_' + value_name1 + '.value' + value_name2 + '\n';
  } else if (timer_type == 2) {
    Blockly.Python.definitions_['import_setup'] = '' + 'from fpioa_manager import *\n' + 'from Maix import GPIO\n' + '';

    var _variable = 'fm.register(' + value_name1 + ',fm.fpioa.GPIOHS' + value_name1 + ')\n' + '_set_ai_ext_pin' + value_name1 + ' = GPIO(GPIO.GPIOHS' + value_name1 + ', GPIO.OUT)\n';

    Blockly.Python.addVariable('_set_ai_ext_pin' + value_name1, _variable, true);
    code = '_set_ai_ext_pin' + value_name1 + '.value(' + value_name2 + ')\n';
  }

  return code;
};

Blockly.Blocks['esp32_main_controller_io_from_analog_pin'] = {
  init: function init() {
    this.appendDummyInput().appendField(Blockly.Msg.analog_get);
    this.appendValueInput("analog_pin_input").setCheck(null);
    this.appendDummyInput().appendField(Blockly.Msg.analog_get_value);
    this.setInputsInline(true);
    this.setOutput(true, null);
    this.setColour(ESP32_IO_COLOR);
    this.setTooltip("");
    this.setHelpUrl("");
  }
};

Blockly.Python['esp32_main_controller_io_from_analog_pin'] = function (block) {
  var value_name = Blockly.Python.valueToCode(block, 'analog_pin_input', Blockly.Python.ORDER_ATOMIC); // TODO: Assemble Python into code variable.

  Blockly.Python.addVariable('_PWM_PIN_IN_' + value_name, '', true);
  Blockly.Python.definitions_['import_setup'] = '' + 'from machine import Pin, ADC\n\n' + '_PWM_PIN_IN_' + value_name + ' = ADC(Pin(' + value_name + '))\n' + '_PWM_PIN_IN_' + value_name + '.atten(ADC.ATTN_11DB)\n' + '';
  var code = '_PWM_PIN_IN_' + value_name + '.read()'; // TODO: Change ORDER_NONE to the correct strength.

  return [code, Blockly.Python.ORDER_CONDITIONAL];
};

Blockly.Blocks['esp32_main_controller_io_set_analog_pin'] = {
  init: function init() {
    this.appendDummyInput().appendField(Blockly.Msg.analog_set);
    this.appendValueInput("analog_pin_input").setCheck(null);
    this.appendDummyInput().appendField(Blockly.Msg.analog_set_freq);
    this.appendValueInput("frequency").setCheck(null);
    this.appendDummyInput().appendField(Blockly.Msg.analog_set_pwm);
    this.appendValueInput("pwm").setCheck(null);
    this.setInputsInline(true);
    this.setPreviousStatement(true, null);
    this.setNextStatement(true, null);
    this.setColour(ESP32_IO_COLOR);
    this.setHelpUrl("");
    var thisBlock = this;
    this.setTooltip(function () {
      var mode = thisBlock.getFieldValue('LED');
      var TOOLTIPS = {
        'LED': Blockly.Msg.Esp32_Main_Controller_Io_Set_Analog_Pin_TOOLTIP.replace('%1', Blockly.Msg.led)
      };
      return TOOLTIPS[mode];
    });
  }
};

Blockly.Python['esp32_main_controller_io_set_analog_pin'] = function (block) {
  var value_name1 = Blockly.Python.valueToCode(block, 'analog_pin_input', Blockly.Python.ORDER_ATOMIC);
  var value_name2 = Blockly.Python.valueToCode(block, 'pwm', Blockly.Python.ORDER_ATOMIC);
  var value_name3 = Blockly.Python.valueToCode(block, 'frequency', Blockly.Python.ORDER_ATOMIC);
  Blockly.Python.addVariable('_PWM_PIN_OUT_' + value_name1, '', true); // TODO: Assemble Python into code variable.

  Blockly.Python.definitions_['import_setup'] = '' + 'from machine import Pin, PWM\n' + '_PWM_PIN_OUT_' + value_name1 + ' = PWM(Pin(' + value_name1 + '), freq=' + value_name3 + ')\n' + '';
  var code = '_PWM_PIN_OUT_' + value_name1 + '.freq(' + value_name3 + ')\n' + '_PWM_PIN_OUT_' + value_name1 + '.duty(' + value_name2 + ')\n';
  return code;
};
/*
Button
*/


Blockly.Blocks['esp32_main_controller_button_read_pressed'] = {
  init: function init() {
    // this.appendDummyInput()
    //    .appendField(new Blockly.FieldImage("blockly/media/button_pressed.png", 38, 38, { alt: "*", flipRtl: "FALSE" }));
    this.appendDummyInput().appendField(Blockly.Msg.ESP32BUTTON).appendField(new Blockly.FieldDropdown([["P1", "button_type_1"], ["P2", "button_type_2"]]), "button_type").appendField(Blockly.Msg.ESP32PRESSED);
    this.setOutput(true, null);
    this.setColour("#e8795b");
    var thisBlock = this;
    this.setTooltip(function () {
      var mode = thisBlock.getFieldValue('button_type');
      var TOOLTIPS = {
        'button_type_1': Blockly.Msg.Esp32_Main_Controller_Button_Read_Pressed_TOOLTIP.replace('%1', "P1"),
        'button_type_2': Blockly.Msg.Esp32_Main_Controller_Button_Read_Pressed_TOOLTIP.replace('%1', "P2")
      };
      return TOOLTIPS[mode];
    });
    this.setHelpUrl("");
  }
};

Blockly.Python['esp32_main_controller_button_read_pressed'] = function (block) {
  Blockly.Python.definitions_['import_Pin'] = 'from machine import Pin';
  var _type = block.getField('button_type').text_;

  var _button_state = block.getFieldValue('button_state');

  var _num = _type == "P1" ? "34" : "35";

  var _upstr = "";

  if (_type == "P2") {
    _upstr = ",Pin.PULL_UP";
  }

  Blockly.Python.addVariable('_' + _type, '_' + _type + ' = Pin(' + _num + ', Pin.IN' + _upstr + ')', true);
  var code = '(_' + _type + '.value() == ' + 1 + ')';
  return [code, Blockly.Python.ORDER_CONDITIONAL];
};

Blockly.Blocks['esp32_main_controller_button_read_released'] = {
  init: function init() {
    // this.appendDummyInput()
    //    .appendField(new Blockly.FieldImage("blockly/media/button_released.png", 38, 38, { alt: "*", flipRtl: "FALSE" }));
    this.appendDummyInput().appendField(Blockly.Msg.ESP32BUTTON).appendField(new Blockly.FieldDropdown([["P1", "button_type_1"], ["P2", "button_type_2"]]), "button_type").appendField(Blockly.Msg.ESP32RELEASED);
    this.setOutput(true, null);
    this.setColour("#e8795b");
    var thisBlock = this;
    this.setTooltip(function () {
      var mode = thisBlock.getFieldValue('button_type');
      var TOOLTIPS = {
        'button_type_1': Blockly.Msg.Esp32_Main_Controller_Button_Read_Released_TOOLTIP.replace('%1', "P1"),
        'button_type_2': Blockly.Msg.Esp32_Main_Controller_Button_Read_Released_TOOLTIP.replace('%1', "P2")
      };
      return TOOLTIPS[mode];
    });
    this.setHelpUrl("");
  }
};

Blockly.Python['esp32_main_controller_button_read_released'] = function (block) {
  Blockly.Python.definitions_['import_Pin'] = 'from machine import Pin';
  var _type = block.getField('button_type').text_;

  var _button_state = block.getFieldValue('button_state');

  var _num = _type == "P1" ? "34" : "35";

  var _upstr = "";

  if (_type == "P2") {
    _upstr = ",Pin.PULL_UP";
  }

  Blockly.Python.addVariable('_' + _type, '_' + _type + ' = Pin(' + _num + ', Pin.IN' + _upstr + ')', true);
  var code = '(_' + _type + '.value() == ' + 0 + ')';
  return [code, Blockly.Python.ORDER_CONDITIONAL];
};

Blockly.Blocks['esp32_main_controller_button_read_value'] = {
  init: function init() {
    this.appendDummyInput().appendField(Blockly.Msg.basic_button_read_value).appendField(new Blockly.FieldDropdown([["P1", "button_type_1"], ["P2", "button_type_2"]]), "button_type").appendField(Blockly.Msg.basic_button_read_value_after);
    this.setInputsInline(true);
    this.setOutput(true, null);
    this.setColour("#e8795b");
    var thisBlock = this;
    this.setTooltip(function () {
      var mode = thisBlock.getFieldValue('button_type');
      var TOOLTIPS = {
        'button_type_1': Blockly.Msg.Esp32_Main_Controller_Button_Read_Value_TOOLTIP.replace('%1', "P1"),
        'button_type_2': Blockly.Msg.Esp32_Main_Controller_Button_Read_Value_TOOLTIP.replace('%1', "P2")
      };
      return TOOLTIPS[mode];
    });
    this.setHelpUrl("");
  }
};

Blockly.Python['esp32_main_controller_button_read_value'] = function (block) {
  Blockly.Python.definitions_['import_Pin'] = 'from machine import Pin';
  var _type = block.getField('button_type').text_; // TODO: Assemble Python into code variable.

  var _num = _type == "P1" ? "34" : "35";

  var _upstr = "";

  if (_type == "P2") {
    _upstr = ",Pin.PULL_UP";
  }

  Blockly.Python.addVariable('_' + _type, '_' + _type + ' = Pin(' + _num + ', Pin.IN' + _upstr + ')', true);
  var code = '_' + _type + '.value()'; // TODO: Change ORDER_NONE to the correct strength.

  return [code, Blockly.Python.ORDER_NONE];
};
/*
Blockly.Python['esp32_main_controller_button_read'] = function (block) {
    Blockly.Python.definitions_['import_Pin'] = 'from machine import Pin';
    var _type = block.getField('button_type').text_;
    var _button_state = block.getFieldValue('button_state');
    var _num = _type == "1" ? "36" : "22";
    var _upstr = "";
    if (_type == "2") { _upstr = ",Pin.PULL_UP"; }
    Blockly.Python.addVariable('p' + _type, 'p' + _type + ' = Pin(' + _num + ', Pin.IN' + _upstr + ')', true);
    var code = '(p' + _type + '.value() == ' + (_button_state == "button_state_pressed" ? "1" : "0") + ')';
    return [code, Blockly.Python.ORDER_CONDITIONAL];
};
*/

/*
Dialer
*/


Blockly.Blocks['esp32_main_controller_dial_switch_read_pressed'] = {
  init: function init() {
    this.appendDummyInput().appendField(Blockly.Msg.ESP32DIALSWITCH).appendField(new Blockly.FieldDropdown([[Blockly.Msg.ESP32DIALER_LEFT, "switch_type_left"], [Blockly.Msg.ESP32DIALER_MIDDLE, "switch_type_middle"], [Blockly.Msg.ESP32DIALER_RIGHT, "switch_type_right"]]), "switch_type").appendField(Blockly.Msg.ESP32PRESSED);
    this.setOutput(true, null);
    this.setColour("#e8795b");
    this.setTooltip("");
    this.setHelpUrl("");
  }
};

Blockly.Python['esp32_main_controller_dial_switch_read_pressed'] = function (block) {
  Blockly.Python.definitions_['import_Pin'] = 'from machine import Pin';

  var _type = block.getFieldValue('switch_type');

  var _num = "34";
  var _upstr = "";
  var _button_type = "";

  if (_type == "switch_type_left") {
    var _num = "34";
    _button_type = "Left";
  } else if (_type == "switch_type_middle") {
    var _num = "19";
    _upstr = ", Pin.PULL_UP";
    _button_type = "Middle";
  } else if (_type == "switch_type_right") {
    var _num = "35";
    _button_type = "Right";
  } // Blockly.Python.addVariable("dialer_type", 'p' + _button_type + ' = Pin(' + _num + ', Pin.IN' + _upstr + ')');


  Blockly.Python.addVariable("pLeft", 'pLeft = Pin(38, Pin.IN)');
  Blockly.Python.addVariable("pMiddle", 'pMiddle = Pin(19, Pin.IN)');
  Blockly.Python.addVariable("pRight", 'pRight = Pin(35, Pin.IN)');
  var code = '(p' + _button_type + '.value() == 1)';
  return [code, Blockly.Python.ORDER_CONDITIONAL];
};

Blockly.Blocks['esp32_main_controller_dial_switch_read_released'] = {
  init: function init() {
    this.appendDummyInput().appendField(Blockly.Msg.ESP32DIALSWITCH).appendField(new Blockly.FieldDropdown([[Blockly.Msg.ESP32DIALER_LEFT, "switch_type_left"], [Blockly.Msg.ESP32DIALER_MIDDLE, "switch_type_middle"], [Blockly.Msg.ESP32DIALER_RIGHT, "switch_type_right"]]), "switch_type").appendField(Blockly.Msg.ESP32RELEASED);
    this.setOutput(true, null);
    this.setColour("#e8795b");
    this.setTooltip("");
    this.setHelpUrl("");
  }
};

Blockly.Python['esp32_main_controller_dial_switch_read_released'] = function (block) {
  Blockly.Python.definitions_['import_Pin'] = 'from machine import Pin';

  var _type = block.getFieldValue('switch_type');

  var _state = block.getFieldValue('switch_state');

  var _num = "34";
  var _upstr = "";
  var _button_type = "";

  if (_type == "switch_type_left") {
    var _num = "34";
    _button_type = "Left";
  } else if (_type == "switch_type_middle") {
    var _num = "19";
    _upstr = ", Pin.PULL_UP";
    _button_type = "Middle";
  } else if (_type == "switch_type_right") {
    var _num = "35";
    _button_type = "Right";
  }

  Blockly.Python.addVariable('p' + _button_type, 'p' + _button_type + ' = Pin(' + _num + ', Pin.IN' + _upstr + ')');
  var code = '(p' + _button_type + '.value() == 0)';
  return [code, Blockly.Python.ORDER_CONDITIONAL];
};
/*
LED 
*/


Blockly.Blocks['esp32_main_controller_set_led_turnon'] = {
  init: function init() {
    // this.appendDummyInput()
    //     .appendField(new Blockly.FieldImage("blockly/media/led_on.png", 38, 38, { alt: "*", flipRtl: "FALSE" }));
    this.appendDummyInput().appendField(Blockly.Msg.ESP32TURN + Blockly.Msg.ESP32LED_MONO_TEXT_NO);
    this.appendValueInput("led_type").setCheck(null);
    this.appendDummyInput().appendField(Blockly.Msg.ESP32LED_MONO_TEXT_AFTER + Blockly.Msg.ESP32LED + Blockly.Msg.ESP32LED_TURNON);
    this.setPreviousStatement(true, null);
    this.setNextStatement(true, null);
    this.setColour("#e8795b");
    this.setTooltip(Blockly.Msg.Esp32_Main_Controller_Set_Led_Turnon_TOOLTIP);
    this.setHelpUrl("");
  }
};

Blockly.Python['esp32_main_controller_set_led_turnon'] = function (block) {
  Blockly.Python.definitions_['import_led_Pin'] = 'from machine import Pin';

  var _type = Blockly.Python.valueToCode(block, 'led_type', Blockly.Python.ORDER_ATOMIC);

  var _state = block.getFieldValue('led_state');

  var _num = "2";

  if (_type == "1") {
    var _num = "2";
  } else if (_type == "2") {
    var _num = "12";
  } else if (_type == "3") {
    var _num = "5";
  } else if (_type == "4") {
    var _num = "13";
  } else if (_type == "5") {
    var _num = "14";
  } else if (_type == "6") {
    var _num = "15";
  } else if (_type == "7") {
    var _num = "18";
  } else if (_type == "8") {
    var _num = "19";
  } else if (_type == "9") {
    var _num = "23";
  } else {
    var _num = "ERROR";
  }

  Blockly.Python.addSetup('iot_led_light_setup', '' + '_light = [0,2,12,5,13,14,15,18,19,23]\n' + '\n' + '_light_1 = Pin(_light[1], Pin.OUT, value=0)\n' + '_light_2 = Pin(_light[2], Pin.OUT, value=0)\n' + '_light_3 = Pin(_light[3], Pin.OUT, value=0)\n' + '_light_4 = Pin(_light[4], Pin.OUT, value=0)\n' + '_light_5 = Pin(_light[5], Pin.OUT, value=0)\n' + '_light_6 = Pin(_light[6], Pin.OUT, value=0)\n' + '_light_7 = Pin(_light[7], Pin.OUT, value=0)\n' + '_light_8 = Pin(_light[8], Pin.OUT, value=0)\n' + '_light_9 = Pin(_light[9], Pin.OUT, value=0)\n' + '\n' + 'def _led_light(state, pin):\n' + '    if (state == True):\n' + '        if pin == 1: _light_1.value(1)\n' + '        if pin == 2: _light_2.value(1)\n' + '        if pin == 3: _light_3.value(1)\n' + '        if pin == 4: _light_4.value(1)\n' + '        if pin == 5: _light_5.value(1)\n' + '        if pin == 6: _light_6.value(1)\n' + '        if pin == 7: _light_7.value(1)\n' + '        if pin == 8: _light_8.value(1)\n' + '        if pin == 9: _light_9.value(1)\n' + '    elif (state == False):\n' + '        if pin == 1: _light_1.value(0)\n' + '        if pin == 2: _light_2.value(0)\n' + '        if pin == 3: _light_3.value(0)\n' + '        if pin == 4: _light_4.value(0)\n' + '        if pin == 5: _light_5.value(0)\n' + '        if pin == 6: _light_6.value(0)\n' + '        if pin == 7: _light_7.value(0)\n' + '        if pin == 8: _light_8.value(0)\n' + '        if pin == 9: _light_9.value(0)\n' + '');
  var code = '_led_light(True,' + _type + ')\n';
  return code;
};

Blockly.Blocks['esp32_main_controller_set_led_turnoff'] = {
  init: function init() {
    // this.appendDummyInput()
    //     .appendField(new Blockly.FieldImage("blockly/media/led_off.png", 38, 38, { alt: "*", flipRtl: "FALSE" }));
    this.appendDummyInput().appendField(Blockly.Msg.ESP32TURN + Blockly.Msg.ESP32LED_MONO_TEXT_NO);
    this.appendValueInput("led_type").setCheck(null);
    this.appendDummyInput().appendField(Blockly.Msg.ESP32LED_MONO_TEXT_AFTER + Blockly.Msg.ESP32LED + Blockly.Msg.ESP32LED_TURNOFF);
    this.setPreviousStatement(true, null);
    this.setNextStatement(true, null);
    this.setColour("#e8795b");
    this.setTooltip(Blockly.Msg.Esp32_Main_Controller_Set_Led_Turnoff_TOOLTIP);
    this.setHelpUrl("");
  }
};

Blockly.Python['esp32_main_controller_set_led_turnoff'] = function (block) {
  Blockly.Python.definitions_['import_led_Pin'] = 'from machine import Pin';

  var _type = Blockly.Python.valueToCode(block, 'led_type', Blockly.Python.ORDER_ATOMIC);

  var _state = block.getFieldValue('led_state');

  var _num = "2";

  if (_type == "1") {
    var _num = "2";
  } else if (_type == "2") {
    var _num = "12";
  } else if (_type == "3") {
    var _num = "5";
  } else if (_type == "4") {
    var _num = "13";
  } else if (_type == "5") {
    var _num = "14";
  } else if (_type == "6") {
    var _num = "15";
  } else if (_type == "7") {
    var _num = "18";
  } else if (_type == "8") {
    var _num = "19";
  } else if (_type == "9") {
    var _num = "23";
  } else {
    var _num = "ERROR";
  }

  Blockly.Python.addSetup('iot_led_light_setup', '' + '_light = [0,2,12,5,13,14,15,18,19,23]\n' + '\n' + '_light_1 = Pin(_light[1], Pin.OUT, value=0)\n' + '_light_2 = Pin(_light[2], Pin.OUT, value=0)\n' + '_light_3 = Pin(_light[3], Pin.OUT, value=0)\n' + '_light_4 = Pin(_light[4], Pin.OUT, value=0)\n' + '_light_5 = Pin(_light[5], Pin.OUT, value=0)\n' + '_light_6 = Pin(_light[6], Pin.OUT, value=0)\n' + '_light_7 = Pin(_light[7], Pin.OUT, value=0)\n' + '_light_8 = Pin(_light[8], Pin.OUT, value=0)\n' + '_light_9 = Pin(_light[9], Pin.OUT, value=0)\n' + '\n' + 'def _led_light(state, pin):\n' + '    if (state == True):\n' + '        if pin == 1: _light_1.value(1)\n' + '        if pin == 2: _light_2.value(1)\n' + '        if pin == 3: _light_3.value(1)\n' + '        if pin == 4: _light_4.value(1)\n' + '        if pin == 5: _light_5.value(1)\n' + '        if pin == 6: _light_6.value(1)\n' + '        if pin == 7: _light_7.value(1)\n' + '        if pin == 8: _light_8.value(1)\n' + '        if pin == 9: _light_9.value(1)\n' + '    elif (state == False):\n' + '        if pin == 1: _light_1.value(0)\n' + '        if pin == 2: _light_2.value(0)\n' + '        if pin == 3: _light_3.value(0)\n' + '        if pin == 4: _light_4.value(0)\n' + '        if pin == 5: _light_5.value(0)\n' + '        if pin == 6: _light_6.value(0)\n' + '        if pin == 7: _light_7.value(0)\n' + '        if pin == 8: _light_8.value(0)\n' + '        if pin == 9: _light_9.value(0)\n' + '');
  var code = '_led_light(False,' + _type + ')\n';
  return code;
};

Blockly.Blocks['esp32_main_controller_set_led_drawpixel_on'] = {
  init: function init() {
    this.appendDummyInput().appendField(Blockly.Msg.ESP32LED_CORD_DRAWPIXEL_LIGHTUP + Blockly.Msg.ESP32LED_CORD_DRAWPIXEL_LIGHT_INIT_TEXT);
    this.appendValueInput("x").setCheck(null);
    this.appendValueInput("y").setCheck(null).appendField(Blockly.Msg.ESP32LED_CORD_DRAWPIXEL_LIGHT_MIDDLE_TEXT);
    this.appendDummyInput().appendField(Blockly.Msg.ESP32LED_CORD_DRAWPIXEL_LIGHT_END_TEXT);
    this.setInputsInline(true);
    this.setPreviousStatement(true, null);
    this.setNextStatement(true, null);
    this.setColour("#e8795b");
    this.setTooltip(Blockly.Msg.Esp32_Main_Controller_Set_Led_Drawpixel_On_TOOLTIP);
    this.setHelpUrl("");
  }
};

Blockly.Python['esp32_main_controller_set_led_drawpixel_on'] = function (block) {
  var value_x = Blockly.Python.valueToCode(block, 'x', Blockly.Python.ORDER_ATOMIC);
  var value_y = Blockly.Python.valueToCode(block, 'y', Blockly.Python.ORDER_ATOMIC); // TODO: Assemble Python into code variable.

  Blockly.Python.definitions_['import_led_Pin'] = 'from machine import Pin';
  Blockly.Python.addSetup('iot_led_light_setup', '' + '_light = [0,2,12,5,13,14,15,18,19,23]\n' + '\n' + '_light_1 = Pin(_light[1], Pin.OUT, value=0)\n' + '_light_2 = Pin(_light[2], Pin.OUT, value=0)\n' + '_light_3 = Pin(_light[3], Pin.OUT, value=0)\n' + '_light_4 = Pin(_light[4], Pin.OUT, value=0)\n' + '_light_5 = Pin(_light[5], Pin.OUT, value=0)\n' + '_light_6 = Pin(_light[6], Pin.OUT, value=0)\n' + '_light_7 = Pin(_light[7], Pin.OUT, value=0)\n' + '_light_8 = Pin(_light[8], Pin.OUT, value=0)\n' + '_light_9 = Pin(_light[9], Pin.OUT, value=0)\n' + '\n' + 'def _led_light(state, pin):\n' + '    if (state == True):\n' + '        if pin == 1: _light_1.value(1)\n' + '        if pin == 2: _light_2.value(1)\n' + '        if pin == 3: _light_3.value(1)\n' + '        if pin == 4: _light_4.value(1)\n' + '        if pin == 5: _light_5.value(1)\n' + '        if pin == 6: _light_6.value(1)\n' + '        if pin == 7: _light_7.value(1)\n' + '        if pin == 8: _light_8.value(1)\n' + '        if pin == 9: _light_9.value(1)\n' + '    elif (state == False):\n' + '        if pin == 1: _light_1.value(0)\n' + '        if pin == 2: _light_2.value(0)\n' + '        if pin == 3: _light_3.value(0)\n' + '        if pin == 4: _light_4.value(0)\n' + '        if pin == 5: _light_5.value(0)\n' + '        if pin == 6: _light_6.value(0)\n' + '        if pin == 7: _light_7.value(0)\n' + '        if pin == 8: _light_8.value(0)\n' + '        if pin == 9: _light_9.value(0)\n' + '');
  Blockly.Python.addSetup('drawpixel_setup', '' + 'def _led_draw_pixel(state, x, y):\n' + '    real_pin = (3*y-3+x)\n' + '    _led_light(state,real_pin)\n' + '\n');
  var code = '_led_draw_pixel(True,' + value_x + ',' + value_y + ')\n';
  return code;
};

Blockly.Blocks['esp32_main_controller_set_led_drawpixel_off'] = {
  init: function init() {
    this.appendDummyInput().appendField(Blockly.Msg.ESP32LED_CORD_DRAWPIXEL_LIGHTOFF + Blockly.Msg.ESP32LED_CORD_DRAWPIXEL_LIGHT_INIT_TEXT);
    this.appendValueInput("x").setCheck(null);
    this.appendValueInput("y").setCheck(null).appendField(Blockly.Msg.ESP32LED_CORD_DRAWPIXEL_LIGHT_MIDDLE_TEXT);
    this.appendDummyInput().appendField(Blockly.Msg.ESP32LED_CORD_DRAWPIXEL_LIGHT_END_TEXT);
    this.setInputsInline(true);
    this.setPreviousStatement(true, null);
    this.setNextStatement(true, null);
    this.setColour("#e8795b");
    this.setTooltip(Blockly.Msg.Esp32_Main_Controller_Set_Led_Drawpixel_Off_TOOLTIP);
    this.setHelpUrl("");
  }
};

Blockly.Python['esp32_main_controller_set_led_drawpixel_off'] = function (block) {
  var value_x = Blockly.Python.valueToCode(block, 'x', Blockly.Python.ORDER_ATOMIC);
  var value_y = Blockly.Python.valueToCode(block, 'y', Blockly.Python.ORDER_ATOMIC); // TODO: Assemble Python into code variable.

  Blockly.Python.definitions_['import_led_Pin'] = 'from machine import Pin';
  Blockly.Python.addSetup('iot_led_light_setup', '' + '_light = [0,2,12,5,13,14,15,18,19,23]\n' + '\n' + '_light_1 = Pin(_light[1], Pin.OUT, value=0)\n' + '_light_2 = Pin(_light[2], Pin.OUT, value=0)\n' + '_light_3 = Pin(_light[3], Pin.OUT, value=0)\n' + '_light_4 = Pin(_light[4], Pin.OUT, value=0)\n' + '_light_5 = Pin(_light[5], Pin.OUT, value=0)\n' + '_light_6 = Pin(_light[6], Pin.OUT, value=0)\n' + '_light_7 = Pin(_light[7], Pin.OUT, value=0)\n' + '_light_8 = Pin(_light[8], Pin.OUT, value=0)\n' + '_light_9 = Pin(_light[9], Pin.OUT, value=0)\n' + '\n' + 'def _led_light(state, pin):\n' + '    if (state == True):\n' + '        if pin == 1: _light_1.value(1)\n' + '        if pin == 2: _light_2.value(1)\n' + '        if pin == 3: _light_3.value(1)\n' + '        if pin == 4: _light_4.value(1)\n' + '        if pin == 5: _light_5.value(1)\n' + '        if pin == 6: _light_6.value(1)\n' + '        if pin == 7: _light_7.value(1)\n' + '        if pin == 8: _light_8.value(1)\n' + '        if pin == 9: _light_9.value(1)\n' + '    elif (state == False):\n' + '        if pin == 1: _light_1.value(0)\n' + '        if pin == 2: _light_2.value(0)\n' + '        if pin == 3: _light_3.value(0)\n' + '        if pin == 4: _light_4.value(0)\n' + '        if pin == 5: _light_5.value(0)\n' + '        if pin == 6: _light_6.value(0)\n' + '        if pin == 7: _light_7.value(0)\n' + '        if pin == 8: _light_8.value(0)\n' + '        if pin == 9: _light_9.value(0)\n' + '');
  Blockly.Python.addSetup('drawpixel_setup', '' + 'def _led_draw_pixel(state, x, y):\n' + '    real_pin = (3*y-3+x)\n' + '    _led_light(state,real_pin)\n' + '\n');
  var code = '_led_draw_pixel(False,' + value_x + ',' + value_y + ')\n';
  return code;
};
/*
BUZZER 
*/


Blockly.Blocks['esp32_main_controller_set_buzzer'] = {
  init: function init() {
    // this.appendDummyInput()
    //     .appendField(new Blockly.FieldImage("blockly/media/buzzer.png", 38, 38, { alt: "*", flipRtl: "FALSE" }));
    this.appendDummyInput().appendField(); //.appendField(new Blockly.FieldNumber(31, 31, 65535, 1), "buzzer_frequency");

    this.appendValueInput("esp32_var_num").setCheck("Number").appendField(Blockly.Msg.basic_buzzer_set);
    this.setInputsInline(true);
    this.setPreviousStatement(true);
    this.setNextStatement(true); // this.setPreviousStatement(true, null);
    // this.setNextStatement(true, null);

    this.setColour("#e8795b");
    this.setTooltip(Blockly.Msg.Esp32_Main_Controller_Set_Buzzer_TOOLTIP);
    this.setHelpUrl("");
  }
};

Blockly.Python['esp32_main_controller_set_buzzer'] = function (block) {
  Blockly.Python.definitions_['import_PWM'] = 'from machine import PWM';
  Blockly.Python.definitions_['import_Pin'] = 'from machine import Pin';

  var _type = Blockly.Python.valueToCode(block, 'esp32_var_num', Blockly.Python.ORDER_ATOMIC) || '0';

  Blockly.Python.definitions_['buzzer_operation'] = '' + 'beeper = PWM(Pin(26, Pin.OUT), freq=440, duty=512)\n' + 'beeper.deinit()\n' +
    /*
    'def _beeper_control(state, freq=31):\n' +
    '    if freq <= 31: freq = 31\n' +
    '    elif freq >= 67108863: freq = 67108863\n' +
    '    if state == True:\n' +
    '        beeper.init()\n' +
    '        beeper.freq(freq)\n' +
    '        time.sleep_ms(20)\n' +
    '    elif state == False:\n' +
    '        time.sleep_ms(20)\n' +
    '        beeper.deinit()\n' +
    */
    '\n';
  var code = 'beeper.init()\nbeeper.freq(' + _type + ')\n';
  return code;
};

Blockly.Blocks['esp32_main_controller_turn_off_buzzer'] = {
  init: function init() {
    this.appendDummyInput().appendField(Blockly.Msg.ESP32TURNOB);
    this.setPreviousStatement(true, null);
    this.setNextStatement(true, null);
    this.setColour("#e8795b");
    this.setTooltip(Blockly.Msg.Esp32_Main_Controller_Turn_Off_Buzzer_TOOLTIP);
    this.setHelpUrl("");
  }
};

Blockly.Python['esp32_main_controller_turn_off_buzzer'] = function (block) {
  Blockly.Python.definitions_['import_PWM'] = 'from machine import PWM';
  Blockly.Python.definitions_['buzzer_operation'] = '' + 'beeper = PWM(Pin(26, Pin.OUT), freq=440, duty=512)\n' + 'beeper.deinit()\n' +
    /*
    'def _beeper_control(state, freq=31):\n' +
    '    if freq <= 31: freq = 31\n' +
    '    elif freq >= 67108863: freq = 67108863\n' +
    '    if state == True:\n' +
    '        beeper.init()\n' +
    '        beeper.freq(freq)\n' +
    '        time.sleep_ms(20)\n' +
    '    elif state == False:\n' +
    '        beeper.deinit()\n' +
    '        time.sleep_ms(20)\n' +
    */
    '\n';
  var code = 'beeper.deinit()\n';
  return code; //return [code, Blockly.Python.ORDER_FUNCTION_CALL];
};
/*
TOUCH AREA
*/


Blockly.Blocks['esp32_main_controller_touch_read_touched'] = {
  init: function init() {
    // this.appendDummyInput()
    //    .appendField(new Blockly.FieldImage("blockly/media/touched.png", 38, 38, { alt: "*", flipRtl: "FALSE" }));
    this.appendDummyInput().appendField(Blockly.Msg.ESP32TA).appendField(new Blockly.FieldDropdown([["A", "touch_area_type_a"], ["B", "touch_area_type_b"]]), "touch_area_type").appendField(Blockly.Msg.ESP32_TOUCHED);
    this.setOutput(true, null);
    this.setColour("#e8795b");
    this.setTooltip("");
    this.setHelpUrl("");
  }
};

Blockly.Python['esp32_main_controller_touch_read_touched'] = function (block) {
  Blockly.Python.definitions_['import_TouchPad'] = 'from machine import TouchPad';
  Blockly.Python.definitions_['import_Pin'] = 'from machine import Pin';

  var _type = block.getFieldValue('touch_area_type');

  var _state = block.getFieldValue('touch_area_state');

  var _num = "4";

  if (_type == "touch_area_type_a") {
    var _num = "4";
  } else if (_type == "touch_area_type_b") {
    var _num = "27";
  }

  Blockly.Python.addVariable('t' + block.getField('touch_area_type').text_, '_TOUCH_' + block.getField('touch_area_type').text_ + ' = TouchPad(Pin(' + _num + '))');
  var code = '_TOUCH_' + block.getField('touch_area_type').text_ + '.read() ' + "< 100";
  return [code, Blockly.Python.ORDER_CONDITIONAL];
};

Blockly.Blocks['esp32_main_controller_touch_read_untouched'] = {
  init: function init() {
    // this.appendDummyInput()
    //    .appendField(new Blockly.FieldImage("blockly/media/untouched.png", 38, 38, { alt: "*", flipRtl: "FALSE" }));
    this.appendDummyInput().appendField(Blockly.Msg.ESP32TA).appendField(new Blockly.FieldDropdown([["A", "touch_area_type_a"], ["B", "touch_area_type_b"]]), "touch_area_type").appendField(Blockly.Msg.ESP32_UNTOUCHED);
    this.setOutput(true, null);
    this.setColour("#e8795b");
    this.setTooltip("");
    this.setHelpUrl("");
  }
};

Blockly.Python['esp32_main_controller_touch_read_untouched'] = function (block) {
  Blockly.Python.definitions_['import_TouchPad'] = 'from machine import TouchPad';
  Blockly.Python.definitions_['import_Pin'] = 'from machine import Pin';

  var _type = block.getFieldValue('touch_area_type');

  var _state = block.getFieldValue('touch_area_state');

  var _num = "4";

  if (_type == "touch_area_type_a") {
    var _num = "4";
  } else if (_type == "touch_area_type_b") {
    var _num = "27";
  }

  Blockly.Python.addVariable('t' + block.getField('touch_area_type').text_, '_TOUCH_' + block.getField('touch_area_type').text_ + ' = TouchPad(Pin(' + _num + '))');
  var code = '_TOUCH_' + block.getField('touch_area_type').text_ + '.read() ' + ">= 100";
  return [code, Blockly.Python.ORDER_CONDITIONAL];
};

Blockly.Blocks['esp32_main_controller_touch_read_value'] = {
  init: function init() {
    this.appendDummyInput().appendField(Blockly.Msg.ESP32_READ).appendField(new Blockly.FieldDropdown([["A", "touch_area_type_a"], ["B", "touch_area_type_b"]]), "touch_area_type").appendField(Blockly.Msg.ESP32_READ_VALUE);
    this.setInputsInline(false);
    this.setOutput(true, null);
    this.setColour("#e8795b");
    this.setTooltip("");
    this.setHelpUrl("");
  }
};

Blockly.Python['esp32_main_controller_touch_read_value'] = function (block) {
  Blockly.Python.definitions_['import_TouchPad'] = 'from machine import TouchPad';
  Blockly.Python.definitions_['import_Pin'] = 'from machine import Pin';

  var _type = block.getFieldValue('touch_area_type');

  var _state = block.getFieldValue('touch_area_state');

  var _num = "4";

  if (_type == "touch_area_type_a") {
    var _num = "4";
  } else if (_type == "touch_area_type_b") {
    var _num = "27";
  }

  Blockly.Python.addVariable('t' + block.getField('touch_area_type').text_, '_TOUCH_' + block.getField('touch_area_type').text_ + ' = TouchPad(Pin(' + _num + '))');
  var code = '_TOUCH_' + block.getField('touch_area_type').text_ + '.read() ';
  return [code, Blockly.Python.ORDER_CONDITIONAL];
};
/* 
Env Sensor: BME280
*/


Blockly.Blocks['esp32_main_controller_get_environmental_value'] = {
  init: function init() {
    // this.appendDummyInput()
    //    .appendField(new Blockly.FieldImage("blockly/media/env_get.png", 38, 38, { alt: "*", flipRtl: "FALSE" }));
    this.appendDummyInput().appendField(Blockly.Msg.ESP32_ENV_GET_TEXT).appendField(new Blockly.FieldDropdown([[Blockly.Msg.basic_temperature, "temperature"], [Blockly.Msg.basic_humidity, "humidity"] // [Blockly.Msg.basic_pressure, "pressure"]
    ]), "env_get_type").appendField(Blockly.Msg.basic_env_value);
    this.setInputsInline(false);
    this.setOutput(true, null);
    this.setColour("#e8795b");
    var thisBlock = this;
    this.setTooltip(function () {
      var mode = thisBlock.getFieldValue('env_get_type');
      var TOOLTIPS = {
        'temperature': Blockly.Msg.Esp32_Main_Controller_Get_Environmental_Value_TOOLTIP.replace('%1', Blockly.Msg.basic_temperature),
        'humidity': Blockly.Msg.Esp32_Main_Controller_Get_Environmental_Value_TOOLTIP.replace('%1', Blockly.Msg.basic_humidity)
      };
      return TOOLTIPS[mode];
    });
    this.setHelpUrl("");
  }
};

Blockly.Python['esp32_main_controller_get_environmental_value'] = function (block) {
  var _type_selected = block.getFieldValue('env_get_type');
  /*
  from machine import Pin, I2C
  import bme280 as BME280
    _SENSOR_BME_PINS = I2C(scl=Pin(17), sda=Pin(16), freq=10000)
    _BME = BME280.BME280(i2c=_SENSOR_BME_PINS)
    */


  Blockly.Python.definitions_['import_bme280'] = 'from machine import Pin, I2C\n' + 'from aht10 import AHT10\n\n' + '_aht10_i2c = I2C(sda=Pin(32), scl=Pin(33))\n' + '_aht10_sensor = AHT10(_aht10_i2c)\n' + '_aht10_sensor.sensor_init()\n' + '_aht10_sensor.is_calibration_enabled()\n' + '';
  Blockly.Python.addVariable('_BME', '');

  if (_type_selected == 'temperature') {
    var code = '_aht10_sensor.read_' + _type_selected + '()';
  } else if (_type_selected == 'humidity') {
    var code = '_aht10_sensor.read_' + _type_selected + '()';
  } else {
    var code = _type_selected;
  } // TODO: Change ORDER_NONE to the correct strength.


  return [code, Blockly.Python.ORDER_CONDITIONAL];
};
/* 
Motion Sensor: MPU6050
*/


Blockly.Blocks['esp32_main_controller_motion_init'] = {
  init: function init() {
    //this.appendDummyInput()
    //    .appendField(new Blockly.FieldImage("blockly/media/motion_setup.png", 38, 38, { alt: "*", flipRtl: "FALSE" }));
    this.appendDummyInput().appendField(Blockly.Msg.basic_motion_use);
    this.setInputsInline(false);
    this.setPreviousStatement(true, null);
    this.setNextStatement(true, null);
    this.setColour("#e8795b");
    this.setTooltip("");
    this.setHelpUrl("");
  }
};

Blockly.Python['esp32_main_controller_motion_init'] = function (block) {
  // Blockly.Python.addVariable('_SENSOR_MPU_PINS', '');
  Blockly.Python.definitions_['import_mpu6050'] = '' + 'from machine import I2C, Pin\n' + 'import math\n' + 'import mpu6050\n' + '_SENSOR_MPU_PINS = I2C(scl=Pin(22), sda=Pin(21))\n' + '';
  var code = '' + '_MPU = mpu6050.accel(_SENSOR_MPU_PINS)\n' + '_MPU_SHAKING_OFFSET = _MPU.get_values()[\'AcZ\']\n' + '_MPU_ACCL_X = _MPU.get_values()[\'AcX\']\n' + '_MPU_ACCL_Y = _MPU.get_values()[\'AcY\']\n' + '_MPU_ACCL_Z = _MPU.get_values()[\'AcZ\']\n' + '_MPU_OFFSET_TILT_X = _MPU_GET_TILT_ANGLE(\'X\')\n' + '_MPU_OFFSET_TILT_Y = _MPU_GET_TILT_ANGLE(\'Y\')\n' + '_MPU_OFFSET_TILT_Z = _MPU_GET_TILT_ANGLE(\'Z\')\n' + '';
  return code;
};

Blockly.Blocks['esp32_main_controller_motion_when_shaking'] = {
  init: function init() {
    this.appendDummyInput().appendField(Blockly.Msg.basic_when_shaking);
    this.setInputsInline(false);
    this.setOutput(true, null);
    this.setColour("#e8795b");
    this.setTooltip("");
    this.setHelpUrl("");
  }
};

Blockly.Python['esp32_main_controller_motion_when_shaking'] = function (block) {
  Blockly.Python.definitions_['shaking_def'] = '' + 'def _CHECK_SHAKING():\n' + '    if _MPU_SHAKING_OFFSET < 0 and _SSTATE == 0:\n' + '        _SSTATE = 1\n' + '        return True\n' + '    elif _MPU_SHAKING_OFFSET > 0 and _SSTATE == 1:\n' + '        _SSTATE = 0\n' + '        return False\n' + '';
  var code = '(_CHECK_SHAKING() == True)';
  return [code, Blockly.Python.ORDER_CONDITIONAL];
};

Blockly.Blocks['esp32_main_controller_motion_when_shaking_STATEMENT'] = {
  init: function init() {
    this.appendDummyInput().appendField(Blockly.Msg.basic_when_shaking_when_module).appendField(new Blockly.FieldDropdown([[Blockly.Msg.basic_when_shaking_when_is_in, "True"], [Blockly.Msg.basic_when_shaking_when_is_not_in, "False"]]), "status").appendField(Blockly.Msg.basic_when_shaking_when_shaking);
    this.appendStatementInput("input").setCheck(null).appendField(Blockly.Msg.basic_motion_statement_exec);
    this.setPreviousStatement(true, null);
    this.setNextStatement(true, null);
    this.setColour("#e8795b");
    var thisBlock = this;
    this.setTooltip(function () {
      var mode = thisBlock.getFieldValue('status');
      var TOOLTIPS = {
        'True': Blockly.Msg.Esp32_Main_Controller_Motion_When_Shaking_STATEMENT_TOOLTIP.replace('%1', Blockly.Msg.basic_when_shaking_when_is_in),
        'False': Blockly.Msg.Esp32_Main_Controller_Motion_When_Shaking_STATEMENT_TOOLTIP.replace('%1', Blockly.Msg.basic_when_shaking_when_is_not_in)
      };
      return TOOLTIPS[mode];
    });
    this.setHelpUrl("");
  }
};

Blockly.Python['esp32_main_controller_motion_when_shaking_STATEMENT'] = function (block) {
  var dropdown_status = block.getFieldValue('status');
  var statements_input = Blockly.Python.statementToCode(block, 'input');
  Blockly.Python.definitions_['import_mpu6050'] = '' + 'from machine import I2C, Pin\n' + 'import math\n' + 'import mpu6050\n' + '_SENSOR_MPU_PINS = I2C(scl=Pin(22), sda=Pin(21))\n' + '';
  Blockly.Python.definitions_['mpu6050_standard_def'] = '' + '_MPU = mpu6050.accel(_SENSOR_MPU_PINS)\n' + '_MPU_SHAKING_OFFSET = _MPU.get_values()[\'AcZ\']\n' + '_MPU_ACCL_Z = _MPU.get_values()[\'AcZ\']\n' + '';
  Blockly.Python.definitions_['shaking_def'] = '' + 'def _CHECK_SHAKING():\n' + '    _MPU = mpu6050.accel(_SENSOR_MPU_PINS)\n' + '    _MPU_SHAKING_OFFSET = _MPU.get_values()[\'AcZ\']\n' + '    _MPU_ACCL_Z = _MPU.get_values()[\'AcZ\']\n' + '    _SSTATE = 0\n' + '    if _MPU_SHAKING_OFFSET < 0:\n' + '        _SSTATE = 1\n' + '        return True\n' + '    elif _MPU_SHAKING_OFFSET > 0:\n' + '        _SSTATE = 0\n' + '        return False\n' + '';
  var code = '' + 'if (_CHECK_SHAKING() == ' + dropdown_status + '):\n' + '\t_MPU = mpu6050.accel(_SENSOR_MPU_PINS)\n' + '\t_MPU_SHAKING_OFFSET = _MPU.get_values()[\'AcZ\']\n' + '\t_MPU_ACCL_Z = _MPU.get_values()[\'AcZ\']\n' + '' + statements_input + '\n' + '';
  return code;
};

Blockly.Blocks['esp32_main_controller_motion_when_tilting'] = {
  init: function init() {
    this.appendDummyInput().appendField(Blockly.Msg.basic_when_tilting_get).appendField(new Blockly.FieldDropdown([[Blockly.Msg.basic_when_tilting_get_left, "L"], [Blockly.Msg.basic_when_tilting_get_right, "R"], [Blockly.Msg.basic_when_tilting_get_forward, "F"], [Blockly.Msg.basic_when_tilting_get_backward, "B"]]), "tilt_type").appendField(Blockly.Msg.basic_when_tilting_get_when);
    this.setInputsInline(false);
    this.setOutput(true, null);
    this.setColour("#e8795b");
    this.setTooltip("");
    this.setHelpUrl("");
  }
};

Blockly.Python['esp32_main_controller_motion_when_tilting'] = function (block) {
  var _type_selected = block.getFieldValue('tilt_type');

  Blockly.Python.definitions_['tilting_def'] = '' + 'def _CHECK_TILT_LR():\n' + '    if _MPU_OFFSET_TILT_X < 160 and _MPU_OFFSET_TILT_X > 0:\n' + '        return "R"\n' + '    elif _MPU_OFFSET_TILT_X > 200 and _MPU_OFFSET_TILT_X < 360:\n' + '        return "L"\n' + '    else:\n' + '        return None\n' + '\n' + 'def _CHECK_TILT_FB():\n' + '    if _MPU_OFFSET_TILT_Y < 160 and _MPU_OFFSET_TILT_Y > 0:\n' + '        return "F"\n' + '    elif _MPU_OFFSET_TILT_Y > 200 and _MPU_OFFSET_TILT_Y < 360:\n' + '        return "B"\n' + '    else:\n' + '        return None\n' + '';

  if (_type_selected == "L" || _type_selected == "R") {
    _check_function = '(_CHECK_TILT_LR() == "';
  } else if (_type_selected == "F" || _type_selected == "B") {
    _check_function = '(_CHECK_TILT_FB() == "';
  }

  var code = _check_function + _type_selected + '")';
  return [code, Blockly.Python.ORDER_CONDITIONAL];
};

Blockly.Blocks['esp32_main_controller_motion_when_tilting_STATEMENT'] = {
  init: function init() {
    this.appendDummyInput().appendField(Blockly.Msg.basic_when_tilting_get).appendField(new Blockly.FieldDropdown([[Blockly.Msg.basic_when_tilting_get_left, "L"], [Blockly.Msg.basic_when_tilting_get_right, "R"], [Blockly.Msg.basic_when_tilting_get_forward, "F"], [Blockly.Msg.basic_when_tilting_get_backward, "B"], [Blockly.Msg.basic_when_tilting_not_tilting, "N"]]), "tilt_type").appendField(Blockly.Msg.basic_when_tilting_get_when);
    this.appendStatementInput("input").setCheck(null).appendField(Blockly.Msg.basic_motion_statement_exec);
    this.setPreviousStatement(true, null);
    this.setNextStatement(true, null);
    this.setColour("#e8795b");
    var thisBlock = this;
    this.setTooltip(function () {
      var mode = thisBlock.getFieldValue('tilt_type');
      var TOOLTIPS = {
        'L': Blockly.Msg.Esp32_Main_Controller_Motion_When_Tilting_STATEMENT_TOOLTIP.replace('%1', Blockly.Msg.basic_when_tilting_get_left),
        'R': Blockly.Msg.Esp32_Main_Controller_Motion_When_Tilting_STATEMENT_TOOLTIP.replace('%1', Blockly.Msg.basic_when_tilting_get_right),
        'F': Blockly.Msg.Esp32_Main_Controller_Motion_When_Tilting_STATEMENT_TOOLTIP.replace('%1', Blockly.Msg.basic_when_tilting_get_forward),
        'B': Blockly.Msg.Esp32_Main_Controller_Motion_When_Tilting_STATEMENT_TOOLTIP.replace('%1', Blockly.Msg.basic_when_tilting_get_backward),
        'N': Blockly.Msg.Esp32_Main_Controller_Motion_When_Tilting_STATEMENT_TOOLTIP.replace('%1', Blockly.Msg.basic_when_tilting_not_tilting)
      };
      return TOOLTIPS[mode];
    });
    this.setHelpUrl("");
  }
};

Blockly.Python['esp32_main_controller_motion_when_tilting_STATEMENT'] = function (block) {
  var _type_selected = block.getFieldValue('tilt_type');

  var statements_input = Blockly.Python.statementToCode(block, 'input');
  Blockly.Python.definitions_['import_mpu6050'] = '' + 'from machine import I2C, Pin\n' + 'import math\n' + 'import mpu6050\n' + '_SENSOR_MPU_PINS = I2C(scl=Pin(22), sda=Pin(21))\n' + '';
  Blockly.Python.definitions_['mpu6050_standard_def'] = '' + '_MPU = mpu6050.accel(_SENSOR_MPU_PINS)\n'
    /* +
            '_MPU_SHAKING_OFFSET = _MPU.get_values()[\'AcZ\']\n' +
            '_MPU_ACCL_X = _MPU.get_values()[\'AcX\']\n' +
            '_MPU_ACCL_Y = _MPU.get_values()[\'AcY\']\n' +
            '_MPU_ACCL_Z = _MPU.get_values()[\'AcZ\']\n' +
            '_MPU_OFFSET_TILT_X = _MPU_GET_TILT_ANGLE(\'X\')\n' +
            '_MPU_OFFSET_TILT_Y = _MPU_GET_TILT_ANGLE(\'Y\')\n' +
            '_MPU_OFFSET_TILT_Z = _MPU_GET_TILT_ANGLE(\'Z\')\n' +
            ''*/
    ;
  Blockly.Python.definitions_['tilting_def'] = '' + 'def _CHECK_TILT_DIRECTION():\n' + '    _MPU = mpu6050.accel(_SENSOR_MPU_PINS)\n' + '    _MPU_OFFSET_TILT_X = _MPU_GET_TILT_ANGLE(\'X\')\n' + '    _MPU_OFFSET_TILT_Y = _MPU_GET_TILT_ANGLE(\'Y\')\n' + '    _MPU_OFFSET_TILT_Z = _MPU_GET_TILT_ANGLE(\'Z\')\n' + '    if _MPU_OFFSET_TILT_X < 150 and _MPU_OFFSET_TILT_X > 0:\n' + '        return "L"\n' + '    elif _MPU_OFFSET_TILT_X > 210 and _MPU_OFFSET_TILT_X < 360:\n' + '        return "R"\n' + '    if _MPU_OFFSET_TILT_Y < 150 and _MPU_OFFSET_TILT_Y > 0:\n' + '        return "B"\n' + '    elif _MPU_OFFSET_TILT_Y > 210 and _MPU_OFFSET_TILT_Y < 360:\n' + '        return "F"\n' + '    else:\n' + '        return "N"\n' + '';
  var _check_function = "(_CHECK_TILT_DIRECTION() == \"";
  var code = '' + 'if ' + _check_function + _type_selected + '"):\n' + '\t_MPU = mpu6050.accel(_SENSOR_MPU_PINS)\n' + '' + statements_input + '\n' + '\n';
  return code;
};

Blockly.Blocks['esp32_main_controller_motion_acceleration'] = {
  init: function init() {
    this.appendDummyInput().appendField(Blockly.Msg.basic_motion_get).appendField(new Blockly.FieldDropdown([["X", "X"], ["Y", "Y"], ["Z", "Z"]]), "accel_type").appendField(Blockly.Msg.basic_motion_accel);
    this.setInputsInline(false);
    this.setOutput(true, null);
    this.setColour("#e8795b");
    var thisBlock = this;
    this.setTooltip(function () {
      var mode = thisBlock.getFieldValue('accel_type');
      var TOOLTIPS = {
        'X': Blockly.Msg.Esp32_Main_Controller_Motion_Acceleration_TOOLTIP.replace('%1', 'X'),
        'Y': Blockly.Msg.Esp32_Main_Controller_Motion_Acceleration_TOOLTIP.replace('%1', 'Y'),
        'Z': Blockly.Msg.Esp32_Main_Controller_Motion_Acceleration_TOOLTIP.replace('%1', 'Z')
      };
      return TOOLTIPS[mode];
    });
    this.setHelpUrl("");
  }
};

Blockly.Python['esp32_main_controller_motion_acceleration'] = function (block) {
  var _type_selected = block.getFieldValue('accel_type');

  Blockly.Python.definitions_['import_mpu6050'] = '' + 'from machine import I2C, Pin\n' + 'import math\n' + 'import mpu6050\n' + '_SENSOR_MPU_PINS = I2C(scl=Pin(22), sda=Pin(21))\n' + '';
  Blockly.Python.definitions_['mpu6050_standard_def'] = '' + '_MPU = mpu6050.accel(_SENSOR_MPU_PINS)\n' + '_MPU_SHAKING_OFFSET = _MPU.get_values()[\'AcZ\']\n' + '_MPU_ACCL_X = _MPU.get_values()[\'AcX\']\n' + '_MPU_ACCL_Y = _MPU.get_values()[\'AcY\']\n' + '_MPU_ACCL_Z = _MPU.get_values()[\'AcZ\']\n' + '_MPU_OFFSET_TILT_X = _MPU_GET_TILT_ANGLE(\'X\')\n' + '_MPU_OFFSET_TILT_Y = _MPU_GET_TILT_ANGLE(\'Y\')\n' + '_MPU_OFFSET_TILT_Z = _MPU_GET_TILT_ANGLE(\'Z\')\n' + '';
  Blockly.Python.definitions_['mpu6050_get_accel'] = '' + 'def mpu6050_get_accel(type):\n' + '\t_MPU = mpu6050.accel(_SENSOR_MPU_PINS)\n' + '\t_MPU_SHAKING_OFFSET = _MPU.get_values()[\'AcZ\']\n' + '\t_MPU_ACCL_X = _MPU.get_values()[\'AcX\']\n' + '\t_MPU_ACCL_Y = _MPU.get_values()[\'AcY\']\n' + '\t_MPU_ACCL_Z = _MPU.get_values()[\'AcZ\']\n' + '\t_MPU_OFFSET_TILT_X = _MPU_GET_TILT_ANGLE(\'X\')\n' + '\t_MPU_OFFSET_TILT_Y = _MPU_GET_TILT_ANGLE(\'Y\')\n' + '\t_MPU_OFFSET_TILT_Z = _MPU_GET_TILT_ANGLE(\'Z\')\n' + '\tif type == \'X\':\n' + '\t\treturn _MPU_ACCL_X\n' + '\tif type == \'Y\':\n' + '\t\treturn _MPU_ACCL_Y\n' + '\tif type == \'Z\':\n' + '\t\treturn _MPU_ACCL_Z\n' + ''; // Blockly.Python.addVariable('_MPU_ACCL_' + _type_selected, '');

  var code = 'mpu6050_get_accel(\'' + _type_selected + '\')';
  return [code, Blockly.Python.ORDER_CONDITIONAL];
};

Blockly.Blocks['esp32_main_controller_motion_tilt_angle'] = {
  init: function init() {
    this.appendDummyInput().appendField(Blockly.Msg.basic_motion_get).appendField(new Blockly.FieldDropdown([["X", "X"], ["Y", "Y"], ["Z", "Z"]]), "tilt_angle_type").appendField(Blockly.Msg.basic_motion_angle);
    this.setInputsInline(false);
    this.setOutput(true, null);
    this.setColour("#e8795b");
    var thisBlock = this;
    this.setTooltip(function () {
      var mode = thisBlock.getFieldValue('tilt_angle_type');
      var TOOLTIPS = {
        'X': Blockly.Msg.Esp32_Main_Controller_Motion_Tilt_Angle_TOOLTIP.replace('%1', 'X'),
        'Y': Blockly.Msg.Esp32_Main_Controller_Motion_Tilt_Angle_TOOLTIP.replace('%1', 'Y'),
        'Z': Blockly.Msg.Esp32_Main_Controller_Motion_Tilt_Angle_TOOLTIP.replace('%1', 'Z')
      };
      return TOOLTIPS[mode];
    });
    this.setHelpUrl("");
  }
};

Blockly.Python['esp32_main_controller_motion_tilt_angle'] = function (block) {
  var _type_selected = block.getFieldValue('tilt_angle_type');

  Blockly.Python.definitions_['import_mpu6050'] = '' + 'from machine import I2C, Pin\n' + 'import math\n' + 'import mpu6050\n' + '_SENSOR_MPU_PINS = I2C(scl=Pin(22), sda=Pin(21))\n' + '';
  Blockly.Python.definitions_['mpu6050_standard_def'] = '' + '_MPU = mpu6050.accel(_SENSOR_MPU_PINS)\n' + '_MPU_SHAKING_OFFSET = _MPU.get_values()[\'AcZ\']\n' + '_MPU_ACCL_X = _MPU.get_values()[\'AcX\']\n' + '_MPU_ACCL_Y = _MPU.get_values()[\'AcY\']\n' + '_MPU_ACCL_Z = _MPU.get_values()[\'AcZ\']\n' + '_MPU_OFFSET_TILT_X = _MPU_GET_TILT_ANGLE(\'X\')\n' + '_MPU_OFFSET_TILT_Y = _MPU_GET_TILT_ANGLE(\'Y\')\n' + '_MPU_OFFSET_TILT_Z = _MPU_GET_TILT_ANGLE(\'Z\')\n' + '';
  Blockly.Python.definitions_['mpu6050_get_angle'] = '' + 'def mpu6050_get_tilt_angle(type):\n' + '\t_MPU = mpu6050.accel(_SENSOR_MPU_PINS)\n' + '\t_MPU_SHAKING_OFFSET = _MPU.get_values()[\'AcZ\']\n' + '\t_MPU_ACCL_X = _MPU.get_values()[\'AcX\']\n' + '\t_MPU_ACCL_Y = _MPU.get_values()[\'AcY\']\n' + '\t_MPU_ACCL_Z = _MPU.get_values()[\'AcZ\']\n' + '\t_MPU_OFFSET_TILT_X = _MPU_GET_TILT_ANGLE(\'X\')\n' + '\t_MPU_OFFSET_TILT_Y = _MPU_GET_TILT_ANGLE(\'Y\')\n' + '\t_MPU_OFFSET_TILT_Z = _MPU_GET_TILT_ANGLE(\'Z\')\n' + '\tif type == \'X\':\n' + '\t\treturn _MPU_OFFSET_TILT_X\n' + '\tif type == \'Y\':\n' + '\t\treturn _MPU_OFFSET_TILT_Y\n' + '\tif type == \'Z\':\n' + '\t\treturn _MPU_OFFSET_TILT_Z\n' + ''; // Blockly.Python.addVariable('_MPU_OFFSET_TILT_' + _type_selected, '');

  var code = 'mpu6050_get_tilt_angle(\'' + _type_selected + '\')';
  return [code, Blockly.Python.ORDER_CONDITIONAL];
};
/*
LIGHT & SOUND
*/


Blockly.Blocks['esp32_main_controller_get_light'] = {
  init: function init() {
    // this.appendDummyInput()
    //    .appendField(new Blockly.FieldImage("blockly/media/light_sensor.png", 38, 38, { alt: "*", flipRtl: "FALSE" }));
    this.appendDummyInput().appendField(Blockly.Msg.basic_light_get);
    this.setInputsInline(false);
    this.setOutput(true, null);
    this.setColour("#e8795b");
    this.setTooltip(Blockly.Msg.Esp32_Main_Controller_Get_Light_TOOLTIP);
    this.setHelpUrl("");
  }
};

Blockly.Python['esp32_main_controller_get_light'] = function (block) {
  Blockly.Python.definitions_['light_import_def'] = '' + 'from machine import Pin, ADC\n' + '_PHOTONRESISTOR = machine.ADC(Pin(39))\n' + '_PHOTONRESISTOR.atten(ADC.ATTN_11DB)\n' + '_PHOTONRESISTOR.width(ADC.WIDTH_10BIT)\n' + '';
  Blockly.Python.addVariable('_PHOTONRESISTOR');
  var code = '_PHOTONRESISTOR.read()';
  return [code, Blockly.Python.ORDER_CONDITIONAL];
};
/* time */


var ESP32_TIME_COLOR = "#fabe23";
Blockly.Blocks['esp32_main_controller_time_timer_init'] = {
  init: function init() {
    this.appendDummyInput().appendField("").appendField(new Blockly.FieldDropdown([[Blockly.Msg.time_iot_module, "on_esp32"], [Blockly.Msg.time_ai_module, "on_ai"]]), "type").appendField(Blockly.Msg.time_init_timer);
    this.setPreviousStatement(true, null);
    this.setNextStatement(true, null);
    this.setColour(ESP32_TIME_COLOR);
    var thisBlock = this;
    this.setTooltip(function () {
      var mode = thisBlock.getFieldValue('type');
      var TOOLTIPS = {
        'on_esp32': Blockly.Msg.Esp32_Main_Controller_Time_Timer_Init_TOOLTIP.replace('%1', Blockly.Msg.time_iot_module),
        'on_ai': Blockly.Msg.Esp32_Main_Controller_Time_Timer_Init_TOOLTIP.replace('%1', Blockly.Msg.time_ai_module)
      };
      return TOOLTIPS[mode];
    });
    this.setHelpUrl("");
  }
};

Blockly.Python['esp32_main_controller_time_timer_init'] = function (block) {
  var timer_type = block.getFieldValue('type');

  if (timer_type == "on_esp32") {
    Blockly.Python.definitions_['import_def'] = '' + 'import machine, time\n' + '_TIMER = machine.Timer(0)\n' + '';
    var code = '_TIMER.init()\n';
  } else if (timer_type == "on_ai") {
    Blockly.Python.definitions_['import_def'] = '' + 'import time\n' + 'from machine import Timer\n' + '\n' + 'def _timer_on_timer(timer):\n' + '    global _timer_current_time_elapsed\n' + '    _timer_current_time_elapsed =  _timer_current_time_elapsed + 1\n' + '\n' + '_timer_current_time_elapsed = 0\n' + '_timer_tim = Timer(Timer.TIMER1, Timer.CHANNEL1, mode=Timer.MODE_PERIODIC, period=1, callback=_timer_on_timer)\n' + '';
    var code = '_timer_tim.start()\n';
  }

  return code;
};

Blockly.Blocks['esp32_main_controller_time_timer_get_current'] = {
  init: function init() {
    this.appendDummyInput().appendField("").appendField(new Blockly.FieldDropdown([[Blockly.Msg.time_iot_module, "on_esp32"], [Blockly.Msg.time_ai_module, "on_ai"]]), "type").appendField(Blockly.Msg.time_timer_get_time);
    this.setOutput(true, null);
    this.setColour(ESP32_TIME_COLOR);
    var thisBlock = this;
    this.setTooltip(function () {
      var mode = thisBlock.getFieldValue('type');
      var TOOLTIPS = {
        'on_esp32': Blockly.Msg.Esp32_Main_Controller_Time_Timer_Get_Current_TOOLTIP.replace('%1', Blockly.Msg.time_iot_module),
        'on_ai': Blockly.Msg.Esp32_Main_Controller_Time_Timer_Get_Current_TOOLTIP.replace('%1', Blockly.Msg.time_ai_module)
      };
      return TOOLTIPS[mode];
    });
    this.setHelpUrl("");
  }
};

Blockly.Python['esp32_main_controller_time_timer_get_current'] = function (block) {
  var timer_type = block.getFieldValue('type'); // TODO: Assemble Python into code variable.

  if (timer_type == "on_esp32") {
    var code = '_TIMER.value()';
  } else if (timer_type == "on_ai") {
    var code = '_timer_current_time_elapsed';
  } // TODO: Change ORDER_NONE to the correct strength.


  return [code, Blockly.Python.ORDER_CONDITIONAL];
};

Blockly.Blocks['esp32_main_controller_time_timer_clear'] = {
  init: function init() {
    this.appendDummyInput().appendField("").appendField(new Blockly.FieldDropdown([[Blockly.Msg.time_iot_module, "on_esp32"], [Blockly.Msg.time_ai_module, "on_ai"]]), "type").appendField(Blockly.Msg.time_timer_clear);
    this.setPreviousStatement(true, null);
    this.setNextStatement(true, null);
    this.setColour(ESP32_TIME_COLOR);
    var thisBlock = this;
    this.setTooltip(function () {
      var mode = thisBlock.getFieldValue('type');
      var TOOLTIPS = {
        'on_esp32': Blockly.Msg.Esp32_Main_Controller_Time_Timer_Clear_TOOLTIP.replace('%1', Blockly.Msg.time_iot_module),
        'on_ai': Blockly.Msg.Esp32_Main_Controller_Time_Timer_Clear_TOOLTIP.replace('%1', Blockly.Msg.time_ai_module)
      };
      return TOOLTIPS[mode];
    });
    this.setHelpUrl("");
  }
};

Blockly.Python['esp32_main_controller_time_timer_clear'] = function (block) {
  var timer_type = block.getFieldValue('type'); // TODO: Assemble Python into code variable.

  if (timer_type == "on_esp32") {
    var code = '_TIMER.deinit()\n';
  } else if (timer_type == "on_ai") {
    var code = '_timer_tim.stop()\n';
  }

  return code;
};

Blockly.Blocks['esp32_main_controller_time_period_timer'] = {
  init: function init() {
    this.appendDummyInput().appendField("").appendField(new Blockly.FieldDropdown([[Blockly.Msg.time_iot_module, "on_esp32"], [Blockly.Msg.time_ai_module, "on_ai"]]), "type").appendField(Blockly.Msg.time_timer_periodically);
    this.appendDummyInput().appendField(Blockly.Msg.time_timer_every).appendField(new Blockly.FieldTextInput("500"), "period_timer_count").appendField(Blockly.Msg.time_timer_ms);
    this.appendStatementInput("exec_period_timer").setCheck(null).appendField(Blockly.Msg.time_execution);
    this.setPreviousStatement(true, null);
    this.setNextStatement(true, null);
    this.setColour(ESP32_TIME_COLOR);
    var thisBlock = this;
    this.setTooltip(function () {
      var mode = thisBlock.getFieldValue('type');
      var TOOLTIPS = {
        'on_esp32': Blockly.Msg.Esp32_Main_Controller_Time_Period_Timer_TOOLTIP.replace('%1', Blockly.Msg.time_iot_module),
        'on_ai': Blockly.Msg.Esp32_Main_Controller_Time_Period_Timer_TOOLTIP.replace('%1', Blockly.Msg.time_ai_module)
      };
      return TOOLTIPS[mode];
    });
    this.setHelpUrl("");
  }
};

Blockly.Python['esp32_main_controller_time_period_timer'] = function (block) {
  var timer_type = block.getFieldValue('type');
  var text_period_timer_count = block.getFieldValue('period_timer_count');
  var statements_name = Blockly.Python.statementToCode(block, 'exec_period_timer');

  if (timer_type == "on_esp32") {
    Blockly.Python.definitions_['import_def'] = '' + 'from machine import Timer\n' + '\n' + 'def _PRD_EXEC_tick(_):\n' + '    global _ControlTopic, _ReportTopic\n' + statements_name + '\n' + '_PRD_EXEC_TIMER = Timer(0)\n' + '_PRD_EXEC_TIMER.deinit()\n' + '_PRD_EXEC_TIMER.init(period=' + text_period_timer_count + ', mode=Timer.PERIODIC, callback=_PRD_EXEC_tick)\n' + '';
  } else if (timer_type == "on_ai") {
    Blockly.Python.definitions_['import_def'] = '' + 'import time\n' + 'from machine import Timer\n' + '\n' + 'def _on_timer(timer):\n' + statements_name + '\n' + 'from machine import Timer\n' + '_periodic_tim = Timer(Timer.TIMER0, Timer.CHANNEL0, mode=Timer.MODE_PERIODIC, period=' + text_period_timer_count + ', callback=_on_timer, arg=_on_timer)\n\n' + '_periodic_tim.start()\n' + '';
  } // TODO: Assemble Python into code variable.


  var code = '';
  return code;
};

Blockly.Blocks['esp32_main_controller_time_period_timer_clear'] = {
  init: function init() {
    this.appendDummyInput().appendField("").appendField(new Blockly.FieldDropdown([[Blockly.Msg.time_iot_module, "on_esp32"], [Blockly.Msg.time_ai_module, "on_ai"]]), "type").appendField(Blockly.Msg.time_timer_periodically_clear);
    this.setPreviousStatement(true, null);
    this.setNextStatement(true, null);
    this.setColour(ESP32_TIME_COLOR);
    var thisBlock = this;
    this.setTooltip(function () {
      var mode = thisBlock.getFieldValue('type');
      var TOOLTIPS = {
        'on_esp32': Blockly.Msg.Esp32_Main_Controller_Time_Period_Timer_Clear_TOOLTIP.replace('%1', Blockly.Msg.time_iot_module),
        'on_ai': Blockly.Msg.Esp32_Main_Controller_Time_Period_Timer_Clear_TOOLTIP.replace('%1', Blockly.Msg.time_ai_module)
      };
      return TOOLTIPS[mode];
    });
    this.setHelpUrl("");
  }
};

Blockly.Python['esp32_main_controller_time_period_timer_clear'] = function (block) {
  var timer_type = block.getFieldValue('type'); // TODO: Assemble Python into code variable.

  if (timer_type == "on_esp32") {
    var code = '_PRD_EXEC_TIMER.deinit()\n';
  } else if (timer_type == "on_ai") {
    var code = '_periodic_tim.stop()\n';
  }

  return code;
};

Blockly.Blocks['esp32_get_current_date'] = {
  init: function init() {
    this.appendDummyInput().appendField(Blockly.Msg.time_get_current_date_title).appendField(new Blockly.FieldDropdown([[Blockly.Msg.time_get_current_date_y, "0"], [Blockly.Msg.time_get_current_date_m, "1"], [Blockly.Msg.time_get_current_date_d, "2"], [Blockly.Msg.time_get_current_date_hour, "3"], [Blockly.Msg.time_get_current_date_min, "4"], [Blockly.Msg.time_get_current_date_sec, "5"]]), "type");
    this.setInputsInline(false);
    this.setOutput(true, null);
    this.setColour(ESP32_TIME_COLOR);
    var thisBlock = this;
    this.setTooltip(function () {
      var mode = thisBlock.getFieldValue('type');
      var TOOLTIPS = {
        '0': Blockly.Msg.Esp32_Get_Current_Date_TOOLTIP.replace('%1', Blockly.Msg.time_get_current_date_y),
        '1': Blockly.Msg.Esp32_Get_Current_Date_TOOLTIP.replace('%1', Blockly.Msg.time_get_current_date_m),
        '2': Blockly.Msg.Esp32_Get_Current_Date_TOOLTIP.replace('%1', Blockly.Msg.time_get_current_date_d),
        '3': Blockly.Msg.Esp32_Get_Current_Date_TOOLTIP.replace('%1', Blockly.Msg.time_get_current_date_hour),
        '4': Blockly.Msg.Esp32_Get_Current_Date_TOOLTIP.replace('%1', Blockly.Msg.time_get_current_date_min),
        '5': Blockly.Msg.Esp32_Get_Current_Date_TOOLTIP.replace('%1', Blockly.Msg.time_get_current_date_sec)
      };
      return TOOLTIPS[mode];
    });
    this.setHelpUrl("");
  }
};

Blockly.Python['esp32_get_current_date'] = function (block) {
  var dropdown_type = block.getFieldValue('type');
  Blockly.Python.definitions_['get_date_current_ntp'] = '' + 'import time\n' + '\n'; // TODO: Assemble Python into code variable.

  var code = 'time.localtime()[' + dropdown_type + ']'; // TODO: Change ORDER_NONE to the correct strength.

  return [code, Blockly.Python.ORDER_NONE];
};
/*
LCD
*/


var ESP32_SCREEN_COLOR = "#5bb2d6";
Blockly.Blocks['esp32_main_controller_lcd_rotation'] = {
  init: function init() {
    this.appendDummyInput().appendField(Blockly.Msg.OLCD_SETROTATION).appendField(new Blockly.FieldDropdown([["0°", "1"], ["90°", "2"], ["180°", "3"], ["270°", "0"]]), "DEGREE").appendField(Blockly.Msg.OLCD_SETROTATION_DEGREE);
    this.setPreviousStatement(true, null);
    this.setNextStatement(true, null);
    this.setColour("#5bb2d6");
    this.setTooltip('');
    this.setHelpUrl('');
  }
};

Blockly.Python['esp32_main_controller_lcd_rotation'] = function (block) {
  var degree = block.getFieldValue("DEGREE");
  var code = "tft.rotation(" + degree + ")\n"; // Blockly.Python.addSetup("setRotation", code);

  return code;
};

Blockly.Blocks['esp32_main_controller_clear_screen'] = {
  init: function init() {
    this.appendDummyInput().appendField(Blockly.Msg.display_clear_screen);
    this.setInputsInline(true);
    this.setPreviousStatement(true, null);
    this.setNextStatement(true, null);
    this.setColour(ESP32_SCREEN_COLOR);
    this.setTooltip("");
    this.setHelpUrl("");
  }
};

Blockly.Python['esp32_main_controller_clear_screen'] = function (block) {
  // TODO: Assemble Python into code variable.
  var code = 'tft.fill(TFT.BLACK)\n';
  return code;
};

Blockly.Blocks['esp32_main_controller_lcd_screen_fill'] = {
  init: function init() {
    this.appendDummyInput().appendField(Blockly.Msg.display_fill_screen);
    this.appendValueInput("COLOR").setCheck(null);
    this.setInputsInline(true);
    this.setPreviousStatement(true, null);
    this.setNextStatement(true, null);
    this.setColour(ESP32_SCREEN_COLOR);
    this.setTooltip("");
    this.setHelpUrl("");
  }
};

Blockly.Python['esp32_main_controller_lcd_screen_fill'] = function (block) {
  var value_lcd_rgb_value = Blockly.Python.valueToCode(block, 'COLOR', Blockly.Python.ORDER_ATOMIC); // TODO: Assemble Python into code variable.

  if (value_lcd_rgb_value.charAt(0) != '#') {
    var code = 'tft.fill(_TFTColor' + value_lcd_rgb_value + ')\n';
  } else if (value_lcd_rgb_value.charAt(0) == '#') {
    var d = 0,
      e = 0,
      f = 0;

    try {
      7 == color.length && (d = parseInt(color.substring(1, 3), 16), e = parseInt(color.substring(3, 5), 16), f = parseInt(color.substring(5, 7), 16));
    } catch (g) { }

    var code = "tft.fill(_TFTColor" + d + "," + e + "," + f + ")\n";
  }

  return code;
};

Blockly.Blocks['esp32_main_controller_lcd_drawpixel'] = {
  init: function init() {
    this.appendDummyInput().appendField(new Blockly.FieldImage("blockly/media/lcd_draw_pixel.png", 42, 42, {
      alt: "*",
      flipRtl: "FALSE"
    }));
    this.appendDummyInput().appendField(Blockly.Msg.OLCD_DRAW + Blockly.Msg.display_draw_pixel);
    this.appendValueInput("COLOR").setCheck("String").appendField(Blockly.Msg.OLCD_COLOR);
    this.appendValueInput("POS").setCheck("String").appendField(Blockly.Msg.OLCD_COORDINATE);
    this.setInputsInline(false);
    this.setPreviousStatement(true);
    this.setNextStatement(true);
    this.setColour("#5bb2d6");
    this.setTooltip('');
    this.setHelpUrl('');
  }
};

Blockly.Python['esp32_main_controller_lcd_drawpixel'] = function (block) {
  // var drawrectcolor = sharpTo565(
  //     Blockly.Python.valueToCode(block, 'COLOR', Blockly.Python.ORDER_ATOMIC));
  var drawrectcoord = Blockly.Python.valueToCode(block, 'POS', Blockly.Python.ORDER_ATOMIC);
  var color = Blockly.Python.valueToCode(block, 'COLOR', Blockly.Python.ORDER_ATOMIC);

  if (color.charAt(0) == '#') {
    var d = 0,
      e = 0,
      f = 0;

    try {
      7 == color.length && (d = parseInt(color.substring(1, 3), 16), e = parseInt(color.substring(3, 5), 16), f = parseInt(color.substring(5, 7), 16));
    } catch (g) { }

    code = "tft.pixel((" + drawrectcoord + "), _TFTColor" + d + "," + e + "," + f + ")\n";
  } else if (color.charAt(0) != '#') {
    code = "tft.pixel((" + drawrectcoord + "), _TFTColor" + color + ")\n";
  }

  return code;
};

Blockly.Blocks['esp32_main_controller_lcd_drawline'] = {
  init: function init() {
    this.appendDummyInput().appendField(new Blockly.FieldImage("blockly/media/lcd_draw_line.png", 42, 42, {
      alt: "*",
      flipRtl: "FALSE"
    })); // this.appendDummyInput()
    //     .appendField(
    //         new Blockly.FieldImage("./../blockly/media/line.png", 25, 25, "15"));

    this.appendDummyInput().appendField(Blockly.Msg.OLCD_DRAW + Blockly.Msg.OLCD_LINE);
    this.appendValueInput("COLOR").setCheck("String").appendField(Blockly.Msg.OLCD_COLOR);
    this.appendValueInput("POSA").setCheck("String").appendField(Blockly.Msg.OLCD_LINE_START);
    this.appendValueInput("POSB").setCheck("String").appendField(Blockly.Msg.OLCD_LINE_END);
    this.setInputsInline(false);
    this.setPreviousStatement(true);
    this.setNextStatement(true);
    this.setColour("#5bb2d6");
    this.setTooltip('');
    this.setHelpUrl('');
  }
};

Blockly.Python['esp32_main_controller_lcd_drawline'] = function (block) {
  // var drawlinecolor = sharpTo565(
  //     Blockly.Python.valueToCode(block, 'COLOR', Blockly.Python.ORDER_ATOMIC));
  var drawlinestart = Blockly.Python.valueToCode(block, 'POSA', Blockly.Python.ORDER_ATOMIC);
  var drawlineend = Blockly.Python.valueToCode(block, 'POSB', Blockly.Python.ORDER_ATOMIC);
  var color = Blockly.Python.valueToCode(block, 'COLOR', Blockly.Python.ORDER_ATOMIC);

  if (color.charAt(0) == '#') {
    var d = 0,
      e = 0,
      f = 0;

    try {
      7 == color.length && (d = parseInt(color.substring(1, 3), 16), e = parseInt(color.substring(3, 5), 16), f = parseInt(color.substring(5, 7), 16));
    } catch (g) { }

    code = "tft.line((" + drawlinestart + "), (" + drawlineend + "), _TFTColor" + d + "," + e + "," + f + ")\n";
  } else if (color.charAt(0) != '#') {
    code = "tft.line((" + drawlinestart + "), (" + drawlineend + "), _TFTColor" + color + ")\n";
  }

  return code;
};

Blockly.Blocks['esp32_main_controller_lcd_drawlinelen'] = {
  init: function init() {
    this.appendDummyInput().appendField(new Blockly.FieldImage("blockly/media/lcd_draw_line.png", 42, 42, {
      alt: "*",
      flipRtl: "FALSE"
    })); // this.appendDummyInput()
    //     .appendField(
    //         new Blockly.FieldImage("./../blockly/media/line.png", 25, 25, "15"));

    this.appendDummyInput().appendField(Blockly.Msg.OLCD_DRAW).appendField(new Blockly.FieldDropdown([[Blockly.Msg.display_draw_vertical, "vline"], [Blockly.Msg.display_draw_horizontal, "hline"]]), "rect_type").appendField(Blockly.Msg.OLCD_LINE);
    this.appendValueInput("COLOR").setCheck(null).appendField(Blockly.Msg.OLCD_COLOR);
    this.appendValueInput("POS").setCheck(null).appendField(Blockly.Msg.display_start_cord);
    this.appendValueInput("LENGTH").setCheck(null).appendField(Blockly.Msg.display_length);
    this.setInputsInline(false);
    this.setPreviousStatement(true);
    this.setNextStatement(true);
    this.setColour("#5bb2d6");
    this.setTooltip('');
    this.setHelpUrl('');
  }
};

Blockly.Python['esp32_main_controller_lcd_drawlinelen'] = function (block) {
  var _type = block.getFieldValue("rect_type");

  var color = Blockly.Python.valueToCode(block, 'COLOR', Blockly.Python.ORDER_ATOMIC);
  var drawlinestart = Blockly.Python.valueToCode(block, 'POS', Blockly.Python.ORDER_ATOMIC);
  var drawlineend = Blockly.Python.valueToCode(block, 'LENGTH', Blockly.Python.ORDER_ATOMIC);
  var color = Blockly.Python.valueToCode(block, 'COLOR', Blockly.Python.ORDER_ATOMIC);
  code = "tft." + _type + "((" + drawlinestart + "), " + drawlineend + ", _TFTColor" + color + ")\n";
  return code;
};

Blockly.Blocks['esp32_main_controller_lcd_drawrect'] = {
  init: function init() {
    this.appendDummyInput().appendField(new Blockly.FieldImage("blockly/media/lcd_draw_rectangle.png", 42, 42, {
      alt: "*",
      flipRtl: "FALSE"
    })); // this.appendDummyInput()
    //     .appendField(
    //         new Blockly.FieldImage("./../blockly/media/line.png", 25, 25, "15"));

    this.appendDummyInput().appendField(Blockly.Msg.OLCD_DRAW).appendField(new Blockly.FieldDropdown([[Blockly.Msg.OLCD_FULL, "fillrect"], [Blockly.Msg.OLCD_CIRCLE, "rect"]]), "rect_type").appendField(Blockly.Msg.display_draw_rectangle);
    this.appendValueInput("COLOR").setCheck("String").appendField(Blockly.Msg.OLCD_COLOR);
    this.appendValueInput("POSA").setCheck("String").appendField(Blockly.Msg.OLCD_COORDINATE);
    this.appendValueInput("POSB").setCheck("String").appendField(Blockly.Msg.OLCD_SIZE);
    this.setInputsInline(false);
    this.setPreviousStatement(true);
    this.setNextStatement(true);
    this.setColour("#5bb2d6");
    this.setTooltip('');
    this.setHelpUrl('');
  }
};

Blockly.Python['esp32_main_controller_lcd_drawrect'] = function (block) {
  // var drawlinecolor = sharpTo565(
  //     Blockly.Python.valueToCode(block, 'COLOR', Blockly.Python.ORDER_ATOMIC));
  var _type = block.getFieldValue("rect_type");

  var drawlinestart = Blockly.Python.valueToCode(block, 'POSA', Blockly.Python.ORDER_ATOMIC);
  var drawlineend = Blockly.Python.valueToCode(block, 'POSB', Blockly.Python.ORDER_ATOMIC);
  var color = Blockly.Python.valueToCode(block, 'COLOR', Blockly.Python.ORDER_ATOMIC);
  code = "tft." + _type + "((" + drawlinestart + "), (" + drawlineend + "), _TFTColor" + color + ")\n";
  return code;
};

Blockly.Blocks['esp32_main_controller_lcd_drawcircle'] = {
  init: function init() {
    this.appendDummyInput().appendField(new Blockly.FieldImage("blockly/media/lcd_draw_circle.png", 42, 42, {
      alt: "*",
      flipRtl: "FALSE"
    }));
    this.appendDummyInput().appendField(Blockly.Msg.OLCD_DRAW).appendField(new Blockly.FieldDropdown([[Blockly.Msg.OLCD_FULL, "fillcircle"], [Blockly.Msg.OLCD_STROKED, "circle"]]), "circle_type").appendField(Blockly.Msg.OLCD_CIRCLE);
    this.appendValueInput("COLOR").setCheck("String").appendField(Blockly.Msg.OLCD_COLOR);
    this.appendValueInput("POSA").setCheck("String").appendField(Blockly.Msg.OLCD_CENTER_POS);
    this.appendValueInput("RADIUS").setCheck(null).appendField(Blockly.Msg.OLCD_RADIUS);
    this.setInputsInline(false);
    this.setPreviousStatement(true);
    this.setNextStatement(true);
    this.setColour("#5bb2d6");
    this.setTooltip('');
    this.setHelpUrl('');
  }
};

Blockly.Python['esp32_main_controller_lcd_drawcircle'] = function (block) {
  // var drawcirclecolor = sharpTo565(
  //     Blockly.Python.valueToCode(block, 'COLOR', Blockly.Python.ORDER_ATOMIC));
  var circletype = block.getFieldValue('circle_type');
  var position = Blockly.Python.valueToCode(block, 'POSA', Blockly.Python.ORDER_ATOMIC);
  var radius = Blockly.Python.valueToCode(block, 'RADIUS', Blockly.Python.ORDER_ATOMIC);
  var color = Blockly.Python.valueToCode(block, 'COLOR', Blockly.Python.ORDER_ATOMIC);
  code = 'tft.' + circletype + '((' + position + '), ' + radius + ', _TFTColor' + color + ')\n';
  return code;
};

Blockly.Blocks['esp32_main_controller_lcd_drawqrcode'] = {
  init: function init() {
    this.appendDummyInput().appendField(new Blockly.FieldImage("blockly/media/lcd_draw_qr.png", 42, 42, {
      alt: "*",
      flipRtl: "FALSE"
    })); // this.appendDummyInput()
    //     .appendField(
    //         new Blockly.FieldImage("./../blockly/media/circle.png", 25, 25, "15"));

    this.appendDummyInput().appendField(Blockly.Msg.OLCD_DRAW + Blockly.Msg.display_drawqr_text);
    this.appendValueInput("POSA").setCheck("String").appendField(Blockly.Msg.OLCD_SET_POS);
    this.appendValueInput("CONTENT").setCheck("String").appendField(Blockly.Msg.display_drawqr_content);
    this.appendValueInput("WIDTH").setCheck("Number").appendField(Blockly.Msg.display_drawqr_padding);
    this.setInputsInline(false);
    this.setPreviousStatement(true);
    this.setNextStatement(true);
    this.setColour("#5bb2d6");
    this.setTooltip('');
    this.setHelpUrl('');
  }
};

Blockly.Python['esp32_main_controller_lcd_drawqrcode'] = function (block) {
  var position = Blockly.Python.valueToCode(block, 'POSA', Blockly.Python.ORDER_ATOMIC);
  var content = Blockly.Python.valueToCode(block, 'CONTENT', Blockly.Python.ORDER_ATOMIC);
  var width = Blockly.Python.valueToCode(block, 'WIDTH', Blockly.Python.ORDER_ATOMIC);
  var code = 'tft.drawqrcode(' + '(' + position + '), ' + content + ', ' + width + ')\n';
  return code;
};

Blockly.Blocks['esp32_main_controller_lcd_drawtext'] = {
  init: function init() {
    this.appendDummyInput().appendField(new Blockly.FieldImage("blockly/media/lcd_draw_text.png", 42, 42, {
      alt: "*",
      flipRtl: "FALSE"
    })); // this.appendDummyInput()
    //     .appendField(
    //         new Blockly.FieldImage("./../blockly/media/circle.png", 25, 25, "15"));

    this.appendDummyInput().appendField(Blockly.Msg.OLCD_DRAW + Blockly.Msg.display_draw_text);
    this.appendValueInput("COLOR").setCheck("String").appendField(Blockly.Msg.OLCD_COLOR);
    this.appendValueInput("POSA").setCheck("String").appendField(Blockly.Msg.display_start_cord);
    this.appendValueInput("CONTENT").setCheck("String").appendField(Blockly.Msg.display_draw_text_content);
    this.appendValueInput("SIZE").setCheck("Number").appendField(Blockly.Msg.display_draw_text_size);
    this.appendDummyInput().appendField(Blockly.Msg.display_draw_text_return).appendField(new Blockly.FieldCheckbox('TRUE'), 'TextCheckBox');
    this.setInputsInline(false);
    this.setPreviousStatement(true);
    this.setNextStatement(true);
    this.setColour("#5bb2d6");
    this.setTooltip('');
    this.setHelpUrl('');
  }
};

Blockly.Python['esp32_main_controller_lcd_drawtext'] = function (block) {
  // var drawcirclecolor = sharpTo565(
  //     Blockly.Python.valueToCode(block, 'COLOR', Blockly.Python.ORDER_ATOMIC));
  var position = Blockly.Python.valueToCode(block, 'POSA', Blockly.Python.ORDER_ATOMIC);
  var content = Blockly.Python.valueToCode(block, 'CONTENT', Blockly.Python.ORDER_ATOMIC);
  var size = Blockly.Python.valueToCode(block, 'SIZE', Blockly.Python.ORDER_ATOMIC);
  var box = block.getFieldValue('TextCheckBox') == "TRUE" ? "True" : "False";
  var color = Blockly.Python.valueToCode(block, 'COLOR', Blockly.Python.ORDER_ATOMIC);
  code = 'tft.text((' + position + '), ' + content + ', _TFTColor' + color + ', sysfont, ' + size + ', nowrap=' + box + ')\n';
  return code;
};

Blockly.Blocks['esp32_main_controller_rgb_value'] = {
  init: function init() {
    this.appendValueInput("rgb_value_r").setCheck(null).appendField(Blockly.Msg.display_red);
    this.appendValueInput("rgb_value_g").setCheck(null).appendField(Blockly.Msg.display_green);
    this.appendValueInput("rgb_value_b").setCheck(null).appendField(Blockly.Msg.display_blue);
    this.setInputsInline(true);
    this.setOutput(true, null);
    this.setColour(ESP32_SCREEN_COLOR);
    this.setTooltip("");
    this.setHelpUrl("");
  }
};

Blockly.Python['esp32_main_controller_rgb_value'] = function (block) {
  var r = Blockly.Python.valueToCode(block, 'rgb_value_r', Blockly.Python.ORDER_ATOMIC);
  var g = Blockly.Python.valueToCode(block, 'rgb_value_g', Blockly.Python.ORDER_ATOMIC);
  var b = Blockly.Python.valueToCode(block, 'rgb_value_b', Blockly.Python.ORDER_ATOMIC);
  var original_r = parseInt(r, 10);
  var original_g = parseInt(g, 10);
  var original_b = parseInt(b, 10);
  _r = original_r.toString(16);
  _g = original_g.toString(16);
  _b = original_b.toString(16);
  if (_r.length == 1) _r = "0" + _r;
  if (_g.length == 1) _g = "0" + _g;
  if (_b.length == 1) _b = "0" + _b; // TODO: Assemble Python into code variable.

  var code = '' + r + ',' + g + ',' + b + ''; // TODO: Change ORDER_NONE to the correct strength.

  return [code, Blockly.Python.ORDER_NONE];
};

Blockly.Blocks['esp32_main_controller_lcd_color_hex_to_rgb'] = {
  init: function init() {
    this.appendDummyInput().appendField(Blockly.Msg.COLOR).appendField(new Blockly.FieldColour("#ff0000"), "COLOR");
    this.setOutput(true, null);
    this.setColour("#5bb2d6");
    this.setTooltip('');
    this.setHelpUrl('');
  }
};

Blockly.Python['esp32_main_controller_lcd_color_hex_to_rgb'] = function (a) {
  a = a.getFieldValue("COLOR"); // var d = 0
  //     , e = 0
  //     , f = 0;
  // try {
  //     7 == a.length && (d = a.substring(1, 3),
  //         e = a.substring(3, 5),
  //         f = a.substring(5, 7));
  // }
  // catch (g) { }

  var gethex = a;

  function hexToRGB(h) {
    var r = 0,
      g = 0,
      b = 0; // 3 digits

    if (h.length == 4) {
      r = "0x" + h[1] + h[1];
      g = "0x" + h[2] + h[2];
      b = "0x" + h[3] + h[3]; // 6 digits
    } else if (h.length == 7) {
      r = "0x" + h[1] + h[2];
      g = "0x" + h[3] + h[4];
      b = "0x" + h[5] + h[6];
    }

    return "" + +r + "," + +g + "," + +b + "";
  }

  var _code = hexToRGB(gethex); //_code += "tft.fill(TFT.TFTColor(FS_COLOR))\n";


  return [_code, Blockly.Python.ORDER_CONDITIONAL];
};
/*
WiFi
*/


var ESP32_WIFI_COLOR = "#3062c1";
Blockly.Blocks['esp32_main_controller_wifi_enable_hotspot_mode'] = {
  init: function init() {
    this.appendDummyInput().appendField(new Blockly.FieldImage("blockly/media/hotspot_setup.png", 38, 38, {
      alt: "*",
      flipRtl: "FALSE"
    }));
    this.appendDummyInput().appendField(Blockly.Msg.wifi_setup_hotspot);
    this.appendValueInput("SSID").setCheck(null).appendField(Blockly.Msg.wifi_hotspot_ssid);
    this.appendValueInput("PASSWORD").setCheck(null).appendField(Blockly.Msg.wifi_hotspot_pass);
    this.setInputsInline(false);
    this.setPreviousStatement(true, null);
    this.setNextStatement(true, null);
    this.setColour(ESP32_WIFI_COLOR);
    this.setTooltip(Blockly.Msg.Esp32_Main_Controller_Wifi_Enable_Hotspot_Mode_TOOLTIP);
    this.setHelpUrl("");
  }
};

Blockly.Python['esp32_main_controller_wifi_enable_hotspot_mode'] = function (block) {
  var text_ssid = Blockly.Python.valueToCode(block, 'SSID', Blockly.Python.ORDER_ATOMIC);
  var text_password = Blockly.Python.valueToCode(block, 'PASSWORD', Blockly.Python.ORDER_ATOMIC);

  var _code = '' + '_WIFI = network.WLAN(network.STA_IF)\n' + '_WIFI.active(False)\n' + '_WIFI = network.WLAN(network.AP_IF)\n' + '_WIFI.active(True)\n';

  Blockly.Python.definitions_['import_network'] = 'import network\n' + _code + '_WIFI.config(essid=' + text_ssid + ', password=' + text_password + ', authmode=2, channel=11, hidden=0)\n' + '\n';
  code = '';
  return code;
};

Blockly.Blocks['esp32_main_controller_wifi_connect_internet'] = {
  init: function init() {
    this.appendDummyInput().appendField(new Blockly.FieldImage("blockly/media/wifi_setup.png", 38, 38, {
      alt: "*",
      flipRtl: "FALSE"
    }));
    this.appendDummyInput().appendField(Blockly.Msg.wifi_connect_router);
    this.appendValueInput("ssid").setCheck(null).appendField(Blockly.Msg.wifi_router_ssid);
    this.appendValueInput("password").setCheck(null).appendField(Blockly.Msg.wifi_router_pass);
    this.setInputsInline(false);
    this.setPreviousStatement(true, null);
    this.setNextStatement(true, null);
    this.setColour(ESP32_WIFI_COLOR);
    this.setTooltip(Blockly.Msg.Esp32_Main_Controller_Wifi_Connect_Internet_TOOLTIP);
    this.setHelpUrl("");
  }
};

Blockly.Python['esp32_main_controller_wifi_connect_internet'] = function (block) {
  var text_ssid = Blockly.Python.valueToCode(block, 'ssid', Blockly.Python.ORDER_ATOMIC);
  var text_password = Blockly.Python.valueToCode(block, 'password', Blockly.Python.ORDER_ATOMIC);
  Blockly.Python.definitions_['esp32_import_network'] = '' + 'import network\n' + 'if (network.WLAN(network.STA_IF).isconnected()) == False:\n' + '    _WIFI = network.WLAN(network.AP_IF)\n' + '    _WIFI.active(False)\n' + '    _WIFI = network.WLAN(network.STA_IF)\n' + '    _WIFI.active(True)\n' + '    _WIFI.connect(' + text_ssid + ', ' + text_password + ')\n' + 'else:\n' + '    pass\n' + '\n';
  var code = '';
  return code;
};

Blockly.Blocks['esp32_main_controller_wifi_disconnect'] = {
  init: function init() {
    this.appendDummyInput().appendField(Blockly.Msg.wifi_router_disconnect);
    this.setInputsInline(false);
    this.setPreviousStatement(true, null);
    this.setNextStatement(true, null);
    this.setColour(ESP32_WIFI_COLOR);
    this.setTooltip(Blockly.Msg.Esp32_Main_Controller_Wifi_Disconnect_TOOLTIP);
    this.setHelpUrl("");
  }
};

Blockly.Python['esp32_main_controller_wifi_disconnect'] = function (block) {
  // TODO: Assemble Python into code variable.
  var code = '_WIFI.active(False)\n';
  return code;
};

Blockly.Blocks['esp32_main_controller_get_wifi_devices_number'] = {
  init: function init() {
    this.appendDummyInput().appendField(Blockly.Msg.wifi_hotspot_get_clients);
    this.setOutput(true, null);
    this.setColour(ESP32_WIFI_COLOR);
    this.setTooltip(Blockly.Msg.Esp32_Main_Controller_Get_Wifi_Devices_Number_TOOLTIP);
    this.setHelpUrl("");
  }
};

Blockly.Python['esp32_main_controller_get_wifi_devices_number'] = function (block) {
  // TODO: Assemble Python into code variable.
  var code = 'len(_WIFI.status("stations"))'; // TODO: Change ORDER_NONE to the correct strength.

  return [code, Blockly.Python.ORDER_CONDITIONAL];
};

Blockly.Blocks['esp32_main_controller_wifi_acquiring_equipment'] = {
  init: function init() {
    this.appendDummyInput().appendField(Blockly.Msg.wifi_hotspot_get_list);
    this.setOutput(true, null);
    this.setColour(ESP32_WIFI_COLOR);
    this.setTooltip(Blockly.Msg.Esp32_Main_Controller_Wifi_Acquiring_Equipment_TOOLTIP);
    this.setHelpUrl("");
  }
};

Blockly.Python['esp32_main_controller_wifi_acquiring_equipment'] = function (block) {
  // TODO: Assemble Python into code variable.
  var code = '_WIFI.status("stations")'; // TODO: Change ORDER_NONE to the correct strength.

  return [code, Blockly.Python.ORDER_CONDITIONAL];
};

Blockly.Blocks['esp32_main_controller_get_wifi_connection_status'] = {
  init: function init() {
    this.appendDummyInput().appendField(Blockly.Msg.wifi_router_connection_status);
    this.setOutput(true, null);
    this.setColour(ESP32_WIFI_COLOR);
    this.setTooltip(Blockly.Msg.Esp32_Main_Controller_Get_Wifi_Connection_Status_TOOLTIP);
    this.setHelpUrl("");
  }
};

Blockly.Python['esp32_main_controller_get_wifi_connection_status'] = function (block) {
  // TODO: Assemble Python into code variable.
  var code = '_WIFI.isconnected()'; // TODO: Change ORDER_NONE to the correct strength.

  return [code, Blockly.Python.ORDER_CONDITIONAL];
};

Blockly.Blocks['esp32_main_controller_wifi_close'] = {
  init: function init() {
    this.appendDummyInput().appendField(Blockly.Msg.wifi_close_hotspot);
    this.setPreviousStatement(true, null);
    this.setNextStatement(true, null);
    this.setColour(ESP32_WIFI_COLOR);
    this.setTooltip(Blockly.Msg.Esp32_Main_Controller_Wifi_Close_TOOLTIP);
    this.setHelpUrl("");
  }
};

Blockly.Python['esp32_main_controller_wifi_close'] = function (block) {
  // TODO: Assemble Python into code variable.
  var code = '_WIFI.active(False)'; // TODO: Change ORDER_NONE to the correct strength.

  return [code, Blockly.Python.ORDER_CONDITIONAL];
};

Blockly.Blocks['esp32_main_controller_wifi_get_info'] = {
  init: function init() {
    this.appendDummyInput().appendField(Blockly.Msg.wifi_router_get_info).appendField(new Blockly.FieldDropdown([[Blockly.Msg.wifi_router_device_ip, "0"], [Blockly.Msg.wifi_router_device_mask, "1"], [Blockly.Msg.wifi_router_device_gateway, "2"], [Blockly.Msg.wifi_router_device_dns, "3"]]), "wifi_info");
    this.setOutput(true, null);
    this.setColour(ESP32_WIFI_COLOR);
    var thisBlock = this;
    this.setTooltip(function () {
      var mode = thisBlock.getFieldValue('wifi_info');
      var TOOLTIPS = {
        '0': Blockly.Msg.Esp32_Main_Controller_Wifi_Get_Info_TOOLTIP.replace('%1', Blockly.Msg.wifi_router_device_ip),
        '1': Blockly.Msg.Esp32_Main_Controller_Wifi_Get_Info_TOOLTIP.replace('%1', Blockly.Msg.wifi_router_device_mask),
        '2': Blockly.Msg.Esp32_Main_Controller_Wifi_Get_Info_TOOLTIP.replace('%1', Blockly.Msg.wifi_router_device_gateway),
        '3': Blockly.Msg.Esp32_Main_Controller_Wifi_Get_Info_TOOLTIP.replace('%1', Blockly.Msg.wifi_router_device_dns)
      };
      return TOOLTIPS[mode];
    });
    this.setHelpUrl("");
  }
};

Blockly.Python['esp32_main_controller_wifi_get_info'] = function (block) {
  var dropdown_name = block.getFieldValue('wifi_info'); // TODO: Assemble Python into code variable.

  var code = '_WIFI.ifconfig()[' + dropdown_name + ']'; // TODO: Change ORDER_NONE to the correct strength.

  return [code, Blockly.Python.ORDER_CONDITIONAL];
};

Blockly.Blocks['esp32_main_controller_wifi_ntptime'] = {
  init: function init() {
    this.appendDummyInput().appendField(new Blockly.FieldImage("blockly/media/ntptime_header.png", 38, 38, {
      alt: "*",
      flipRtl: "FALSE"
    }));
    this.appendDummyInput().appendField(Blockly.Msg.wifi_ntptime_title);
    this.appendDummyInput().appendField(Blockly.Msg.wifi_ntptime_set_timezone).appendField(new Blockly.FieldDropdown([[Blockly.Msg.wifi_ntptime_utc8, "8"], [Blockly.Msg.wifi_ntptime_utc9, "9"], [Blockly.Msg.wifi_ntptime_utc10, "10"], [Blockly.Msg.wifi_ntptime_utc11, "11"], [Blockly.Msg.wifi_ntptime_utc12, "12"], [Blockly.Msg.wifi_ntptime_utcm12, "-12"], [Blockly.Msg.wifi_ntptime_utcm11, "-11"], [Blockly.Msg.wifi_ntptime_utcm10, "-10"], [Blockly.Msg.wifi_ntptime_utcm9, "-9"], [Blockly.Msg.wifi_ntptime_utcm8, "-8"], [Blockly.Msg.wifi_ntptime_utcm7, "-7"], [Blockly.Msg.wifi_ntptime_utcm6, "-6"], [Blockly.Msg.wifi_ntptime_utcm5, "-5"], [Blockly.Msg.wifi_ntptime_utcm4, "-4"], [Blockly.Msg.wifi_ntptime_utcm3, "-3"], [Blockly.Msg.wifi_ntptime_utcm2, "-2"], [Blockly.Msg.wifi_ntptime_utcm1, "-1"], [Blockly.Msg.wifi_ntptime_utc0, "0"], [Blockly.Msg.wifi_ntptime_utc1, "1"], [Blockly.Msg.wifi_ntptime_utc2, "2"], [Blockly.Msg.wifi_ntptime_utc3, "3"], [Blockly.Msg.wifi_ntptime_utc4, "4"], [Blockly.Msg.wifi_ntptime_utc5, "5"], [Blockly.Msg.wifi_ntptime_utc6, "6"], [Blockly.Msg.wifi_ntptime_utc7, "7"]]), "timezone");
    this.appendDummyInput().appendField(Blockly.Msg.wifi_ntptime_time_server).appendField(new Blockly.FieldTextInput("time.windows.com"), "website");
    this.setInputsInline(false);
    this.setPreviousStatement(true, null);
    this.setNextStatement(true, null);
    this.setColour(ESP32_WIFI_COLOR);
    this.setTooltip(Blockly.Msg.Esp32_Main_Controller_Wifi_Ntptime_TOOLTIP);
    this.setHelpUrl("");
  }
};

Blockly.Python['esp32_main_controller_wifi_ntptime'] = function (block) {
  var dropdown_timezone = block.getFieldValue('timezone');
  var text_website = block.getFieldValue('website');
  Blockly.Python.definitions_['esp32_main_controller_wifi_ntptime_def'] = '' + 'import network\n' + 'import ntptime\n' + '\n'; // TODO: Assemble Python into code variable.

  var code = 'ntptime.settime(' + dropdown_timezone + ', "' + text_website + '")\n';
  return code;
};
/*
IoT Service 
*/


Blockly.Blocks['esp32_main_controller_ThingSpeak_send_data'] = {
  init: function init() {
    this.appendDummyInput().appendField(new Blockly.FieldImage("blockly/media/thingspeak.png", 190, 50, {
      alt: "*",
      flipRtl: "FALSE"
    }));
    this.appendDummyInput().appendField(Blockly.Msg.iotservice_thingspeak_send_title);
    this.appendDummyInput().appendField(Blockly.Msg.iotservice_thingspeak_send_api_set).appendField(new Blockly.FieldTextInput("ENTER_YOUR_CHANNEL_API_KEY"), "key");
    this.appendValueInput("data").setCheck(null).appendField(Blockly.Msg.iotservice_thingspeak_send_data_1);
    this.setPreviousStatement(true, null);
    this.setNextStatement(true, null);
    this.setColour(ESP32_IOT_COLOR);
    this.setTooltip("");
    this.setHelpUrl("");
  }
};

Blockly.Python['esp32_main_controller_ThingSpeak_send_data'] = function (block) {
  var text_key = block.getFieldValue('key');
  var data = Blockly.Python.valueToCode(block, 'data', Blockly.Python.ORDER_ATOMIC);
  Blockly.Python.definitions_['import_urequests'] = '' + 'import urequests\n' + 'import ujson as json\n';
  '';
  var code = '_THINGSPEAK_CHANNEL_API = "' + text_key + '"\n';
  Blockly.Python.addSetup("esp32_main_controller_ThingSpeak_send_data", code);
  var code = '_THINGSPEAK_DATA1 = ' + data + '\n';
  code += '_THINGSPEAK_ENDPOINT = "http://api.thingspeak.com/update?api_key=" + _THINGSPEAK_CHANNEL_API + "&field1=" + _THINGSPEAK_DATA1\n';
  code += '_THINGSPEAK_REQEUST = urequests.get(_THINGSPEAK_ENDPOINT)\n';
  return code;
};

Blockly.Blocks['CocoRobo_set_max'] = {
  init: function init() {
    this.appendDummyInput().appendField(new Blockly.FieldImage("blockly/media/http_server_header.png", 130, 50, {
      alt: "*",
      flipRtl: "FALSE"
    }));
    this.appendDummyInput().appendField(Blockly.Msg.internet_server_setup);
    this.appendDummyInput().appendField(Blockly.Msg.internet_server_set_max).appendField(new Blockly.FieldTextInput("5"), "number");
    this.setPreviousStatement(true, null);
    this.setNextStatement(true, null);
    this.setColour("#183895");
    this.setTooltip("");
    this.setHelpUrl("");
  }
};

Blockly.Python['CocoRobo_set_max'] = function (block) {
  var number = block.getFieldValue('number');
  Blockly.Python.definitions_['import_socket'] = 'import usocket as socket';
  var code = '_S = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n';
  code += '_S.bind((_WIFI.ifconfig()[0], 80))\n';
  code += '_S.listen(' + number + ')\n';
  Blockly.Python.addSetup("CocoRobo_set_max", code);
  var code = '_SERVER_CONN, _SERVER_ADDR = _S.accept()\n';
  code += '_SERVER_REQUEST = _CONN.recv(1024)\n';
  return code;
};

Blockly.Blocks['CocoRobo_get_source'] = {
  init: function init() {
    this.appendDummyInput().appendField(Blockly.Msg.internet_server_set_source);
    this.setOutput(true, null);
    this.setColour("#183895");
    this.setTooltip("");
    this.setHelpUrl("");
  }
};

Blockly.Python['CocoRobo_get_source'] = function (block) {
  var code = 'str(_SERVER_ADDR)\n';
  return [code, Blockly.Python.ORDER_CONDITIONAL];
};

Blockly.Blocks['CocoRobo_get'] = {
  init: function init() {
    this.appendDummyInput().appendField(Blockly.Msg.internet_response_http_content_title).appendField(new Blockly.FieldDropdown([[Blockly.Msg.internet_response_text, "text"], [Blockly.Msg.internet_response_content, "content"], [Blockly.Msg.internet_response_status, "state"], [Blockly.Msg.internet_response_json, "json"], [Blockly.Msg.internet_response_encode, "code"], [Blockly.Msg.internet_response_reason, "reason"]]), "op");
    this.setOutput(true, null);
    this.setColour("#183895");
    this.setTooltip(Blockly.Msg.CocoRobo_get_TOOLTIP);
    this.setHelpUrl("");
  }
};

Blockly.Python['CocoRobo_get'] = function (block) {
  var op = block.getFieldValue('op');
  var code = '_SEND_HTTP_REQUEST.text';

  if (op == "text") {
    code = '_SEND_HTTP_REQUEST.text';
  } else if (op == "content") {
    code = '_SEND_HTTP_REQUEST.content';
  } else if (op == "state") {
    code = '_SEND_HTTP_REQUEST.status_code';
  } else if (op == "json") {
    code = '_SEND_HTTP_REQUEST.json()';
  } else if (op == "code") {
    code = '_SEND_HTTP_REQUEST.encoding';
  } else if (op == "reason") {
    code = '_SEND_HTTP_REQUEST.reason';
  }

  return [code, Blockly.Python.ORDER_CONDITIONAL];
};

Blockly.Blocks['iot_system_run'] = {
  init: function init() {
    this.appendDummyInput().appendField(Blockly.Msg.SYSTEM_RUN);
    this.appendValueInput("PATH").setCheck(null).appendField(Blockly.Msg.system_code_path);
    this.setInputsInline(false);
    this.setPreviousStatement(true, null);
    this.setNextStatement(true, null);
    this.setColour(32);
    this.setTooltip(Blockly.Msg.Iot_System_Run_TOOLTIP);
    this.setHelpUrl("");
  }
};

Blockly.Python.iot_system_run = function (block) {
  var _path = Blockly.Python.valueToCode(block, 'PATH', Blockly.Python.ORDER_ATOMIC);

  var _code = "exec(open(" + _path + ").read())\n";

  return _code;
};

Blockly.Blocks['iot_system_create'] = {
  init: function init() {
    this.appendDummyInput().appendField(Blockly.Msg.SYSTEM_CREATE);
    this.appendValueInput("PATH").setCheck(null).appendField(Blockly.Msg.SYSTEM_CREATE_F);
    this.setInputsInline(false);
    this.setPreviousStatement(true, null);
    this.setNextStatement(true, null);
    this.setColour(32);
    this.setTooltip(Blockly.Msg.Iot_System_Create_TOOLTIP);
    this.setHelpUrl("");
  }
};

Blockly.Python.iot_system_create = function (block) {
  var _path = Blockly.Python.valueToCode(block, 'PATH', Blockly.Python.ORDER_ATOMIC);

  var _code = "def _CREATE_TEXT_FILE(_path):\n";
  _code += "    f = open(_path, 'w')\n";
  _code += "    f.close()\n";
  Blockly.Python.addFunction("_CREATE_TEXT_FILE", _code);
  _code = "_CREATE_TEXT_FILE(" + _path + ")\n";
  return _code;
};

Blockly.Blocks['iot_system_write'] = {
  init: function init() {
    this.appendDummyInput().appendField(Blockly.Msg.SYSTEM_WRITE);
    this.appendValueInput("PATH").setCheck(null).appendField(Blockly.Msg.SYSTEM_WRITE_F);
    this.appendValueInput("WPATH").setCheck(null).appendField(Blockly.Msg.SYSTEM_WRITE_W);
    this.appendDummyInput().appendField(Blockly.Msg.SYSTEM_WRITE_S).appendField(new Blockly.FieldDropdown([[Blockly.Msg.SYSTEM_WRITE_S_N, "newline"], [Blockly.Msg.SYSTEM_WRITE_S_C, "comma"], [Blockly.Msg.SYSTEM_WRITE_S_S, "space"], [Blockly.Msg.SYSTEM_WRITE_S_SE, "semicolon"]]), "separator");
    this.setInputsInline(false);
    this.setPreviousStatement(true, null);
    this.setNextStatement(true, null);
    this.setColour(32);
    this.setHelpUrl("");
    var thisBlock = this;
    this.setTooltip(function () {
      var mode = thisBlock.getFieldValue('separator');
      var TOOLTIPS = {
        'newline': Blockly.Msg.Iot_System_Write_TOOLTIP.replace('%1', Blockly.Msg.SYSTEM_WRITE_S_N),
        'comma': Blockly.Msg.Iot_System_Write_TOOLTIP.replace('%1', Blockly.Msg.SYSTEM_WRITE_S_C),
        'space': Blockly.Msg.Iot_System_Write_TOOLTIP.replace('%1', Blockly.Msg.SYSTEM_WRITE_S_S),
        'semicolon': Blockly.Msg.Iot_System_Write_TOOLTIP.replace('%1', Blockly.Msg.SYSTEM_WRITE_S_SE)
      };
      return TOOLTIPS[mode];
    });
  }
};

Blockly.Python.iot_system_write = function (block) {
  var _path = Blockly.Python.valueToCode(block, 'PATH', Blockly.Python.ORDER_ATOMIC);

  var _wpath = Blockly.Python.valueToCode(block, 'WPATH', Blockly.Python.ORDER_ATOMIC);

  var _separator = block.getFieldValue('separator');

  var _code = "def _CREATE_TEXT_FILE_WITH_CONTENT(_path, _data, _sep):\n";
  _code += "    f = open(_path, 'a')\n";
  _code += "    f.write(_data + _sep)\n";
  _code += "    f.close()\n";
  Blockly.Python.addFunction("_CREATE_TEXT_FILE_WITH_CONTENT", _code);
  _code = "_CREATE_TEXT_FILE_WITH_CONTENT(" + _path + ", " + _wpath + ", '\\r\\n')";

  if (_separator == "newline") {
    _code = "_CREATE_TEXT_FILE_WITH_CONTENT(" + _path + ", " + _wpath + ", '\\r\\n')";
  } else if (_separator == "comma") {
    _code = "_CREATE_TEXT_FILE_WITH_CONTENT(" + _path + ", " + _wpath + ", ',')";
  } else if (_separator == "space") {
    _code = "_CREATE_TEXT_FILE_WITH_CONTENT(" + _path + ", " + _wpath + ", ' ')";
  } else if (_separator == "semicolon") {
    _code = "_CREATE_TEXT_FILE_WITH_CONTENT(" + _path + ", " + _wpath + ", ';')";
  }

  return _code;
};

Blockly.Blocks['iot_system_input'] = {
  init: function init() {
    this.appendDummyInput().appendField(Blockly.Msg.SYSTEM_INPUT);
    this.appendValueInput("PATH").setCheck(null).appendField(Blockly.Msg.SYSTEM_WRITE_F);
    this.appendDummyInput().appendField(Blockly.Msg.SYSTEM_WRITE_S).appendField(new Blockly.FieldDropdown([[Blockly.Msg.SYSTEM_WRITE_S_N, "newline"], [Blockly.Msg.SYSTEM_WRITE_S_C, "comma"], [Blockly.Msg.SYSTEM_WRITE_S_S, "space"], [Blockly.Msg.SYSTEM_WRITE_S_SE, "semicolon"]]), "separator");
    this.setInputsInline(false);
    this.setPreviousStatement(true, null);
    this.setNextStatement(true, null);
    this.setColour(32);
    // this.setTooltip("");
    this.setHelpUrl("");
    var thisBlock = this;
    this.setTooltip(function () {
      var mode = thisBlock.getFieldValue('separator');
      var TOOLTIPS = {
        'newline': Blockly.Msg.Iot_System_Input_TOOLTIP.replace('%1', Blockly.Msg.SYSTEM_WRITE_S_N),
        'comma': Blockly.Msg.Iot_System_Input_TOOLTIP.replace('%1', Blockly.Msg.SYSTEM_WRITE_S_C),
        'space': Blockly.Msg.Iot_System_Input_TOOLTIP.replace('%1', Blockly.Msg.SYSTEM_WRITE_S_S),
        'semicolon': Blockly.Msg.Iot_System_Input_TOOLTIP.replace('%1', Blockly.Msg.SYSTEM_WRITE_S_SE)
      };
      return TOOLTIPS[mode];
    });
  }
};

Blockly.Python.iot_system_input = function (block) {
  var _path = Blockly.Python.valueToCode(block, 'PATH', Blockly.Python.ORDER_ATOMIC);

  var _separator = block.getFieldValue('separator');

  var _code = "def _GET_LIST_FROM_FILE(_path, _sep):\n";
  _code += "    f = open(_path, 'r')\n";
  _code += "    result = f.read().split(_sep)\n";
  _code += "    f.close()\n";
  _code += "    return result\n";
  Blockly.Python.addFunction("_GET_LIST_FROM_FILE", _code);
  _code = "_GET_LIST_FROM_FILE(" + _path + ", '\\r\\n')";

  if (_separator == "newline") {
    _code = "_GET_LIST_FROM_FILE(" + _path + ", '\\r\\n')";
  } else if (_separator == "comma") {
    _code = "_GET_LIST_FROM_FILE(" + _path + ", ',')";
  } else if (_separator == "space") {
    _code = "_GET_LIST_FROM_FILE(" + _path + ", ' ')";
  } else if (_separator == "semicolon") {
    _code = "_GET_LIST_FROM_FILE(" + _path + ", ';')";
  }

  return _code;
};

Blockly.Blocks['iot_system_restart'] = {
  init: function init() {
    this.appendDummyInput().appendField(Blockly.Msg.SYSTEM);
    this.setPreviousStatement(true);
    this.setNextStatement(true);
    this.setColour("#22398e");
    this.setTooltip(Blockly.Msg.Iot_System_Restart_TOOLTIP);
    this.setHelpUrl("");
  }
};

Blockly.Python.iot_system_restart = function (block) {
  Blockly.Python.definitions_.import_machine = "import machine";
  var _code = "machine.reset()\n";
  return _code;
};

Blockly.Blocks['iot_system_get'] = {
  init: function init() {
    this.appendDummyInput().appendField(Blockly.Msg.system_get_size);
    this.setOutput(true, null);
    this.setColour("#22398e");
    this.setTooltip(Blockly.Msg.Iot_System_Get_TOOLTIP);
    this.setHelpUrl("");
  }
};

Blockly.Python.iot_system_get = function (block) {
  var code = "_MCU_FREESPACE";
  return [code, Blockly.Python.ORDER_CONDITIONAL];
};

Blockly.Blocks['iot_system_mac'] = {
  init: function init() {
    this.appendDummyInput().appendField(Blockly.Msg.system_get_mac);
    this.setOutput(true, null);
    this.setColour("#22398e");
    this.setTooltip(Blockly.Msg.Iot_System_Mac_TOOLTIP);
    this.setHelpUrl("");
  }
};

Blockly.Python.iot_system_mac = function (block) {
  Blockly.Python.definitions_.import_machine_ub = "import machine, ubinascii";
  var _code = "ubinascii.hexlify(machine.unique_id()).decode().upper()";
  return [_code, Blockly.Python.ORDER_CONDITIONAL];
};

Blockly.Blocks['iot_system_get_cocorobo_id'] = {
  init: function init() {
    this.appendDummyInput().appendField(Blockly.Msg.system_get_cocorobo_cid);
    this.setInputsInline(false);
    this.setOutput(true, null);
    this.setColour("#22398e");
    this.setTooltip(Blockly.Msg.Iot_System_Get_Cocorobo_Id_TOOLTIP);
    this.setHelpUrl("");
  }
};

Blockly.Python['iot_system_get_cocorobo_id'] = function (block) {
  Blockly.Python.definitions_['import_cocorobo_cid'] = 'from cocorobo import cid\n'; // TODO: Assemble Python into code variable.

  var code = 'cid._GET_MACHINE_ID().strip(\'\\n\')'; // TODO: Change ORDER_NONE to the correct strength.

  return [code, Blockly.Python.ORDER_NONE];
};
/*

  _____     _____   __                 _          
  \_   \___/__   \ / _\ ___ _ ____   _(_) ___ ___ 
   / /\/ _ \ / /\/ \ \ / _ \ '__\ \ / / |/ __/ _ \
/\/ /_| (_) / /    _\ \  __/ |   \ V /| | (_|  __/
\____/ \___/\/     \__/\___|_|    \_/ |_|\___\___|
                                                  

*/


var ESP32_IOT_COLOR = "#3c7683";
var IFTTT_BLOCK_COLOR = "#ff3b00";
var ONENET_BLOCK_COLOR = "#00b5ff";
Blockly.Blocks['esp32_main_controller_onenet_setup'] = {
  init: function init() {
    this.appendDummyInput().appendField(new Blockly.FieldImage("blockly/media/onenet_setup_logo.png", 130, 70, {
      alt: "*",
      flipRtl: "FALSE"
    }));
    this.appendDummyInput().appendField(Blockly.Msg.iotservice_onenet_mqtt_setup);
    this.appendDummyInput().appendField(Blockly.Msg.iotservice_onenet_mqtt_server).appendField(new Blockly.FieldTextInput("183.230.40.39"), "server_ip");
    this.appendDummyInput().appendField(Blockly.Msg.iotservice_onenet_mqtt_productid).appendField(new Blockly.FieldTextInput("ENTER_YOUR_PRODUCT_ID"), "product_id");
    this.appendDummyInput().appendField(Blockly.Msg.iotservice_onenet_mqtt_productkey).appendField(new Blockly.FieldTextInput("ENTER_YOUR_PRODUCT_KEY"), "product_api_key");
    this.appendDummyInput().appendField(Blockly.Msg.iotservice_onenet_mqtt_deviceid).appendField(new Blockly.FieldTextInput("ENTER_YOUR_DEVICE_ID"), "device_id");
    this.setPreviousStatement(true, null);
    this.setNextStatement(true, null);
    this.setColour(ONENET_BLOCK_COLOR);
    this.setTooltip("");
    this.setHelpUrl("");
  }
};

Blockly.Python['esp32_main_controller_onenet_setup'] = function (block) {
  var text_server_ip = block.getFieldValue('server_ip');
  var text_product_id = block.getFieldValue('product_id');
  var text_product_api_key = block.getFieldValue('product_api_key');
  var text_device_id = block.getFieldValue('device_id'); // TODO: Assemble Python into code variable.

  var code = '...\n';
  return code;
};

Blockly.Blocks['iot_service_onenet'] = {
  init: function init() {
    this.appendDummyInput().appendField(new Blockly.FieldImage("blockly/media/onenet_setup_logo.png", 120, 70, {
      alt: "*",
      flipRtl: "FALSE"
    }));
    this.appendDummyInput().appendField(Blockly.Msg.iotservice_onenet_mqtt_send);
    /*this.appendValueInput("first_input")
        .setCheck(null)
        .appendField("Field 0");*/

    this.itemCount_ = 1;
    this.updateShape_();
    this.setMutator(new Blockly.Mutator(['iot_service_onenet_create_with_item']));
    this.setColour(ONENET_BLOCK_COLOR);
    this.setPreviousStatement(true, null);
    this.setNextStatement(true, null);
    this.setTooltip("");
    this.setHelpUrl("");
  },
  mutationToDom: function mutationToDom() {
    var container = document.createElement('mutation');
    container.setAttribute('items', this.itemCount_);
    return container;
  },
  domToMutation: function domToMutation(xmlElement) {
    this.itemCount_ = parseInt(xmlElement.getAttribute('items'), 10);
    this.updateShape_();
  },
  decompose: function decompose(workspace) {
    var containerBlock = workspace.newBlock('iot_service_onenet_create_with_container');
    containerBlock.initSvg();
    var connection = containerBlock.getInput('STACK').connection;

    for (var i = 0; i < this.itemCount_; i++) {
      var itemBlock = workspace.newBlock('iot_service_onenet_create_with_item');
      itemBlock.initSvg();
      connection.connect(itemBlock.previousConnection);
      connection = itemBlock.nextConnection;
    }

    return containerBlock;
  },
  compose: function compose(containerBlock) {
    var itemBlock = containerBlock.getInputTargetBlock('STACK'); // Count number of inputs.

    var connections = [];

    while (itemBlock) {
      connections.push(itemBlock.valueConnection_);
      itemBlock = itemBlock.nextConnection && itemBlock.nextConnection.targetBlock();
    } // Disconnect any children that don't belong.


    for (var i = 0; i < this.itemCount_; i++) {
      var connection = this.getInput('ADD' + i).connection.targetConnection;

      if (connection && connections.indexOf(connection) == -1) {
        connection.disconnect();
      }
    }

    this.itemCount_ = connections.length;
    this.updateShape_(); // Reconnect any child blocks.

    for (var i = 0; i < this.itemCount_; i++) {
      Blockly.Mutator.reconnect(connections[i], this, 'ADD' + i);
    }
  },
  saveConnections: function saveConnections(containerBlock) {
    var itemBlock = containerBlock.getInputTargetBlock('STACK');
    var i = 0;

    while (itemBlock) {
      var input = this.getInput('ADD' + i);
      itemBlock.valueConnection_ = input && input.connection.targetConnection;
      i++;
      itemBlock = itemBlock.nextConnection && itemBlock.nextConnection.targetBlock();
    }
  },
  updateShape_: function updateShape_() {
    for (var i = 0; i < this.itemCount_; i++) {
      if (!this.getInput('ADD' + i)) {
        var input = this.appendValueInput('ADD' + i);
        input.appendField(Blockly.Msg.iotservice_onenet_mqtt_send_item).appendField(new Blockly.FieldTextInput("Property" + i), "field" + i); //input.appendField("資料 " + (i + 1) + ":");
        //input.appendField(new Blockly.FieldLabelSerializable("field" + (i + 1)), 'FIELD' + i);
        // input.appendField(new Blockly.FieldTextInput("資料" + (i + 1)), 'FIELD' + i)
      }
    }

    while (this.getInput('ADD' + i)) {
      this.removeInput('ADD' + i);
      i++;
    }
  }
};
Blockly.Blocks['iot_service_onenet_create_with_container'] = {
  init: function init() {
    this.setColour(ONENET_BLOCK_COLOR);
    this.appendDummyInput().appendField("Items");
    this.appendStatementInput('STACK');
    this.setTooltip('');
    this.contextMenu = false;
  }
};
Blockly.Blocks['iot_service_onenet_create_with_item'] = {
  init: function init() {
    this.setColour(ONENET_BLOCK_COLOR);
    this.appendDummyInput().appendField("Field");
    this.setPreviousStatement(true);
    this.setNextStatement(true);
    this.setTooltip('');
    this.contextMenu = false;
  }
};

Blockly.Python['iot_service_onenet'] = function (block) {
  var code = ""; // onenet_data_final.slice(0, -3) + '}\''

  return code;
};

Blockly.Blocks['esp32_main_controller_onenet_when_receive_msg'] = {
  init: function init() {
    this.appendDummyInput().appendField(Blockly.Msg.iotservice_onenet_mqtt_receive);
    this.appendValueInput("content").setCheck(null);
    this.appendDummyInput().appendField(Blockly.Msg.iotservice_onenet_mqtt_receive_when);
    this.appendStatementInput("exec").setCheck(null).appendField(Blockly.Msg.iotservice_onenet_mqtt_receive_exec);
    this.setInputsInline(true);
    this.setPreviousStatement(true, null);
    this.setNextStatement(true, null);
    this.setColour(ONENET_BLOCK_COLOR);
    this.setTooltip("");
    this.setHelpUrl("");
  }
};

Blockly.Python['esp32_main_controller_onenet_when_receive_msg'] = function (block) {
  var value_content = Blockly.Python.valueToCode(block, 'content', Blockly.Python.ORDER_ATOMIC);
  var statements_exec = Blockly.Python.statementToCode(block, 'exec'); // TODO: Assemble Python into code variable.

  var code = '...\n';
  return code;
};

Blockly.Blocks['esp32_main_controller_onenet_disconnect'] = {
  init: function init() {
    this.appendDummyInput().appendField(Blockly.Msg.iotservice_onenet_mqtt_disconnect);
    this.setInputsInline(true);
    this.setPreviousStatement(true, null);
    this.setNextStatement(true, null);
    this.setColour(ONENET_BLOCK_COLOR);
    this.setTooltip("");
    this.setHelpUrl("");
  }
};

Blockly.Python['esp32_main_controller_onenet_disconnect'] = function (block) {
  // TODO: Assemble Python into code variable.
  var code = '\n';
  return code;
};

Blockly.Blocks['esp32_main_controller_ifttt_send_data'] = {
  init: function init() {
    this.appendDummyInput().appendField(new Blockly.FieldImage("blockly/media/ifttt_webhook.png", 110, 60, {
      alt: "*",
      flipRtl: "FALSE"
    }));
    this.appendDummyInput().appendField(Blockly.Msg.iotservice_ifttt_send_title);
    this.appendDummyInput().appendField(Blockly.Msg.iotservice_ifttt_send_webhook).appendField(new Blockly.FieldTextInput("ENTER_YOUR_API_KEY"), "ifttt_api_key");
    this.appendDummyInput().appendField(Blockly.Msg.iotservice_ifttt_send_eventname).appendField(new Blockly.FieldTextInput("ENTER_YOUR_EVENT_NAME"), "ifttt_event");
    this.appendValueInput("ifttt_data_1").setCheck(null).appendField(Blockly.Msg.iotservice_ifttt_send_1);
    this.appendValueInput("ifttt_data_2").setCheck(null).appendField(Blockly.Msg.iotservice_ifttt_send_2);
    this.appendValueInput("ifttt_data_3").setCheck(null).appendField(Blockly.Msg.iotservice_ifttt_send_3);
    this.setPreviousStatement(true, null);
    this.setNextStatement(true, null);
    this.setColour(IFTTT_BLOCK_COLOR);
    this.setTooltip(Blockly.Msg.Esp32_Main_Controller_Ifttt_Send_Data_TOOLTIP);
    this.setHelpUrl("");
  }
};

Blockly.Python['esp32_main_controller_ifttt_send_data'] = function (block) {
  var text_ifttt_api_key = block.getFieldValue('ifttt_api_key');
  var text_ifttt_event = block.getFieldValue('ifttt_event');
  var value_ifttt_data_1 = Blockly.Python.valueToCode(block, 'ifttt_data_1', Blockly.Python.ORDER_ATOMIC);
  var value_ifttt_data_2 = Blockly.Python.valueToCode(block, 'ifttt_data_2', Blockly.Python.ORDER_ATOMIC);
  var value_ifttt_data_3 = Blockly.Python.valueToCode(block, 'ifttt_data_3', Blockly.Python.ORDER_ATOMIC); // TODO: Assemble Python into code variable.

  Blockly.Python.definitions_['import_urequests'] = '' + 'import urequests\n' + 'import ujson as json\n';
  '';
  var code = '' + '_IFTTT_POST_API_KEY = "' + text_ifttt_api_key + '"\n' + '_IFTTT_POST_EVENT_NAME = "' + text_ifttt_event + '"\n' + '_IFTTT_POST_ENDPOINT = "http://maker.ifttt.com/trigger/"+ _IFTTT_POST_EVENT_NAME + "/with/key/" + _IFTTT_POST_API_KEY\n' + '_IFTTT_POST_DATA = \'{"value1":"\'+ str(' + value_ifttt_data_1 + ') +\'","value2":"\'+ str(' + value_ifttt_data_2 + ') +\'","value3":"\'+ str(' + value_ifttt_data_3 + ') +\'"}\'\n' + '_IFTTT_POST_REQUEST = urequests.post(_IFTTT_POST_ENDPOINT, data = _IFTTT_POST_DATA , headers = { "Content-type": "application/json" }, timeout=60)\n' + '\n';
  return code;
};

Blockly.Blocks['esp32_main_controller_ifttt_touched'] = {
  init: function init() {
    this.appendDummyInput().appendField(new Blockly.FieldImage("blockly/media/ifttt_webhook.png", 110, 60, {
      alt: "*",
      flipRtl: "FALSE"
    }));
    this.appendDummyInput().appendField(Blockly.Msg.iotservice_ifttt_trigger_title);
    this.appendDummyInput().appendField(Blockly.Msg.iotservice_ifttt_trigger_webhook).appendField(new Blockly.FieldTextInput("ENTER_YOUR_API_KEY"), "key");
    this.appendDummyInput().appendField(Blockly.Msg.iotservice_ifttt_trigger_eventname).appendField(new Blockly.FieldTextInput("ENTER_YOUR_EVENT_NAME"), "timename");
    this.setPreviousStatement(true, null);
    this.setNextStatement(true, null);
    this.setColour(IFTTT_BLOCK_COLOR);
    this.setTooltip(Blockly.Msg.Esp32_Main_Controller_Ifttt_Touched_TOOLTIP);
    this.setHelpUrl("");
  }
};

Blockly.Python['esp32_main_controller_ifttt_touched'] = function (block) {
  var text_ifttt_api_key = block.getFieldValue('key');
  var text_timename = block.getFieldValue('timename');
  Blockly.Python.definitions_['import_urequests'] = '' + 'import urequests\n' + 'import ujson as json\n';
  '';
  var code = '_IFTTT_TRIGGER_EVENT_NAME = "' + text_timename + '"\n';
  code += '_IFTTT_TRIGGER_API_KEY = "' + text_ifttt_api_key + '"\n';
  code += '_IFTTT_TRIGGER_ENDPOINT = "https://maker.ifttt.com/trigger/" + _IFTTT_TRIGGER_EVENT_NAME + "/with/key/" + _IFTTT_TRIGGER_API_KEY\n';
  Blockly.Python.addSetup("esp32_main_controller_ifttt_touched", code);
  var code = '_IFTTT_GET_REQUEST = urequests.get(_IFTTT_TRIGGER_ENDPOINT, timeout=60)\n';
  return code;
};

IOT_THINGSPEAK_COLOR = "#1b379f"; // IOT_THINGSPEAK_COLOR = ESP32_IOT_COLOR;

Blockly.Blocks['iot_service_thingspeak'] = {
  init: function init() {
    this.appendDummyInput().appendField(new Blockly.FieldImage("blockly/media/thingspeak.png", 170, 45, {
      alt: "*",
      flipRtl: "FALSE"
    }));
    this.appendDummyInput().appendField(Blockly.Msg.iotservice_thingspeak_send_title);
    this.appendDummyInput().appendField(Blockly.Msg.iotservice_thingspeak_send_api).appendField(new Blockly.FieldTextInput("ENTET_YOUT_CHANNEL_WRITE_API_KEY"), "t_api");
    /*this.appendValueInput("first_input")
        .setCheck(null)
        .appendField("Field 0");*/

    this.itemCount_ = 1;
    this.updateShape_();
    this.setMutator(new Blockly.Mutator(['iot_service_thingspeak_create_with_item']));
    this.setColour(IOT_THINGSPEAK_COLOR);
    this.setPreviousStatement(true, null);
    this.setNextStatement(true, null);
    this.setTooltip(Blockly.Msg.Iot_Service_Thingspeak_TOOLTIP);
    this.setHelpUrl("");
  },
  mutationToDom: function mutationToDom() {
    var container = document.createElement('mutation');
    container.setAttribute('items', this.itemCount_);
    return container;
  },
  domToMutation: function domToMutation(xmlElement) {
    this.itemCount_ = parseInt(xmlElement.getAttribute('items'), 10);
    this.updateShape_();
  },
  decompose: function decompose(workspace) {
    var containerBlock = workspace.newBlock('iot_service_thingspeak_create_with_container');
    containerBlock.initSvg();
    var connection = containerBlock.getInput('STACK').connection;

    for (var i = 0; i < this.itemCount_; i++) {
      var itemBlock = workspace.newBlock('iot_service_thingspeak_create_with_item');
      itemBlock.initSvg();
      connection.connect(itemBlock.previousConnection);
      connection = itemBlock.nextConnection;
    }

    return containerBlock;
  },
  compose: function compose(containerBlock) {
    var itemBlock = containerBlock.getInputTargetBlock('STACK'); // Count number of inputs.

    var connections = [];

    while (itemBlock) {
      connections.push(itemBlock.valueConnection_);
      itemBlock = itemBlock.nextConnection && itemBlock.nextConnection.targetBlock();
    } // Disconnect any children that don't belong.


    for (var i = 0; i < this.itemCount_; i++) {
      var connection = this.getInput('ADD' + i).connection.targetConnection;

      if (connection && connections.indexOf(connection) == -1) {
        connection.disconnect();
      }
    }

    this.itemCount_ = connections.length;
    this.updateShape_(); // Reconnect any child blocks.

    for (var i = 0; i < this.itemCount_; i++) {
      Blockly.Mutator.reconnect(connections[i], this, 'ADD' + i);
    }
  },
  saveConnections: function saveConnections(containerBlock) {
    var itemBlock = containerBlock.getInputTargetBlock('STACK');
    var i = 0;

    while (itemBlock) {
      var input = this.getInput('ADD' + i);
      itemBlock.valueConnection_ = input && input.connection.targetConnection;
      i++;
      itemBlock = itemBlock.nextConnection && itemBlock.nextConnection.targetBlock();
    }
  },
  updateShape_: function updateShape_() {
    for (var i = 0; i < this.itemCount_; i++) {
      if (!this.getInput('ADD' + i)) {
        var input = this.appendValueInput('ADD' + i);
        input.appendField("Field " + (i + 1) + ":"); //input.appendField(new Blockly.FieldLabelSerializable("field" + (i + 1)), 'FIELD' + i);
        // input.appendField(new Blockly.FieldTextInput("field" + (i + 1)), 'FIELD' + i)
      }
    }

    while (this.getInput('ADD' + i)) {
      this.removeInput('ADD' + i);
      i++;
    }
  }
};
Blockly.Blocks['iot_service_thingspeak_create_with_container'] = {
  init: function init() {
    this.setColour(IOT_THINGSPEAK_COLOR);
    this.appendDummyInput().appendField("Items");
    this.appendStatementInput('STACK');
    this.setTooltip('');
    this.contextMenu = false;
  }
};
Blockly.Blocks['iot_service_thingspeak_create_with_item'] = {
  init: function init() {
    this.setColour(IOT_THINGSPEAK_COLOR);
    this.appendDummyInput().appendField("Field");
    this.setPreviousStatement(true);
    this.setNextStatement(true);
    this.setTooltip('');
    this.contextMenu = false;
  }
};

Blockly.Python['iot_service_thingspeak'] = function (block) {
  var first_input = Blockly.Python.valueToCode(block, 'first_input', Blockly.Python.ORDER_ATOMIC);
  var api = block.getFieldValue('t_api');
  Blockly.Python.addVariable('_THINGSPEAK_REQUEST', '', true);
  Blockly.Python.definitions_['import_urequests'] = '' + 'import urequests\n' + 'import ujson as json\n';
  ''; // var key = Blockly.Arduino.valueToCode(block, 'KEY', Blockly.Arduino.ORDER_ATOMIC).replace(/\"/g, '') || "";

  var item_field = '',
    item_value = '';
  var thingspeak_url = "http://api.thingspeak.com/update?api_key=" + api;

  for (var n = 0; n < this.itemCount_; n++) {
    item_field = "field" + (n + 1);
    item_value = Blockly.Python.valueToCode(this, 'ADD' + n, Blockly.Python.ORDER_NONE) || '';
    thingspeak_url += '&' + item_field + '=\"+str(' + item_value + ')+\"';
  }

  var code = '' + '_THINGSPEAK_ENDPOINT = "' + thingspeak_url + '"\n' + '_THINGSPEAK_REQUEST = urequests.get(_THINGSPEAK_ENDPOINT,timeout=60)\n' + '';
  return code;
};

Blockly.Blocks['iot_service_thingspeak_read'] = {
  init: function init() {
    this.appendDummyInput().appendField(new Blockly.FieldImage("blockly/media/thingspeak.png", 170, 45, {
      alt: "*",
      flipRtl: "FALSE"
    }));
    this.appendDummyInput().appendField(Blockly.Msg.iotservice_thingspeak_query_title);
    this.appendDummyInput().appendField(Blockly.Msg.iotservice_thingspeak_query_api).appendField(new Blockly.FieldTextInput("ENTER_YOUR_CHANNEL_READ_API_KEY"), "api_key");
    this.appendDummyInput().appendField(Blockly.Msg.iotservice_thingspeak_channel_id).appendField(new Blockly.FieldTextInput("ENTER_YOUR_CHANNEL_ID"), "id");
    this.setInputsInline(false);
    this.setPreviousStatement(true, null);
    this.setNextStatement(true, null);
    this.setColour(IOT_THINGSPEAK_COLOR);
    this.setTooltip(Blockly.Msg.Iot_Service_Thingspeak_Read_TOOLTIP);
    this.setHelpUrl("");
  }
};

Blockly.Python['iot_service_thingspeak_read'] = function (block) {
  var text_api_key = block.getFieldValue('api_key');
  var text_id = block.getFieldValue('id');
  Blockly.Python.definitions_['import_urequests'] = '' + 'import urequests\n' + 'import ujson as json\n';
  '';
  Blockly.Python.addVariable('_THINGSPEAK_READ_REQUEST', '', true); // TODO: Assemble Python into code variable.

  var code = '_THINGSPEAK_READ_REQUEST = urequests.get("https://api.thingspeak.com/channels/" + "' + text_id + '" + "/feeds.json?api_key=" + "' + text_api_key + '",timeout=60)\n';
  return code;
};

Blockly.Blocks['iot_service_thingspeak_read_total'] = {
  init: function init() {
    this.appendDummyInput().appendField(Blockly.Msg.iotservice_thingspeak_read_total);
    this.setInputsInline(false);
    this.setOutput(true, null);
    this.setColour(IOT_THINGSPEAK_COLOR);
    this.setTooltip(Blockly.Msg.Iot_Service_Thingspeak_Read_Total_TOOLTIP);
    this.setHelpUrl("");
  }
};

Blockly.Python['iot_service_thingspeak_read_total'] = function (block) {
  // TODO: Assemble Python into code variable.
  var code = '_THINGSPEAK_READ_REQUEST.json()[\'channel\'][\'last_entry_id\']'; // TODO: Change ORDER_NONE to the correct strength.

  return [code, Blockly.Python.ORDER_NONE];
};

Blockly.Blocks['iot_service_thingspeak_read_specific'] = {
  init: function init() {
    this.appendDummyInput().appendField(Blockly.Msg.iotservice_thingspeak_get_title);
    this.appendValueInput("entry").setCheck(null);
    this.appendDummyInput().appendField(Blockly.Msg.iotservice_thingspeaK_get_field);
    this.appendValueInput("field").setCheck(null);
    this.appendDummyInput().appendField(Blockly.Msg.iotservice_thingspeaK_get_value);
    this.setInputsInline(true);
    this.setOutput(true, null);
    this.setColour(IOT_THINGSPEAK_COLOR);
    this.setTooltip(Blockly.Msg.Iot_Service_Thingspeak_Read_Specific_TOOLTIP);
    this.setHelpUrl("");
  }
};

Blockly.Python['iot_service_thingspeak_read_specific'] = function (block) {
  var value_entry = Blockly.Python.valueToCode(block, 'entry', Blockly.Python.ORDER_ATOMIC);
  var value_field = Blockly.Python.valueToCode(block, 'field', Blockly.Python.ORDER_ATOMIC); // TODO: Assemble Python into code variable.

  var code = '_THINGSPEAK_READ_REQUEST.json()[\'feeds\'][' + value_entry + '][\'field' + value_field + '\']'; // TODO: Change ORDER_NONE to the correct strength.

  return [code, Blockly.Python.ORDER_NONE];
}; // cococloud 


var COCOCLOUD_BLOCK_COLOR = "#4085de";
Blockly.Blocks['iot_service_cococloud'] = {
  init: function init() {
    this.appendDummyInput().appendField(new Blockly.FieldImage("blockly/media/cococloud_send.png", 180, 65, {
      alt: "*",
      flipRtl: "FALSE"
    }));
    this.appendDummyInput().appendField(Blockly.Msg.iotservice_cococloud_send_title);
    this.appendDummyInput().appendField(Blockly.Msg.iotservice_cococloud_send_title_api).appendField(new Blockly.FieldTextInput("ENTET_YOUT_EVENT_API_KEY"), "t_api");
    /*this.appendValueInput("first_input")
        .setCheck(null)
        .appendField("Field 0");*/

    this.itemCount_ = 1;
    this.updateShape_();
    this.setMutator(new Blockly.Mutator(['iot_service_cococloud_create_with_item']));
    this.setColour(COCOCLOUD_BLOCK_COLOR);
    this.setPreviousStatement(true, null);
    this.setNextStatement(true, null);
    this.setTooltip(Blockly.Msg.Iot_Service_Cococloud_TOOLTIP);
    this.setHelpUrl("");
  },
  mutationToDom: function mutationToDom() {
    var container = document.createElement('mutation');
    container.setAttribute('items', this.itemCount_);
    return container;
  },
  domToMutation: function domToMutation(xmlElement) {
    this.itemCount_ = parseInt(xmlElement.getAttribute('items'), 10);
    this.updateShape_();
  },
  decompose: function decompose(workspace) {
    var containerBlock = workspace.newBlock('iot_service_cococloud_create_with_container');
    containerBlock.initSvg();
    var connection = containerBlock.getInput('STACK').connection;

    for (var i = 0; i < this.itemCount_; i++) {
      var itemBlock = workspace.newBlock('iot_service_cococloud_create_with_item');
      itemBlock.initSvg();
      connection.connect(itemBlock.previousConnection);
      connection = itemBlock.nextConnection;
    }

    return containerBlock;
  },
  compose: function compose(containerBlock) {
    var itemBlock = containerBlock.getInputTargetBlock('STACK'); // Count number of inputs.

    var connections = [];

    while (itemBlock) {
      connections.push(itemBlock.valueConnection_);
      itemBlock = itemBlock.nextConnection && itemBlock.nextConnection.targetBlock();
    } // Disconnect any children that don't belong.


    for (var i = 0; i < this.itemCount_; i++) {
      var connection = this.getInput('ADD' + i).connection.targetConnection;

      if (connection && connections.indexOf(connection) == -1) {
        connection.disconnect();
      }
    }

    this.itemCount_ = connections.length;
    this.updateShape_(); // Reconnect any child blocks.

    for (var i = 0; i < this.itemCount_; i++) {
      Blockly.Mutator.reconnect(connections[i], this, 'ADD' + i);
    }
  },
  saveConnections: function saveConnections(containerBlock) {
    var itemBlock = containerBlock.getInputTargetBlock('STACK');
    var i = 0;

    while (itemBlock) {
      var input = this.getInput('ADD' + i);
      itemBlock.valueConnection_ = input && input.connection.targetConnection;
      i++;
      itemBlock = itemBlock.nextConnection && itemBlock.nextConnection.targetBlock();
    }
  },
  updateShape_: function updateShape_() {
    for (var i = 0; i < this.itemCount_; i++) {
      if (!this.getInput('ADD' + i)) {
        var input = this.appendValueInput('ADD' + i);
        input.appendField(Blockly.Msg.iotservice_cococloud_send_property).appendField(new Blockly.FieldTextInput("Property" + i), "field" + i); //input.appendField("資料 " + (i + 1) + ":");
        //input.appendField(new Blockly.FieldLabelSerializable("field" + (i + 1)), 'FIELD' + i);
        // input.appendField(new Blockly.FieldTextInput("資料" + (i + 1)), 'FIELD' + i)
      }
    }

    while (this.getInput('ADD' + i)) {
      this.removeInput('ADD' + i);
      i++;
    }
  }
};
Blockly.Blocks['iot_service_cococloud_create_with_container'] = {
  init: function init() {
    this.setColour(COCOCLOUD_BLOCK_COLOR);
    this.appendDummyInput().appendField("Items");
    this.appendStatementInput('STACK');
    this.setTooltip('');
    this.contextMenu = false;
  }
};
Blockly.Blocks['iot_service_cococloud_create_with_item'] = {
  init: function init() {
    this.setColour(COCOCLOUD_BLOCK_COLOR);
    this.appendDummyInput().appendField("Field");
    this.setPreviousStatement(true);
    this.setNextStatement(true);
    this.setTooltip('');
    this.contextMenu = false;
  }
};

Blockly.Python['iot_service_cococloud'] = function (block) {
  var api = block.getFieldValue('t_api');
  Blockly.Python.addVariable('_COCOCLOUD_SEND_REQUEST', '', true);
  Blockly.Python.definitions_['import_urequests'] = '' + 'import urequests\n' + 'import ujson as json\n';
  ''; // var key = Blockly.Arduino.valueToCode(block, 'KEY', Blockly.Arduino.ORDER_ATOMIC).replace(/\"/g, '') || "";

  var item_field = '',
    item_value = '';
  var cococloud_data = "'{";

  for (var n = 0; n < this.itemCount_; n++) {
    item_field = block.getFieldValue("field" + n);
    item_value = Blockly.Python.valueToCode(this, 'ADD' + n, Blockly.Python.ORDER_NONE) || '';
    cococloud_data += '"' + item_field + '":"\' + str(' + item_value + ') + \'",';
  }

  var cococloud_data_final = cococloud_data + "}'";
  var code = '' + '_COCOCLOUD_SEND_ENDPOINT = "http://api.cocorobo.cn/iot/data/eventAPIKey/"+ "' + api + '"\n' + '_COCOCLOUD_SEND_DATA = ' + cococloud_data_final.slice(0, -3) + '}\'' + '\n' + '_COCOCLOUD_SEND_REQUEST = urequests.post(_COCOCLOUD_SEND_ENDPOINT, data = _COCOCLOUD_SEND_DATA , headers = { "Content-type": "application/json" }, timeout = 30)\n';
  ''; // cococloud_data_final.slice(0, -3) + '}\''

  return code;
};

Blockly.Blocks['iot_service_cococloud_read'] = {
  init: function init() {
    this.appendDummyInput().appendField(new Blockly.FieldImage("blockly/media/cococloud_get.png", 200, 70, {
      alt: "*",
      flipRtl: "FALSE"
    }));
    this.appendDummyInput().appendField(Blockly.Msg.iotservice_cococloud_get_title);
    this.appendDummyInput().appendField(Blockly.Msg.iotservice_cococloud_get_api).appendField(new Blockly.FieldTextInput("ENTET_YOUT_EVENT_API_KEY"), "api");
    this.setInputsInline(false);
    this.setPreviousStatement(true, null);
    this.setNextStatement(true, null);
    this.setColour(COCOCLOUD_BLOCK_COLOR);
    this.setTooltip(Blockly.Msg.Iot_Service_Cococloud_Read_TOOLTIP);
    this.setHelpUrl("");
  }
};

Blockly.Python['iot_service_cococloud_read'] = function (block) {
  var api = block.getFieldValue('api');
  Blockly.Python.addVariable('_COCOCLOUD_READ_REQUEST', '', true);
  Blockly.Python.definitions_['import_urequests'] = '' + 'import urequests\n' + 'import ujson as json\n';
  ''; // TODO: Assemble Python into code variable.

  var code = '_COCOCLOUD_READ_REQUEST = urequests.get("http://api.cocorobo.cn/iot/data/eventAPIKey/" + "' + api + '", timeout=60)\n';
  return code;
};

Blockly.Blocks['iot_service_cococloud_read_data'] = {
  init: function init() {
    this.appendDummyInput().appendField(Blockly.Msg.iotservice_cococloud_get_property);
    this.appendValueInput("property").setCheck(null);
    this.appendDummyInput().appendField(Blockly.Msg.iotservice_cococloud_get_data);
    this.setInputsInline(true);
    this.setOutput(true, null);
    this.setColour(COCOCLOUD_BLOCK_COLOR);
    this.setTooltip(Blockly.Msg.Iot_Service_Cococloud_Read_Data_TOOLTIP);
    this.setHelpUrl("");
  }
};

Blockly.Python['iot_service_cococloud_read_data'] = function (block) {
  var property = Blockly.Python.valueToCode(block, 'property', Blockly.Python.ORDER_ATOMIC); // TODO: Assemble Python into code variable.

  var code = '_COCOCLOUD_READ_REQUEST.json()[\'data\'][0][' + property + ']'; // TODO: Change ORDER_NONE to the correct strength.

  return [code, Blockly.Python.ORDER_NONE];
};
/*
     __     _                      _        __                            _   
  /\ \ \___| |___      _____  _ __| | __   /__\ ___  __ _ _   _  ___  ___| |_ 
 /  \/ / _ \ __\ \ /\ / / _ \| '__| |/ /  / \/// _ \/ _` | | | |/ _ \/ __| __|
/ /\  /  __/ |_ \ V  V / (_) | |  |   <  / _  \  __/ (_| | |_| |  __/\__ \ |_ 
\_\ \/ \___|\__| \_/\_/ \___/|_|  |_|\_\ \/ \_/\___|\__, |\__,_|\___||___/\__|
                                                       |_|                    
*/


var NETWORK_BLOCK_COLOR = "#16318a";
Blockly.Blocks['esp32_network_http_get'] = {
  init: function init() {
    this.appendDummyInput().appendField(new Blockly.FieldImage("blockly/media/http_header_get.png", 180, 50, {
      alt: "*",
      flipRtl: "FALSE"
    }));
    this.appendDummyInput().appendField(Blockly.Msg.internet_http_get_title);
    this.appendValueInput("http_get_url").setCheck(null).appendField(Blockly.Msg.internet_http_get_url);
    this.setInputsInline(false);
    this.setPreviousStatement(true, null);
    this.setNextStatement(true, null);
    this.setColour(NETWORK_BLOCK_COLOR);
    this.setTooltip(Blockly.Msg.Esp32_Network_Http_Get_TOOLTIP);
    this.setHelpUrl("");
  }
};

Blockly.Python['esp32_network_http_get'] = function (block) {
  var url = Blockly.Python.valueToCode(block, 'http_get_url', Blockly.Python.ORDER_ATOMIC);
  Blockly.Python.addVariable('_SEND_HTTP_GET_ENDPOINT', '', true);
  Blockly.Python.addVariable('_SEND_HTTP_REQUEST', '', true);
  Blockly.Python.definitions_['import_urequests'] = '' + 'import urequests as requests\n' + 'import ujson as json\n' + '\n' + '_SEND_HTTP_GET_ENDPOINT = ' + url + '\n' + ''; // TODO: Assemble Python into code variable.

  var code = '_SEND_HTTP_REQUEST = requests.get(_SEND_HTTP_GET_ENDPOINT)\n';
  return code;
};

Blockly.Blocks['esp32_network_http_post'] = {
  init: function init() {
    this.appendDummyInput().appendField(new Blockly.FieldImage("blockly/media/http_header_post.png", 180, 50, {
      alt: "*",
      flipRtl: "FALSE"
    }));
    this.appendDummyInput().appendField(Blockly.Msg.internet_http_post_title);
    this.appendValueInput("http_post_url").setCheck(null).appendField(Blockly.Msg.internet_http_post_url);
    this.appendValueInput("data").setCheck(null).appendField(Blockly.Msg.internet_http_post_json);
    this.setInputsInline(false);
    this.setPreviousStatement(true, null);
    this.setNextStatement(true, null);
    this.setColour(NETWORK_BLOCK_COLOR);
    this.setTooltip(Blockly.Msg.Esp32_Network_Http_Post_TOOLTIP);
    this.setHelpUrl("");
  }
};

Blockly.Python['esp32_network_http_post'] = function (block) {
  var url = Blockly.Python.valueToCode(block, 'http_post_url', Blockly.Python.ORDER_ATOMIC);
  var data = Blockly.Python.valueToCode(block, 'data', Blockly.Python.ORDER_ATOMIC);
  Blockly.Python.addVariable('_SEND_HTTP_POST_ENDPOINT', '', true);
  Blockly.Python.addVariable('_SEND_HTTP_REQUEST', '', true);
  Blockly.Python.definitions_['import_urequests'] = '' + 'import urequests as requests\n' + 'import ujson as json\n' + '\n' + '_SEND_HTTP_POST_ENDPOINT = ' + url + '\n' + ''; // TODO: Assemble Python into code variable.

  var code = '' + '_SEND_HTTP_POST_DATA = \'' + data + '\'\n' + '_SEND_HTTP_REQUEST = requests.post(_SEND_HTTP_POST_ENDPOINT, data = _SEND_HTTP_POST_DATA , headers = { "Content-type": "application/json" })\n' + '';
  return code;
};

Blockly.Blocks['esp32_network_http_get_data_from_local_server'] = {
  init: function init() {
    this.appendDummyInput().appendField(Blockly.Msg.internet_http_get_server_data_title);
    this.appendDummyInput().appendField(Blockly.Msg.internet_http_get_server_data_type).appendField(new Blockly.FieldDropdown([[Blockly.Msg.internet_http_get_server_data_json, "json"], [Blockly.Msg.internet_http_get_server_data_text, "text"]]), "type");
    this.setInputsInline(false);
    this.setOutput(true, null);
    this.setColour(NETWORK_BLOCK_COLOR);
    var thisBlock = this;
    this.setTooltip(function () {
      var mode = thisBlock.getFieldValue('type');
      var TOOLTIPS = {
        'json': Blockly.Msg.Esp32_Network_Http_Get_Data_From_Local_Server_TOOLTIP.replace('%1', Blockly.Msg.internet_http_get_server_data_json),
        'text': Blockly.Msg.Esp32_Network_Http_Get_Data_From_Local_Server_TOOLTIP.replace('%1', Blockly.Msg.internet_http_get_server_data_text)
      };
      return TOOLTIPS[mode];
    });
    this.setHelpUrl("");
    this.setHelpUrl("");
  }
};

Blockly.Python['esp32_network_http_get_data_from_local_server'] = function (block) {
  var dropdown_type = block.getFieldValue('type'); // TODO: Assemble Python into code variable.

  if (dropdown_type == "text") {
    var request_code = "_SEND_HTTP_REQUEST.text";
  } else if (dropdown_type == "json") {
    var request_code = "eval(_SEND_HTTP_REQUEST.text)";
  }

  var code = request_code; // TODO: Change ORDER_NONE to the correct strength.

  return [code, Blockly.Python.ORDER_NONE];
};

Blockly.Blocks['esp32_network_http_server_setup'] = {
  init: function init() {
    this.appendDummyInput().appendField(new Blockly.FieldImage("blockly/media/http_server_header.png", 130, 40, {
      alt: "*",
      flipRtl: "FALSE"
    }));
    this.appendDummyInput().appendField(Blockly.Msg.wifi_web_http_server_setup);
    this.setInputsInline(false);
    this.setPreviousStatement(true, null);
    this.setNextStatement(true, null);
    this.setColour(NETWORK_BLOCK_COLOR);
    this.setTooltip(Blockly.Msg.Esp32_Network_Http_Server_Setup_TOOLTIP);
    this.setHelpUrl("");
  }
};

Blockly.Python['esp32_network_http_server_setup'] = function (block) {
  // TODO: Assemble Python into code variable.
  Blockly.Python.definitions_['esp32_network_http_server_setup_def_setup'] = '' + 'from microWebSrv import MicroWebSrv\n' + 'import time\n' + '';
  var code = '';
  return code;
};

Blockly.Blocks['esp32_network_http_server_route'] = {
  init: function init() {
    this.appendDummyInput().appendField(Blockly.Msg.wifi_web_http_server_route_setting_title);
    this.appendDummyInput().appendField(Blockly.Msg.wifi_web_http_server_route_setting_path).appendField(new Blockly.FieldTextInput("/"), "path").appendField(Blockly.Msg.wifi_web_http_server_route_setting_being_requested);
    this.appendDummyInput().appendField(Blockly.Msg.wifi_web_http_server_route_setting_property).appendField(new Blockly.FieldDropdown([[Blockly.Msg.wifi_web_http_server_route_setting_get, "get"], [Blockly.Msg.wifi_web_http_server_route_setting_post, "post"]]), "response_type");
    this.appendStatementInput("exec").setCheck(null).appendField(Blockly.Msg.wifi_web_http_server_route_setting_do);
    this.setInputsInline(false);
    this.setPreviousStatement(true, null);
    this.setNextStatement(true, null);
    this.setColour(NETWORK_BLOCK_COLOR);
    var thisBlock = this;
    this.setTooltip(function () {
      var mode = thisBlock.getFieldValue('response_type');
      var TOOLTIPS = {
        'get': Blockly.Msg.Esp32_Network_Http_Server_Route_TOOLTIP.replace('%1', Blockly.Msg.wifi_web_http_server_route_setting_get),
        'post': Blockly.Msg.Esp32_Network_Http_Server_Route_TOOLTIP.replace('%1', Blockly.Msg.wifi_web_http_server_route_setting_post)
      };
      return TOOLTIPS[mode];
    });
    this.setHelpUrl("");
  }
};

Blockly.Python['esp32_network_http_server_route'] = function (block) {
  var dropdown_response_type = block.getFieldValue('response_type');
  var text_path = block.getFieldValue('path');
  var statements_exec = Blockly.Python.statementToCode(block, 'exec');
  var response_type = "";
  var response_writeok = "";

  if (dropdown_response_type == "get") {
    response_type = "";
  } else if (dropdown_response_type == "post") {
    response_type = ", 'POST'";
  }
  /*Blockly.Python.addVariable('', '' +
      '' +
      '@MicroWebSrv.route(\'' + text_path + '\'' + response_type + ')\n' +
      'def _httpHandlerTestGet(httpClient, httpResponse):\n' +
      statements_exec +
      '', true);*/


  Blockly.Python.definitions_['esp32_network_http_server_route_def_' + text_path.substring(1)] = '' + '@MicroWebSrv.route(\'' + text_path + '\'' + response_type + ')\n' + 'def _httpHandler' + text_path.substring(1) + 'Get(httpClient, httpResponse):\n' + statements_exec + '\n';
  Blockly.Python.addSetup("server_route_setup", '' + 'def _acceptWebSocketCallback(webSocket, httpClient) :\n' + '    print("WS ACCEPT")\n' + '    webSocket.RecvTextCallback   = _recvTextCallback\n' + '    webSocket.RecvBinaryCallback = _recvBinaryCallback\n' + '    webSocket.ClosedCallback     = _closedCallback\n' + '\n' + 'def _recvTextCallback(webSocket, msg) :\n' + '    print("WS RECV TEXT : %s" % msg)\n' + '    webSocket.SendText("Reply for %s" % msg)\n' + '\n' + 'def _recvBinaryCallback(webSocket, data) :\n' + '    print("WS RECV DATA : %s" % data)\n' + '\n' + 'def _closedCallback(webSocket) :\n' + '    print("WS CLOSED")\n' + '\n' + 'try:\n' + '    srv.Stop()\n' + '    srv = MicroWebSrv()\n' + '    srv.MaxWebSocketRecvLen     = 1024\n' + '    srv.WebSocketThreaded       = False\n' + '    srv.AcceptWebSocketCallback = _acceptWebSocketCallback\n' + '    srv.Start(threaded=True)\n' + 'except BaseException as e:\n' + '    print(str(e))\n' + '    srv = MicroWebSrv()\n' + '    srv.MaxWebSocketRecvLen     = 1024\n' + '    srv.WebSocketThreaded       = False\n' + '    srv.AcceptWebSocketCallback = _acceptWebSocketCallback\n' + '    srv.Start(threaded=True)\n' + ''); // TODO: Assemble Python into code variable.

  var code = '';
  return code;
};

Blockly.Blocks['esp32_network_http_server_route_respond'] = {
  init: function init() {
    this.appendValueInput("exec").setCheck(null).appendField(Blockly.Msg.wifi_web_http_server_respond_title);
    this.appendDummyInput().appendField(Blockly.Msg.wifi_web_http_server_respond_type).appendField(new Blockly.FieldDropdown([[Blockly.Msg.wifi_web_http_server_respond_text, "text/plain"], [Blockly.Msg.wifi_web_http_server_respond_json, "application/json"], [Blockly.Msg.wifi_web_http_server_respond_html, "text/html"]]), "response_type");
    this.setInputsInline(false);
    this.setPreviousStatement(true, null);
    this.setNextStatement(true, null);
    this.setColour(NETWORK_BLOCK_COLOR);
    var thisBlock = this;
    this.setTooltip(function () {
      var mode = thisBlock.getFieldValue('response_type');
      var TOOLTIPS = {
        'text/plain': Blockly.Msg.Esp32_Network_Http_Server_Route_Respond_TOOLTIP.replace('%1', Blockly.Msg.wifi_web_http_server_respond_text),
        'application/json': Blockly.Msg.Esp32_Network_Http_Server_Route_Respond_TOOLTIP.replace('%1', Blockly.Msg.wifi_web_http_server_respond_json),
        'text/html': Blockly.Msg.Esp32_Network_Http_Server_Route_Respond_TOOLTIP.replace('%1', Blockly.Msg.wifi_web_http_server_respond_html)
      };
      return TOOLTIPS[mode];
    });
    this.setHelpUrl("");
  }
};

Blockly.Python['esp32_network_http_server_route_respond'] = function (block) {
  var dropdown_response_type = block.getFieldValue('response_type');
  var statements_exec = Blockly.Python.valueToCode(block, 'exec', Blockly.Python.ORDER_ATOMIC); // TODO: Assemble Python into code variable.

  var code = '' + 'content = ' + statements_exec + '\n' + 'httpResponse.WriteResponseOk( headers        = None,\n' + '                              contentType    = "' + dropdown_response_type + '",\n' + '                              contentCharset = "UTF-8",\n' + '                              content        = str(content) )\n' + '';
  return code;
};

Blockly.Blocks['esp32_network_http_server_get_data'] = {
  init: function init() {
    this.appendDummyInput().appendField(Blockly.Msg.wifi_web_http_server_get_title).appendField(new Blockly.FieldDropdown([[Blockly.Msg.wifi_web_http_server_get_as_json, "json"], [Blockly.Msg.wifi_web_http_server_get_as_text, "text"]]), "type");
    this.setInputsInline(false);
    this.setOutput(true, null);
    this.setColour(NETWORK_BLOCK_COLOR);
    var thisBlock = this;
    this.setTooltip(function () {
      var mode = thisBlock.getFieldValue('type');
      var TOOLTIPS = {
        'json': Blockly.Msg.Esp32_Network_Http_Server_Get_Data_TOOLTIP.replace('%1', Blockly.Msg.wifi_web_http_server_get_as_json),
        'text': Blockly.Msg.Esp32_Network_Http_Server_Get_Data_TOOLTIP.replace('%1', Blockly.Msg.wifi_web_http_server_get_as_text)
      };
      return TOOLTIPS[mode];
    });
    this.setHelpUrl("");
  }
};

Blockly.Python['esp32_network_http_server_get_data'] = function (block) {
  var dropdown_type = block.getFieldValue('type');

  if (dropdown_type == "json") {
    var as_type = "ReadRequestContentAsJSON()";
  } else if (dropdown_type == "text") {
    var as_type = "ReadRequestContent(size=None)";
  } // TODO: Assemble Python into code variable.


  var code = 'httpClient.' + as_type; // TODO: Change ORDER_NONE to the correct strength.

  return [code, Blockly.Python.ORDER_NONE];
};

var WS_BLOCK_COLOR = "#83178a";
Blockly.Blocks['esp32_web_ws_setup_send'] = {
  init: function init() {
    this.appendDummyInput().appendField(new Blockly.FieldImage("blockly/media/ws_header_send.png", 220, 50, {
      alt: "*",
      flipRtl: "FALSE"
    }));
    this.appendDummyInput().appendField(Blockly.Msg.internet_ws_setup_send_text);
    this.appendDummyInput().appendField(Blockly.Msg.internet_ws_setup_send_ip).appendField(new Blockly.FieldTextInput("192.168.4.1"), "ip");
    this.setInputsInline(false);
    this.setPreviousStatement(true, null);
    this.setNextStatement(true, null);
    this.setColour(WS_BLOCK_COLOR);
    this.setTooltip(Blockly.Msg.Esp32_Web_Ws_Setup_Send_TOOLTIP);
    this.setHelpUrl("");
  }
};

Blockly.Python['esp32_web_ws_setup_send'] = function (block) {
  var text_ip = block.getFieldValue('ip');
  Blockly.Python.definitions_['ws_setup_send'] = '' + 'import uwebsockets.client\n' + '\n'; // TODO: Assemble Python into code variable.

  var code = '_client_websocket = uwebsockets.client.connect("ws://' + text_ip + ':80")\n';
  return code;
};

Blockly.Blocks['esp32_web_ws_send'] = {
  init: function init() {
    this.appendValueInput("command").setCheck(null).appendField(Blockly.Msg.internet_ws_send_msg);
    this.setInputsInline(true);
    this.setPreviousStatement(true, null);
    this.setNextStatement(true, null);
    this.setColour(WS_BLOCK_COLOR);
    this.setTooltip(Blockly.Msg.Esp32_Web_Ws_Send_TOOLTIP);
    this.setHelpUrl("");
  }
};

Blockly.Python['esp32_web_ws_send'] = function (block) {
  var value_command = Blockly.Python.valueToCode(block, 'command', Blockly.Python.ORDER_ATOMIC); // TODO: Assemble Python into code variable.

  var code = '' + 'message = ' + value_command + '\n' + '_client_websocket.send(message)\n';
  return code;
};

Blockly.Blocks['esp32_web_ws_setup_receive'] = {
  init: function init() {
    this.appendDummyInput().appendField(new Blockly.FieldImage("blockly/media/ws_header_receive.png", 220, 50, {
      alt: "*",
      flipRtl: "FALSE"
    }));
    this.appendDummyInput().appendField(Blockly.Msg.internet_ws_setup_recv);
    this.setInputsInline(false);
    this.setPreviousStatement(true, null);
    this.setNextStatement(true, null);
    this.setColour(WS_BLOCK_COLOR);
    this.setTooltip(Blockly.Msg.Esp32_Web_Ws_Setup_Receive_TOOLTIP);
    this.setHelpUrl("");
  }
};

Blockly.Python['esp32_web_ws_setup_receive'] = function (block) {
  Blockly.Python.definitions_['ws_setup_receive'] = '' + 'import uasyncio, logging\n' + 'from uasyncio.websocket.server import WSReader, WSWriter\n' + 'logging.basicConfig(level=logging.DEBUG)\n' + '\n'; // TODO: Assemble Python into code variable.

  var code = '';
  return code;
};

Blockly.Blocks['esp32_web_ws_receive_statement'] = {
  init: function init() {
    this.appendDummyInput().appendField(Blockly.Msg.internet_ws_setup_receiving);
    this.appendStatementInput("command").setCheck(null).appendField(Blockly.Msg.internet_ws_setup_recv_exec);
    this.setInputsInline(false);
    this.setPreviousStatement(true, null);
    this.setNextStatement(true, null);
    this.setColour(WS_BLOCK_COLOR);
    this.setTooltip(Blockly.Msg.Esp32_Web_Ws_Receive_Statement_TOOLTIP);
    this.setHelpUrl("");
  }
};

Blockly.Python['esp32_web_ws_receive_statement'] = function (block) {
  var statements_command = Blockly.Python.statementToCode(block, 'command');
  Blockly.Python.definitions_['ws_setup_receive_statement'] = '' + 'def _ws_exec(msg):\n' + '' + statements_command + '\n' + 'def _ws_echo(reader, writer):\n' + '    yield from reader.readline()\n' + '\n' + '    reader = yield from WSReader(reader, writer)\n' + '    writer = WSWriter(reader, writer)\n' + '\n' + '    while 1:\n' + '        _ws_l = yield from reader.read(1024)\n' + '        print(_ws_l)\n' + '        _ws_exec(_ws_l)\n' + '\n' + '        if _ws_l == b"\\r":\n' + '            await writer.awrite(b"\\r\\n")\n' + '        else:\n' + '            await writer.awrite(_ws_l)\n' + '\n' + '_ws_loop = uasyncio.get_event_loop()\n' + '_ws_loop.create_task(uasyncio.start_server(_ws_echo, "0.0.0.0", 80))\n' + '_ws_loop.run_forever()\n' + '_ws_loop.close()\n' + ''; // TODO: Assemble Python into code variable.

  var code = '\n';
  return code;
};

Blockly.Blocks['esp32_web_ws_receive_get_data'] = {
  init: function init() {
    this.appendDummyInput().appendField(Blockly.Msg.internet_ws_setup_get_msg);
    this.appendDummyInput().appendField(Blockly.Msg.internet_ws_setup_get_msg_type).appendField(new Blockly.FieldDropdown([[Blockly.Msg.internet_ws_setup_get_msg_text, "text"], [Blockly.Msg.internet_ws_setup_get_msg_json, "json"]]), "type");
    this.setInputsInline(false);
    this.setOutput(true, null);
    this.setColour(WS_BLOCK_COLOR);
    var thisBlock = this;
    this.setTooltip(function () {
      var mode = thisBlock.getFieldValue('type');
      var TOOLTIPS = {
        'text': Blockly.Msg.Esp32_Web_Ws_Receive_Get_Data_TOOLTIP.replace('%1', Blockly.Msg.internet_ws_setup_get_msg_text),
        'json': Blockly.Msg.Esp32_Web_Ws_Receive_Get_Data_TOOLTIP.replace('%1', Blockly.Msg.internet_ws_setup_get_msg_json)
      };
      return TOOLTIPS[mode];
    });
    this.setHelpUrl("");
  }
};

Blockly.Python['esp32_web_ws_receive_get_data'] = function (block) {
  var dropdown_type = block.getFieldValue('type'); // TODO: Assemble Python into code variable.

  if (dropdown_type == "text") {
    var code = "msg.decode(\"utf-8\")";
  } else if (dropdown_type == "json") {
    var code = "eval(msg.decode(\"utf-8\"))";
  } // TODO: Change ORDER_NONE to the correct strength.


  return [code, Blockly.Python.ORDER_NONE];
};
/*

     __  ___        _____     _____ 
  /\ \ \/ __\       \_   \___/__   \
 /  \/ /__\//_____   / /\/ _ \ / /\/
/ /\  / \/  \_____/\/ /_| (_) / /   
\_\ \/\_____/     \____/ \___/\/    

Blockly.Python.addVariable('', '', true);
Blockly.Python.definitions_['definition'] = '';
Blockly.Python.addSetup("setup", '');
                                    

*/


var ESP32_NBIOT_COLOR = "#629978";
Blockly.Blocks['esp32_nbiot_setup'] = {
  init: function init() {
    this.appendDummyInput().appendField(new Blockly.FieldImage("blockly/media/nbiot_esp32_header.png", 110, 40, {
      alt: "*",
      flipRtl: "FALSE"
    }));
    this.appendDummyInput().appendField(Blockly.Msg.nbiot_module_init);
    this.setPreviousStatement(true, null);
    this.setNextStatement(true, null);
    this.setColour(ESP32_NBIOT_COLOR);
    this.setTooltip("");
    this.setHelpUrl("");
  }
};

Blockly.Python['esp32_nbiot_setup'] = function (block) {
  // TODO: Assemble Python into code variable.
  Blockly.Python.addVariable('_nbiot_serial_read', '_nbiot_serial_read = ""', true);
  Blockly.Python.addVariable('_nbiot_readings', '_nbiot_readings = ""', true);
  Blockly.Python.addVariable('_nbiot_power_on_status', '_nbiot_power_on_status = False', true);
  Blockly.Python.addVariable('_nbiot_internet_status', '_nbiot_internet_status = False', true);
  Blockly.Python.addVariable('_nbiot_internet_ip_address', '_nbiot_internet_ip_address = ""', true);
  Blockly.Python.definitions_['import_definition'] = '' + 'from machine import UART\n' + 'from machine import Timer\n' + 'import ubinascii as binascii\n' + 'import time\n' + '\n' + '_nbiot_serial = UART(2,rx=16, tx=17, baudrate=115200, timeout=10)\n' + '\n' + '_nbiot_serial_timer = Timer(1)\n' + '_nbiot_serial_timer.init(period=50, mode=Timer.PERIODIC, callback=lambda t: _read_nbiot_serial(_nbiot_serial))\n' + '\n' + 'def _read_nbiot_serial(uart):\n' + '    global _nbiot_readings, _nbiot_power_on_status, _nbiot_internet_status, _nbiot_internet_ip_address\n' + '    if _nbiot_serial.any():\n' + '        _nbiot_serial_read = _nbiot_serial.readline().decode("utf-8")\n' + '        _nbiot_serial_read = _nbiot_serial_read.strip()\n' + '        _nbiot_readings = _nbiot_serial_read.strip()\n' + '\n' + '        if _nbiot_serial_read == "+CPIN: READY":\n' + '            _nbiot_power_on_status = True\n' + '            print("NB-IoT Module Initiated!\\n")\n' + '            _nbiot_serial.write(b\'AT+CMSYSCTRL=0,2,50,300,100,800\\r\\n\')\n' + '\n' + '        if "+IP" in _nbiot_serial_read:\n' + '            _nbiot_internet_status = True\n' + '            _nbiot_internet_ip_address = _nbiot_serial_read[5:len(_nbiot_serial_read)]\n' + '';
  var code = '';
  return code;
};

Blockly.Blocks['esp32_nbiot_get_power_status'] = {
  init: function init() {
    this.appendDummyInput().appendField(Blockly.Msg.nbiot_module_power);
    this.setOutput(true, null);
    this.setColour(ESP32_NBIOT_COLOR);
    this.setTooltip(Blockly.Msg.esp32_nbiot_get_power_status_TOOLTIP);
    this.setHelpUrl("");
  }
};

Blockly.Python['esp32_nbiot_get_power_status'] = function (block) {
  // TODO: Assemble Python into code variable.
  var code = '_nbiot_power_on_status'; // TODO: Change ORDER_NONE to the correct strength.

  return [code, Blockly.Python.ORDER_NONE];
};

Blockly.Blocks['esp32_nbiot_get_network_status'] = {
  init: function init() {
    this.appendDummyInput().appendField(Blockly.Msg.nbiot_module_connectivity);
    this.setOutput(true, null);
    this.setColour(ESP32_NBIOT_COLOR);
    this.setTooltip("");
    this.setHelpUrl("");
  }
};

Blockly.Python['esp32_nbiot_get_network_status'] = function (block) {
  // TODO: Assemble Python into code variable.
  var code = '_nbiot_internet_status'; // TODO: Change ORDER_NONE to the correct strength.

  return [code, Blockly.Python.ORDER_NONE];
};

Blockly.Blocks['esp32_nbiot_get_network_ip'] = {
  init: function init() {
    this.appendDummyInput().appendField(Blockly.Msg.nbiot_module_ip);
    this.setOutput(true, null);
    this.setColour(ESP32_NBIOT_COLOR);
    this.setTooltip("");
    this.setHelpUrl("");
  }
};

Blockly.Python['esp32_nbiot_get_network_ip'] = function (block) {
  // TODO: Assemble Python into code variable.
  var code = '_nbiot_internet_ip_address'; // TODO: Change ORDER_NONE to the correct strength.

  return [code, Blockly.Python.ORDER_NONE];
};

Blockly.Blocks['esp32_nbiot_onenet_init'] = {
  init: function init() {
    this.appendDummyInput().appendField(new Blockly.FieldImage("blockly/media/nbiot_onenet.png", 200, 60, {
      alt: "*",
      flipRtl: "FALSE"
    }));
    this.appendDummyInput().appendField(Blockly.Msg.nbiot_onenet_title);
    this.appendValueInput("product_id").setCheck(null).appendField(Blockly.Msg.nbiot_onenet_connect_productid);
    this.appendValueInput("device_id").setCheck(null).appendField(Blockly.Msg.nbiot_onenet_connect_deviceid);
    this.appendValueInput("device_apikey").setCheck(null).appendField(Blockly.Msg.nbiot_onenet_connect_device_api);
    this.setPreviousStatement(true, null);
    this.setNextStatement(true, null);
    this.setColour(ONENET_BLOCK_COLOR);
    this.setTooltip("");
    this.setHelpUrl("");
  }
};

Blockly.Python['esp32_nbiot_onenet_init'] = function (block) {
  var value_product_id = Blockly.Python.valueToCode(block, 'product_id', Blockly.Python.ORDER_ATOMIC);
  var value_device_id = Blockly.Python.valueToCode(block, 'device_id', Blockly.Python.ORDER_ATOMIC);
  var value_device_apikey = Blockly.Python.valueToCode(block, 'device_apikey', Blockly.Python.ORDER_ATOMIC); // TODO: Assemble Python into code variable.

  Blockly.Python.addVariable('_nbiot_onenet_product_id', '', true);
  Blockly.Python.addVariable('_nbiot_onenet_device_id', '', true);
  Blockly.Python.addVariable('_nbiot_onent_device_apikey', '', true);
  Blockly.Python.addVariable('_nbiot_onenet_connection_status', '', true);
  Blockly.Python.addVariable('_nbiot_onenet_read_anything', '', true);
  Blockly.Python.addVariable('_nbiot_onenet_init_state', '', true);
  Blockly.Python.addSetup("setup", '' + '_nbiot_onenet_init_state = False\n' + '_nbiot_onenet_connection_status = False\n' + '_nbiot_onenet_read_anything = False\n' + '_nbiot_onenet_product_id = ' + value_product_id + '\n' + '_nbiot_onenet_device_id = ' + value_device_id + '\n' + '_nbiot_onent_device_apikey = ' + value_device_apikey + '\n' + '\n' + 'def _nbiot_send_onenet_data(data):\n' + '    _nbiot_send_message = data\n' + '    _nbiot_send_data_content = binascii.hexlify(_nbiot_send_message).decode("utf-8")\n' + '    _nbiot_send_header = ",0300" + str(hex(len(_nbiot_send_message)).split(\'x\')[-1])\n' + '    _nbiot_send_at_content = "AT+MQTTPUB=$dp,0,1,0," + str(len(_nbiot_send_message)+len(_nbiot_send_header[1:7].replace("0",""))) + ",0300" + str(hex(len(_nbiot_send_message)).split(\'x\')[-1]) + str(_nbiot_send_data_content)\n' + '    return _nbiot_send_at_content\n' + '\n' + 'def _nbiot_read_onenet_data(raw_response):\n' + '    _nbiot_receive = raw_response\n' + '    if "+MQTTPUBLISH" not in raw_response:\n' + '        return ""\n' + '    elif "+MQTTPUBLISH" in raw_response:\n' + '        _nbiot_occur = -1\n' + '        for i in range(0, 6):  _nbiot_occur = _nbiot_receive.find(",", _nbiot_occur + 1)\n' + '        return _nbiot_receive[_nbiot_occur+1:len(_nbiot_receive)]\n' + '\n' + 'def _read_nbiot_onenet(_incoming_data):\n' + '    global _nbiot_onenet_connection_status, _nbiot_onenet_read_anything\n' + '\n' + '    if "+MQTTOPEN: OK" in _incoming_data:\n' + '        _nbiot_onenet_connection_status = True\n' + '        # print("OneNET Connected!")\n' + '    if "+MQTTOPEN: FAIL" in _incoming_data:\n' + '        _nbiot_onenet_connection_status = False\n' + '        # print("OneNET Lost Connection!")\n' + '\n' + '    if "+MQTTPUBLISH" in _incoming_data:\n' + '        _nbiot_onenet_read_anything = True\n' + '    else:\n' + '        _nbiot_onenet_read_anything = False\n' + '\n' + '    if "+MQTTDISC" in _incoming_data:\n' + '        _nbiot_onenet_read_anything = False\n' + '        _nbiot_onenet_configuration = "AT+MQTTCFG=183.230.40.39,6002,"+_nbiot_onenet_device_id+",100,"+_nbiot_onenet_product_id+","+_nbiot_onent_device_apikey+",1,0\\r\\n"\n' + '        print("Enabling OneNET Connection...")\n' + '        _nbiot_serial.write(_nbiot_onenet_configuration.encode())\n' + '        time.sleep_ms(100)\n' + '        _nbiot_serial.write(b\'AT+MQTTOPEN=1,1,0\\r\\n\')\n' + '\n' + 'def _init_onenet_connection():\n' + '    _nbiot_onenet_configuration = "AT+MQTTCFG=183.230.40.39,6002,"+_nbiot_onenet_device_id+",100,"+_nbiot_onenet_product_id+","+_nbiot_onent_device_apikey+",1,0\\r\\n"\n' + '    print("Enabling OneNET Connection...")\n' + '    _nbiot_serial.write(_nbiot_onenet_configuration.encode())\n' + '    time.sleep_ms(100)\n' + '    _nbiot_serial.write(b\'AT+MQTTOPEN=1,1,0\\r\\n\')\n' + '    time.sleep_ms(100)\n' + '');
  var code = '' + 'if (_nbiot_internet_status == True) and (_nbiot_onenet_init_state == False) and (_nbiot_onenet_connection_status == False):\n' + '    _init_onenet_connection()\n' + '    _nbiot_onenet_init_state = True\n' + '\n' + '_read_nbiot_onenet(_nbiot_readings)\n' + '';
  return code;
};

Blockly.Blocks['esp32_nbiot_onenet_connection_status'] = {
  init: function init() {
    this.appendDummyInput().appendField(Blockly.Msg.nbiot_onenet_connectivity);
    this.setOutput(true, null);
    this.setColour(ONENET_BLOCK_COLOR);
    this.setTooltip("");
    this.setHelpUrl("");
  }
};

Blockly.Python['esp32_nbiot_onenet_connection_status'] = function (block) {
  // TODO: Assemble Python into code variable.
  var code = '_nbiot_onenet_connection_status'; // TODO: Change ORDER_NONE to the correct strength.

  return [code, Blockly.Python.ORDER_NONE];
};

Blockly.Blocks['iot_service_nbiot_onenet'] = {
  init: function init() {
    this.appendDummyInput().appendField(new Blockly.FieldImage("blockly/media/nbiot_onenet_send.png", 210, 60, {
      alt: "*",
      flipRtl: "FALSE"
    }));
    this.appendDummyInput().appendField(Blockly.Msg.nbiot_onenet_send_title);
    /*this.appendValueInput("first_input")
        .setCheck(null)
        .appendField("Field 0");*/

    this.itemCount_ = 1;
    this.updateShape_();
    this.setMutator(new Blockly.Mutator(['iot_service_nbiot_onenet_create_with_item']));
    this.setColour(ONENET_BLOCK_COLOR);
    this.setPreviousStatement(true, null);
    this.setNextStatement(true, null);
    this.setTooltip("");
    this.setHelpUrl("");
  },
  mutationToDom: function mutationToDom() {
    var container = document.createElement('mutation');
    container.setAttribute('items', this.itemCount_);
    return container;
  },
  domToMutation: function domToMutation(xmlElement) {
    this.itemCount_ = parseInt(xmlElement.getAttribute('items'), 10);
    this.updateShape_();
  },
  decompose: function decompose(workspace) {
    var containerBlock = workspace.newBlock('iot_service_nbiot_onenet_create_with_container');
    containerBlock.initSvg();
    var connection = containerBlock.getInput('STACK').connection;

    for (var i = 0; i < this.itemCount_; i++) {
      var itemBlock = workspace.newBlock('iot_service_nbiot_onenet_create_with_item');
      itemBlock.initSvg();
      connection.connect(itemBlock.previousConnection);
      connection = itemBlock.nextConnection;
    }

    return containerBlock;
  },
  compose: function compose(containerBlock) {
    var itemBlock = containerBlock.getInputTargetBlock('STACK'); // Count number of inputs.

    var connections = [];

    while (itemBlock) {
      connections.push(itemBlock.valueConnection_);
      itemBlock = itemBlock.nextConnection && itemBlock.nextConnection.targetBlock();
    } // Disconnect any children that don't belong.


    for (var i = 0; i < this.itemCount_; i++) {
      var connection = this.getInput('ADD' + i).connection.targetConnection;

      if (connection && connections.indexOf(connection) == -1) {
        connection.disconnect();
      }
    }

    this.itemCount_ = connections.length;
    this.updateShape_(); // Reconnect any child blocks.

    for (var i = 0; i < this.itemCount_; i++) {
      Blockly.Mutator.reconnect(connections[i], this, 'ADD' + i);
    }
  },
  saveConnections: function saveConnections(containerBlock) {
    var itemBlock = containerBlock.getInputTargetBlock('STACK');
    var i = 0;

    while (itemBlock) {
      var input = this.getInput('ADD' + i);
      itemBlock.valueConnection_ = input && input.connection.targetConnection;
      i++;
      itemBlock = itemBlock.nextConnection && itemBlock.nextConnection.targetBlock();
    }
  },
  updateShape_: function updateShape_() {
    for (var i = 0; i < this.itemCount_; i++) {
      if (!this.getInput('ADD' + i)) {
        var input = this.appendValueInput('ADD' + i);
        input.appendField(Blockly.Msg.nbiot_onenet_send_property).appendField(new Blockly.FieldTextInput("Property" + i), "field" + i); //input.appendField("資料 " + (i + 1) + ":");
        //input.appendField(new Blockly.FieldLabelSerializable("field" + (i + 1)), 'FIELD' + i);
        // input.appendField(new Blockly.FieldTextInput("資料" + (i + 1)), 'FIELD' + i)
      }
    }

    while (this.getInput('ADD' + i)) {
      this.removeInput('ADD' + i);
      i++;
    }
  }
};
Blockly.Blocks['iot_service_nbiot_onenet_create_with_container'] = {
  init: function init() {
    this.setColour(ONENET_BLOCK_COLOR);
    this.appendDummyInput().appendField("Items");
    this.appendStatementInput('STACK');
    this.setTooltip('');
    this.contextMenu = false;
  }
};
Blockly.Blocks['iot_service_nbiot_onenet_create_with_item'] = {
  init: function init() {
    this.setColour(ONENET_BLOCK_COLOR);
    this.appendDummyInput().appendField("Field");
    this.setPreviousStatement(true);
    this.setNextStatement(true);
    this.setTooltip('');
    this.contextMenu = false;
  }
};

Blockly.Python['iot_service_nbiot_onenet'] = function (block) {
  // var key = Blockly.Arduino.valueToCode(block, 'KEY', Blockly.Arduino.ORDER_ATOMIC).replace(/\"/g, '') || "";
  var item_field = '',
    item_value = '';
  var nbiot_onenet_data = "'{";

  for (var n = 0; n < this.itemCount_; n++) {
    item_field = block.getFieldValue("field" + n);
    item_value = Blockly.Python.valueToCode(this, 'ADD' + n, Blockly.Python.ORDER_NONE) || '';
    nbiot_onenet_data += '"' + item_field + '":"\' + str(' + item_value + ') + \'",';
  }

  var nbiot_onenet_data_final = nbiot_onenet_data + "}'";
  var code = '' + '_data_to_be_send = ' + nbiot_onenet_data_final.slice(0, -3) + '}\\r\\n\'' + '\n' + '_data_add_rn = _nbiot_send_onenet_data(_data_to_be_send) + "\\r\\n"\n' + '_data_for_at = _data_add_rn.encode()\n' + '_nbiot_serial.write(_data_for_at)\n' + // '_nbiot_serial.write(_nbiot_send_onenet_data(_data_to_be_send).encode())\n' +
    '\n' + '';
  return code;
};

Blockly.Blocks['iot_service_nbiot_onenet_read'] = {
  init: function init() {
    this.appendDummyInput().appendField(Blockly.Msg.nbiot_onenet_when_incoming_msg);
    this.appendValueInput("message").setCheck(null);
    this.appendDummyInput().appendField(Blockly.Msg.nbiot_onenet_when_incoming_msg_when);
    this.appendStatementInput("exec").setCheck(null).appendField(Blockly.Msg.nbiot_onenet_when_incoming_msg_exec);
    this.setPreviousStatement(true, null);
    this.setNextStatement(true, null);
    this.setColour(ONENET_BLOCK_COLOR);
    this.setTooltip("");
    this.setHelpUrl("");
  }
};

Blockly.Python['iot_service_nbiot_onenet_read'] = function (block) {
  var value_message = Blockly.Python.valueToCode(block, 'message', Blockly.Python.ORDER_ATOMIC);
  var statements_exec = Blockly.Python.statementToCode(block, 'exec'); // TODO: Assemble Python into code variable.

  var code = 'if (_nbiot_read_onenet_data(_nbiot_readings) == ' + value_message + '):\n' + statements_exec + '\n';
  return code;
};

Blockly.Blocks['esp32_nbiot_onenet_read_value'] = {
  init: function init() {
    this.appendDummyInput().appendField(Blockly.Msg.nbiot_onenet_receive_command);
    this.setOutput(true, null);
    this.setColour(ONENET_BLOCK_COLOR);
    this.setTooltip("");
    this.setHelpUrl("");
  }
};

Blockly.Python['esp32_nbiot_onenet_read_value'] = function (block) {
  // TODO: Assemble Python into code variable.
  var code = '_nbiot_read_onenet_data(_nbiot_readings)'; // TODO: Change ORDER_NONE to the correct strength.

  return [code, Blockly.Python.ORDER_NONE];
};

Blockly.Blocks['iot_service_nbiot_cococloud_read'] = {
  init: function init() {
    this.appendDummyInput().appendField(new Blockly.FieldImage("blockly/media/nbiot_cococloud_get.png", 260, 60, {
      alt: "*",
      flipRtl: "FALSE"
    }));
    this.appendDummyInput().appendField(Blockly.Msg.nbiot_cococloud_get_event_title);
    this.appendDummyInput().appendField(Blockly.Msg.nbiot_cococloud_get_event_api).appendField(new Blockly.FieldTextInput("ENTER_YOUR_EVENT_API_KEY"), "t_api");
    this.setPreviousStatement(true, null);
    this.setNextStatement(true, null);
    this.setColour(COCOCLOUD_BLOCK_COLOR);
    this.setTooltip("");
    this.setHelpUrl("");
  }
};

Blockly.Python['iot_service_nbiot_cococloud_read'] = function (block) {
  var api = block.getFieldValue('t_api'); // TODO: Assemble Python into code variable.

  var code = '\n';
  return code;
};

Blockly.Blocks['iot_service_nbiot_cococloud_read_data'] = {
  init: function init() {
    this.appendDummyInput().appendField(Blockly.Msg.nbiot_cococloud_get_property);
    this.appendValueInput("property").setCheck(null);
    this.appendDummyInput().appendField(Blockly.Msg.nbiot_cococloud_get_data);
    this.setInputsInline(true);
    this.setOutput(true, null);
    this.setColour(COCOCLOUD_BLOCK_COLOR);
    this.setTooltip("");
    this.setHelpUrl("");
  }
};

Blockly.Python['iot_service_nbiot_cococloud_read_data'] = function (block) {
  var property = Blockly.Python.valueToCode(block, 'property', Blockly.Python.ORDER_ATOMIC); // TODO: Assemble Python into code variable.

  var code = '\n'; // TODO: Change ORDER_NONE to the correct strength.

  return [code, Blockly.Python.ORDER_NONE];
};

Blockly.Blocks['iot_service_nbiot_cococloud'] = {
  init: function init() {
    this.appendDummyInput().appendField(new Blockly.FieldImage("blockly/media/nbiot_cococloud_send.png", 260, 60, {
      alt: "*",
      flipRtl: "FALSE"
    }));
    this.appendDummyInput().appendField(Blockly.Msg.nbiot_cococloud_send_title);
    this.appendDummyInput().appendField(Blockly.Msg.nbiot_cococloud_send_api).appendField(new Blockly.FieldTextInput("ENTET_YOUT_EVENT_API_KEY"), "t_api");
    /*this.appendValueInput("first_input")
        .setCheck(null)
        .appendField("Field 0");*/

    this.itemCount_ = 1;
    this.updateShape_();
    this.setMutator(new Blockly.Mutator(['iot_service_nbiot_cococloud_create_with_item']));
    this.setColour(COCOCLOUD_BLOCK_COLOR);
    this.setPreviousStatement(true, null);
    this.setNextStatement(true, null);
    this.setTooltip(Blockly.Msg.iot_service_nbiot_cococloud_TOOLTIP);
    this.setHelpUrl("");
  },
  mutationToDom: function mutationToDom() {
    var container = document.createElement('mutation');
    container.setAttribute('items', this.itemCount_);
    return container;
  },
  domToMutation: function domToMutation(xmlElement) {
    this.itemCount_ = parseInt(xmlElement.getAttribute('items'), 10);
    this.updateShape_();
  },
  decompose: function decompose(workspace) {
    var containerBlock = workspace.newBlock('iot_service_nbiot_cococloud_create_with_container');
    containerBlock.initSvg();
    var connection = containerBlock.getInput('STACK').connection;

    for (var i = 0; i < this.itemCount_; i++) {
      var itemBlock = workspace.newBlock('iot_service_nbiot_cococloud_create_with_item');
      itemBlock.initSvg();
      connection.connect(itemBlock.previousConnection);
      connection = itemBlock.nextConnection;
    }

    return containerBlock;
  },
  compose: function compose(containerBlock) {
    var itemBlock = containerBlock.getInputTargetBlock('STACK'); // Count number of inputs.

    var connections = [];

    while (itemBlock) {
      connections.push(itemBlock.valueConnection_);
      itemBlock = itemBlock.nextConnection && itemBlock.nextConnection.targetBlock();
    } // Disconnect any children that don't belong.


    for (var i = 0; i < this.itemCount_; i++) {
      var connection = this.getInput('ADD' + i).connection.targetConnection;

      if (connection && connections.indexOf(connection) == -1) {
        connection.disconnect();
      }
    }

    this.itemCount_ = connections.length;
    this.updateShape_(); // Reconnect any child blocks.

    for (var i = 0; i < this.itemCount_; i++) {
      Blockly.Mutator.reconnect(connections[i], this, 'ADD' + i);
    }
  },
  saveConnections: function saveConnections(containerBlock) {
    var itemBlock = containerBlock.getInputTargetBlock('STACK');
    var i = 0;

    while (itemBlock) {
      var input = this.getInput('ADD' + i);
      itemBlock.valueConnection_ = input && input.connection.targetConnection;
      i++;
      itemBlock = itemBlock.nextConnection && itemBlock.nextConnection.targetBlock();
    }
  },
  updateShape_: function updateShape_() {
    for (var i = 0; i < this.itemCount_; i++) {
      if (!this.getInput('ADD' + i)) {
        var input = this.appendValueInput('ADD' + i);
        input.appendField(Blockly.Msg.nbiot_cococloud_send_property).appendField(new Blockly.FieldTextInput("Property" + i), "field" + i); //input.appendField("資料 " + (i + 1) + ":");
        //input.appendField(new Blockly.FieldLabelSerializable("field" + (i + 1)), 'FIELD' + i);
        // input.appendField(new Blockly.FieldTextInput("資料" + (i + 1)), 'FIELD' + i)
      }
    }

    while (this.getInput('ADD' + i)) {
      this.removeInput('ADD' + i);
      i++;
    }
  }
};
Blockly.Blocks['iot_service_nbiot_cococloud_create_with_container'] = {
  init: function init() {
    this.setColour(ESP32_NBIOT_COLOR);
    this.appendDummyInput().appendField("Items");
    this.appendStatementInput('STACK');
    this.setTooltip('');
    this.contextMenu = false;
  }
};
Blockly.Blocks['iot_service_nbiot_cococloud_create_with_item'] = {
  init: function init() {
    this.setColour(COCOCLOUD_BLOCK_COLOR);
    this.appendDummyInput().appendField("Field");
    this.setPreviousStatement(true);
    this.setNextStatement(true);
    this.setTooltip('');
    this.contextMenu = false;
  }
};

Blockly.Python['iot_service_nbiot_cococloud'] = function (block) {
  var api = block.getFieldValue('t_api');
  Blockly.Python.addVariable('_nbiot_cococloud_send_init_state', '', true);
  Blockly.Python.addVariable('_nbiot_cococloud_json_content', '', true);
  Blockly.Python.definitions_['import'] = '' + '_nbiot_cococloud_send_init_state = False\n' + '\n' + 'def _nbiot_cococloud_send(data):\n' + '    _nbiot_cococloud_send_data = \'AT+HTTPCONTENT=0,\"\'+ data + \'\"\\r\\n\'\n' + '    print(_nbiot_cococloud_send_data)\n' + '    _nbiot_serial.write(b\'AT+HTTPCLOSE=0\\r\\n\')\n' + '    time.sleep_ms(500)\n' + '    _nbiot_serial.write(b\'AT+HTTPCREATE=\"http://api.cocorobo.cn/\"\\r\\n\')\n' + '    time.sleep_ms(500)\n' + '    _nbiot_serial.write(b\'AT+HTTPHEADER=0,\"Content-Type: application/json\\\\r\\\\n\"\\r\\n\')\n' + '    time.sleep_ms(500)\n' + '    _nbiot_serial.write(_nbiot_cococloud_send_data.encode())\n' + '    time.sleep_ms(500)\n' + '    _nbiot_serial.write(b\'AT+HTTPSEND=0,1,\"/iot/data/eventAPIKey/' + api + '\"\\r\\n\')\n' + '    time.sleep_ms(500)\n' + '';
  var item_field = '',
    item_value = '';
  var nbiot_cococloud_data = "'{";

  for (var n = 0; n < this.itemCount_; n++) {
    item_field = block.getFieldValue("field" + n);
    item_value = Blockly.Python.valueToCode(this, 'ADD' + n, Blockly.Python.ORDER_NONE) || '';
    nbiot_cococloud_data += '"' + item_field + '":"\' + str(' + item_value + ') + \'",';
  }

  var nbiot_cococloud_data_final = nbiot_cococloud_data + "}'";
  var code = '' + '_nbiot_cococloud_json_content = ' + nbiot_cococloud_data_final.slice(0, -3) + '}\'' + '\n' + '_nbiot_cococloud_send(_nbiot_cococloud_json_content)\n' + '';
  return code;
};

Blockly.Blocks['esp32_network_nbiot_http_get'] = {
  init: function init() {
    this.appendDummyInput().appendField(new Blockly.FieldImage("blockly/media/nbiot_esp32_header.png", 150, 50, {
      alt: "*",
      flipRtl: "FALSE"
    }));
    this.appendDummyInput().appendField(Blockly.Msg.nbiot_http_get_title);
    this.appendValueInput("nbiot_http_get_url").setCheck(null).appendField(Blockly.Msg.nbiot_http_get_url);
    this.setInputsInline(false);
    this.setPreviousStatement(true, null);
    this.setNextStatement(true, null);
    this.setColour(COCOCLOUD_BLOCK_COLOR);
    this.setTooltip("");
    this.setHelpUrl("");
  }
};
/*

Blockly.Python['esp32_network_nbiot_http_get'] = function(block) {
    var url = Blockly.Python.valueToCode(block, 'nbiot_http_get_url', Blockly.Python.ORDER_ATOMIC);

    Blockly.Python.addVariable('_SEND_HTTP_GET_ENDPOINT', '', true);
    Blockly.Python.addVariable('_SEND_HTTP_REQUEST', '', true);

    Blockly.Python.definitions_['import_urequests'] = '' +
        'import urequests as requests\n' +
        'import ujson as json\n' +
        '\n' +
        '_SEND_HTTP_GET_ENDPOINT = ' + url + '\n' +
        '';
    // TODO: Assemble Python into code variable.

    var code = '_SEND_HTTP_REQUEST = requests.get(_SEND_HTTP_GET_ENDPOINT)\n';
    return code;
};

Blockly.Blocks['esp32_network_nbiot_http_post'] = {
    init: function() {
        this.appendDummyInput()
            .appendField(new Blockly.FieldImage("blockly/media/nbiot_http_post.png", 220, 45, { alt: "*", flipRtl: "FALSE" }));
        this.appendDummyInput()
            .appendField("發送 HTTP POST 請求");
        this.appendValueInput("nbiot_http_post_url")
            .setCheck(null)
            .appendField("設定目標網址:");
        this.appendValueInput("data")
            .setCheck(null)
            .appendField("提交資料 (JSON):");
        this.setInputsInline(false);
        this.setPreviousStatement(true, null);
        this.setNextStatement(true, null);
        this.setColour(ESP32_NBIOT_COLOR);
        this.setTooltip("");
        this.setHelpUrl("");
    }
};

Blockly.Python['esp32_network_nbiot_http_post'] = function(block) {
    var url = Blockly.Python.valueToCode(block, 'nbiot_http_post_url', Blockly.Python.ORDER_ATOMIC);
    var data = Blockly.Python.valueToCode(block, 'data', Blockly.Python.ORDER_ATOMIC);

    Blockly.Python.addVariable('_SEND_HTTP_POST_ENDPOINT', '', true);
    Blockly.Python.addVariable('_SEND_HTTP_REQUEST', '', true);

    Blockly.Python.definitions_['import_urequests'] = '' +
        'import urequests as requests\n' +
        'import ujson as json\n' +
        '\n' +
        '_SEND_HTTP_POST_ENDPOINT = ' + url + '\n' +
        '';
    // TODO: Assemble Python into code variable.

    var code = '' +
        '_SEND_HTTP_POST_DATA = \'' + data + '\'\n' +
        '_SEND_HTTP_REQUEST = requests.post(_SEND_HTTP_POST_ENDPOINT, data = _SEND_HTTP_POST_DATA , headers = { "Content-type": "application/json" })\n' +
        '';
    return code;
};
*/

/*
  ____
 / ___|  ___ _ ____   _____
 \___ \ / _ \ '__\ \ / / _ \
  ___) |  __/ |   \ V / (_) |
 |____/ \___|_|    \_/ \___/

Blockly.Python.addVariable('', '', true);
Blockly.Python.definitions_['definition'] = '';
Blockly.Python.addSetup("setup", '');

*/